typebulb 0.18.3 → 0.18.5
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 +25 -22
- package/dist/index.js +189 -187
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,159 +1,159 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
3
|
+
var Fh=Object.create;var Ti=Object.defineProperty;var qh=Object.getOwnPropertyDescriptor;var Uh=Object.getOwnPropertyNames;var Jh=Object.getPrototypeOf,Kh=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 C=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Rc=(r,e)=>{for(var t in e)Ti(r,t,{get:e[t],enumerable:!0})},Wh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Uh(e))!Kh.call(r,s)&&s!==t&&Ti(r,s,{get:()=>e[s],enumerable:!(n=qh(e,s))||n.enumerable});return r};var Hh=(r,e,t)=>(t=r!=null?Fh(Jh(r)):{},Wh(e||!r||!r.__esModule?Ti(t,"default",{value:r,enumerable:!0}):t,r));function qc(r){return vt.find(e=>wt[e].path===r)}function Jc(r){return!!r?.startsWith("typebulb")}var wt,vt,Uc,yn=C(()=>{wt={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"}},vt=["code","css","html","data","infer","insight","config","notes"];Uc="typebulb/v1"});function Ri(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Ni(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var bn=C(()=>{});function Qe(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=sm(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Kc);if(l){let d=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Wc);if(!u){t++;continue}let f=u[1];t++;let p=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${f}\\s*$`));)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...rm(d,p,m)),i.set(d,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function rm(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Kc);i&&tm.has(i[1].trim())&&nm(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 nm(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Wc)}function sm(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=Ni(i);break}}return!Jc(e.format)||!e.name?null:e}function Hc(r){return Qe(r)?.warnings??[]}function Vc(r){let e=Object.fromEntries(vt.map(t=>[t,r.files.get(wt[t].path)||""]));return{name:r.frontmatter.name,...e}}var Kc,Wc,tm,Yc=C(()=>{yn();bn();Kc=/^\*\*(.+)\*\*$/,Wc=/^(`{3,})(\w*)\s*$/,tm=new Set(vt.map(r=>wt[r].path))});function im(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 Gc(r){let e=vt.filter(t=>r[t]).map(t=>{let{path:n}=wt[t],s=r[t],i=n.split(".").pop(),o=im(s);return`**${n}**
|
|
6
6
|
|
|
7
7
|
${o}${i}
|
|
8
8
|
${s}
|
|
9
|
-
${o}`});return["---",`format: ${
|
|
10
|
-
`)}var
|
|
11
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=er(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,m=1,h=0;for(;(c=er(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(m+=
|
|
12
|
-
>]`),h+=
|
|
13
|
-
`)}};nr.defaultYaml={explicit:!1,version:"1.2"};nr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
14
|
-
`)?
|
|
9
|
+
${o}`});return["---",`format: ${Uc}`,`name: ${Ri(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}var zc=C(()=>{yn();bn()});function Qc(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var Xc=C(()=>{});var Zc=C(()=>{});function _i(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var el=C(()=>{});function er(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var tl=C(()=>{});function wn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var rl=C(()=>{});function tr(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=_i(r,`<${e}[
|
|
11
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=er(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,m=1,h=0;for(;(c=er(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(m+=wn(y,"<"+e+`[
|
|
12
|
+
>]`),h+=wn(y,"</"+e+">"),h>=m)break;p=c}}else c=er(a,"[ /]"+e+">",0);let d=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",d),d===-1)return;let u=r.slice(o,d),f;return l?f=null:f=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:f,outer:u,start:o,end:d}}var Ii=C(()=>{el();tl();rl()});var Li=C(()=>{Ii()});var $i=C(()=>{Li()});var nl=C(()=>{$i()});var sl=C(()=>{});var il=C(()=>{Zc();Ii();Li();nl();$i();sl()});var _=T(z=>{"use strict";var Mi=Symbol.for("yaml.alias"),ol=Symbol.for("yaml.document"),vn=Symbol.for("yaml.map"),al=Symbol.for("yaml.pair"),Di=Symbol.for("yaml.scalar"),Sn=Symbol.for("yaml.seq"),Te=Symbol.for("yaml.node.type"),cm=r=>!!r&&typeof r=="object"&&r[Te]===Mi,lm=r=>!!r&&typeof r=="object"&&r[Te]===ol,um=r=>!!r&&typeof r=="object"&&r[Te]===vn,fm=r=>!!r&&typeof r=="object"&&r[Te]===al,cl=r=>!!r&&typeof r=="object"&&r[Te]===Di,dm=r=>!!r&&typeof r=="object"&&r[Te]===Sn;function ll(r){if(r&&typeof r=="object")switch(r[Te]){case vn:case Sn:return!0}return!1}function pm(r){if(r&&typeof r=="object")switch(r[Te]){case Mi:case vn:case Di:case Sn:return!0}return!1}var hm=r=>(cl(r)||ll(r))&&!!r.anchor;z.ALIAS=Mi;z.DOC=ol;z.MAP=vn;z.NODE_TYPE=Te;z.PAIR=al;z.SCALAR=Di;z.SEQ=Sn;z.hasAnchor=hm;z.isAlias=cm;z.isCollection=ll;z.isDocument=lm;z.isMap=um;z.isNode=pm;z.isPair=fm;z.isScalar=cl;z.isSeq=dm});var rr=T(Bi=>{"use strict";var H=_(),te=Symbol("break visit"),ul=Symbol("skip children"),we=Symbol("remove node");function xn(r,e){let t=fl(e);H.isDocument(r)?St(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):St(null,r,t,Object.freeze([]))}xn.BREAK=te;xn.SKIP=ul;xn.REMOVE=we;function St(r,e,t,n){let s=dl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return pl(r,n,s),St(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=St(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===te)return te;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=St("key",e.key,t,n);if(i===te)return te;i===we&&(e.key=null);let o=St("value",e.value,t,n);if(o===te)return te;o===we&&(e.value=null)}}return s}async function kn(r,e){let t=fl(e);H.isDocument(r)?await xt(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):await xt(null,r,t,Object.freeze([]))}kn.BREAK=te;kn.SKIP=ul;kn.REMOVE=we;async function xt(r,e,t,n){let s=await dl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return pl(r,n,s),xt(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await xt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===te)return te;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=await xt("key",e.key,t,n);if(i===te)return te;i===we&&(e.key=null);let o=await xt("value",e.value,t,n);if(o===te)return te;o===we&&(e.value=null)}}return s}function fl(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 dl(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(H.isMap(e))return t.Map?.(r,e,n);if(H.isSeq(e))return t.Seq?.(r,e,n);if(H.isPair(e))return t.Pair?.(r,e,n);if(H.isScalar(e))return t.Scalar?.(r,e,n);if(H.isAlias(e))return t.Alias?.(r,e,n)}function pl(r,e,t){let n=e[e.length-1];if(H.isCollection(n))n.items[r]=t;else if(H.isPair(n))r==="key"?n.key=t:n.value=t;else if(H.isDocument(n))n.contents=t;else{let s=H.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Bi.visit=xn;Bi.visitAsync=kn});var ji=T(ml=>{"use strict";var hl=_(),mm=rr(),gm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ym=r=>r.replace(/[!,[\]{}]/g,e=>gm[e]),nr=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+ym(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&&hl.isNode(e.contents)){let i={};mm.visit(e.contents,(o,a)=>{hl.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
13
|
+
`)}};nr.defaultYaml={explicit:!1,version:"1.2"};nr.defaultTags={"!!":"tag:yaml.org,2002:"};ml.Directives=nr});var En=T(sr=>{"use strict";var gl=_(),bm=rr();function wm(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 yl(r){let e=new Set;return bm.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function bl(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function vm(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=yl(r));let o=bl(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(gl.isScalar(o.node)||gl.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}}sr.anchorIsValid=wm;sr.anchorNames=yl;sr.createNodeAnchors=vm;sr.findNewAnchor=bl});var Fi=T(wl=>{"use strict";function ir(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=ir(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=ir(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=ir(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=ir(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}wl.applyReviver=ir});var Ie=T(Sl=>{"use strict";var Sm=_();function vl(r,e,t){if(Array.isArray(r))return r.map((n,s)=>vl(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Sm.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}Sl.toJS=vl});var An=T(kl=>{"use strict";var xm=Fi(),xl=_(),km=Ie(),qi=class{constructor(e){Object.defineProperty(this,xl.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(!xl.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=km.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?xm.applyReviver(i,{"":a},"",a):a}};kl.NodeBase=qi});var or=T(El=>{"use strict";var Em=En(),Am=rr(),kt=_(),Tm=An(),Pm=Ie(),Ui=class extends Tm.NodeBase{constructor(e){super(kt.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=[],Am.visit(e,{Node:(i,o)=>{(kt.isAlias(o)||kt.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||(Pm.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=Tn(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(Em.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 Tn(r,e,t){if(kt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(kt.isCollection(e)){let n=0;for(let s of e.items){let i=Tn(r,s,t);i>n&&(n=i)}return n}else if(kt.isPair(e)){let n=Tn(r,e.key,t),s=Tn(r,e.value,t);return Math.max(n,s)}return 1}El.Alias=Ui});var U=T(Ji=>{"use strict";var Om=_(),Cm=An(),Rm=Ie(),Nm=r=>!r||typeof r!="function"&&typeof r!="object",Le=class extends Cm.NodeBase{constructor(e){super(Om.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Rm.toJS(this.value,e,t)}toString(){return String(this.value)}};Le.BLOCK_FOLDED="BLOCK_FOLDED";Le.BLOCK_LITERAL="BLOCK_LITERAL";Le.PLAIN="PLAIN";Le.QUOTE_DOUBLE="QUOTE_DOUBLE";Le.QUOTE_SINGLE="QUOTE_SINGLE";Ji.Scalar=Le;Ji.isScalarValue=Nm});var ar=T(Tl=>{"use strict";var _m=or(),Xe=_(),Al=U(),Im="tag:yaml.org,2002:";function Lm(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 $m(r,e,t){if(Xe.isDocument(r)&&(r=r.contents),Xe.isNode(r))return r;if(Xe.isPair(r)){let u=t.schema[Xe.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 _m.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Im+e.slice(2));let l=Lm(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Al.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[Xe.MAP]:Symbol.iterator in Object(r)?o[Xe.SEQ]:o[Xe.MAP]}i&&(i(l),delete t.onTagObj);let d=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new Al.Scalar(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Tl.createNode=$m});var On=T(Pn=>{"use strict";var Mm=ar(),ve=_(),Dm=An();function Ki(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 Mm.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 Pl=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Wi=class extends Dm.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>ve.isNode(n)||ve.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Pl(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(ve.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,Ki(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(ve.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&ve.isScalar(i)?i.value:i:ve.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ve.isPair(t))return!1;let n=t.value;return n==null||e&&ve.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return ve.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(ve.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,Ki(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Pn.Collection=Wi;Pn.collectionFromPath=Ki;Pn.isEmptyPath=Pl});var cr=T(Cn=>{"use strict";var Bm=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Hi(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var jm=(r,e,t)=>r.endsWith(`
|
|
14
|
+
`)?Hi(t,e):t.includes(`
|
|
15
15
|
`)?`
|
|
16
|
-
`+
|
|
17
|
-
`)t===
|
|
16
|
+
`+Hi(t,e):(r.endsWith(" ")?"":" ")+t;Cn.indentComment=Hi;Cn.lineComment=jm;Cn.stringifyComment=Bm});var Cl=T(lr=>{"use strict";var Fm="flow",Vi="block",Rn="quoted";function qm(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],d={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let f,p,m=!1,h=-1,y=-1,S=-1;t===Vi&&(h=Ol(r,h,e.length),h!==-1&&(u=h+c));for(let g;g=r[h+=1];){if(t===Rn&&g==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(g===`
|
|
17
|
+
`)t===Vi&&(h=Ol(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(g===" "&&p&&p!==" "&&p!==`
|
|
18
18
|
`&&p!==" "){let b=r[h+1];b&&b!==" "&&b!==`
|
|
19
|
-
`&&b!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===
|
|
20
|
-
${e}${r.slice(0,v)}`:(t===
|
|
21
|
-
${e}${r.slice(b+1,v)}`)}return
|
|
22
|
-
`);n=e,s=e+1,i=r[s]}return n}lr.FOLD_BLOCK=
|
|
23
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function ur(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
19
|
+
`&&b!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Rn){for(;p===" "||p===" ";)p=g,g=r[h+=1],m=!0;let b=h>S+1?h-2:y-1;if(d[b])return r;l.push(b),d[b]=!0,u=b+c,f=void 0}else m=!0}p=g}if(m&&a&&a(),l.length===0)return r;o&&o();let A=r.slice(0,l[0]);for(let g=0;g<l.length;++g){let b=l[g],v=l[g+1]||r.length;b===0?A=`
|
|
20
|
+
${e}${r.slice(0,v)}`:(t===Rn&&d[b]&&(A+=`${r[b]}\\`),A+=`
|
|
21
|
+
${e}${r.slice(b+1,v)}`)}return A}function Ol(r,e,t){let n=e,s=e+1,i=r[s];for(;i===" "||i===" ";)if(e<s+t)i=r[++e];else{do i=r[++e];while(i&&i!==`
|
|
22
|
+
`);n=e,s=e+1,i=r[s]}return n}lr.FOLD_BLOCK=Vi;lr.FOLD_FLOW=Fm;lr.FOLD_QUOTED=Rn;lr.foldFlowLines=qm});var fr=T(Rl=>{"use strict";var fe=U(),$e=Cl(),_n=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),In=r=>/^(%|---|\.\.\.)/m.test(r);function Um(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;i<s;++i)if(r[i]===`
|
|
23
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function ur(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(In(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let d=t.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
24
24
|
|
|
25
25
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
26
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:$e.foldFlowLines(o,i,$e.FOLD_QUOTED,
|
|
27
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return ur(r,e);let t=e.indent||(
|
|
28
|
-
${t}`)+"'";return e.implicitKey?n:$e.foldFlowLines(n,t,$e.FOLD_FLOW,
|
|
26
|
+
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:$e.foldFlowLines(o,i,$e.FOLD_QUOTED,_n(e,!1))}function Yi(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
27
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return ur(r,e);let t=e.indent||(In(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
28
|
+
${t}`)+"'";return e.implicitKey?n:$e.foldFlowLines(n,t,$e.FOLD_FLOW,_n(e,!1))}function Et(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=ur;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=Yi:i&&!s?n=ur:n=t?Yi:ur}return n(r,e)}var Gi;try{Gi=new RegExp(`(^|(?<!
|
|
29
29
|
))
|
|
30
30
|
+(?!
|
|
31
|
-
|$)`,"g")}catch{
|
|
31
|
+
|$)`,"g")}catch{Gi=/\n+(?!\n|$)/g}function Nn({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 Et(t,n);let l=n.indent||(n.forceBlockIndent||In(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===fe.Scalar.BLOCK_FOLDED?!1:e===fe.Scalar.BLOCK_LITERAL?!0:!Um(t,c,l.length);if(!t)return d?`|
|
|
32
32
|
`:`>
|
|
33
33
|
`;let u,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==`
|
|
34
34
|
`&&v!==" "&&v!==" ")break}let p=t.substring(f),m=p.indexOf(`
|
|
35
35
|
`);m===-1?u="-":t===p||m!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
36
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
37
|
-
`)
|
|
38
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
39
|
-
${l}${
|
|
40
|
-
${l}${
|
|
36
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Gi,`$&${l}`));let h=!1,y,S=-1;for(y=0;y<t.length;++y){let v=t[y];if(v===" ")h=!0;else if(v===`
|
|
37
|
+
`)S=y;else break}let A=t.substring(0,S<y?S+1:y);A&&(t=t.substring(A.length),A=A.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+u;if(r&&(b+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let v=t.replace(/\n+/g,`
|
|
38
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),x=!1,P=_n(n,!0);o!=="folded"&&e!==fe.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{x=!0});let k=$e.foldFlowLines(`${A}${v}${p}`,l,$e.FOLD_BLOCK,P);if(!x)return`>${b}
|
|
39
|
+
${l}${k}`}return t=t.replace(/\n+/g,`$&${l}`),`|${b}
|
|
40
|
+
${l}${A}${t}${p}`}function Jm(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&i.includes(`
|
|
41
41
|
`)||d&&/[[\]{},]/.test(i))return Et(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
42
|
-
`)?Et(i,e):
|
|
43
|
-
`))return
|
|
44
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Et(i,e)}return a?u:$e.foldFlowLines(u,c,$e.FOLD_FLOW,
|
|
45
|
-
${e.indent}${a}`:a}
|
|
46
|
-
${a}:`):(y=`${y}:`,f&&(y+=pr.lineComment(y,t.indent,l(f))));let
|
|
47
|
-
`:"",
|
|
48
|
-
${pr.indentComment(P,t.indent)}`}v===""&&!t.inFlow?
|
|
49
|
-
`&&g&&(
|
|
50
|
-
|
|
51
|
-
`):
|
|
52
|
-
${t.indent}`}else if(!p&&Pe.isCollection(e)){let P=v[0],
|
|
53
|
-
`),L=
|
|
42
|
+
`)?Et(i,e):Nn(r,e,t,n);if(!a&&!d&&s!==fe.Scalar.PLAIN&&i.includes(`
|
|
43
|
+
`))return Nn(r,e,t,n);if(In(i)){if(c==="")return e.forceBlockIndent=!0,Nn(r,e,t,n);if(a&&c===l)return Et(i,e)}let u=i.replace(/\n+/g,`$&
|
|
44
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Et(i,e)}return a?u:$e.foldFlowLines(u,c,$e.FOLD_FLOW,_n(e,!1))}function Km(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!==fe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=fe.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case fe.Scalar.BLOCK_FOLDED:case fe.Scalar.BLOCK_LITERAL:return s||i?Et(o.value,e):Nn(o,e,t,n);case fe.Scalar.QUOTE_DOUBLE:return ur(o.value,e);case fe.Scalar.QUOTE_SINGLE:return Yi(o.value,e);case fe.Scalar.PLAIN:return Jm(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=s&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Rl.stringifyString=Km});var dr=T(zi=>{"use strict";var Wm=En(),Me=_(),Hm=cr(),Vm=fr();function Ym(r,e){let t=Object.assign({blockQuote:!0,commentString:Hm.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 Gm(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(Me.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 zm(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Me.isScalar(r)||Me.isCollection(r))&&r.anchor;i&&Wm.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 Qm(r,e,t,n){if(Me.isPair(r))return r.toString(e,t,n);if(Me.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=Me.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Gm(e.doc.schema.tags,i));let o=zm(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):Me.isScalar(i)?Vm.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Me.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
45
|
+
${e.indent}${a}`:a}zi.createStringifyContext=Ym;zi.stringify=Qm});var Ll=T(Il=>{"use strict";var Pe=_(),Nl=U(),_l=dr(),pr=cr();function Xm({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=Pe.isNode(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Pe.isCollection(r)||!Pe.isNode(r)&&typeof r=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||Pe.isCollection(r)||(Pe.isScalar(r)?r.type===Nl.Scalar.BLOCK_FOLDED||r.type===Nl.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let m=!1,h=!1,y=_l.stringify(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.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 m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(i&&!u||e==null&&p)return y=`? ${y}`,f&&!m?y+=pr.lineComment(y,t.indent,l(f)):h&&s&&s(),y;m&&(f=null),p?(f&&(y+=pr.lineComment(y,t.indent,l(f))),y=`? ${y}
|
|
46
|
+
${a}:`):(y=`${y}:`,f&&(y+=pr.lineComment(y,t.indent,l(f))));let S,A,g;Pe.isNode(e)?(S=!!e.spaceBefore,A=e.commentBefore,g=e.comment):(S=!1,A=null,g=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&Pe.isScalar(e)&&(t.indentAtStart=y.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Pe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let b=!1,v=_l.stringify(e,t,()=>b=!0,()=>h=!0),x=" ";if(f||S||A){if(x=S?`
|
|
47
|
+
`:"",A){let P=l(A);x+=`
|
|
48
|
+
${pr.indentComment(P,t.indent)}`}v===""&&!t.inFlow?x===`
|
|
49
|
+
`&&g&&(x=`
|
|
50
|
+
|
|
51
|
+
`):x+=`
|
|
52
|
+
${t.indent}`}else if(!p&&Pe.isCollection(e)){let P=v[0],k=v.indexOf(`
|
|
53
|
+
`),L=k!==-1,Q=t.inFlow??e.flow??e.items.length===0;if(L||!Q){let V=!1;if(L&&(P==="&"||P==="!")){let B=v.indexOf(" ");P==="&"&&B!==-1&&B<k&&v[B+1]==="!"&&(B=v.indexOf(" ",B+1)),(B===-1||k<B)&&(V=!0)}V||(x=`
|
|
54
54
|
${t.indent}`)}}else(v===""||v[0]===`
|
|
55
|
-
`)&&(
|
|
55
|
+
`)&&(x="");return y+=x+v,t.inFlow?b&&n&&n():g&&!b?y+=pr.lineComment(y,t.indent,l(g)):h&&s&&s(),y}Il.stringifyPair=Xm});var Xi=T(Qi=>{"use strict";var $l=gn("process");function Zm(r,...e){r==="debug"&&console.log(...e)}function eg(r,e){(r==="debug"||r==="warn")&&(typeof $l.emitWarning=="function"?$l.emitWarning(e):console.warn(e))}Qi.debug=Zm;Qi.warn=eg});var Dn=T(Mn=>{"use strict";var hr=_(),Ml=U(),Ln="<<",$n={identify:r=>r===Ln||typeof r=="symbol"&&r.description===Ln,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ml.Scalar(Symbol(Ln)),{addToJSMap:Dl}),stringify:()=>Ln},tg=(r,e)=>($n.identify(e)||hr.isScalar(e)&&(!e.type||e.type===Ml.Scalar.PLAIN)&&$n.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===$n.tag&&t.default);function Dl(r,e,t){if(t=r&&hr.isAlias(t)?t.resolve(r.doc):t,hr.isSeq(t))for(let n of t.items)Zi(r,e,n);else if(Array.isArray(t))for(let n of t)Zi(r,e,n);else Zi(r,e,t)}function Zi(r,e,t){let n=r&&hr.isAlias(t)?t.resolve(r.doc):t;if(!hr.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}Mn.addMergeToJSMap=Dl;Mn.isMergeKey=tg;Mn.merge=$n});var to=T(Fl=>{"use strict";var rg=Xi(),Bl=Dn(),ng=dr(),jl=_(),eo=Ie();function sg(r,e,{key:t,value:n}){if(jl.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Bl.isMergeKey(r,t))Bl.addMergeToJSMap(r,e,n);else{let s=eo.toJS(t,"",r);if(e instanceof Map)e.set(s,eo.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=ig(t,s,r),o=eo.toJS(n,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function ig(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(jl.isNode(r)&&t?.doc){let n=ng.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)+'..."'),rg.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)}Fl.addPairToJSMap=sg});var De=T(ro=>{"use strict";var ql=ar(),og=Ll(),ag=to(),Bn=_();function cg(r,e,t){let n=ql.createNode(r,void 0,t),s=ql.createNode(e,void 0,t);return new jn(n,s)}var jn=class r{constructor(e,t=null){Object.defineProperty(this,Bn.NODE_TYPE,{value:Bn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Bn.isNode(t)&&(t=t.clone(e)),Bn.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return ag.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?og.stringifyPair(this,e,t,n):JSON.stringify(this)}};ro.Pair=jn;ro.createPair=cg});var no=T(Jl=>{"use strict";var Ze=_(),Ul=dr(),Fn=cr();function lg(r,e,t){return(e.inFlow??r.flow?fg:ug)(r,e,t)}function ug({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,f=[];for(let m=0;m<e.length;++m){let h=e[m],y=null;if(Ze.isNode(h))!u&&h.spaceBefore&&f.push(""),qn(t,f,h.commentBefore,u),h.comment&&(y=h.comment);else if(Ze.isPair(h)){let A=Ze.isNode(h.key)?h.key:null;A&&(!u&&A.spaceBefore&&f.push(""),qn(t,f,A.commentBefore,u))}u=!1;let S=Ul.stringify(h,d,()=>y=null,()=>u=!0);y&&(S+=Fn.lineComment(S,i,l(y))),u&&y&&(u=!1),f.push(n+S)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
|
|
56
56
|
${c}${h}`:`
|
|
57
57
|
`}}return r?(p+=`
|
|
58
|
-
`+
|
|
59
|
-
`))&&(l=!0),u.push(
|
|
58
|
+
`+Fn.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function fg({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let m=0;m<r.length;++m){let h=r[m],y=null;if(Ze.isNode(h))h.spaceBefore&&u.push(""),qn(e,u,h.commentBefore,!1),h.comment&&(y=h.comment);else if(Ze.isPair(h)){let A=Ze.isNode(h.key)?h.key:null;A&&(A.spaceBefore&&u.push(""),qn(e,u,A.commentBefore,!1),A.comment&&(l=!0));let g=Ze.isNode(h.value)?h.value:null;g?(g.comment&&(y=g.comment),g.commentBefore&&(l=!0)):h.value==null&&A?.comment&&(y=A.comment)}y&&(l=!0);let S=Ul.stringify(h,c,()=>y=null);m<r.length-1&&(S+=","),y&&(S+=Fn.lineComment(S,n,a(y))),!l&&(u.length>d||S.includes(`
|
|
59
|
+
`))&&(l=!0),u.push(S),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let m=u.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of u)m+=h?`
|
|
60
60
|
${i}${s}${h}`:`
|
|
61
61
|
`;return`${m}
|
|
62
|
-
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function
|
|
63
|
-
`:" ")}return
|
|
62
|
+
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function qn({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Fn.indentComment(e(n),r);t.push(i.trimStart())}}Jl.stringifyCollection=lg});var je=T(io=>{"use strict";var dg=no(),pg=to(),hg=On(),Be=_(),Un=De(),mg=U();function mr(r,e){let t=Be.isScalar(e)?e.value:e;for(let n of r)if(Be.isPair(n)&&(n.key===e||n.key===t||Be.isScalar(n.key)&&n.key.value===t))return n}var so=class extends hg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Be.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(Un.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;Be.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Un.Pair(e,e?.value):n=new Un.Pair(e.key,e.value);let s=mr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Be.isScalar(s.value)&&mg.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=mr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=mr(this.items,e)?.value;return(!t&&Be.isScalar(s)?s.value:s)??void 0}has(e){return!!mr(this.items,e)}set(e,t){this.add(new Un.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)pg.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Be.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})),dg.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};io.YAMLMap=so;io.findPair=mr});var At=T(Wl=>{"use strict";var gg=_(),Kl=je(),yg={collection:"map",default:!0,nodeClass:Kl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return gg.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Kl.YAMLMap.from(r,e,t)};Wl.map=yg});var Fe=T(Hl=>{"use strict";var bg=ar(),wg=no(),vg=On(),Kn=_(),Sg=U(),xg=Ie(),oo=class extends vg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Kn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Jn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Jn(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Kn.isScalar(s)?s.value:s}has(e){let t=Jn(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=Jn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Kn.isScalar(s)&&Sg.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(xg.toJS(i,String(s++),t));return n}toString(e,t,n){return e?wg.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(bg.createNode(a,void 0,n))}}return i}};function Jn(r){let e=Kn.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Hl.YAMLSeq=oo});var Tt=T(Yl=>{"use strict";var kg=_(),Vl=Fe(),Eg={collection:"seq",default:!0,nodeClass:Vl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return kg.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Vl.YAMLSeq.from(r,e,t)};Yl.seq=Eg});var gr=T(Gl=>{"use strict";var Ag=fr(),Tg={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),Ag.stringifyString(r,e,t,n)}};Gl.string=Tg});var Wn=T(Xl=>{"use strict";var zl=U(),Ql={identify:r=>r==null,createNode:()=>new zl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zl.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Ql.test.test(r)?r:e.options.nullStr};Xl.nullTag=Ql});var ao=T(eu=>{"use strict";var Pg=U(),Zl={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Pg.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Zl.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};eu.boolTag=Zl});var Pt=T(tu=>{"use strict";function Og({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}tu.stringifyNumber=Og});var lo=T(Hn=>{"use strict";var Cg=U(),co=Pt(),Rg={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:co.stringifyNumber},Ng={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():co.stringifyNumber(r)}},_g={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 Cg.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:co.stringifyNumber};Hn.float=_g;Hn.floatExp=Ng;Hn.floatNaN=Rg});var fo=T(Yn=>{"use strict";var ru=Pt(),Vn=r=>typeof r=="bigint"||Number.isInteger(r),uo=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function nu(r,e,t){let{value:n}=r;return Vn(n)&&n>=0?t+n.toString(e):ru.stringifyNumber(r)}var Ig={identify:r=>Vn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>uo(r,2,8,t),stringify:r=>nu(r,8,"0o")},Lg={identify:Vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>uo(r,0,10,t),stringify:ru.stringifyNumber},$g={identify:r=>Vn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>uo(r,2,16,t),stringify:r=>nu(r,16,"0x")};Yn.int=Lg;Yn.intHex=$g;Yn.intOct=Ig});var iu=T(su=>{"use strict";var Mg=At(),Dg=Wn(),Bg=Tt(),jg=gr(),Fg=ao(),po=lo(),ho=fo(),qg=[Mg.map,Bg.seq,jg.string,Dg.nullTag,Fg.boolTag,ho.intOct,ho.int,ho.intHex,po.floatNaN,po.floatExp,po.float];su.schema=qg});var cu=T(au=>{"use strict";var Ug=U(),Jg=At(),Kg=Tt();function ou(r){return typeof r=="bigint"||Number.isInteger(r)}var Gn=({value:r})=>JSON.stringify(r),Wg=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Gn},{identify:r=>r==null,createNode:()=>new Ug.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gn},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Gn},{identify:ou,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})=>ou(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:Gn}],Hg={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Vg=[Jg.map,Kg.seq].concat(Wg,Hg);au.schema=Vg});var go=T(lu=>{"use strict";var yr=gn("buffer"),mo=U(),Yg=fr(),Gg={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof yr.Buffer=="function")return yr.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 yr.Buffer=="function")a=o instanceof yr.Buffer?o.toString("base64"):yr.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=mo.Scalar.BLOCK_LITERAL),e!==mo.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=a.substr(f,c);a=d.join(e===mo.Scalar.BLOCK_LITERAL?`
|
|
63
|
+
`:" ")}return Yg.stringifyString({comment:r,type:e,value:a},n,s,i)}};lu.binary=Gg});var Xn=T(Qn=>{"use strict";var zn=_(),yo=De(),zg=U(),Qg=Fe();function uu(r,e){if(zn.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!zn.isPair(n)){if(zn.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new yo.Pair(new zg.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
64
64
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
65
|
-
${i.comment}`:n.comment}n=s}r.items[t]=Yn.isPair(n)?n:new mo.Pair(n)}}else e("Expected a sequence for this tag");return r}function uu(r,e,t){let{replacer:n}=t,s=new Yg.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(mo.createPair(a,c,t))}return s}var Gg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:lu,createNode:uu};Gn.createPairs=uu;Gn.pairs=Gg;Gn.resolvePairs=lu});var bo=T(yo=>{"use strict";var fu=_(),go=Ie(),br=je(),zg=Fe(),du=zn(),et=class r extends zg.YAMLSeq{constructor(){super(),this.add=br.YAMLMap.prototype.add.bind(this),this.delete=br.YAMLMap.prototype.delete.bind(this),this.get=br.YAMLMap.prototype.get.bind(this),this.has=br.YAMLMap.prototype.has.bind(this),this.set=br.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(fu.isPair(s)?(i=go.toJS(s.key,"",t),o=go.toJS(s.value,i,t)):i=go.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=du.createPairs(e,t,n),i=new this;return i.items=s.items,i}};et.tag="tag:yaml.org,2002:omap";var Qg={collection:"seq",identify:r=>r instanceof Map,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=du.resolvePairs(r,e),n=[];for(let{key:s}of t.items)fu.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)};yo.YAMLOMap=et;yo.omap=Qg});var yu=T(wo=>{"use strict";var pu=U();function hu({value:r,source:e},t){return e&&(r?mu:gu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var mu={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 pu.Scalar(!0),stringify:hu},gu={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 pu.Scalar(!1),stringify:hu};wo.falseTag=gu;wo.trueTag=mu});var bu=T(Qn=>{"use strict";var Xg=U(),vo=Pt(),Zg={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:vo.stringifyNumber},ey={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():vo.stringifyNumber(r)}},ty={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 Xg.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:vo.stringifyNumber};Qn.float=ty;Qn.floatExp=ey;Qn.floatNaN=Zg});var vu=T(vr=>{"use strict";var wu=Pt(),wr=r=>typeof r=="bigint"||Number.isInteger(r);function Xn(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 So(r,e,t){let{value:n}=r;if(wr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return wu.stringifyNumber(r)}var ry={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Xn(r,2,2,t),stringify:r=>So(r,2,"0b")},ny={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Xn(r,1,8,t),stringify:r=>So(r,8,"0")},sy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Xn(r,0,10,t),stringify:wu.stringifyNumber},iy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Xn(r,2,16,t),stringify:r=>So(r,16,"0x")};vr.int=sy;vr.intBin=ry;vr.intHex=iy;vr.intOct=ny});var ko=T(xo=>{"use strict";var ts=_(),Zn=De(),es=je(),tt=class r extends es.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ts.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Zn.Pair(e.key,null):t=new Zn.Pair(e,null),es.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=es.findPair(this.items,e);return!t&&ts.isPair(n)?ts.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=es.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Zn.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(Zn.createPair(o,null,n));return i}};tt.tag="tag:yaml.org,2002:set";var oy={collection:"map",identify:r=>r instanceof Set,nodeClass:tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>tt.from(r,e,t),resolve(r,e){if(ts.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};xo.YAMLSet=tt;xo.set=oy});var Ao=T(rs=>{"use strict";var ay=Pt();function Eo(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 Su(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return ay.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 cy={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})=>Eo(r,t),stringify:Su},ly={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=>Eo(r,!1),stringify:Su},xu={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(xu.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=Eo(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};rs.floatTime=ly;rs.intTime=cy;rs.timestamp=xu});var Au=T(Eu=>{"use strict";var uy=At(),fy=Jn(),dy=Tt(),py=gr(),hy=ho(),ku=yu(),To=bu(),ns=vu(),my=$n(),gy=bo(),yy=zn(),by=ko(),Po=Ao(),wy=[uy.map,dy.seq,py.string,fy.nullTag,ku.trueTag,ku.falseTag,ns.intBin,ns.intOct,ns.int,ns.intHex,To.floatNaN,To.floatExp,To.float,hy.binary,my.merge,gy.omap,yy.pairs,by.set,Po.intTime,Po.floatTime,Po.timestamp];Eu.schema=wy});var $u=T(Ro=>{"use strict";var Cu=At(),vy=Jn(),Ru=Tt(),Sy=gr(),xy=io(),Oo=ao(),Co=lo(),ky=su(),Ey=au(),Nu=ho(),Sr=$n(),_u=bo(),Iu=zn(),Tu=Au(),Lu=ko(),ss=Ao(),Pu=new Map([["core",ky.schema],["failsafe",[Cu.map,Ru.seq,Sy.string]],["json",Ey.schema],["yaml11",Tu.schema],["yaml-1.1",Tu.schema]]),Ou={binary:Nu.binary,bool:xy.boolTag,float:Oo.float,floatExp:Oo.floatExp,floatNaN:Oo.floatNaN,floatTime:ss.floatTime,int:Co.int,intHex:Co.intHex,intOct:Co.intOct,intTime:ss.intTime,map:Cu.map,merge:Sr.merge,null:vy.nullTag,omap:_u.omap,pairs:Iu.pairs,seq:Ru.seq,set:Lu.set,timestamp:ss.timestamp},Ay={"tag:yaml.org,2002:binary":Nu.binary,"tag:yaml.org,2002:merge":Sr.merge,"tag:yaml.org,2002:omap":_u.omap,"tag:yaml.org,2002:pairs":Iu.pairs,"tag:yaml.org,2002:set":Lu.set,"tag:yaml.org,2002:timestamp":ss.timestamp};function Ty(r,e,t){let n=Pu.get(e);if(n&&!r)return t&&!n.includes(Sr.merge)?n.concat(Sr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Pu.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(Sr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Ou[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ou).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Ro.coreKnownTags=Ay;Ro.getTags=Ty});var Io=T(Mu=>{"use strict";var No=_(),Py=At(),Oy=Tt(),Cy=gr(),is=$u(),Ry=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,_o=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?is.getTags(e,"compat"):e?is.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?is.coreKnownTags:{},this.tags=is.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,No.MAP,{value:Py.map}),Object.defineProperty(this,No.SCALAR,{value:Cy.string}),Object.defineProperty(this,No.SEQ,{value:Oy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ry:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Mu.Schema=_o});var Bu=T(Du=>{"use strict";var Ny=_(),Lo=dr(),xr=cr();function _y(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=Lo.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(xr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Ny.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(xr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Lo.stringify(r.contents,s,()=>a=null,c);a&&(l+=xr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Lo.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
65
|
+
${i.comment}`:n.comment}n=s}r.items[t]=zn.isPair(n)?n:new yo.Pair(n)}}else e("Expected a sequence for this tag");return r}function fu(r,e,t){let{replacer:n}=t,s=new Qg.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(yo.createPair(a,c,t))}return s}var Xg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:uu,createNode:fu};Qn.createPairs=fu;Qn.pairs=Xg;Qn.resolvePairs=uu});var vo=T(wo=>{"use strict";var du=_(),bo=Ie(),br=je(),Zg=Fe(),pu=Xn(),et=class r extends Zg.YAMLSeq{constructor(){super(),this.add=br.YAMLMap.prototype.add.bind(this),this.delete=br.YAMLMap.prototype.delete.bind(this),this.get=br.YAMLMap.prototype.get.bind(this),this.has=br.YAMLMap.prototype.has.bind(this),this.set=br.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(du.isPair(s)?(i=bo.toJS(s.key,"",t),o=bo.toJS(s.value,i,t)):i=bo.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=pu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};et.tag="tag:yaml.org,2002:omap";var ey={collection:"seq",identify:r=>r instanceof Map,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=pu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)du.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)};wo.YAMLOMap=et;wo.omap=ey});var bu=T(So=>{"use strict";var hu=U();function mu({value:r,source:e},t){return e&&(r?gu:yu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var gu={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 hu.Scalar(!0),stringify:mu},yu={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 hu.Scalar(!1),stringify:mu};So.falseTag=yu;So.trueTag=gu});var wu=T(Zn=>{"use strict";var ty=U(),xo=Pt(),ry={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:xo.stringifyNumber},ny={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():xo.stringifyNumber(r)}},sy={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 ty.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:xo.stringifyNumber};Zn.float=sy;Zn.floatExp=ny;Zn.floatNaN=ry});var Su=T(vr=>{"use strict";var vu=Pt(),wr=r=>typeof r=="bigint"||Number.isInteger(r);function es(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 ko(r,e,t){let{value:n}=r;if(wr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return vu.stringifyNumber(r)}var iy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>es(r,2,2,t),stringify:r=>ko(r,2,"0b")},oy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>es(r,1,8,t),stringify:r=>ko(r,8,"0")},ay={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>es(r,0,10,t),stringify:vu.stringifyNumber},cy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>es(r,2,16,t),stringify:r=>ko(r,16,"0x")};vr.int=ay;vr.intBin=iy;vr.intHex=cy;vr.intOct=oy});var Ao=T(Eo=>{"use strict";var ns=_(),ts=De(),rs=je(),tt=class r extends rs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ns.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ts.Pair(e.key,null):t=new ts.Pair(e,null),rs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=rs.findPair(this.items,e);return!t&&ns.isPair(n)?ns.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=rs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ts.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(ts.createPair(o,null,n));return i}};tt.tag="tag:yaml.org,2002:set";var ly={collection:"map",identify:r=>r instanceof Set,nodeClass:tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>tt.from(r,e,t),resolve(r,e){if(ns.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Eo.YAMLSet=tt;Eo.set=ly});var Po=T(ss=>{"use strict";var uy=Pt();function To(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 xu(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return uy.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 fy={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})=>To(r,t),stringify:xu},dy={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=>To(r,!1),stringify:xu},ku={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(ku.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=To(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ss.floatTime=dy;ss.intTime=fy;ss.timestamp=ku});var Tu=T(Au=>{"use strict";var py=At(),hy=Wn(),my=Tt(),gy=gr(),yy=go(),Eu=bu(),Oo=wu(),is=Su(),by=Dn(),wy=vo(),vy=Xn(),Sy=Ao(),Co=Po(),xy=[py.map,my.seq,gy.string,hy.nullTag,Eu.trueTag,Eu.falseTag,is.intBin,is.intOct,is.int,is.intHex,Oo.floatNaN,Oo.floatExp,Oo.float,yy.binary,by.merge,wy.omap,vy.pairs,Sy.set,Co.intTime,Co.floatTime,Co.timestamp];Au.schema=xy});var Mu=T(_o=>{"use strict";var Ru=At(),ky=Wn(),Nu=Tt(),Ey=gr(),Ay=ao(),Ro=lo(),No=fo(),Ty=iu(),Py=cu(),_u=go(),Sr=Dn(),Iu=vo(),Lu=Xn(),Pu=Tu(),$u=Ao(),os=Po(),Ou=new Map([["core",Ty.schema],["failsafe",[Ru.map,Nu.seq,Ey.string]],["json",Py.schema],["yaml11",Pu.schema],["yaml-1.1",Pu.schema]]),Cu={binary:_u.binary,bool:Ay.boolTag,float:Ro.float,floatExp:Ro.floatExp,floatNaN:Ro.floatNaN,floatTime:os.floatTime,int:No.int,intHex:No.intHex,intOct:No.intOct,intTime:os.intTime,map:Ru.map,merge:Sr.merge,null:ky.nullTag,omap:Iu.omap,pairs:Lu.pairs,seq:Nu.seq,set:$u.set,timestamp:os.timestamp},Oy={"tag:yaml.org,2002:binary":_u.binary,"tag:yaml.org,2002:merge":Sr.merge,"tag:yaml.org,2002:omap":Iu.omap,"tag:yaml.org,2002:pairs":Lu.pairs,"tag:yaml.org,2002:set":$u.set,"tag:yaml.org,2002:timestamp":os.timestamp};function Cy(r,e,t){let n=Ou.get(e);if(n&&!r)return t&&!n.includes(Sr.merge)?n.concat(Sr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Ou.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(Sr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Cu[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Cu).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}_o.coreKnownTags=Oy;_o.getTags=Cy});var $o=T(Du=>{"use strict";var Io=_(),Ry=At(),Ny=Tt(),_y=gr(),as=Mu(),Iy=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Lo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?as.getTags(e,"compat"):e?as.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?as.coreKnownTags:{},this.tags=as.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Io.MAP,{value:Ry.map}),Object.defineProperty(this,Io.SCALAR,{value:_y.string}),Object.defineProperty(this,Io.SEQ,{value:Ny.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Iy:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Du.Schema=Lo});var ju=T(Bu=>{"use strict";var Ly=_(),Mo=dr(),xr=cr();function $y(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=Mo.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(xr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Ly.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(xr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Mo.stringify(r.contents,s,()=>a=null,c);a&&(l+=xr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Mo.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
66
|
`)?(t.push("..."),t.push(xr.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(xr.indentComment(i(c),"")))}return t.join(`
|
|
67
67
|
`)+`
|
|
68
|
-
`}
|
|
68
|
+
`}Bu.stringifyDocument=$y});var kr=T(Fu=>{"use strict";var My=or(),Ot=On(),ae=_(),Dy=De(),By=Ie(),jy=$o(),Fy=ju(),Do=En(),qy=Fi(),Uy=ar(),Bo=ji(),jo=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ae.NODE_TYPE,{value:ae.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 Bo.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,{[ae.NODE_TYPE]:{value:ae.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=ae.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ct(this.contents)&&this.contents.add(e)}addIn(e,t){Ct(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Do.anchorNames(this);e.anchor=!t||n.has(t)?Do.findNewAnchor(t||"a",n):t}return new My.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 y=A=>typeof A=="number"||A instanceof String||A instanceof Number,S=t.filter(y).map(String);S.length>0&&(t=t.concat(S)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:p}=Do.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},h=Uy.createNode(e,d,m);return a&&ae.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Dy.Pair(s,i)}delete(e){return Ct(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ot.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Ct(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ot.isEmptyPath(e)?!t&&ae.isScalar(this.contents)?this.contents.value:this.contents:ae.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ot.isEmptyPath(e)?this.contents!==void 0:ae.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ot.collectionFromPath(this.schema,[e],t):Ct(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ot.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ot.collectionFromPath(this.schema,Array.from(e),t):Ct(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 Bo.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 Bo.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 jy.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=By.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:d}of a.anchors.values())i(d,l);return typeof o=="function"?qy.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 Fy.stringifyDocument(this,e)}};function Ct(r){if(ae.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Fu.Document=jo});var Tr=T(Ar=>{"use strict";var Er=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Fo=class extends Er{constructor(e,t,n){super("YAMLParseError",e,t,n)}},qo=class extends Er{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Jy=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
69
69
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:
|
|
70
70
|
|
|
71
71
|
${o}
|
|
72
72
|
${l}
|
|
73
|
-
`}};Ar.YAMLError=Er;Ar.YAMLParseError=
|
|
74
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(
|
|
75
|
-
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||
|
|
76
|
-
`+g.comment:
|
|
77
|
-
`+
|
|
78
|
-
`+P:
|
|
79
|
-
`+L.comment:
|
|
80
|
-
`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}
|
|
81
|
-
`.repeat(Math.max(1,o.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:h,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let h=0;h<a;++h){let[y,
|
|
82
|
-
`;for(let h=d;h<a;++h){let[y,
|
|
83
|
-
`):y.length>c||
|
|
73
|
+
`}};Ar.YAMLError=Er;Ar.YAMLParseError=Fo;Ar.YAMLWarning=qo;Ar.prettifyError=Jy});var Pr=T(qu=>{"use strict";function Ky(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,m=!1,h=null,y=null,S=null,A=null,g=null,b=null,v=null;for(let k of r)switch(m&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&i(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),d=!0;break;case"comment":{d||i(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=k.source.substring(1)||" ";u?u+=f+L:u=L,f="",l=!1;break}case"newline":l?u?u+=k.source:(!b||t!=="seq-item-ind")&&(c=!0):f+=k.source,l=!0,p=!0,(y||S)&&(A=k),d=!0;break;case"anchor":y&&i(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&i(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=k,v??(v=k.offset),l=!1,d=!1,m=!0;break;case"tag":{S&&i(k,"MULTIPLE_TAGS","A node can have at most one tag"),S=k,v??(v=k.offset),l=!1,d=!1,m=!0;break}case t:(y||S)&&i(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&i(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),b=k,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){g&&i(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),g=k,l=!1,d=!1;break}default:i(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,d=!1}let x=r[r.length-1],P=x?x.offset+x.source.length:s;return m&&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"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:g,found:b,spaceBefore:c,comment:u,hasNewline:p,anchor:y,tag:S,newlineAfterProp:A,end:P,start:v??P}}qu.resolveProps=Ky});var cs=T(Uu=>{"use strict";function Uo(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
|
74
|
+
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Uo(e.key)||Uo(e.value))return!0}return!1;default:return!0}}Uu.containsNewline=Uo});var Jo=T(Ju=>{"use strict";var Wy=cs();function Hy(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Wy.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ju.flowIndentCheck=Hy});var Ko=T(Wu=>{"use strict";var Ku=_();function Vy(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Ku.isScalar(i)&&Ku.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Wu.mapIncludes=Vy});var Qu=T(zu=>{"use strict";var Hu=De(),Yy=je(),Vu=Pr(),Gy=cs(),Yu=Jo(),zy=Ko(),Gu="All mapping items must start at the same column";function Qy({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Yy.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:p,value:m}=d,h=Vu.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&s(c,"BAD_INDENT",Gu)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=`
|
|
75
|
+
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Gy.containsNewline(f))&&s(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&s(c,"BAD_INDENT",Gu);t.atKey=!0;let S=h.end,A=f?r(t,f,h,s):e(t,S,u,null,h,s);t.schema.compat&&Yu.flowIndentCheck(n.indent,f,s),t.atKey=!1,zy.mapIncludes(t,a.items,A)&&s(S,"DUPLICATE_KEY","Map keys must be unique");let g=Vu.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=g.end,g.found){y&&(m?.type==="block-map"&&!g.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<g.found.offset-1024&&s(A.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?r(t,m,g,s):e(t,c,p,null,g,s);t.schema.compat&&Yu.flowIndentCheck(n.indent,m,s),c=b.range[2];let v=new Hu.Pair(A,b);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}else{y&&s(A.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(A.comment?A.comment+=`
|
|
76
|
+
`+g.comment:A.comment=g.comment);let b=new Hu.Pair(A);t.options.keepSourceTokens&&(b.srcToken=d),a.items.push(b)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}zu.resolveBlockMap=Qy});var Zu=T(Xu=>{"use strict";var Xy=Fe(),Zy=Pr(),eb=Jo();function tb({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Xy.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:d,value:u}of n.items){let f=Zy.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let p=u?r(t,u,f,s):e(t,f.end,d,null,f,s);t.schema.compat&&eb.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Xu.resolveBlockSeq=tb});var Rt=T(ef=>{"use strict";function rb(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";s?s+=o+d:s=d,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}ef.resolveEnd=rb});var sf=T(nf=>{"use strict";var nb=_(),sb=De(),tf=je(),ib=Fe(),ob=Rt(),rf=Pr(),ab=cs(),cb=Ko(),Wo="Block collections are not allowed within flow collections",Ho=r=>r&&(r.type==="block-map"||r.type==="block-seq");function lb({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?tf.YAMLMap:ib.YAMLSeq),l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){let S=n.items[y],{start:A,key:g,sep:b,value:v}=S,x=rf.resolveProps(A,{flow:a,indicator:"explicit-key-ind",next:g??b?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!b&&!v){y===0&&x.comma?s(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&s(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(l.comment?l.comment+=`
|
|
77
|
+
`+x.comment:l.comment=x.comment),u=x.end;continue}!o&&t.options.strict&&ab.containsNewline(g)&&s(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)x.comma&&s(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(x.comma||s(x.start,"MISSING_CHAR",`Missing , between ${a} items`),x.comment){let P="";e:for(let k of A)switch(k.type){case"comma":case"space":break;case"comment":P=k.source.substring(1);break e;default:break e}if(P){let k=l.items[l.items.length-1];nb.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
78
|
+
`+P:k.comment=P,x.comment=x.comment.substring(P.length+1)}}if(!o&&!b&&!x.found){let P=v?r(t,v,x,s):e(t,x.end,b,null,x,s);l.items.push(P),u=P.range[2],Ho(v)&&s(P.range,"BLOCK_IN_FLOW",Wo)}else{t.atKey=!0;let P=x.end,k=g?r(t,g,x,s):e(t,P,A,null,x,s);Ho(g)&&s(k.range,"BLOCK_IN_FLOW",Wo),t.atKey=!1;let L=rf.resolveProps(b??[],{flow:a,indicator:"map-value-ind",next:v,offset:k.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(L.found){if(!o&&!x.found&&t.options.strict){if(b)for(let B of b){if(B===L.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<L.found.offset-1024&&s(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else v&&("source"in v&&v.source?.[0]===":"?s(v,"MISSING_CHAR",`Missing space after : in ${a}`):s(L.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Q=v?r(t,v,L,s):L.found?e(t,L.end,b,null,L,s):null;Q?Ho(v)&&s(Q.range,"BLOCK_IN_FLOW",Wo):L.comment&&(k.comment?k.comment+=`
|
|
79
|
+
`+L.comment:k.comment=L.comment);let V=new sb.Pair(k,Q);if(t.options.keepSourceTokens&&(V.srcToken=S),o){let B=l;cb.mapIncludes(t,B.items,k)&&s(P,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(V)}else{let B=new tf.YAMLMap(t.schema);B.flow=!0,B.items.push(V);let w=(Q??k).range;B.range=[k.range[0],w[1],w[2]],l.items.push(B)}u=Q?Q.range[2]:L.end}}let f=o?"}":"]",[p,...m]=n.end,h=u;if(p?.source===f)h=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),S=d?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;s(u,d?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let y=ob.resolveEnd(m,h,t.options.strict,s);y.comment&&(l.comment?l.comment+=`
|
|
80
|
+
`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}nf.resolveFlowCollection=lb});var af=T(of=>{"use strict";var ub=_(),fb=U(),db=je(),pb=Fe(),hb=Qu(),mb=Zu(),gb=sf();function Vo(r,e,t,n,s,i){let o=t.type==="block-map"?hb.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?mb.resolveBlockSeq(r,e,t,n,i):gb.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 yb(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!p||p.offset<m.offset)&&s(m,"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===db.YAMLMap.tagName&&a==="map"||o===pb.YAMLSeq.tagName&&a==="seq")return Vo(r,e,t,s,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Vo(r,e,t,s,o)}let l=Vo(r,e,t,s,o,c),d=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=ub.isNode(d)?d:new fb.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}of.composeCollection=yb});var Go=T(cf=>{"use strict";var Yo=U();function bb(r,e,t){let n=e.offset,s=wb(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?Yo.Scalar.BLOCK_FOLDED:Yo.Scalar.BLOCK_LITERAL,o=e.source?vb(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&o.length>0?`
|
|
81
|
+
`.repeat(Math.max(1,o.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:h,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let h=0;h<a;++h){let[y,S]=o[h];if(S===""||S==="\r")s.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=y.length),d=h,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+S.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(c)+`
|
|
82
|
+
`;for(let h=d;h<a;++h){let[y,S]=o[h];l+=y.length+S.length+1;let A=S[S.length-1]==="\r";if(A&&(S=S.slice(0,-1)),S&&y.length<c){let b=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-S.length-(A?2:1),"BAD_INDENT",b),y=""}i===Yo.Scalar.BLOCK_LITERAL?(u+=f+y.slice(c)+S,f=`
|
|
83
|
+
`):y.length>c||S[0]===" "?(f===" "?f=`
|
|
84
84
|
`:!p&&f===`
|
|
85
85
|
`&&(f=`
|
|
86
86
|
|
|
87
|
-
`),u+=f+y.slice(c)+
|
|
88
|
-
`,p=!0):
|
|
87
|
+
`),u+=f+y.slice(c)+S,f=`
|
|
88
|
+
`,p=!0):S===""?f===`
|
|
89
89
|
`?u+=`
|
|
90
90
|
`:f=`
|
|
91
|
-
`:(u+=f+
|
|
91
|
+
`:(u+=f+S,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let h=a;h<o.length;++h)u+=`
|
|
92
92
|
`+o[h][0].slice(c);u[u.length-1]!==`
|
|
93
93
|
`&&(u+=`
|
|
94
94
|
`);break;default:u+=`
|
|
95
|
-
`}let m=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,m,m]}}function
|
|
95
|
+
`}let m=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,m,m]}}function wb({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let f=1;f<s.length;++f){let p=s[f];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=r+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,d="",u=s.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,d=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function vb(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}cf.resolveBlockScalar=bb});var Qo=T(uf=>{"use strict";var zo=U(),Sb=Rt();function xb(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(f,p,m)=>t(n+f,p,m);switch(s){case"scalar":a=zo.Scalar.PLAIN,c=kb(i,l);break;case"single-quoted-scalar":a=zo.Scalar.QUOTE_SINGLE,c=Eb(i,l);break;case"double-quoted-scalar":a=zo.Scalar.QUOTE_DOUBLE,c=Ab(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let d=n+i.length,u=Sb.resolveEnd(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function kb(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}`),lf(r)}function Eb(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),lf(r.slice(1,-1)).replace(/''/g,"'")}function lf(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
96
96
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
97
97
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===`
|
|
98
98
|
`?s+=i:i=`
|
|
99
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
99
|
+
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function Ab(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
100
100
|
`))if(s===`
|
|
101
|
-
`){let{fold:i,offset:o}=
|
|
101
|
+
`){let{fold:i,offset:o}=Tb(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=Pb[i];if(o)t+=o;else if(i===`
|
|
102
102
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
103
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
103
|
+
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=Ob(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
104
104
|
`&&!(o==="\r"&&r[n+2]===`
|
|
105
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
105
|
+
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function Tb(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
106
106
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
107
107
|
`);)n===`
|
|
108
108
|
`&&(t+=`
|
|
109
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
110
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
109
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var Pb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
110
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ob(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)}uf.resolveFlowScalar=xb});var pf=T(df=>{"use strict";var rt=_(),ff=U(),Cb=Go(),Rb=Qo();function Nb(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Cb.resolveBlockScalar(r,e,n):Rb.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[rt.SCALAR]:c?l=_b(r.schema,s,c,t,n):e.type==="scalar"?l=Ib(r,s,e,n):l=r.schema[rt.SCALAR];let d;try{let u=l.resolve(s,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);d=rt.isScalar(u)?u:new ff.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",f),d=new ff.Scalar(s)}return d.range=a,d.source=s,i&&(d.type=i),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function _b(r,e,t,n,s){if(t==="!")return r[rt.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[rt.SCALAR])}function Ib({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[rt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[rt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}df.composeScalar=Nb});var mf=T(hf=>{"use strict";function Lb(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=Lb});var bf=T(Zo=>{"use strict";var $b=or(),Mb=_(),Db=af(),gf=pf(),Bb=Rt(),jb=mf(),Fb={composeNode:yf,composeEmptyNode:Xo};function yf(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=qb(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=gf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Db.composeCollection(Fb,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=Xo(r,e.offset,void 0,null,t,n),d=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!Mb.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&d&&(l.srcToken=e),l}function Xo(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:jb.emptyScalarPosition(e,t,n),indent:-1,source:""},u=gf.composeScalar(r,d,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function qb({options:r},{offset:e,source:t,end:n},s){let i=new $b.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=Bb.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Zo.composeEmptyNode=Xo;Zo.composeNode=yf});var Sf=T(vf=>{"use strict";var Ub=kr(),wf=bf(),Jb=Rt(),Kb=Pr();function Wb(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new Ub.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Kb.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?wf.composeNode(l,s,d,o):wf.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=Jb.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}vf.composeDoc=Wb});var ta=T(Ef=>{"use strict";var Hb=gn("process"),Vb=ji(),Yb=kr(),Or=Tr(),xf=_(),Gb=Sf(),zb=Rt();function Cr(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 kf(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
111
111
|
|
|
112
112
|
`:`
|
|
113
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
114
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
113
|
+
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var ea=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=Cr(t);i?this.warnings.push(new Or.YAMLWarning(o,n,s)):this.errors.push(new Or.YAMLParseError(o,n,s))},this.directives=new Vb.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=kf(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
114
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(xf.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];xf.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
115
115
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
116
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
117
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Or.YAMLParseError(Cr(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new
|
|
116
|
+
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:kf(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(Hb.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=Cr(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Gb.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 Or.YAMLParseError(Cr(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 Or.YAMLParseError(Cr(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=zb.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
117
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Or.YAMLParseError(Cr(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 Yb.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}}};Ef.Composer=ea});var Pf=T(ls=>{"use strict";var Qb=Go(),Xb=Qo(),Zb=Tr(),Af=fr();function ew(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 Zb.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Xb.resolveFlowScalar(r,e,n);case"block-scalar":return Qb.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function tw(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Af.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
118
118
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
119
119
|
`),d=a.substring(0,l),u=a.substring(l+1)+`
|
|
120
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return
|
|
121
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function
|
|
120
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return Tf(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
121
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:f,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function rw(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=Af.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">":nw(r,c);break;case'"':ra(r,c,"double-quoted-scalar");break;case"'":ra(r,c,"single-quoted-scalar");break;default:ra(r,c,"scalar")}}function nw(r,e){let t=e.indexOf(`
|
|
122
122
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
123
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
124
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
125
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}
|
|
123
|
+
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];Tf(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
124
|
+
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function Tf(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 ra(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let n=r.props.slice(1),s=e.length;r.props[0].type==="block-scalar-header"&&(s-=r.props[0].source.length);for(let i of n)i.offset+=s;delete r.props,Object.assign(r,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{let s={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
|
|
125
|
+
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}ls.createScalarToken=tw;ls.resolveAsScalar=ew;ls.setScalarValue=rw});var Cf=T(Of=>{"use strict";var sw=r=>"type"in r?fs(r):us(r);function fs(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=fs(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=us(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=us(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=us(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 us({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=fs(e)),t)for(let i of t)s+=i.source;return n&&(s+=fs(n)),s}Of.stringify=sw});var If=T(_f=>{"use strict";var na=Symbol("break visit"),iw=Symbol("skip children"),Rf=Symbol("remove item");function nt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Nf(Object.freeze([]),r,e)}nt.BREAK=na;nt.SKIP=iw;nt.REMOVE=Rf;nt.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};nt.parentCollection=(r,e)=>{let t=nt.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 Nf(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=Nf(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===na)return na;a===Rf&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}_f.visit=nt});var ds=T(re=>{"use strict";var sa=Pf(),ow=Cf(),aw=If(),ia="\uFEFF",oa="",aa="",ca="",cw=r=>!!r&&"items"in r,lw=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function uw(r){switch(r){case ia:return"<BOM>";case oa:return"<DOC>";case aa:return"<FLOW_END>";case ca:return"<SCALAR>";default:return JSON.stringify(r)}}function fw(r){switch(r){case ia:return"byte-order-mark";case oa:return"doc-mode";case aa:return"flow-error-end";case ca:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
126
126
|
`:case`\r
|
|
127
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}re.createScalarToken=
|
|
128
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
129
|
-
\r `),
|
|
127
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}re.createScalarToken=sa.createScalarToken;re.resolveAsScalar=sa.resolveAsScalar;re.setScalarValue=sa.setScalarValue;re.stringify=ow.stringify;re.visit=aw.visit;re.BOM=ia;re.DOCUMENT=oa;re.FLOW_END=aa;re.SCALAR=ca;re.isCollection=cw;re.isScalar=lw;re.prettyToken=uw;re.tokenType=fw});var fa=T($f=>{"use strict";var Rr=ds();function de(r){switch(r){case void 0:case" ":case`
|
|
128
|
+
`:case"\r":case" ":return!0;default:return!1}}var Lf=new Set("0123456789ABCDEFabcdef"),dw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ps=new Set(",[]{}"),pw=new Set(` ,[]{}
|
|
129
|
+
\r `),la=r=>!r||pw.has(r),ua=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
130
130
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
131
131
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
132
132
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
133
133
|
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&de(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
134
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Rr.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 Rr.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==="...")&&de(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&&!de(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===":")&&de(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(
|
|
134
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Rr.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 Rr.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==="...")&&de(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&&!de(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===":")&&de(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(la),"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("..."))&&de(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Rr.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(la),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||de(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
135
135
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
136
136
|
`,i)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>de(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
137
137
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
138
138
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
139
139
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
140
140
|
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
141
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Rr.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(de(i)||e&&
|
|
141
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Rr.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(de(i)||e&&ps.has(i))break;t=n}else if(de(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
142
142
|
`?(n+=1,s=`
|
|
143
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
144
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
143
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&ps.has(i))break;if(s===`
|
|
144
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&ps.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Rr.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(la))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(de(t)||e&&ps.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!de(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(dw.has(t))t=this.buffer[++e];else if(t==="%"&&Lf.has(this.buffer[e+1])&&Lf.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
145
145
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
146
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}
|
|
146
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};$f.Lexer=ua});var pa=T(Mf=>{"use strict";var da=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}}}};Mf.LineCounter=da});var ma=T(qf=>{"use strict";var hw=gn("process"),Df=ds(),mw=fa();function qe(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Bf(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 Ff(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 hs(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 Nt(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 jf(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!qe(e.start,"explicit-key-ind")&&!qe(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ff(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 ha=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 mw.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,hw.env.LOG_TOKENS&&console.log("|",Df.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Df.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"&&jf(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&&Bf(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":{Bf(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=hs(this.peek(2)),n=Nt(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
147
147
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
148
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(qe(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(
|
|
148
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(qe(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(Ff(t.key)&&!qe(t.sep,"newline")){let o=Nt(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(qe(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Nt(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]}):qe(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&&!qe(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||qe(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=hs(n),i=Nt(s);jf(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
149
149
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
150
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=
|
|
151
|
-
`),t=e.trim();if(
|
|
150
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=hs(e),n=Nt(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=hs(e),n=Nt(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())}}};qf.Parser=ha});var Hf=T(_r=>{"use strict";var Uf=ta(),gw=kr(),Nr=Tr(),yw=Xi(),bw=_(),ww=pa(),Jf=ma();function Kf(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new ww.LineCounter||null,prettyErrors:e}}function vw(r,e={}){let{lineCounter:t,prettyErrors:n}=Kf(e),s=new Jf.Parser(t?.addNewLine),i=new Uf.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Nr.prettifyError(r,t)),a.warnings.forEach(Nr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Wf(r,e={}){let{lineCounter:t,prettyErrors:n}=Kf(e),s=new Jf.Parser(t?.addNewLine),i=new Uf.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 Nr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Nr.prettifyError(r,t)),o.warnings.forEach(Nr.prettifyError(r,t))),o}function Sw(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Wf(r,t);if(!s)return null;if(s.warnings.forEach(i=>yw.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 xw(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 bw.isDocument(r)&&!n?r.toString(t):new gw.Document(r,n,t).toString(t)}_r.parse=Sw;_r.parseAllDocuments=vw;_r.parseDocument=Wf;_r.stringify=xw});var Yf=T($=>{"use strict";var kw=ta(),Ew=kr(),Aw=$o(),ga=Tr(),Tw=or(),Ue=_(),Pw=De(),Ow=U(),Cw=je(),Rw=Fe(),Nw=ds(),_w=fa(),Iw=pa(),Lw=ma(),ms=Hf(),Vf=rr();$.Composer=kw.Composer;$.Document=Ew.Document;$.Schema=Aw.Schema;$.YAMLError=ga.YAMLError;$.YAMLParseError=ga.YAMLParseError;$.YAMLWarning=ga.YAMLWarning;$.Alias=Tw.Alias;$.isAlias=Ue.isAlias;$.isCollection=Ue.isCollection;$.isDocument=Ue.isDocument;$.isMap=Ue.isMap;$.isNode=Ue.isNode;$.isPair=Ue.isPair;$.isScalar=Ue.isScalar;$.isSeq=Ue.isSeq;$.Pair=Pw.Pair;$.Scalar=Ow.Scalar;$.YAMLMap=Cw.YAMLMap;$.YAMLSeq=Rw.YAMLSeq;$.CST=Nw;$.Lexer=_w.Lexer;$.LineCounter=Iw.LineCounter;$.Parser=Lw.Parser;$.parse=ms.parse;$.parseAllDocuments=ms.parseAllDocuments;$.parseDocument=ms.parseDocument;$.stringify=ms.stringify;$.visit=Vf.visit;$.visitAsync=Vf.visitAsync});function Mw(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Dw(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match($w);return t?tr(e,t[1])!==null:!1}function Bw(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Gf.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function zf(r){return Mw(r)||Dw(r)||Bw(r)}var Gf,$w,ya=C(()=>{il();Gf=Hh(Yf(),1),$w=/<([a-zA-Z_][\w.-]*)/});function jw(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
151
|
+
`),t=e.trim();if(zf(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
152
152
|
`).length}];let n=e.split(`
|
|
153
153
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
154
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function
|
|
155
|
-
`))for(let s of
|
|
156
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
154
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function ba(r){return jw(r).map(e=>e.text)}var Qf=C(()=>{ya()});var Ir=C(()=>{yn();Yc();zc();Xc();ya();Qf();bn()});function gs(r){return{...Vc(r),server:r.files.get("server.ts")??""}}var wa=C(()=>{Ir();Ir();Ir()});function Zf(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 ed(r){let e=[],t=new Set;for(let n of r.split(`
|
|
155
|
+
`))for(let s of Xf)for(let i of n.matchAll(s)){let o=Zf(i[1]);o&&!t.has(o)&&(t.add(o),e.push(o))}return e}function Lr(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
156
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of qw)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Kw(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...Uw(i,n)),s}function Uw(r,e){let t=new Set(Object.keys(e)),n=new Set,s=[];for(let i=0;i<r.length;i++)for(let o of Xf)for(let a of r[i].matchAll(o)){let c=Zf(a[1]);!c||t.has(c)||n.has(c)||(n.add(c),s.push({type:"UNDECLARED_IMPORT",severity:"error",message:Jw(c,i+1),lineNumber:i+1,lineContent:r[i]}))}return s}function Jw(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
157
157
|
|
|
158
158
|
**CRITICAL**: Every bare import in code.tsx must be declared in the **config.json** "dependencies" block. A bulb that imports a package it doesn't declare is incomplete \u2014 it won't type-check, its versions aren't pinned, and it can't be reliably re-run or ported to typebulb.com.
|
|
159
159
|
|
|
@@ -167,7 +167,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
167
167
|
}
|
|
168
168
|
\`\`\`
|
|
169
169
|
|
|
170
|
-
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function
|
|
170
|
+
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function Kw(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
171
171
|
|
|
172
172
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
173
173
|
|
|
@@ -321,14 +321,14 @@ import { something } from 'module-name'
|
|
|
321
321
|
const something = require('module-name') // NOT SUPPORTED!
|
|
322
322
|
\`\`\`
|
|
323
323
|
|
|
324
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var st,it,
|
|
325
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
326
|
-
`)}function
|
|
327
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}var
|
|
328
|
-
`):r==null?"":ke(JSON.stringify(r))}function
|
|
324
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var st,it,qw,Xf,ys=C(()=>{st=["client"],it=["client","server"],qw=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:st},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:it},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:st},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:st},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:st},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:it},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:it},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:it},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:it},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:it},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:it},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:st},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:st},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:st}],Xf=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{realpathSync as Ov}from"fs";import{join as $a,resolve as Cv}from"path";import{homedir as Rv}from"os";function $s(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?$a(r,".."):$a(Rv(),".typebulb")}function Ce(){return process.env.TYPEBULB_SERVERS_DIR||$a($s(),"servers")}function J(r){let e=Cv(r),t=e;try{t=Ov.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Id(r,e){let t=J(r),n=J(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Qr=C(()=>{});import{readFileSync as Nv,writeFileSync as _v,mkdirSync as Iv}from"fs";import{join as Lv}from"path";function Ld(){return Lv($s(),"trust.json")}function Ma(){try{let r=JSON.parse(Nv(Ld(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function $v(r){Iv($s(),{recursive:!0}),_v(Ld(),JSON.stringify([...r]))}function lt(r){return Ma().has(J(r))}function jt(r,e){let t=Ma(),n=J(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),$v(t))}function Da(){return[...Ma()]}var Xr=C(()=>{Qr()});function Ut(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var js=C(()=>{});import{spawn as Hd}from"child_process";import{readdir as sS,readFile as Yd,writeFile as Gd,unlink as ut,mkdir as iS}from"fs/promises";import{mkdirSync as zd,writeFileSync as Fs,appendFileSync as oS,readFileSync as ja}from"fs";import*as ue from"path";import{fileURLToPath as aS}from"url";function Fa(r){return ue.join(Ce(),`${r}.json`)}function Jt(r){return ue.join(Ce(),`${r}.log`)}function qs(r){return ue.join(Ce(),`${r}.wait.json`)}function Qd(r){try{let e=JSON.parse(ja(qs(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:typeof e.offset=="number"?{"":e.offset}:{}}catch{return{}}}function qa(r,e=""){let t=Qd(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Us(r,e,t=""){try{zd(Ce(),{recursive:!0});let n=Qd(r);n[t]=e,Fs(qs(r),JSON.stringify({cursors:n}))}catch{}}function Js(r){let e=Jt(r);try{zd(Ce(),{recursive:!0}),Fs(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(oS(e,c),s+=c.length,s>2*Vd){let l=ja(e),d=l.subarray(Math.max(0,l.length-Vd));Fs(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Xd(r){try{Fs(Jt(r),"")}catch{}}function xe(r,e=0){try{let t=ja(Jt(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 Ua(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function lS(r){let e=cS.exec(r);return e?Number(e[1]):void 0}function Zd(r,e){let t=r.split(`
|
|
325
|
+
`),n=[];if(t.forEach((o,a)=>{let c=lS(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(`
|
|
326
|
+
`)}function Ja(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Ks(r){await iS(Ce(),{recursive:!0}),await Gd(Fa(r.pid),JSON.stringify(r))}async function ep(r,e){let t=Fa(r);try{let n=JSON.parse(await Yd(t,"utf8"));if(n.denied===e)return;n.denied=e,await Gd(t,JSON.stringify(n))}catch{}}async function tn(r){await ut(Fa(r)).catch(()=>{}),await ut(Jt(r)).catch(()=>{}),await ut(qs(r)).catch(()=>{})}async function K(r){let e;try{e=await sS(Ce())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=ue.join(Ce(),s),o;try{o=JSON.parse(await Yd(i,"utf8"))}catch{await ut(i).catch(()=>{});return}o&&typeof o.pid=="number"&&Ja(o.pid)?t.push(o):(await ut(i).catch(()=>{}),o?.pid&&(await ut(Jt(o.pid)).catch(()=>{}),await ut(qs(o.pid)).catch(()=>{})))})),(r?t.filter(s=>s.agent==null&&Id(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function rn(r,e){let t=J(r);return(await K()).find(n=>n.cwd!=null&&J(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function ft(r){try{process.kill(r,"SIGTERM")}catch{}await tn(r)}function Ws(r,e){let t=J(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&J(n.file)===t)}async function Ka(r){let e=Ws(await K(),r);for(let t of e)await ft(t.pid);return e}function fS(r,e,t){(process.platform==="win32"?Hd("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Hd(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function tp(){return ue.join(ue.dirname(aS(import.meta.url)),"index.js")}function dS(r,e={}){return{command:process.execPath,args:[tp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function pS(r){return{command:process.execPath,args:[tp(),`agent:${r}`,"--no-open"]}}async function rp(r,e,t,n){let s=await r();if(s)return s;fS(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await uS(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Hs(r,e={}){let t=e.cwd??process.cwd(),n=ue.resolve(t,r);return await Ka(n),rp(async()=>Ws(await K(),n)[0],dS(r,e),t,ue.basename(r))}async function np(r,e=process.cwd()){return rp(()=>rn(e,r),pS(r),e,`the ${r} mirror`)}var Vd,cS,uS,ge=C(()=>{Qr();Vd=1e6;cS=/^── run (\d+) ── /;uS=r=>new Promise(e=>setTimeout(e,r))});function ke(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
327
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}var Vs,Ys=C(()=>{Vs=(r,e)=>``});import{existsSync as hS,readdirSync as mS,statSync as gS}from"fs";import{join as yS}from"path";function Gs(r){if(!hS(r))return[];let e;try{e=mS(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=yS(r,n);try{let i=gS(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Wa=C(()=>{});var Kt,Ha=C(()=>{Kt=class{ensureWaitSupport(){}}});import{openSync as bS,readSync as wS,closeSync as vS,statSync as SS,readdirSync as xS,readFileSync as kS}from"fs";import{join as zs}from"path";import{homedir as op}from"os";function ES(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Qs(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Vs(e.data,e.media_type):""}function Va(r){return typeof r=="string"?ke(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return ke(e);let t=e;return typeof t?.text=="string"?ke(t.text):t?.content!=null?Va(t.content):Qs(t)}).join(`
|
|
328
|
+
`):r==null?"":ke(JSON.stringify(r))}function TS(r){let e=r.trim();return!!e&&ap.some(t=>t.test(e))}function PS(r){let e=r.trim();return e?ap.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function CS(r){return r.replace(OS,"")}function RS(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 Ye(r){let e=CS(r).trim();return e?RS(e)??(TS(e)?"":e):""}function Ya(r){return r?.type==="text"&&typeof r.text=="string"?Ye(r.text):""}function nn(r){return!!r.isSidechain||!!r.isMeta}function NS(r){let e;try{e=bS(r,"r")}catch{return""}try{let n=65536;try{n=SS(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=wS(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
329
329
|
`)){if(!p.includes(`"${d}"`))continue;let m;try{m=JSON.parse(p)}catch{continue}let h=m?.[u];m?.type===d&&typeof h=="string"&&h&&(f=h)}return f},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
330
|
-
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||nn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Ye(u):Array.isArray(u)&&(f=u.map(
|
|
331
|
-
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:d,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&Ye(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
|
|
330
|
+
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||nn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Ye(u):Array.isArray(u)&&(f=u.map(Ya).filter(Boolean).join(" "));let p=f.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{vS(e)}}function _S(r){let e;try{e=xS(ip)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(kS(zs(ip,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var AS,sp,ap,OS,ip,Wt,Xs=C(()=>{Ys();Wa();Ha();AS=zs(op(),".claude","projects"),sp=r=>zs(AS,ES(r));ap=[/\[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];OS=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;ip=zs(op(),".claude","sessions");Wt=class extends Kt{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}sessionsDir(e){return sp(e)}listSessionFiles(e){return Gs(sp(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(nn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=Ye(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result")n.push({type:"tool_result",id:i.tool_use_id??"",content:Va(i.content),isError:!!i.is_error});else{let o=Ya(i)||Qs(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=Ye(Va(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=>!PS(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
331
|
+
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:d,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&Ye(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 _S(e)}readPreview(e){return NS(e)}searchText(e){if(!e||nn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=Ye(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Ya).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{existsSync as IS,mkdirSync as LS,writeFileSync as $S}from"fs";import{homedir as MS}from"os";import*as sn from"path";function lp(){try{if(!IS(cp()))return;let r=DS();LS(sn.dirname(r),{recursive:!0}),$S(r,BS)}catch{}}var cp,DS,BS,up=C(()=>{cp=()=>sn.join(MS(),".pi","agent"),DS=()=>sn.join(cp(),"extensions","typebulb-wait.ts"),BS=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
332
332
|
import { spawn } from "node:child_process";
|
|
333
333
|
|
|
334
334
|
function logErr(...a) { try { console.error("[typebulb-wait]", ...a); } catch (e) {} }
|
|
@@ -386,20 +386,20 @@ export default function (pi) {
|
|
|
386
386
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
387
387
|
} catch (e) { logErr("load", e && e.message); }
|
|
388
388
|
}
|
|
389
|
-
`});import{statSync as
|
|
390
|
-
`),c=i.filter(u=>u.type==="toolCall").map(u=>({id:u.id??"",name:u.name??"",input:u.arguments??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=s.usage,d=l&&{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0};return{events:n,usage:d,model:s.model}}return{events:n}}chainWorking(e){let t;for(let a of e)
|
|
391
|
-
`)){if(!u.includes('"type"'))continue;let f;try{f=JSON.parse(u)}catch{continue}f?.type==="session_info"&&typeof f.name=="string"&&f.name?c=f.name:!l&&f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}let d=c||l;return d?d.slice(0,200):""}finally{
|
|
392
|
-
`):""}}});function
|
|
393
|
-
`)}var Yt,
|
|
394
|
-
`))>=0;){let j=w.partial.slice(0,M);if(w.partial=w.partial.slice(M+1),!j.trim())continue;let ie=r.parseEntry(j);if(!ie)continue;let Y=r.idOf(ie);Y&&(w.entries.set(Y,ie),!r.isSidechain(ie)&&r.isLeafType(ie)&&(N=Y))}if(!N)return;let D=[],I=w.entries.get(N),F=!1;for(;I;){if(D.push(I),r.idOf(I)===w.chainLastId){F=!0;break}let j=r.parentOf(I);I=j?w.entries.get(j):void 0}if(F)for(let j=D.length-2;j>=0;j--)
|
|
395
|
-
`)){if(!D.trim())continue;let I=r.parseEntry(D);if(!I)continue;let F=r.searchText(I);F&&N.push({text:F,lower:F.toLowerCase()})}return L.set(w,{mtime:
|
|
396
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=
|
|
397
|
-
`)}function
|
|
389
|
+
`});import{statSync as jS,openSync as FS,readSync as qS,closeSync as US}from"fs";import{join as dp}from"path";import{homedir as JS}from"os";function WS(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function fp(r){return r.type==="message"?HS(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var KS,HS,Ht,Ga=C(()=>{Ys();Wa();Ha();up();KS=dp(JS(),".pi","agent","sessions");HS=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Ht=class extends Kt{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}ensureWaitSupport(){lp()}sessionsDir(e){return dp(KS,WS(e))}listSessionFiles(e){return Gs(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 fp(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")return n.push({type:"tool_result",id:s.toolCallId??"",content:this.contentText(s.content),isError:!!s.isError}),{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(u=>u.type==="text").map(u=>u.text??"").join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
390
|
+
`),c=i.filter(u=>u.type==="toolCall").map(u=>({id:u.id??"",name:u.name??"",input:u.arguments??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=s.usage,d=l&&{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0};return{events:n,usage:d,model:s.model}}return{events:n}}chainWorking(e){let t;for(let a of e)fp(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=FS(e,"r")}catch{return""}try{let s=65536;try{s=jS(e).size}catch{}let i=Buffer.alloc(Math.min(65536,s)),o=qS(t,i,0,i.length,0),a=i.subarray(0,o).toString("utf8"),c="",l="";for(let u of a.split(`
|
|
391
|
+
`)){if(!u.includes('"type"'))continue;let f;try{f=JSON.parse(u)}catch{continue}f?.type==="session_info"&&typeof f.name=="string"&&f.name?c=f.name:!l&&f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}let d=c||l;return d?d.slice(0,200):""}finally{US(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"?ke(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?ke(t.text):t?.type==="image"&&t.data?Vs(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
392
|
+
`):""}}});function Qa(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}async function pt(){let[r,e]=await Promise.all([lx(),cx()]);return[...ux(e),...r]}async function cx(){if(Vt&&Date.now()-Vt.fetchedAt<=ox)return Vt.models;let r=await fetch(ix).catch(()=>null);return!r||!r.ok?Vt?.models??[]:(Vt={models:await r.json(),fetchedAt:Date.now()},Vt.models)}async function lx(){if(ei&&Date.now()-ei.fetchedAt<=ax)return ei.models;let r=Qa(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 ei={models:e,fetchedAt:Date.now()},e}function ux(r){let e=new Set(Object.entries(Yt).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function vp(){return Object.values(Yt).some(r=>!!process.env[r])}function Sp(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(`
|
|
393
|
+
`)}var Yt,ix,ox,ax,Vt,ei,ti=C(()=>{Yt={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};ix="https://api.typebulb.com/api/models",ox=1440*60*1e3,ax=60*1e3,Vt=null,ei=null});function be(r){return r?.message??String(r)}var G,mi=C(()=>{G=process.cwd()});var gi,Kp=C(()=>{gi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function yi(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 fc=C(()=>{});import{existsSync as Wp,openSync as Nx,readSync as _x,closeSync as Ix,statSync as zt,readdirSync as Hp,watchFile as Lx,unwatchFile as Vp,mkdirSync as $x,writeFileSync as Mx,readFileSync as dc,unlinkSync as Dx,rmSync as Bx}from"fs";import{join as Qt}from"path";function bi(r){let e={cwd:G,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=w=>Qt(w,Fx),n=(w,E)=>Qt(t(w),`${E}.lock`);function s(w,E){try{let O=n(w,E);if(Date.now()-zt(O).mtimeMs>=Yp)return!1;try{if(parseInt(dc(O,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function i(w,E){if(E)try{$x(t(w),{recursive:!0}),Mx(n(w,E),String(process.pid))}catch(O){console.error("[lock] claim failed:",be(O))}}function o(w){try{Bx(Qt(w,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function a(w){let E=t(w);if(!Wp(E))return;let O;try{O=Hp(E)}catch{return}let N=Date.now();for(let M of O){if(!M.endsWith(".lock"))continue;let D=Qt(E,M);try{let I=zt(D);N-I.mtimeMs>qx&&Dx(D)}catch{}}}function c(w){try{return zt(w),!1}catch(E){return E.code==="ENOENT"}}function l(){let w=e;if(w.file&&!c(w.file)){i(w.cwd,w.sessionId);return}let E=d(w);E&&p(E)}function d(w){if(!w.everAttached)return u(w.cwd)??f(w.cwd,()=>!0)}function u(w){let E=t(w);if(!Wp(E))return;let O;try{O=Hp(E)}catch{return}let N;for(let D of O)if(D.endsWith(".lock"))try{let I=zt(Qt(E,D));if(Date.now()-I.mtimeMs>=Yp||parseInt(dc(Qt(E,D),"utf8").trim(),10)!==process.pid)continue;(!N||I.mtimeMs>N.mtime)&&(N={sessionId:D.slice(0,-5),mtime:I.mtimeMs})}catch{}if(!N)return;let M=r.listSessionFiles(w).find(D=>D.sessionId===N.sessionId);if(!(!M||c(M.file)))return M}function f(w,E){return r.listSessionFiles(w).sort((O,N)=>N.mtime-O.mtime).find(O=>!s(w,O.sessionId)&&E(O))}function p(w){let E=e;if(E.file)try{Vp(E.file)}catch{}E.file=w.file,E.sessionId=w.sessionId,E.everAttached=!0,E.partial="",E.offset=0,E.latest={in:0,out:0,cached:0,cacheCreate:0},E.latestModel=null,E.entries=new Map,E.chainLastId=void 0,E.buffer.push({type:"cleared"}),E.buffer.push({type:"session",sessionId:w.sessionId}),i(E.cwd,w.sessionId),m();try{Vp(w.file)}catch{}Lx(w.file,{interval:200},()=>m())}function m(){let w=e;if(!w.file)return;let E;try{E=zt(w.file).size}catch{return}if(E<=w.offset)return;let O;try{O=Nx(w.file,"r")}catch{return}try{let j=E-w.offset,ie=Buffer.alloc(j),Y=0;for(;Y<j;){let Cc=_x(O,ie,Y,j-Y,w.offset+Y);if(!Cc)break;Y+=Cc}w.offset+=Y,w.partial+=ie.subarray(0,Y).toString("utf8")}finally{Ix(O)}let N,M;for(;(M=w.partial.indexOf(`
|
|
394
|
+
`))>=0;){let j=w.partial.slice(0,M);if(w.partial=w.partial.slice(M+1),!j.trim())continue;let ie=r.parseEntry(j);if(!ie)continue;let Y=r.idOf(ie);Y&&(w.entries.set(Y,ie),!r.isSidechain(ie)&&r.isLeafType(ie)&&(N=Y))}if(!N)return;let D=[],I=w.entries.get(N),F=!1;for(;I;){if(D.push(I),r.idOf(I)===w.chainLastId){F=!0;break}let j=r.parentOf(I);I=j?w.entries.get(j):void 0}if(F)for(let j=D.length-2;j>=0;j--)A(D[j]);else{w.chainLastId!==void 0&&(w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:w.sessionId}),w.latest={in:0,out:0,cached:0,cacheCreate:0});let j=new Set(D.map(Y=>r.idOf(Y))),ie=h(w.entries);for(let Y=D.length-1;Y>=0;Y--)A(D[Y]),y(r.idOf(D[Y]),ie,j)}w.chainLastId=N}function h(w){let E=new Map;for(let O of w.values()){let N=r.parentOf(O);if(!N)continue;let M=E.get(N);M?M.push(O):E.set(N,[O])}return E}function y(w,E,O){if(!w)return;let N=E.get(w);if(!N)return;let M=N.filter(j=>!r.isSidechain(j));if(M.length<2)return;let D=M.filter(j=>!O.has(r.idOf(j)));if(!D.length)return;let I=[],F=0;for(let j of D){let ie=S(j,E);I.push(...ie.events),F+=ie.count}F>0&&e.buffer.push({type:"fork",atId:w,count:F,events:I})}function S(w,E){let O=[],N=[w];for(;N.length;){let I=N.pop();if(r.isSidechain(I))continue;O.push(I);let F=E.get(r.idOf(I)??"");if(F)for(let j of F)N.push(j)}O.sort((I,F)=>(Date.parse(r.timestampOf(I)??"")||0)-(Date.parse(r.timestampOf(F)??"")||0));let M=[];for(let I of O)r.isRecoveryNoise(I)||M.push(...r.apply(I,e.sessionStartMs).events);return{count:M.reduce((I,F)=>I+(F.type==="user"||F.type==="assistant"?1:0),0),events:M}}function A(w){try{let{events:E,usage:O,model:N}=r.apply(w,e.sessionStartMs);for(let M of E)e.buffer.push(M);N&&(e.latestModel=N),O&&(e.latest=O,e.buffer.push({type:"usage",...e.latest}))}catch(E){console.error("[mirror] skipped malformed entry:",be(E))}}async function g(){return{cwd:e.cwd,pid:process.pid}}let b=new gi;async function v(w,E){b.accept(w,E)&&console.log(E)}function x(){let w=r.sessionAlive(e.sessionId,e.cwd);if(w!==void 0)return w;if(!e.file)return!1;try{return Date.now()-zt(e.file).mtimeMs<1e4}catch{return!1}}async function P(w){let E=e;return l(),{events:E.buffer.slice(w),cursor:E.buffer.length,working:r.chainWorking([...E.entries.values()])&&x(),latestModel:E.latestModel}}async function k(){return r.listSessionFiles(e.cwd).sort((w,E)=>E.mtime-w.mtime).map(({sessionId:w,file:E,mtime:O})=>({sessionId:w,mtime:O,preview:r.readPreview(E)}))}let L=new Map;function Q(w,E){let O=L.get(w);if(O&&O.mtime===E)return O.turns;let N=[],M="";try{M=dc(w,"utf8")}catch{return[]}for(let D of M.split(`
|
|
395
|
+
`)){if(!D.trim())continue;let I=r.parseEntry(D);if(!I)continue;let F=r.searchText(I);F&&N.push({text:F,lower:F.toLowerCase()})}return L.set(w,{mtime:E,turns:N}),N}async function V(w){let E=w.toLowerCase(),O=[];for(let{sessionId:N,file:M,mtime:D}of r.listSessionFiles(e.cwd).sort((I,F)=>F.mtime-I.mtime)){let{hitCount:I,snippet:F}=yi(Q(M,D),E);if(I&&(O.push({sessionId:N,mtime:D,preview:r.readPreview(M),hitCount:I,snippet:F}),O.length>=Ux))break}return O}async function B(w){let E=e,O=r.listSessionFiles(E.cwd).find(N=>N.sessionId===w);return O?O.file===E.file?{ok:!0}:(p(O),{ok:!0}):{ok:!1,error:"session not found"}}return o(e.cwd),a(e.cwd),l(),{info:g,poll:P,logEmbedStatus:v,listSessions:k,searchSessions:V,attach:B}}var jx,Fx,Yp,qx,Ux,pc=C(()=>{mi();Kp();fc();jx=".typebulb",Fx=`${jx}/locks`,Yp=5e3,qx=6e4,Ux=50});function wi(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 hc(r){return(wi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var mc=C(()=>{});import{readdirSync as Jx,readFileSync as Kx,statSync as Wx}from"fs";import{join as Gp,basename as Hx}from"path";function zp(r,e,t){if(e>8)return t;let n;try{n=Jx(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;zp(Gp(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Gp(r,s.name));return t}function vi(r){return zp(r,0,[]).map(e=>{let t=0;try{t=Wx(e).mtimeMs}catch{}let n;try{n=wi(Kx(e,"utf8").slice(0,1024))}catch{}return{path:e,name:n??Hx(e).replace(/\.bulb\.md$/,""),mtime:t}})}var Qp=C(()=>{mc()});import{readFile as Vx}from"fs/promises";async function gc(r){try{let e=Qe(await Vx(r,"utf-8"));return e?Ut(gs(e)):void 0}catch{return}}var Xp=C(()=>{wa();js()});function yc(r){let e=Qe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=ed(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,d]of e.files){let u=qc(l);u&&(c[u]=d)}return c.config=JSON.stringify(i,null,2),Gc(c)}var Zp=C(()=>{Ir();ys()});import{spawn as eh}from"child_process";import{basename as Yx}from"path";function Gx(){return process.env.TYPEBULB_EDITOR||"code"}function Qx(r,e,t){return t==null?[e]:zx.test(Yx(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function Xx(r,e){let t=Gx();return{command:t,args:Qx(t,r,e)}}function bc(r,e){let{command:t,args:n}=Xx(r,e),s=process.platform==="win32"?eh("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):eh(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var zx,th=C(()=>{zx=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});var wc=C(()=>{ge();Qp();Xp();mc();Zp();th();Xr();ti()});import{existsSync as vc,mkdirSync as Zx,readFileSync as rh,writeFileSync as ek}from"fs";import{join as Xt,isAbsolute as tk}from"path";async function nh(r,e){let t=tk(r)?r:Xt(G,r);return vc(t)?(bc(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function sh(r){let e=G,t=yc(r),n=Xt(e,"typebulbs");Zx(n,{recursive:!0});let s=hc(t),i=`${s}.bulb.md`;for(let l=2;vc(Xt(n,i))&&rh(Xt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Xt(n,i);vc(o)||ek(o,t);let a=Xt("typebulbs",i),c=await Hs(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function ih(){return K(G)}async function oh(r){return await ft(r),{ok:!0}}async function ah(){return vi(G).map(r=>({...r,trusted:lt(r.path)}))}async function ch(r){let e=r.toLowerCase(),t=[];for(let n of vi(G).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=rh(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
396
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=yi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function lh(r,e){let t=G;e!=null&&jt(r,e);let n=await Hs(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function uh(r){return{cap:await gc(r)}}async function fh(r,e){return jt(r,e),{ok:!0}}async function dh(r,e){return xe(r,e)}var Sc=C(()=>{wc();mi();fc()});import{readFileSync as Ec,writeFileSync as hh,mkdirSync as rk,appendFileSync as mh,rmSync as ph}from"fs";import{join as ki,dirname as nk}from"path";import{createServer as sk}from"http";function ze(r){try{return JSON.parse(Ec(r,"utf8"))}catch{return null}}function xi(r,e){rk(nk(r),{recursive:!0}),hh(r,JSON.stringify(e,null,2)+`
|
|
397
|
+
`)}function yh(r,e,t){let n=ki(r,".gitignore"),s="";try{s=Ec(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(`
|
|
398
398
|
`)?`
|
|
399
|
-
`:"";try{
|
|
399
|
+
`:"";try{mh(n,a+t+`
|
|
400
400
|
`+o.join(`
|
|
401
401
|
`)+`
|
|
402
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",be(c))}}function
|
|
402
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",be(c))}}function lk(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?pn="live":s>ck&&(pn="uncached")}function wh(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 uk(r){if(Array.isArray(r?.messages))for(let e of r.messages){if(!Array.isArray(e?.content))continue;let t=e.content.filter(n=>n?.type!=="thinking"&&n?.type!=="redacted_thinking");t.length&&t.length!==e.content.length&&(e.content=t)}}function vh(r){let e;try{e=JSON.parse(r)}catch{return r}dn=typeof e?.model=="string"?e.model:null,Ae&&(e.model=Ae),yt&&(e.provider=bh(yt));let t=/haiku/i.test(dn||"");return hn!=null&&!t&&(e.reasoning={effort:xc[hn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,uk(e),JSON.stringify(e)}function fk(){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}
|
|
403
403
|
data: ${JSON.stringify(a)}
|
|
404
404
|
|
|
405
405
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -407,10 +407,10 @@ data: ${JSON.stringify(a)}
|
|
|
407
407
|
|
|
408
408
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
409
409
|
|
|
410
|
-
`))!==-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
|
|
410
|
+
`))!==-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 dk(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 fn(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 pk(r,e,t){if(!Ae){fn(e,400,"invalid_request_error",ak);return}let n=process.env.OPENROUTER_API_KEY;if(!n){fn(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(Ac,{method:"POST",headers:wh(r,n),body:vh(t),signal:s.signal})}catch(u){fn(e,502,"api_error",`proxy upstream failed: ${be(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,d=a?fk():null;try{for(;;){let{done:u,value:f}=await c.read();if(u)break;if(f)if(d){let p=l.decode(f,{stream:!0});lk(p);let m=d(p);m&&e.write(m)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function hk(r,e,t){let n=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(t.length/4))}))};if(!Ae||!n)return s();try{let i=await fetch(`${Ac}/count_tokens`,{method:"POST",headers:wh(r,n),body:vh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function mk(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){fn(e,404,"not_found_error",t);return}dk(r).then(n=>{if(t.includes("count_tokens"))return hk(r,e,n);if(t.includes("/v1/messages"))return pk(r,e,n);fn(e,404,"not_found_error",t)})}function gk(){return Zt&>?Promise.resolve(gt):new Promise((r,e)=>{let t=sk(mk);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Zt=t,gt=t.address().port,console.log(`[switcher] wire proxy listening on ${Si(gt)}`),r(gt)})})}function yk(){try{Zt?.close()}catch{}Zt=null,gt=null}function bk(r,e){let t=Ei(r),n=ze(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Si(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Ai(r);if(!ze(i)){let a={};for(let c of gh)a[c]=c in s.env?s.env[c]:null;xi(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Si(e),s.env.ANTHROPIC_AUTH_TOKEN=ok,xi(t,s),yh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function wk(r,e,t){let n=Ai(r),s=ze(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},xi(n,s)}function Sh(r){let e=Ei(r),t=Ai(r),n=ze(t),s=ze(e);if(s?.env){let i=n?.snapshot||{};for(let o of gh){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{ph(e,{force:!0})}catch{}else xi(e,s)}try{ph(t,{force:!0})}catch{}}async function vk(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await pt()).filter(t=>t.provider==="openrouter"&&!Tc(t.name)).map(t=>({id:t.name,label:t.friendlyName||t.name}))}catch(t){console.error("[switcher] model list failed",be(t))}return{hasKey:r,models:e}}async function Sk(){if(Zt&&Ae)return{active:!0,managed:!0,model:Ae,port:gt,provider:yt,routedModel:dn,caching:pn,reasoning:hn,externalBaseUrl:null};let r=ze(Ei(G))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:hn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function xh(r,e){let t=await gk();return Ae=r,yt=e,bk(G,t),t}async function xk({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(Tc(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 xh(r,Pc[r]??null),dn=null,pn="unknown",wk(G,r,yt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${be(e)}`}}return{ok:!0}}async function kk({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=xc.length)?{ok:!1,error:`reasoning level must be 0\u2013${xc.length-1} or null`}:(hn=r,{ok:!0,level:r})}async function Ek(){return Sh(G),Ae=null,yt=null,dn=null,pn="unknown",{ok:!0}}async function Ak({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=G,n=ki(t,".env"),s="";try{s=Ec(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(`
|
|
411
411
|
`)?`
|
|
412
|
-
`:"";
|
|
413
|
-
`)}}catch(i){return{ok:!1,error:be(i)}}return process.env.OPENROUTER_API_KEY=e,hh(t,[".env"],"# secrets"),{ok:!0}}function xk(){if(!(!Zt&&!Ae)){try{bh(G)}catch{}pk()}}function kk(r,e){return vh.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 Ek(r){if(vh.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 Ak(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=xc(e?.cache_read_input_tokens)||xc(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 Tk({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(Ac(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:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:mh(a)}:i),u=await fetch(Ec,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:kk(a.status,x),restriction:Ek(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=xc(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:m,read:h,note:y}=Ak(f.ok,p?.usage,l);return m===!0&&l&&(Tc[r]=l,Ae===r&&(yt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:y}}}catch(a){let c=be(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var tk,Ec,rk,nk,ph,sk,Sc,xi,ki,wi,Ac,Zt,gt,Ae,yt,un,fn,dn,Tc,xc,mh,vh,Sh=C(()=>{bc();pi();tk="https://openrouter.ai/api",Ec=`${tk}/v1/messages`,rk="typebulb-proxy-managed",nk="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.",ph=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],sk=5e3,Sc=["low","medium","high"],xi=r=>Si(r,".claude","settings.local.json"),ki=r=>Si(r,".claude",".cc-switcher.json"),wi=r=>`http://127.0.0.1:${r}`;Ac=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Zt=null,gt=null,Ae=null,yt=null,un=null,fn="unknown",dn=1,Tc={},xc=r=>typeof r=="number"?r:0,mh=r=>({order:[r],allow_fallbacks:!1});vh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=ze(ki(G)),t=e?.active?.model;if(!t)return;let s=(ze(xi(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await wh(t,e.active.provider??Tc[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${wi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",be(e))}})()});var kh={};Cc(kh,{attach:()=>Ik,blockToMarkdown:()=>Gs,breakout:()=>th,capText:()=>ke,cleanUserText:()=>Ye,clearSwitchModel:()=>vk,displayName:()=>Pk,info:()=>Ok,isHiddenTurn:()=>nn,launchBulb:()=>oh,listBreakouts:()=>rh,listBulbFiles:()=>sh,listSessions:()=>Nk,listSwitchModels:()=>gk,logEmbedStatus:()=>Rk,openFile:()=>eh,poll:()=>Ck,predictTrustOf:()=>ah,probeModel:()=>Tk,readBulbLog:()=>lh,saveOpenRouterKey:()=>Sk,searchBulbs:()=>ih,searchSessions:()=>_k,setBulbTrust:()=>ch,setReasoning:()=>wk,setSwitchModel:()=>bk,shutdownSwitcher:()=>xk,stopBreakout:()=>nh,switchState:()=>yk});var xh,Pk,Ok,Ck,Rk,Nk,_k,Ik,Eh=C(()=>{dc();zs();vc();Sh();zs();Hs();xh=new Wt,Pk=xh.displayName,{info:Ok,poll:Ck,logEmbedStatus:Rk,listSessions:Nk,searchSessions:_k,attach:Ik}=gi(xh)});var Th={};Cc(Th,{attach:()=>Fk,breakout:()=>th,displayName:()=>Lk,info:()=>$k,launchBulb:()=>oh,listBreakouts:()=>rh,listBulbFiles:()=>sh,listSessions:()=>Bk,logEmbedStatus:()=>Dk,openFile:()=>eh,poll:()=>Mk,predictTrustOf:()=>ah,readBulbLog:()=>lh,searchBulbs:()=>ih,searchSessions:()=>jk,setBulbTrust:()=>ch,stopBreakout:()=>nh});var Ah,Lk,$k,Mk,Dk,Bk,jk,Fk,Ph=C(()=>{dc();Va();vc();Ah=new Ht,Lk=Ah.displayName,{info:$k,poll:Mk,logEmbedStatus:Dk,listSessions:Bk,searchSessions:jk,attach:Fk}=gi(Ah)});import*as Mh from"fs/promises";import*as _e from"path";import*as Nc from"fs/promises";import{existsSync as bt,readFileSync as Kh}from"fs";import*as W from"path";import{pathToFileURL as Wh}from"url";import{resolve as Ti}from"resolve.exports";import{init as _c,parse as Ic}from"es-module-lexer";function Lc(r,e){let t=W.join(r,"package.json");try{return JSON.parse(Kh(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Ai=["browser","import","default"],Rc=["node","import","default"];function $c(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:W.resolve(n)}}async function Mc(r){let{name:e,dir:t}=r;if(!bt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Lc(t,e),s=Hh(n,e),i=W.resolve(t,s);if(!bt(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=W.dirname(i),a=`/local/${e}/${W.basename(i)}`,c=Vh(n,t);return await Yh(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Hh(r,e){if(r.exports!==void 0){let n;try{n=Ti(r,".",{browser:!0,conditions:Ai})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Ai.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Pi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Ai.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 Vh(r,e){if(r.exports!==void 0)try{let n=Ti(r,".",{conditions:["types"]}),s=Pi(n);if(s){let i=W.resolve(e,s);if(bt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(bt(n))return n}}function Pi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Yh(r,e,t){await _c;let n=W.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await Nc.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Ic(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=Gh(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Gh(r,e,t){let n=e.replace(/[?#].*$/,""),s=W.resolve(W.dirname(r),n),i=[s,s+".js",s+".mjs",W.join(s,"index.js"),W.join(s,"index.mjs")];for(let o of i)if(W.normalize(o).startsWith(t)&&bt(o))return o}function zh(r,e,t){let n=Lc(r,e),s;if(n.exports!==void 0)try{s=Pi(Ti(n,t,{conditions:Rc}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Rc.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=W.resolve(r,s);if(!bt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Wh(i).href}async function Dc(r,e){await _c;let t;try{[t]=Ic(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=zh(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Qh=5e3;function Bc(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=Qh;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=$c(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 a.startsWith("-")||(t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a)}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 jc(){console.log(`
|
|
412
|
+
`:"";mh(n,i+`OPENROUTER_API_KEY=${e}
|
|
413
|
+
`)}}catch(i){return{ok:!1,error:be(i)}}return process.env.OPENROUTER_API_KEY=e,yh(t,[".env"],"# secrets"),{ok:!0}}function Tk(){if(!(!Zt&&!Ae)){try{Sh(G)}catch{}yk()}}function Pk(r,e){return kh.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 Ok(r){if(kh.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 Ck(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=kc(e?.cache_read_input_tokens)||kc(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 Rk({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(Tc(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:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:bh(a)}:i),u=await fetch(Ac,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let S=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:Pk(a.status,S),restriction:Ok(S)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(S=>S.type==="text")?.text??c?.content?.[0]?.text??"ok",u=kc(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:m,read:h,note:y}=Ck(f.ok,p?.usage,l);return m===!0&&l&&(Pc[r]=l,Ae===r&&(yt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:y}}}catch(a){let c=be(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var ik,Ac,ok,ak,gh,ck,xc,Ei,Ai,Si,Tc,Zt,gt,Ae,yt,dn,pn,hn,Pc,kc,bh,kh,Eh=C(()=>{wc();mi();ik="https://openrouter.ai/api",Ac=`${ik}/v1/messages`,ok="typebulb-proxy-managed",ak="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.",gh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],ck=5e3,xc=["low","medium","high"],Ei=r=>ki(r,".claude","settings.local.json"),Ai=r=>ki(r,".claude",".cc-switcher.json"),Si=r=>`http://127.0.0.1:${r}`;Tc=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Zt=null,gt=null,Ae=null,yt=null,dn=null,pn="unknown",hn=1,Pc={},kc=r=>typeof r=="number"?r:0,bh=r=>({order:[r],allow_fallbacks:!1});kh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=ze(Ai(G)),t=e?.active?.model;if(!t)return;let s=(ze(Ei(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await xh(t,e.active.provider??Pc[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Si(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",be(e))}})()});var Th={};Rc(Th,{attach:()=>Dk,blockToMarkdown:()=>Qs,breakout:()=>sh,capText:()=>ke,cleanUserText:()=>Ye,clearSwitchModel:()=>Ek,displayName:()=>Nk,info:()=>_k,isHiddenTurn:()=>nn,launchBulb:()=>lh,listBreakouts:()=>ih,listBulbFiles:()=>ah,listSessions:()=>$k,listSwitchModels:()=>vk,logEmbedStatus:()=>Lk,openFile:()=>nh,poll:()=>Ik,predictTrustOf:()=>uh,probeModel:()=>Rk,readBulbLog:()=>dh,saveOpenRouterKey:()=>Ak,searchBulbs:()=>ch,searchSessions:()=>Mk,setBulbTrust:()=>fh,setReasoning:()=>kk,setSwitchModel:()=>xk,shutdownSwitcher:()=>Tk,stopBreakout:()=>oh,switchState:()=>Sk});var Ah,Nk,_k,Ik,Lk,$k,Mk,Dk,Ph=C(()=>{pc();Xs();Sc();Eh();Xs();Ys();Ah=new Wt,Nk=Ah.displayName,{info:_k,poll:Ik,logEmbedStatus:Lk,listSessions:$k,searchSessions:Mk,attach:Dk}=bi(Ah)});var Ch={};Rc(Ch,{attach:()=>Kk,breakout:()=>sh,displayName:()=>Bk,info:()=>jk,launchBulb:()=>lh,listBreakouts:()=>ih,listBulbFiles:()=>ah,listSessions:()=>Uk,logEmbedStatus:()=>qk,openFile:()=>nh,poll:()=>Fk,predictTrustOf:()=>uh,readBulbLog:()=>dh,searchBulbs:()=>ch,searchSessions:()=>Jk,setBulbTrust:()=>fh,stopBreakout:()=>oh});var Oh,Bk,jk,Fk,qk,Uk,Jk,Kk,Rh=C(()=>{pc();Ga();Sc();Oh=new Ht,Bk=Oh.displayName,{info:jk,poll:Fk,logEmbedStatus:qk,listSessions:Uk,searchSessions:Jk,attach:Kk}=bi(Oh)});import*as jh from"fs/promises";import*as _e from"path";import*as _c from"fs/promises";import{existsSync as bt,readFileSync as Vh}from"fs";import*as W from"path";import{pathToFileURL as Yh}from"url";import{resolve as Oi}from"resolve.exports";import{init as Ic,parse as Lc}from"es-module-lexer";function $c(r,e){let t=W.join(r,"package.json");try{return JSON.parse(Vh(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Pi=["browser","import","default"],Nc=["node","import","default"];function Mc(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:W.resolve(n)}}async function Dc(r){let{name:e,dir:t}=r;if(!bt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=$c(t,e),s=Gh(n,e),i=W.resolve(t,s);if(!bt(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=W.dirname(i),a=`/local/${e}/${W.basename(i)}`,c=zh(n,t);return await Qh(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Gh(r,e){if(r.exports!==void 0){let n;try{n=Oi(r,".",{browser:!0,conditions:Pi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Pi.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Ci(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Pi.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 zh(r,e){if(r.exports!==void 0)try{let n=Oi(r,".",{conditions:["types"]}),s=Ci(n);if(s){let i=W.resolve(e,s);if(bt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(bt(n))return n}}function Ci(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Qh(r,e,t){await Ic;let n=W.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await _c.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Lc(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=Xh(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Xh(r,e,t){let n=e.replace(/[?#].*$/,""),s=W.resolve(W.dirname(r),n),i=[s,s+".js",s+".mjs",W.join(s,"index.js"),W.join(s,"index.mjs")];for(let o of i)if(W.normalize(o).startsWith(t)&&bt(o))return o}function Zh(r,e,t){let n=$c(r,e),s;if(n.exports!==void 0)try{s=Ci(Oi(n,t,{conditions:Nc}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Nc.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=W.resolve(r,s);if(!bt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Yh(i).href}async function Bc(r,e){await Ic;let t;try{[t]=Lc(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=Zh(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var em=5e3;function jc(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=em;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=Mc(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 a.startsWith("-")||(t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a)}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 Fc(){console.log(`
|
|
414
414
|
typebulb - Local bulb runner for Typebulb
|
|
415
415
|
|
|
416
416
|
Usage:
|
|
@@ -452,8 +452,8 @@ Usage:
|
|
|
452
452
|
'wait <file>': the bulb's own console.log).
|
|
453
453
|
Resumes where your last wait/call left off, so
|
|
454
454
|
an event that beats the wait still fires it.
|
|
455
|
-
typebulb stop [file|pid]
|
|
456
|
-
project's running servers; a pid/path stops any).
|
|
455
|
+
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
456
|
+
project's running servers; a pid/path/agent stops any).
|
|
457
457
|
Batch flags: --bulbs (this project's bulbs, the
|
|
458
458
|
mirror survives), --agent (this project's mirror),
|
|
459
459
|
--global (every bulb + mirror, all projects).
|
|
@@ -471,8 +471,8 @@ Options:
|
|
|
471
471
|
-n, --lines <n> Print only the last n lines (logs)
|
|
472
472
|
--match <substring> Only lines containing this literal substring end
|
|
473
473
|
the wait \u2014 not a regex (wait)
|
|
474
|
-
--timeout <sec> Give up
|
|
475
|
-
bulb default 1800
|
|
474
|
+
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
475
|
+
manual (foreground) bulb wait, default 1800 (wait)
|
|
476
476
|
--wait[=ms] For 'send': if no page is connected yet (e.g. the
|
|
477
477
|
page is mid hot-reload), retry the push for up to
|
|
478
478
|
ms (default 5000) before reporting. Use it right
|
|
@@ -539,10 +539,10 @@ Examples:
|
|
|
539
539
|
typebulb my-editor.bulb.md
|
|
540
540
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
541
541
|
typebulb .
|
|
542
|
-
`)}
|
|
542
|
+
`)}wa();import*as He from"fs/promises";import*as Ls from"path";import{pathToFileURL as Pv}from"url";import{transform as Fw}from"sucrase";function va(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Fw(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}ys();function Ww(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
543
543
|
`)[0]}`).join(`
|
|
544
|
-
`)}function
|
|
545
|
-
${Uw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",wa="https://data.jsdelivr.com/v1/package/npm/";function td(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var R=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=_t(t??s.version),this.subpath=_t(n??s.subpath)}static parse(e){let t=td(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=rd(t[1]??""),a=_t(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=rd(t[0]),o=_t(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($r).host,s=new URL(Mr).host;if(t.host===n){let i=td(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}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:_t(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},_t=r=>r&&r.length?r:void 0,rd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),_t(r.slice(e+1))]};async function ne(r){try{return await r()}catch{return}}var Dr=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=$r,this.jsDelivrBase=Mr,this.jsDelivrMeta=wa,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new R(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${this.esmHost}/${e}?${o.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await ne(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ne(()=>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 ne(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=R.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new R(`${e}@${t}`)),i=await ne(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var nd=r=>r.startsWith("@types/"),Br=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!nd(e)),va=r=>Object.keys(r?.dependencies||{}).filter(e=>!nd(e)),Jw=r=>Br(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),jr=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 Jw(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=>Br(i.meta))),n=new Map;for(let i of e)for(let o of va(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:Br(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var Fr=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await ne(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=await ne(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let o=this.selectVersionFromIndex(s.versions,t,s.distTags);if(o){if(this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}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 ne(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let i=await this.cdn.resolveExactVersion(`${e}@${t}`);if(i&&this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}async effectivePackage(e,t){let n=new R(e),s=n.root(),i=t[s],o=i?await ne(()=>this.cache.getPinnedExact(s,i))??await ne(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Kw,parse as Ww}from"es-module-lexer";var It=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))R.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{R.isBare(s)&&t.add(s)};try{await Kw;let[s]=Ww(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(R.rootOf(u))),i=[...new Set(s.map(R.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,i=await this.version.resolveExactForRoot(e,n);if(!i){let o=await ne(()=>this.cdn.pinEsmUrl(s));if(!o)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);i=R.versionFromUrl(o),i&&n&&await ne(()=>this.cache.setPinnedExact(e,n,i))}if(!i)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return i}buildEntries(e,t,n,s){let i=new Map(t.map(m=>[m.name,m])),o=m=>{let h=i.get(R.rootOf(m));return new R(m).withPreferredVersion(h.version,s[h.name]).format()},a=new Set([...n.entries()].filter(([,m])=>m.isPeerRoot||m.isSharedDep).map(([m])=>m)),c=new Set(e.filter(m=>m!==R.rootOf(m)).map(R.rootOf)),l=[],d=new Set,u=new Set(e.filter(m=>m===R.rootOf(m))),f=new Set;for(let m of e){let h=R.rootOf(m),y=i.get(h),{isPeerRoot:x,hasPeers:k,isSharedDep:g}=n.get(h),b=c.has(h),v=m!==h,P=!(x||g)&&(b||!k),E=this.singletonDepsOf(y,a),L=v&&u.has(h);L&&f.add(h);let Q=L?[...E,h]:E.length?E:void 0;l.push([m,this.cdn.buildEsmUrl(o(m),{bundle:P,external:Q})]),d.add(m)}let p=new Set([...a,...f]);for(let m of p)i.has(m)&&(d.has(m)||l.push([m,this.cdn.buildEsmUrl(o(m),{})]),l.push([`${m}/`,`${this.cdn.esmHost}/${o(m)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Br(e.meta),...va(e.meta)])].filter(n=>t.has(n))}};It.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as sd,satisfies as Hw,maxSatisfying as Sa,major as Vw,prerelease as Yw,rsort as Gw,valid as zw}from"semver";var gs=class{cmp(e,t){return e===t?0:sd(e,t)?1:sd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Hw(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=Sa(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?Gw(e)[0]:void 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=Sa(e,n,{includePrerelease:!1});if(a)return a}return Sa(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Vw(e)}isPrerelease(e){return Yw(e)!==null}isExactVersion(e){return zw(e)!==null}},ot=new gs;function id(r,e){let t=new Dr(r,e),n=new jr(t),s=new Fr(r,t,ot);return{packageService:new It(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as xd from"fs/promises";import*as he from"path";var xa=[{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"}],ka=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var ad=`
|
|
544
|
+
`)}function td(r,e){let t=Lr(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
545
|
+
${Ww(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",Sa="https://data.jsdelivr.com/v1/package/npm/";function rd(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var R=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=_t(t??s.version),this.subpath=_t(n??s.subpath)}static parse(e){let t=rd(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=nd(t[1]??""),a=_t(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=nd(t[0]),o=_t(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($r).host,s=new URL(Mr).host;if(t.host===n){let i=rd(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}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:_t(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},_t=r=>r&&r.length?r:void 0,nd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),_t(r.slice(e+1))]};async function ne(r){try{return await r()}catch{return}}var Dr=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=$r,this.jsDelivrBase=Mr,this.jsDelivrMeta=Sa,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new R(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${this.esmHost}/${e}?${o.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await ne(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ne(()=>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 ne(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=R.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new R(`${e}@${t}`)),i=await ne(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var sd=r=>r.startsWith("@types/"),Br=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!sd(e)),xa=r=>Object.keys(r?.dependencies||{}).filter(e=>!sd(e)),Hw=r=>Br(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),jr=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 Hw(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=>Br(i.meta))),n=new Map;for(let i of e)for(let o of xa(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:Br(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var Fr=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await ne(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=await ne(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let o=this.selectVersionFromIndex(s.versions,t,s.distTags);if(o){if(this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}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 ne(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let i=await this.cdn.resolveExactVersion(`${e}@${t}`);if(i&&this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}async effectivePackage(e,t){let n=new R(e),s=n.root(),i=t[s],o=i?await ne(()=>this.cache.getPinnedExact(s,i))??await ne(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Vw,parse as Yw}from"es-module-lexer";var It=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))R.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{R.isBare(s)&&t.add(s)};try{await Vw;let[s]=Yw(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(R.rootOf(u))),i=[...new Set(s.map(R.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,i=await this.version.resolveExactForRoot(e,n);if(!i){let o=await ne(()=>this.cdn.pinEsmUrl(s));if(!o)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);i=R.versionFromUrl(o),i&&n&&await ne(()=>this.cache.setPinnedExact(e,n,i))}if(!i)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return i}buildEntries(e,t,n,s){let i=new Map(t.map(m=>[m.name,m])),o=m=>{let h=i.get(R.rootOf(m));return new R(m).withPreferredVersion(h.version,s[h.name]).format()},a=new Set([...n.entries()].filter(([,m])=>m.isPeerRoot||m.isSharedDep).map(([m])=>m)),c=new Set(e.filter(m=>m!==R.rootOf(m)).map(R.rootOf)),l=[],d=new Set,u=new Set(e.filter(m=>m===R.rootOf(m))),f=new Set;for(let m of e){let h=R.rootOf(m),y=i.get(h),{isPeerRoot:S,hasPeers:A,isSharedDep:g}=n.get(h),b=c.has(h),v=m!==h,P=!(S||g)&&(b||!A),k=this.singletonDepsOf(y,a),L=v&&u.has(h);L&&f.add(h);let Q=L?[...k,h]:k.length?k:void 0;l.push([m,this.cdn.buildEsmUrl(o(m),{bundle:P,external:Q})]),d.add(m)}let p=new Set([...a,...f]);for(let m of p)i.has(m)&&(d.has(m)||l.push([m,this.cdn.buildEsmUrl(o(m),{})]),l.push([`${m}/`,`${this.cdn.esmHost}/${o(m)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Br(e.meta),...xa(e.meta)])].filter(n=>t.has(n))}};It.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as id,satisfies as Gw,maxSatisfying as ka,major as zw,prerelease as Qw,rsort as Xw,valid as Zw}from"semver";var bs=class{cmp(e,t){return e===t?0:id(e,t)?1:id(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Gw(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=ka(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?Xw(e)[0]:void 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=ka(e,n,{includePrerelease:!1});if(a)return a}return ka(e,n,{includePrerelease:!0})??void 0}majorOf(e){return zw(e)}isPrerelease(e){return Qw(e)!==null}isExactVersion(e){return Zw(e)!==null}},ot=new bs;function od(r,e){let t=new Dr(r,e),n=new jr(t),s=new Fr(r,t,ot);return{packageService:new It(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as kd from"fs/promises";import*as he from"path";var Ea=[{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"}],Aa=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var cd=`
|
|
546
546
|
/**
|
|
547
547
|
* Get raw data chunk from the Data tab.
|
|
548
548
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -553,7 +553,7 @@ ${Uw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",wa="https:
|
|
|
553
553
|
* @param index - Chunk index (0-based)
|
|
554
554
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
555
555
|
*/
|
|
556
|
-
json<T = unknown>(index: number): T;`,
|
|
556
|
+
json<T = unknown>(index: number): T;`,ld=`
|
|
557
557
|
/**
|
|
558
558
|
* Get the insight data produced by the inference layer.
|
|
559
559
|
*
|
|
@@ -562,7 +562,7 @@ ${Uw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",wa="https:
|
|
|
562
562
|
*
|
|
563
563
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
564
564
|
*/
|
|
565
|
-
insight<T = unknown>(): T | undefined;`,
|
|
565
|
+
insight<T = unknown>(): T | undefined;`,ad=`options: {
|
|
566
566
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
567
567
|
system?: string;
|
|
568
568
|
/** Reasoning depth hint (0=min, 1=low, 2=med, 3=high). Mapped to provider-specific parameters (e.g. Anthropic adaptive thinking, OpenAI reasoning effort). Default: 0. */
|
|
@@ -573,12 +573,12 @@ ${Uw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",wa="https:
|
|
|
573
573
|
webSearch?: boolean;
|
|
574
574
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
575
575
|
signal?: AbortSignal;
|
|
576
|
-
}`,
|
|
576
|
+
}`,ud=`
|
|
577
577
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
578
578
|
type AiChunk =
|
|
579
579
|
| { kind: "text"; text: string }
|
|
580
580
|
| { kind: "reasoning"; text: string };
|
|
581
|
-
`,
|
|
581
|
+
`,fd=`
|
|
582
582
|
/**
|
|
583
583
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
584
584
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -587,7 +587,7 @@ type AiChunk =
|
|
|
587
587
|
* @throws On rate limit, network error, or provider error
|
|
588
588
|
*/
|
|
589
589
|
ai: {
|
|
590
|
-
(${
|
|
590
|
+
(${ad}): Promise<{ text: string }>;
|
|
591
591
|
/**
|
|
592
592
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
593
593
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -601,8 +601,8 @@ type AiChunk =
|
|
|
601
601
|
* if (c.kind === "text") answer += c.text;
|
|
602
602
|
* }
|
|
603
603
|
*/
|
|
604
|
-
stream(${
|
|
605
|
-
};`,
|
|
604
|
+
stream(${ad}): AsyncIterable<AiChunk>;
|
|
605
|
+
};`,dd=`
|
|
606
606
|
/**
|
|
607
607
|
* Returns AI models available to the current user.
|
|
608
608
|
* Models are filtered by the user's configured API keys.
|
|
@@ -617,7 +617,7 @@ type AiChunk =
|
|
|
617
617
|
friendlyName: string;
|
|
618
618
|
/** Provider display name, e.g. "Anthropic" */
|
|
619
619
|
providerName: string;
|
|
620
|
-
}>>;`,
|
|
620
|
+
}>>;`,ev="\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;",pd=`
|
|
621
621
|
/**
|
|
622
622
|
* The mode this bulb is running in.
|
|
623
623
|
*
|
|
@@ -627,7 +627,7 @@ type AiChunk =
|
|
|
627
627
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
628
628
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
629
629
|
*/
|
|
630
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
630
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,hd=`
|
|
631
631
|
/**
|
|
632
632
|
* Local filesystem access (CLI only).
|
|
633
633
|
*
|
|
@@ -642,7 +642,7 @@ type AiChunk =
|
|
|
642
642
|
readBytes(path: string): Promise<Uint8Array>;
|
|
643
643
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
644
644
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
645
|
-
};`,
|
|
645
|
+
};`,tv=`
|
|
646
646
|
/**
|
|
647
647
|
* Server-side function proxy. The built-in \`log\` prints to CLI stdout
|
|
648
648
|
* (falls back to console.log on web). On the server side, this object only
|
|
@@ -650,7 +650,7 @@ type AiChunk =
|
|
|
650
650
|
*/
|
|
651
651
|
server: {
|
|
652
652
|
log(...args: any[]): Promise<void>;
|
|
653
|
-
};`,
|
|
653
|
+
};`,rv=`
|
|
654
654
|
/**
|
|
655
655
|
* Async value inspector for tensor-like objects.
|
|
656
656
|
*
|
|
@@ -717,7 +717,7 @@ type AiChunk =
|
|
|
717
717
|
*
|
|
718
718
|
* @returns The full canonical URL
|
|
719
719
|
*/
|
|
720
|
-
url(): Promise<string>;`,
|
|
720
|
+
url(): Promise<string>;`,nv=`
|
|
721
721
|
/**
|
|
722
722
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
723
723
|
*
|
|
@@ -732,23 +732,23 @@ type AiChunk =
|
|
|
732
732
|
* @param handler - Called with each pushed message.
|
|
733
733
|
* @returns An unsubscribe function.
|
|
734
734
|
*/
|
|
735
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
735
|
+
onMessage(handler: (message: any) => void): () => void;`,sv="\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>>;",Ta=`${ud}
|
|
736
736
|
/**
|
|
737
737
|
* Typebulb utilities namespace.
|
|
738
738
|
* Type \`tb.\` to discover available helpers.
|
|
739
739
|
*/
|
|
740
|
-
declare const tb: {${
|
|
740
|
+
declare const tb: {${cd}${rv}${ld}${sv}${nv}${fd}${hd}${dd}${ev}${pd}
|
|
741
741
|
};
|
|
742
|
-
`,
|
|
742
|
+
`,Pa=`${ud}
|
|
743
743
|
/**
|
|
744
744
|
* Typebulb utilities namespace (server-side).
|
|
745
745
|
* Type \`tb.\` to discover available helpers.
|
|
746
746
|
*/
|
|
747
|
-
declare const tb: {${
|
|
747
|
+
declare const tb: {${cd}${ld}${fd}${hd}${tv}${dd}${pd}
|
|
748
748
|
};
|
|
749
|
-
`;var at=class{constructor(e){this.store=e}async isNegative(e){let t=await ys(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ys(()=>this.store.get(e)))?.attempts||0)+1;await ys(()=>this.store.set(e,{until:Date.now()+rv(n),attempts:n}))}async clearNegative(e){await ys(()=>this.store.delete(e))}};function rv(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function ys(r){try{return await r()}catch{return}}import cv from"p-limit";import{resolve as hd}from"resolve.exports";var Lt=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var Je={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},qr=["index.d.ts","index.d.mts"],Ur=/\.d\.(ts|mts)$/i;function Ta(r){if(Ur.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function $t(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function Jr(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(nv(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function nv(r){return r===408||r===429||r>=500&&r<600}var Kr=class extends Lt{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new R({name:e,version:t})),s=await Jr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new R({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...qr],t);if(!Ur.test(s)){let i=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(i)return i}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...qr,...n],t)}toResolutionResult(e){return{kind:Ur.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(hd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(hd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=R.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 R(i).format(),a=new R({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let m=await this.resolveFromSelected(this.toResolutionResult(f),c);if(m)return{...m,resolvedPkg:a}}let p=await this.tryUntilSuccess(this.declarationCandidatesFor(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),i=new URL(s,e).toString(),o=await this.fetchDtsText(i);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...qr];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=$t(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...$t(`${s}index`)),n}};import{gunzipSync as sv}from"fflate";var Mt=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Jr(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=sv(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let m=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(m))}i+=Math.ceil(f/512)*512}}catch{}return t}},iv=new Mt;var Wr=class extends Lt{constructor(e,t,n,s=new Mt){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=ot.majorOf(n),o=e.filter(a=>ot.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ot.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=[...$t(t),`${t}/index.d.ts`,`${t}/index.d.mts`];return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new R(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 R(t).format():t.name}}}async resolve(e){let t=R.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 Hr=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,i)=>(t.add(s[i]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let i=new RegExp(t.source,"g"),o;for(;o=i.exec(e);){let a=n(o);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var md="file:///node_modules",Vr=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${md}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=ov(t);return`${md}/${this.epochDir()}/${e}/${n}`}};function ov(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as av}from"lru-cache";function Pa(r){let e=new av({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let i=e.get(s);if(i&&Date.now()-i<1e4)return;let o=await r.getCachedFile(s);if(o)return{dts:o,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var bs=class{constructor(e){this.inFlight=new Map,this.scanner=new Hr,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Pa(e.cache),this.typescriptProvider=new Kr(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Wr(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Vr}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new R(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new R(e).subpath===new R(t).subpath}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)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Je.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Je.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Ta(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let m=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,m,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new R(e).name!==new R(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.capArray(this.scanner.collectBareModuleRefs(e),Je.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=cv(Je.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Je.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Je.maxBareDeps).filter(u=>!i.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new R(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let m=f.map(k=>k.content).join(`
|
|
750
|
-
`);await this.prefetchBareDeps(m,l,f,p,s);let h=c.format(),y=e===h?[e]:[e,h],
|
|
751
|
-
`,"utf8")}async function
|
|
749
|
+
`;var at=class{constructor(e){this.store=e}async isNegative(e){let t=await ws(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ws(()=>this.store.get(e)))?.attempts||0)+1;await ws(()=>this.store.set(e,{until:Date.now()+iv(n),attempts:n}))}async clearNegative(e){await ws(()=>this.store.delete(e))}};function iv(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function ws(r){try{return await r()}catch{return}}import fv from"p-limit";import{resolve as md}from"resolve.exports";var Lt=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var Je={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},qr=["index.d.ts","index.d.mts"],Ur=/\.d\.(ts|mts)$/i;function Oa(r){if(Ur.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function $t(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function Jr(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(ov(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function ov(r){return r===408||r===429||r>=500&&r<600}var Kr=class extends Lt{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new R({name:e,version:t})),s=await Jr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new R({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...qr],t);if(!Ur.test(s)){let i=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(i)return i}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...qr,...n],t)}toResolutionResult(e){return{kind:Ur.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(md(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(md(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=R.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 R(i).format(),a=new R({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let m=await this.resolveFromSelected(this.toResolutionResult(f),c);if(m)return{...m,resolvedPkg:a}}let p=await this.tryUntilSuccess(this.declarationCandidatesFor(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),i=new URL(s,e).toString(),o=await this.fetchDtsText(i);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...qr];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=$t(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...$t(`${s}index`)),n}};import{gunzipSync as av}from"fflate";var Mt=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Jr(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=av(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let m=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(m))}i+=Math.ceil(f/512)*512}}catch{}return t}},cv=new Mt;var Wr=class extends Lt{constructor(e,t,n,s=new Mt){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=ot.majorOf(n),o=e.filter(a=>ot.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ot.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=[...$t(t),`${t}/index.d.ts`,`${t}/index.d.mts`];return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new R(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 R(t).format():t.name}}}async resolve(e){let t=R.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 Hr=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,i)=>(t.add(s[i]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let i=new RegExp(t.source,"g"),o;for(;o=i.exec(e);){let a=n(o);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var gd="file:///node_modules",Vr=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${gd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=lv(t);return`${gd}/${this.epochDir()}/${e}/${n}`}};function lv(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as uv}from"lru-cache";function Ca(r){let e=new uv({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let i=e.get(s);if(i&&Date.now()-i<1e4)return;let o=await r.getCachedFile(s);if(o)return{dts:o,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var vs=class{constructor(e){this.inFlight=new Map,this.scanner=new Hr,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Ca(e.cache),this.typescriptProvider=new Kr(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Wr(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Vr}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new R(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new R(e).subpath===new R(t).subpath}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)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Je.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Je.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Oa(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let m=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,m,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new R(e).name!==new R(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.capArray(this.scanner.collectBareModuleRefs(e),Je.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=fv(Je.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Je.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Je.maxBareDeps).filter(u=>!i.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new R(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let m=f.map(A=>A.content).join(`
|
|
750
|
+
`);await this.prefetchBareDeps(m,l,f,p,s);let h=c.format(),y=e===h?[e]:[e,h],S=y.some(A=>this.ambientlyDeclares(i,A));return S?this.markFileAmbient(f,d):p.push(...y.map(A=>({module:A,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:S}}};function Ra(r){return new vs(r)}import*as Se from"fs/promises";import*as Oe from"path";import*as wd from"os";import*as Na from"fs/promises";import*as yd from"crypto";function pe(r){return yd.createHash("sha1").update(r).digest("hex")}async function ct(r){try{return JSON.parse(await Na.readFile(r,"utf8"))}catch{return}}async function Ss(r){try{return await Na.readFile(r,"utf8")}catch{return}}var bd=1,Ke=Oe.join(wd.homedir(),".typebulb","cache"),Yr=Oe.join(Ke,"packages"),Gr=Oe.join(Ke,"proxy"),xs=Oe.join(Ke,"dts"),dv=Oe.join(Ke,"emit"),_a;function q(){return _a||(_a=pv()),_a}function ks(r,e){return Oe.join(dv,pe(r),e)}async function pv(){await Se.mkdir(Ke,{recursive:!0});let r=Oe.join(Ke,"version.json");if((await hv(r))?.version===bd)return;let t=await Se.readdir(Ke).catch(()=>[]);await Promise.all(t.map(n=>Se.rm(Oe.join(Ke,n),{recursive:!0,force:!0}))),await Se.writeFile(r,JSON.stringify({version:bd})+`
|
|
751
|
+
`,"utf8")}async function hv(r){try{let e=await Se.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as We from"fs/promises";import*as vd from"path";async function ce(r,e){await We.mkdir(vd.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await We.writeFile(t,e,"utf8"),await We.rename(t,r).catch(async n=>{throw await We.rm(t,{force:!0}).catch(()=>{}),n})}var Dt=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ct(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 ce(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Ia=he.join(Yr,"indexes"),Sd=he.join(Yr,"pinned"),mv=he.join(Yr,"meta"),gv=he.join(Yr,"negative.json"),Bt=Symbol("missing"),As=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new at(new Dt(gv));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===Bt?void 0:s;await q();let i=await Ss(he.join(Sd,pe(n)+".txt"));return this.pinnedMem.set(n,i??Bt),i}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await q(),await ce(he.join(Sd,pe(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===Bt?void 0:t;await q();let n=await ct(he.join(Ia,Es(e)+".json"));return this.indexMem.set(e,n??Bt),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await q(),await ce(he.join(Ia,Es(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await kd.rm(he.join(Ia,Es(e)+".json"),{force:!0})}async isNegative(e){return await q(),this.negativeCache.isNegative(e)}async recordNegative(e){await q(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===Bt?void 0:s;await q();let i=await ct(xd(e,t));return this.metaMem.set(n,i??Bt),i}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 q(),await ce(xd(e,t),JSON.stringify(o))}};function xd(r,e){return he.join(mv,Es(r),encodeURIComponent(e)+".json")}function Es(r){return r.replace(/\//g,"__")}var Ed={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 yv=new As,{packageService:Ts,versionResolver:Ad,cdnClient:Td,peerResolver:SP}=od(yv,Ed);var Pd=`
|
|
752
752
|
(() => {
|
|
753
753
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
754
754
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1082,11 +1082,11 @@ declare const tb: {${ad}${cd}${ud}${pd}${Xw}${fd}${dd}
|
|
|
1082
1082
|
};
|
|
1083
1083
|
}
|
|
1084
1084
|
})();
|
|
1085
|
-
`;function
|
|
1085
|
+
`;function Ps(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Os=` *, *::before, *::after { box-sizing: border-box; }
|
|
1086
1086
|
canvas { max-width: 100%; }
|
|
1087
1087
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1088
1088
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1089
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1089
|
+
html[data-theme="light"] { color-scheme: light; }`;function Cs(r,e){let t=n=>n.replace(/<\/script/gi,"<\\/script");return` <script>
|
|
1090
1090
|
(function() {
|
|
1091
1091
|
try {
|
|
1092
1092
|
var KEY = ${t(JSON.stringify("tb-theme:"+r))};
|
|
@@ -1121,19 +1121,19 @@ declare const tb: {${ad}${cd}${ud}${pd}${Xw}${fd}${dd}
|
|
|
1121
1121
|
});
|
|
1122
1122
|
} catch (e) {}
|
|
1123
1123
|
})();
|
|
1124
|
-
</script>`}function
|
|
1125
|
-
html, body { height: 100%; }`,f=m=>m.replace(/<\/script/gi,"<\\/script"),p={imports:
|
|
1124
|
+
</script>`}function Od(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l}=r,d=s.trim()||'<div id="app"></div>',u=l?"":`
|
|
1125
|
+
html, body { height: 100%; }`,f=m=>m.replace(/<\/script/gi,"<\\/script"),p={imports:wv(a.imports)};return`<!DOCTYPE html>
|
|
1126
1126
|
<html>
|
|
1127
1127
|
<head>
|
|
1128
1128
|
<meta charset="utf-8">
|
|
1129
1129
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1130
|
-
<title>${
|
|
1131
|
-
${
|
|
1130
|
+
<title>${Ps(e)} - typebulb</title>
|
|
1131
|
+
${Cs(e,c)}
|
|
1132
1132
|
<script type="importmap">
|
|
1133
1133
|
${JSON.stringify(p,null,2)}
|
|
1134
1134
|
</script>
|
|
1135
1135
|
<style>
|
|
1136
|
-
${
|
|
1136
|
+
${Os}${u}
|
|
1137
1137
|
</style>
|
|
1138
1138
|
<style>
|
|
1139
1139
|
${n}
|
|
@@ -1146,17 +1146,17 @@ ${i.length>0?`<script>window.__TB_DATA__ = ${f(JSON.stringify(i))};</script>`:""
|
|
|
1146
1146
|
${o?`<script>window.__TB_INSIGHT__ = ${f(JSON.stringify(o))};</script>`:""}
|
|
1147
1147
|
|
|
1148
1148
|
<script>
|
|
1149
|
-
${
|
|
1149
|
+
${Pd}
|
|
1150
1150
|
</script>
|
|
1151
1151
|
|
|
1152
|
-
${
|
|
1152
|
+
${bv}
|
|
1153
1153
|
|
|
1154
1154
|
<script type="module">
|
|
1155
1155
|
${f(t)}
|
|
1156
1156
|
globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtocol */
|
|
1157
1157
|
</script>
|
|
1158
1158
|
</body>
|
|
1159
|
-
</html>`}var
|
|
1159
|
+
</html>`}var bv=`<script>
|
|
1160
1160
|
(function () {
|
|
1161
1161
|
var framed = window.parent !== window;
|
|
1162
1162
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1252,53 +1252,55 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1252
1252
|
}
|
|
1253
1253
|
});
|
|
1254
1254
|
})();
|
|
1255
|
-
</script>`;function
|
|
1256
|
-
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),
|
|
1257
|
-
`,"utf8"),{dir:e}}function
|
|
1258
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1255
|
+
</script>`;function wv(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Ns from"fs/promises";import*as Rs from"path";import{existsSync as Cd,readFileSync as vv}from"fs";import{execFile as Sv}from"child_process";import{promisify as xv}from"util";import{satisfies as kv}from"semver";var Ev=xv(Sv);async function _s(r,e,t){let s=r.map(o=>Av(o,t)).filter(o=>!Tv(o,e));if(s.length===0)return;await Ns.mkdir(e,{recursive:!0});let i=Rs.join(e,"package.json");Cd(i)||await Ns.writeFile(i,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await Ev("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function Av(r,e){if(!e||Nd(r))return r;let t=e[r];return t?`${r}@${t}`:r}function Tv(r,e){let t=Rs.join(e,"node_modules",Rd(r));if(!Cd(t))return!1;let n=Nd(r);if(!n)return!0;try{let s=JSON.parse(vv(Rs.join(t,"package.json"),"utf-8")).version;return kv(s,n)}catch{return!1}}function Is(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(i)}return[...e]}function Rd(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function Nd(r){let e=Rd(r);return r.length>e.length?r.slice(e.length+1):""}async function _d(r){let t=(await He.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?Ls.join(r,t):null}async function me(r){let e=await He.readFile(r,"utf-8"),t=Qe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=gs(t);return{bulb:n,config:Qc(n.config),warnings:Hc(e)}}async function zr(r,e,t,n){let s=va(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await Bc(i,t));let o=Ls.join(e,".typebulb");await He.mkdir(o,{recursive:!0});let a=Is(i);a.length>0&&await _s(a,o,n);let c=Ls.join(o,"server.mjs");return await He.writeFile(c,i,"utf-8"),await import(`${Pv(c).href}?t=${Date.now()}`)}async function La(r,e,t,n,s){let{bulb:i,config:o}=await me(r),a=ba(i.data);td(i.code,o.dependencies??{});let c=va(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Ts.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let d=Od({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,watch:e}),u=null;return i.server&&t&&(u=await zr(i.server,s,n,o.dependencies)),{html:d,bulb:i,serverExports:u}}Xr();import Mv from"open";async function Ft(r){await Mv(r)}var $d=new Set(["claude","pi"]);function Md(r){return $d.has(r)}function Zr(){return[...$d]}import*as Ve from"path";import{spawn as Qv,execSync as Xv}from"child_process";import{createRequire as Zv}from"module";import{existsSync as eS}from"fs";import*as ee from"fs/promises";import*as X from"path";import*as qt from"path";var Dv=qt.join(xs,"pkg"),Bv=qt.join(xs,"files"),jv=qt.join(xs,"negative.json"),Ds=class{pkgMem=new Map;fileMem=new Map;negativeCache=new at(new Dt(jv));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await q();let t=await ct(Dd(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 Ms(async()=>{await q(),await ce(Dd(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await q();let t=await Ss(Bd(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await Ms(async()=>{await q(),await ce(Bd(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Ms(async()=>{await q(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Ms(()=>this.negativeCache.clearNegative(e))}};async function Ms(r){try{await r()}catch{}}function Dd(r){return qt.join(Dv,pe(r)+".json")}function Bd(r){return qt.join(Bv,pe(r)+".txt")}var Ba;function Fv(){return Ba||(Ba=Ra({cache:new Ds,cdnClient:Td,packageService:Ts,versionResolver:Ad})),Ba}var jd="file:///node_modules/";async function Fd(r){let e=ks(r.emitKey,"typecheck");await q(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=Kv(r.jsxImportSource,r.dependencies),n=await Fv().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(d=>d.pkg!==s):n,o=new Set;for(let d of i)for(let u of d.files){let f=Bs(u.path);if(!f||o.has(f))continue;o.add(f);let p=X.join(e,"node_modules",f);await ee.mkdir(X.dirname(p),{recursive:!0}),await ee.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=Bs(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=Bs(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of i)for(let u of d.files){if(!u.ambient)continue;let f=Bs(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await Wv(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=qv(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1256
|
+
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),Ta,"utf8"),{dir:e}}function qv(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:Uv([...Ea,...Aa]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,paths:e},include:["code.tsx","tb.d.ts",...t]}}function Uv(r){return r.filter(e=>!e.since).map(e=>Jv(e.name))}function Jv(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 Kv(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Bs(r){if(!r.startsWith(jd))return;let e=r.slice(jd.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function Wv(r,e){if(!r.typesAbs)return;let t=X.dirname(r.typesAbs),n=X.join(e,"node_modules",r.name);for(let s of await Hv(t)){let i=X.join(n,X.relative(t,s));await ee.mkdir(X.dirname(i),{recursive:!0}),await ee.copyFile(s,i)}return X.basename(r.typesAbs)}async function Hv(r){let e=[];async function t(n){let s=await ee.readdir(n,{withFileTypes:!0});for(let i of s){let o=X.join(n,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(r),e}import*as le from"fs/promises";import*as Re from"path";import{existsSync as Vv}from"fs";var Yv="^22";async function qd(r){let e=ks(r.emitKey,"typecheck-server");await q(),await le.rm(e,{recursive:!0,force:!0}),await le.mkdir(e,{recursive:!0});let t=Re.join(r.bulbDir,".typebulb"),n=Is(r.server).filter(o=>o!==r.local?.name);await _s([`@types/node@${Yv}`,...n],t,r.dependencies);let s=Re.join(t,"node_modules"),i=Re.join(e,"node_modules");return await zv(s,i),await le.writeFile(Re.join(e,"server.ts"),r.server,"utf8"),await le.writeFile(Re.join(e,"tb.d.ts"),Pa,"utf8"),await le.writeFile(Re.join(e,"tsconfig.json"),JSON.stringify(Gv(r.local),null,2)+`
|
|
1257
|
+
`,"utf8"),{dir:e}}function Gv(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Re.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 zv(r,e){if(!Vv(r)){await le.mkdir(e,{recursive:!0});return}await le.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await le.symlink(r,e,t)}ys();async function Jd(r,e){let{bulb:t,config:n,warnings:s}=await me(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=Ud(Lr(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Ud(Lr(t.server,{target:"server"}),"server")||i);let o=nS([process.cwd(),Ve.dirname(r)]);if(!o){let l=Ve.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 Fd({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 qd({server:t.server,bulbDir:Ve.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:d}of a){let{stdout:u,exitCode:f}=await tS(o,d);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);f!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function Ud(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1258
|
+
`))console.log(`${e} ${n}`);return r.length>0}function tS(r,e){return new Promise(t=>{let n=Qv(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 rS=Zv(import.meta.url);function nS(r){let e=n=>{try{let s=rS.resolve("typescript/package.json",{paths:n}),i=Ve.join(Ve.dirname(s),"lib","tsc.js");return eS(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=Xv("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}js();Xr();async function Kd(r,e){let{bulb:t}=await me(r),n=Ut(t);if(lt(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.)")}Xr();import*as en from"path";async function Wd(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Da();if(!n.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of n)console.log(` ${s}`);return}let t=en.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),jt(t,e),console.log(e?`Trusted ${en.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${en.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}ge();import*as bp from"readline";ge();Xs();Ga();var on={claude:()=>new Wt,pi:()=>new Ht};function pp(){for(let r of Object.values(on))try{r().ensureWaitSupport()}catch{}}function an(){for(let r of Object.keys(on))try{if(on[r]().detectsSelf())return r}catch{}}async function hp(r){let e=Zr(),t=new Map(e.filter(i=>on[i]).map(i=>[i,on[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=await rn(r);if(n?.agent&&t.has(n.agent))return{name:n.agent};let s=[...t].filter(([,i])=>i.listSessionFiles(r).length>0).map(([i])=>i);return s.length===1?{name:s[0]}:s.length===0?{name:e[0]}:{ambiguous:s}}import{readFileSync as VS,existsSync as YS}from"fs";import*as dt from"path";import{fileURLToPath as GS}from"url";function mp(){let r=dt.dirname(GS(import.meta.url));for(;!YS(dt.join(r,"package.json"));){let e=dt.dirname(r);if(e===r)break;r=e}return r}function Zs(){return dt.join(mp(),"README.md")}function za(){return dt.join(mp(),"description.md")}function zS(r){return`---
|
|
1259
1259
|
name: typebulb
|
|
1260
|
-
description: ${
|
|
1260
|
+
description: ${VS(za(),"utf8").trim().replace(/\s+/g," ")}
|
|
1261
1261
|
version: ${r}
|
|
1262
|
-
---`}function
|
|
1262
|
+
---`}function QS(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 gp(r,e){return`${zS(e)}
|
|
1263
1263
|
|
|
1264
|
-
${
|
|
1264
|
+
${QS(e)}
|
|
1265
1265
|
|
|
1266
1266
|
${r.trim()}
|
|
1267
|
-
`}async function
|
|
1267
|
+
`}async function wp(r){let e=await hp(process.cwd());if("ambiguous"in e){let t=await XS(r,e.ambiguous);return t?yp(r,t):ZS(r,e.ambiguous)}return yp(r,e.name)}async function yp(r,e){let t,n;try{t=await np(e)}catch(f){n=f instanceof Error?f.message:String(f)}let s=process.stdout.isTTY===!0,i=f=>p=>s?`\x1B[${f}m${p}\x1B[0m`:p,o=i("1;92"),a=i("1;4;92"),c=i("38;5;135"),l=[" Read the authoring skill before writing a bulb:",` \u2022 ${o("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${o(za())}`,` ${o(Zs())}`],d=t?[" Agent mirror is live",` ${o("\u25CF")} ${a(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${o(".bulb.md")}`," Show something inline \u2192 embed a bulb"," after emitting the bulb, background a wait:",` \u2022 ${o('typebulb wait agent --match "[embed <name>"')}`,...l," 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: ${o(`npx typebulb agent:${e}`)}`," Agents:",...l],u=[` ${c(`typebulb v${r}`)}`,...d,""];process.stdout.write(u.join(`
|
|
1268
1268
|
`)+`
|
|
1269
|
-
`)}function
|
|
1269
|
+
`)}async function XS(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let t=a=>c=>`\x1B[${a}m${c}\x1B[0m`,n=t("1;92"),i=[` ${t("38;5;135")(`typebulb v${r}`)}`," This project has sessions for more than one agent harness.",...e.map((a,c)=>` ${n(String(c+1))}) ${a}`),""];process.stdout.write(i.join(`
|
|
1270
1270
|
`)+`
|
|
1271
|
-
`)}
|
|
1272
|
-
`)
|
|
1273
|
-
|
|
1271
|
+
`);let o=bp.createInterface({input:process.stdin,output:process.stdout});try{let a=(await new Promise(l=>o.question(" Open which? [1]: ",l))).trim();if(a==="")return e[0];let c=Number(a);return Number.isInteger(c)&&c>=1&&c<=e.length?e[c-1]:e.find(l=>l===a.toLowerCase())}finally{o.close()}}function ZS(r,e){let t=process.stdout.isTTY===!0,n=a=>c=>t?`\x1B[${a}m${c}\x1B[0m`:c,s=n("1;92"),o=[` ${n("38;5;135")(`typebulb v${r}`)}`," This project has sessions for more than one agent harness."," Open the mirror for the one you want:",...e.map(a=>` \u2022 ${s(`npx typebulb agent:${a}`)}`),""];process.stdout.write(o.join(`
|
|
1272
|
+
`)+`
|
|
1273
|
+
`)}import{readFileSync as ex,existsSync as tx}from"fs";import*as Ne from"path";function rx(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function Ee(r,e=process.cwd()){let t={},n=[];for(let s of rx(r)){let i;try{i=ex(Ne.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of nx(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*nx(r){for(let e of r.split(`
|
|
1274
|
+
`)){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 sx(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 Ge(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ne.dirname(e),c=`(mode: ${s??"none"})`,l=t?sx(t):[],d=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);d.length?console.log(`env: ${d.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Ne.resolve(a)!==Ne.resolve(o);if(u)for(let p of[".env.local",".env"])tx(Ne.join(a,p))&&console.log(`env: ${Ne.join(a,p)} present but not loaded (cwd is ${o})`);let f=l.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}ti();async function xp(r){Ee(r);let e=await pt();if(e.length>0){console.log(Sp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!vp()){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(Yt))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.")}import*as kp from"fs/promises";async function Ep(r){let e=Zs(),t;try{t=await kp.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(gp(t,r))}Qr();import*as Ap from"path";ge();function fx(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&&J(o.cwd)===J(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>J(i.file)===J(e))}var cn=r=>r.agent??Ap.basename(r.file);function Tp(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Xa(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Tp(r,t=>console.log(t)),console.log(`
|
|
1275
|
+
`+e)}function Za(r,e,t,n,s){let i=fx(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>\`):`),Tp(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Pp(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Xa(await K(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Za(await K(),r,"logs",process.cwd(),an());if(e.clear){Xd(t.pid),console.log(`Cleared log for ${cn(t)} (pid ${t.pid}).`);return}let n=xe(t.pid),s=n.text;if(e.run!==void 0&&(s=Zd(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(`
|
|
1274
1276
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1275
1277
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1276
1278
|
`)&&process.stdout.write(`
|
|
1277
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=xe(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
|
|
1278
|
-
`);
|
|
1279
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=xe(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 dx=r=>new Promise(e=>setTimeout(e,r));async function Op(r,e){if(!r){Xa(await K(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Za(await K(),r,"wait",process.cwd(),an()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=n?30:e.timeoutSec??1800,a=e.match??"",c=xe(t.pid).offset,l=qa(t.pid,a)??(a?qa(t.pid):void 0),d=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,f=n?1e4:1e3,p,m=!1,h="",y=0;for(;;){let S=xe(t.pid,d);if(d=S.offset,S.text){h+=S.text;let A=h.split(`
|
|
1280
|
+
`);h=A.pop()??"";for(let g of A)g.trim()&&(e.match&&!g.includes(e.match)||(console.log(g),p??=Date.now()+f,n&&(g.includes("] compile error")||g.includes("] runtime error"))&&(m=!0)))}if(m||p&&Date.now()>=p)break;if(!i&&!p&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${cn(t)} within ${o}s`),y=2;break}if(!Ja(t.pid)){p||(console.error(`server ${cn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await dx(400)}Us(t.pid,d,a),process.exit(y)}async function Cp(r){if(!r){Xa(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Za(await K(),r,"stop",process.cwd(),an());await ft(e.pid),console.log(`Stopped ${cn(e)} (pid ${e.pid}, ${e.url}).`)}async function Rp(r){let e=process.cwd(),t=r==="agent"?an():void 0,n=r==="global"?await K():r==="bulbs"?await K(e):(await K()).filter(i=>i.agent!=null&&i.cwd!=null&&J(i.cwd)===J(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=>ft(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${cn(i)}`)}ge();import*as Np from"path";async function _p(r,e,t=0){let n=Np.resolve(r),s=Ws(await K(),n)[0];s||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let i=async()=>{let a=await fetch(`${s.url}/__send`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return a.ok||(console.error(`send failed: HTTP ${a.status} from ${s.url}/__send`),process.exit(1)),(await a.json().catch(()=>({}))).clients??0},o=0;try{let a=Date.now()+t;do{if(o=await i(),o>0||Date.now()>=a)break;await new Promise(c=>setTimeout(c,150))}while(!0)}catch(a){console.error(`send failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}o>0?console.log(`Sent to ${o} page${o===1?"":"s"}.`):t>0?console.log(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.log("Sent, but no page is connected yet \u2014 open the bulb and retry.")}ge();import*as qp from"fs/promises";import*as Gt from"path";import{EventEmitter as lc}from"events";js();import{Hono as Sx}from"hono";import{serve as xx}from"@hono/node-server";import{streamSSE as kx}from"hono/streaming";import*as mt from"fs/promises";import*as ye from"path";var se=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},oe=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
|
|
1279
1281
|
|
|
1280
|
-
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let i={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(i.code=s.error.code),i}return s.message?{message:s.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 se(t.message,n,!!t.retryable)}if(t.error)throw new se(this.extractErrorMessage(t.error))}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
|
|
1282
|
+
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let i={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(i.code=s.error.code),i}return s.message?{message:s.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 se(t.message,n,!!t.retryable)}if(t.error)throw new se(this.extractErrorMessage(t.error))}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 ri=class extends oe{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};return n?.webSearch!==!1&&(o.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(i=>i.text).join(`
|
|
1281
1283
|
`)),!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"error":return null;case"response.failed":{let s=e.response?.error,i=s?.message||"Response failed",o=s?.code==="insufficient_quota"||s?.code==="rate_limit_exceeded";throw new se(i,o?"rate_limit":"unknown",o)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};case"response.created":case"response.in_progress":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":case"response.output_text.done":case"response.output_text.annotation.added":case"response.reasoning_summary_text.done":case"response.completed":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":return null;default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
1282
1284
|
|
|
1283
|
-
`)}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
|
|
1285
|
+
`)}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 ni=class extends oe{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"low",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let i={model:t,messages:e,stream:s};return n?.webSearch===!0&&(i.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning]}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message?.content??n?.text??"",i=n?.message?.reasoning??t.reasoning;return{text:s,reasoning:i}}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||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 si=class extends oe{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};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
|
|
1284
1286
|
|
|
1285
|
-
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!this.isAnthropicEvent(e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return 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-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var
|
|
1287
|
+
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!this.isAnthropicEvent(e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return 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-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var ii=class extends oe{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
1286
1288
|
`),c={contents:o.map(l=>({role:l.role==="assistant"?"model":"user",parts:[{text:l.content}]}))};return n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]}),this.isReasoningEnabled(n)&&(c.generationConfig={thinkingConfig:{includeThoughts:!0,thinkingBudget:-1}}),c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
1287
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new se(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new se(`Prompt blocked: ${t}`)}}};var
|
|
1289
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new se(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new se(`Prompt blocked: ${t}`)}}};var oi=class extends oe{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}}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let n=e.choices[0]?.message,s=n?.content??"",i=n?.reasoning??n?.reasoning_content;return{text:s,reasoning:i}}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 Ip=new oi,px=new Map([["openai",new ri],["openrouter",new ni],["anthropic",new si],["gemini",new ii],["ollama",Ip],["openai-compat",Ip]]);function ht(r){let e=px.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function hx(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function ec(r,e){let t=ht(r.protocol),n=t.getPath(e.model,e.stream),s=hx(r.baseUrl,n),i=t.buildHeaders(r.apiKey,e.origin),o=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(o),fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}async function tc(r,e){let t=ht(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&&(o="context_exceeded"),{code:o,message:s,retryable:i===429}}function Lp(r){let e=r.indexOf(`\r
|
|
1288
1290
|
\r
|
|
1289
1291
|
`),t=r.indexOf(`
|
|
1290
1292
|
|
|
1291
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
1292
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function
|
|
1293
|
-
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${P}`,403)}await b()},m=async(g,b)=>{let v=g.req.header("sec-fetch-site");if(v){if(v!=="same-origin")return g.text(`Forbidden: ${v} request`,403)}else{let
|
|
1294
|
-
${p.name}`),console.log(` ${
|
|
1293
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function rc(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(`
|
|
1294
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*$p(r,e){let t=new TextDecoder,n="";try{for(;;){if(e?.aborted)return;let{done:s,value:i}=await r.read();if(s){if(n.trim()){let c=rc(n);c!==null&&c!=="done"&&(yield c)}return}n+=t.decode(i,{stream:!0});let{pos:o,len:a}=Lp(n);for(;o!==-1;){let c=n.slice(0,o);n=n.slice(o+a);let l=rc(c);if(l==="done")return;l!==null&&(yield l),{pos:o,len:a}=Lp(n)}}}finally{try{await r.cancel()}catch{}}}async function nc(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of ai(r,e))n.kind==="text"&&(t+=n.text);return t}async function*ai(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=ht(t);if(!r.body)return;let s=r.body.getReader();for await(let i of $p(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}import*as sc from"fs/promises";import*as ln from"path";var ci=class{async get(e){let t=pe(e),n=ln.join(Gr,t+".bin"),s=ln.join(Gr,t+".json");try{let[i,o]=await Promise.all([sc.readFile(n),sc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await q();let n=pe(e),s=ln.join(Gr,n+".bin"),i=ln.join(Gr,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([ce(s,t.body),ce(i,JSON.stringify(o))])}};ge();ti();import{stream as mx}from"hono/streaming";var gx="X-TB-Stream";function yx(r){return r instanceof se?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function ic(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(gx,"1"),mx(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:yx(s)}))}finally{try{await n.return?.()}catch{}}})}var oc={log:(...r)=>console.log(...r)};function li(r,e){let t=r?.[e]??oc[e];return typeof t=="function"?t:void 0}function ui(r){return r.constructor?.name==="AsyncGeneratorFunction"}var bx=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,wx=/[?&]target=/,vx=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Mp(r,e=""){return bx.test(r)?!0:vx.test(r)&&wx.test(e)}var Bp="127.0.0.1",Ex=new Set(["localhost","127.0.0.1","::1"]);function Ax(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function Tx(r){let e=Ax(r);return!!e&&Ex.has(e)}function Px(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function fi(r){return r instanceof Error?r.message:"Unknown error"}async function di(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,localOverride:a,trusted:c=!1,trustHint:l,staticAssets:d}=r,u=new Sx;u.use("*",async(g,b)=>{if(!Tx(g.req.header("host")))return g.text("Forbidden: untrusted Host",403);await b()}),u.use("*",async(g,b)=>{await b(),g.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),g.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let f=["/__fs/*","/__api/*","/__ai"],p=async(g,b)=>{if(!c){let v=new URL(g.req.url).pathname,x=v.startsWith("/__fs")?"the filesystem":v==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";ep(process.pid,x);let P=l?`
|
|
1295
|
+
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${P}`,403)}await b()},m=async(g,b)=>{let v=g.req.header("sec-fetch-site");if(v){if(v!=="same-origin")return g.text(`Forbidden: ${v} request`,403)}else{let x=g.req.header("origin");if(x&&!Px(x,g.req.header("host")))return g.text("Forbidden: cross-origin request",403)}await b()};for(let g of f)u.use(g,p),u.use(g,m);u.use("/__log",m),u.post("/__log",async g=>{try{let{args:b}=await g.req.json();console.log(...b||[])}catch{}return g.json({ok:!0})}),i&&(u.use("/__send",m),u.post("/__send",async g=>{let b="";try{b=await g.req.text()}catch{}let v=i.listenerCount("message");return i.emit("message",b),g.json({clients:v})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:b}=await g.req.json(),v=cc(b,t),x=await mt.readFile(v);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(b){let v=fi(b);return g.json({error:v},400)}}),u.post("/__fs/write",async g=>{try{let b=g.req.query("path");if(!b)return g.json({error:"Missing path"},400);let v=cc(b,t);return await mt.mkdir(ye.dirname(v),{recursive:!0}),await mt.writeFile(v,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(b){let v=fi(b);return g.json({error:v},400)}}),u.post("/__api/:name",async g=>{try{let b=g.req.param("name"),v=li(o?.(),b);if(!v)return g.json({error:`API function '${b}' not found`},404);let{args:x}=await g.req.json();if(ui(v))return ic(g,v(...x||[]));let P=await v(...x||[]);return g.json({result:P})}catch(b){let v=fi(b);return g.json({error:v},500)}}),u.post("/__ai",async g=>{try{let{messages:b,system:v,reasoning:x,provider:P,model:k,webSearch:L,stream:Q}=await g.req.json();if(!b||!Array.isArray(b)||b.length===0)return g.json({message:"messages array is required",code:"unknown",retryable:!1},400);let V=Ox(P,k);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=[...v?[{role:"system",content:v}]:[],...b.map(O=>({role:O.role,content:O.content}))],w=await ec(V,{model:V.model,messages:B,stream:!0,reasoning:x??0,webSearch:L??!0});if(!w.ok){let O=await tc(w,V.protocol);return g.json(O,w.status)}if(Q)return ic(g,ai(w,V.protocol));let E=await nc(w,V.protocol);return E||console.warn("[tb.ai] Empty response from provider"),g.json({text:E})}catch(b){if(b instanceof se)return g.json({message:b.message,code:b.code,retryable:b.retryable},500);let v=fi(b);return g.json({message:v,code:"unknown",retryable:!1},500)}}),u.get("/__models",async g=>{try{let b=await pt();return g.json(b)}catch{return g.json([],200)}});let h=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],y=new ci;u.get("/proxy/*",async g=>{let b=new URL(g.req.url),x=(b.pathname+b.search).slice(7),P=x.lastIndexOf("https://");return P===-1?g.text("Invalid proxy URL",400):S(g,x.slice(P))}),a&&Dp(u,`/local/${a.name}/`,a.serveDir),d&&Dp(u,d.mount,d.dir);async function S(g,b){let v;try{v=new URL(b)}catch{return g.text("Invalid URL",400)}if(v.protocol!=="https:")return g.text("HTTPS only",400);if(!h.includes(v.hostname))return g.text("Host not allowed",403);let x=await y.get(b);if(x)return new Response(x.body,{status:200,headers:ac(x.contentType,x.cacheControl)});try{let P=await fetch(b,{headers:{Accept:g.req.header("Accept")||"*/*"},redirect:"follow"});if(!P.ok)return g.text(`Upstream ${P.status}`,P.status);let k=P.headers.get("Content-Type")||void 0,L=P.headers.get("Cache-Control")||void 0;if(P.body){let[Q,V]=P.body.tee();return(async()=>{try{let B=await new Response(V).arrayBuffer();await y.set(b,{body:Buffer.from(B),contentType:k,cacheControl:L})}catch{}})(),new Response(Q,{status:P.status,headers:ac(k,L)})}return new Response(null,{status:P.status,headers:ac(k,L)})}catch(P){return g.text(`Proxy fetch failed: ${P instanceof Error?P.message:P}`,502)}}(s||i)&&u.get("/__reload",g=>kx(g,async b=>{let v=()=>{b.writeSSE({event:"reload",data:""})},x=P=>{b.writeSSE({event:"message",data:JSON.stringify(P)})};for(s?.on("reload",v),i?.on("message",x),b.onAbort(()=>{s?.removeListener("reload",v),i?.removeListener("message",x)});;)await b.sleep(3e4)})),u.notFound(async g=>{if(g.req.method!=="GET")return g.text("Not Found",404);let b=new URL(g.req.url);return Mp(b.pathname,b.search)?S(g,"https://esm.sh"+b.pathname+b.search):g.text("Not Found",404)});let A=xx({fetch:u.fetch,port:n,hostname:Bp});return{port:n,close:()=>A.close()}}function Ox(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=ht(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Qa(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=Yt[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 ac(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 Dp(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=cc(i,t),a=await mt.readFile(o);return new Response(a,{headers:{"Content-Type":Cx(o)}})}catch{return n.text("Not Found",404)}})}function Cx(r){switch(ye.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function cc(r,e){let t=ye.resolve(e,r),n=ye.normalize(e),s=ye.normalize(t);if(s!==n&&!s.startsWith(n+ye.sep))throw new Error("Path traversal detected - access denied");return t}async function un(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Bp,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(un(r+1))})})}import jp from"chokidar";var Fp={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function pi(r){let{bulbPath:e,emitter:t,debounceMs:n=150}=r,s,i=jp.watch(e,Fp);return i.on("change",()=>{s&&clearTimeout(s),s=setTimeout(()=>t.emit("reload"),n)}),()=>{s&&clearTimeout(s),i.close()}}function hi(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,i=jp.watch(e,Fp);return i.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),i.close()}}ge();async function Up(r,e,t,n,s){let i=process.cwd(),o=Js(process.pid),a=e.watch?new lc:void 0,c=new lc;c.setMaxListeners(0);let l=Ee(e.mode),d=await Ka(r);d.length&&console.log(`Replacing the running server for this bulb (pid ${d.map(x=>x.pid).join(", ")})`);let u=1;console.log(Ua(u)),console.log(`Loading ${Gt.basename(r)}...`);let{html:f,bulb:p,serverExports:m}=await La(r,e.watch,e.trust,n,s);Ge(l,r,p.server);let h=await un(e.port),y=await di({getHtml:()=>f,basePath:i,port:h,reloadEmitter:a,messageEmitter:c,getServerExports:()=>m,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),S=`http://localhost:${h}`,A=e.trust?void 0:Ut(p);await Ks({pid:process.pid,port:h,url:S,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:A}),console.log(`
|
|
1296
|
+
${p.name}`),console.log(` ${S}`),h!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(A?` trust: restricted \u2014 this bulb appears to use ${A}; re-run with --trust to enable it:
|
|
1295
1297
|
${t}
|
|
1296
1298
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1297
1299
|
`),e.watch&&console.log(` Watching for changes...
|
|
1298
|
-
`);let g,b;if(e.watch&&a){let
|
|
1299
|
-
`),a.emit("reload")}})}}e.open&&(d.some(
|
|
1300
|
-
`):await Ft(
|
|
1301
|
-
Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let
|
|
1300
|
+
`);let g,b;if(e.watch&&a){let x=new lc;if(x.on("reload",async()=>{try{console.log("Recompiling...");let P=await La(r,!0,e.trust,n,s);f=P.html,m=P.serverExports,u++,console.log(Ua(u)),a.emit("reload")}catch(P){console.error("Compile error:",P)}}),g=pi({bulbPath:r,emitter:x}),n){let{name:P,serveDir:k}=n;b=hi({dir:k,onChange:()=>{console.log(`Local package '${P}' changed. Browser reloading...
|
|
1301
|
+
`),a.emit("reload")}})}}e.open&&(d.some(x=>x.port===h)?console.log(` Reusing the open browser tab.
|
|
1302
|
+
`):await Ft(S));let v=async()=>{console.log(`
|
|
1303
|
+
Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let x=Gt.join(Gt.dirname(r),".typebulb","server.mjs");await qp.rm(x,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import{readFileSync as Nh,copyFileSync as Wk,existsSync as Hk}from"fs";import*as Z from"path";import{fileURLToPath as Vk}from"url";import{EventEmitter as Yk}from"events";ge();var uc=r=>`/agents/${r}/client.js`,Rx=`
|
|
1302
1304
|
(() => {
|
|
1303
1305
|
const api = async (name, ...args) => {
|
|
1304
1306
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1333,15 +1335,15 @@ Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let S=Gt.join
|
|
|
1333
1335
|
es.onerror = () => { es.close(); };
|
|
1334
1336
|
}
|
|
1335
1337
|
})();
|
|
1336
|
-
`;function
|
|
1338
|
+
`;function Jp(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=uc(t);return`<!DOCTYPE html>
|
|
1337
1339
|
<html>
|
|
1338
1340
|
<head>
|
|
1339
1341
|
<meta charset="utf-8">
|
|
1340
1342
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1341
|
-
<title>${
|
|
1342
|
-
${
|
|
1343
|
+
<title>${Ps(e)} - typebulb</title>
|
|
1344
|
+
${Cs(e,o)}
|
|
1343
1345
|
<style>
|
|
1344
|
-
${
|
|
1346
|
+
${Os}
|
|
1345
1347
|
</style>
|
|
1346
1348
|
<style>
|
|
1347
1349
|
${n}
|
|
@@ -1353,19 +1355,19 @@ ${s}
|
|
|
1353
1355
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1354
1356
|
|
|
1355
1357
|
<script>
|
|
1356
|
-
${
|
|
1358
|
+
${Rx}
|
|
1357
1359
|
</script>
|
|
1358
1360
|
|
|
1359
1361
|
<script type="module" src="${a}"></script>
|
|
1360
1362
|
</body>
|
|
1361
|
-
</html>`}var
|
|
1363
|
+
</html>`}var Gk={claude:()=>Promise.resolve().then(()=>(Ph(),Th)),pi:()=>Promise.resolve().then(()=>(Rh(),Ch))};async function _h(r){let e=process.cwd(),t=r.agentTarget,n=Js(process.pid),s=r.watch?new Yk:void 0,i=Ee(r.mode),o=await Gk[t](),a=o.displayName||`${t} mirror`;Ge(i,Z.join(e,"mirror"));let c=Z.dirname(Vk(import.meta.url)),l=Z.join(c,"agents",t),d=Z.join(c,"..","cli","agents"),u=Z.join(l,"styles.css"),f=Z.join(l,"index.html"),p=()=>Jp({name:a,agent:t,styles:Nh(u,"utf8"),mountHtml:Nh(f,"utf8"),watch:r.watch}),m=await un(r.port),h=await di({getHtml:p,basePath:e,port:m,reloadEmitter:s,getServerExports:()=>o,trusted:!0,staticAssets:{mount:`${Z.posix.dirname(uc(t))}/`,dir:l}}),y=`http://localhost:${m}`;await Ks({pid:process.pid,port:m,url:y,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t}),console.log(`
|
|
1362
1364
|
${a}`),console.log(` ${y}`),m!==r.port&&console.log(` (port ${r.port} was busy)`),r.watch&&console.log(` Watching for changes...
|
|
1363
|
-
`);let
|
|
1364
|
-
`),s.emit("reload")}catch(
|
|
1365
|
-
Shutting down...`);try{o.shutdownSwitcher?.()}catch{}h.close(),b?.(),n(),await tn(process.pid),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import*as
|
|
1366
|
-
`);let c=new
|
|
1367
|
-
`)}catch(p){
|
|
1368
|
-
`),process.exit(0)}async function
|
|
1369
|
-
`),process.exit(1)}function
|
|
1370
|
-
${e}`),process.exit(1))}async function
|
|
1371
|
-
${l.url}`),r.open&&await Ft(l.url);return}await
|
|
1365
|
+
`);let S=Z.join(d,t,"client"),A=Z.join(d,"core","client");async function g(){await(await import("esbuild")).build({entryPoints:[Z.join(S,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:Z.join(l,"client.js")});for(let P of["styles.css","index.html"])Wk(Z.join(A,P),Z.join(l,P))}let b;if(r.watch&&s){let x=Hk(S),P=!1;b=hi({dir:x?d:l,onChange:async()=>{if(!P){P=!0;try{x&&await g(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1366
|
+
`),s.emit("reload")}catch(k){console.error("Mirror rebuild failed:",k instanceof Error?k.message:k)}finally{P=!1}}}})}r.open&&await Ft(y);let v=async()=>{console.log(`
|
|
1367
|
+
Shutting down...`);try{o.shutdownSwitcher?.()}catch{}h.close(),b?.(),n(),await tn(process.pid),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import*as Ih from"path";import{EventEmitter as zk}from"events";async function Lh(r,e,t,n,s){let i=Ee(t),o=!1,a=async()=>{let{bulb:c,config:l}=await me(r);o||(Ge(i,r,c.server),o=!0),await zr(c.server,s,n,l.dependencies)};if(console.log(`Running ${Ih.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1368
|
+
`);let c=new zk;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),pi({bulbPath:r,emitter:c})}}import{Console as Qk}from"node:console";ge();Qr();async function Mh(r,e,t,n,s){r0();try{let p=J(r),m=(await K()).find(h=>J(h.file)===p);m&&Us(m.pid,xe(m.pid).offset)}catch{}let i=Ee(t),{bulb:o,config:a}=await me(r);o.server||mn("This bulb has no **server.ts** block; nothing to call."),Ge(i,r,o.server);let c;try{c=await zr(o.server,s,n,a.dependencies)}catch(p){mn(p instanceof Error?p.message:String(p))}let l=li(c,e.fn);if(!l){let p=[...Object.keys(c).filter(m=>typeof c[m]=="function"),...Object.keys(oc)];mn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let d=await Xk(e);if(ui(l)){try{for await(let p of l(...d))await $h(JSON.stringify(p,Dh)+`
|
|
1369
|
+
`)}catch(p){mn(p instanceof Error?p.stack??p.message:String(p))}process.exit(0)}let u;try{u=await l(...d)}catch(p){mn(p instanceof Error?p.stack??p.message:String(p))}let f=t0(u);f!==void 0&&await $h(f+`
|
|
1370
|
+
`),process.exit(0)}async function Xk(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await n0()),e0(e)}return Zk(r.positional)}function Zk(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function e0(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 t0(r){if(r!==void 0)return JSON.stringify(r,Dh,2)}function Dh(r,e){return typeof e=="bigint"?e.toString():e}function mn(r){process.stderr.write(r+`
|
|
1371
|
+
`),process.exit(1)}function r0(){let r=new Qk(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 $h(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function n0(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Oc="0.18.5";function Bh(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1372
|
+
${e}`),process.exit(1))}async function s0(){let r=jc(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Oc}`),process.exit(0)),r.help&&(Fc(),process.exit(0)),pp(),r.subcommand==="logs"){await Pp(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Op(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Rp(r.stopScope):await Cp(r.file||void 0);return}if(r.subcommand==="send"){await _p(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Ep(Oc);return}if(r.subcommand==="models"){await xp(r.mode);return}if(r.subcommand==="agent"){if(!r.agentTarget){await wp(Oc);return}Md(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${Zr().join(", ")}.`),process.exit(1));let l=await rn(process.cwd(),r.agentTarget);if(l){console.log(`Mirror '${r.agentTarget}' is already running for this project:
|
|
1373
|
+
${l.url}`),r.open&&await Ft(l.url);return}await _h(r);return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Wd(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await _d(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=_e.resolve(r.file);await jh.access(e).then(()=>!0,()=>!1)||(Zr().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:_e.relative(process.cwd(),e)||_e.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Kd(e,s);return}let i=!r.noTrust&<(e);i&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await me(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 Dc(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${_e.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Jd(e,a);return}let c=_e.dirname(e);if(r.subcommand==="call"){Bh(r.trust,s),await Mh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(!o.bulb.code||r.server)){Bh(r.trust,s),await Lh(e,r.watch,r.mode,a,c);return}await Up(e,r,s,a,c)}s0().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|