typebulb 0.29.3 → 0.31.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 +13 -3
- package/dist/agents/claude/client.js +186 -105
- package/dist/agents/claude/styles.css +30 -7
- package/dist/agents/pi/client.js +122 -41
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/agents/pi/styles.css +30 -7
- package/dist/dts/tbTypings.d.ts +1 -1
- package/dist/dts/tbTypings.d.ts.map +1 -1
- package/dist/dts/tbTypings.js +5 -3
- package/dist/dts/tbTypings.js.map +1 -1
- package/dist/index.js +282 -213
- package/dist/render.js +100 -19
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,143 +1,143 @@
|
|
|
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=eb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
3
|
+
var Dy=Object.create;var Oo=Object.defineProperty;var By=Object.getOwnPropertyDescriptor;var jy=Object.getOwnPropertyNames;var Fy=Object.getPrototypeOf,qy=Object.prototype.hasOwnProperty;var Gn=(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),au=(r,e)=>{for(var t in e)Oo(r,t,{get:e[t],enumerable:!0})},Uy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jy(e))!qy.call(r,s)&&s!==t&&Oo(r,s,{get:()=>e[s],enumerable:!(n=By(e,s))||n.enumerable});return r};var Jy=(r,e,t)=>(t=r!=null?Dy(Fy(r)):{},Uy(e||!r||!r.__esModule?Oo(t,"default",{value:r,enumerable:!0}):t,r));function wu(r){return Xe.find(e=>Pe[e].path===r)}function Su(r){return!!r?.startsWith("typebulb")}var Pe,Xe,vu,zn=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"}},Xe=["code","css","html","data","infer","insight","config","notes"];vu="typebulb/v1"});function Io(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 Xn=A(()=>{});function fe(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=eb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(xu);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=Lo(d);for(;t<e.length&&!e[t]?.match(y);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Qy(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 Qy(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(xu);i&&Xy.has(i[1].trim())&&Zy(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 Zy(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Qn)}function eb(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!Su(e.format)||!e.name?null:e}function ku(r){return fe(r)?.warnings??[]}function Eu(r){let e=Object.fromEntries(Xe.map(t=>[t,r.files.get(Pe[t].path)||""]));return{name:r.frontmatter.name,...e}}var xu,Qn,Xy,Lo,Mo=A(()=>{zn();Xn();xu=/^\*\*(.+)\*\*$/,Qn=/^(`{3,})(\w*)\s*$/,Xy=new Set(Xe.map(r=>Pe[r].path)),Lo=r=>new RegExp(`^${r}\\s*$`)});function Au(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 Tu(r,e){let{path:t}=Pe[r],n=t.split(".").pop(),s=Au(e);return`**${t}**
|
|
6
6
|
|
|
7
7
|
${s}${n}
|
|
8
8
|
${e}
|
|
9
|
-
${s}`}function
|
|
10
|
-
`)}function
|
|
11
|
-
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(
|
|
9
|
+
${s}`}function Pu(r){let e=Xe.filter(t=>r[t]).map(t=>Tu(t,r[t]));return["---",`format: ${vu}`,`name: ${Io(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function Do(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=Lo(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=Au(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
|
+
${Tu(e,t)}
|
|
16
|
+
`}var Ou=A(()=>{zn();Mo();Xn()});function Lr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function rb(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function Bo(r){let e=Lr(r??"").description?.trim();if(!e)return tb;let t=rb(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var tb,_u=A(()=>{tb="A Typebulb bulb."});var Cu=A(()=>{});function jo(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Ru=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 Nu=A(()=>{});function Zn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var Iu=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=jo(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+=Zn(b,"<"+e+`[
|
|
18
|
-
>]`),m+=Zn(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
|
|
19
|
-
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
20
|
-
`)?
|
|
18
|
+
>]`),m+=Zn(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 Fo=A(()=>{Ru();Nu();Iu()});var qo=A(()=>{Fo()});var Uo=A(()=>{qo()});var $u=A(()=>{Uo()});var Lu=A(()=>{});var Mu=A(()=>{Cu();Fo();qo();$u();Uo();Lu()});var j=E(te=>{"use strict";var Jo=Symbol.for("yaml.alias"),Du=Symbol.for("yaml.document"),es=Symbol.for("yaml.map"),Bu=Symbol.for("yaml.pair"),Ko=Symbol.for("yaml.scalar"),ts=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),ib=r=>!!r&&typeof r=="object"&&r[je]===Jo,ob=r=>!!r&&typeof r=="object"&&r[je]===Du,ab=r=>!!r&&typeof r=="object"&&r[je]===es,cb=r=>!!r&&typeof r=="object"&&r[je]===Bu,ju=r=>!!r&&typeof r=="object"&&r[je]===Ko,lb=r=>!!r&&typeof r=="object"&&r[je]===ts;function Fu(r){if(r&&typeof r=="object")switch(r[je]){case es:case ts:return!0}return!1}function ub(r){if(r&&typeof r=="object")switch(r[je]){case Jo:case es:case Ko:case ts:return!0}return!1}var db=r=>(ju(r)||Fu(r))&&!!r.anchor;te.ALIAS=Jo;te.DOC=Du;te.MAP=es;te.NODE_TYPE=je;te.PAIR=Bu;te.SCALAR=Ko;te.SEQ=ts;te.hasAnchor=db;te.isAlias=ib;te.isCollection=Fu;te.isDocument=ob;te.isMap=ab;te.isNode=ub;te.isPair=cb;te.isScalar=ju;te.isSeq=lb});var Br=E(Ho=>{"use strict";var Q=j(),ae=Symbol("break visit"),qu=Symbol("skip children"),Oe=Symbol("remove node");function rs(r,e){let t=Uu(e);Q.isDocument(r)?zt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):zt(null,r,t,Object.freeze([]))}rs.BREAK=ae;rs.SKIP=qu;rs.REMOVE=Oe;function zt(r,e,t,n){let s=Ju(r,e,t,n);if(Q.isNode(s)||Q.isPair(s))return Ku(r,n,s),zt(r,s,t,n);if(typeof s!="symbol"){if(Q.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=zt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ae)return ae;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(Q.isPair(e)){n=Object.freeze(n.concat(e));let i=zt("key",e.key,t,n);if(i===ae)return ae;i===Oe&&(e.key=null);let o=zt("value",e.value,t,n);if(o===ae)return ae;o===Oe&&(e.value=null)}}return s}async function ns(r,e){let t=Uu(e);Q.isDocument(r)?await Xt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):await Xt(null,r,t,Object.freeze([]))}ns.BREAK=ae;ns.SKIP=qu;ns.REMOVE=Oe;async function Xt(r,e,t,n){let s=await Ju(r,e,t,n);if(Q.isNode(s)||Q.isPair(s))return Ku(r,n,s),Xt(r,s,t,n);if(typeof s!="symbol"){if(Q.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===ae)return ae;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(Q.isPair(e)){n=Object.freeze(n.concat(e));let i=await Xt("key",e.key,t,n);if(i===ae)return ae;i===Oe&&(e.key=null);let o=await Xt("value",e.value,t,n);if(o===ae)return ae;o===Oe&&(e.value=null)}}return s}function Uu(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 Ju(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(Q.isMap(e))return t.Map?.(r,e,n);if(Q.isSeq(e))return t.Seq?.(r,e,n);if(Q.isPair(e))return t.Pair?.(r,e,n);if(Q.isScalar(e))return t.Scalar?.(r,e,n);if(Q.isAlias(e))return t.Alias?.(r,e,n)}function Ku(r,e,t){let n=e[e.length-1];if(Q.isCollection(n))n.items[r]=t;else if(Q.isPair(n))r==="key"?n.key=t:n.value=t;else if(Q.isDocument(n))n.contents=t;else{let s=Q.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ho.visit=rs;Ho.visitAsync=ns});var Wo=E(Wu=>{"use strict";var Hu=j(),fb=Br(),pb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mb=r=>r.replace(/[!,[\]{}]/g,e=>pb[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+mb(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&&Hu.isNode(e.contents)){let i={};fb.visit(e.contents,(o,a)=>{Hu.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:"};Wu.Directives=jr});var ss=E(Fr=>{"use strict";var Yu=j(),hb=Br();function gb(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 Vu(r){let e=new Set;return hb.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Gu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function yb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Vu(r));let o=Gu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Yu.isScalar(o.node)||Yu.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=gb;Fr.anchorNames=Vu;Fr.createNodeAnchors=yb;Fr.findNewAnchor=Gu});var Yo=E(zu=>{"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)}zu.applyReviver=qr});var Qe=E(Qu=>{"use strict";var bb=j();function Xu(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Xu(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!bb.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}Qu.toJS=Xu});var is=E(ed=>{"use strict";var wb=Yo(),Zu=j(),vb=Qe(),Vo=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=vb.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?wb.applyReviver(i,{"":a},"",a):a}};ed.NodeBase=Vo});var Ur=E(td=>{"use strict";var Sb=ss(),xb=Br(),Qt=j(),kb=is(),Eb=Qe(),Go=class extends kb.NodeBase{constructor(e){super(Qt.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=[],xb.visit(e,{Node:(i,o)=>{(Qt.isAlias(o)||Qt.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||(Eb.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=os(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(Sb.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 os(r,e,t){if(Qt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Qt.isCollection(e)){let n=0;for(let s of e.items){let i=os(r,s,t);i>n&&(n=i)}return n}else if(Qt.isPair(e)){let n=os(r,e.key,t),s=os(r,e.value,t);return Math.max(n,s)}return 1}td.Alias=Go});var G=E(zo=>{"use strict";var Ab=j(),Tb=is(),Pb=Qe(),Ob=r=>!r||typeof r!="function"&&typeof r!="object",Ze=class extends Tb.NodeBase{constructor(e){super(Ab.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Pb.toJS(this.value,e,t)}toString(){return String(this.value)}};Ze.BLOCK_FOLDED="BLOCK_FOLDED";Ze.BLOCK_LITERAL="BLOCK_LITERAL";Ze.PLAIN="PLAIN";Ze.QUOTE_DOUBLE="QUOTE_DOUBLE";Ze.QUOTE_SINGLE="QUOTE_SINGLE";zo.Scalar=Ze;zo.isScalarValue=Ob});var Jr=E(nd=>{"use strict";var _b=Ur(),xt=j(),rd=G(),Cb="tag:yaml.org,2002:";function Rb(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 Nb(r,e,t){if(xt.isDocument(r)&&(r=r.contents),xt.isNode(r))return r;if(xt.isPair(r)){let u=t.schema[xt.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 _b.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Cb+e.slice(2));let l=Rb(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new rd.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[xt.MAP]:Symbol.iterator in Object(r)?o[xt.SEQ]:o[xt.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 rd.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}nd.createNode=Nb});var cs=E(as=>{"use strict";var Ib=Jr(),_e=j(),$b=is();function Xo(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 Ib.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 sd=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Qo=class extends $b.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>_e.isNode(n)||_e.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(sd(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(_e.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,Xo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(_e.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&_e.isScalar(i)?i.value:i:_e.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_e.isPair(t))return!1;let n=t.value;return n==null||e&&_e.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return _e.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(_e.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,Xo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};as.Collection=Qo;as.collectionFromPath=Xo;as.isEmptyPath=sd});var Kr=E(ls=>{"use strict";var Lb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Zo(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mb=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?Zo(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+
|
|
23
|
-
`)t===
|
|
22
|
+
`+Zo(t,e):(r.endsWith(" ")?"":" ")+t;ls.indentComment=Zo;ls.lineComment=Mb;ls.stringifyComment=Lb});var od=E(Hr=>{"use strict";var Db="flow",ea="block",us="quoted";function Bb(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,x=-1;t===ea&&(m=id(r,m,e.length),m!==-1&&(u=m+c));for(let T;T=r[m+=1];){if(t===us&&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}x=m}if(T===`
|
|
23
|
+
`)t===ea&&(m=id(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!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===us){for(;p===" "||p===" ";)p=T,T=r[m+=1],y=!0;let P=m>
|
|
26
|
-
${e}${r.slice(0,_)}`:(t===us&&f[P]&&(
|
|
27
|
-
${e}${r.slice(P+1,_)}`)}return
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=
|
|
25
|
+
`&&P!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===us){for(;p===" "||p===" ";)p=T,T=r[m+=1],y=!0;let P=m>x+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 k=r.slice(0,l[0]);for(let T=0;T<l.length;++T){let P=l[T],_=l[T+1]||r.length;P===0?k=`
|
|
26
|
+
${e}${r.slice(0,_)}`:(t===us&&f[P]&&(k+=`${r[P]}\\`),k+=`
|
|
27
|
+
${e}${r.slice(P+1,_)}`)}return k}function id(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=ea;Hr.FOLD_FLOW=Db;Hr.FOLD_QUOTED=us;Hr.foldFlowLines=Bb});var Yr=E(ad=>{"use strict";var be=G(),et=od(),fs=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ps=r=>/^(%|---|\.\.\.)/m.test(r);function jb(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
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||(ps(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:
|
|
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:et.foldFlowLines(o,i,et.FOLD_QUOTED,fs(e,!1))}function ta(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
33
|
`)||/[ \t]\n|\n[ \t]/.test(r))return Wr(r,e);let t=e.indent||(ps(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
|
-
${t}`)+"'";return e.implicitKey?n:
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:et.foldFlowLines(n,t,et.FOLD_FLOW,fs(e,!1))}function Zt(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Wr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=ta:i&&!s?n=Wr:n=t?ta:Wr}return n(r,e)}var ra;try{ra=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{ra=/\n+(?!\n|$)/g}function ds({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 Zt(t,n);let l=n.indent||(n.forceBlockIndent||ps(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===be.Scalar.BLOCK_FOLDED?!1:e===be.Scalar.BLOCK_LITERAL?!0:!jb(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
39
|
`;let u,d;for(d=t.length;d>0;--d){let _=t[d-1];if(_!==`
|
|
40
40
|
`&&_!==" "&&_!==" ")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
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
43
|
-
`)
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,
|
|
42
|
+
`&&(p=p.slice(0,-1)),p=p.replace(ra,`$&${l}`));let m=!1,b,x=-1;for(b=0;b<t.length;++b){let _=t[b];if(_===" ")m=!0;else if(_===`
|
|
43
|
+
`)x=b;else break}let k=t.substring(0,x<b?x+1:b);k&&(t=t.substring(k.length),k=k.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let _=t.replace(/\n+/g,`
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,N=fs(n,!0);o!=="folded"&&e!==be.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{O=!0});let h=et.foldFlowLines(`${k}${_}${p}`,l,et.FOLD_BLOCK,N);if(!O)return`>${P}
|
|
45
45
|
${l}${h}`}return t=t.replace(/\n+/g,`$&${l}`),`|${P}
|
|
46
|
-
${l}${
|
|
46
|
+
${l}${k}${t}${p}`}function Fb(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
47
|
`)||f&&/[[\]{},]/.test(i))return Zt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
-
`)?Zt(i,e):
|
|
49
|
-
`))return
|
|
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 Zt(i,e)}return a?u:
|
|
51
|
-
${e.indent}${a}`:a}
|
|
52
|
-
${a}:`):(b=`${b}:`,d&&(b+=Gr.lineComment(b,t.indent,l(d))));let k,
|
|
53
|
-
`:"",
|
|
54
|
-
${Gr.indentComment(
|
|
48
|
+
`)?Zt(i,e):ds(r,e,t,n);if(!a&&!f&&s!==be.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return ds(r,e,t,n);if(ps(i)){if(c==="")return e.forceBlockIndent=!0,ds(r,e,t,n);if(a&&c===l)return Zt(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:y}=e.doc.schema;if(y.some(d)||p?.some(d))return Zt(i,e)}return a?u:et.foldFlowLines(u,c,et.FOLD_FLOW,fs(e,!1))}function qb(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?Zt(o.value,e):ds(o,e,t,n);case be.Scalar.QUOTE_DOUBLE:return Wr(o.value,e);case be.Scalar.QUOTE_SINGLE:return ta(o.value,e);case be.Scalar.PLAIN:return Fb(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}ad.stringifyString=qb});var Vr=E(na=>{"use strict";var Ub=ss(),tt=j(),Jb=Kr(),Kb=Yr();function Hb(r,e){let t=Object.assign({blockQuote:!0,commentString:Jb.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 Wb(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(tt.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 Yb(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(tt.isScalar(r)||tt.isCollection(r))&&r.anchor;i&&Ub.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 Vb(r,e,t,n){if(tt.isPair(r))return r.toString(e,t,n);if(tt.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=tt.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Wb(e.doc.schema.tags,i));let o=Yb(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):tt.isScalar(i)?Kb.stringifyString(i,e,t,n):i.toString(e,t,n);return o?tt.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}na.createStringifyContext=Hb;na.stringify=Vb});var dd=E(ud=>{"use strict";var Fe=j(),cd=G(),ld=Vr(),Gr=Kr();function Gb({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=Fe.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Fe.isCollection(r)||!Fe.isNode(r)&&typeof r=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||Fe.isCollection(r)||(Fe.isScalar(r)?r.type===cd.Scalar.BLOCK_FOLDED||r.type===cd.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=ld.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 x,k,T;Fe.isNode(e)?(x=!!e.spaceBefore,k=e.commentBefore,T=e.comment):(x=!1,k=null,T=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&Fe.isScalar(e)&&(t.indentAtStart=b.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&Fe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let P=!1,_=ld.stringify(e,t,()=>P=!0,()=>m=!0),O=" ";if(d||x||k){if(O=x?`
|
|
53
|
+
`:"",k){let N=l(k);O+=`
|
|
54
|
+
${Gr.indentComment(N,t.indent)}`}_===""&&!t.inFlow?O===`
|
|
55
55
|
`&&T&&(O=`
|
|
56
56
|
|
|
57
57
|
`):O+=`
|
|
58
|
-
${t.indent}`}else if(!p&&
|
|
59
|
-
`),S=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(S||!I){let
|
|
58
|
+
${t.indent}`}else if(!p&&Fe.isCollection(e)){let N=_[0],h=_.indexOf(`
|
|
59
|
+
`),S=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(S||!I){let L=!1;if(S&&(N==="&"||N==="!")){let R=_.indexOf(" ");N==="&"&&R!==-1&&R<h&&_[R+1]==="!"&&(R=_.indexOf(" ",R+1)),(R===-1||h<R)&&(L=!0)}L||(O=`
|
|
60
60
|
${t.indent}`)}}else(_===""||_[0]===`
|
|
61
|
-
`)&&(O="");return b+=O+_,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}
|
|
61
|
+
`)&&(O="");return b+=O+_,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}ud.stringifyPair=Gb});var ia=E(sa=>{"use strict";var fd=Gn("process");function zb(r,...e){r==="debug"&&console.log(...e)}function Xb(r,e){(r==="debug"||r==="warn")&&(typeof fd.emitWarning=="function"?fd.emitWarning(e):console.warn(e))}sa.debug=zb;sa.warn=Xb});var ys=E(gs=>{"use strict";var zr=j(),pd=G(),ms="<<",hs={identify:r=>r===ms||typeof r=="symbol"&&r.description===ms,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new pd.Scalar(Symbol(ms)),{addToJSMap:md}),stringify:()=>ms},Qb=(r,e)=>(hs.identify(e)||zr.isScalar(e)&&(!e.type||e.type===pd.Scalar.PLAIN)&&hs.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===hs.tag&&t.default);function md(r,e,t){if(t=r&&zr.isAlias(t)?t.resolve(r.doc):t,zr.isSeq(t))for(let n of t.items)oa(r,e,n);else if(Array.isArray(t))for(let n of t)oa(r,e,n);else oa(r,e,t)}function oa(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}gs.addMergeToJSMap=md;gs.isMergeKey=Qb;gs.merge=hs});var ca=E(yd=>{"use strict";var Zb=ia(),hd=ys(),ew=Vr(),gd=j(),aa=Qe();function tw(r,e,{key:t,value:n}){if(gd.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(hd.isMergeKey(r,t))hd.addMergeToJSMap(r,e,n);else{let s=aa.toJS(t,"",r);if(e instanceof Map)e.set(s,aa.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=rw(t,s,r),o=aa.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 rw(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(gd.isNode(r)&&t?.doc){let n=ew.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)+'..."'),Zb.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)}yd.addPairToJSMap=tw});var rt=E(la=>{"use strict";var bd=Jr(),nw=dd(),sw=ca(),bs=j();function iw(r,e,t){let n=bd.createNode(r,void 0,t),s=bd.createNode(e,void 0,t);return new ws(n,s)}var ws=class r{constructor(e,t=null){Object.defineProperty(this,bs.NODE_TYPE,{value:bs.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return bs.isNode(t)&&(t=t.clone(e)),bs.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return sw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?nw.stringifyPair(this,e,t,n):JSON.stringify(this)}};la.Pair=ws;la.createPair=iw});var ua=E(vd=>{"use strict";var kt=j(),wd=Vr(),vs=Kr();function ow(r,e,t){return(e.inFlow??r.flow?cw:aw)(r,e,t)}function aw({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(kt.isNode(m))!u&&m.spaceBefore&&d.push(""),Ss(t,d,m.commentBefore,u),m.comment&&(b=m.comment);else if(kt.isPair(m)){let k=kt.isNode(m.key)?m.key:null;k&&(!u&&k.spaceBefore&&d.push(""),Ss(t,d,k.commentBefore,u))}u=!1;let x=wd.stringify(m,f,()=>b=null,()=>u=!0);b&&(x+=vs.lineComment(x,i,l(b))),u&&b&&(u=!1),d.push(n+x)}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
|
-
`+vs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function cw({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(
|
|
65
|
-
`))&&(l=!0),u.push(
|
|
64
|
+
`+vs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function cw({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(kt.isNode(m))m.spaceBefore&&u.push(""),Ss(e,u,m.commentBefore,!1),m.comment&&(b=m.comment);else if(kt.isPair(m)){let k=kt.isNode(m.key)?m.key:null;k&&(k.spaceBefore&&u.push(""),Ss(e,u,k.commentBefore,!1),k.comment&&(l=!0));let T=kt.isNode(m.value)?m.value:null;T?(T.comment&&(b=T.comment),T.commentBefore&&(l=!0)):m.value==null&&k?.comment&&(b=k.comment)}b&&(l=!0);let x=wd.stringify(m,c,()=>b=null);y<r.length-1&&(x+=","),b&&(x+=vs.lineComment(x,n,a(b))),!l&&(u.length>f||x.includes(`
|
|
65
|
+
`))&&(l=!0),u.push(x),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let 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`${d}${o}${u.join(" ")}${o}${p}`}function Ss({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=vs.indentComment(e(n),r);t.push(i.trimStart())}}
|
|
69
|
-
`:" ")}return Hw.stringifyString({comment:r,type:e,value:a},n,s,i)}};
|
|
68
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Ss({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=vs.indentComment(e(n),r);t.push(i.trimStart())}}vd.stringifyCollection=ow});var st=E(fa=>{"use strict";var lw=ua(),uw=ca(),dw=cs(),nt=j(),xs=rt(),fw=G();function Xr(r,e){let t=nt.isScalar(e)?e.value:e;for(let n of r)if(nt.isPair(n)&&(n.key===e||n.key===t||nt.isScalar(n.key)&&n.key.value===t))return n}var da=class extends dw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(nt.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(xs.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;nt.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new xs.Pair(e,e?.value):n=new xs.Pair(e.key,e.value);let s=Xr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);nt.isScalar(s.value)&&fw.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=Xr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Xr(this.items,e)?.value;return(!t&&nt.isScalar(s)?s.value:s)??void 0}has(e){return!!Xr(this.items,e)}set(e,t){this.add(new xs.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)uw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!nt.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})),lw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};fa.YAMLMap=da;fa.findPair=Xr});var er=E(xd=>{"use strict";var pw=j(),Sd=st(),mw={collection:"map",default:!0,nodeClass:Sd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return pw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Sd.YAMLMap.from(r,e,t)};xd.map=mw});var it=E(kd=>{"use strict";var hw=Jr(),gw=ua(),yw=cs(),Es=j(),bw=G(),ww=Qe(),pa=class extends yw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Es.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&&Es.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];Es.isScalar(s)&&bw.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(ww.toJS(i,String(s++),t));return n}toString(e,t,n){return e?gw.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(hw.createNode(a,void 0,n))}}return i}};function ks(r){let e=Es.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}kd.YAMLSeq=pa});var tr=E(Ad=>{"use strict";var vw=j(),Ed=it(),Sw={collection:"seq",default:!0,nodeClass:Ed.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return vw.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ed.YAMLSeq.from(r,e,t)};Ad.seq=Sw});var Qr=E(Td=>{"use strict";var xw=Yr(),kw={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),xw.stringifyString(r,e,t,n)}};Td.string=kw});var As=E(_d=>{"use strict";var Pd=G(),Od={identify:r=>r==null,createNode:()=>new Pd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Pd.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Od.test.test(r)?r:e.options.nullStr};_d.nullTag=Od});var ma=E(Rd=>{"use strict";var Ew=G(),Cd={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Ew.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Cd.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Rd.boolTag=Cd});var rr=E(Nd=>{"use strict";function Aw({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}Nd.stringifyNumber=Aw});var ga=E(Ts=>{"use strict";var Tw=G(),ha=rr(),Pw={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:ha.stringifyNumber},Ow={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():ha.stringifyNumber(r)}},_w={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 Tw.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:ha.stringifyNumber};Ts.float=_w;Ts.floatExp=Ow;Ts.floatNaN=Pw});var ba=E(Os=>{"use strict";var Id=rr(),Ps=r=>typeof r=="bigint"||Number.isInteger(r),ya=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function $d(r,e,t){let{value:n}=r;return Ps(n)&&n>=0?t+n.toString(e):Id.stringifyNumber(r)}var Cw={identify:r=>Ps(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>ya(r,2,8,t),stringify:r=>$d(r,8,"0o")},Rw={identify:Ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>ya(r,0,10,t),stringify:Id.stringifyNumber},Nw={identify:r=>Ps(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>ya(r,2,16,t),stringify:r=>$d(r,16,"0x")};Os.int=Rw;Os.intHex=Nw;Os.intOct=Cw});var Md=E(Ld=>{"use strict";var Iw=er(),$w=As(),Lw=tr(),Mw=Qr(),Dw=ma(),wa=ga(),va=ba(),Bw=[Iw.map,Lw.seq,Mw.string,$w.nullTag,Dw.boolTag,va.intOct,va.int,va.intHex,wa.floatNaN,wa.floatExp,wa.float];Ld.schema=Bw});var jd=E(Bd=>{"use strict";var jw=G(),Fw=er(),qw=tr();function Dd(r){return typeof r=="bigint"||Number.isInteger(r)}var _s=({value:r})=>JSON.stringify(r),Uw=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:_s},{identify:r=>r==null,createNode:()=>new jw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_s},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:_s},{identify:Dd,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})=>Dd(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:_s}],Jw={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Kw=[Fw.map,qw.seq].concat(Uw,Jw);Bd.schema=Kw});var xa=E(Fd=>{"use strict";var Zr=Gn("buffer"),Sa=G(),Hw=Yr(),Ww={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=Sa.Scalar.BLOCK_LITERAL),e!==Sa.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===Sa.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Hw.stringifyString({comment:r,type:e,value:a},n,s,i)}};Fd.binary=Ww});var Ns=E(Rs=>{"use strict";var Cs=j(),ka=rt(),Yw=G(),Vw=it();function qd(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 ka.Pair(new Yw.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 ka.Pair(n)}}else e("Expected a sequence for this tag");return r}function Uf(r,e,t){let{replacer:n}=t,s=new Vw.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(ka.createPair(a,c,t))}return s}var Gw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qf,createNode:Uf};Rs.createPairs=Uf;Rs.pairs=Gw;Rs.resolvePairs=qf});var Aa=E(Ea=>{"use strict";var Jf=j(),xa=ze(),en=rt(),zw=nt(),Kf=Ns(),Et=class r extends zw.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(Jf.isPair(s)?(i=xa.toJS(s.key,"",t),o=xa.toJS(s.value,i,t)):i=xa.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=Kf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Qw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Kf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Jf.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)};Ea.YAMLOMap=Et;Ea.omap=Qw});var Gf=E(Ta=>{"use strict";var Hf=W();function Wf({value:r,source:e},t){return e&&(r?Yf:Vf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yf={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 Hf.Scalar(!0),stringify:Wf},Vf={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 Hf.Scalar(!1),stringify:Wf};Ta.falseTag=Vf;Ta.trueTag=Yf});var zf=E(Is=>{"use strict";var Xw=W(),Pa=rr(),Zw={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:Pa.stringifyNumber},ev={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():Pa.stringifyNumber(r)}},tv={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 Xw.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:Pa.stringifyNumber};Is.float=tv;Is.floatExp=ev;Is.floatNaN=Zw});var Xf=E(rn=>{"use strict";var Qf=rr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function $s(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 Oa(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 Qf.stringifyNumber(r)}var rv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>$s(r,2,2,t),stringify:r=>Oa(r,2,"0b")},nv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>$s(r,1,8,t),stringify:r=>Oa(r,8,"0")},sv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>$s(r,0,10,t),stringify:Qf.stringifyNumber},iv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>$s(r,2,16,t),stringify:r=>Oa(r,16,"0x")};rn.int=sv;rn.intBin=rv;rn.intHex=iv;rn.intOct=nv});var Ca=E(_a=>{"use strict";var Ds=j(),Ls=et(),Ms=rt(),At=class r extends Ms.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ds.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ls.Pair(e.key,null):t=new Ls.Pair(e,null),Ms.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ms.findPair(this.items,e);return!t&&Ds.isPair(n)?Ds.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=Ms.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ls.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(Ls.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var ov={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(Ds.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}};_a.YAMLSet=At;_a.set=ov});var Na=E(Bs=>{"use strict";var av=rr();function Ra(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 av.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 cv={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})=>Ra(r,t),stringify:Zf},lv={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=>Ra(r,!1),stringify:Zf},ed={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(ed.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=Ra(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$/,"")??""};Bs.floatTime=lv;Bs.intTime=cv;Bs.timestamp=ed});var nd=E(rd=>{"use strict";var uv=er(),fv=As(),dv=tr(),pv=Xr(),mv=Sa(),td=Gf(),Ia=zf(),js=Xf(),hv=ys(),gv=Aa(),yv=Ns(),bv=Ca(),$a=Na(),wv=[uv.map,dv.seq,pv.string,fv.nullTag,td.trueTag,td.falseTag,js.intBin,js.intOct,js.int,js.intHex,Ia.floatNaN,Ia.floatExp,Ia.float,mv.binary,hv.merge,gv.omap,yv.pairs,bv.set,$a.intTime,$a.floatTime,$a.timestamp];rd.schema=wv});var pd=E(Da=>{"use strict";var ad=er(),vv=As(),cd=tr(),Sv=Xr(),kv=pa(),La=ha(),Ma=ya(),xv=Mf(),Ev=jf(),ld=Sa(),nn=ys(),ud=Aa(),fd=Ns(),sd=nd(),dd=Ca(),Fs=Na(),id=new Map([["core",xv.schema],["failsafe",[ad.map,cd.seq,Sv.string]],["json",Ev.schema],["yaml11",sd.schema],["yaml-1.1",sd.schema]]),od={binary:ld.binary,bool:kv.boolTag,float:La.float,floatExp:La.floatExp,floatNaN:La.floatNaN,floatTime:Fs.floatTime,int:Ma.int,intHex:Ma.intHex,intOct:Ma.intOct,intTime:Fs.intTime,map:ad.map,merge:nn.merge,null:vv.nullTag,omap:ud.omap,pairs:fd.pairs,seq:cd.seq,set:dd.set,timestamp:Fs.timestamp},Av={"tag:yaml.org,2002:binary":ld.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ud.omap,"tag:yaml.org,2002:pairs":fd.pairs,"tag:yaml.org,2002:set":dd.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Tv(r,e,t){let n=id.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(id.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"?od[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(od).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},[])}Da.coreKnownTags=Av;Da.getTags=Tv});var Fa=E(md=>{"use strict";var Ba=j(),Pv=er(),Ov=tr(),_v=Xr(),qs=pd(),Cv=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ja=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?qs.getTags(e,"compat"):e?qs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?qs.coreKnownTags:{},this.tags=qs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ba.MAP,{value:Pv.map}),Object.defineProperty(this,Ba.SCALAR,{value:_v.string}),Object.defineProperty(this,Ba.SEQ,{value:Ov.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Cv:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};md.Schema=ja});var gd=E(hd=>{"use strict";var Rv=j(),qa=Vr(),sn=Kr();function Nv(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=qa.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(Rv.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=qa.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(qa.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 ka.Pair(n)}}else e("Expected a sequence for this tag");return r}function Ud(r,e,t){let{replacer:n}=t,s=new Vw.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(ka.createPair(a,c,t))}return s}var Gw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qd,createNode:Ud};Rs.createPairs=Ud;Rs.pairs=Gw;Rs.resolvePairs=qd});var Ta=E(Aa=>{"use strict";var Jd=j(),Ea=Qe(),en=st(),zw=it(),Kd=Ns(),Et=class r extends zw.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(Jd.isPair(s)?(i=Ea.toJS(s.key,"",t),o=Ea.toJS(s.value,i,t)):i=Ea.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=Kd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Xw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Kd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Jd.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)};Aa.YAMLOMap=Et;Aa.omap=Xw});var Gd=E(Pa=>{"use strict";var Hd=G();function Wd({value:r,source:e},t){return e&&(r?Yd:Vd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yd={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 Hd.Scalar(!0),stringify:Wd},Vd={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 Hd.Scalar(!1),stringify:Wd};Pa.falseTag=Vd;Pa.trueTag=Yd});var zd=E(Is=>{"use strict";var Qw=G(),Oa=rr(),Zw={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:Oa.stringifyNumber},ev={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():Oa.stringifyNumber(r)}},tv={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 Qw.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:Oa.stringifyNumber};Is.float=tv;Is.floatExp=ev;Is.floatNaN=Zw});var Qd=E(rn=>{"use strict";var Xd=rr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function $s(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 _a(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 Xd.stringifyNumber(r)}var rv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>$s(r,2,2,t),stringify:r=>_a(r,2,"0b")},nv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>$s(r,1,8,t),stringify:r=>_a(r,8,"0")},sv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>$s(r,0,10,t),stringify:Xd.stringifyNumber},iv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>$s(r,2,16,t),stringify:r=>_a(r,16,"0x")};rn.int=sv;rn.intBin=rv;rn.intHex=iv;rn.intOct=nv});var Ra=E(Ca=>{"use strict";var Ds=j(),Ls=rt(),Ms=st(),At=class r extends Ms.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ds.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ls.Pair(e.key,null):t=new Ls.Pair(e,null),Ms.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ms.findPair(this.items,e);return!t&&Ds.isPair(n)?Ds.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=Ms.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ls.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(Ls.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var ov={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(Ds.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}};Ca.YAMLSet=At;Ca.set=ov});var Ia=E(Bs=>{"use strict";var av=rr();function Na(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 Zd(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return av.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 cv={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})=>Na(r,t),stringify:Zd},lv={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=>Na(r,!1),stringify:Zd},ef={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(ef.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=Na(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$/,"")??""};Bs.floatTime=lv;Bs.intTime=cv;Bs.timestamp=ef});var nf=E(rf=>{"use strict";var uv=er(),dv=As(),fv=tr(),pv=Qr(),mv=xa(),tf=Gd(),$a=zd(),js=Qd(),hv=ys(),gv=Ta(),yv=Ns(),bv=Ra(),La=Ia(),wv=[uv.map,fv.seq,pv.string,dv.nullTag,tf.trueTag,tf.falseTag,js.intBin,js.intOct,js.int,js.intHex,$a.floatNaN,$a.floatExp,$a.float,mv.binary,hv.merge,gv.omap,yv.pairs,bv.set,La.intTime,La.floatTime,La.timestamp];rf.schema=wv});var mf=E(Ba=>{"use strict";var cf=er(),vv=As(),lf=tr(),Sv=Qr(),xv=ma(),Ma=ga(),Da=ba(),kv=Md(),Ev=jd(),uf=xa(),nn=ys(),df=Ta(),ff=Ns(),sf=nf(),pf=Ra(),Fs=Ia(),of=new Map([["core",kv.schema],["failsafe",[cf.map,lf.seq,Sv.string]],["json",Ev.schema],["yaml11",sf.schema],["yaml-1.1",sf.schema]]),af={binary:uf.binary,bool:xv.boolTag,float:Ma.float,floatExp:Ma.floatExp,floatNaN:Ma.floatNaN,floatTime:Fs.floatTime,int:Da.int,intHex:Da.intHex,intOct:Da.intOct,intTime:Fs.intTime,map:cf.map,merge:nn.merge,null:vv.nullTag,omap:df.omap,pairs:ff.pairs,seq:lf.seq,set:pf.set,timestamp:Fs.timestamp},Av={"tag:yaml.org,2002:binary":uf.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":df.omap,"tag:yaml.org,2002:pairs":ff.pairs,"tag:yaml.org,2002:set":pf.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Tv(r,e,t){let n=of.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(of.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"?af[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(af).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},[])}Ba.coreKnownTags=Av;Ba.getTags=Tv});var qa=E(hf=>{"use strict";var ja=j(),Pv=er(),Ov=tr(),_v=Qr(),qs=mf(),Cv=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Fa=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?qs.getTags(e,"compat"):e?qs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?qs.coreKnownTags:{},this.tags=qs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ja.MAP,{value:Pv.map}),Object.defineProperty(this,ja.SCALAR,{value:_v.string}),Object.defineProperty(this,ja.SEQ,{value:Ov.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Cv:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};hf.Schema=Fa});var yf=E(gf=>{"use strict";var Rv=j(),Ua=Vr(),sn=Kr();function Nv(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=Ua.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(Rv.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=Ua.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(Ua.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
|
+
`}gf.stringifyDocument=Nv});var on=E(bf=>{"use strict";var Iv=Ur(),nr=cs(),pe=j(),$v=rt(),Lv=Qe(),Mv=qa(),Dv=yf(),Ja=ss(),Bv=Yo(),jv=Jr(),Ka=Wo(),Ha=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 Ka.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){sr(this.contents)&&this.contents.add(e)}addIn(e,t){sr(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 Iv.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=k=>typeof k=="number"||k instanceof String||k instanceof Number,x=t.filter(b).map(String);x.length>0&&(t=t.concat(x)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag: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=jv.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 $v.Pair(s,i)}delete(e){return sr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return nr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):sr(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 nr.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 nr.isEmptyPath(e)?this.contents!==void 0:pe.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=nr.collectionFromPath(this.schema,[e],t):sr(this.contents)&&this.contents.set(e,t)}setIn(e,t){nr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=nr.collectionFromPath(this.schema,Array.from(e),t):sr(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 Ka.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 Ka.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 Mv.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=Lv.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"?Bv.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 Dv.stringifyDocument(this,e)}};function sr(r){if(pe.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}bf.Document=Ha});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}},Wa=class extends an{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Ya=class extends an{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Fv=(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=
|
|
80
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Wv.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",
|
|
82
|
-
`+T.comment:
|
|
83
|
-
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&sS.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
|
|
84
|
-
`+
|
|
85
|
-
`+S.comment:h.comment=S.comment);let
|
|
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,f=0;for(let m=0;m<a;++m){let[b,
|
|
88
|
-
`;for(let m=f;m<a;++m){let[b,
|
|
89
|
-
`):b.length>c||
|
|
79
|
+
`}};cn.YAMLError=an;cn.YAMLParseError=Wa;cn.YAMLWarning=Ya;cn.prettifyError=Fv});var un=E(wf=>{"use strict";function qv(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,x=null,k=null,T=null,P=null,_=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||x)&&(k=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,_??(_=h.offset),l=!1,f=!1,y=!0;break;case"tag":{x&&i(h,"MULTIPLE_TAGS","A node can have at most one tag"),x=h,_??(_=h.offset),l=!1,f=!1,y=!0;break}case t:(b||x)&&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],N=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:x,newlineAfterProp:k,end:N,start:_??N}}wf.resolveProps=qv});var Us=E(vf=>{"use strict";function Va(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(Va(e.key)||Va(e.value))return!0}return!1;default:return!0}}vf.containsNewline=Va});var Ga=E(Sf=>{"use strict";var Uv=Us();function Jv(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Uv.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Sf.flowIndentCheck=Jv});var za=E(kf=>{"use strict";var xf=j();function Kv(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||xf.isScalar(i)&&xf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}kf.mapIncludes=Kv});var _f=E(Of=>{"use strict";var Ef=rt(),Hv=st(),Af=un(),Wv=Us(),Tf=Ga(),Yv=za(),Pf="All mapping items must start at the same column";function Vv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Hv.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=Af.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",Pf)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Wv.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",Pf);t.atKey=!0;let x=m.end,k=d?r(t,d,m,s):e(t,x,u,null,m,s);t.schema.compat&&Tf.flowIndentCheck(n.indent,d,s),t.atKey=!1,Yv.mapIncludes(t,a.items,k)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let T=Af.resolveProps(p??[],{indicator:"map-value-ind",next:y,offset:k.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(k.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&&Tf.flowIndentCheck(n.indent,y,s),c=P.range[2];let _=new Ef.Pair(k,P);t.options.keepSourceTokens&&(_.srcToken=f),a.items.push(_)}else{b&&s(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),T.comment&&(k.comment?k.comment+=`
|
|
82
|
+
`+T.comment:k.comment=T.comment);let P=new Ef.Pair(k);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}Of.resolveBlockMap=Vv});var Rf=E(Cf=>{"use strict";var Gv=it(),zv=un(),Xv=Ga();function Qv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Gv.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=zv.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&&Xv.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Cf.resolveBlockSeq=Qv});var ir=E(Nf=>{"use strict";function Zv(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}}Nf.resolveEnd=Zv});var Mf=E(Lf=>{"use strict";var eS=j(),tS=rt(),If=st(),rS=it(),nS=ir(),$f=un(),sS=Us(),iS=za(),Xa="Block collections are not allowed within flow collections",Qa=r=>r&&(r.type==="block-map"||r.type==="block-seq");function oS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?If.YAMLMap:rS.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 x=n.items[b],{start:k,key:T,sep:P,value:_}=x,O=$f.resolveProps(k,{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&&!_){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&&sS.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 N="";e:for(let h of k)switch(h.type){case"comma":case"space":break;case"comment":N=h.source.substring(1);break e;default:break e}if(N){let h=l.items[l.items.length-1];eS.isPair(h)&&(h=h.value??h.key),h.comment?h.comment+=`
|
|
84
|
+
`+N:h.comment=N,O.comment=O.comment.substring(N.length+1)}}if(!o&&!P&&!O.found){let N=_?r(t,_,O,s):e(t,O.end,P,null,O,s);l.items.push(N),u=N.range[2],Qa(_)&&s(N.range,"BLOCK_IN_FLOW",Xa)}else{t.atKey=!0;let N=O.end,h=T?r(t,T,O,s):e(t,N,k,null,O,s);Qa(T)&&s(h.range,"BLOCK_IN_FLOW",Xa),t.atKey=!1;let S=$f.resolveProps(P??[],{flow:a,indicator:"map-value-ind",next:_,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 R of P){if(R===S.found)break;if(R.type==="newline"){s(R,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}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 _&&("source"in _&&_.source?.[0]===":"?s(_,"MISSING_CHAR",`Missing space after : in ${a}`):s(S.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=_?r(t,_,S,s):S.found?e(t,S.end,P,null,S,s):null;I?Qa(_)&&s(I.range,"BLOCK_IN_FLOW",Xa):S.comment&&(h.comment?h.comment+=`
|
|
85
|
+
`+S.comment:h.comment=S.comment);let L=new tS.Pair(h,I);if(t.options.keepSourceTokens&&(L.srcToken=x),o){let R=l;iS.mapIncludes(t,R.items,h)&&s(N,"DUPLICATE_KEY","Map keys must be unique"),R.items.push(L)}else{let R=new If.YAMLMap(t.schema);R.flow=!0,R.items.push(L);let K=(I??h).range;R.range=[h.range[0],K[1],K[2]],l.items.push(R)}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),x=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",x),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let b=nS.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}Lf.resolveFlowCollection=oS});var Bf=E(Df=>{"use strict";var aS=j(),cS=G(),lS=st(),uS=it(),dS=_f(),fS=Rf(),pS=Mf();function Za(r,e,t,n,s,i){let o=t.type==="block-map"?dS.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?fS.resolveBlockSeq(r,e,t,n,i):pS.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 mS(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===lS.YAMLMap.tagName&&a==="map"||o===uS.YAMLSeq.tagName&&a==="seq")return Za(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),Za(r,e,t,s,o)}let l=Za(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=aS.isNode(f)?f:new cS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Df.composeCollection=mS});var tc=E(jf=>{"use strict";var ec=G();function hS(r,e,t){let n=e.offset,s=gS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?ec.Scalar.BLOCK_FOLDED:ec.Scalar.BLOCK_LITERAL,o=e.source?yS(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,x]=o[m];if(x===""||x==="\r")s.indent===0&&b.length>c&&(c=b.length);else{b.length<c&&t(l+b.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=b.length),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=b.length+x.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",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,x]=o[m];l+=b.length+x.length+1;let k=x[x.length-1]==="\r";if(k&&(x=x.slice(0,-1)),x&&b.length<c){let P=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(k?2:1),"BAD_INDENT",P),b=""}i===ec.Scalar.BLOCK_LITERAL?(u+=d+b.slice(c)+x,d=`
|
|
89
|
+
`):b.length>c||x[0]===" "?(d===" "?d=`
|
|
90
90
|
`:!p&&d===`
|
|
91
91
|
`&&(d=`
|
|
92
92
|
|
|
93
|
-
`),u+=d+b.slice(c)+
|
|
94
|
-
`,p=!0):
|
|
93
|
+
`),u+=d+b.slice(c)+x,d=`
|
|
94
|
+
`,p=!0):x===""?d===`
|
|
95
95
|
`?u+=`
|
|
96
96
|
`:d=`
|
|
97
|
-
`:(u+=d+
|
|
97
|
+
`:(u+=d+x,d=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function gS({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 yS(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}
|
|
101
|
+
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function gS({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 yS(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}jf.resolveBlockScalar=hS});var nc=E(qf=>{"use strict";var rc=G(),bS=ir();function wS(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=rc.Scalar.PLAIN,c=vS(i,l);break;case"single-quoted-scalar":a=rc.Scalar.QUOTE_SINGLE,c=SS(i,l);break;case"double-quoted-scalar":a=rc.Scalar.QUOTE_DOUBLE,c=xS(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=bS.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function vS(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}`),Ff(r)}function SS(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Ff(r.slice(1,-1)).replace(/''/g,"'")}function Ff(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 xS(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}=kS(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=ES[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
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+=AS(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 kS(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
115
|
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var ES={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 AS(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)}
|
|
116
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function AS(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)}qf.resolveFlowScalar=wS});var Kf=E(Jf=>{"use strict";var Tt=j(),Uf=G(),TS=tc(),PS=nc();function OS(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?TS.resolveBlockScalar(r,e,n):PS.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=_S(r.schema,s,c,t,n):e.type==="scalar"?l=CS(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 Uf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new Uf.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 _S(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 CS({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}Jf.composeScalar=OS});var Wf=E(Hf=>{"use strict";function RS(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}Hf.emptyScalarPosition=RS});var Gf=E(ic=>{"use strict";var NS=Ur(),IS=j(),$S=Bf(),Yf=Kf(),LS=ir(),MS=Wf(),DS={composeNode:Vf,composeEmptyNode:sc};function Vf(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=BS(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=Yf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=$S.composeCollection(DS,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=sc(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&&(!IS.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 sc(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:MS.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Yf.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 BS({options:r},{offset:e,source:t,end:n},s){let i=new NS.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=LS.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}ic.composeEmptyNode=sc;ic.composeNode=Vf});var Qf=E(Xf=>{"use strict";var jS=on(),zf=Gf(),FS=ir(),qS=un();function US(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new jS.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=qS.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?zf.composeNode(l,s,f,o):zf.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=FS.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Xf.composeDoc=US});var ac=E(tp=>{"use strict";var JS=Gn("process"),KS=Wo(),HS=on(),dn=ln(),Zf=j(),WS=Qf(),YS=ir();function fn(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 ep(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
117
117
|
|
|
118
118
|
`:`
|
|
119
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
120
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
119
|
+
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var oc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=fn(t);i?this.warnings.push(new dn.YAMLWarning(o,n,s)):this.errors.push(new dn.YAMLParseError(o,n,s))},this.directives=new KS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=ep(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(Zf.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Zf.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
|
|
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:ep(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(JS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=fn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=WS.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 dn.YAMLParseError(fn(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 dn.YAMLParseError(fn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=YS.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 dn.YAMLParseError(fn(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 HS.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}}};tp.Composer=oc});var sp=E(Js=>{"use strict";var VS=tc(),GS=nc(),zS=ln(),rp=Yr();function XS(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 zS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return GS.resolveFlowScalar(r,e,n);case"block-scalar":return VS.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function QS(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=rp.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
125
|
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
-
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return
|
|
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 ZS(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=
|
|
126
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return np(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 ZS(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=rp.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">":ex(r,c);break;case'"':cc(r,c,"double-quoted-scalar");break;case"'":cc(r,c,"single-quoted-scalar");break;default:cc(r,c,"scalar")}}function ex(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})}}}Js.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}];np(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 np(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 cc(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})}}}Js.createScalarToken=QS;Js.resolveAsScalar=XS;Js.setScalarValue=ZS});var op=E(ip=>{"use strict";var tx=r=>"type"in r?Hs(r):Ks(r);function Hs(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=Hs(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=Ks(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=Ks(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=Ks(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 Ks({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=Hs(e)),t)for(let i of t)s+=i.source;return n&&(s+=Hs(n)),s}ip.stringify=tx});var up=E(lp=>{"use strict";var lc=Symbol("break visit"),rx=Symbol("skip children"),ap=Symbol("remove item");function Pt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),cp(Object.freeze([]),r,e)}Pt.BREAK=lc;Pt.SKIP=rx;Pt.REMOVE=ap;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 cp(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=cp(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===lc)return lc;a===ap&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}lp.visit=Pt});var Ws=E(ce=>{"use strict";var uc=sp(),nx=op(),sx=up(),dc="\uFEFF",fc="",pc="",mc="",ix=r=>!!r&&"items"in r,ox=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function ax(r){switch(r){case dc:return"<BOM>";case fc:return"<DOC>";case pc:return"<FLOW_END>";case mc:return"<SCALAR>";default:return JSON.stringify(r)}}function cx(r){switch(r){case dc:return"byte-order-mark";case fc:return"doc-mode";case pc:return"flow-error-end";case mc: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 `),
|
|
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}ce.createScalarToken=uc.createScalarToken;ce.resolveAsScalar=uc.resolveAsScalar;ce.setScalarValue=uc.setScalarValue;ce.stringify=nx.stringify;ce.visit=sx.visit;ce.BOM=dc;ce.DOCUMENT=fc;ce.FLOW_END=pc;ce.SCALAR=mc;ce.isCollection=ix;ce.isScalar=ox;ce.prettyToken=ax;ce.tokenType=cx});var yc=E(fp=>{"use strict";var pn=Ws();function we(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var dp=new Set("0123456789ABCDEFabcdef"),lx=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ys=new Set(",[]{}"),ux=new Set(` ,[]{}
|
|
135
|
+
\r `),hc=r=>!r||ux.has(r),gc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
136
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
137
137
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
138
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
139
139
|
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&we(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
140
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===pn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield pn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&we(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!we(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&we(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(
|
|
140
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===pn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield pn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&we(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!we(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&we(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(hc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&s[0]!=="#"||n===0&&(s.startsWith("---")||s.startsWith("..."))&&we(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield pn.FLOW_END,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(hc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||we(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
141
141
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
142
142
|
`,i)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>we(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
143
143
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
@@ -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&&Ys.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&&Ys.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&&Ys.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(
|
|
150
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ys.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(hc))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(we(t)||e&&Ys.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(lx.has(t))t=this.buffer[++e];else if(t==="%"&&dp.has(this.buffer[e+1])&&dp.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)}};fp.Lexer=
|
|
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)}};fp.Lexer=gc});var wc=E(pp=>{"use strict";var bc=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}}}};pp.LineCounter=bc});var Sc=E(bp=>{"use strict";var dx=Gn("process"),mp=Ws(),fx=yc();function ot(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function hp(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 yp(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 Vs(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 or(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 gp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!ot(e.start,"explicit-key-ind")&&!ot(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,yp(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 vc=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 fx.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,dx.env.LOG_TOKENS&&console.log("|",mp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=mp.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"&&gp(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&&hp(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":{hp(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=Vs(this.peek(2)),n=or(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
153
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
154
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
154
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ot(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(yp(t.key)&&!ot(t.sep,"newline")){let o=or(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(ot(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=or(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]}):ot(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&&!ot(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||ot(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=Vs(n),i=or(s);gp(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=Vs(e),n=or(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=Vs(e),n=or(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=Vs(e),n=or(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=Vs(e),n=or(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())}}};bp.Parser=vc});var kp=E(hn=>{"use strict";var wp=ac(),px=on(),mn=ln(),mx=ia(),hx=j(),gx=wc(),vp=Sc();function Sp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new gx.LineCounter||null,prettyErrors:e}}function yx(r,e={}){let{lineCounter:t,prettyErrors:n}=Sp(e),s=new vp.Parser(t?.addNewLine),i=new wp.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 xp(r,e={}){let{lineCounter:t,prettyErrors:n}=Sp(e),s=new vp.Parser(t?.addNewLine),i=new wp.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 bx(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=xp(r,t);if(!s)return null;if(s.warnings.forEach(i=>mx.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 wx(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 hx.isDocument(r)&&!n?r.toString(t):new px.Document(r,n,t).toString(t)}hn.parse=bx;hn.parseAllDocuments=yx;hn.parseDocument=xp;hn.stringify=wx});var Ap=E(F=>{"use strict";var vx=ac(),Sx=on(),xx=qa(),xc=ln(),kx=Ur(),at=j(),Ex=rt(),Ax=G(),Tx=st(),Px=it(),Ox=Ws(),_x=yc(),Cx=wc(),Rx=Sc(),Gs=kp(),Ep=Br();F.Composer=vx.Composer;F.Document=Sx.Document;F.Schema=xx.Schema;F.YAMLError=xc.YAMLError;F.YAMLParseError=xc.YAMLParseError;F.YAMLWarning=xc.YAMLWarning;F.Alias=kx.Alias;F.isAlias=at.isAlias;F.isCollection=at.isCollection;F.isDocument=at.isDocument;F.isMap=at.isMap;F.isNode=at.isNode;F.isPair=at.isPair;F.isScalar=at.isScalar;F.isSeq=at.isSeq;F.Pair=Ex.Pair;F.Scalar=Ax.Scalar;F.YAMLMap=Tx.YAMLMap;F.YAMLSeq=Px.YAMLSeq;F.CST=Ox;F.Lexer=_x.Lexer;F.LineCounter=Cx.LineCounter;F.Parser=Rx.Parser;F.parse=Gs.parse;F.parseAllDocuments=Gs.parseAllDocuments;F.parseDocument=Gs.parseDocument;F.stringify=Gs.stringify;F.visit=Ep.visit;F.visitAsync=Ep.visitAsync});function Ix(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function $x(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Nx);return t?Dr(e,t[1])!==null:!1}function Lx(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Tp.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Pp(r){return Ix(r)||$x(r)||Lx(r)}var Tp,Nx,kc=A(()=>{Mu();Tp=Jy(Ap(),1),Nx=/<([a-zA-Z_][\w.-]*)/});function Mx(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Pp(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 zs(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 zs(r){return Mx(r).map(e=>e.text)}var Op,_p=A(()=>{kc();Op=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var
|
|
164
|
-
`).length-1}));return n}function
|
|
165
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
163
|
+
`});var qe=A(()=>{zn();Mo();Ou();_u();kc();_p();Xn()});function ar(r){return{...Eu(r),server:r.files.get("server.ts")??""}}function Xs(r){return!!r.server&&!r.code}var gn=A(()=>{qe();qe()});function Fx(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 Cp(r){let e=[];for(let s of jx)for(let i of r.matchAll(s)){let o=Fx(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 Rp(r){return Cp(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 Bx)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Jx(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...qx(i,n)),s}function qx(r,e){let t=new Set(Object.keys(e));return Cp(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Ux(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Ux(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 Jx(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,21 +331,21 @@ 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,_t,
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Ot,_t,Bx,jx,Qs=A(()=>{Ot=["client"],_t=["client","server"],Bx=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Ot},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:_t},{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:_t},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:_t},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:_t},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:_t},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:_t},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:_t},{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}],jx=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var Qp=A(()=>{});var de,xe,dr=A(()=>{de=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},xe=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
|
-
`){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
|
|
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
|
|
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 de(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 de(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 pi,Rc=A(()=>{dr();pi=class extends xe{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
|
+
`)),!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 de(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(`
|
|
338
338
|
|
|
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
|
|
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 fr,mi=A(()=>{dr();fr=class extends xe{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 hi,Nc=A(()=>{mi();hi=class extends fr{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 gi,Ic=A(()=>{dr();gi=class extends xe{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
|
-
`);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 yi
|
|
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 yi,$c=A(()=>{dr();yi=class extends xe{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
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
|
|
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 de(`Prompt blocked: ${t}`)}}}});var bi,Lc=A(()=>{mi();bi=class extends fr{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=pk.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function mk(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Mc(r,e){let t=$t(r.protocol),n=t.getPath(r.model,e.stream),s=mk(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 hk(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function pr(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||hk(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Zp,pk,Dc=A(()=>{Rc();Nc();Ic();$c();Lc();Zp=new bi,pk=new Map([["openai",new pi],["openrouter",new hi],["anthropic",new gi],["gemini",new yi],["ollama",Zp],["openai-compat",Zp]])});function em(r){let e=r.indexOf(`\r
|
|
344
344
|
\r
|
|
345
345
|
`),t=r.indexOf(`
|
|
346
346
|
|
|
347
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
348
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
347
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Bc(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*tm(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=Bc(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=em(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=Bc(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=em(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 tm(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var rm=A(()=>{Dc()});import{strToU8 as gk,strFromU8 as yk,deflateSync as bk,inflateSync as wk}from"fflate";function Fc(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 hr,
|
|
368
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function
|
|
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?"":
|
|
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":
|
|
366
|
+
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function Sk(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 xk(r){let e=Sk(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 kk(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 Ek(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=kk(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 qc(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 vk){let c=a(t);if(c!==null){let l=An(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=Ek(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function Uc(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=bk(gk(t),{level:9}),s=Tk(n),i=`${nm}:${s}`;return i.length>Ak?"":"#"+jc+i}catch{return""}}function Jc(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(jc))return null;let t=e.slice(jc.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==nm)return null;let s=Pk(t.slice(n+1)),i=JSON.parse(yk(wk(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 Tk(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 Pk(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 vk,jc,nm,Ak,sm=A(()=>{vk=[["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",xk]];jc="tb=",nm="1",Ak=6e4});var mr=A(()=>{Qp();dr();Dc();rm();sm();mi();Ic();$c();Rc();Nc();Lc()});function gr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function Kc(){return Pn}async function Ke(){let[r,e]=await Promise.all([om(),Ik()]);return Nk([...$k(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function Nk(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function im(){let r;try{r=await fetch(Ok,{signal:AbortSignal.timeout(Ck)})}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 Ik(){if(Tn&&Date.now()-Tn.fetchedAt<=_k)return Tn.models;let r=await im()??await im();return r?(Tn={models:r,fetchedAt:Date.now()},Pn=null,r):Tn?.models??[]}async function om(){if(wi&&Date.now()-wi.fetchedAt<=Rk)return wi.models;let r=gr(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 wi={models:e,fetchedAt:Date.now()},e}function $k(r){let e=new Set(Object.entries(hr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Hc(){return Object.values(hr).some(r=>!!process.env[r])}async function vi(){return Hc()||process.env.TB_AI_BASE_URL?!0:(await om()).length>0}function am(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 hr,Ok,_k,Ck,Rk,Tn,wi,Pn,Dt=A(()=>{hr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};Ok="https://api.typebulb.com/api/models",_k=1440*60*1e3,Ck=5e3,Rk=60*1e3,Tn=null,wi=null,Pn=null});function He(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:`${gr(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=hr[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 ft(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 Mc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var Si=A(()=>{mr();Dt()});import{realpathSync as Bk}from"fs";import{join as Vc,resolve as jk}from"path";import{homedir as Fk}from"os";function Ai(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Vc(r,".."):Vc(Fk(),".typebulb")}function Ye(){return process.env.TYPEBULB_SERVERS_DIR||Vc(Ai(),"servers")}function re(r){let e=jk(r),t=e;try{t=Bk.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function dm(r,e){let t=re(r),n=re(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ti=A(()=>{});import{readFileSync as qk,writeFileSync as Uk,mkdirSync as Jk}from"fs";import{join as Kk}from"path";function fm(){return Kk(Ai(),"trust.json")}function Gc(){try{let r=JSON.parse(qk(fm(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Hk(r){Jk(Ai(),{recursive:!0}),Uk(fm(),JSON.stringify([...r]))}function Bt(r){return Gc().has(re(r))}function br(r,e){let t=Gc(),n=re(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Hk(t))}function zc(){return[...Gc()]}var Cn=A(()=>{Ti()});function Ce(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
368
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Ve(r){let e=r.replace(Wk,"").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 Wk,Pi,Oi=A(()=>{Wk=/\u001b\[[0-9;]*m/g;Pi=(r,e)=>``});import{existsSync as Yk,readdirSync as Vk,statSync as Gk}from"fs";import{join as zk}from"path";function _i(r){if(!Yk(r))return[];let e;try{e=Vk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=zk(r,n);try{let i=Gk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Xc=A(()=>{});var wr,Qc=A(()=>{wr=class{ensureHarnessSupport(){}}});import{openSync as Xk,readSync as Qk,closeSync as Zk,statSync as e0,readdirSync as t0,readFileSync as r0,existsSync as n0}from"fs";import{join as Nn}from"path";import{homedir as tl}from"os";function s0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Ci(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Pi(e.data,e.media_type):""}function Zc(r){return typeof r=="string"?Ce(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ce(e);let t=e;return typeof t?.text=="string"?Ce(t.text):t?.content!=null?Zc(t.content):Ci(t)}).join(`
|
|
370
|
+
`):r==null?"":Ce(JSON.stringify(r))}function o0(r){let e=r.trim();return!!e&&gm.some(t=>t.test(e))}function a0(r){let e=r.trim();return e?gm.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function l0(r){return r.replace(c0,"")}function u0(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 mt(r){let e=l0(r).trim();return e?u0(e)??(o0(e)?"":e):""}function el(r){return r?.type==="text"&&typeof r.text=="string"?mt(r.text):""}function rl(r,e){if(typeof r=="string")return Ve(r);if(!r||typeof r!="object")return Ve(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=mm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=mm(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":Ve(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"):Ve(e)}function Rn(r){return!!r.isSidechain||!!r.isMeta}function d0(r){let e;try{e=Xk(r,"r")}catch{return""}try{let n=65536;try{n=e0(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=Qk(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
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||Rn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=
|
|
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()&&
|
|
373
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||Rn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=mt(u):Array.isArray(u)&&(d=u.map(el).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{Zk(e)}}function f0(r){let e;try{e=t0(hm)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(r0(Nn(hm,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var i0,pm,gm,c0,Ee,mm,hm,vr,Ri=A(()=>{Oi();Xc();Qc();i0=Nn(tl(),".claude","projects"),pm=r=>Nn(i0,s0(r));gm=[/\[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];c0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Ee=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,mm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;hm=Nn(tl(),".claude","sessions");vr=class extends wr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return n0(Nn(tl(),".claude"))}sessionsDir(e){return pm(e)}listSessionFiles(e){return _i(pm(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(Rn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=mt(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=Zc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:rl(e.toolUseResult,o)})}else{let o=el(i)||Ci(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=mt(Zc(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=>!a0(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()&&mt(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 f0(e)}readPreview(e){return d0(e)}searchText(e){if(!e||Rn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=mt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(el).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 ym}from"child_process";import{readdir as p0,readFile as wm,writeFile as vm,unlink as nl,mkdir as m0}from"fs/promises";import{mkdirSync as Sm,writeFileSync as Ni,appendFileSync as h0,readFileSync as sl}from"fs";import*as he from"path";import{fileURLToPath as g0}from"url";function il(r){return he.join(Ye(),`${r}.json`)}function $n(r){return he.join(Ye(),`${r}.log`)}function ol(r){return he.join(Ye(),`${r}.wait.json`)}function xm(r){try{let e=JSON.parse(sl(ol(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function al(r,e=""){let t=xm(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Ii(r,e,t=""){try{Sm(Ye(),{recursive:!0});let n=xm(r);n[t]=e,Ni(ol(r),JSON.stringify({cursors:n}))}catch{}}function $i(r){let e=$n(r);try{Sm(Ye(),{recursive:!0}),Ni(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(h0(e,c),s+=c.length,s>2*bm){let l=sl(e),f=l.subarray(Math.max(0,l.length-bm));Ni(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 km(r){try{Ni($n(r),"")}catch{}}function Re(r,e=0){try{let t=sl($n(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 cl(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function b0(r){let e=y0.exec(r);return e?Number(e[1]):void 0}function Em(r,e){let t=r.split(`
|
|
375
375
|
`),n=[];if(t.forEach((o,a)=>{let c=b0(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
|
|
376
|
+
`)}function ll(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Am(r){await m0(Ye(),{recursive:!0}),await vm(il(r.pid),JSON.stringify(r))}async function Tm(r,e){let t=il(r);try{let n=JSON.parse(await wm(t,"utf8"));if(n.denied===e)return;n.denied=e,await vm(t,JSON.stringify(n))}catch{}}async function In(r){await nl(il(r)).catch(()=>{}),await nl($n(r)).catch(()=>{}),await nl(ol(r)).catch(()=>{})}async function z(r){let e;try{e=await p0(Ye())}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 wm(he.join(Ye(),s),"utf8"))}catch{await In(i);return}o&&typeof o.pid=="number"&&ll(o.pid)?t.push(o):await In(i)})),(r?t.filter(s=>s.agent==null&&dm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function ul(r,e){let t=re(r);return(await z()).find(n=>n.cwd!=null&&re(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function jt(r){try{process.kill(r,"SIGTERM")}catch{}await In(r)}function Sr(r,e){let t=re(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&re(n.file)===t)}async function dl(r){let e=Sr(await z(),r);for(let t of e)await jt(t.pid);return e}function v0(r,e,t){(process.platform==="win32"?ym("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):ym(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Pm(){return he.join(he.dirname(g0(import.meta.url)),"index.js")}function S0(r,e={}){return{command:process.execPath,args:[Pm(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function x0(r){return{command:process.execPath,args:[Pm(),`agent:${r}`,"--no-open"]}}async function Om(r,e,t,n){let s=await r();if(s)return s;v0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await w0(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Li(r,e={}){let t=e.cwd??process.cwd(),n=he.resolve(t,r),[s]=await dl(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return Om(async()=>Sr(await z(),n)[0],S0(r,i),t,he.basename(r))}async function _m(r,e=process.cwd()){return Om(()=>ul(e,r),x0(r),e,`the ${r} mirror`)}var bm,y0,w0,Ne=A(()=>{Ti();bm=1e6;y0=/^── run (\d+) ── /;w0=r=>new Promise(e=>setTimeout(e,r))});function Mi(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function fl(r){return(Mi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var pl=A(()=>{});import{readdirSync as k0,readFileSync as E0,statSync as A0}from"fs";import{join as Cm,basename as T0}from"path";function Rm(r,e,t){if(e>8)return t;let n;try{n=k0(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Rm(Cm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Cm(r,s.name));return t}function Di(r){return Rm(r,0,[]).map(e=>{let t=0;try{t=A0(e).mtimeMs}catch{}let n,s=!1;try{let i=E0(e,"utf8");n=Mi(i.slice(0,1024));let o=fe(i);s=!!o&&Xs(ar(o))}catch{}return{path:e,name:n??T0(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Nm=A(()=>{qe();gn();pl()});function xr(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 Bi=A(()=>{});import{readFile as P0}from"fs/promises";async function ml(r){try{let e=fe(await P0(r,"utf-8"));return e?xr(ar(e)):void 0}catch{return}}var Im=A(()=>{gn();Bi()});function hl(r){let e=fe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Rp(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=wu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Pu(c)}var $m=A(()=>{qe();Qs()});import{spawn as Lm}from"child_process";import{basename as O0}from"path";function _0(){return process.env.TYPEBULB_EDITOR||"code"}function R0(r,e,t){return t==null?[e]:C0.test(O0(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function N0(r,e){let t=_0();return{command:t,args:R0(t,r,e)}}function gl(r,e){let{command:t,args:n}=N0(r,e),s=process.platform==="win32"?Lm("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Lm(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var C0,Mm=A(()=>{C0=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as I0,existsSync as $0}from"fs";import*as Ft from"path";import{fileURLToPath as L0}from"url";function Dm(){let r=Ft.dirname(L0(import.meta.url));for(;!$0(Ft.join(r,"package.json"));){let e=Ft.dirname(r);if(e===r)break;r=e}return r}function qt(){return Ft.join(Dm(),"README.md")}function kr(){return Ft.join(Dm(),"description.md")}function M0(r){let e=I0(kr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
377
377
|
name: typebulb
|
|
378
378
|
description: ${JSON.stringify(e)}
|
|
379
379
|
version: ${r}
|
|
380
|
-
---`}function D0(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
|
|
380
|
+
---`}function D0(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 Bm(r,e){return`${M0(e)}
|
|
381
381
|
|
|
382
382
|
${D0(e)}
|
|
383
383
|
|
|
384
384
|
${r.trim()}
|
|
385
|
-
`}var ji=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 Fi(r,e=process.cwd()){for(let t of
|
|
385
|
+
`}var ji=A(()=>{});import{readFileSync as jm,existsSync as B0}from"fs";import*as Ie from"path";function Fm(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of Fm(r)){let i;try{i=jm(Ie.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of qm(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*qm(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 Fi(r,e=process.cwd()){for(let t of Fm()){let n;try{n=jm(Ie.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of qm(n))if(s===r)return i}return process.env[r]}function j0(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function ht(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ie.dirname(e),c=`(mode: ${s??"none"})`,l=t?j0(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"])B0(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 gt=A(()=>{});import*as $e from"fs/promises";import*as Ae from"path";function bl(r,e){ge(e);let t=process.env.TYPEBULB_ORIGIN||F0;try{return Ui(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function Ui(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
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,qi(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 Ji(r,e={}){let t=await fetch(
|
|
389
|
-
`),n=
|
|
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 Ji(r,e={}){let t=await fetch(yl(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(q0(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 q0(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
389
|
+
`),n=fe(t(r)),s=fe(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Xe.every(i=>(n.files.get(Pe[i].path)||"")===(s.files.get(Pe[i].path)||""))}async function Um(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=bl(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await Ji(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 F0,qi,
|
|
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 F0,qi,yl,Ki=A(()=>{gt();qe();F0="https://typebulb.com",qi=(r,e)=>Ae.join("typebulbs","u",r,`${e}.bulb.md`),yl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Er from"fs/promises";import*as Km from"path";async function Hi(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(yl(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:Jm(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Jm(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 Jm(r){try{return JSON.parse(r).error||r}catch{return r}}async function Hm(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=bl(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=Km.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Hi(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
|
|
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 wl=A(()=>{Ki()});var Ar=A(()=>{Ne();Nm();Im();pl();$m();Mm();Cn();Dt();Dt();Si();ji();Ki();wl();gt()});import{copyFileSync as U0,existsSync as Wm,mkdirSync as Ym,rmSync as J0,writeFileSync as K0}from"fs";import{homedir as H0}from"os";import*as Le from"path";import{fileURLToPath as W0}from"url";function Q0(){return X0.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(kr())).replace('"__TB_README_PATH__"',JSON.stringify(qt()))}function Vm(){try{if(!Wm(Wi()))return}catch{return}try{let r=Y0();Ym(Le.dirname(r),{recursive:!0}),K0(r,Q0()),J0(V0(),{force:!0})}catch{}try{let r=G0();if(!Wm(r))return;let e=z0();Ym(Le.dirname(e),{recursive:!0}),U0(r,e)}catch{}}var Wi,Y0,V0,G0,z0,X0,Gm=A(()=>{Ar();Wi=()=>Le.join(H0(),".pi","agent"),Y0=()=>Le.join(Wi(),"extensions","typebulb.ts"),V0=()=>Le.join(Wi(),"extensions","typebulb-wait.ts"),G0=()=>Le.join(Le.dirname(W0(import.meta.url)),"agents","pi","matchu-patchu.ts"),z0=()=>Le.join(Wi(),"extensions","matchu-patchu.ts"),X0=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
|
|
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 eE,tE,
|
|
545
|
-
`)}catch{}await Promise.race([this.#v,Qm(
|
|
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"?sE:iE)})}#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.#
|
|
543
|
+
`});function U(r){return r?.message??String(r)}var H,yt=A(()=>{H=process.cwd()});import{spawn as zm}from"child_process";import{StringDecoder as Z0}from"string_decoder";function aE(r,e){let t=new Z0("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 eE,tE,Xm,rE,nE,sE,iE,oE,Yi,Vi,Qm,Zm=A(()=>{yt();eE=3e4,tE=5e3,Xm=2e3,rE=2e3,nE=12e4,sE=8e3,iE=15e3,oE=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),Yi=new Set;process.on("exit",()=>{for(let r of Yi)try{r.kill()}catch{}});Vi=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#d;#f;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>zm(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#f="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#f=`could not start pi: ${U(o)}`,this.#b();return}this.#e=i,this.#d=t,Yi.add(i),i.stdout&&aE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-rE)}),i.on("error",o=>this.#k(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#k(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),Yi.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#d=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#d}get error(){return this.#f}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#x({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.#x(i),{ok:!0}}async rpc(e){if(!oE.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#d=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#d}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error: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()+tE),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,Qm(Xm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Qm(Xm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{zm("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Yi.delete(e),this.#r=[],this.#E("pi was shut down")}}#x(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"?sE:iE)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#f??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},eE);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??nE),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}}#
|
|
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)
|
|
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??nE),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}}#k(e){this.#f=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},Qm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as eh,readFileSync as cE,realpathSync as lE}from"fs";import{join as Ut,dirname as sh,resolve as uE}from"path";import{homedir as th}from"os";function fE(r,e){let t=Ut(r,".pi");if(dE.some(s=>eh(Ut(t,s))))return!0;let n=Ut(e,".agents","skills");for(let s=r;;){let i=Ut(s,".agents","skills");if(i!==n&&eh(i))return!0;let o=sh(s);if(o===s)return!1;s=o}}function pE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=sh(t);if(n===t)return!1;t=n}}function ih(r,e){try{let t=e?.agentDir??Ut(th(),".pi","agent"),n=rh(e?.home??process.env.HOME??th()),s=rh(uE(r));if(!fE(s,n))return null;let i=nh(Ut(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||pE(nh(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 dE,rh,nh,oh=A(()=>{dE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],rh=r=>{try{return lE(r)}catch{return r}},nh=r=>{try{return JSON.parse(cE(r,"utf8"))}catch{return{}}}});import{statSync as mE,openSync as hE,readSync as gE,closeSync as yE,existsSync as bE}from"fs";import{join as vl}from"path";import{homedir as ch}from"os";function vE(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function ah(r){return r.type==="message"?SE(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var wE,SE,Tr,Sl=A(()=>{Oi();Xc();Qc();Gm();Zm();oh();wE=vl(ch(),".pi","agent","sessions");SE=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 bE(vl(ch(),".pi","agent"))}ensureHarnessSupport(){Vm()}createDriver(e,t){let n=new Vi(e,t),s=ih(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return vl(wE,vE(e))}listSessionFiles(e){return _i(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 ah(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:Ve(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)ah(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=hE(e,"r")}catch{return""}try{let s=65536;try{s=mE(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),y=gE(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
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{yE(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"?
|
|
552
|
-
`):""}}});var Gi,
|
|
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,IE)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=LE(await Lt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function
|
|
556
|
-
`))>=0;){let q=g.partial.slice(0,
|
|
557
|
-
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await HE(Jt(e.cwd,w))).mtimeMs}}catch{return{f:w,m:0}}}))).sort((w,C)=>C.m-w.m).map(w=>w.f)}function
|
|
558
|
-
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&C.push({text:J,lower:J.toLowerCase()})}return
|
|
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()&&(
|
|
560
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=
|
|
561
|
-
${r}`;return
|
|
562
|
-
`)}function
|
|
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{yE(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"?Ce(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ce(t.text):t?.type==="image"&&t.data?Pi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
552
|
+
`):""}}});var Gi,lh=A(()=>{Gi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as xE}from"child_process";import{promisify as kE}from"util";import{readFile as EE}from"fs/promises";import{resolve as uh,sep as AE}from"path";async function Pr(r,e){let{stdout:t}=await TE("git",r,{cwd:e,maxBuffer:67108864});return t}async function Or(){if(zi)return zi;try{zi=(await Pr(["rev-parse","--show-toplevel"],H)).trim()}catch{}return zi}function PE(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function fh(){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:PE(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 ph(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=uh(e,r);if(!s.startsWith(uh(e)+AE))return{ok:!1,error:"outside repository"};let i=await EE(s);return i.includes(0)?xl("Binary file (not shown)",!1):xl(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 xl(n,!1)}catch(t){return{ok:!1,error:U(t)}}}var TE,dh,zi,xl,Xi=A(()=>{yt();TE=kE(xE),dh=2e6;xl=(r,e)=>({ok:!0,text:r.slice(0,dh),untracked:e,truncated:r.length>dh})});function Qi(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 kl=A(()=>{});var Zi,eo,mh=A(()=>{Zi=".typebulb/paste",eo={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 OE,mkdirSync as _E,writeFileSync as CE,readFileSync as RE}from"fs";import{join as to}from"path";function hh(){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 LE(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function ME(r){let e=AbortSignal.timeout(NE);for(let[t,n]of $E){let s=He(t,n);if(typeof s!="string"){try{let i=await ft(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,IE)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=LE(await Lt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function gh(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=to(r,Zi);try{_E(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${hh()}`,s=Object.keys(eo).find(a=>eo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await ME(e.data)??`paste-${hh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;OE(to(t,o));a++)o=`${n}-${a}.${s}`;try{CE(to(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${Zi}/${o}`}}function yh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=eo[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:RE(to(r,Zi,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var NE,IE,$E,bh=A(()=>{mr();Ar();yt();mh();NE=4e3,IE=4e3,$E=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as wh,openSync as DE,readSync as BE,closeSync as jE,statSync as _r,readdirSync as vh,watchFile as FE,unwatchFile as Sh,mkdirSync as qE,writeFileSync as UE,readFileSync as ro,unlinkSync as JE,rmSync as KE}from"fs";import{stat as HE}from"fs/promises";import{dirname as WE,join as Jt,resolve as xh}from"path";import{execFile as YE}from"child_process";function XE(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function no(r){let e={cwd:H,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&&_(g)}}let l=g=>Jt(g,GE),f=(g,v)=>Jt(l(g),`${v}.lock`);function u(g,v){try{let w=f(g,v);if(Date.now()-_r(w).mtimeMs>=kh)return!1;try{let C=parseInt(ro(w,"utf8").trim(),10);if(C===process.pid||!XE(C))return!1}catch{}return!0}catch{return!1}}function d(g,v){if(v)try{qE(l(g),{recursive:!0}),UE(f(g,v),String(process.pid))}catch(w){console.error("[lock] claim failed:",U(w))}}function p(g){try{KE(Jt(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function y(g){let v=l(g);if(!wh(v))return;let w;try{w=vh(v)}catch{return}let C=Date.now();for(let M of w){if(!M.endsWith(".lock"))continue;let B=Jt(v,M);try{let $=_r(B);C-$.mtimeMs>zE&&JE(B)}catch{}}}function m(g){try{return _r(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=x(g);v&&_(v)}function x(g){if(!g.everAttached)return k(g.cwd)??T(g.cwd,()=>!0)}function k(g){let v=l(g);if(!wh(v))return;let w;try{w=vh(v)}catch{return}let C;for(let B of w)if(B.endsWith(".lock"))try{let $=_r(Jt(v,B));if(Date.now()-$.mtimeMs>=kh||parseInt(ro(Jt(v,B),"utf8").trim(),10)!==process.pid)continue;(!C||$.mtimeMs>C.mtime)&&(C={sessionId:B.slice(0,-5),mtime:$.mtimeMs})}catch{}if(!C)return;let M=r.listSessionFiles(g).find(B=>B.sessionId===C.sessionId);if(!(!M||m(M.file)))return M}function T(g,v){return r.listSessionFiles(g).sort((w,C)=>C.mtime-w.mtime).find(w=>!u(g,w.sessionId)&&v(w))}function P(g,v){let w=e;if(w.file)try{Sh(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 _(g){let v=e;n=void 0,P(g.file,g.sessionId),v.everAttached=!0,d(v.cwd,g.sessionId),N();try{Sh(g.file)}catch{}FE(g.file,{interval:200},()=>N())}function O(){P(void 0,"")}function N(){let g=e;if(!g.file)return;let v;try{v=_r(g.file).size}catch{return}if(v<=g.offset)return;let w;try{w=DE(g.file,"r")}catch{return}try{let q=v-g.offset,ue=Buffer.alloc(q),ee=0;for(;ee<q;){let ou=BE(w,ue,ee,q-ee,g.offset+ee);if(!ou)break;ee+=ou}g.offset+=ee,g.partial+=ue.subarray(0,ee).toString("utf8")}finally{jE(w)}let C,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 ue=r.parseEntry(q);if(!ue)continue;let ee=r.idOf(ue);ee&&(g.entries.set(ee,ue),!r.isSidechain(ue)&&r.isLeafType(ue)&&(C=ee))}if(!C)return;let B=[],$=g.entries.get(C),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(ee=>r.idOf(ee))),ue=h(g.entries);for(let ee=B.length-1;ee>=0;ee--)L(B[ee]),S(r.idOf(B[ee]),ue,q)}g.chainLastId=C}function h(g){let v=new Map;for(let w of g.values()){let C=r.parentOf(w);if(!C)continue;let M=v.get(C);M?M.push(w):v.set(C,[w])}return v}function S(g,v,w){if(!g)return;let C=v.get(g);if(!C)return;let M=C.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 ue=I(q,v);$.push(...ue.events),J+=ue.count}J>0&&e.buffer.push({type:"fork",atId:g,count:J,events:$})}function I(g,v){let w=[],C=[g];for(;C.length;){let $=C.pop();if(r.isSidechain($))continue;w.push($);let J=v.get(r.idOf($)??"");if(J)for(let q of J)C.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:C,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(),C&&(e.latestModel=C),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 R(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await K()}}async function K(){if(r.listSessionFiles(e.cwd).length)return;let g=await Or();if(!g)return;let v=xh(g).toLowerCase();for(let w=xh(e.cwd);w.toLowerCase()!==v;){let C=WE(w);if(C===w)return;w=C;let M=r.listSessionFiles(w).length;if(M)return{dir:w,count:M}}}K().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 W=new Gi;async function De(g,v){W.accept(g,v)&&console.log(v)}function Z(){let g=r.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-_r(e.file).mtimeMs<1e4}catch{return!1}}function Y(){return r.chainWorking([...e.entries.values()])&&Z()}function Be(){!r.createDriver||s()||e.latestModel||Y()||i(e.file)}async function Te(g){let v=e;b(),c(),Be(),a();let w=s();for(let $ of t)$!==w&&$.d.dialog;let C=new Set([...t].filter($=>$.d.streaming&&$.file).map($=>$.file)),M=C.size?r.listSessionFiles(v.cwd).filter($=>C.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||Y(),latestModel:v.latestModel,composer:B,busy:M}}async function ru(){b(),c();let g=s();if(g?.d.error&&!g.d.streaming&&(await o(g),g=void 0),!g){if(Y())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 xy(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 C=await ru();return C.ok?C.d.send(w,v):C}async function ky(g,v){let w=s();return w?w.d.respondUi(String(g??""),v??{}):{ok:!1,error:"no dialog pending"}}async function Ey(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 C=await ru();return C.ok?C.d.rpc(g):C}let w=s();return!w||w.d.error?{ok:!1,error:"not running"}:w.d.rpc(g)}async function Ay(){let g=s();if(g)try{await g.d.stop()}catch(v){console.error("[composer] stop:",U(v))}return{ok:!0}}async function Ty(){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 Py(){if(!r.createDriver)return[];let g=await new Promise(w=>{YE("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(C,M)=>w(C?"":M))});return(await Promise.all(g.split(`
|
|
557
|
+
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await HE(Jt(e.cwd,w))).mtimeMs}}catch{return{f:w,m:0}}}))).sort((w,C)=>C.m-w.m).map(w=>w.f)}function Oy(){for(let g of[...t])o(g)}async function _y(g){return r.createDriver?gh(e.cwd,g):{ok:!1,error:"not supported"}}async function Cy(g){return yh(e.cwd,String(g??""))}async function Ry(){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 nu=new Map;function Ny(g,v){let w=nu.get(g);if(w&&w.mtime===v)return w.turns;let C=[],M="";try{M=ro(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&&C.push({text:J,lower:J.toLowerCase()})}return nu.set(g,{mtime:v,turns:C}),C}async function Iy(g){let v=g.toLowerCase(),w=[];for(let{sessionId:C,file:M,mtime:B}of r.listSessionFiles(e.cwd).sort(($,J)=>J.mtime-$.mtime)){let{hitCount:$,snippet:J}=Qi(Ny(M,B),v);if($&&(w.push({sessionId:C,mtime:B,preview:r.readPreview(M),hitCount:$,snippet:J}),w.length>=QE))break}return w}let su=800,iu=new Map;function $y(g,v){let w=iu.get(g);if(w&&w.mtime===v)return w.text;let C="";try{C=ro(g,"utf8")}catch{return""}let M="";for(let $ of C.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>su?M.slice(0,su).trimEnd()+"\u2026":M;return iu.set(g,{mtime:v,text:B}),B}async function Ly(g){let v=r.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:v?$y(v.file,v.mtime):""}}async function My(g){let v=e,w=r.listSessionFiles(v.cwd).find(C=>C.sessionId===g);return w?w.file===v.file?{ok:!0}:(_(w),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),y(e.cwd),b(),{info:R,poll:Te,logEmbedStatus:De,listSessions:Ry,searchSessions:Iy,sessionPeek:Ly,attach:My,composerSend:xy,composerStop:Ay,composerNew:Ty,composerFiles:Py,composerUiRespond:ky,composerRpc:Ey,composerPaste:_y,composerPasteRead:Cy,shutdownComposer:Oy}}var VE,GE,kh,zE,QE,El=A(()=>{yt();lh();Xi();kl();bh();VE=".typebulb",GE=`${VE}/locks`,kh=5e3,zE=6e4;QE=50});import{existsSync as Ol,mkdirSync as ZE,readFileSync as Eh,writeFileSync as eA}from"fs";import{join as Kt,isAbsolute as tA}from"path";async function Ah(r,e){let t=tA(r)?r:Kt(H,r);return Ol(t)?(gl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Th(r){let e=H,t=hl(r),n=Kt(e,"typebulbs");ZE(n,{recursive:!0});let s=fl(t),i=`${s}.bulb.md`;for(let l=2;Ol(Kt(n,i))&&Eh(Kt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Kt(n,i);Ol(o)||eA(o,t);let a=Kt("typebulbs",i),c=await Li(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Ph(){return z(H)}async function Oh(r){return await jt(r),{ok:!0}}async function _h(){return Di(H).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Bt(r.path)}))}async function Ch(r){let e=r.toLowerCase(),t=[];for(let n of Di(H).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Eh(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}=Qi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Rh(r,e){let t=H;e!=null&&br(r,e);let n=await Li(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Nh(r){return{cap:await ml(r)}}async function Ih(r,e){return br(r,e),{ok:!0}}async function $h(r,e){return Re(r,e)}async function Bh(){return Ln&&Date.now()-Ln.fetchedAt<=nA?Ln.samples:(Al??=sA().finally(()=>{Al=null}),Al)}async function sA(){try{let r=await fetch(`${rA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Mh)});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:Bo(i.config)}));return Ln={samples:s,fetchedAt:Date.now()},s}catch{return Ln?.samples??[]}}async function jh(r){return _l.test(r)?Uh(Lh,"samples",r,!0):{ok:!1,error:"bad slug"}}async function Fh(){let r=Cl();if(!r)return{bulbs:[]};let e=`${so()}
|
|
561
|
+
${r}`;return bt?.key===e&&Date.now()-bt.fetchedAt<=iA?{user:bt.user,bulbs:bt.bulbs}:(Tl??=oA(e,r).finally(()=>{Tl=null}),Tl)}async function Pl(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Mh)});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 oA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=so(),s;try{s=await Pl(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await Pl(n,"/api/me",t)}let o=(await Pl(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Bo(a.config)}));return bt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return bt?.key===r?{user:bt.user,bulbs:bt.bulbs}:{bulbs:[]}}}async function qh(r,e,t=!1){return!_l.test(e)||!_l.test(r)?{ok:!1,error:"bad slug"}:Uh(so(),r,e,t)}async function Uh(r,e,t,n){let s=qi(e,t);try{let i=await Ji({origin:r,userSlug:e,slug:t,dest:Kt(H,s)},{force:n,token:Cl(),timeoutMs:Dh});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 Jh(r,e=!1){let t=Cl();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=Ui(r,H,so()),s=await Hi(n,{token:t,force:e,timeoutMs:Dh});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 rA,Lh,nA,Mh,Dh,Ln,Al,_l,iA,bt,Tl,so,Cl,Rl=A(()=>{Ar();yt();kl();qe();rA="https://api.typebulb.com",Lh="https://typebulb.com",nA=3600*1e3,Mh=5e3,Dh=15e3,Ln=null,Al=null;_l=/^[a-z0-9][a-z0-9-]*$/,iA=300*1e3,bt=null,Tl=null,so=()=>Fi("TYPEBULB_ORIGIN",H)||Lh,Cl=()=>Fi("TYPEBULB_TOKEN",H)});import{readFileSync as $l,writeFileSync as Hh,mkdirSync as aA,appendFileSync as Wh,rmSync as Kh}from"fs";import{join as ao,dirname as cA}from"path";import{createServer as lA}from"http";function wt(r){try{return JSON.parse($l(r,"utf8"))}catch{return null}}function oo(r,e){aA(cA(r),{recursive:!0}),Hh(r,JSON.stringify(e,null,2)+`
|
|
562
|
+
`)}function Vh(r,e,t){let n=ao(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{Wh(n,a+t+`
|
|
565
565
|
`+o.join(`
|
|
566
566
|
`)+`
|
|
567
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function mA(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?Bn="live":s>pA&&(Bn="uncached")}function
|
|
567
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function mA(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?Bn="live":s>pA&&(Bn="uncached")}function zh(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 hA(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 Xh(r){let e;try{e=JSON.parse(r)}catch{return r}Dn=typeof e?.model=="string"?e.model:null,Me&&(e.model=Me),Wt&&(e.provider=Gh(Wt));let t=/haiku/i.test(Dn||"");return jn!=null&&!t&&(e.reasoning={effort:Nl[jn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,hA(e),JSON.stringify(e)}function gA(){let r="",e=0,t=new Map,n=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return t.clear(),e=0,i;case"content_block_start":{if(n.has(a.content_block?.type))return t.set(a.index,null),null;let c=e++;return t.set(a.index,c),a.index=c,`event: ${a.type}
|
|
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 yA(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 Mn(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 bA(r,e,t){if(!
|
|
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 yA(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 Mn(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 bA(r,e,t){if(!Me){Mn(e,400,"invalid_request_error",fA);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Mn(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(Ll,{method:"POST",headers:zh(r,n),body:Xh(t),signal:s.signal})}catch(u){Mn(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?gA():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});mA(p);let y=f(p);y&&e.write(y)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function wA(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(`${Ll}/count_tokens`,{method:"POST",headers:zh(r,n),body:Xh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function vA(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Mn(e,404,"not_found_error",t);return}yA(r).then(n=>{if(t.includes("count_tokens"))return wA(r,e,n);if(t.includes("/v1/messages"))return bA(r,e,n);Mn(e,404,"not_found_error",t)})}function SA(){return Cr&&Ht?Promise.resolve(Ht):new Promise((r,e)=>{let t=lA(vA);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Cr=t,Ht=t.address().port,console.log(`[switcher] wire proxy listening on ${io(Ht)}`),r(Ht)})})}function xA(){try{Cr?.close()}catch{}Cr=null,Ht=null}function kA(r,e){let t=co(r),n=wt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===io(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=lo(r);if(!wt(i)){let a={};for(let c of Yh)a[c]=c in s.env?s.env[c]:null;oo(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=io(e),s.env.ANTHROPIC_AUTH_TOKEN=dA,oo(t,s),Vh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function EA(r,e,t){let n=lo(r),s=wt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},oo(n,s)}function Qh(r){let e=co(r),t=lo(r),n=wt(t),s=wt(e);if(s?.env){let i=n?.snapshot||{};for(let o of Yh){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{Kh(e,{force:!0})}catch{}else oo(e,s)}try{Kh(t,{force:!0})}catch{}}async function AA(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ke()).filter(n=>n.provider==="openrouter"&&!Ml(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:Kc()??void 0;return{hasKey:r,models:e,error:t}}async function TA(){if(Cr&&Me)return{active:!0,managed:!0,model:Me,port:Ht,provider:Wt,routedModel:Dn,caching:Bn,reasoning:jn,externalBaseUrl:null};let r=wt(co(H))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:jn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function Zh(r,e){let t=await SA();return Me=r,Wt=e,kA(H,t),t}async function PA({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(Ml(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,Dl[r]??null),Dn=null,Bn="unknown",EA(H,r,Wt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${U(e)}`}}return{ok:!0}}async function OA({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Nl.length)?{ok:!1,error:`reasoning level must be 0\u2013${Nl.length-1} or null`}:(jn=r,{ok:!0,level:r})}async function _A(){return Qh(H),Me=null,Wt=null,Dn=null,Bn="unknown",{ok:!0}}async function CA({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=H,n=ao(t,".env"),s="";try{s=$l(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Hh(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 GA,
|
|
577
|
+
`:"";Wh(n,i+`OPENROUTER_API_KEY=${e}
|
|
578
|
+
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,Vh(t,[".env"],"# secrets"),{ok:!0}}function RA(){if(!(!Cr&&!Me)){try{Qh(H)}catch{}xA()}}function NA(r,e){return eg.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 IA(r){if(eg.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 $A(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=Il(e?.cache_read_input_tokens)||Il(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 LA({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(Ml(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:Gh(a)}:i),u=await fetch(Ll,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:NA(a.status,x),restriction:IA(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Il(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:m,note:b}=$A(d.ok,p?.usage,l);return y===!0&&l&&(Dl[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 uA,Ll,dA,fA,Yh,pA,Nl,co,lo,io,Ml,Cr,Ht,Me,Wt,Dn,Bn,jn,Dl,Il,Gh,eg,tg=A(()=>{Ar();yt();uA="https://openrouter.ai/api",Ll=`${uA}/v1/messages`,dA="typebulb-proxy-managed",fA="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.",Yh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],pA=5e3,Nl=["low","medium","high"],co=r=>ao(r,".claude","settings.local.json"),lo=r=>ao(r,".claude",".cc-switcher.json"),io=r=>`http://127.0.0.1:${r}`;Ml=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Cr=null,Ht=null,Me=null,Wt=null,Dn=null,Bn="unknown",jn=1,Dl={},Il=r=>typeof r=="number"?r:0,Gh=r=>({order:[r],allow_fallbacks:!1});eg=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=wt(lo(H)),t=e?.active?.model;if(!t)return;let s=(wt(co(H))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Zh(t,e.active.provider??Dl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${io(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var ng={};au(ng,{attach:()=>JA,blockToMarkdown:()=>Ci,breakout:()=>Th,capText:()=>Ce,cleanUserText:()=>mt,clearSwitchModel:()=>_A,composerPasteRead:()=>KA,displayName:()=>MA,downloadSample:()=>jh,firstLineDigest:()=>Ve,gitChangedFiles:()=>fh,gitDiff:()=>ph,info:()=>DA,isHiddenTurn:()=>Rn,launchBulb:()=>Rh,listBreakouts:()=>Ph,listBulbFiles:()=>_h,listMyBulbs:()=>Fh,listSamples:()=>Bh,listSessions:()=>FA,listSwitchModels:()=>AA,logEmbedStatus:()=>jA,openFile:()=>Ah,poll:()=>BA,predictTrustOf:()=>Nh,probeModel:()=>LA,pullRemoteBulb:()=>qh,pushLocalBulb:()=>Jh,readBulbLog:()=>$h,repoRoot:()=>Or,saveOpenRouterKey:()=>CA,searchBulbs:()=>Ch,searchSessions:()=>qA,sessionPeek:()=>UA,setBulbTrust:()=>Ih,setReasoning:()=>OA,setSwitchModel:()=>PA,shutdownSwitcher:()=>RA,stopBreakout:()=>Oh,switchState:()=>TA,toolResultDigest:()=>rl});var rg,MA,DA,BA,jA,FA,qA,UA,JA,KA,sg=A(()=>{El();Ri();Rl();Xi();tg();Ri();Oi();rg=new vr,MA=rg.displayName,{info:DA,poll:BA,logEmbedStatus:jA,listSessions:FA,searchSessions:qA,sessionPeek:UA,attach:JA,composerPasteRead:KA}=no(rg)});import{readFileSync as HA,writeFileSync as WA,mkdirSync as YA}from"fs";import{homedir as VA}from"os";import*as uo from"path";async function ag(){try{let r=await fetch(new URL("/api/tags",og()).toString(),{signal:AbortSignal.timeout(GA)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function cg(r){let e;try{e=HA(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&&!Bl(n)}}}catch{}return{json:void 0,unreadable:!0}}function Bl(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function zA(r){let e=Bl(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 lg(){let{json:r,unreadable:e}=cg(ig());return e?{installed:[],configured:null}:{installed:await ag(),configured:zA(r)}}async function ug(){let r=await ag();return r.length?XA(ig(),r,og()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function XA(r,e,t){let{json:n,unreadable:s}=cg(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...Bl(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{YA(uo.dirname(r),{recursive:!0}),WA(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 GA,ig,og,dg=A(()=>{yt();Ar();GA=1500,ig=()=>uo.join(VA(),".pi","agent","models.json"),og=()=>gr(process.env.OLLAMA_HOST??"http://localhost:11434")});var pg={};au(pg,{attach:()=>iT,breakout:()=>Th,composerFiles:()=>lT,composerNew:()=>cT,composerPaste:()=>fT,composerPasteRead:()=>pT,composerRpc:()=>dT,composerSend:()=>oT,composerStop:()=>aT,composerUiRespond:()=>uT,displayName:()=>QA,downloadSample:()=>jh,gitChangedFiles:()=>fh,gitDiff:()=>ph,info:()=>ZA,launchBulb:()=>Rh,listBreakouts:()=>Ph,listBulbFiles:()=>_h,listMyBulbs:()=>Fh,listSamples:()=>Bh,listSessions:()=>rT,logEmbedStatus:()=>tT,ollamaOffer:()=>lg,ollamaSync:()=>ug,openFile:()=>Ah,poll:()=>eT,predictTrustOf:()=>Nh,pullRemoteBulb:()=>qh,pushLocalBulb:()=>Jh,readBulbLog:()=>$h,repoRoot:()=>Or,searchBulbs:()=>Ch,searchSessions:()=>nT,sessionPeek:()=>sT,setBulbTrust:()=>Ih,shutdownComposer:()=>mT,stopBreakout:()=>Oh});var fg,QA,ZA,eT,tT,rT,nT,sT,iT,oT,aT,cT,lT,uT,dT,fT,pT,mT,mg=A(()=>{El();Sl();Rl();Xi();dg();fg=new Tr,QA=fg.displayName,{info:ZA,poll:eT,logEmbedStatus:tT,listSessions:rT,searchSessions:nT,sessionPeek:sT,attach:iT,composerSend:oT,composerStop:aT,composerNew:cT,composerFiles:lT,composerUiRespond:uT,composerRpc:dT,composerPaste:fT,composerPasteRead:pT,shutdownComposer:mT}=no(fg)});import*as Sy from"fs/promises";import*as Vt from"path";import*as gu from"path";import*as lu from"fs/promises";import{existsSync as Gt,readFileSync as Ky}from"fs";import*as X from"path";import{pathToFileURL as Hy}from"url";import{resolve as Co}from"resolve.exports";import{init as uu,parse as du}from"es-module-lexer";function fu(r,e){let t=X.join(r,"package.json");try{return JSON.parse(Ky(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var _o=["browser","import","default"],cu=["node","import","default"];function pu(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:X.resolve(n)}}async function mu(r){let{name:e,dir:t}=r;if(!Gt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=fu(t,e),s=Wy(n,e),i=X.resolve(t,s);if(!Gt(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=X.dirname(i),a=`/local/${e}/${X.basename(i)}`,c=Yy(n,t);return await Vy(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Wy(r,e){if(r.exports!==void 0){let n;try{n=Co(r,".",{browser:!0,conditions:_o})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${_o.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Ro(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${_o.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 Yy(r,e){if(r.exports!==void 0)try{let n=Co(r,".",{conditions:["types"]}),s=Ro(n);if(s){let i=X.resolve(e,s);if(Gt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=X.resolve(e,t);if(Gt(n))return n}}function Ro(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Vy(r,e,t){await uu;let n=X.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 lu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=du(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=Gy(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 Gy(r,e,t){let n=e.replace(/[?#].*$/,""),s=X.resolve(X.dirname(r),n),i=[s,s+".js",s+".mjs",X.join(s,"index.js"),X.join(s,"index.mjs")];for(let o of i)if(X.normalize(o).startsWith(t)&&Gt(o))return o}function zy(r,e,t){let n=fu(r,e),s;if(n.exports!==void 0)try{s=Ro(Co(n,t,{conditions:cu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${cu.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=X.resolve(r,s);if(!Gt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Hy(i).href}async function hu(r,e){await uu;let t;try{[t]=du(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=zy(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var No=5e3;function yu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||gu.isAbsolute(l)||l.split(/[\\/]/).some(f=>f===""||f===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=No;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=pu(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 bu(){console.log(`
|
|
580
580
|
typebulb - Local bulb runner for Typebulb
|
|
581
581
|
|
|
582
582
|
Usage:
|
|
@@ -607,10 +607,12 @@ Usage:
|
|
|
607
607
|
without watching its terminal.
|
|
608
608
|
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
609
609
|
its tb.onMessage(cb) handlers receive it. The
|
|
610
|
-
client-side twin of 'call';
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
610
|
+
client-side twin of 'call'; msg is JSON-or-
|
|
611
|
+
string, omit it for a bare trigger. No --trust.
|
|
612
|
+
With --wait, a handler's non-undefined return
|
|
613
|
+
prints on stdout (JSON; a bare string raw).
|
|
614
|
+
msg 'tb:snapshot' instead prints the page's
|
|
615
|
+
rendered outline (roles, names, visible text).
|
|
614
616
|
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
615
617
|
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
616
618
|
at that path re-pulls in place). Unlisted and
|
|
@@ -652,10 +654,11 @@ Options:
|
|
|
652
654
|
changed since your last sync (push)
|
|
653
655
|
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
654
656
|
manual (foreground) bulb wait, default 1800 (wait)
|
|
655
|
-
--wait[=ms] For 'send':
|
|
656
|
-
page is
|
|
657
|
-
|
|
658
|
-
after an edit
|
|
657
|
+
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
658
|
+
no page is connected (a hot reload's gap), then
|
|
659
|
+
hold for the handlers' replies (default 5000).
|
|
660
|
+
Use it right after an edit, and for any send
|
|
661
|
+
whose reply you read.
|
|
659
662
|
--no-watch Disable hot reload (watch is on by default)
|
|
660
663
|
-p, --port <port> Use a specific port (default: 3000)
|
|
661
664
|
--open Force-open the external browser (default off
|
|
@@ -723,11 +726,11 @@ Examples:
|
|
|
723
726
|
typebulb my-editor.bulb.md
|
|
724
727
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
725
728
|
typebulb .
|
|
726
|
-
`)}gn();import*as
|
|
729
|
+
`)}gn();import*as pt from"fs/promises";import*as ie from"path";import{pathToFileURL as Dk}from"url";import{transform as Dx}from"sucrase";function Ec(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Dx(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Qs();function Kx(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
727
730
|
`)[0]}`).join(`
|
|
728
|
-
`)}function
|
|
729
|
-
${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https://data.jsdelivr.com/v1/package/npm/";function Np(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var M=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=cr(t??s.version),this.subpath=cr(n??s.subpath)}static parse(e){let t=Np(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Ip(t[1]??""),a=cr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Ip(t[0]),o=cr(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=Np(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:cr(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://")}},cr=r=>r&&r.length?r:void 0,Ip=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),cr(r.slice(e+1))]};async function ce(r){try{return await r()}catch{return}}function Ct(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ac(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 M(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Ct(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(`${Ec}${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=M.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 M(`${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 $p=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!$p(e)),Tc=r=>Object.keys(r?.dependencies||{}).filter(e=>!$p(e)),Hk=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 Hk(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 Tc(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 M(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 Wk,parse as Yk}from"es-module-lexer";var lr=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))M.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{M.isBare(s)&&t.add(s)};try{await Wk;let[s]=Yk(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(M.rootOf(u))),i=[...new Set(s.map(M.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(M.rootOf(p));return new M(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!==M.rootOf(p)).map(M.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===M.rootOf(p))),u=new Set;for(let p of e){let y=M.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),...Tc(e.meta)])].filter(n=>t.has(n))}};lr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Lp,satisfies as Vk,maxSatisfying as Mp,major as Gk,valid as zk}from"semver";var Zs=class{cmp(e,t){return e===t?0:Lp(e,t)?1:Lp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Vk(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=Mp(e,n,{includePrerelease:!1});if(a)return a}return Mp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Gk(e)}isExactVersion(e){return zk(e)!==null}},Rt=new Zs;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()+Qk(n),attempts:n}))}async clearNegative(e){await ce(()=>this.store.delete(e))}};function Qk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Dp(r,e){let t=new wn(r,e),n=new Sn(t),s=new kn(r,t,Rt);return{packageService:new lr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Kp from"fs/promises";import*as Se from"path";import*as ct from"fs/promises";import*as Fe from"path";import*as Fp from"os";import*as Pc from"fs/promises";import*as Bp from"crypto";function ve(r){return Bp.createHash("sha1").update(r).digest("hex")}async function je(r){try{return JSON.parse(await Pc.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await Pc.readFile(r,"utf8")}catch{return}}var jp=1,at=Fe.join(Fp.homedir(),".typebulb","cache"),xn=Fe.join(at,"packages"),En=Fe.join(at,"proxy"),ti=Fe.join(at,"dts"),Xk=Fe.join(at,"emit"),Oc;function H(){return Oc||(Oc=Zk()),Oc}function ri(r,e){return Fe.join(Xk,ve(r),e)}async function Zk(){await ct.mkdir(at,{recursive:!0});let r=Fe.join(at,"version.json");if((await je(r))?.version===jp)return;let t=await ct.readdir(at).catch(()=>[]);await Promise.all(t.map(n=>ct.rm(Fe.join(at,n),{recursive:!0,force:!0}))),await ct.writeFile(r,JSON.stringify({version:jp})+`
|
|
730
|
-
`,"utf8")}import*as
|
|
731
|
+
`)}function Np(r,e){let t=yn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
732
|
+
${Kx(t)}`)}var ct="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ac="https://data.jsdelivr.com/v1/package/npm/";function Ip(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=cr(t??s.version),this.subpath=cr(n??s.subpath)}static parse(e){let t=Ip(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=$p(t[1]??""),a=cr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=$p(t[0]),o=cr(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(ct).host,s=new URL(bn).host;if(t.host===n){let i=Ip(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:cr(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://")}},cr=r=>r&&r.length?r:void 0,$p=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),cr(r.slice(e+1))]};async function le(r){try{return await r()}catch{return}}function Ct(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Tc(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(Ct(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(",")),`${ct}/${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),`${ct}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await le(()=>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 le(()=>this.http.getJson(`${Ac}${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 le(()=>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 Lp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Lp(e)),Pc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Lp(e)),Hx=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 Hx(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 Pc(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 xn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await le(()=>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 le(()=>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 le(()=>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 le(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Wx,parse as Yx}from"es-module-lexer";var lr=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 Wx;let[s]=Yx(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:x,isSharedDep:k}=n.get(y),T=a.has(y),P=p!==y,O=!(b||k)&&(T||!x),N=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let S=h?[...N,y]:N.length?N: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}/`,`${ct}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...Pc(e.meta)])].filter(n=>t.has(n))}};lr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Mp,satisfies as Vx,maxSatisfying as Dp,major as Gx,valid as zx}from"semver";var Zs=class{cmp(e,t){return e===t?0:Mp(e,t)?1:Mp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Vx(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=Dp(e,n,{includePrerelease:!1});if(a)return a}return Dp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Gx(e)}isExactVersion(e){return zx(e)!==null}},Rt=new Zs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await le(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await le(()=>this.store.get(e)))?.attempts||0)+1;await le(()=>this.store.set(e,{until:Date.now()+Xx(n),attempts:n}))}async clearNegative(e){await le(()=>this.store.delete(e))}};function Xx(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Bp(r,e){let t=new wn(r,e),n=new Sn(t),s=new xn(r,t,Rt);return{packageService:new lr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Hp from"fs/promises";import*as Se from"path";import*as ut from"fs/promises";import*as Je from"path";import*as qp from"os";import*as Oc from"fs/promises";import*as jp from"crypto";function ve(r){return jp.createHash("sha1").update(r).digest("hex")}async function Ue(r){try{return JSON.parse(await Oc.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await Oc.readFile(r,"utf8")}catch{return}}var Fp=1,lt=Je.join(qp.homedir(),".typebulb","cache"),kn=Je.join(lt,"packages"),En=Je.join(lt,"proxy"),ti=Je.join(lt,"dts"),Qx=Je.join(lt,"emit"),_c;function V(){return _c||(_c=Zx()),_c}function ri(r,e){return Je.join(Qx,ve(r),e)}async function Zx(){await ut.mkdir(lt,{recursive:!0});let r=Je.join(lt,"version.json");if((await Ue(r))?.version===Fp)return;let t=await ut.readdir(lt).catch(()=>[]);await Promise.all(t.map(n=>ut.rm(Je.join(lt,n),{recursive:!0,force:!0}))),await ut.writeFile(r,JSON.stringify({version:Fp})+`
|
|
733
|
+
`,"utf8")}import*as dt from"fs/promises";import*as Up from"path";async function me(r,e){await dt.mkdir(Up.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await dt.writeFile(t,e,"utf8"),await dt.rename(t,r).catch(async n=>{throw await dt.rm(t,{force:!0}).catch(()=>{}),n})}var ur=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Ue(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 Cc=Se.join(kn,"indexes"),Jp=Se.join(kn,"pinned"),ek=Se.join(kn,"meta"),tk=Se.join(kn,"negative.json"),si=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Nt(new ur(tk));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await V();let s=await ei(Se.join(Jp,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 V(),await me(Se.join(Jp,ve(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await V();let t=await Ue(Se.join(Cc,ni(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 V(),await me(Se.join(Cc,ni(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Hp.rm(Se.join(Cc,ni(e)+".json"),{force:!0})}async isNegative(e){return await V(),this.negativeCache.isNegative(e)}async recordNegative(e){await V(),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 V();let s=await Ue(Kp(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 V(),await me(Kp(e,t),JSON.stringify(o))}};function Kp(r,e){return Se.join(ek,ni(r),encodeURIComponent(e)+".json")}function ni(r){return r.replace(/\//g,"__")}var Wp={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 rk=new si,{packageService:ii,versionResolver:Yp,cdnClient:Vp,peerResolver:zC}=Bp(rk,Wp);var Gp=`
|
|
731
734
|
(() => {
|
|
732
735
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
733
736
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1097,7 +1100,8 @@ ${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https:
|
|
|
1097
1100
|
|
|
1098
1101
|
// Receive a value pushed from the terminal via \`typebulb send\` (data-in, the dual of the
|
|
1099
1102
|
// ungated tb.server.log). Returns an unsubscribe fn. Inert when embedded \u2014 no server, so no
|
|
1100
|
-
// sender; the handler is registered but never fires (cf. tb.models returning []).
|
|
1103
|
+
// sender; the handler is registered but never fires (cf. tb.models returning []). A handler's
|
|
1104
|
+
// non-undefined return (awaited) becomes the reply \`send --wait\` prints (TB-Interrogation.md).
|
|
1101
1105
|
onMessage: (handler) => {
|
|
1102
1106
|
if (typeof handler === 'function') messageHandlers.add(handler);
|
|
1103
1107
|
return () => messageHandlers.delete(handler);
|
|
@@ -1113,6 +1117,60 @@ ${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https:
|
|
|
1113
1117
|
set theme(v) { if (window.__tbTheme) window.__tbTheme.set(v); }
|
|
1114
1118
|
});
|
|
1115
1119
|
|
|
1120
|
+
// tb:snapshot \u2014 the page serializes its own accessibility outline (roles, names, visible text;
|
|
1121
|
+
// the YAML-not-pixels shape) as the reply to \`typebulb send <file> tb:snapshot\`
|
|
1122
|
+
// (TB-Interrogation.md). Heuristic by design: explicit role attr, a small
|
|
1123
|
+
// implicit-role map, aria-label/alt/value then visible text for names \u2014 enough to catch
|
|
1124
|
+
// text/structure divergence, which is what an agent can judge without pixels.
|
|
1125
|
+
const IMPLICIT_ROLES = { BUTTON: 'button', SELECT: 'combobox', TEXTAREA: 'textbox', OPTION: 'option', IMG: 'img', NAV: 'navigation', MAIN: 'main', HEADER: 'banner', FOOTER: 'contentinfo', ASIDE: 'complementary', FORM: 'form', DIALOG: 'dialog', TABLE: 'table', TR: 'row', TH: 'columnheader', TD: 'cell', UL: 'list', OL: 'list', LI: 'listitem', LABEL: 'label', P: 'paragraph', PROGRESS: 'progressbar', SUMMARY: 'button', FIGURE: 'figure', BLOCKQUOTE: 'blockquote', HR: 'separator' };
|
|
1126
|
+
const INPUT_ROLES = { checkbox: 'checkbox', radio: 'radio', range: 'slider', number: 'spinbutton', search: 'searchbox', button: 'button', submit: 'button', reset: 'button', hidden: '' };
|
|
1127
|
+
const snapshot = () => {
|
|
1128
|
+
const MAX_LINES = 400;
|
|
1129
|
+
const squash = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
1130
|
+
const clip = (s) => (s.length > 200 ? s.slice(0, 200) + '\u2026' : s);
|
|
1131
|
+
const roleOf = (el) => {
|
|
1132
|
+
const explicit = el.getAttribute('role');
|
|
1133
|
+
if (explicit) return explicit;
|
|
1134
|
+
const t = el.tagName;
|
|
1135
|
+
if (t === 'A') return el.hasAttribute('href') ? 'link' : '';
|
|
1136
|
+
if (t === 'INPUT') { const r = INPUT_ROLES[(el.getAttribute('type') || 'text').toLowerCase()]; return r === undefined ? 'textbox' : r; }
|
|
1137
|
+
if (/^H[1-6]$/.test(t)) return 'heading';
|
|
1138
|
+
return IMPLICIT_ROLES[t] || '';
|
|
1139
|
+
};
|
|
1140
|
+
const hiddenEl = (el) => {
|
|
1141
|
+
if (el.hidden || el.getAttribute('aria-hidden') === 'true') return true;
|
|
1142
|
+
const cs = getComputedStyle(el);
|
|
1143
|
+
return cs.display === 'none' || cs.visibility === 'hidden';
|
|
1144
|
+
};
|
|
1145
|
+
const lines = [];
|
|
1146
|
+
const walk = (node, depth) => {
|
|
1147
|
+
for (let ch = node.firstChild; ch && lines.length <= MAX_LINES; ch = ch.nextSibling) {
|
|
1148
|
+
if (ch.nodeType === 3) {
|
|
1149
|
+
const t = squash(ch.nodeValue);
|
|
1150
|
+
if (t) lines.push(' '.repeat(depth) + '- text: ' + clip(t));
|
|
1151
|
+
continue;
|
|
1152
|
+
}
|
|
1153
|
+
if (ch.nodeType !== 1) continue;
|
|
1154
|
+
const tag = ch.tagName;
|
|
1155
|
+
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'TEMPLATE' || tag === 'NOSCRIPT' || tag === 'LINK' || tag === 'META') continue;
|
|
1156
|
+
if (hiddenEl(ch)) continue;
|
|
1157
|
+
const role = roleOf(ch);
|
|
1158
|
+
if (!role) { walk(ch, depth); continue; } // structural (div/span/\u2026): descend transparently
|
|
1159
|
+
const attr = (n) => squash(ch.getAttribute(n) || '');
|
|
1160
|
+
const text = squash(ch.textContent);
|
|
1161
|
+
const name = attr('aria-label') || (tag === 'IMG' ? attr('alt') : '') || (typeof ch.value === 'string' ? squash(ch.value) || attr('placeholder') : '') || text;
|
|
1162
|
+
let line = role + (name ? ' "' + clip(name) + '"' : '');
|
|
1163
|
+
const lv = role === 'heading' ? (attr('aria-level') || (/^H[1-6]$/.test(tag) ? tag.charAt(1) : '')) : '';
|
|
1164
|
+
if (lv) line += ' [level=' + lv + ']';
|
|
1165
|
+
lines.push(' '.repeat(depth) + '- ' + line);
|
|
1166
|
+
if (!(name && name === text)) walk(ch, depth + 1); // subtree \u2261 name \u21D2 the one line says it all
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
walk(document.body, 0);
|
|
1170
|
+
if (lines.length > MAX_LINES) { lines.length = MAX_LINES; lines.push('- \u2026 (truncated)'); }
|
|
1171
|
+
return lines.length ? lines.join('\\n') : '(empty page)';
|
|
1172
|
+
};
|
|
1173
|
+
|
|
1116
1174
|
// Events channel (dev server only): 'reload' drives hot reload (only emitted when watching),
|
|
1117
1175
|
// 'message' delivers \`typebulb send\` pushes to tb.onMessage. Connect for a CLI-served page (http
|
|
1118
1176
|
// origin, not an embed); a srcdoc embed or a file:// static export has no server, so onMessage just
|
|
@@ -1123,11 +1181,37 @@ ${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https:
|
|
|
1123
1181
|
console.log('[typebulb] Reloading...');
|
|
1124
1182
|
window.location.reload();
|
|
1125
1183
|
});
|
|
1126
|
-
es.addEventListener('message', (e) => {
|
|
1127
|
-
// Wire payload
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1184
|
+
es.addEventListener('message', async (e) => {
|
|
1185
|
+
// Wire envelope { id?, payload } (JSON \u2014 SSE-line-safe). tb:* payloads are the shim's reserved
|
|
1186
|
+
// namespace (TB-Interrogation.md): answered by a built-in handler, never delivered to
|
|
1187
|
+
// tb.onMessage. Each settled non-undefined return is a reply candidate \u2014 the CLI enforces the
|
|
1188
|
+
// one-reply rule, the shim just reports what it collected.
|
|
1189
|
+
let env;
|
|
1190
|
+
try { env = JSON.parse(e.data) || {}; } catch { return; }
|
|
1191
|
+
const errText = (err) => String((err && err.message) || err);
|
|
1192
|
+
const results = []; const errors = [];
|
|
1193
|
+
const keep = (v) => {
|
|
1194
|
+
try {
|
|
1195
|
+
const enc = JSON.stringify(v);
|
|
1196
|
+
if (enc === undefined) throw new Error('unsupported value');
|
|
1197
|
+
results.push(enc);
|
|
1198
|
+
} catch (err) { errors.push('reply is not JSON-serializable: ' + errText(err)); }
|
|
1199
|
+
};
|
|
1200
|
+
const reservedCall = async () => {
|
|
1201
|
+
if (env.payload === 'tb:snapshot') return snapshot();
|
|
1202
|
+
throw new Error('unknown reserved message: ' + env.payload);
|
|
1203
|
+
};
|
|
1204
|
+
const value = parseMsg(env.payload);
|
|
1205
|
+
const calls = typeof env.payload === 'string' && env.payload.indexOf('tb:') === 0
|
|
1206
|
+
? [reservedCall]
|
|
1207
|
+
: Array.from(messageHandlers, (h) => async () => h(value));
|
|
1208
|
+
for (const s of await Promise.allSettled(calls.map((f) => f()))) {
|
|
1209
|
+
if (s.status === 'rejected') { console.error(s.reason); errors.push(errText(s.reason)); }
|
|
1210
|
+
else if (s.value !== undefined) keep(s.value);
|
|
1211
|
+
}
|
|
1212
|
+
if (env.id !== undefined) {
|
|
1213
|
+
try { fetch('/__send-reply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: env.id, results, errors }) }); } catch {}
|
|
1214
|
+
}
|
|
1131
1215
|
});
|
|
1132
1216
|
es.onerror = () => {
|
|
1133
1217
|
// Server closed, stop trying
|
|
@@ -1174,8 +1258,8 @@ ${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https:
|
|
|
1174
1258
|
});
|
|
1175
1259
|
} catch (e) {}
|
|
1176
1260
|
})();
|
|
1177
|
-
</script>`}function
|
|
1178
|
-
html, body { height: 100%; }`,p={imports:
|
|
1261
|
+
</script>`}function zp(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?"":`
|
|
1262
|
+
html, body { height: 100%; }`,p={imports:sk(a.imports)};return`<!DOCTYPE html>
|
|
1179
1263
|
<html>
|
|
1180
1264
|
<head>
|
|
1181
1265
|
<meta charset="utf-8">
|
|
@@ -1200,10 +1284,10 @@ ${o?`<script>window.__TB_INSIGHT__ = ${It(JSON.stringify(o))};</script>`:""}
|
|
|
1200
1284
|
${f?`<script>window.__TB_DIR__ = ${It(JSON.stringify(f))};</script>`:""}
|
|
1201
1285
|
|
|
1202
1286
|
<script>
|
|
1203
|
-
${
|
|
1287
|
+
${Gp}
|
|
1204
1288
|
</script>
|
|
1205
1289
|
|
|
1206
|
-
${
|
|
1290
|
+
${nk}
|
|
1207
1291
|
|
|
1208
1292
|
<script type="module">
|
|
1209
1293
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
@@ -1211,7 +1295,7 @@ await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when presen
|
|
|
1211
1295
|
${It(t)}
|
|
1212
1296
|
</script>
|
|
1213
1297
|
</body>
|
|
1214
|
-
</html>`}var
|
|
1298
|
+
</html>`}var nk=`<script>
|
|
1215
1299
|
(function () {
|
|
1216
1300
|
var framed = window.parent !== window;
|
|
1217
1301
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1307,8 +1391,8 @@ ${It(t)}
|
|
|
1307
1391
|
}
|
|
1308
1392
|
});
|
|
1309
1393
|
})();
|
|
1310
|
-
</script>`;function
|
|
1311
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await ui.mkdir(e,{recursive:!0});let a=li.join(e,"package.json");
|
|
1394
|
+
</script>`;function sk(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as ui from"fs/promises";import*as li from"path";import{existsSync as Xp,readFileSync as ik}from"fs";import{execFile as ok}from"child_process";import{promisify as ak}from"util";import{satisfies as ck}from"semver";var lk=ak(ok),uk=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function di(r,e,t,n){let i=r.map(l=>dk(l,t)).filter(l=>!fk(l,e));if(i.length===0)return;let o=i.filter(l=>!uk.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1395
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await ui.mkdir(e,{recursive:!0});let a=li.join(e,"package.json");Xp(a)||await ui.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 lk("npm",["install",...c,...i],{cwd:e,shell:!0})}function dk(r,e){if(!e||D.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function fk(r,e){let{name:t,version:n}=D.parse(r),s=li.join(e,"node_modules",t);if(!Xp(s))return!1;if(!n)return!0;try{let i=JSON.parse(ik(li.join(s,"package.json"),"utf-8")).version;return ck(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]}mr();Si();Dt();import*as yr from"fs/promises";import*as We from"path";function xi(r,e,t=e){let n=We.resolve(e,r),s=We.normalize(t),i=We.normalize(n);if(i!==s&&!i.startsWith(s+We.sep))throw new Error("Path traversal detected - access denied");return n}async function On(r,e,t){return yr.readFile(xi(r,e,t))}async function ki(r,e,t,n){let s=xi(r,t,n);await yr.mkdir(We.dirname(s),{recursive:!0}),await yr.writeFile(s,typeof e=="string"?e:Buffer.from(e))}async function cm(r){let e=He(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await ft(e,r);if(!t.ok){let n=await pr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function Lk(r){let{response:e,protocol:t}=await cm(r);return{text:await Lt(e,t)}}async function*Mk(r){let{response:e,protocol:t}=await cm(r);yield*Mt(e,t)}function lm(r,e=process.cwd()){let t=Object.assign(Lk,{stream:Mk}),n={read:async s=>{let i=await On(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await On(s,r,e)),write:async(s,i)=>(await ki(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>Ke(),hasOwnKeys:vi,mode:"local"})}async function um(r){let t=(await pt.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?ie.join(r,t):null}function Ei(r,e){let t=ie.resolve(r),n=ie.join(ie.dirname(t),ie.basename(t).replace(/\.bulb\.md$/,""));return e?ie.join(n,e):n}async function ke(r){let e=await pt.readFile(r,"utf-8"),t=fe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=ar(t);return{bulb:n,config:Lr(n.config),warnings:ku(e)}}function Wc(r){let e=ie.basename(r).replace(/\.bulb\.md$/i,"");return ie.join(ie.dirname(r),".typebulb",`${e}.server.mjs`)}async function _n(r,e,t,n,s){let i=Ec(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await hu(o,t));let a=ie.join(ie.dirname(e),".typebulb");await pt.mkdir(a,{recursive:!0});let c=fi(o);c.length>0&&await di(c,a,n);let l=Wc(e);return await pt.writeFile(l,o,"utf-8"),lm(Ei(e,s)),await import(`${Dk(l).href}?t=${Date.now()}`)}async function Yc(r,e,t,n,s){let{bulb:i,config:o}=await ke(r),a=zs(i.data);Np(i.code,o.dependencies??{});let c=Ec(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await ii.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=zp({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:Ei(r,s),watch:e}),u=null;return i.server&&t&&(u=await _n(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}gn();Cn();Ri();Sl();var fo={claude:{adapter:()=>new vr,server:()=>Promise.resolve().then(()=>(sg(),ng))},pi:{adapter:()=>new Tr,server:()=>Promise.resolve().then(()=>(mg(),pg))}};function hg(r){return r in fo}function Rr(){return Object.keys(fo)}function gg(){return Object.fromEntries(Object.entries(fo).map(([r,e])=>[r,e.adapter]))}function yg(r){return fo[r].server()}import*as St from"path";import{spawn as jT,execSync as FT}from"child_process";import{createRequire as qT}from"module";import{existsSync as UT}from"fs";import*as oe from"fs/promises";import*as ne from"path";var jl=[{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"}],Fl=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function ql(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 hT=`
|
|
1312
1396
|
/**
|
|
1313
1397
|
* Get raw data chunk from the Data tab.
|
|
1314
1398
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1328,7 +1412,7 @@ ${It(t)}
|
|
|
1328
1412
|
*
|
|
1329
1413
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1330
1414
|
*/
|
|
1331
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1415
|
+
insight<T = unknown>(): T | undefined;`,bg=`options: {
|
|
1332
1416
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1333
1417
|
system?: string;
|
|
1334
1418
|
/** 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. */
|
|
@@ -1339,12 +1423,12 @@ ${It(t)}
|
|
|
1339
1423
|
webSearch?: boolean;
|
|
1340
1424
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1341
1425
|
signal?: AbortSignal;
|
|
1342
|
-
}`,
|
|
1426
|
+
}`,wg=`
|
|
1343
1427
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1344
1428
|
type AiChunk =
|
|
1345
1429
|
| { kind: "text"; text: string }
|
|
1346
1430
|
| { kind: "reasoning"; text: string };
|
|
1347
|
-
`,
|
|
1431
|
+
`,vg=`
|
|
1348
1432
|
/**
|
|
1349
1433
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1350
1434
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1353,7 +1437,7 @@ type AiChunk =
|
|
|
1353
1437
|
* @throws On rate limit, network error, or provider error
|
|
1354
1438
|
*/
|
|
1355
1439
|
ai: {
|
|
1356
|
-
(${
|
|
1440
|
+
(${bg}): Promise<{ text: string }>;
|
|
1357
1441
|
/**
|
|
1358
1442
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1359
1443
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1367,8 +1451,8 @@ type AiChunk =
|
|
|
1367
1451
|
* if (c.kind === "text") answer += c.text;
|
|
1368
1452
|
* }
|
|
1369
1453
|
*/
|
|
1370
|
-
stream(${
|
|
1371
|
-
};`,
|
|
1454
|
+
stream(${bg}): AsyncIterable<AiChunk>;
|
|
1455
|
+
};`,Sg=`
|
|
1372
1456
|
/**
|
|
1373
1457
|
* Returns AI models available to the current user.
|
|
1374
1458
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1392,7 +1476,7 @@ type AiChunk =
|
|
|
1392
1476
|
* making many AI calls should check this and show a "use your own keys"
|
|
1393
1477
|
* notice instead of running.
|
|
1394
1478
|
*/
|
|
1395
|
-
hasOwnKeys(): Promise<boolean>;`,yT="\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;",
|
|
1479
|
+
hasOwnKeys(): Promise<boolean>;`,yT="\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;",xg=`
|
|
1396
1480
|
/**
|
|
1397
1481
|
* The mode this bulb is running in.
|
|
1398
1482
|
*
|
|
@@ -1419,7 +1503,7 @@ type AiChunk =
|
|
|
1419
1503
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1420
1504
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1421
1505
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1422
|
-
};`,
|
|
1506
|
+
};`,Eg=`
|
|
1423
1507
|
/**
|
|
1424
1508
|
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1425
1509
|
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
@@ -1495,54 +1579,39 @@ type AiChunk =
|
|
|
1495
1579
|
*
|
|
1496
1580
|
* @returns The full canonical URL
|
|
1497
1581
|
*/
|
|
1498
|
-
url(): Promise<string>;`,wT
|
|
1499
|
-
/**
|
|
1500
|
-
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
1501
|
-
*
|
|
1502
|
-
* The dual of \`tb.server.log\` (data out): a value sent *in* from the CLI, no \`--trust\` required.
|
|
1503
|
-
* Use it to start expensive work on demand instead of on load \u2014 e.g. \`tb.onMessage(() => start())\`
|
|
1504
|
-
* \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.
|
|
1505
|
-
*
|
|
1506
|
-
* The message is the JSON-parsed value of what \`send\` was given (or the raw string if it isn't
|
|
1507
|
-
* JSON; \`undefined\` for a bare \`typebulb send <file>\`). Returns an unsubscribe function. Inert in
|
|
1508
|
-
* an embedded bulb (no sender) \u2014 the handler is registered but never fires.
|
|
1509
|
-
*
|
|
1510
|
-
* @param handler - Called with each pushed message.
|
|
1511
|
-
* @returns An unsubscribe function.
|
|
1512
|
-
*/
|
|
1513
|
-
onMessage(handler: (message: any) => void): () => void;`,vT="\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>>;",ql=`${bg}
|
|
1582
|
+
url(): Promise<string>;`,wT="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.server.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",vT="\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>>;",Ul=`${wg}
|
|
1514
1583
|
/**
|
|
1515
1584
|
* Typebulb utilities namespace.
|
|
1516
1585
|
* Type \`tb.\` to discover available helpers.
|
|
1517
1586
|
*/
|
|
1518
|
-
declare const tb: {${hT}${bT}${gT}${vT}${wT}${
|
|
1587
|
+
declare const tb: {${hT}${bT}${gT}${vT}${wT}${vg}${kg}${Eg}${Sg}${yT}${xg}
|
|
1519
1588
|
};
|
|
1520
|
-
`,
|
|
1589
|
+
`,Jl=`${wg}
|
|
1521
1590
|
/**
|
|
1522
1591
|
* Typebulb utilities namespace (server-side).
|
|
1523
1592
|
* Type \`tb.\` to discover available helpers.
|
|
1524
1593
|
*/
|
|
1525
|
-
declare const tb: {${
|
|
1594
|
+
declare const tb: {${vg}${kg}${Eg}${Sg}${xg}
|
|
1526
1595
|
};
|
|
1527
|
-
`;import ET from"p-limit";import{resolve as
|
|
1596
|
+
`;import ET from"p-limit";import{resolve as Tg}from"resolve.exports";var Ge={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Fn=["index.d.ts","index.d.mts"],Kl=/\.d\.(ts|mts|cts)$/i;function po(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Ag(r){return[`${r}.d.ts`,`${r}.d.mts`]}function vt(r){if(!r||r==="./"||r==="/")return[...Fn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Ag(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Ag(`${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(ST(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function ST(r){return r===408||r===429||r>=500&&r<600}var mo=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||po(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=Ct(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...Fn],t);if(!Kl.test(o)){let a=await this.tryUntilSuccess(vt(o),t);if(a)return a}return t(o)}let s=vt(e.path),i=n?.subpath?[...s,...Fn]:[...Fn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Kl.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Tg(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Tg(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=Tc(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(vt(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=Ct(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 xT}from"fflate";var ho=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=xT(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 go=class{constructor(e,t,n=new ho){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=vt(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 yo=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(`
|
|
1528
1597
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1529
|
-
`),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
|
|
1530
|
-
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],
|
|
1531
|
-
`,"utf8"),await
|
|
1532
|
-
`,"utf8"),{dir:e}}function DT(r){let e={...
|
|
1533
|
-
`))console.log(`${e} ${n}`);return r.length>0}function JT(r,e){return new Promise(t=>{let n=jT(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 KT=qT(import.meta.url);function HT(r){let e=n=>{try{let s=KT.resolve("typescript/package.json",{paths:n}),i=
|
|
1598
|
+
`),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 Pg="file:///node_modules",bo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Pg}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Ct(t);return`${Pg}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as kT}from"lru-cache";function Og(r){let e=new kT({ttl:Ge.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 qn=class{constructor(e){this.inFlight=new Map,this.scanner=new yo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Og(e.cache),this.typescriptProvider=new mo(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new go(e.cdnClient,e.cache),this.virtualFs=new bo}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>Ge.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ge.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=po(c)?[c]:vt(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,Ge.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=ET(Ge.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ge.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,Ge.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(k=>k.content).join(`
|
|
1599
|
+
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],x=b.some(k=>this.ambientlyDeclares(i,k));return x?this.markFileAmbient(d,f):p.push(...b.map(k=>({module:k,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};import*as Ir from"path";var AT=Ir.join(ti,"pkg"),TT=Ir.join(ti,"files"),PT=Ir.join(ti,"negative.json"),vo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Nt(new ur(PT));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await V();let t=await Ue(_g(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 wo(async()=>{await V(),await me(_g(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await V();let t=await ei(Cg(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await wo(async()=>{await V(),await me(Cg(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await wo(async()=>{await V(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return wo(()=>this.negativeCache.clearNegative(e))}};async function wo(r){try{await r()}catch{}}function _g(r){return Ir.join(AT,ve(r)+".json")}function Cg(r){return Ir.join(TT,ve(r)+".txt")}var Hl;function OT(){return Hl||(Hl=new qn({cache:new vo,cdnClient:Vp,packageService:ii,versionResolver:Yp})),Hl}var Rg="file:///node_modules/";async function Ng(r){let e=ri(r.emitKey,"typecheck");await V(),await oe.rm(e,{recursive:!0,force:!0}),await oe.mkdir(e,{recursive:!0});let t=NT(r.jsxImportSource,r.dependencies),n=await OT().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=So(u.path);if(!d||o.has(d))continue;o.add(d);let p=ne.join(e,"node_modules",d);await oe.mkdir(ne.dirname(p),{recursive:!0}),await oe.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=So(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=So(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=So(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await IT(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=_T(r.jsxImportSource,a,[...c]);return await oe.writeFile(ne.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1600
|
+
`,"utf8"),await oe.writeFile(ne.join(e,"code.tsx"),r.code,"utf8"),await oe.writeFile(ne.join(e,"tb.d.ts"),Ul,"utf8"),{dir:e}}var Wl={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function _T(r,e,t=[]){return{compilerOptions:{...Wl,lib:CT([...jl,...Fl]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function CT(r){return ql(r).map(e=>RT(e.name))}function RT(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 NT(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function So(r){if(!r.startsWith(Rg))return;let e=r.slice(Rg.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function IT(r,e){if(!r.typesAbs)return;let t=ne.dirname(r.typesAbs),n=ne.join(e,"node_modules",r.name);for(let s of await $T(t)){let i=ne.join(n,ne.relative(t,s));await oe.mkdir(ne.dirname(i),{recursive:!0}),await oe.copyFile(s,i)}return ne.basename(r.typesAbs)}async function $T(r){let e=[];async function t(n){let s=await oe.readdir(n,{withFileTypes:!0});for(let i of s){let o=ne.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 ze from"path";import{existsSync as LT}from"fs";var MT="^22";async function Ig(r){let e=ri(r.emitKey,"typecheck-server");await V(),await ye.rm(e,{recursive:!0,force:!0}),await ye.mkdir(e,{recursive:!0});let t=ze.join(r.bulbDir,".typebulb"),n=fi(r.server).filter(o=>o!==r.local?.name);await di([`@types/node@${MT}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=ze.join(t,"node_modules"),i=ze.join(e,"node_modules");return await BT(s,i),await ye.writeFile(ze.join(e,"server.ts"),r.server,"utf8"),await ye.writeFile(ze.join(e,"tb.d.ts"),Jl,"utf8"),await ye.writeFile(ze.join(e,"tsconfig.json"),JSON.stringify(DT(r.local),null,2)+`
|
|
1601
|
+
`,"utf8"),{dir:e}}function DT(r){let e={...Wl,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(ze.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 BT(r,e){if(!LT(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 Lg(r,e){let{bulb:t,config:n,warnings:s}=await ke(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=HT([process.cwd(),St.dirname(r)]);if(!o){let l=St.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 Ng({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 Ig({server:t.server,bulbDir:St.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 JT(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(`
|
|
1602
|
+
`))console.log(`${e} ${n}`);return r.length>0}function JT(r,e){return new Promise(t=>{let n=jT(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 KT=qT(import.meta.url);function HT(r){let e=n=>{try{let s=KT.resolve("typescript/package.json",{paths:n}),i=St.join(St.dirname(s),"lib","tsc.js");return UT(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=FT("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Bi();Cn();async function Mg(r,e){let{bulb:t}=await ke(r),n=xr(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 Un from"path";async function Dg(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=zc();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=Un.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),br(t,e),console.log(e?`Trusted ${Un.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Un.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Ne();import*as qg from"readline";var Jn=gg();function Bg(){for(let r of Object.values(Jn))try{r().ensureHarnessSupport()}catch{}}function Kn(){for(let r of Object.keys(Jn))try{if(Jn[r]().detectsSelf())return r}catch{}}function jg(r){let e=Rr(),t=new Map(e.filter(i=>Jn[i]).map(i=>[i,Jn[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)))}}ji();function Yl(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 Ug(r){let e=jg(process.cwd());if("ambiguous"in e){let t=await WT(r,e.ambiguous);return t?Fg(r,t):YT(r,e.ambiguous)}return Fg(r,e.name)}async function Fg(r,e){let t,n;try{t=await _m(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Yl(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(kr())}`,` ${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(`
|
|
1534
1603
|
`)+`
|
|
1535
|
-
`)}async function WT(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=
|
|
1604
|
+
`)}async function WT(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Yl(!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(`
|
|
1536
1605
|
`)+`
|
|
1537
|
-
`);let i=
|
|
1606
|
+
`);let i=qg.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 YT(r,e){let{lit:t,brand:n}=Yl(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(`
|
|
1538
1607
|
`)+`
|
|
1539
|
-
`)}
|
|
1540
|
-
`+e)}function
|
|
1608
|
+
`)}gt();Dt();async function Jg(r){ge(r);let e=await Ke();if(e.length>0){console.log(am(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Hc()){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(hr))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.")}ji();import*as Kg from"fs/promises";async function Hg(r){let e=qt(),t;try{t=await Kg.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Bm(t,r))}Ti();import*as Wg from"path";Ne();function VT(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&&re(o.cwd)===re(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>re(i.file)===re(e))}var Hn=r=>r.agent??Wg.basename(r.file);function Yg(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.dir?` --dir ${t.dir}`:""} ${t.file}`)}function Vl(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Yg(r,t=>console.log(t)),console.log(`
|
|
1609
|
+
`+e)}function Gl(r,e,t,n,s){let i=VT(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>\`):`),Yg(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Vg(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Vl(await z(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Gl(await z(),r,"logs",process.cwd(),Kn());if(e.clear){km(t.pid),console.log(`Cleared log for ${Hn(t)} (pid ${t.pid}).`);return}let n=Re(t.pid),s=n.text;if(e.run!==void 0&&(s=Em(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(`
|
|
1541
1610
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1542
1611
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1543
1612
|
`)&&process.stdout.write(`
|
|
1544
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=
|
|
1545
|
-
`);m=
|
|
1613
|
+
`),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 GT=r=>new Promise(e=>setTimeout(e,r));async function Gg(r,e){if(!r){Vl(await z(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Gl(await z(),r,"wait",process.cwd(),Kn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Re(t.pid).offset,l=al(t.pid,a)??(a?al(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 x=Re(t.pid,f);if(f=x.offset,x.text){m+=x.text;let k=m.split(`
|
|
1614
|
+
`);m=k.pop()??"";for(let T of k)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 ${Hn(t)} within ${o}s`),b=2;break}if(!ll(t.pid)){y||(console.error(`server ${Hn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await GT(400)}Ii(t.pid,f,a),process.exit(b)}async function zg(r){if(!r){Vl(await z(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Gl(await z(),r,"stop",process.cwd(),Kn());await jt(e.pid),console.log(`Stopped ${Hn(e)} (pid ${e.pid}, ${e.url}).`)}async function Xg(r){let e=process.cwd(),t=r==="agent"?Kn():void 0,n=r==="global"?await z():r==="bulbs"?await z(e):(await z()).filter(i=>i.agent!=null&&i.cwd!=null&&re(i.cwd)===re(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} ${Hn(i)}`)}Ne();import*as Qg from"path";async function Zg(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=No);let s=Qg.resolve(r),i=Sr(await z(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await fetch(`${i.url}/__send${d>0?`?reply=${d}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Ki();wl();gt();import*as $r from"fs/promises";import*as cy from"path";import{EventEmitter as ay}from"events";qe();Bi();import dP from"open";mr();qe();import{Hono as tP}from"hono";import{serve as rP}from"@hono/node-server";import{streamSSE as nP}from"hono/streaming";import*as ny from"fs/promises";import*as sy from"path";import*as zl from"fs/promises";import*as Wn from"path";var xo=class{async get(e){let t=ve(e),n=Wn.join(En,t+".bin"),s=Wn.join(En,t+".json");try{let[i,o]=await Promise.all([zl.readFile(n),zl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await V();let n=ve(e),s=Wn.join(En,n+".bin"),i=Wn.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 ey=`
|
|
1546
1615
|
const CSS = '\\n' +
|
|
1547
1616
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1548
1617
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1846,17 +1915,17 @@ export function runInference(ctx) {
|
|
|
1846
1915
|
showConfirm();
|
|
1847
1916
|
document.body.appendChild(host);
|
|
1848
1917
|
}
|
|
1849
|
-
`;
|
|
1850
|
-
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${
|
|
1851
|
-
`+
|
|
1918
|
+
`;Ne();Dt();Si();mr();import{stream as zT}from"hono/streaming";var XT="X-TB-Stream";function Yn(r){return r instanceof de?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function ko(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(XT,"1"),zT(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:Yn(s)}))}finally{try{await n.return?.()}catch{}}})}var Eo={log:(...r)=>console.log(...r)};function Ao(r,e){let t=r?.[e]??(Object.hasOwn(Eo,e)?Eo[e]:void 0);return typeof t=="function"?t:void 0}function To(r){return r.constructor?.name==="AsyncGeneratorFunction"}var QT=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,ZT=/[?&]target=/,eP=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function ty(r,e=""){return QT.test(r)?!0:eP.test(r)&&ZT.test(e)}var iy="127.0.0.1",sP=new Set(["localhost","127.0.0.1","::1"]);function iP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function oP(r){let e=iP(r);return!!e&&sP.has(e)}function aP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Xl(r){return r instanceof Error?r.message:"Unknown error"}async function oy(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 tP;m.use("*",async(h,S)=>{if(!oP(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"]],x=async(h,S)=>{if(!u){let I=new URL(h.req.url).pathname,L=b.find(([K])=>K.endsWith("/*")?I.startsWith(K.slice(0,-2)):I===K)?.[1]??"server-side code (server.ts)";Tm(process.pid,L);let R=d?`
|
|
1919
|
+
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${R}`,403)}await S()},k=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&&!aP(L,h.req.header("host")))return h.text("Forbidden: cross-origin request",403)}await S()};for(let[h]of b)m.use(h,x),m.use(h,k);if(m.use("/__log",k),m.post("/__log",async h=>{try{let{args:S}=await h.req.json();console.log(...S||[])}catch{}return h.json({ok:!0})}),o){let h=0,S=new Map;m.use("/__send",k),m.post("/__send",async I=>{let L="";try{L=await I.req.text()}catch{}let R=Number(I.req.query("reply"))||0,K=o.listenerCount("message");if(R<=0||K===0)return o.emit("message",{payload:L}),I.json({clients:K});let W=++h,De=await new Promise(Z=>{let Y={expected:K,received:0,results:[],errors:[],finish:Te=>{clearTimeout(Be),S.delete(W),Z({results:Y.results,errors:Y.errors,timedOut:Te})}},Be=setTimeout(()=>Y.finish(!0),R);S.set(W,Y),o.emit("message",{id:W,payload:L})});return I.json({clients:K,...De})}),m.use("/__send-reply",k),m.post("/__send-reply",async I=>{try{let{id:L,results:R,errors:K}=await I.req.json(),W=S.get(L);W&&(W.results.push(...R??[]),W.errors.push(...K??[]),++W.received>=W.expected&&W.finish(!1))}catch{}return I.json({ok:!0})})}m.get("/",h=>h.html(e())),m.post("/__fs/read",async h=>{try{let{path:S}=await h.req.json(),I=await On(S,y,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(S){let I=Xl(S);return h.json({error:I},400)}}),m.post("/__fs/write",async h=>{try{let S=h.req.query("path");return S?(await ki(S,new Uint8Array(await h.req.arrayBuffer()),y,t),h.json({success:!0})):h.json({error:"Missing path"},400)}catch(S){let I=Xl(S);return h.json({error:I},400)}}),m.post("/__api/:name",async h=>{try{let S=h.req.param("name"),I=Ao(a?.(),S);if(!I)return h.json({error:`API function '${S}' not found`},404);let{args:L}=await h.req.json();if(To(I))return ko(h,I(...L||[]));let R=await I(...L||[]);return h.json({result:R})}catch(S){let I=Xl(S);return h.json({error:I},500)}}),m.post("/__ai",async h=>{try{let{messages:S,system:I,effort:L,provider:R,model:K,webSearch:W,stream:De}=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 Z=He(R,K);if(typeof Z=="string")return h.json({message:Z,code:"unknown",retryable:!1},400);let Y=await ft(Z,{messages:S,system:I,effort:L,webSearch:W,signal:h.req.raw.signal});if(!Y.ok){let Te=await pr(Y,Z.protocol);return h.json(Te,Y.status)}if(De)return ko(h,Mt(Y,Z.protocol));let Be=await Lt(Y,Z.protocol);return Be||console.warn("[tb.ai] Empty response from provider"),h.json({text:Be})}catch(S){return h.json(Yn(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=He();if(typeof L=="string")return h.json({message:L,code:"unknown",retryable:!1},400);let R=Array.isArray(S)?S.map(String):[],K=Fc(I,R),W=await ft(L,{messages:[{role:"user",content:K}],signal:h.req.raw.signal});if(!W.ok){let Z=await pr(W,L.protocol);return h.json(Z,W.status)}let De=(async function*(){let Z="";for await(let Te of Mt(W,L.protocol))Te.kind!=="text"||!Te.text||(Z+=Te.text,yield{kind:"delta",text:Te.text});let Y=qc(Z);if(Y.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1920
|
+
`+Z.slice(-4e3)),new de("LLM output is not valid JSON","parse_error",!0);Y.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",Y.fixesApplied.join(", "));let Be={insight:Y.parsed,insightJson:Y.json,data:R};yield{kind:"complete",...Be,fixesApplied:Y.fixesApplied,hash:Uc(Be)}})();return ko(h,De)}catch(S){return h.json(Yn(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(Yn(S),500)}}),m.get("/__infer-info",h=>{let S=c?.(),I=Lr(S?.config??"").inference,L=zs(S?.data??""),R=He();return typeof R=="string"?h.json({error:R,inference:I,data:L}):h.json({provider:R.protocol,model:R.model,inference:I,data:L})}),m.use("/__infer-decode",k),m.post("/__infer-decode",async h=>h.json(await T(h)??{error:"invalid fragment"})),m.get("/__infer-ui.js",h=>h.body(ey,200,{"Content-Type":"text/javascript; charset=utf-8"})),m.get("/__models",async h=>{try{let S=await Ke();return h.json(S)}catch{return h.json([],200)}}),m.get("/__has-own-keys",async h=>{try{return h.json(await vi())}catch{return h.json(!1,200)}});let P=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],_=new xo;m.get("/proxy/*",async h=>{let S=new URL(h.req.url),L=(S.pathname+S.search).slice(7),R=L.lastIndexOf("https://");return R===-1?h.text("Invalid proxy URL",400):O(h,L.slice(R))}),f&&ry(m,`/local/${f.name}/`,f.serveDir),p&&ry(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 _.get(S);if(L)return new Response(L.body,{status:200,headers:Ql(L.contentType,L.cacheControl)});try{let R=await fetch(S,{headers:{Accept:h.req.header("Accept")||"*/*"},redirect:"follow"});if(!R.ok)return h.text(`Upstream ${R.status}`,R.status);let K=R.headers.get("Content-Type")||void 0,W=R.headers.get("Cache-Control")||void 0;if(R.body){let[De,Z]=R.body.tee();return(async()=>{try{let Y=await new Response(Z).arrayBuffer();await _.set(S,{body:Buffer.from(Y),contentType:K,cacheControl:W})}catch{}})(),new Response(De,{status:R.status,headers:Ql(K,W)})}return new Response(null,{status:R.status,headers:Ql(K,W)})}catch(R){return h.text(`Proxy fetch failed: ${R instanceof Error?R.message:R}`,502)}}(i||o)&&m.get("/__reload",h=>nP(h,async S=>{let I=()=>{S.writeSSE({event:"reload",data:""})},L=R=>{S.writeSSE({event:"message",data:JSON.stringify(R)})};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 ty(S.pathname,S.search)?O(h,"https://esm.sh"+S.pathname+S.search):h.text("Not Found",404)});let N=rP({fetch:m.fetch,port:s,hostname:iy});return{port:s,close:()=>N.close()}}function Ql(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 ry(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=xi(i,t),a=await ny.readFile(o);return new Response(a,{headers:{"Content-Type":cP(o)}})}catch{return n.text("Not Found",404)}})}function cP(r){switch(sy.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"}}async function Zl(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,iy,()=>{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 Po(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Zl(e),a=await oy(t(o)),c=`http://localhost:${o}`;await Am(n(o,c)),console.log(`
|
|
1852
1921
|
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1853
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import lP from"chokidar";var uP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Yt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=lP.watch(e,uP),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}
|
|
1922
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import lP from"chokidar";var uP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Yt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=lP.watch(e,uP),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 ly(r,e,t,n){let s=process.cwd(),i=$i(process.pid),o=e.watch?new ay:void 0,a=new ay;a.setMaxListeners(0);let c=ge(e.mode),l=await dl(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(P=>P.pid).join(", ")})`);let f=1;console.log(cl(f)),console.log(`Loading ${cy.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await Yc(r,e.watch,e.trust,n,e.dir);ht(c,r,d.server);let y=e.trust?void 0:xr(d),{port:m,url:b,onCleanup:x}=await Po({portPreference:e.port,displayName:d.name,stopLog:i,makeServerOptions:P=>({getHtml:()=>u,basePath:s,fsBase:Ei(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(_,O)=>{let N=await $r.readFile(r,"utf-8");N=Do(N,"data",_.join(Op)),N=Do(N,"insight",O),await $r.writeFile(r,N)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),makeEntry:(P,_)=>({pid:process.pid,port:P,url:_,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,dir:e.dir,mode:e.mode,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:
|
|
1854
1923
|
${t}
|
|
1855
1924
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1856
1925
|
`),e.watch&&console.log(` Watching for changes...
|
|
1857
|
-
`);let
|
|
1858
|
-
`),o.emit("reload")}})}}x
|
|
1859
|
-
`):await
|
|
1926
|
+
`);let k,T;if(e.watch&&o){let P=0,_=Promise.resolve();if(k=Yt({target:r,onChange:()=>{let O=++P;_=_.then(async()=>{if(O===P)try{console.log("Recompiling...");let N=await Yc(r,!0,e.trust,n,e.dir);u=N.html,p=N.serverExports,d=N.bulb,f++,console.log(cl(f)),o.emit("reload")}catch(N){console.error("Compile error:",N)}})}}),n){let{name:O,serveDir:N}=n;T=Yt({target:N,events:"all",onChange:()=>{console.log(`Local package '${O}' changed. Browser reloading...
|
|
1927
|
+
`),o.emit("reload")}})}}k&&x(k),T&&x(T),x(()=>$r.rm(Wc(r),{force:!0})),e.open&&(l.some(P=>P.port===m)?console.log(` Reusing the open browser tab.
|
|
1928
|
+
`):await dP(b))}gt();import{readFileSync as dy,copyFileSync as pP,existsSync as mP}from"fs";import*as se from"path";import{fileURLToPath as hP}from"url";import{EventEmitter as gP}from"events";import fy from"open";Ne();var eu=r=>`/agents/${r}/client.js`,fP=`
|
|
1860
1929
|
(() => {
|
|
1861
1930
|
const api = async (name, ...args) => {
|
|
1862
1931
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1891,7 +1960,7 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(pr
|
|
|
1891
1960
|
es.onerror = () => { es.close(); };
|
|
1892
1961
|
}
|
|
1893
1962
|
})();
|
|
1894
|
-
`;function
|
|
1963
|
+
`;function uy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=eu(t);return`<!DOCTYPE html>
|
|
1895
1964
|
<html>
|
|
1896
1965
|
<head>
|
|
1897
1966
|
<meta charset="utf-8">
|
|
@@ -1911,17 +1980,17 @@ ${s}
|
|
|
1911
1980
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1912
1981
|
|
|
1913
1982
|
<script>
|
|
1914
|
-
${
|
|
1983
|
+
${fP}
|
|
1915
1984
|
</script>
|
|
1916
1985
|
|
|
1917
1986
|
<script type="module" src="${a}"></script>
|
|
1918
1987
|
</body>
|
|
1919
|
-
</html>`}async function
|
|
1920
|
-
${n.url}`),r.open&&await fy(n.url);return}let s=$i(process.pid),i=r.watch?new gP:void 0,o=ge(r.mode),a=await
|
|
1921
|
-
`);let
|
|
1922
|
-
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{
|
|
1923
|
-
`);let c=0,l=Promise.resolve();Yt({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)}})}})}}
|
|
1924
|
-
`)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}return
|
|
1925
|
-
`),
|
|
1926
|
-
`),process.exit(1)}function
|
|
1927
|
-
${e}`),process.exit(1))}async function EP(){let r=
|
|
1988
|
+
</html>`}async function py(r){let e=process.cwd(),t=r.agentTarget;hg(t)||(console.error(`Unknown agent '${t}'. Known: ${Rr().join(", ")}.`),process.exit(1));let n=await ul(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1989
|
+
${n.url}`),r.open&&await fy(n.url);return}let s=$i(process.pid),i=r.watch?new gP:void 0,o=ge(r.mode),a=await yg(t),c=a.displayName||`${t} mirror`;ht(o,se.join(e,"mirror"));let l=se.dirname(hP(import.meta.url)),f=se.join(l,"agents",t),u=se.join(l,"..","cli","agents"),d=se.join(f,"styles.css"),p=se.join(f,"index.html"),y=()=>uy({name:c,agent:t,styles:dy(d,"utf8"),mountHtml:dy(p,"utf8"),watch:r.watch}),{port:m,url:b,onCleanup:x}=await Po({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:O=>({getHtml:y,basePath:e,port:O,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${se.posix.dirname(eu(t))}/`,dir:f}}),makeEntry:(O,N)=>({pid:process.pid,port:O,url:N,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1990
|
+
`);let k=se.join(u,t,"client"),T=se.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[se.join(k,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:se.join(f,"client.js")});for(let N of["styles.css","index.html","typebulb.png","typebulb-inv.png"])pP(se.join(T,N),se.join(f,N))}let _;if(r.watch&&i){let O=mP(k),N=!1;_=Yt({target:O?u:f,events:"all",onChange:async()=>{if(!N){N=!0;try{O&&await P(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1991
|
+
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{N=!1}}}})}r.open&&await fy(b),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),_&&x(_)}gt();import*as my from"path";async function hy(r,e,t,n,s){let i=ge(t),o=!1,a=async()=>{let{bulb:c,config:l}=await ke(r);o||(ht(i,r,c.server),o=!0),await _n(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${my.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1992
|
+
`);let c=0,l=Promise.resolve();Yt({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)}})}})}}gt();import{Console as yP}from"node:console";Ne();async function by(r,e,t,n,s){xP();try{let p=Sr(await z(),r)[0];p&&(Ii(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 ke(r);o.server||Vn("This bulb has no **server.ts** block; nothing to call."),ht(i,r,o.server);let c;try{c=await _n(o.server,r,n,a.dependencies,s)}catch(p){Vn(p instanceof Error?p.message:String(p))}let l=Ao(c,e.fn);if(!l){let p=[...Object.keys(c).filter(y=>typeof c[y]=="function"),...Object.keys(Eo)];Vn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await bP(e);if(To(l)){try{for await(let p of l(...f))await yy(JSON.stringify(p,wy)+`
|
|
1993
|
+
`)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}return gy(0)}let u;try{u=await l(...f)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}let d=SP(u);d!==void 0&&await yy(d+`
|
|
1994
|
+
`),gy(0)}function gy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function bP(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await kP()),vP(e)}return wP(r.positional)}function wP(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function vP(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 SP(r){if(r!==void 0)return JSON.stringify(r,wy,2)}function wy(r,e){return typeof e=="bigint"?e.toString():e}function Vn(r){process.stderr.write(r+`
|
|
1995
|
+
`),process.exit(1)}function xP(){let r=new yP(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 yy(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function kP(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var tu="0.31.0";function vy(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1996
|
+
${e}`),process.exit(1))}async function EP(){let r=yu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${tu}`),process.exit(0)),r.help&&(bu(),process.exit(0)),Bg(),r.subcommand==="logs"){await Vg(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Gg(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Xg(r.stopScope):await zg(r.file||void 0);return}if(r.subcommand==="send"){await Zg(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Hg(tu);return}if(r.subcommand==="models"){await Jg(r.mode);return}if(r.subcommand==="pull"){await Um(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Hm(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?py(r):Ug(tu));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Dg(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await um(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Vt.resolve(r.file);await Sy.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:Vt.relative(process.cwd(),e)||Vt.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Mg(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 ke(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 mu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Vt.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Lg(e,a);return}if(r.subcommand==="call"){vy(r.trust,s),await by(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(Xs(o.bulb)||r.server)){vy(r.trust,s),await hy(e,r.watch,r.mode,a,r.dir);return}await ly(e,r,s,a)}EP().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|