shadow-claw 1.41.0 → 1.41.1
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/.well-known/mcp/server-card.json +1 -1
- package/.well-known/mcp.json +1 -1
- package/README.md +2 -2
- package/dist/cli/build/build.js +1 -1
- package/dist/cli/{chunk-bQQkVCw-.js → chunk-63s8NnIS.js} +15 -16
- package/dist/cli/chunk-BATVgkFY.js +17 -0
- package/dist/cli/chunk-Cmdxoq9q.js +13 -0
- package/dist/cli/cli.js +1 -1
- package/dist/cli/prerender/dsd-shell/prerender-dsd-shell.js +1 -1
- package/dist/public/.well-known/mcp/server-card.json +1 -1
- package/dist/public/.well-known/mcp.json +1 -1
- package/dist/public/AGENTS.md +6 -1
- package/dist/public/README.md +2 -2
- package/dist/public/docs/README.md +1 -0
- package/dist/public/docs/example/article/index.html +1 -1
- package/dist/public/docs/guides/publishing-to-github-pages.md +46 -0
- package/dist/public/docs/publishing/index.html +1 -1
- package/dist/public/docs/skill-creator/index.html +1 -1
- package/dist/public/docs/subsystems/theming.md +242 -0
- package/dist/public/e2e/README.md +1 -0
- package/dist/public/index.html +1 -1
- package/dist/public/llms.txt +2 -2
- package/dist/public/main/index.html +1 -1
- package/dist/public/main/memory/index.html +1 -1
- package/dist/public/service-worker.js +1 -1
- package/package.json +1 -1
- package/src/cli/build/build.ts +18 -11
- package/src/cli/prerender/dsd-shell/prerender-dsd-shell.ts +6 -0
- package/src/cli/prerender/pretty-paths/prerender-pretty-paths.ts +22 -0
- package/src/cli/prerender/utils/insert-before-closing-head.test.ts +22 -1
- package/src/cli/prerender/utils/insert-before-closing-head.ts +19 -3
- package/src/cli/site-config/apply.ts +13 -14
- package/dist/cli/chunk-BvVUnHTq.js +0 -14
- package/dist/cli/chunk-DTES-dE6.js +0 -17
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{t as e}from"./chunk-uAI_Zi6n.js";import{C as t,S as n,_ as r,a as i,b as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,o as p,p as m,r as h,t as g,w as _,x as v,y}from"./chunk-BATVgkFY.js";import{n as ee}from"./chunk-kF1oe5Yi.js";import*as te from"node:fs";import b,{join as x,posix as S,resolve as C,win32 as ne}from"node:path";import{fileURLToPath as re}from"node:url";import w,{chdir as ie,env as ae,exit as oe}from"node:process";import{execSync as se}from"node:child_process";import{copyFile as T,cp as E,lstat as ce,mkdir as D,readFile as O,readdir as le,readlink as ue,realpath as de,rm as fe,stat as pe,writeFile as k}from"node:fs/promises";import{chmodSync as me,lstatSync as he,lstatSync as ge,readdir as _e,readdirSync as ve,readlinkSync as ye,realpathSync as be,renameSync as xe,rmSync as Se,rmdirSync as Ce,statSync as we,unlinkSync as Te}from"fs";import{EventEmitter as Ee}from"node:events";import De from"node:stream";import{StringDecoder as Oe}from"node:string_decoder";import{basename as A,parse as j,resolve as M}from"path";import{inspect as ke}from"util";import Ae from"fs/promises";import{setTimeout as je}from"timers/promises";import{tmpdir as Me}from"os";var Ne=(e,t,n)=>{let r=e instanceof RegExp?Pe(e,n):e,i=t instanceof RegExp?Pe(t,n):t,a=r!==null&&i!=null&&Fe(r,i,n);return a&&{start:a[0],end:a[1],pre:n.slice(0,a[0]),body:n.slice(a[0]+r.length,a[1]),post:n.slice(a[1]+i.length)}},Pe=(e,t)=>{let n=t.match(e);return n?n[0]:null},Fe=(e,t,n)=>{let r,i,a,o,s,c=n.indexOf(e),l=n.indexOf(t,c+1),u=c;if(c>=0&&l>0){if(e===t)return[c,l];for(r=[],a=n.length;u>=0&&!s;){if(u===c)r.push(u),c=n.indexOf(e,u+1);else if(r.length===1){let e=r.pop();e!==void 0&&(s=[e,l])}else i=r.pop(),i!==void 0&&i<a&&(a=i,o=l),l=n.indexOf(t,u+1);u=c<l&&c>=0?c:l}r.length&&o!==void 0&&(s=[a,o])}return s},Ie=`\0SLASH`+Math.random()+`\0`,Le=`\0OPEN`+Math.random()+`\0`,Re=`\0CLOSE`+Math.random()+`\0`,ze=`\0COMMA`+Math.random()+`\0`,Be=`\0PERIOD`+Math.random()+`\0`,Ve=new RegExp(Ie,`g`),He=new RegExp(Le,`g`),Ue=new RegExp(Re,`g`),We=new RegExp(ze,`g`),Ge=new RegExp(Be,`g`),Ke=/\\\\/g,qe=/\\{/g,Je=/\\}/g,Ye=/\\,/g,Xe=/\\./g,Ze=1e5;function Qe(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function $e(e){return e.replace(Ke,Ie).replace(qe,Le).replace(Je,Re).replace(Ye,ze).replace(Xe,Be)}function et(e){return e.replace(Ve,`\\`).replace(He,`{`).replace(Ue,`}`).replace(We,`,`).replace(Ge,`.`)}function tt(e){if(!e)return[``];let t=[],n=Ne(`{`,`}`,e);if(!n)return e.split(`,`);let{pre:r,body:i,post:a}=n,o=r.split(`,`);o[o.length-1]+=`{`+i+`}`;let s=tt(a);return a.length&&(o[o.length-1]+=s.shift(),o.push.apply(o,s)),t.push.apply(t,o),t}function nt(e,t={}){if(!e)return[];let{max:n=Ze}=t;return e.slice(0,2)===`{}`&&(e=`\\{\\}`+e.slice(2)),st($e(e),n,!0).map(et)}function rt(e){return`{`+e+`}`}function it(e){return/^-?0\d/.test(e)}function at(e,t){return e<=t}function ot(e,t){return e>=t}function st(e,t,n){let r=[],i=Ne(`{`,`}`,e);if(!i)return[e];let a=i.pre,o=i.post.length?st(i.post,t,!1):[``];if(/\$$/.test(i.pre))for(let e=0;e<o.length&&e<t;e++){let t=a+`{`+i.body+`}`+o[e];r.push(t)}else{let s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),l=s||c,u=i.body.indexOf(`,`)>=0;if(!l&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+`{`+i.body+Re+i.post,st(e,t,!0)):[e];let d;if(l)d=i.body.split(/\.\./);else if(d=tt(i.body),d.length===1&&d[0]!==void 0&&(d=st(d[0],t,!1).map(rt),d.length===1))return o.map(e=>i.pre+d[0]+e);let f;if(l&&d[0]!==void 0&&d[1]!==void 0){let e=Qe(d[0]),t=Qe(d[1]),n=Math.max(d[0].length,d[1].length),r=d.length===3&&d[2]!==void 0?Math.abs(Qe(d[2])):1,i=at;t<e&&(r*=-1,i=ot);let a=d.some(it);f=[];for(let o=e;i(o,t);o+=r){let e;if(c)e=String.fromCharCode(o),e===`\\`&&(e=``);else if(e=String(o),a){let t=n-e.length;if(t>0){let n=Array(t+1).join(`0`);e=o<0?`-`+n+e.slice(1):n+e}}f.push(e)}}else{f=[];for(let e=0;e<d.length;e++)f.push.apply(f,st(d[e],t,!1))}for(let e=0;e<f.length;e++)for(let i=0;i<o.length&&r.length<t;i++){let t=a+f[e]+o[i];(!n||l||t)&&r.push(t)}}return r}var ct=e=>{if(typeof e!=`string`)throw TypeError(`invalid pattern`);if(e.length>65536)throw TypeError(`pattern is too long`)},lt={"[:alnum:]":[`\\p{L}\\p{Nl}\\p{Nd}`,!0],"[:alpha:]":[`\\p{L}\\p{Nl}`,!0],"[:ascii:]":[`\\x00-\\x7f`,!1],"[:blank:]":[`\\p{Zs}\\t`,!0],"[:cntrl:]":[`\\p{Cc}`,!0],"[:digit:]":[`\\p{Nd}`,!0],"[:graph:]":[`\\p{Z}\\p{C}`,!0,!0],"[:lower:]":[`\\p{Ll}`,!0],"[:print:]":[`\\p{C}`,!0],"[:punct:]":[`\\p{P}`,!0],"[:space:]":[`\\p{Z}\\t\\r\\n\\v\\f`,!0],"[:upper:]":[`\\p{Lu}`,!0],"[:word:]":[`\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}`,!0],"[:xdigit:]":[`A-Fa-f0-9`,!1]},ut=e=>e.replace(/[[\]\\-]/g,`\\$&`),dt=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),ft=e=>e.join(``),pt=(e,t)=>{let n=t;if(e.charAt(n)!==`[`)throw Error(`not in a brace expression`);let r=[],i=[],a=n+1,o=!1,s=!1,c=!1,l=!1,u=n,d=``;t:for(;a<e.length;){let t=e.charAt(a);if((t===`!`||t===`^`)&&a===n+1){l=!0,a++;continue}if(t===`]`&&o&&!c){u=a+1;break}if(o=!0,t===`\\`&&!c){c=!0,a++;continue}if(t===`[`&&!c){for(let[t,[o,c,l]]of Object.entries(lt))if(e.startsWith(t,a)){if(d)return[`$.`,!1,e.length-n,!0];a+=t.length,l?i.push(o):r.push(o),s||=c;continue t}}if(c=!1,d){t>d?r.push(ut(d)+`-`+ut(t)):t===d&&r.push(ut(t)),d=``,a++;continue}if(e.startsWith(`-]`,a+1)){r.push(ut(t+`-`)),a+=2;continue}if(e.startsWith(`-`,a+1)){d=t,a+=2;continue}r.push(ut(t)),a++}if(u<a)return[``,!1,0,!1];if(!r.length&&!i.length)return[`$.`,!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!l)return[dt(r[0].length===2?r[0].slice(-1):r[0]),!1,u-n,!1];let f=`[`+(l?`^`:``)+ft(r)+`]`,p=`[`+(l?``:`^`)+ft(i)+`]`;return[r.length&&i.length?`(`+f+`|`+p+`)`:r.length?f:p,s,u-n,!0]},mt=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^\/\\])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,`$1$2`).replace(/\\([^\/])/g,`$1`):t?e.replace(/\[([^\/\\{}])\]/g,`$1`):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,`$1$2`).replace(/\\([^\/{}])/g,`$1`),ht=new Set([`!`,`?`,`+`,`*`,`@`]),gt=e=>ht.has(e),_t=`(?!(?:^|/)\\.\\.?(?:$|/))`,vt=`(?!\\.)`,yt=new Set([`[`,`.`]),bt=new Set([`..`,`.`]),xt=new Set(`().*{}+?[]^$\\!`),St=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),Ct=`[^/]`,wt=Ct+`*?`,Tt=Ct+`+?`,Et=class e{type;#e;#t;#n=!1;#r=[];#i;#a;#o;#s=!1;#c;#l;#u=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#c=this.#e===this?n:this.#e.#c,this.#o=this.#e===this?[]:this.#e.#o,e===`!`&&!this.#e.#s&&this.#o.push(this),this.#a=this.#i?this.#i.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!=`string`&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l===void 0?this.type?this.#l=this.type+`(`+this.#r.map(e=>String(e)).join(`|`)+`)`:this.#l=this.#r.map(e=>String(e)).join(``):this.#l}#d(){if(this!==this.#e)throw Error(`should only call on root`);if(this.#s)return this;this.toString(),this.#s=!0;let e;for(;e=this.#o.pop();){if(e.type!==`!`)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#a+1;!n.type&&r<n.#r.length;r++)for(let t of e.#r){if(typeof t==`string`)throw Error(`string part in extglob AST??`);t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...t){for(let n of t)if(n!==``){if(typeof n!=`string`&&!(n instanceof e&&n.#i===this))throw Error(`invalid part: `+n);this.#r.push(n)}}toJSON(){let e=this.type===null?this.#r.slice().map(e=>typeof e==`string`?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#s&&this.#i?.type===`!`)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#a===0)return!0;let t=this.#i;for(let n=0;n<this.#a;n++){let r=t.#r[n];if(!(r instanceof e&&r.type===`!`))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type===`!`)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#r.length:0;return this.#a===e-1}copyIn(e){typeof e==`string`?this.push(e):this.push(e.clone(this))}clone(t){let n=new e(this.type,t);for(let e of this.#r)n.copyIn(e);return n}static#f(t,n,r,i){let a=!1,o=!1,s=-1,c=!1;if(n.type===null){let l=r,u=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,u+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),u+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,u+=r;continue}if(!i.noext&>(r)&&t.charAt(l)===`(`){n.push(u),u=``;let a=new e(r,n);l=e.#f(t,a,l,i),n.push(a);continue}u+=r}return n.push(u),l}let l=r+1,u=new e(null,n),d=[],f=``;for(;l<t.length;){let r=t.charAt(l++);if(a||r===`\\`){a=!a,f+=r;continue}if(o){l===s+1?(r===`^`||r===`!`)&&(c=!0):r===`]`&&!(l===s+2&&c)&&(o=!1),f+=r;continue}else if(r===`[`){o=!0,s=l,c=!1,f+=r;continue}if(gt(r)&&t.charAt(l)===`(`){u.push(f),f=``;let n=new e(r,u);u.push(n),l=e.#f(t,n,l,i);continue}if(r===`|`){u.push(f),f=``,d.push(u),u=new e(null,n);continue}if(r===`)`)return f===``&&n.#r.length===0&&(n.#u=!0),u.push(f),f=``,n.push(...d,u),l;f+=r}return n.type=null,n.#t=void 0,n.#r=[t.substring(r-1)],l}static fromGlob(t,n={}){let r=new e(null,void 0,n);return e.#f(t,r,0,n),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#c.nocase&&!this.#c.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#c.nocase?`i`:``)+(i?`u`:``);return Object.assign(RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#c}toRegExpSource(t){let n=t??!!this.#c.dot;if(this.#e===this&&this.#d(),!this.type){let r=this.isStart()&&this.isEnd()&&!this.#r.some(e=>typeof e!=`string`),i=this.#r.map(n=>{let[i,a,o,s]=typeof n==`string`?e.#m(n,this.#t,r):n.toRegExpSource(t);return this.#t=this.#t||o,this.#n=this.#n||s,i}).join(``),a=``;if(this.isStart()&&typeof this.#r[0]==`string`&&!(this.#r.length===1&&bt.has(this.#r[0]))){let e=yt,r=n&&e.has(i.charAt(0))||i.startsWith(`\\.`)&&e.has(i.charAt(2))||i.startsWith(`\\.\\.`)&&e.has(i.charAt(4)),o=!n&&!t&&e.has(i.charAt(0));a=r?_t:o?vt:``}let o=``;return this.isEnd()&&this.#e.#s&&this.#i?.type===`!`&&(o=`(?:$|\\/)`),[a+i+o,mt(i),this.#t=!!this.#t,this.#n]}let r=this.type===`*`||this.type===`+`,i=this.type===`!`?`(?:(?!(?:`:`(?:`,a=this.#p(n);if(this.isStart()&&this.isEnd()&&!a&&this.type!==`!`){let e=this.toString();return this.#r=[e],this.type=null,this.#t=void 0,[e,mt(this.toString()),!1,!1]}let o=!r||t||n||!vt?``:this.#p(!0);o===a&&(o=``),o&&(a=`(?:${a})(?:${o})*?`);let s=``;if(this.type===`!`&&this.#u)s=(this.isStart()&&!n?vt:``)+Tt;else{let e=this.type===`!`?`))`+(this.isStart()&&!n&&!t?vt:``)+wt+`)`:this.type===`@`?`)`:this.type===`?`?`)?`:this.type===`+`&&o?`)`:this.type===`*`&&o?`)?`:`)${this.type}`;s=i+a+e}return[s,mt(a),this.#t=!!this.#t,this.#n]}#p(e){return this.#r.map(t=>{if(typeof t==`string`)throw Error(`string type in extglob ast??`);let[n,r,i,a]=t.toRegExpSource(e);return this.#n=this.#n||a,n}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join(`|`)}static#m(e,t,n=!1){let r=!1,i=``,a=!1,o=!1;for(let s=0;s<e.length;s++){let c=e.charAt(s);if(r){r=!1,i+=(xt.has(c)?`\\`:``)+c;continue}if(c===`*`){if(o)continue;o=!0,i+=n&&/^[*]+$/.test(e)?Tt:wt,t=!0;continue}else o=!1;if(c===`\\`){s===e.length-1?i+=`\\\\`:r=!0;continue}if(c===`[`){let[n,r,o,c]=pt(e,s);if(o){i+=n,a||=r,s+=o-1,t||=c;continue}}if(c===`?`){i+=Ct,t=!0;continue}i+=St(c)}return[i,mt(e),!!t,a]}},Dt=(e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,`[$&]`):e.replace(/[?*()[\]\\{}]/g,`\\$&`):t?e.replace(/[?*()[\]]/g,`[$&]`):e.replace(/[?*()[\]\\]/g,`\\$&`),N=(e,t,n={})=>(ct(t),!n.nocomment&&t.charAt(0)===`#`?!1:new nn(t,n).match(e)),Ot=/^\*+([^+@!?\*\[\(]*)$/,kt=e=>t=>!t.startsWith(`.`)&&t.endsWith(e),At=e=>t=>t.endsWith(e),jt=e=>(e=e.toLowerCase(),t=>!t.startsWith(`.`)&&t.toLowerCase().endsWith(e)),Mt=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Nt=/^\*+\.\*+$/,Pt=e=>!e.startsWith(`.`)&&e.includes(`.`),Ft=e=>e!==`.`&&e!==`..`&&e.includes(`.`),It=/^\.\*+$/,Lt=e=>e!==`.`&&e!==`..`&&e.startsWith(`.`),Rt=/^\*+$/,zt=e=>e.length!==0&&!e.startsWith(`.`),Bt=e=>e.length!==0&&e!==`.`&&e!==`..`,Vt=/^\?+([^+@!?\*\[\(]*)?$/,Ht=([e,t=``])=>{let n=Kt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Ut=([e,t=``])=>{let n=qt([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},Wt=([e,t=``])=>{let n=qt([e]);return t?e=>n(e)&&e.endsWith(t):n},Gt=([e,t=``])=>{let n=Kt([e]);return t?e=>n(e)&&e.endsWith(t):n},Kt=([e])=>{let t=e.length;return e=>e.length===t&&!e.startsWith(`.`)},qt=([e])=>{let t=e.length;return e=>e.length===t&&e!==`.`&&e!==`..`},Jt=typeof process==`object`&&process?typeof process.env==`object`&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:`posix`,Yt={win32:{sep:`\\`},posix:{sep:`/`}};N.sep=Jt===`win32`?Yt.win32.sep:Yt.posix.sep;var P=Symbol(`globstar **`);N.GLOBSTAR=P;var Xt=`[^/]*?`,Zt=`(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?`,Qt=`(?:(?!(?:\\/|^)\\.).)*?`;N.filter=(e,t={})=>n=>N(n,e,t);var F=(e,t={})=>Object.assign({},e,t);N.defaults=e=>{if(!e||typeof e!=`object`||!Object.keys(e).length)return N;let t=N;return Object.assign((n,r,i={})=>t(n,r,F(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,F(e,n))}static defaults(n){return t.defaults(F(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,F(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,F(e,r))}},unescape:(n,r={})=>t.unescape(n,F(e,r)),escape:(n,r={})=>t.escape(n,F(e,r)),filter:(n,r={})=>t.filter(n,F(e,r)),defaults:n=>t.defaults(F(e,n)),makeRe:(n,r={})=>t.makeRe(n,F(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,F(e,r)),match:(n,r,i={})=>t.match(n,r,F(e,i)),sep:t.sep,GLOBSTAR:P})};var $t=(e,t={})=>(ct(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:nt(e,{max:t.braceExpandMax}));N.braceExpand=$t,N.makeRe=(e,t={})=>new nn(e,t).makeRe(),N.match=(e,t,n={})=>{let r=new nn(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};var en=/[?*]|[+@!]\(.*?\)|\[|\]/,tn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,`\\$&`),nn=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ct(e),t||={},this.options=t,this.pattern=e,this.platform=t.platform||Jt,this.isWindows=this.platform===`win32`,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,`/`)),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot===void 0?!!(this.isWindows&&this.nocase):t.windowsNoMagicRoot,this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!=`string`)return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)===`#`){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){let t=e[0]===``&&e[1]===``&&(e[2]===`?`||!en.test(e[2]))&&!en.test(e[3]),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>e.indexOf(!1)===-1),this.isWindows)for(let e=0;e<this.set.length;e++){let t=this.set[e];t[0]===``&&t[1]===``&&this.globParts[e][2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3])&&(t[2]=`?`)}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)e[t][n]===`**`&&(e[t][n]=`*`);let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;(t=e.indexOf(`**`,t+1))!==-1;){let n=t;for(;e[n+1]===`**`;)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>(e=e.reduce((e,t)=>{let n=e[e.length-1];return t===`**`&&n===`**`?e:t===`..`&&n&&n!==`..`&&n!==`.`&&n!==`**`?(e.pop(),e):(e.push(t),e)},[]),e.length===0?[``]:e))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let r=e[n];n===1&&r===``&&e[0]===``||(r===`.`||r===``)&&(t=!0,e.splice(n,1),n--)}e[0]===`.`&&e.length===2&&(e[1]===`.`||e[1]===``)&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf(`..`,n+1))!==-1;){let r=e[n-1];r&&r!==`.`&&r!==`..`&&r!==`**`&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[``]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;(r=n.indexOf(`**`,r+1))!==-1;){let i=r;for(;n[i+1]===`**`;)i++;i>r&&n.splice(r+1,i-r);let a=n[r+1],o=n[r+2],s=n[r+3];if(a!==`..`||!o||o===`.`||o===`..`||!s||s===`.`||s===`..`)continue;t=!0,n.splice(r,1);let c=n.slice(0);c[r]=`**`,e.push(c),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){let r=n[e];e===1&&r===``&&n[0]===``||(r===`.`||r===``)&&(t=!0,n.splice(e,1),e--)}n[0]===`.`&&n.length===2&&(n[1]===`.`||n[1]===``)&&(t=!0,n.pop())}let i=0;for(;(i=n.indexOf(`..`,i+1))!==-1;){let e=n[i-1];if(e&&e!==`.`&&e!==`..`&&e!==`**`){t=!0;let e=i===1&&n[i+1]===`**`?[`.`]:[];n.splice(i-1,2,...e),n.length===0&&n.push(``),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,a=[],o=``;for(;r<e.length&&i<t.length;)if(e[r]===t[i])a.push(o===`b`?t[i]:e[r]),r++,i++;else if(n&&e[r]===`**`&&t[i]===e[r+1])a.push(e[r]),r++;else if(n&&t[i]===`**`&&e[r]===t[i+1])a.push(t[i]),i++;else if(e[r]===`*`&&t[i]&&(this.options.dot||!t[i].startsWith(`.`))&&t[i]!==`**`){if(o===`b`)return!1;o=`a`,a.push(e[r]),r++,i++}else if(t[i]===`*`&&e[r]&&(this.options.dot||!e[r].startsWith(`.`))&&e[r]!==`**`){if(o===`a`)return!1;o=`b`,a.push(t[i]),r++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let r=0;r<e.length&&e.charAt(r)===`!`;r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let r=this.options;if(this.isWindows){let n=typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]),r=!n&&e[0]===``&&e[1]===``&&e[2]===`?`&&/^[a-z]:$/i.test(e[3]),i=typeof t[0]==`string`&&/^[a-z]:$/i.test(t[0]),a=!i&&t[0]===``&&t[1]===``&&t[2]===`?`&&typeof t[3]==`string`&&/^[a-z]:$/i.test(t[3]),o=r?3:n?0:void 0,s=a?3:i?0:void 0;if(typeof o==`number`&&typeof s==`number`){let[n,r]=[e[o],t[s]];n.toLowerCase()===r.toLowerCase()&&(t[s]=n,s>o?t=t.slice(s):o>s&&(e=e.slice(o)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug(`matchOne`,this,{file:e,pattern:t}),this.debug(`matchOne`,e.length,t.length);for(var a=0,o=0,s=e.length,c=t.length;a<s&&o<c;a++,o++){this.debug(`matchOne loop`);var l=t[o],u=e[a];if(this.debug(t,l,u),l===!1)return!1;if(l===P){this.debug(`GLOBSTAR`,[t,l,u]);var d=a,f=o+1;if(f===c){for(this.debug(`** at the end`);a<s;a++)if(e[a]===`.`||e[a]===`..`||!r.dot&&e[a].charAt(0)===`.`)return!1;return!0}for(;d<s;){var p=e[d];if(this.debug(`
|
|
2
|
+
globstar while`,e,d,t,f,p),this.matchOne(e.slice(d),t.slice(f),n))return this.debug(`globstar found match!`,d,s,p),!0;if(p===`.`||p===`..`||!r.dot&&p.charAt(0)===`.`){this.debug(`dot detected!`,e,d,t,f);break}this.debug(`globstar swallow a segment, and continue`),d++}return!!(n&&(this.debug(`
|
|
3
|
+
>>> no match, partial?`,e,d,t,f),d===s))}let i;if(typeof l==`string`?(i=u===l,this.debug(`string match`,l,u,i)):(i=l.test(u),this.debug(`pattern match`,l,u,i)),!i)return!1}if(a===s&&o===c)return!0;if(a===s)return n;if(o===c)return a===s-1&&e[a]===``;throw Error(`wtf?`)}braceExpand(){return $t(this.pattern,this.options)}parse(e){ct(e);let t=this.options;if(e===`**`)return P;if(e===``)return``;let n,r=null;(n=e.match(Rt))?r=t.dot?Bt:zt:(n=e.match(Ot))?r=(t.nocase?t.dot?Mt:jt:t.dot?At:kt)(n[1]):(n=e.match(Vt))?r=(t.nocase?t.dot?Ut:Ht:t.dot?Wt:Gt)(n):(n=e.match(Nt))?r=t.dot?Ft:Pt:(n=e.match(It))&&(r=Lt);let i=Et.fromGlob(e,this.options).toMMPattern();return r&&typeof i==`object`&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,n=t.noglobstar?Xt:t.dot?Zt:Qt,r=new Set(t.nocase?[`i`]:[]),i=e.map(e=>{let t=e.map(e=>{if(e instanceof RegExp)for(let t of e.flags.split(``))r.add(t);return typeof e==`string`?tn(e):e===P?P:e._src});t.forEach((e,r)=>{let i=t[r+1],a=t[r-1];e!==P||a===P||(a===void 0?i!==void 0&&i!==P?t[r+1]=`(?:\\/|`+n+`\\/)?`+i:t[r]=n:i===void 0?t[r-1]=a+`(?:\\/|\\/`+n+`)?`:i!==P&&(t[r-1]=a+`(?:\\/|\\/`+n+`\\/)`+i,t[r+1]=P))});let i=t.filter(e=>e!==P);if(this.partial&&i.length>=1){let e=[];for(let t=1;t<=i.length;t++)e.push(i.slice(0,t).join(`/`));return`(?:`+e.join(`|`)+`)`}return i.join(`/`)}).join(`|`),[a,o]=e.length>1?[`(?:`,`)`]:[``,``];i=`^`+a+i+o+`$`,this.partial&&(i=`^(?:\\/|`+a+i.slice(1,-1)+o+`)$`),this.negate&&(i=`^(?!`+i+`).+$`);try{this.regexp=new RegExp(i,[...r].join(``))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split(`/`):this.isWindows&&/^\/\/[^\/]+/.test(e)?[``,...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug(`match`,e,this.pattern),this.comment)return!1;if(this.empty)return e===``;if(e===`/`&&t)return!0;let n=this.options;this.isWindows&&(e=e.split(`\\`).join(`/`));let r=this.slashSplit(e);this.debug(this.pattern,`split`,r);let i=this.set;this.debug(this.pattern,`set`,i);let a=r[r.length-1];if(!a)for(let e=r.length-2;!a&&e>=0;e--)a=r[e];for(let e=0;e<i.length;e++){let o=i[e],s=r;if(n.matchBase&&o.length===1&&(s=[a]),this.matchOne(s,o,t))return n.flipNegate?!0:!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return N.defaults(e).Minimatch}};N.AST=Et,N.Minimatch=nn,N.escape=Dt,N.unescape=mt;var rn=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,an=new Set,on=typeof process==`object`&&process?process:{},sn=(e,t,n,r)=>{typeof on.emitWarning==`function`?on.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},cn=globalThis.AbortController,ln=globalThis.AbortSignal;if(typeof cn>`u`){ln=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},cn=class{constructor(){t()}signal=new ln;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=on.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,sn("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}var un=e=>!an.has(e),dn=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),fn=e=>dn(e)?e<=2**8?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?pn:null:null,pn=class extends Array{constructor(e){super(e),this.fill(0)}},mn=class e{heap;length;static#e=!1;static create(t){let n=fn(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},hn=class e{#e;#t;#n;#r;#i;#a;#o;#s;get perf(){return this.#s}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;static unsafeExposeInternals(e){return{starts:e.#b,ttls:e.#x,autopurgeTimers:e.#S,sizes:e.#y,keyMap:e.#u,keyList:e.#d,valList:e.#f,next:e.#p,prev:e.#m,get head(){return e.#h},get tail(){return e.#g},free:e.#_,isBackgroundFetch:t=>e.#V(t),backgroundFetch:(t,n,r,i)=>e.#B(t,n,r,i),moveToTail:t=>e.#U(t),indexes:t=>e.#I(t),rindexes:t=>e.#L(t),isStale:t=>e.#j(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#l}get size(){return this.#c}get fetchMethod(){return this.#a}get memoMethod(){return this.#o}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#i}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,onInsert:u,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:p,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:_,memoMethod:v,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:ee,allowStaleOnFetchRejection:te,allowStaleOnFetchAbort:b,ignoreFetchAbort:x,perf:S}=t;if(S!==void 0&&typeof S?.now!=`function`)throw TypeError(`perf option must have a now() method if specified`);if(this.#s=S??rn,n!==0&&!dn(n))throw TypeError(`max option must be a nonnegative integer`);let C=n?fn(n):Array;if(!C)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(v!==void 0&&typeof v!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#o=v,_!==void 0&&typeof _!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#a=_,this.#w=!!_,this.#u=new Map,this.#d=Array(n).fill(void 0),this.#f=Array(n).fill(void 0),this.#p=new C(n),this.#m=new C(n),this.#h=0,this.#g=0,this.#_=mn.create(n),this.#c=0,this.#l=0,typeof l==`function`&&(this.#n=l),typeof u==`function`&&(this.#r=u),typeof d==`function`?(this.#i=d,this.#v=[]):(this.#i=void 0,this.#v=void 0),this.#C=!!this.#n,this.#E=!!this.#r,this.#T=!!this.#i,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!te,this.allowStaleOnFetchAbort=!!b,this.ignoreFetchAbort=!!x,this.maxEntrySize!==0){if(this.#t!==0&&!dn(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!dn(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#M()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!ee,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=dn(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!dn(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#D()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;un(t)&&(an.add(t),sn(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#u.has(e)?1/0:0}#D(){let e=new pn(this.#e),t=new pn(this.#e);this.#x=e,this.#b=t;let n=this.ttlAutopurge?Array(this.#e):void 0;this.#S=n,this.#A=(r,i,a=this.#s.now())=>{if(t[r]=i===0?0:a,e[r]=i,n?.[r]&&(clearTimeout(n[r]),n[r]=void 0),i!==0&&n){let e=setTimeout(()=>{this.#j(r)&&this.#W(this.#d[r],`expire`)},i+1);e.unref&&e.unref(),n[r]=e}},this.#O=n=>{t[n]=e[n]===0?0:this.#s.now()},this.#k=(n,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;n.ttl=o,n.start=s,n.now=r||i(),n.remainingTTL=o-(n.now-s)}};let r=0,i=()=>{let e=this.#s.now();if(this.ttlResolution>0){r=e;let t=setTimeout(()=>r=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=n=>{let a=this.#u.get(n);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((r||i())-s)},this.#j=n=>{let a=t[n],o=e[n];return!!o&&!!a&&(r||i())-a>o}}#O=()=>{};#k=()=>{};#A=()=>{};#j=()=>!1;#M(){let e=new pn(this.#e);this.#l=0,this.#y=e,this.#N=t=>{this.#l-=e[t],e[t]=0},this.#F=(e,t,n,r)=>{if(this.#V(t))return 0;if(!dn(n))if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!dn(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`);return n},this.#P=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#l>n;)this.#z(!0)}this.#l+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#l)}}#N=e=>{};#P=(e,t,n)=>{};#F=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#g;!(!this.#R(t)||((e||!this.#j(t))&&(yield t),t===this.#h));)t=this.#m[t]}*#L({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#h;!(!this.#R(t)||((e||!this.#j(t))&&(yield t),t===this.#g));)t=this.#p[t]}#R(e){return e!==void 0&&this.#u.get(this.#d[e])===e}*entries(){for(let e of this.#I())this.#f[e]!==void 0&&this.#d[e]!==void 0&&!this.#V(this.#f[e])&&(yield[this.#d[e],this.#f[e]])}*rentries(){for(let e of this.#L())this.#f[e]!==void 0&&this.#d[e]!==void 0&&!this.#V(this.#f[e])&&(yield[this.#d[e],this.#f[e]])}*keys(){for(let e of this.#I()){let t=this.#d[e];t!==void 0&&!this.#V(this.#f[e])&&(yield t)}}*rkeys(){for(let e of this.#L()){let t=this.#d[e];t!==void 0&&!this.#V(this.#f[e])&&(yield t)}}*values(){for(let e of this.#I())this.#f[e]!==void 0&&!this.#V(this.#f[e])&&(yield this.#f[e])}*rvalues(){for(let e of this.#L())this.#f[e]!==void 0&&!this.#V(this.#f[e])&&(yield this.#f[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#I()){let r=this.#f[n],i=this.#V(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#d[n],this))return this.get(this.#d[n],t)}}forEach(e,t=this){for(let n of this.#I()){let r=this.#f[n],i=this.#V(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#d[n],this)}}rforEach(e,t=this){for(let n of this.#L()){let r=this.#f[n],i=this.#V(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#d[n],this)}}purgeStale(){let e=!1;for(let t of this.#L({allowStale:!0}))this.#j(t)&&(this.#W(this.#d[t],`expire`),e=!0);return e}info(e){let t=this.#u.get(e);if(t===void 0)return;let n=this.#f[t],r=this.#V(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#x&&this.#b){let e=this.#x[t],n=this.#b[t];e&&n&&(i.ttl=e-(this.#s.now()-n),i.start=Date.now())}return this.#y&&(i.size=this.#y[t]),i}dump(){let e=[];for(let t of this.#I({allowStale:!0})){let n=this.#d[t],r=this.#f[t],i=this.#V(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#x&&this.#b){a.ttl=this.#x[t];let e=this.#s.now()-this.#b[t];a.start=Math.floor(Date.now()-e)}this.#y&&(a.size=this.#y[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=this.#s.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#F(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#W(e,`set`),this;let u=this.#c===0?void 0:this.#u.get(e);if(u===void 0)u=this.#c===0?this.#g:this.#_.length===0?this.#c===this.#e?this.#z(!1):this.#c:this.#_.pop(),this.#d[u]=e,this.#f[u]=t,this.#u.set(e,u),this.#p[this.#g]=u,this.#m[u]=this.#g,this.#g=u,this.#c++,this.#P(u,l,s),s&&(s.set=`add`),c=!1,this.#E&&this.#r?.(t,e,`add`);else{this.#U(u);let n=this.#f[u];if(t!==n){if(this.#w&&this.#V(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#C&&this.#n?.(t,e,`set`),this.#T&&this.#v?.push([t,e,`set`]))}else a||(this.#C&&this.#n?.(n,e,`set`),this.#T&&this.#v?.push([n,e,`set`]));if(this.#N(u),this.#P(u,l,s),this.#f[u]=t,s){s.set=`replace`;let e=n&&this.#V(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`);this.#E&&this.onInsert?.(t,e,t===n?`update`:`replace`)}if(r!==0&&!this.#x&&this.#D(),this.#x&&(c||this.#A(u,r,i),s&&this.#k(s,u)),!a&&this.#T&&this.#v){let e=this.#v,t;for(;t=e?.shift();)this.#i?.(...t)}return this}pop(){try{for(;this.#c;){let e=this.#f[this.#h];if(this.#z(!0),this.#V(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#T&&this.#v){let e=this.#v,t;for(;t=e?.shift();)this.#i?.(...t)}}}#z(e){let t=this.#h,n=this.#d[t],r=this.#f[t];return this.#w&&this.#V(r)?r.__abortController.abort(Error(`evicted`)):(this.#C||this.#T)&&(this.#C&&this.#n?.(r,n,`evict`),this.#T&&this.#v?.push([r,n,`evict`])),this.#N(t),this.#S?.[t]&&(clearTimeout(this.#S[t]),this.#S[t]=void 0),e&&(this.#d[t]=void 0,this.#f[t]=void 0,this.#_.push(t)),this.#c===1?(this.#h=this.#g=0,this.#_.length=0):this.#h=this.#p[t],this.#u.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#u.get(e);if(i!==void 0){let e=this.#f[i];if(this.#V(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#j(i))r&&(r.has=`stale`,this.#k(r,i));else return n&&this.#O(i),r&&(r.has=`hit`,this.#k(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#u.get(e);if(r===void 0||!n&&this.#j(r))return;let i=this.#f[r];return this.#V(i)?i.__staleWhileFetching:i}#B(e,t,n,r){let i=t===void 0?void 0:this.#f[t];if(this.#V(i))return i;let a=new cn,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0,l=n.ignoreFetchAbort||!!(n.allowStaleOnFetchAbort&&r!==void 0);if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason,l);let d=f,p=this.#f[t];return(p===f||c&&i&&p===void 0)&&(r===void 0?d.__staleWhileFetching===void 0?this.#W(e,`fetch`):this.#f[t]=d.__staleWhileFetching:(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e,!1)),u=(r,i)=>{let{aborted:o}=a.signal,s=o&&n.allowStaleOnFetchAbort,c=s||n.allowStaleOnFetchRejection,l=c||n.noDeleteOnFetchRejection,u=f;if(this.#f[t]===f&&(!l||!i&&u.__staleWhileFetching===void 0?this.#W(e,`fetch`):s||(this.#f[t]=u.__staleWhileFetching)),c)return n.status&&u.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw r},d=(t,r)=>{let o=this.#a?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#u.get(e)):this.#f[t]=p,p}#V(e){if(!this.#w)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof cn}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#w)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#u.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#B(e,y,v,m);return t.__returned=t}else{let t=this.#f[y];if(this.#V(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#j(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#U(y),r&&this.#O(y),g&&this.#k(g,y),t;let a=this.#B(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#o;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#u.get(e);if(o!==void 0){let t=this.#f[o],s=this.#V(t);return a&&this.#k(a,o),this.#j(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#W(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#U(o),r&&this.#O(o),t))}else a&&(a.get=`miss`)}#H(e,t){this.#m[t]=e,this.#p[e]=t}#U(e){e!==this.#g&&(e===this.#h?this.#h=this.#p[e]:this.#H(this.#m[e],this.#p[e]),this.#H(this.#g,e),this.#g=e)}delete(e){return this.#W(e,`delete`)}#W(e,t){let n=!1;if(this.#c!==0){let r=this.#u.get(e);if(r!==void 0)if(this.#S?.[r]&&(clearTimeout(this.#S?.[r]),this.#S[r]=void 0),n=!0,this.#c===1)this.#G(t);else{this.#N(r);let n=this.#f[r];if(this.#V(n)?n.__abortController.abort(Error(`deleted`)):(this.#C||this.#T)&&(this.#C&&this.#n?.(n,e,t),this.#T&&this.#v?.push([n,e,t])),this.#u.delete(e),this.#d[r]=void 0,this.#f[r]=void 0,r===this.#g)this.#g=this.#m[r];else if(r===this.#h)this.#h=this.#p[r];else{let e=this.#m[r];this.#p[e]=this.#p[r];let t=this.#p[r];this.#m[t]=this.#m[r]}this.#c--,this.#_.push(r)}}if(this.#T&&this.#v?.length){let e=this.#v,t;for(;t=e?.shift();)this.#i?.(...t)}return n}clear(){return this.#G(`delete`)}#G(e){for(let t of this.#L({allowStale:!0})){let n=this.#f[t];if(this.#V(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#d[t];this.#C&&this.#n?.(n,r,e),this.#T&&this.#v?.push([n,r,e])}}if(this.#u.clear(),this.#f.fill(void 0),this.#d.fill(void 0),this.#x&&this.#b){this.#x.fill(0),this.#b.fill(0);for(let e of this.#S??[])e!==void 0&&clearTimeout(e);this.#S?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#h=0,this.#g=0,this.#_.length=0,this.#l=0,this.#c=0,this.#T&&this.#v){let e=this.#v,t;for(;t=e?.shift();)this.#i?.(...t)}}},gn=typeof process==`object`&&process?process:{stdout:null,stderr:null},_n=e=>!!e&&typeof e==`object`&&(e instanceof Qn||e instanceof De||vn(e)||yn(e)),vn=e=>!!e&&typeof e==`object`&&e instanceof Ee&&typeof e.pipe==`function`&&e.pipe!==De.Writable.prototype.pipe,yn=e=>!!e&&typeof e==`object`&&e instanceof Ee&&typeof e.write==`function`&&typeof e.end==`function`,bn=Symbol(`EOF`),xn=Symbol(`maybeEmitEnd`),Sn=Symbol(`emittedEnd`),Cn=Symbol(`emittingEnd`),wn=Symbol(`emittedError`),Tn=Symbol(`closed`),En=Symbol(`read`),Dn=Symbol(`flush`),On=Symbol(`flushChunk`),I=Symbol(`encoding`),kn=Symbol(`decoder`),L=Symbol(`flowing`),An=Symbol(`paused`),jn=Symbol(`resume`),R=Symbol(`buffer`),z=Symbol(`pipes`),B=Symbol(`bufferLength`),Mn=Symbol(`bufferPush`),Nn=Symbol(`bufferShift`),V=Symbol(`objectMode`),H=Symbol(`destroyed`),Pn=Symbol(`error`),Fn=Symbol(`emitData`),In=Symbol(`emitEnd`),Ln=Symbol(`emitEnd2`),Rn=Symbol(`async`),zn=Symbol(`abort`),Bn=Symbol(`aborted`),Vn=Symbol(`signal`),Hn=Symbol(`dataListeners`),U=Symbol(`discarded`),Un=e=>Promise.resolve().then(e),Wn=e=>e(),Gn=e=>e===`end`||e===`finish`||e===`prefinish`,Kn=e=>e instanceof ArrayBuffer||!!e&&typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,qn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Jn=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[jn](),this.dest.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Yn=class extends Jn{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>this.dest.emit(`error`,e),e.on(`error`,this.proxyErrors)}},Xn=e=>!!e.objectMode,Zn=e=>!e.objectMode&&!!e.encoding&&e.encoding!==`buffer`,Qn=class extends Ee{[L]=!1;[An]=!1;[z]=[];[R]=[];[V];[I];[Rn];[kn];[bn]=!1;[Sn]=!1;[Cn]=!1;[Tn]=!1;[wn]=null;[B]=0;[H]=!1;[Vn];[Bn]=!1;[Hn]=0;[U]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding==`string`)throw TypeError(`Encoding and objectMode may not be used together`);Xn(t)?(this[V]=!0,this[I]=null):Zn(t)?(this[I]=t.encoding,this[V]=!1):(this[V]=!1,this[I]=null),this[Rn]=!!t.async,this[kn]=this[I]?new Oe(this[I]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[R]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[z]});let{signal:n}=t;n&&(this[Vn]=n,n.aborted?this[zn]():n.addEventListener(`abort`,()=>this[zn]()))}get bufferLength(){return this[B]}get encoding(){return this[I]}set encoding(e){throw Error(`Encoding must be set at instantiation time`)}setEncoding(e){throw Error(`Encoding must be set at instantiation time`)}get objectMode(){return this[V]}set objectMode(e){throw Error(`objectMode must be set at instantiation time`)}get async(){return this[Rn]}set async(e){this[Rn]=this[Rn]||!!e}[zn](){this[Bn]=!0,this.emit(`abort`,this[Vn]?.reason),this.destroy(this[Vn]?.reason)}get aborted(){return this[Bn]}set aborted(e){}write(e,t,n){if(this[Bn])return!1;if(this[bn])throw Error(`write after end`);if(this[H])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||=`utf8`;let r=this[Rn]?Un:Wn;if(!this[V]&&!Buffer.isBuffer(e)){if(qn(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Kn(e))e=Buffer.from(e);else if(typeof e!=`string`)throw Error(`Non-contiguous data written to non-objectMode stream`)}return this[V]?(this[L]&&this[B]!==0&&this[Dn](!0),this[L]?this.emit(`data`,e):this[Mn](e),this[B]!==0&&this.emit(`readable`),n&&r(n),this[L]):e.length?(typeof e==`string`&&!(t===this[I]&&!this[kn]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[I]&&(e=this[kn].write(e)),this[L]&&this[B]!==0&&this[Dn](!0),this[L]?this.emit(`data`,e):this[Mn](e),this[B]!==0&&this.emit(`readable`),n&&r(n),this[L]):(this[B]!==0&&this.emit(`readable`),n&&r(n),this[L])}read(e){if(this[H])return null;if(this[U]=!1,this[B]===0||e===0||e&&e>this[B])return this[xn](),null;this[V]&&(e=null),this[R].length>1&&!this[V]&&(this[R]=[this[I]?this[R].join(``):Buffer.concat(this[R],this[B])]);let t=this[En](e||null,this[R][0]);return this[xn](),t}[En](e,t){if(this[V])this[Nn]();else{let n=t;e===n.length||e===null?this[Nn]():typeof n==`string`?(this[R][0]=n.slice(e),t=n.slice(0,e),this[B]-=e):(this[R][0]=n.subarray(e),t=n.subarray(0,e),this[B]-=e)}return this.emit(`data`,t),!this[R].length&&!this[bn]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=`utf8`),e!==void 0&&this.write(e,t),n&&this.once(`end`,n),this[bn]=!0,this.writable=!1,(this[L]||!this[An])&&this[xn](),this}[jn](){this[H]||(!this[Hn]&&!this[z].length&&(this[U]=!0),this[An]=!1,this[L]=!0,this.emit(`resume`),this[R].length?this[Dn]():this[bn]?this[xn]():this.emit(`drain`))}resume(){return this[jn]()}pause(){this[L]=!1,this[An]=!0,this[U]=!1}get destroyed(){return this[H]}get flowing(){return this[L]}get paused(){return this[An]}[Mn](e){this[V]?this[B]+=1:this[B]+=e.length,this[R].push(e)}[Nn](){return this[V]?--this[B]:this[B]-=this[R][0].length,this[R].shift()}[Dn](e=!1){do;while(this[On](this[Nn]())&&this[R].length);!e&&!this[R].length&&!this[bn]&&this.emit(`drain`)}[On](e){return this.emit(`data`,e),this[L]}pipe(e,t){if(this[H])return e;this[U]=!1;let n=this[Sn];return t||={},e===gn.stdout||e===gn.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[z].push(t.proxyErrors?new Yn(this,e,t):new Jn(this,e,t)),this[Rn]?Un(()=>this[jn]()):this[jn]()),e}unpipe(e){let t=this[z].find(t=>t.dest===e);t&&(this[z].length===1?(this[L]&&this[Hn]===0&&(this[L]=!1),this[z]=[]):this[z].splice(this[z].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e===`data`)this[U]=!1,this[Hn]++,!this[z].length&&!this[L]&&this[jn]();else if(e===`readable`&&this[B]!==0)super.emit(`readable`);else if(Gn(e)&&this[Sn])super.emit(e),this.removeAllListeners(e);else if(e===`error`&&this[wn]){let e=t;this[Rn]?Un(()=>e.call(this,this[wn])):e.call(this,this[wn])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e===`data`&&(this[Hn]=this.listeners(`data`).length,this[Hn]===0&&!this[U]&&!this[z].length&&(this[L]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e===`data`||e===void 0)&&(this[Hn]=0,!this[U]&&!this[z].length&&(this[L]=!1)),t}get emittedEnd(){return this[Sn]}[xn](){!this[Cn]&&!this[Sn]&&!this[H]&&this[R].length===0&&this[bn]&&(this[Cn]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[Tn]&&this.emit(`close`),this[Cn]=!1)}emit(e,...t){let n=t[0];if(e!==`error`&&e!==`close`&&e!==H&&this[H])return!1;if(e===`data`)return!this[V]&&!n?!1:this[Rn]?(Un(()=>this[Fn](n)),!0):this[Fn](n);if(e===`end`)return this[In]();if(e===`close`){if(this[Tn]=!0,!this[Sn]&&!this[H])return!1;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}else if(e===`error`){this[wn]=n,super.emit(Pn,n);let e=!this[Vn]||this.listeners(`error`).length?super.emit(`error`,n):!1;return this[xn](),e}else if(e===`resume`){let e=super.emit(`resume`);return this[xn](),e}else if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,...t);return this[xn](),r}[Fn](e){for(let t of this[z])t.dest.write(e)===!1&&this.pause();let t=!this[U]&&super.emit(`data`,e);return this[xn](),t}[In](){return this[Sn]?!1:(this[Sn]=!0,this.readable=!1,this[Rn]?(Un(()=>this[Ln]()),!0):this[Ln]())}[Ln](){if(this[kn]){let e=this[kn].end();if(e){for(let t of this[z])t.dest.write(e);this[U]||super.emit(`data`,e)}}for(let e of this[z])e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}async collect(){let e=Object.assign([],{dataLength:0});this[V]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[V]||(e.dataLength+=t.length)}),await t,e}async concat(){if(this[V])throw Error(`cannot concat in objectMode`);let e=await this.collect();return this[I]?e.join(``):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(H,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[Symbol.asyncIterator](){this[U]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[bn])return t();let r,i,a=e=>{this.off(`data`,o),this.off(`end`,s),this.off(H,c),t(),i(e)},o=e=>{this.off(`error`,a),this.off(`end`,s),this.off(H,c),this.pause(),r({value:e,done:!!this[bn]})},s=()=>{this.off(`error`,a),this.off(`data`,o),this.off(H,c),t(),r({done:!0,value:void 0})},c=()=>a(Error(`stream destroyed`));return new Promise((e,t)=>{i=t,r=e,this.once(H,c),this.once(`error`,a),this.once(`end`,s),this.once(`data`,o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let e=!1,t=()=>(this.pause(),this.off(Pn,t),this.off(H,t),this.off(`end`,t),e=!0,{done:!0,value:void 0});return this.once(`end`,t),this.once(Pn,t),this.once(H,t),{next:()=>{if(e)return t();let n=this.read();return n===null?t():{done:!1,value:n}},throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[H])return e?this.emit(`error`,e):this.emit(H),this;this[H]=!0,this[U]=!0,this[R].length=0,this[B]=0;let t=this;return typeof t.close==`function`&&!this[Tn]&&t.close(),e?this.emit(`error`,e):this.emit(H),this}static get isStream(){return _n}},$n={lstatSync:he,readdir:_e,readdirSync:ve,readlinkSync:ye,realpathSync:be.native,promises:{lstat:ce,readdir:le,readlink:ue,realpath:de}},er=e=>!e||e===$n||e===te?$n:{...$n,...e,promises:{...$n.promises,...e.promises||{}}},tr=/^\\\\\?\\([a-z]:)\\?$/i,nr=e=>e.replace(/\//g,`\\`).replace(tr,`$1\\`),rr=/[\\\/]/,W=0,ir=1,ar=2,or=4,sr=6,cr=8,lr=10,ur=12,G=15,dr=~G,fr=16,pr=32,mr=64,K=128,hr=256,gr=512,_r=mr|K|gr,vr=1023,yr=e=>e.isFile()?cr:e.isDirectory()?or:e.isSymbolicLink()?lr:e.isCharacterDevice()?ar:e.isBlockDevice()?sr:e.isSocket()?ur:e.isFIFO()?ir:W,br=new hn({max:2**12}),xr=e=>{let t=br.get(e);if(t)return t;let n=e.normalize(`NFKD`);return br.set(e,n),n},Sr=new hn({max:2**12}),Cr=e=>{let t=Sr.get(e);if(t)return t;let n=xr(e.toLowerCase());return Sr.set(e,n),n},wr=class extends hn{constructor(){super({max:256})}},Tr=class extends hn{constructor(e=16*1024){super({maxSize:e,sizeCalculation:e=>e.length+1})}},Er=Symbol(`PathScurry setAsCwd`),q=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#i;get uid(){return this.#i}#a;get gid(){return this.#a}#o;get rdev(){return this.#o}#s;get blksize(){return this.#s}#c;get ino(){return this.#c}#l;get size(){return this.#l}#u;get blocks(){return this.#u}#d;get atimeMs(){return this.#d}#f;get mtimeMs(){return this.#f}#p;get ctimeMs(){return this.#p}#m;get birthtimeMs(){return this.#m}#h;get atime(){return this.#h}#g;get mtime(){return this.#g}#_;get ctime(){return this.#_}#v;get birthtime(){return this.#v}#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=W,n,r,i,a,o){this.name=e,this.#y=i?Cr(e):xr(e),this.#T=t&vr,this.nocase=i,this.roots=r,this.root=n||this,this.#E=a,this.#x=o.fullpath,this.#C=o.relative,this.#w=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=er(o.fs)}depth(){return this.#b===void 0?this.parent?this.#b=this.parent.depth()+1:this.#b=0:this.#b}childrenCache(){return this.#E}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#k(n):this.#k(n)}#k(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#E.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#E.set(this,t),this.#T&=~fr,t}child(e,t){if(e===``||e===`.`)return this;if(e===`..`)return this.parent||this;let n=this.children(),r=this.nocase?Cr(e):xr(e);for(let e of n)if(e.#y===r)return e;let i=this.parent?this.sep:``,a=this.#x?this.#x+i+e:void 0,o=this.newChild(e,W,{...t,parent:this,fullpath:a});return this.canReaddir()||(o.#T|=K),n.push(o),o}relative(){if(this.isCWD)return``;if(this.#C!==void 0)return this.#C;let e=this.name,t=this.parent;if(!t)return this.#C=this.name;let n=t.relative();return n+(!n||!t.parent?``:this.sep)+e}relativePosix(){if(this.sep===`/`)return this.relative();if(this.isCWD)return``;if(this.#w!==void 0)return this.#w;let e=this.name,t=this.parent;if(!t)return this.#w=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?``:`/`)+e}fullpath(){if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.name;let n=t.fullpath()+(t.parent?this.sep:``)+e;return this.#x=n}fullpathPosix(){if(this.#S!==void 0)return this.#S;if(this.sep===`/`)return this.#S=this.fullpath();if(!this.parent){let e=this.fullpath().replace(/\\/g,`/`);return/^[a-z]:\//i.test(e)?this.#S=`//?/${e}`:this.#S=e}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?``:`/`)+this.name;return this.#S=n}isUnknown(){return(this.#T&G)===W}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?`Unknown`:this.isDirectory()?`Directory`:this.isFile()?`File`:this.isSymbolicLink()?`SymbolicLink`:this.isFIFO()?`FIFO`:this.isCharacterDevice()?`CharacterDevice`:this.isBlockDevice()?`BlockDevice`:this.isSocket()?`Socket`:`Unknown`}isFile(){return(this.#T&G)===cr}isDirectory(){return(this.#T&G)===or}isCharacterDevice(){return(this.#T&G)===ar}isBlockDevice(){return(this.#T&G)===sr}isFIFO(){return(this.#T&G)===ir}isSocket(){return(this.#T&G)===ur}isSymbolicLink(){return(this.#T&lr)===lr}lstatCached(){return this.#T&pr?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#O}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let e=this.#T&G;return!(e!==W&&e!==lr||this.#T&hr||this.#T&K)}calledReaddir(){return!!(this.#T&fr)}isENOENT(){return!!(this.#T&K)}isNamed(e){return this.nocase?this.#y===Cr(e):this.#y===xr(e)}async readlink(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return this.#D=t}catch(e){this.#L(e.code);return}}readlinkSync(){let e=this.#D;if(e)return e;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return this.#D=t}catch(e){this.#L(e.code);return}}#A(e){this.#T|=fr;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#j()}}#j(){this.#T&K||(this.#T=(this.#T|K)&dr,this.#M())}#M(){let e=this.children();e.provisional=0;for(let t of e)t.#j()}#N(){this.#T|=gr,this.#P()}#P(){if(this.#T&mr)return;let e=this.#T;(e&G)===or&&(e&=dr),this.#T=e|mr,this.#M()}#F(e=``){e===`ENOTDIR`||e===`EPERM`?this.#P():e===`ENOENT`?this.#j():this.children().provisional=0}#I(e=``){e===`ENOTDIR`?this.parent.#P():e===`ENOENT`&&this.#j()}#L(e=``){let t=this.#T;t|=hr,e===`ENOENT`&&(t|=K),(e===`EINVAL`||e===`UNKNOWN`)&&(t&=dr),this.#T=t,e===`ENOTDIR`&&this.parent&&this.parent.#P()}#R(e,t){return this.#B(e,t)||this.#z(e,t)}#z(e,t){let n=yr(e),r=this.newChild(e.name,n,{parent:this}),i=r.#T&G;return i!==or&&i!==lr&&i!==W&&(r.#T|=mr),t.unshift(r),t.provisional++,r}#B(e,t){for(let n=t.provisional;n<t.length;n++){let r=t[n];if((this.nocase?Cr(e.name):xr(e.name))===r.#y)return this.#V(e,r,n,t)}}#V(e,t,n,r){let i=t.name;return t.#T=t.#T&dr|yr(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if((this.#T&K)===0)try{return this.#H(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#I(e.code)}}lstatSync(){if((this.#T&K)===0)try{return this.#H(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#I(e.code)}}#H(e){let{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:a,blocks:o,ctime:s,ctimeMs:c,dev:l,gid:u,ino:d,mode:f,mtime:p,mtimeMs:m,nlink:h,rdev:g,size:_,uid:v}=e;this.#h=t,this.#d=n,this.#v=r,this.#m=i,this.#s=a,this.#u=o,this.#_=s,this.#p=c,this.#t=l,this.#a=u,this.#c=d,this.#n=f,this.#g=p,this.#f=m,this.#r=h,this.#o=g,this.#l=_,this.#i=v;let y=yr(e);this.#T=this.#T&dr|y|pr,y!==W&&y!==or&&y!==lr&&(this.#T|=mr)}#U=[];#W=!1;#G(e){this.#W=!1;let t=this.#U.slice();this.#U.length=0,t.forEach(t=>t(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let r=n.slice(0,n.provisional);t?e(null,r):queueMicrotask(()=>e(null,r));return}if(this.#U.push(e),this.#W)return;this.#W=!0;let r=this.fullpath();this.#e.readdir(r,{withFileTypes:!0},(e,t)=>{if(e)this.#F(e.code),n.provisional=0;else{for(let e of t)this.#R(e,n);this.#A(n)}this.#G(n.slice(0,n.provisional))})}#K;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#K)await this.#K;else{let n=()=>{};this.#K=new Promise(e=>n=e);try{for(let n of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#R(n,e);this.#A(e)}catch(t){this.#F(t.code),e.provisional=0}this.#K=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#R(n,e);this.#A(e)}catch(t){this.#F(t.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#T&_r)return!1;let e=G&this.#T;return e===W||e===or||e===lr}shouldWalk(e,t){return(this.#T&or)===or&&!(this.#T&_r)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#O)return this.#O;if(!((gr|hr|K)&this.#T))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#O=this.resolve(e)}catch{this.#N()}}realpathSync(){if(this.#O)return this.#O;if(!((gr|hr|K)&this.#T))try{let e=this.#e.realpathSync(this.fullpath());return this.#O=this.resolve(e)}catch{this.#N()}}[Er](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],r=this;for(;r&&r.parent;)t.add(r),r.#C=n.join(this.sep),r.#w=n.join(`/`),r=r.parent,n.push(`..`);for(r=e;r&&r.parent&&!t.has(r);)r.#C=void 0,r.#w=void 0,r=r.parent}},Dr=class e extends q{sep=`\\`;splitSep=rr;constructor(e,t=W,n,r,i,a,o){super(e,t,n,r,i,a,o)}newChild(t,n=W,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return ne.parse(e).root}getRoot(e){if(e=nr(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new Ar(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,`\\`).replace(tr,`$1\\`),e===t}},Or=class e extends q{splitSep=`/`;sep=`/`;constructor(e,t=W,n,r,i,a,o){super(e,t,n,r,i,a,o)}getRootString(e){return e.startsWith(`/`)?`/`:``}getRoot(e){return this.root}newChild(t,n=W,r={}){return new e(t,n,this.root,this.roots,this.nocase,this.childrenCache(),r)}},kr=class{root;rootPath;roots;cwd;#e;#t;#n;nocase;#r;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16*1024,fs:a=$n}={}){this.#r=er(a),(e instanceof URL||e.startsWith(`file://`))&&(e=re(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new wr,this.#t=new wr,this.#n=new Tr(i);let s=o.substring(this.rootPath.length).split(n);if(s.length===1&&!s[0]&&s.pop(),r===void 0)throw TypeError(`must provide nocase setting to PathScurryBase ctor`);this.nocase=r,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,l=s.length-1,u=t.sep,d=this.rootPath,f=!1;for(let e of s){let t=l--;c=c.child(e,{relative:Array(t).fill(`..`).join(u),relativePosix:Array(t).fill(`..`).join(`/`),fullpath:d+=(f?``:u)+e}),f=!0}this.cwd=c}depth(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#e.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpath();return this.#e.set(t,r),r}resolvePosix(...e){let t=``;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(!r||r===`.`)&&(t=t?`${r}/${t}`:r,this.isAbsolute(r)))break}let n=this.#t.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,r),r}relative(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let t=await e.readdir();return n?t:t.map(e=>e.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(e=>e.name):[]}async lstat(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e==`string`&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set,c=(e,t)=>{s.add(e),e.readdirCB((e,l)=>{if(e)return t(e);let u=l.length;if(!u)return t();let d=()=>{--u===0&&t()};for(let e of l)(!i||i(e))&&o.push(n?e:e.fullpath()),r&&e.isSymbolicLink()?e.realpath().then(e=>e?.isUnknown()?e.lstat():e).then(e=>e?.shouldWalk(s,a)?c(e,d):d()):e.shouldWalk(s,a)?c(e,d):d()},!0)},l=e;return new Promise((e,t)=>{c(l,n=>{if(n)return t(n);e(o)})})}walkSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=[];(!i||i(e))&&o.push(n?e:e.fullpath());let s=new Set([e]);for(let e of s){let t=e.readdirSync();for(let e of t){(!i||i(e))&&o.push(n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&s.add(t)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield n?e:e.fullpath());let o=new Set([e]);for(let e of o){let t=e.readdirSync();for(let e of t){(!i||i(e))&&(yield n?e:e.fullpath());let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(o,a)&&o.add(t)}}}stream(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new Qn({objectMode:!0});(!i||i(e))&&o.write(n?e:e.fullpath());let s=new Set,c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let d=(t,p,m=!1)=>{if(t)return o.emit(`error`,t);if(r&&!m){let e=[];for(let t of p)t.isSymbolicLink()&&e.push(t.realpath().then(e=>e?.isUnknown()?e.lstat():e));if(e.length){Promise.all(e).then(()=>d(null,p,!0));return}}for(let t of p)t&&(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of p){let t=e.realpathCached()||e;t.shouldWalk(s,a)&&c.push(t)}e&&!o.flowing?o.once(`drain`,u):f||u()},f=!0;t.readdirCB(d,!0),f=!1}};return u(),o}streamSync(e=this.cwd,t={}){typeof e==`string`?e=this.cwd.resolve(e):e instanceof q||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:a}=t,o=new Qn({objectMode:!0}),s=new Set;(!i||i(e))&&o.write(n?e:e.fullpath());let c=[e],l=0,u=()=>{let e=!1;for(;!e;){let t=c.shift();if(!t){l===0&&o.end();return}l++,s.add(t);let u=t.readdirSync();for(let t of u)(!i||i(t))&&(o.write(n?t:t.fullpath())||(e=!0));l--;for(let e of u){let t=e;if(e.isSymbolicLink()){if(!(r&&(t=e.realpathSync())))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(s,a)&&c.push(t)}}e&&!o.flowing&&o.once(`drain`,u)};return u(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e==`string`?this.cwd.resolve(e):e,this.cwd[Er](t)}},Ar=class extends kr{sep=`\\`;constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,ne,`\\`,{...t,nocase:n}),this.nocase=n;for(let e=this.cwd;e;e=e.parent)e.nocase=this.nocase}parseRootPath(e){return ne.parse(e).root.toUpperCase()}newRoot(e){return new Dr(this.rootPath,or,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)||e.startsWith(`\\`)||/^[a-z]:(\/|\\)/i.test(e)}},jr=class extends kr{sep=`/`;constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,S,`/`,{...t,nocase:n}),this.nocase=n}parseRootPath(e){return`/`}newRoot(e){return new Or(this.rootPath,or,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith(`/`)}},Mr=class extends jr{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}};process.platform;var Nr=process.platform===`win32`?Ar:process.platform===`darwin`?Mr:jr,Pr=e=>e.length>=1,Fr=e=>e.length>=1,Ir=Symbol.for(`nodejs.util.inspect.custom`),Lr=class e{#e;#t;#n;length;#r;#i;#a;#o;#s;#c;#l=!0;constructor(e,t,n,r){if(!Pr(e))throw TypeError(`empty pattern list`);if(!Fr(t))throw TypeError(`empty glob list`);if(t.length!==e.length)throw TypeError(`mismatched pattern list and glob list lengths`);if(this.length=e.length,n<0||n>=this.length)throw TypeError(`index out of range`);if(this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#n===0){if(this.isUNC()){let[e,t,n,r,...i]=this.#e,[a,o,s,c,...l]=this.#t;i[0]===``&&(i.shift(),l.shift());let u=[e,t,n,r,``].join(`/`),d=[a,o,s,c,``].join(`/`);this.#e=[u,...i],this.#t=[d,...l],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[e,...t]=this.#e,[n,...r]=this.#t;t[0]===``&&(t.shift(),r.shift());let i=e+`/`,a=n+`/`;this.#e=[i,...t],this.#t=[a,...r],this.length=this.#e.length}}}[Ir](){return`Pattern <`+this.#t.slice(this.#n).join(`/`)+`>`}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]==`string`}isGlobstar(){return this.#e[this.#n]===P}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#a=this.#a||(this.#n===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join(`/`):this.#t.join(`/`):this.#t.slice(this.#n).join(`/`))}hasMore(){return this.length>this.#n+1}rest(){return this.#i===void 0?this.hasMore()?(this.#i=new e(this.#e,this.#t,this.#n+1,this.#r),this.#i.#c=this.#c,this.#i.#s=this.#s,this.#i.#o=this.#o,this.#i):this.#i=null:this.#i}isUNC(){let e=this.#e;return this.#s===void 0?this.#s=this.#r===`win32`&&this.#n===0&&e[0]===``&&e[1]===``&&typeof e[2]==`string`&&!!e[2]&&typeof e[3]==`string`&&!!e[3]:this.#s}isDrive(){let e=this.#e;return this.#o===void 0?this.#o=this.#r===`win32`&&this.#n===0&&this.length>1&&typeof e[0]==`string`&&/^[a-z]:$/i.test(e[0]):this.#o}isAbsolute(){let e=this.#e;return this.#c===void 0?this.#c=e[0]===``&&e.length>1||this.isDrive()||this.isUNC():this.#c}root(){let e=this.#e[0];return typeof e==`string`&&this.isAbsolute()&&this.#n===0?e:``}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}},Rr=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`,zr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:a=Rr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let t of e)this.add(t)}add(e){let t=new nn(e,this.mmopts);for(let e=0;e<t.set.length;e++){let n=t.set[e],r=t.globParts[e];if(!n||!r)throw Error(`invalid pattern object`);for(;n[0]===`.`&&r[0]===`.`;)n.shift(),r.shift();let i=new Lr(n,r,0,this.platform),a=new nn(i.globString(),this.mmopts),o=r[r.length-1]===`**`,s=i.isAbsolute();s?this.absolute.push(a):this.relative.push(a),o&&(s?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),n=`${t}/`,r=e.relative()||`.`,i=`${r}/`;for(let e of this.relative)if(e.match(r)||e.match(i))return!0;for(let e of this.absolute)if(e.match(t)||e.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+`/`,n=(e.relative()||`.`)+`/`;for(let e of this.relativeChildren)if(e.match(n))return!0;for(let e of this.absoluteChildren)if(e.match(t))return!0;return!1}},Br=class e{store;constructor(e=new Map){this.store=e}copy(){return new e(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},Vr=class{store=new Map;add(e,t,n){let r=(t?2:0)|!!n,i=this.store.get(e);this.store.set(e,i===void 0?r:r&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Hr=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(e=>e.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw Error(`attempting to walk unknown path`);return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},Ur=class e{hasWalkedCache;matches=new Vr;subwalks=new Hr;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Br}processPatterns(e,t){this.patterns=t;let n=t.map(t=>[e,t]);for(let[e,t]of n){this.hasWalkedCache.storeWalked(e,t);let n=t.root(),r=t.isAbsolute()&&this.opts.absolute!==!1;if(n){e=e.resolve(n===`/`&&this.opts.root!==void 0?this.opts.root:n);let r=t.rest();if(r)t=r;else{this.matches.add(e,!0,!1);continue}}if(e.isENOENT())continue;let i,a,o=!1;for(;typeof(i=t.pattern())==`string`&&(a=t.rest());)e=e.resolve(i),t=a,o=!0;if(i=t.pattern(),a=t.rest(),o){if(this.hasWalkedCache.hasWalked(e,t))continue;this.hasWalkedCache.storeWalked(e,t)}if(typeof i==`string`){let t=i===`..`||i===``||i===`.`;this.matches.add(e.resolve(i),r,t);continue}else if(i===P){(!e.isSymbolicLink()||this.follow||t.checkFollowGlobstar())&&this.subwalks.add(e,t);let n=a?.pattern(),i=a?.rest();if(!a||(n===``||n===`.`)&&!i)this.matches.add(e,r,n===``||n===`.`);else if(n===`..`){let t=e.parent||e;i?this.hasWalkedCache.hasWalked(t,i)||this.subwalks.add(t,i):this.matches.add(t,r,!0)}}else i instanceof RegExp&&this.subwalks.add(e,t)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new e(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),r=this.child();for(let e of t)for(let t of n){let n=t.isAbsolute(),i=t.pattern(),a=t.rest();i===P?r.testGlobstar(e,t,a,n):i instanceof RegExp?r.testRegExp(e,i,a,n):r.testString(e,i,a,n)}return r}testGlobstar(e,t,n,r){if((this.dot||!e.name.startsWith(`.`))&&(t.hasMore()||this.matches.add(e,r,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let t=n.pattern();if(typeof t==`string`&&t!==`..`&&t!==``&&t!==`.`)this.testString(e,t,n.rest(),r);else if(t===`..`){let t=e.parent||e;this.subwalks.add(t,n)}else t instanceof RegExp&&this.testRegExp(e,t,n.rest(),r)}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}},Wr=(e,t)=>typeof e==`string`?new zr([e],t):Array.isArray(e)?new zr(e,t):e,Gr=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#n;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#n=!n.posix&&n.platform===`win32`?`\\`:`/`,this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#t=Wr(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!=`function`))throw Error(`cannot ignore child matches, ignore lacks add() method.`);this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener(`abort`,()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let e=await r.realpath();e&&(e.isUnknown()||this.opts.stat)&&await e.lstat()}return this.matchCheckTest(r,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let r=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let e=r.realpathSync();e&&(e?.isUnknown()||this.opts.stat)&&e.lstatSync()}return this.matchCheckTest(r,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let t=`${e.relativePosix()}/**`;this.#t.add(t)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let r=this.opts.mark&&e.isDirectory()?this.#n:``;if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let t=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(t+r)}else{let t=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!t.startsWith(`..`+this.#n)?`.`+this.#n:``;this.matchEmit(t?n+t+r:`.`+r)}}async match(e,t,n){let r=await this.matchCheck(e,n);r&&this.matchFinish(r,t)}matchSync(e,t,n){let r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new Ur(this.opts),n)}walkCB2(e,t,n,r){if(this.#i(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries())this.#r(e)||(i++,this.match(e,t,r).then(()=>a()));for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirCached();e.calledReaddir()?this.walkCB3(e,t,n,a):e.readdirCB((t,r)=>this.walkCB3(e,r,n,a),!0)}a()}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries())this.#r(e)||(i++,this.match(e,t,r).then(()=>a()));for(let[e,t]of n.subwalks.entries())i++,this.walkCB2(e,t,n.child(),a);a()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new Ur(this.opts),n)}walkCB2Sync(e,t,n,r){if(this.#i(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,r));return}n.processPatterns(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries())this.#r(e)||this.matchSync(e,t,r);for(let e of n.subwalkTargets()){if(this.maxDepth!==1/0&&e.depth()>=this.maxDepth)continue;i++;let t=e.readdirSync();this.walkCB3Sync(e,t,n,a)}a()}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1,a=()=>{--i===0&&r()};for(let[e,t,r]of n.matches.entries())this.#r(e)||this.matchSync(e,t,r);for(let[e,t]of n.subwalks.entries())i++,this.walkCB2Sync(e,t,n.child(),a);a()}},Kr=class extends Gr{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},qr=class extends Gr{results;constructor(e,t,n){super(e,t,n),this.results=new Qn({signal:this.signal,objectMode:!0}),this.results.on(`drain`,()=>this.resume()),this.results.on(`resume`,()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},Jr=typeof process==`object`&&process&&typeof process.platform==`string`?process.platform:`linux`,Yr=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw TypeError(`glob options required`);if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith(`file://`))&&(t.cwd=re(t.cwd)):this.cwd=``,this.cwd=t.cwd||``,this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth==`number`?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw Error(`cannot set absolute and withFileTypes:true`);if(typeof e==`string`&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(e=>e.replace(/\\/g,`/`))),this.matchBase){if(t.noglobstar)throw TypeError(`base matching requires globstar`);e=e.map(e=>e.includes(`/`)?e:`./**/${e}`)}if(this.pattern=e,this.platform=t.platform||Jr,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw Error(`nocase option contradicts provided scurry option`)}else{let e=t.platform===`win32`?Ar:t.platform===`darwin`?Mr:t.platform?jr:Nr;this.scurry=new e(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform===`darwin`||this.platform===`win32`,r={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},[i,a]=this.pattern.map(e=>new nn(e,r)).reduce((e,t)=>(e[0].push(...t.set),e[1].push(...t.globParts),e),[[],[]]);this.patterns=i.map((e,t)=>{let n=a[t];if(!n)throw Error(`invalid pattern object`);return new Lr(e,n,0,this.platform)})}async walk(){return[...await new Kr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Kr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new qr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new qr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth===1/0?1/0:this.maxDepth+this.scurry.cwd.depth(),platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},Xr=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let n of e)if(new nn(n,t).hasMagic())return!0;return!1};function Zr(e,t={}){return new Yr(e,t).streamSync()}function Qr(e,t={}){return new Yr(e,t).stream()}function $r(e,t={}){return new Yr(e,t).walkSync()}async function ei(e,t={}){return new Yr(e,t).walk()}function ti(e,t={}){return new Yr(e,t).iterateSync()}function ni(e,t={}){return new Yr(e,t).iterate()}var ri=Zr,ii=Object.assign(Qr,{sync:Zr}),ai=ti,oi=Object.assign(ni,{sync:ti}),si=Object.assign($r,{stream:Zr,iterate:ti}),ci=Object.assign(ei,{glob:ei,globSync:$r,sync:si,globStream:Qr,stream:ii,globStreamSync:Zr,streamSync:ri,globIterate:ni,iterate:oi,globIterateSync:ti,iterateSync:ai,Glob:Yr,hasMagic:Xr,escape:Dt,unescape:mt});ci.glob=ci;const li=(e,t)=>e===void 0||typeof e===t,ui=e=>!!e&&typeof e==`object`&&li(e.preserveRoot,`boolean`)&&li(e.tmp,`string`)&&li(e.maxRetries,`number`)&&li(e.retryDelay,`number`)&&li(e.backoff,`number`)&&li(e.maxBackoff,`number`)&&(li(e.glob,`boolean`)||e.glob&&typeof e.glob==`object`)&&li(e.filter,`function`),di=e=>{if(!ui(e))throw Error(`invalid rimraf options`)},fi=e=>{di(e);let{glob:t,...n}=e;if(!t)return n;let r=t===!0?e.signal?{signal:e.signal}:{}:e.signal?{signal:e.signal,...t}:t;return{...n,glob:{...r,absolute:!0,withFileTypes:!1}}},pi=(e={})=>fi(e),mi=(e={})=>fi(e),hi=(e,t={})=>{let n=typeof e;if(n!==`string`){let t=e&&n===`object`&&e.constructor,r=`The "path" argument must be of type string. Received ${t&&t.name?`an instance of ${t.name}`:n===`object`?ke(e):`type ${n} ${e}`}`;throw Object.assign(TypeError(r),{path:e,code:`ERR_INVALID_ARG_TYPE`})}if(/\0/.test(e))throw Object.assign(TypeError(`path must be a string without null bytes`),{path:e,code:`ERR_INVALID_ARG_VALUE`});e=M(e);let{root:r}=j(e);if(e===r&&t.preserveRoot!==!1)throw Object.assign(Error(`refusing to remove root directory without preserveRoot:false`),{path:e,code:`ERR_PRESERVE_ROOT`});if(process.platform===`win32`){let t=/[*|"<>?:]/,{root:n}=j(e);if(t.test(e.substring(n.length)))throw Object.assign(Error(`Illegal characters in path.`),{path:e,code:`EINVAL`})}return e},gi=e=>ve(e,{withFileTypes:!0}),_i={chmod:Ae.chmod,mkdir:Ae.mkdir,readdir:e=>Ae.readdir(e,{withFileTypes:!0}),rename:Ae.rename,rm:Ae.rm,rmdir:Ae.rmdir,stat:Ae.stat,lstat:Ae.lstat,unlink:Ae.unlink},{readdir:vi}=_i,yi=e=>vi(e).catch(e=>e),bi=e=>{try{return gi(e)}catch(e){return e}},xi=e=>!!e&&typeof e==`object`,Si=(e,t)=>t in e&&typeof e[t]==`string`,Ci=e=>xi(e)&&Si(e,`code`)&&Si(e,`path`),J=e=>xi(e)&&Si(e,`code`)?e.code:null,Y=async(e,t)=>e.catch(e=>{if(J(e)!==`ENOENT`)throw t??e}),X=(e,t)=>{try{return e()}catch(e){if(J(e)===`ENOENT`)return;throw t??e}},{lstat:wi,rmdir:Ti,unlink:Ei}=_i,Di=async(e,t)=>(t?.signal?.throwIfAborted(),await Y(wi(e).then(n=>ki(e,t,n)))??!0),Oi=(e,t)=>(t?.signal?.throwIfAborted(),X(()=>Ai(e,t,ge(e)))??!0),ki=async(e,t,n)=>{t?.signal?.throwIfAborted();let r=n.isDirectory()?await yi(e):null;if(!Array.isArray(r)){if(r){if(J(r)===`ENOENT`)return!0;if(J(r)!==`ENOTDIR`)throw r}return t.filter&&!await t.filter(e,n)?!1:(await Y(Ei(e)),!0)}return!(await Promise.all(r.map(n=>ki(M(e,n.name),t,n)))).every(e=>e===!0)||t.preserveRoot===!1&&e===j(e).root||t.filter&&!await t.filter(e,n)?!1:(await Y(Ti(e)),!0)},Ai=(e,t,n)=>{t?.signal?.throwIfAborted();let r=n.isDirectory()?bi(e):null;if(!Array.isArray(r)){if(r){if(J(r)===`ENOENT`)return!0;if(J(r)!==`ENOTDIR`)throw r}return t.filter&&!t.filter(e,n)?!1:(X(()=>Te(e)),!0)}let i=!0;for(let n of r){let r=M(e,n.name);i=Ai(r,t,n)&&i}return t.preserveRoot===!1&&e===j(e).root||!i||t.filter&&!t.filter(e,n)?!1:(X(()=>Ce(e)),!0)},{chmod:ji}=_i,Mi=e=>async t=>{try{await Y(e(t));return}catch(n){if(J(n)===`EPERM`){if(!await Y(ji(t,438).then(()=>!0),n))return;await e(t);return}throw n}},Ni=e=>t=>{try{X(()=>e(t));return}catch(n){if(J(n)===`EPERM`){if(!X(()=>(me(t,438),!0),n))return;e(t);return}throw n}},Pi=new Set([`EMFILE`,`ENFILE`,`EBUSY`]),Fi=e=>{let t=async(n,r,i=1,a=0)=>{let o=r.maxBackoff||200,s=r.backoff||1.2,c=r.maxRetries||10,l=0;for(;;)try{return await e(n)}catch(e){if(Ci(e)&&e.path===n&&Pi.has(e.code)){if(i=Math.ceil(i*s),a=i+a,a<o)return await je(i),t(n,r,i,a);if(l<c){l++;continue}}throw e}};return t},Ii=e=>(t,n)=>{let r=n.maxRetries||10,i=0;for(;;)try{return e(t)}catch(e){if(Ci(e)&&e.path===t&&Pi.has(e.code)&&i<r){i++;continue}throw e}},{stat:Li}=_i,Ri=e=>{try{return we(e).isDirectory()}catch{return!1}},zi=e=>Li(e).then(e=>e.isDirectory(),()=>!1),Bi=async e=>{let{root:t}=j(e),n=Me(),{root:r}=j(n);if(t.toLowerCase()===r.toLowerCase())return n;let i=M(t,`/temp`);return await zi(i)?i:t},Vi=e=>{let{root:t}=j(e),n=Me(),{root:r}=j(n);if(t.toLowerCase()===r.toLowerCase())return n;let i=M(t,`/temp`);return Ri(i)?i:t},Hi=async()=>Me(),Ui=()=>Me(),Wi=process.platform===`win32`?Bi:Hi,Gi=process.platform===`win32`?Vi:Ui,{lstat:Ki,rename:qi,unlink:Ji,rmdir:Yi}=_i,Xi=e=>`.${A(e)}.${Math.random()}`,Zi=Mi(Ji),Qi=Ni(Te),$i=async(e,t)=>(t?.signal?.throwIfAborted(),await Y(Ki(e).then(n=>ea(e,t,n)))??!0),ea=async(e,t,n)=>{if(t?.signal?.throwIfAborted(),!t.tmp)return ea(e,{...t,tmp:await Wi(e)},n);if(e===t.tmp&&j(e).root!==e)throw Error(`cannot delete temp directory used for deletion`);let r=n.isDirectory()?await yi(e):null;if(!Array.isArray(r)){if(r){if(J(r)===`ENOENT`)return!0;if(J(r)!==`ENOTDIR`)throw r}return t.filter&&!await t.filter(e,n)?!1:(await Y(ta(e,t.tmp,Zi)),!0)}return!(await Promise.all(r.map(n=>ea(M(e,n.name),t,n)))).every(e=>e===!0)||t.preserveRoot===!1&&e===j(e).root||t.filter&&!await t.filter(e,n)?!1:(await Y(ta(e,t.tmp,Yi)),!0)},ta=async(e,t,n)=>{let r=M(t,Xi(e));return await qi(e,r),await n(r)},na=(e,t)=>(t?.signal?.throwIfAborted(),X(()=>ra(e,t,ge(e)))??!0),ra=(e,t,n)=>{if(t?.signal?.throwIfAborted(),!t.tmp)return ra(e,{...t,tmp:Gi(e)},n);let r=t.tmp;if(e===t.tmp&&j(e).root!==e)throw Error(`cannot delete temp directory used for deletion`);let i=n.isDirectory()?bi(e):null;if(!Array.isArray(i)){if(i){if(J(i)===`ENOENT`)return!0;if(J(i)!==`ENOTDIR`)throw i}return t.filter&&!t.filter(e,n)?!1:(X(()=>ia(e,r,Qi)),!0)}let a=!0;for(let n of i){let r=M(e,n.name);a=ra(r,t,n)&&a}return!a||t.preserveRoot===!1&&e===j(e).root||t.filter&&!t.filter(e,n)?!1:(X(()=>ia(e,r,Ce)),!0)},ia=(e,t,n)=>{let r=M(t,Xi(e));return xe(e,r),n(r)},{unlink:aa,rmdir:oa,lstat:sa}=_i,ca=Fi(Mi(aa)),la=Ii(Ni(Te)),ua=Fi(Mi(oa)),da=Ii(Ni(Ce)),fa=async(e,{filter:t,...n})=>{n?.signal?.throwIfAborted();try{return await ua(e,n),!0}catch(t){if(J(t)===`ENOTEMPTY`)return $i(e,n);throw t}},pa=(e,{filter:t,...n})=>{n?.signal?.throwIfAborted();try{return da(e,n),!0}catch(t){if(J(t)===`ENOTEMPTY`)return na(e,n);throw t}},ma=Symbol(`start`),ha=Symbol(`child`),ga=Symbol(`finish`),_a=async(e,t)=>(t?.signal?.throwIfAborted(),await Y(sa(e).then(n=>ya(e,t,n,ma)))??!0),va=(e,t)=>(t?.signal?.throwIfAborted(),X(()=>ba(e,t,ge(e),ma))??!0),ya=async(e,t,n,r=ma)=>{t?.signal?.throwIfAborted();let i=n.isDirectory()?await yi(e):null;if(!Array.isArray(i)){if(i){if(J(i)===`ENOENT`)return!0;if(J(i)!==`ENOTDIR`)throw i}return t.filter&&!await t.filter(e,n)?!1:(await Y(ca(e,t)),!0)}let a=r===ma?ha:r,o=(await Promise.all(i.map(n=>ya(M(e,n.name),t,n,a)))).every(e=>e===!0);if(r===ma)return ya(e,t,n,ga);if(r===ga){if(t.preserveRoot===!1&&e===j(e).root||!o||t.filter&&!await t.filter(e,n))return!1;await Y(fa(e,t))}return!0},ba=(e,t,n,r=ma)=>{let i=n.isDirectory()?bi(e):null;if(!Array.isArray(i)){if(i){if(J(i)===`ENOENT`)return!0;if(J(i)!==`ENOTDIR`)throw i}return t.filter&&!t.filter(e,n)?!1:(X(()=>la(e,t)),!0)}let a=!0;for(let n of i){let i=r===ma?ha:r,o=M(e,n.name);a=ba(o,t,n,i)&&a}if(r===ma)return ba(e,t,n,ga);if(r===ga){if(t.preserveRoot===!1&&e===j(e).root||!a||t.filter&&!t.filter(e,n))return!1;X(()=>pa(e,t))}return!0},xa=process.platform===`win32`?_a:Di,Sa=process.platform===`win32`?va:Oi,{rm:Ca}=_i,wa=async(e,t)=>(await Ca(e,{...t,force:!0,recursive:!0}),!0),Ta=(e,t)=>(Se(e,{...t,force:!0,recursive:!0}),!0),[Ea=0,Da=0]=process.version.replace(/^v/,``).split(`.`).map(e=>parseInt(e,10)),Oa=Ea>14||Ea===14&&Da>=14,ka=!Oa||process.platform===`win32`?()=>!1:e=>!e?.signal&&!e?.filter,Aa=!Oa||process.platform===`win32`?()=>!1:e=>!e?.signal&&!e?.filter,ja=e=>async(t,n)=>{let r=pi(n);return r.glob&&(t=await ci(t,r.glob)),Array.isArray(t)?!!(await Promise.all(t.map(t=>e(hi(t,r),r)))).reduce((e,t)=>e&&t,!0):!!await e(hi(t,r),r)},Ma=e=>(t,n)=>{let r=mi(n);return r.glob&&(t=$r(t,r.glob)),Array.isArray(t)?!!t.map(t=>e(hi(t,r),r)).reduce((e,t)=>e&&t,!0):!!e(hi(t,r),r)},Na=Ma(Ta),Pa=Object.assign(ja(wa),{sync:Na}),Fa=Ma(Sa),Ia=Object.assign(ja(xa),{sync:Fa}),La=Ma(va),Ra=Object.assign(ja(_a),{sync:La}),za=Ma(Oi),Ba=Object.assign(ja(Di),{sync:za}),Va=Ma(na),Ha=Object.assign(ja($i),{sync:Va}),Ua=Ma((e,t)=>Aa(t)?Ta(e,t):Sa(e,t)),Wa=ja((e,t)=>ka(t)?wa(e,t):xa(e,t)),Ga=Object.assign(Wa,{rimraf:Wa,sync:Ua,rimrafSync:Ua,manual:Ia,manualSync:Fa,native:Pa,nativeSync:Na,posix:Ba,posixSync:za,windows:Ra,windowsSync:La,moveRemove:Ha,moveRemoveSync:Va});Ga.rimraf=Ga;async function Ka(e,t,{baseDir:n=``,readdirImpl:r=le,cpImpl:i=E,joinImpl:a=x}={}){for(let o of e){let e=n?a(n,o):o;try{let n=await r(e,{withFileTypes:!0});for(let r of n){let n=a(e,r.name),o=a(t,r.name);r.isDirectory()?await i(n,o,{recursive:!0,force:!0}):r.isFile()&&await i(n,o,{force:!0})}}catch{}}}async function qa(e,t,n={},{statImpl:r=pe,cpImpl:i=E}={}){let a=Array.isArray(e)?e:[e];for(let e of a)try{return await r(e),await i(e,t,n),!0}catch{}return!1}async function Ja(e,{statImpl:t=pe}={}){for(let n of e)try{return await t(n),n}catch{}return null}function Ya({contentRoot:e=``,toolchainRoot:t=``,distPublicDir:n=`dist/public`}={}){let r=[{sources:[`pages/resources/README.md`,`pages/deps/README.md`,`resources/README.md`,`deps/README.md`,`pages/README.md`,`README.md`],dest:`dist/public/README.md`},{sources:[`pages/resources/docs`,`pages/deps/docs`,`resources/docs`,`deps/docs`,`pages/docs`,`docs`],dest:`dist/public/docs`,opts:{recursive:!0}},{sources:[`pages/resources/AGENTS.md`,`pages/deps/AGENTS.md`,`resources/AGENTS.md`,`deps/AGENTS.md`,`pages/AGENTS.md`,`AGENTS.md`],dest:`dist/public/AGENTS.md`},{sources:[`pages/resources/llms.txt`,`pages/deps/llms.txt`,`resources/llms.txt`,`deps/llms.txt`,`pages/llms.txt`,`llms.txt`],dest:`dist/public/llms.txt`},{sources:[`pages/resources/robots.txt`,`pages/deps/robots.txt`,`resources/robots.txt`,`deps/robots.txt`,`pages/robots.txt`,`robots.txt`],dest:`dist/public/robots.txt`},{sources:[`pages/resources/sitemap.xml`,`pages/deps/sitemap.xml`,`resources/sitemap.xml`,`deps/sitemap.xml`,`pages/sitemap.xml`,`pages/main/sitemap.xml`,`sitemap.xml`],dest:`dist/public/sitemap.xml`},{sources:[`pages/resources/sitemap.txt`,`pages/deps/sitemap.txt`,`resources/sitemap.txt`,`deps/sitemap.txt`,`pages/sitemap.txt`,`pages/main/sitemap.txt`,`sitemap.txt`],dest:`dist/public/sitemap.txt`},{sources:[`pages/resources/404.html`,`pages/deps/404.html`,`resources/404.html`,`deps/404.html`,`pages/404.html`,`pages/main/404.html`,`404.html`],dest:`dist/public/404.html`},{sources:[`pages/resources/manifest.json`,`pages/deps/manifest.json`,`resources/manifest.json`,`deps/manifest.json`,`pages/manifest.json`,`pages/main/manifest.json`,`manifest.json`],dest:`dist/public/manifest.json`},{sources:[`pages/resources/assets/icons/favicon.svg`,`pages/deps/assets/icons/favicon.svg`,`resources/assets/icons/favicon.svg`,`deps/assets/icons/favicon.svg`,`pages/resources/assets/favicon.svg`,`pages/resources/favicon.svg`,`pages/deps/favicon.svg`,`resources/favicon.svg`,`deps/favicon.svg`,`pages/favicon.svg`,`pages/main/favicon.svg`,`assets/icons/favicon.svg`],dest:`dist/public/favicon.svg`},{sources:[`pages/resources/assets/icons/favicon.ico`,`pages/deps/assets/icons/favicon.ico`,`resources/assets/icons/favicon.ico`,`deps/assets/icons/favicon.ico`,`pages/resources/assets/favicon.ico`,`pages/resources/favicon.ico`,`pages/deps/favicon.ico`,`resources/favicon.ico`,`deps/favicon.ico`,`pages/favicon.ico`,`pages/main/favicon.ico`,`assets/icons/favicon.ico`],dest:`dist/public/favicon.ico`}];return!e&&!t&&n===`dist/public`?r:r.map(r=>{let i=n?r.dest.replace(/^dist\/public/,n):r.dest,a=[];if(e)for(let t of r.sources)a.push(b.join(e,t));if(t&&t!==e)for(let e of r.sources)a.push(b.join(t,e));return!e&&!t&&a.push(...r.sources),{sources:a,dest:i,...r.opts?{opts:r.opts}:{}}})}function Xa(e){let t=[`pages/resources/routes.json`,`pages/deps/routes.json`,`resources/routes.json`,`deps/routes.json`,`pages/routes.json`,`routes.json`];return e?t.map(t=>b.join(e,t)):t}function Za(e){return e?[b.join(e,`shadow-claw-config.json`),b.join(e,`shadow-claw.config.json`),b.join(e,`shadowclaw.config.json`),b.join(e,`pages/shadow-claw-config.json`),b.join(e,`pages/shadow-claw.config.json`),b.join(e,`site-config.json`),b.join(e,`pages/site-config.json`)]:[`shadow-claw-config.json`,`shadow-claw.config.json`,`shadowclaw.config.json`,`site-config.json`]}function Qa(e={}){let t=e.PRERENDER_PAGES||`all`;return{isProduction:e.NODE_ENV===`production`,copyAllAssets:e.COPY_ALL_ASSETS===`true`,prerenderPages:t,prerenderMainMemory:e.PRERENDER_MAIN_MEMORY!==`false`&&t!==`none`&&t!==`0`}}function $a(e){return e.replace(/^\/+|\/+$/g,``)}function eo(e){let t=$a(e);if(t.startsWith(`pages/main/`))return t.slice(11);if(t.startsWith(`pages/br:main/`)||t.startsWith(`pages/br-main/`))return t.slice(14);if(t.startsWith(`main/`))return t.slice(5);if(t.startsWith(`pages/`)){let e=t.split(`/`);if(e.length>=3)return e.slice(2).join(`/`)}return t}function to(e,r){let i=`<script id="shadow-claw-static-routing" type="application/json">${t(r)}<\/script>`;return/id="shadow-claw-static-routing"/iu.test(e)?e.replace(/<script\s+id="shadow-claw-static-routing"[\s\S]*?<\/script>/iu,()=>i):n(e,` ${i}`)}async function no(e={}){let t=b.resolve(e.publicDir||`dist/public`),n=b.resolve(e.routesPath||`pages/routes.json`),c=b.resolve(e.sourcePath||`pages/main`),g=b.resolve(e.indexPath||b.join(t,`index.html`)),v={},ee=[e.siteConfigPath,b.resolve(b.dirname(c),`shadow-claw.config.json`),b.resolve(b.dirname(c),`site-config.json`),b.resolve(`shadow-claw.config.json`),b.resolve(`site-config.json`),b.join(t,`shadow-claw.config.json`),b.join(t,`site-config.json`)].filter(Boolean);for(let e of ee)try{let t=await O(e,`utf8`);v=JSON.parse(t);break}catch{}let te=_(e.prerenderPages===void 0?w.env.PRERENDER_PAGES??1:e.prerenderPages),x;try{x=await O(n,`utf8`)}catch(e){if(e?.code===`ENOENT`)return{count:0,skipped:!0,reason:`No routes.json found`};throw e}let S;try{S=JSON.parse(x)}catch(e){return console.warn(`Failed to parse ${n}:`,e),{count:0,skipped:!0,reason:`Invalid JSON in routes.json`}}if(!S||typeof S!=`object`)return{count:0,skipped:!0,reason:`Invalid routes.json`};S.routes||={};let C={...S.routes||{}},ne=new Set;async function re(e,t){if(!e.subRoutes)return;let n=Array.isArray(e.subRoutes)?e.subRoutes:Object.values(e.subRoutes);for(let e of n){let n=b.resolve(b.dirname(t),e);if(typeof e==`string`&&e.startsWith(`pages/`)&&(n=b.resolve(e)),!ne.has(n)){ne.add(n);try{let e=await O(n,`utf8`),t=JSON.parse(e);t.routes&&Object.assign(C,t.routes),await re(t,n)}catch(e){console.warn(`Failed to read subRoute: ${n}`,e?.message)}}}}await re(S,n),Object.assign(S.routes,C),Array.isArray(S.subRoutes)&&delete S.subRoutes;let ie=Object.entries(C);if(ie.length===0)return{count:0,skipped:!0,reason:`Empty routes table`};let ae=JSON.stringify(S,null,2),oe=b.join(t,`static-routing.json`);await D(t,{recursive:!0}),await k(oe,ae,`utf8`);let se=JSON.stringify(S),T=b.join(t,`components/shadow-claw/shadow-claw.html`),ce=b.join(t,`components/shadow-claw-pages/shadow-claw-pages.html`),ue=b.join(t,`components/shadow-claw-page-header/shadow-claw-page-header.html`),de=b.join(t,`components/shadow-claw/shadow-claw.css`),fe=b.join(t,`components/shadow-claw-pages/shadow-claw-pages.css`),me=b.join(t,`components/shadow-claw-page-header/shadow-claw-page-header.css`),[he,ge,_e,ve,ye,be,xe,Se]=await Promise.all([O(g,`utf8`),O(T,`utf8`),O(ce,`utf8`).catch(()=>``),O(ue,`utf8`).catch(()=>``),p(c),O(de,`utf8`).catch(()=>``),O(fe,`utf8`).catch(()=>``),O(me,`utf8`).catch(()=>``)]),Ce=(await Promise.all(ye.map(async e=>{let t=typeof e.inlineContent==`string`?e.inlineContent:await O(e.absolutePath,`utf8`);return{...e,content:t}}))).filter(e=>!(e.displayPath.endsWith(`.md`)&&/^---\r?\n[\s\S]*?slug:\s*"shadow-claw--purge-pages"[\s\S]*?---/mu.test(e.content||``)));await k(g,await s(l(to(he,se)),t),`utf8`);let we=d(ge),Te=d(_e),Ee=d(ve),De=Ce.map(e=>({displayPath:e.displayPath,content:e.content})),Oe=b.join(t,`static-main-manifest.json`),A={};try{A=JSON.parse(await O(Oe,`utf8`))}catch{}let j={pages:De,...Array.isArray(A.skills)?{skills:A.skills}:{},...Array.isArray(A.tools)?{tools:A.tools}:{},...A.skillsPurgeId?{skillsPurgeId:A.skillsPurgeId}:{},...A.preRenderedStaticPages?{preRenderedStaticPages:A.preRenderedStaticPages}:{},...A.purgeId?{purgeId:A.purgeId}:{}};await k(Oe,JSON.stringify(j,null,2),`utf8`);try{if((await pe(c)).isDirectory()){let e=b.join(t,`static-main`);await D(e,{recursive:!0}),await E(c,e,{recursive:!0});let n=b.join(t,`files/main`);await D(n,{recursive:!0}),await E(c,n,{recursive:!0})}}catch{}let M=[];for(let[e,n]of ie){if(!n||!n.prettyPath)continue;let d=eo(e),p=Ce.find(e=>e.displayPath===d);if(!p)try{let e=b.join(c,d);p={absolutePath:e,displayPath:d,content:await O(e,`utf8`)}}catch{console.warn(`Could not find page file for route: ${e} (${d})`);continue}let g=Ce.filter(e=>e.displayPath!==p.displayPath),_=[],ee=[];te===`all`?(_=[p,...g],ee=_.map(e=>({displayPath:e.displayPath,content:e.content}))):typeof te==`number`&&(te===0?(_=[],ee=[]):(_=[p,...g.slice(0,te-1)],ee=_.map(e=>({displayPath:e.displayPath,content:e.content}))));let x=y(p.content||``),S=x.data&&x.data.title?x.data.title:``,C=await r(p.content||``,p.displayPath),ne;ne=te===0?i(we,be,v.sidebar):u(we,h(Te,_,C,Ee,S,xe,Se),be,v.sidebar);let re=await s(l(to(a(f(o(he,ne)),JSON.stringify({pages:ee,...Array.isArray(A.skills)?{skills:A.skills}:{},...Array.isArray(A.tools)?{tools:A.tools}:{},...A.skillsPurgeId?{skillsPurgeId:A.skillsPurgeId}:{},...A.preRenderedStaticPages?{preRenderedStaticPages:A.preRenderedStaticPages}:{},...A.purgeId?{purgeId:A.purgeId}:{}})),se)),t),w=$a(n.prettyPath),ie;ie=w.endsWith(`.html`)?w:b.join(w,`index.html`);let ae=b.join(t,ie),oe=b.dirname(ae);if(await D(oe,{recursive:!0}),await k(ae,re,`utf8`),p&&p.absolutePath)try{let e=b.dirname(p.absolutePath),t=await le(e,{withFileTypes:!0});for(let n of t)n.isFile()&&!m(n.name)&&n.name!==`routes.json`&&await E(b.join(e,n.name),b.join(oe,n.name))}catch(t){console.warn(`Failed to copy co-located assets for ${e}:`,t)}M.push(ie.replace(/\\/g,`/`))}return(e.silent??w.env.NODE_ENV===`test`)||console.log(`Prerendered ${M.length} pretty path page${M.length===1?``:`s`} from ${n} (prerender-pages: ${te}).`),{count:M.length,generatedPaths:M,skipped:!1}}async function ro(){let e=w.argv.slice(2).filter(e=>!e.startsWith(`--`)),t=w.argv.slice(2).filter(e=>e.startsWith(`--`)),n;for(let e of t)e.startsWith(`--prerender-pages=`)?n=e.slice(18):e.startsWith(`--pages=`)&&(n=e.slice(8));let r=e[0]||`dist/public`;await no({publicDir:r,routesPath:e[1]||`pages/routes.json`,sourcePath:e[2]||`pages/main`,indexPath:e[3]||b.join(r,`index.html`),prerenderPages:n})}w.argv[1]&&b.resolve(w.argv[1])===b.resolve(re(import.meta.url))&&ro().catch(e=>{console.error(e),w.exit(1)});function io(e={},t={}){let n=e.customElements;return{rawScripts:(typeof n==`object`&&!Array.isArray(n)?n.scripts:n)||e.scripts||t.scripts||[],allowedDomains:(typeof n==`object`&&!Array.isArray(n)?n.allowedDomains:void 0)||e.allowedCustomElementDomains||[]}}function ao(e,t){if(!e.startsWith(`http://`)&&!e.startsWith(`https://`)&&!e.startsWith(`//`)||!t||Array.isArray(t)&&t.length===0)return!0;try{let n=new URL(e,`https://localhost`).hostname.toLowerCase();return(Array.isArray(t)?t:String(t).split(/[\n,]+/)).some(e=>{let t=e.trim().toLowerCase();return n===t||n.endsWith(`.`+t)||t===`*`})}catch{return!1}}function oo(e,t){let n=JSON.parse(JSON.stringify(e));return n.customElements&&typeof n.customElements==`object`&&Array.isArray(n.customElements.scripts)&&(n.customElements.scripts=n.customElements.scripts.filter(e=>{let n=typeof e==`string`?e:e?.src;return n?ao(n,t):!1})),n}function Z(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}const so=[`pages/resources/`,`pages/deps/`,`resources/`,`deps/`,`pages/assets/`,`pages/main/assets/`];function co(e){for(let t of so)if(e.startsWith(t))return e.slice(t.length);return e}async function lo(e){try{return JSON.parse(await O(e,`utf8`))}catch{return null}}async function uo(e){try{return await O(e,`utf8`)}catch{return null}}async function fo(e,t){await k(e,t,`utf8`)}function po(e){return!Array.isArray(e)||e.length===0?``:`<nav slot="sidebar" class="sidebar-custom-sections" aria-label="Site Navigation">\n${e.map((e,t)=>{if(e.html)return e.html;let n=e.title?`sidebar-${e.title.toLowerCase().replace(/[^a-z0-9]+/g,`-`)}`:`sidebar-section-${t+1}`,r=e.headerHref?`<a href="${Z(e.headerHref)}" class="sidebar-link">${Z(e.title||``)}</a>`:`<span>${Z(e.title||``)}</span>`,i=e.title?` <div class="sidebar-section-header">${r}</div>`:``,a=(e.items||[]).map(e=>{let t=e.title||e.label||``,n=e.href||`#`,r=e.target?` target="${Z(e.target)}"`:``,i=e.rel?` rel="${Z(e.rel)}"`:e.target===`_blank`?` rel="noopener noreferrer"`:``,a=e.active?` active`:``,o=e.active?` aria-current="page"`:``;return` <div class="sidebar-item"><a href="${Z(n)}"${r}${i} class="sidebar-link${a}"${o}>${Z(t)}</a></div>`}).join(`
|
|
4
|
+
`);return[` <section class="sidebar-section" id="${n}">`,i,a,` </section>`].filter(Boolean).join(`
|
|
5
|
+
`)}).join(`
|
|
6
|
+
`)}\n</nav>`}function mo(e,t,r){let i=e,a=t.site||{};a.title&&(i=i.replace(/<title>[^<]*<\/title>/iu,`<title>${Z(a.title)}</title>`)),a.description&&(i=i.replace(/<meta\s+name="description"\s+content="[^"]*"\s*\/?>/iu,`<meta name="description" content="${Z(a.description)}" />`)),a.themeColor&&(i=i.replace(/<meta\s+name="theme-color"\s+content="[^"]*"\s*\/?>/iu,`<meta name="theme-color" content="${Z(a.themeColor)}" />`)),a.lang&&(i=i.replace(/<html\s+lang="[^"]*"/iu,`<html lang="${a.lang}"`));let o=t.branding||{};if(o.faviconPath){let e=o.faviconPath.replace(/^pages\/main\//,``),t=e.endsWith(`.svg`)?`image/svg+xml`:e.endsWith(`.png`)?`image/png`:`image/x-icon`,r=`<link href="${Z(e)}" rel="icon" type="${t}" />`,a=!1;i=i.replace(/<link\b[^>]*\brel=["']?(?:shortcut\s+)?icon["']?[^>]*\/?>/giu,()=>a?``:(a=!0,r)),a||(i=n(i,` ${r}`))}if(o.appleTouchIconPath){let e=`<link href="${Z(o.appleTouchIconPath.replace(/^pages\/main\//,``))}" rel="apple-touch-icon" />`,t=!1;i=i.replace(/<link\b[^>]*\brel=["']?apple-touch-icon["']?[^>]*\/?>/giu,()=>t?``:(t=!0,e)),t||(i=n(i,` ${e}`))}if(o.titleText||o.siteUrl||o.logoSlotHtml){let e=o.titleText||`ShadowClaw`,t=o.siteUrl||``,n=o.logoSlotHtml||``;i=i.replace(/<a\b[^>]*\bslot="header-title-link"[^>]*>[\s\S]*?<\/a>/iu,[`<a`,` aria-label="${Z(e)}"`,` class="header-title-link"`,t?` href="${Z(t)}"`:``,` slot="header-title-link"`,` >`,n?` ${n}`:``,` <span class="header-title">${Z(e)}</span>`,` </a>`].filter(Boolean).join(`
|
|
7
|
+
`))}if(o.repoUrl){let e=o.repoLabel||`Project on GitHub`;i=i.replace(/<a\b[^>]*\bslot="header-actions-logo"[^>]*>[\s\S]*?<\/a>/iu,[`<a`,` aria-label="${Z(e)}"`,` class="header-actions-logo-link"`,` href="${Z(o.repoUrl)}"`,` slot="header-actions-logo"`,` >`,` <svg aria-hidden="true" focusable="false" viewBox="0 0 496 512" xmlns="http://www.w3.org/2000/svg">`,` <path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8z" fill="var(--shadow-claw-bg-primary-reverse, currentColor)"></path>`,` </svg>`,` </a>`].join(`
|
|
8
|
+
`))}o.siteUrl&&!o.siteUrl.includes(`xt-ml.github.io`)&&(i=i.replace(/\s*<meta\s+http-equiv="origin-trial"\s+content="[^"]*"\s*\/?>\s*/iu,`
|
|
9
|
+
`));let s=t.theme||{};if(s.stylesheet){let e=co(s.stylesheet),t=`<link rel="stylesheet" href="${Z(e)}" />`,r=Z(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),o=RegExp(`<link\\s+[^>]*href=["'](?:${a}|${r})["'][^>]*>`,`iu`),c=v(i),l=(c===-1?i:i.slice(0,c)).replace(/<script\b[\s\S]*?<\/script>/gi,``);o.test(l)||(i=/<link\s+rel="stylesheet"\s+href="index\.css"\s*\/?>/iu.test(i)?i.replace(/(<link\s+rel="stylesheet"\s+href="index\.css"\s*\/?>)/iu,`$1\n ${t}`):n(i,` ${t}`))}let{allowedDomains:c}=io(t,s),l=oo(t,c),u=`<script id="shadow-claw-site-config" type="application/json">${JSON.stringify(l).replace(/</g,`\\u003c`).replace(/>/g,`\\u003e`).replace(/\//g,`\\u002f`)}<\/script>`;i=i.includes(`<script id="shadow-claw-site-config"`)?i.replace(/<script\s+id="shadow-claw-site-config"[\s\S]*?<\/script>/iu,()=>u):i.includes(`<script src="theme-init.js">`)?i.replace(`<script src="theme-init.js">`,`${u}\n <script src="theme-init.js">`):/<script\b[^>]*>\s*var\s+ShadowClawThemeInit\b/iu.test(i)?i.replace(/(<script\b[^>]*>\s*var\s+ShadowClawThemeInit\b)/iu,`${u}\n $1`):n(i,` ${u}`);let d=r||t.sidebar?.slotHtml||(t.sidebar?.sections?po(t.sidebar.sections):``);if(d){let e=d.trim();/\bslot="sidebar(?:-nav|-content|-footer)?"/iu.test(e)||(e=`<div slot="sidebar" class="sidebar-custom-sections">\n${e}\n</div>`);let t=i.match(/<[^>]+?\bslot="sidebar(?:-nav|-content|-footer)?"[^>]*>[\s\S]*?<\/[^>]+>/iu);t&&(i=i.replace(t[0],``)),i.includes(`</shadow-claw>`)?i=i.replace(`</shadow-claw>`,` ${e}\n</shadow-claw>`):i.includes(`<shadow-claw></shadow-claw>`)&&(i=i.replace(`<shadow-claw></shadow-claw>`,`<shadow-claw>\n ${e}\n</shadow-claw>`))}return t.sidebar&&(i=g(i,t.sidebar)),i}function ho(e){let t=(e.src||``).replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``),n=e.type||(t.endsWith(`.svg`)?`image/svg+xml`:t.endsWith(`.png`)?`image/png`:`image/x-icon`),r=(e.purpose||`any`).trim();return n===`image/svg+xml`||t.endsWith(`.svg`)?[{...e,src:t,type:n,purpose:`any`}]:r.includes(`any`)&&r.includes(`maskable`)?[{...e,src:t,type:n,purpose:`any`},{...e,src:t,type:n,purpose:`maskable`}]:[{...e,src:t,type:n,purpose:r}]}function go(e,t){let n=typeof e==`string`?JSON.parse(e):e,r=t.pwa||{},i=t.site||{},a=w.env.PAGES_ORIGIN;if((r.name||i.title)&&(n.name=r.name||i.title),(r.shortName||i.title)&&(n.short_name=r.shortName||i.title),i.description&&(n.description=i.description),r.backgroundColor&&(n.background_color=r.backgroundColor),(r.themeColor||i.themeColor)&&(n.theme_color=r.themeColor||i.themeColor),r.startUrl?n.start_url=r.startUrl:a?n.start_url=a:n.start_url||=`./`,r.icons&&Array.isArray(r.icons)){let e=r.icons.flatMap(ho),t=Array.isArray(n.icons)?n.icons.flatMap(ho):[],i=new Set(e.map(e=>e.src));n.icons=[...e,...t.filter(e=>!i.has(e.src))]}else Array.isArray(n.icons)&&(n.icons=n.icons.flatMap(ho));return r.screenshots&&Array.isArray(r.screenshots)&&(n.screenshots=r.screenshots.map(e=>{let t=(e.src||``).replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``);return{...e,src:t}})),JSON.stringify(n,null,2)}function _o(e,t){if(!t)return e;if(/<loc>/i.test(e))return e.replace(/<loc>[^<]*<\/loc>/giu,`<loc>${Z(t)}</loc>`);let n=t.endsWith(`/`)?t:t+`/`;return e.split(`
|
|
10
|
+
`).map(e=>{let t=e.trim();if(!t)return e;if(t.startsWith(`http://`)||t.startsWith(`https://`))try{let e=new URL(t),r=new URL(n);return e.protocol=r.protocol,e.host=r.host,e.pathname=(r.pathname.endsWith(`/`)?r.pathname.slice(0,-1):r.pathname)+e.pathname,e.toString()}catch{return n}else if(t.startsWith(`/`))try{return new URL(t,n).toString()}catch{return e}return e}).join(`
|
|
11
|
+
`)}function vo(e,t,n){let r=e,i=t.site||{};if(i.title&&(r=r.replace(/<title>[^<]*<\/title>/iu,`<title>${Z(i.title)} - Not Found</title>`)),n){let e=n.endsWith(`/`)?n:n+`/`;r=r.replace(/l\.replace\(["']\/shadow-claw\/["']\)/gu,`l.replace("${Z(e)}")`)}return r}function yo(e){let t=b.resolve(e),n=t.split(b.sep),r=n[n.length-1],i=n[n.length-2];return(r===`resources`||r===`deps`)&&i===`pages`?b.resolve(t,`../..`):r===`resources`||r===`deps`||r===`pages`?b.resolve(t,`..`):t}function bo(e){let t=b.resolve(e),n=b.basename(t);return n===`resources`||n===`deps`||n===`pages`?b.resolve(t,`..`):t}function Q(e,t,n){if(!e||typeof e!=`string`)return[];if(b.isAbsolute(e))return[e];let r=e.replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``),i=yo(t);return[b.resolve(t,`resources`,r),b.resolve(t,`deps`,r),b.resolve(t,`main`,r),b.resolve(i,`pages`,`resources`,r),b.resolve(i,`pages`,`resources`,e),b.resolve(i,`pages`,`deps`,r),b.resolve(i,`pages`,`deps`,e),b.resolve(i,`resources`,r),b.resolve(i,`resources`,e),b.resolve(i,`deps`,r),b.resolve(i,`deps`,e),b.resolve(n,`pages`,`resources`,r),b.resolve(n,`pages`,`deps`,r),b.resolve(n,`resources`,r),b.resolve(n,`deps`,r),b.resolve(n,`pages`,e),b.resolve(n,`pages`,r),b.resolve(n,`pages`,`main`,r),b.resolve(i,`pages`,e),b.resolve(i,`pages`,r),b.resolve(i,`pages`,`main`,r),b.resolve(i,`pages`,`main`,e),b.resolve(t,e),b.resolve(t,r),b.resolve(n,e),b.resolve(n,r),b.resolve(i,e),b.resolve(i,r)]}async function xo(e){for(let t of e)if(t)try{return await pe(t),t}catch{}return null}async function So(e,t,n){let r=n?b.dirname(b.resolve(n)):w.cwd(),i=bo(r),a=yo(r),o=[b.resolve(r,`resources`),b.resolve(r,`deps`),b.resolve(i,`resources`),b.resolve(i,`deps`),b.resolve(i,`pages`,`resources`),b.resolve(i,`pages`,`deps`),b.resolve(a,`resources`),b.resolve(a,`deps`),b.resolve(a,`pages`,`resources`),b.resolve(a,`pages`,`deps`)];for(let e of o)try{let n=await le(e,{withFileTypes:!0});for(let r of n){let n=b.join(e,r.name),i=b.join(t,r.name);r.isDirectory()?await E(n,i,{recursive:!0,force:!0}):r.isFile()&&(await D(b.dirname(i),{recursive:!0}),await T(n,i))}}catch{}let s=await xo([...e.pages?.notFoundPath?Q(e.pages.notFoundPath,r,i):[],...e.branding?.notFoundPath?Q(e.branding.notFoundPath,r,i):[],...e.notFoundPath?Q(e.notFoundPath,r,i):[],...Q(`404.html`,r,i)]);if(s)try{await T(s,b.join(t,`404.html`)),console.log(` Copied custom 404.html: ${s}`)}catch(e){console.warn(` Warning: Could not copy custom 404.html: ${e.message}`)}let c=await xo([...e.pwa?.manifestPath?Q(e.pwa.manifestPath,r,i):[],...e.manifestPath?Q(e.manifestPath,r,i):[],...Q(`manifest.json`,r,i)]);if(c)try{await T(c,b.join(t,`manifest.json`)),console.log(` Copied custom manifest.json: ${c}`)}catch(e){console.warn(` Warning: Could not copy custom manifest.json: ${e.message}`)}let l=!1;if(e.sitemapPath){let n=await xo(Q(e.sitemapPath,r,i));if(n)try{let e=b.basename(n);await T(n,b.join(t,e)),console.log(` Copied custom sitemap: ${n} → ${e}`),l=!0}catch(e){console.warn(` Warning: Could not copy custom sitemap: ${e.message}`)}}if(!l){let e=await xo(Q(`sitemap.xml`,r,i));if(e)try{await T(e,b.join(t,`sitemap.xml`)),console.log(` Copied custom sitemap.xml: ${e}`)}catch(e){console.warn(` Warning: Could not copy custom sitemap.xml: ${e.message}`)}let n=await xo(Q(`sitemap.txt`,r,i));if(n)try{await T(n,b.join(t,`sitemap.txt`)),console.log(` Copied custom sitemap.txt: ${n}`)}catch(e){console.warn(` Warning: Could not copy custom sitemap.txt: ${e.message}`)}}let u=e.overwriteAssets===!0||e.branding?.overwriteAssets===!0,d=Array.isArray(e.assets)?e.assets:[e.assetsDir,e.assets].filter(Boolean),f=Array.from(new Set([...d.flatMap(e=>Q(e,r,i)),...Q(`assets`,r,i)].filter(e=>e&&typeof e==`string`))),p=b.join(t,`assets`);if(u)try{await fe(p,{recursive:!0,force:!0}),await D(p,{recursive:!0}),console.log(` Cleared dist public assets for complete template asset overwrite.`)}catch{}let m=new Set,h=[...f].reverse();for(let e of h)if(!m.has(e))try{let t=await pe(e);if(m.add(e),t.isDirectory())await E(e,p,{recursive:!0,force:!0}),console.log(` Copied custom assets: ${e} → ${p}`);else if(t.isFile()){let t=b.basename(e);await D(p,{recursive:!0}),await T(e,b.join(p,t)),console.log(` Copied custom asset file: ${e} → ${p}`)}}catch{}}async function Co(e,t,n){let r=e.theme||{};if(!r.stylesheet)return;let i=n?b.dirname(b.resolve(n)):w.cwd(),a=bo(i),o=await xo(Q(r.stylesheet,i,a));if(!o)return;let s=r.stylesheet.replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``),c=b.join(t,s);try{await D(b.dirname(c),{recursive:!0}),await T(o,c),console.log(` Copied theme stylesheet: ${o} → ${c}`)}catch(e){console.warn(` Warning: Could not copy theme stylesheet ${o}: ${e.message}`)}}async function wo(e,t,n){let r=(e.customElements&&typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.scripts:void 0)||e.scripts||[];if(!Array.isArray(r)||r.length===0)return;let i=n?b.dirname(b.resolve(n)):w.cwd(),a=bo(i);for(let e of r){let n=typeof e==`string`?e:e?.src;if(!n||n.startsWith(`http://`)||n.startsWith(`https://`)||n.startsWith(`//`))continue;let r=await xo(Q(n,i,a));if(r){let e=n.replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``),i=b.join(t,e);try{await D(b.dirname(i),{recursive:!0}),await T(r,i),console.log(` Copied custom script: ${r} → ${i}`)}catch(e){console.warn(` Warning: Could not copy custom script ${r}: ${e.message}`)}}}}async function To(e,t,n){let r=e.branding||{},i=e.pwa||{},a=n?b.dirname(b.resolve(n)):w.cwd(),o=bo(a),s=[],c=await xo(Q(i.manifestPath||e.manifestPath||`manifest.json`,a,o));if(c){let e=await lo(c);e&&Array.isArray(e.icons)&&(s=e.icons.map(e=>e?.src).filter(Boolean))}let l=[r.faviconPath,r.appleTouchIconPath,`assets/icons/favicon.svg`,`assets/icons/favicon.ico`,`favicon.svg`,`favicon.ico`,`pages/resources/assets/icons/favicon.svg`,`pages/resources/assets/icons/favicon.ico`,`pages/resources/favicon.svg`,`pages/deps/favicon.svg`,`pages/main/favicon.svg`,...Array.isArray(i.icons)?i.icons.map(e=>e.src):[],...s].filter(e=>!!e&&typeof e==`string`&&!e.startsWith(`http://`)&&!e.startsWith(`https://`)&&!e.startsWith(`//`));if(l.length===0)return;let u=new Set,d=new Set;for(let e of l){if(u.has(e))continue;u.add(e);let n=await xo(Q(e,a,o));if(n){let r=e.replace(/^(pages\/)?(resources\/|deps\/|main\/)?/,``),i=b.join(t,r);if(d.has(i))continue;d.add(i);try{await D(b.dirname(i),{recursive:!0}),await T(n,i),console.log(` Copied branding asset: ${n} → ${i}`)}catch(e){console.warn(` Warning: Could not copy branding asset ${n}: ${e.message}`)}}}}async function Eo(e,t){let n=await lo(t);if(!n)return console.log(`No site-config.json found — skipping site configuration.`),{applied:!1};console.log(`Applying site-config.json...`);let r=w.env.PAGES_ORIGIN||``,i=w.env.PAGES_BASE_PATH||``;await So(n,e,t);let a=t?b.dirname(b.resolve(t)):w.cwd(),o=bo(a),s;if(n.sidebar?.slotHtml)s=n.sidebar.slotHtml;else if(n.sidebar?.sections)s=po(n.sidebar.sections);else{let e=await xo([n.sidebar?.slotPath,`pages/main/sidebar.html`,`pages/sidebar.html`,`sidebar.html`,`resources/sidebar.html`].filter(Boolean).flatMap(e=>Q(e,a,o)));e&&(s=await uo(e)??void 0,console.log(` Found slotted sidebar: ${e}`))}let c=b.join(e,`index.html`),l=await uo(c);l&&(await fo(c,mo(l,n,s)),console.log(` Patched index.html`));let u=b.join(e,`manifest.json`),d=await uo(u);d&&(await fo(u,go(d,n)),console.log(` Patched manifest.json`));let f=b.join(e,`sitemap.xml`),p=await uo(f);p&&(await fo(f,_o(p,r)),console.log(` Patched sitemap.xml`));let m=b.join(e,`sitemap.txt`),h=await uo(m);h&&(await fo(m,_o(h,r)),console.log(` Patched sitemap.txt`));let g=b.join(e,`404.html`),_=await uo(g);return _&&(await fo(g,vo(_,n,i)),console.log(` Patched 404.html`)),await Co(n,e,t),await wo(n,e,t),await To(n,e,t),console.log(`Site configuration applied successfully.`),{applied:!0}}async function Do(){let[e,t]=w.argv.slice(2);(!e||!t)&&(console.error(`Usage: node bin/site-config/apply.mjs <distPublicDir> <siteConfigPath>`),w.exit(1)),await Eo(e,t)}w.argv[1]&&b.resolve(w.argv[1])===b.resolve(re(import.meta.url))&&Do().catch(e=>{console.error(`site-config/apply.ts failed:`,e),w.exit(1)});async function Oo(t,{writeFileImpl:n=k}={}){await n(x(t||x(e(import.meta.url),`dist`,`public`),`.nojekyll`),``,`utf-8`)}w.argv[1]&&b.resolve(w.argv[1])===b.resolve(re(import.meta.url))&&await Oo();const ko=e(import.meta.url);async function $(e){try{return await pe(e),!0}catch{return!1}}async function Ao(e={}){let t=e.quiet??(process.env.NODE_ENV===`test`&&!process.env.VERBOSE),n=e.stdio??(process.env.NODE_ENV===`test`&&!process.env.VERBOSE?`pipe`:`inherit`),r=(...e)=>{t||console.log(...e)};async function i(e,r={}){!t&&!r.quiet&&console.log(`> ${e}`),se(e,{stdio:r.stdio??n,...r})}let a=C(e.contentRoot||ae.SHADOWCLAW_CONTENT_ROOT||process.cwd()),o=C(e.toolchainRoot||ko),s=a===o,{isProduction:l,copyAllAssets:u,prerenderPages:d,prerenderMainMemory:f}=Qa({...ae,...e.isProduction===void 0?{}:{NODE_ENV:e.isProduction?`production`:`development`},...e.copyAllAssets===void 0?{}:{COPY_ALL_ASSETS:String(e.copyAllAssets)},...e.prerenderPages===void 0?{}:{PRERENDER_PAGES:String(e.prerenderPages)},...e.prerenderMainMemory===void 0?{}:{PRERENDER_MAIN_MEMORY:String(e.prerenderMainMemory)}});if(s){if(ie(ko),await Ga(`dist/public`),await D(`dist/public/assets`,{recursive:!0}),u)await E(`assets`,`dist/public`,{recursive:!0});else{await E(`assets/icons`,`dist/public/assets/icons`,{recursive:!0}),await E(`assets/screenshots`,`dist/public/assets/screenshots`,{recursive:!0});try{await E(`assets/fonts`,`dist/public/assets/fonts`,{recursive:!0})}catch{}}await Ka([`pages/resources`,`pages/deps`,`resources`,`deps`,`pages/assets`,`pages/main/assets`],`dist/public`);for(let e of Ya())await qa(e.sources,e.dest,e.opts||{});try{await E(`e2e/README.md`,`dist/public/e2e/README.md`)}catch{}try{await E(`pages`,`dist/public/pages`,{recursive:!0})}catch{}try{await E(`pages/main`,`dist/public/files/main`,{recursive:!0})}catch{}try{await E(`pages/main`,`dist/public/static-main`,{recursive:!0})}catch{}try{await E(`.agents/skills`,`dist/public/.agents/skills`,{recursive:!0})}catch{}try{await E(`.agents/tools`,`dist/public/.agents/tools`,{recursive:!0})}catch{}try{await E(`.agents/scripts`,`dist/public/.agents/scripts`,{recursive:!0})}catch{}if(await $(`.agents/skills`))try{let{generateSkillsIndex:e}=await import(`./chunk-BT2f5jvi.js`);await e(ko)}catch(e){console.warn(`Notice: Failed to auto-generate agent-skills index:`,e)}if(await $(`.well-known`))try{await E(`.well-known`,`dist/public/.well-known`,{recursive:!0,force:!0})}catch{}await i(`npm run -s rolldown`);let t=await Ja(Za())||`pages/site-config.json`;f?await c({indexPath:`dist/public/index.html`,sourcePath:`pages/main`,prerenderPages:d,siteConfigPath:t}):await c({indexPath:`dist/public/index.html`,noSeed:!0,siteConfigPath:t});try{await Eo(`dist/public`,t)}catch{}try{let e=JSON.parse(await O(`package.json`,`utf8`));if(e.version){let t=`dist/public/index.html`;await k(t,(await O(t,`utf8`)).replace(/<meta\s+name="version"[^>]*>/,`<meta name="version" content="${e.version}" />`),`utf8`);for(let t of[`.well-known/mcp.json`,`.well-known/mcp/server-card.json`]){let n=x(`dist/public`,t);if(await $(n))try{let t=JSON.parse(await O(n,`utf8`));t.version!==e.version&&(t.version=e.version,await k(n,JSON.stringify(t,null,2)+`
|
|
12
|
+
`,`utf8`))}catch{}}}}catch{}if(l){r(`Running production post-build steps...`);let t=e.pagesOrigin||ae.PAGES_ORIGIN,n=e.basePath||(ae.PAGES_BASE_PATH??`/shadow-claw/`);if(r(` PAGES_ORIGIN : ${t||`(relative ./)`}`),r(` PAGES_BASE_PATH: ${n}`),t)try{let e=`dist/public/manifest.json`,n=await O(e,`utf8`),r=JSON.parse(n);r.start_url&&(r.start_url=t,await k(e,JSON.stringify(r,null,2),`utf8`))}catch{}try{let e=`dist/public/index.html`,t=await O(e,`utf8`);t=t.replace(/<base\s+href="[^"]*"\s*\/?>/i,`<base href="${n}" />`),await k(e,t,`utf8`)}catch{}await Oo(`dist/public`);let a=``;try{a=se(`npm run -s build:pkg:get:meta`,{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{}a&&await i(`npm run -s build:pkg:meta "${a}"`)}await no({publicDir:`dist/public`,routesPath:await Ja(Xa())||`pages/routes.json`,sourcePath:`pages/main`,prerenderPages:d,siteConfigPath:t}),await i(`npm run -s build:service-worker`);let n=`dist/public/service-worker.js`;await $(n)&&await ee(n,{logImpl:()=>{}}),r(`Build completed successfully.`);return}let p=C(a,e.outDir||`dist/public`);await D(p,{recursive:!0}),await D(x(p,`assets`),{recursive:!0});let m=x(o,`dist/public`);await $(x(m,`index.js`))||(r(`Building ShadowClaw core toolchain...`),await Ga(x(o,`dist/public`)),await Ga(x(o,`dist-electron`)),await i(`npm run -s rolldown`,{cwd:o})),await E(m,p,{recursive:!0,filter:e=>!(e.includes(`/assets/cache/`)||e.includes(`\\assets\\cache\\`)||e.includes(`/.cache/`)||e.includes(`\\.cache\\`))});let h=x(a,`assets`);await $(h)&&(u?await E(h,p,{recursive:!0,force:!0}):(await $(x(h,`icons`))&&await E(x(h,`icons`),x(p,`assets/icons`),{recursive:!0,force:!0}),await $(x(h,`screenshots`))&&await E(x(h,`screenshots`),x(p,`assets/screenshots`),{recursive:!0,force:!0}),await $(x(h,`fonts`))&&await E(x(h,`fonts`),x(p,`assets/fonts`),{recursive:!0,force:!0}))),await Ka([`pages/resources`,`pages/deps`,`resources`,`deps`,`pages/assets`,`pages/main/assets`],p,{baseDir:a});let g=Ya({contentRoot:a,toolchainRoot:o,distPublicDir:p});for(let e of g)await qa(e.sources,e.dest,e.opts||{});let _=x(a,`pages`);await $(_)&&await E(_,x(p,`pages`),{recursive:!0,force:!0});let v=x(a,`pages/main`);await $(v)&&(await E(v,x(p,`files/main`),{recursive:!0,force:!0}),await E(v,x(p,`static-main`),{recursive:!0,force:!0}));let y=x(a,`.agents/skills`);await $(y)&&await E(y,x(p,`.agents/skills`),{recursive:!0,force:!0});let te=x(o,`.agents/skills`);a!==o&&await $(te)&&await E(te,x(p,`.agents/skills`),{recursive:!0,force:!1,errorOnExist:!1});let b=x(a,`.agents/tools`);if(await $(b))await E(b,x(p,`.agents/tools`),{recursive:!0,force:!0});else{let e=x(o,`.agents/tools`);await $(e)&&await E(e,x(p,`.agents/tools`),{recursive:!0,force:!0})}let S=x(a,`.agents/scripts`);if(await $(S))await E(S,x(p,`.agents/scripts`),{recursive:!0,force:!0});else{let e=x(o,`.agents/scripts`);await $(e)&&await E(e,x(p,`.agents/scripts`),{recursive:!0,force:!0})}let ne=x(o,`.well-known`);await $(ne)&&await E(ne,x(p,`.well-known`),{recursive:!0,force:!0});let re=x(a,`.well-known`);if(a!==o&&await $(re)&&await E(re,x(p,`.well-known`),{recursive:!0,force:!0}),await $(x(p,`.agents/skills`)))try{let{generateSkillsIndex:e}=await import(`./chunk-BT2f5jvi.js`);if(await e(p,{metadataRoot:a,outDir:`.well-known/agent-skills`,toolchainRoot:o,includeBundled:!0}),await $(y))try{await e(a,{toolchainRoot:o,includeBundled:!0})}catch{}}catch(e){console.warn(`Notice: Failed to auto-generate agent-skills index:`,e)}let w=await Ja(Za(a))||x(a,`pages/site-config.json`),oe=x(p,`index.html`);f&&await $(v)?await c({indexPath:oe,sourcePath:v,prerenderPages:d,siteConfigPath:w}):await c({indexPath:oe,noSeed:!0,siteConfigPath:w});try{await Eo(p,w)}catch{}let T=l?e.basePath||ae.PAGES_BASE_PATH||`/`:e.basePath||`/`;try{let e=await O(oe,`utf8`);e=e.replace(/<base\s+href="[^"]*"\s*\/?>/i,`<base href="${T}" />`);let t=``;try{let e=await Ja([x(a,`package.json`),x(o,`package.json`)]);e&&(t=JSON.parse(await O(e,`utf8`)).version||``)}catch{}if(t){e=e.replace(/<meta\s+name="version"[^>]*>/,`<meta name="version" content="${t}" />`);for(let e of[`.well-known/mcp.json`,`.well-known/mcp/server-card.json`]){let n=x(p,e);if(await $(n))try{let e=JSON.parse(await O(n,`utf8`));e.version!==t&&(e.version=t,await k(n,JSON.stringify(e,null,2)+`
|
|
13
|
+
`,`utf8`))}catch{}}}await k(oe,e,`utf8`)}catch{}if(l){r(`Running production post-build steps...`);let t=e.pagesOrigin||ae.PAGES_ORIGIN;if(r(` PAGES_ORIGIN : ${t||`(relative ./)`}`),r(` PAGES_BASE_PATH: ${T}`),t)try{let e=x(p,`manifest.json`),n=await O(e,`utf8`),r=JSON.parse(n);r.start_url&&(r.start_url=t,await k(e,JSON.stringify(r,null,2),`utf8`))}catch{}await k(x(p,`.nojekyll`),``,`utf8`);let n=``;try{n=se(`git rev-parse HEAD`,{cwd:a,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{try{n=se(`git rev-parse HEAD`,{cwd:o,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{}}n&&await k(oe,(await O(oe,`utf8`)).replace(/<meta\s+name="revision"[^>]*>/,`<meta name="revision" content="${n}" />`),`utf8`)}await no({publicDir:p,routesPath:await Ja(Xa(a))||x(a,`pages/routes.json`),sourcePath:await $(v)?v:x(o,`pages/main`),prerenderPages:d,siteConfigPath:w});let ce=x(p,`service-worker.js`);await $(ce)&&await ee(ce,{logImpl:()=>{}}),r(`Build completed successfully.`)}process.argv[1]&&C(process.argv[1])===C(re(import.meta.url))&&Ao().catch(e=>{console.error(e),oe(1)});export{Ao as t};
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-uAI_Zi6n.js";import{d as t,f as n,n as r}from"./chunk-DUlIqkaX.js";import{t as i}from"./chunk-bQQkVCw-.js";import{c as a,i as o,o as s,s as c}from"./chunk-DHi40kQk.js";import{t as l}from"./chunk-DFh_pp_7.js";import{t as u}from"./chunk-BQCWtrzh.js";import{n as d}from"./chunk-CK6ejMig.js";import{t as f}from"./chunk-BLMC1Bxv.js";import{r as p}from"./chunk-C-5VcG3a.js";import m from"node:fs";import h from"node:path";import{fileURLToPath as g}from"node:url";import _ from"node:process";import{exec as v}from"node:child_process";import{mkdir as y,mkdtemp as b,readFile as x,stat as S,writeFile as C}from"node:fs/promises";import{Command as w}from"commander";import T from"process";import E from"node:http";import{tmpdir as D}from"node:os";import ee from"node:readline";async function O(e={}){let t=new l(e);try{let e=await t.listClients();if(!e||e.length===0){console.log(`No clients currently registered or connected.`);return}console.log(`Connected / registered clients (${e.length}):\n`),e.forEach((e,t)=>{let n=Math.max(0,Math.floor((Date.now()-e.lastSeen)/1e3)),r=n<60?`${n}s ago`:`${Math.floor(n/60)}m ago`;console.log(` ${t+1}. ${e.deviceLabel} (id: ${e.clientId})`),e.peerId&&console.log(` Peer ID: ${e.peerId}`),console.log(` Capabilities: ${e.capabilities.join(`, `)||`none`}`),console.log(` Version: ${e.version}`),console.log(` Last seen: ${r}\n`)})}catch(e){console.error(`Error fetching clients: ${e.message}`),T.exitCode=1}}async function te(e,t={}){if(!e||typeof e!=`string`||!e.trim()){console.error(`Error: Message cannot be empty.`),T.exitCode=1;return}let n=new l(t);try{let r=t.client;if(!r){let e=await n.listClients();if(!e||e.length===0){console.error(`Error: No clients are connected.`),T.exitCode=1;return}r=e[0].clientId,console.log(`Targeting client: ${e[0].deviceLabel||r} (${r})`)}let i=r||``,a=t.timeout?Number(t.timeout)*1e3:12e4,o;if(t.file?(console.log(`Sending message with file "${t.file}" to ${i}...`),o=await n.sendFile(i,t.file,{prompt:e.trim(),groupId:t.group,timeoutMs:a})):(console.log(`Sending message to ${i}...`),o=await n.sendCommand(i,`send-message`,{text:e.trim(),groupId:t.group},a)),o.success)if(console.log(`Message successfully dispatched.`),o.data?.reply||o.data?.text){let e=o.data.reply||o.data.text;console.log(``),console.log(`Response from ${i}:`),console.log(`----------------------------------------`),console.log(e),console.log(`----------------------------------------`)}else o.data&&(t.json,console.log(JSON.stringify(o.data,null,2)));else console.error(`Error from client: ${o.error||`Unknown error`}`),T.exitCode=1}catch(e){console.error(`Error sending message: ${e.message}`),T.exitCode=1}}async function k(e,t={}){if(!e||typeof e!=`string`||!e.trim()){console.error(`Error: File path cannot be empty.`),T.exitCode=1;return}let n=h.resolve(e.trim());if(!m.existsSync(n)){console.error(`Error: File not found: ${e}`),T.exitCode=1;return}let r=m.statSync(n);if(r.isDirectory()){console.error(`Error: Cannot send directory: ${e}`),T.exitCode=1;return}let i=new l(t);try{let e=t.client;if(!e){let t=await i.listClients();if(!t||t.length===0){console.error(`Error: No clients are connected.`),T.exitCode=1;return}e=t[0].clientId,console.log(`Targeting client: ${t[0].deviceLabel||e} (${e})`)}let a=e||``,o=t.name||h.basename(n);console.log(`Sending "${o}" (${r.size} bytes) to ${a}...`);let s=t.timeout?Number(t.timeout)*1e3:12e4,c=await i.sendFile(a,n,{prompt:t.prompt,name:t.name,groupId:t.group,timeoutMs:s});if(c.success)if(console.log(`File "${o}" successfully transferred to ${a}.`),c.data?.path&&console.log(`Remote location: ${c.data.path}`),c.data?.reply||c.data?.text){let e=c.data.reply||c.data.text;console.log(``),console.log(`Response from ${a}:`),console.log(`----------------------------------------`),console.log(e),console.log(`----------------------------------------`)}else t.json&&c.data&&console.log(JSON.stringify(c.data,null,2));else console.error(`Error from client: ${c.error||`Unknown error`}`),T.exitCode=1}catch(e){console.error(`Error sending file: ${e.message}`),T.exitCode=1}}async function A(e=`trigger`,t={}){let n=new l(t);try{if(e===`list`){let e=await n.listBackups(t.client);if(!e||e.length===0){console.log(`No backups found.`);return}console.log(`Available backups (${e.length}):\n`),e.forEach((e,t)=>{let n=new Date(e.timestamp).toISOString(),r=(e.totalBytes/(1024*1024)).toFixed(2);console.log(` ${t+1}. [${e.id}] Client: ${e.clientId}`),console.log(` Date: ${n}`),console.log(` Files: ${e.fileCount} (${r} MB)\n`)});return}if(e===`delete`){if(!t.backupId){console.error(`Error: --backup-id is required for delete action.`),T.exitCode=1;return}await n.deleteBackup(t.backupId,t.client),console.log(`Backup ${t.backupId} deleted.`);return}let r=t.client;if(!r){let e=await n.listClients();if(!e||e.length===0){console.error(`Error: No clients are connected to back up.`),T.exitCode=1;return}r=e[0].clientId}let i=r||``;console.log(`Requesting backup from client ${i}...`);let a=await n.sendCommand(i,`trigger-backup`,{groupId:t.group,token:n.token});a.success?(console.log(`Backup completed successfully.`),console.log(JSON.stringify(a.data,null,2))):(console.error(`Backup failed: ${a.error}`),T.exitCode=1)}catch(e){console.error(`Error executing backup command: ${e.message}`),T.exitCode=1}}async function j(e={}){let t=new l(e);try{let n=e.client;if(!n){let e=await t.listClients();if(!e||e.length===0){console.error(`Error: No clients connected.`),T.exitCode=1;return}n=e[0].clientId}let r=n||``;console.log(`Fetching tasks from client ${r}${e.group?` (group: ${e.group})`:``}...`);let i=await t.sendCommand(r,`list-tasks`,{groupId:e.group});if(i.success){let t=i.data?.tasks||[];if(t.length===0){console.log(e.group?`No tasks configured on client for group "${e.group}".`:`No tasks configured on client.`);return}console.log(`Tasks on ${n}${e.group?` (group: ${e.group})`:``} (${t.length}):\n`),t.forEach((e,t)=>{let n=e.enabled?`[enabled]`:`[disabled]`,r=e.name||e.prompt?.slice(0,30)||`Untitled task`;console.log(` ${t+1}. ${n} ${r} (${e.schedule||`manual`})`)})}else console.error(`Failed to list tasks: ${i.error}`),T.exitCode=1}catch(e){console.error(`Error executing tasks command: ${e.message}`),T.exitCode=1}}async function M(e=`get`,t={}){let n=t.cacheDir,r=o(n),i=!!(t.renew||e===`renew`||e===`generate`||e===`new`),l=t.set||(e===`set`&&t.id?t.id:null),u=``,d=!1;if(l)u=a(l,n),d=!0;else if(i)u=a(void 0,n),d=!0;else{let e=c(n);e?(u=e,d=!1):(u=s(void 0,n),d=!0)}return t.quiet?(console.log(u),{peerId:u,filePath:r,isRenewed:d}):t.json?(console.log(JSON.stringify({peerId:u,filePath:r,renewed:d},null,2)),{peerId:u,filePath:r,isRenewed:d}):(console.log(l?`WebRTC CLI Peer ID set to: ${u}`:d?`WebRTC CLI Peer ID created/renewed: ${u}`:`WebRTC CLI Peer ID: ${u}`),console.log(`Stored in: ${r}`),{peerId:u,filePath:r,isRenewed:d})}function N(e,t){return typeof e==`string`?t===`raw`?e.startsWith(`shadowclaw_client_`)?e.slice(18):e:e.startsWith(`shadowclaw_client_`)?e:`shadowclaw_client_${e}`:e}function P(e){return N(e,`raw`)}function F(e){return N(e,`exposed`)}const I=[{name:`shadowclaw_server_list_clients`,description:`List connected browser and Electron clients, including device type, ID, and active capabilities.`,inputSchema:{type:`object`,properties:{}}},{name:`shadowclaw_server_send_message`,description:`Send a message or prompt to a connected ShadowClaw client's active AI orchestrator queue.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The prompt or message text to dispatch.`},clientId:{type:`string`,description:`Target client ID. If omitted, targets the first available connected client.`},groupId:{type:`string`,description:`Target conversation group ID (e.g. 'br:main'). If omitted, targets the active group.`}},required:[`text`]}},{name:`shadowclaw_server_read_state`,description:`Read the current orchestrator state (idle, responding, etc.), active group ID, and capabilities from a connected client.`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (defaults to first available connected client).`}}}},{name:`shadowclaw_server_list_tasks`,description:`List scheduled background tasks configured on a connected client (optionally filtered by conversation group).`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (defaults to first available connected client).`},groupId:{type:`string`,description:`Optional conversation group ID filter.`}}}},{name:`shadowclaw_server_set_active_client`,description:`Set the active default connected client used when no clientId is explicitly provided in tool calls.`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (or index '0', '1', prefix, or device label) to make active.`}},required:[`clientId`]}},{name:`shadowclaw_server_manage_backup`,description:`Trigger or manage OPFS workspace file backups for a connected client (trigger, list, or delete).`,inputSchema:{type:`object`,properties:{action:{type:`string`,enum:[`trigger`,`list`,`delete`],description:`Backup action to perform (default: 'trigger').`,default:`trigger`},clientId:{type:`string`,description:`Target client ID.`},backupId:{type:`string`,description:`Backup snapshot ID (required for 'delete').`},groupId:{type:`string`,description:`Optional workspace conversation group ID.`}}}},{name:`shadowclaw_server_status`,description:`Query ShadowClaw Node server status, version, and active client count.`,inputSchema:{type:`object`,properties:{}}},{name:`shadowclaw_server_send_notification`,description:`Broadcast an OS-level push notification to subscribed devices via Web Push (VAPID), or send to a specific registered client. Works even when the client browser tab is closed, asleep, or running in the background.`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Notification title (default: 'ShadowClaw').`},body:{type:`string`,description:`The notification body message text.`},clientId:{type:`string`,description:`Target client ID, prefix, or device label of a specific client that has registered in the past. If omitted, broadcasts to all subscribed devices.`}},required:[`body`]}}];function L(e,t){try{let n=typeof e.getConnectedClients==`function`?e.getConnectedClients():typeof e.listClients==`function`?e.listClients():[];if(Array.isArray(n)&&n.length>0){if(typeof t==`string`&&t.trim()){let e=t.trim(),r=n.find(t=>(t.clientId||t.id)===e);if(r)return r.clientId||r.id||``;let i=parseInt(e,10);if(!isNaN(i)&&i>=0&&i<n.length)return n[i].clientId||n[i].id||``;let a=n.find(t=>(t.clientId||t.id||``).startsWith(e)||(t.clientId||t.id||``).replace(/^client-/,``).startsWith(e));if(a)return a.clientId||a.id||``;let o=n.find(t=>t.deviceLabel?.toLowerCase().includes(e.toLowerCase()));return o?o.clientId||o.id||``:e}if(typeof e.getActiveClientId==`function`){let t=e.getActiveClientId();if(t)return t}return n[0].clientId||n[0].id||``}}catch{}return typeof t==`string`?t.trim():``}const ne=h.dirname(g(import.meta.url));function re(){try{let e=h.resolve(ne,`../../../package.json`);if(m.existsSync(e)){let t=JSON.parse(m.readFileSync(e,`utf8`));if(t.version)return t.version}}catch{}return`1.27.1`}const R=`shadowclaw_local_`,ie=I;function z(e,t=R){let n=e.inputSchema||e.input_schema,r=n&&typeof n==`object`?{...n,type:n.type||`object`,properties:n.properties||{}}:{type:`object`,properties:{}};return{name:t?`${t}${e.name}`:e.name,description:e.description||`CLI agent tool: ${e.name}`,inputSchema:r,annotations:e.annotations}}function B(e,t,n){let r=!1,i=[];return Array.isArray(e)?i=e.map(e=>e&&typeof e==`object`?e.type===`image`?{type:`image`,data:e.data||``,mimeType:e.media_type||e.mimeType||`image/png`}:e.type===`text`?{type:`text`,text:String(e.text??``)}:{type:`text`,text:JSON.stringify(e,null,2)}:{type:`text`,text:String(e??``)}):typeof e==`string`?((e.toLowerCase().startsWith(`error`)||e.toLowerCase().startsWith(`tool error`)||e.includes(`SecurityError`)||e.startsWith(`Tool "`)&&e.includes(`is not allowed`)||e.startsWith(`Tool "`)&&e.includes(`is not available`))&&(r=!0),i=[{type:`text`,text:e}]):e&&typeof e==`object`?((e.error||e.success===!1)&&(r=!0),i=[{type:`text`,text:JSON.stringify(e,null,2)}]):i=[{type:`text`,text:String(e??``)}],{jsonrpc:`2.0`,id:n,result:{resultType:`complete`,isError:r,content:i,_meta:{"io.modelcontextprotocol/serverInfo":t}}}}function V(e={}){let n=e.client||new l(e),r=e.relayClientTools!==!1,i=e.targetClientId||e.clientTarget,a=i||``,o={name:`shadow-claw`,version:e.version||re()},s={tools:{listChanged:!0},extensions:{"io.modelcontextprotocol/tasks":{}}};async function c(e){let t=e||a||i;try{let e=await n.listClients();return L({getConnectedClients:()=>e},t)}catch{}return L(n,t)}let d=new Map,p=new Map,m=e.localTools!==!1,g=e.toolPrefix??`local`,_=g===`none`||g===``?``:g===`shadowclaw`?`shadowclaw_`:R,v=new Map,x=null;async function S(){return x||=(async()=>{if(e.core&&e.db){let t;if(e.workspaceDir||e.workspace)t=e.workspaceDir||e.workspace;else{let e=h.join(D(),`shadow-claw`);await y(e,{recursive:!0}),t=await b(h.join(e,`workspace-`))}return{db:e.db,workspaceDir:t,core:e.core}}let n=e.core||await f(),r=e.workspaceDir||e.workspace,i=null,a=null,o=null;if(r)i=h.resolve(r),a=e.cacheDir?h.resolve(e.cacheDir):h.join(i,`.cache`),o=e.databaseDir?h.resolve(e.databaseDir):h.join(a,`database`);else try{let t=h.join(D(),`shadow-claw`);await y(t,{recursive:!0}),i=await b(h.join(t,`workspace-`)),a=e.cacheDir?h.resolve(e.cacheDir):await b(h.join(t,`cache-`)),o=e.databaseDir?h.resolve(e.databaseDir):h.join(a,`database`),await y(a,{recursive:!0}),await y(o,{recursive:!0})}catch(e){return console.error(`[ShadowClaw MCP] Warning: No --workspace provided and failed to initialize temporary fallback workspace (${e.message}). Local workspace tools are disabled.`),null}try{let r=await t({...e,workspace:i,cacheDir:a,databaseDir:o,yes:!0,quiet:!0,isTTY:!1,core:n});return{db:r.db,workspaceDir:r.workspaceDir,core:r.core}}catch(e){return console.error(`[ShadowClaw MCP] Warning: Failed to bootstrap headless agent context (${e.message}). Local workspace tools are disabled.`),null}})(),x}async function C(){if(!m)return[];let t;try{t=await S()}catch(e){return console.error(`[ShadowClaw MCP] Failed to initialize local agent context: ${e.message}`),[]}if(!t)return[];let{db:n,core:r}=t,i=e.group||r.DEFAULT_SERVER_GROUP_ID||`server:main`,a=null;if(e.toolsProfile||e.profile){let t=String(e.toolsProfile||e.profile).trim().toLowerCase(),i=r.DEFAULT_BUILTIN_PROFILE||null,o=[];if(typeof r.getConfig==`function`)try{let e=await r.getConfig(n,r.CONFIG_KEYS?.TOOL_PROFILES||`tool_profiles`);typeof e==`string`?o=JSON.parse(e):Array.isArray(e)&&(o=e)}catch{}let s=[i,...o].filter(Boolean).find(e=>e.id&&String(e.id).toLowerCase()===t||e.name&&String(e.name).toLowerCase()===t);s&&(a=new Set(s.enabledToolNames||[]))}let o=null;if(e.tools&&typeof e.tools==`string`&&e.tools.trim()){let t=e.tools.split(`,`).map(e=>e.trim()).filter(Boolean);o=new Set(t)}let s=[...r.TOOL_DEFINITIONS||[]];if(typeof r.loadDeclarativeTools==`function`)try{let e=await r.loadDeclarativeTools(n,i);if(e&&Array.isArray(e.tools))for(let t of e.tools)s.some(e=>e.name===t.name)||s.push(t)}catch{}let c=r.BROWSER_ONLY_TOOLS||u;v.clear();let l=[];for(let e of s){if(!e||!e.name||c&&c.has(e.name)||o&&!o.has(e.name)||a&&!a.has(e.name))continue;let t=z(e,_);v.set(e.name,e),v.set(`shadowclaw_local_${e.name}`,e),v.set(`shadowclaw_${e.name}`,e),l.push(t)}return l}async function w(t,n,r){try{let i=await S();if(!i)return{jsonrpc:`2.0`,id:r,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Local workspace tools are not initialized.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};let a=e.group||i.core.DEFAULT_SERVER_GROUP_ID||`server:main`,s;try{let{resolveAgentProvider:t}=await import(`./chunk-Cj9wl0qx.js`),n=await t(i.db,i.core,i.workspaceDir,{...e,interactive:!1});s={db:i.db,provider:n.providerId,model:n.model,apiKey:n.apiKey}}catch{}return console.error(`[ShadowClaw MCP] Executing local tool '${t.name}' in workspace: ${i.workspaceDir}`),B(await i.core.executeTool(i.db,t.name,n,a,{invokeContext:s}),o,r)}catch(e){return{jsonrpc:`2.0`,id:r,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error executing local tool '${t.name}': ${e.message||String(e)}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}async function T(){if(!r)return[];let e=[];try{e=await n.listClients()}catch{}if(!Array.isArray(e)||e.length===0)return d.clear(),p.clear(),[];d.clear(),p.clear();for(let t of e){let e=t.clientId||t.id;if(e)try{let r=await n.sendCommand(e,`list-tools`,{});if(r&&r.success&&r.data?.tools&&Array.isArray(r.data.tools))for(let e of r.data.tools){let n=P(e.name);n===`send_notification`||n.startsWith(`shadowclaw_`)&&!n.startsWith(`shadowclaw_client_`)||(p.has(n)||(p.set(n,e),d.set(n,[])),d.get(n).push(t))}}catch{}}let t=await c(),i=[];for(let[n,r]of p.entries()){let a=d.get(n)||[],o=a.map(e=>e.clientId||e.id).filter(Boolean),s=a.find(e=>(e.clientId||e.id)===t)||a[0],c=s?.clientId||s?.id||``,l=s?.deviceLabel||`Client`,u=r.inputSchema&&typeof r.inputSchema==`object`?r.inputSchema:{type:`object`,properties:{}},f={...u.properties||{},clientId:{type:`string`,description:`Target ShadowClaw client ID (optional; defaults to ${c} [${l}]). Available on: ${a.map(e=>`${e.clientId||e.id} (${e.deviceLabel||`Client`})`).join(`, `)}`,enum:o}},p=e.length>1?a.length>1?` [Default: ${l} (${c.slice(0,14)}...)]`:` [Client: ${l} (${c.slice(0,14)}...)]`:``,m=F(n);i.push({name:m,description:(r.description||`Relayed tool '${n}' from connected client.`)+p,inputSchema:{...u,type:`object`,properties:f},annotations:r.annotations})}return i}async function E(e,t={}){let i=e.id===void 0||e.id===null,l=e.id??null;if(t[`mcp-method`]&&t[`mcp-method`]!==e.method)return{jsonrpc:`2.0`,id:l,error:{code:-32020,message:`Mcp-Method header '${t[`mcp-method`]}' does not match '${e.method}'`}};switch(e.method){case`server/discover`:return{jsonrpc:`2.0`,id:l,result:{protocolVersion:`2026-07-28`,supportedProtocolVersions:[`2026-07-28`,`2025-11-25`,`2024-11-05`],capabilities:s,serverInfo:o,_meta:{"io.modelcontextprotocol/serverInfo":o}}};case`initialize`:return{jsonrpc:`2.0`,id:l,result:{protocolVersion:e.params?.protocolVersion||`2024-11-05`,capabilities:s,serverInfo:o}};case`notifications/initialized`:return null;case`tools/list`:{let e=[];try{if(typeof n.listPushClients==`function`)e=await n.listPushClients();else if(typeof n.listPushSubscriptions==`function`){let t=await n.listPushSubscriptions();if(Array.isArray(t)){let n=new Map;for(let e of t){let t=(e.client_id||``).trim()||(e.id?String(e.id):``);t&&!n.has(t)&&n.set(t,{clientId:t,deviceLabel:e.device_label||void 0})}e=Array.from(n.values())}}}catch{}let t=Array.isArray(e)?[...e].sort((e,t)=>(e.clientId||``).localeCompare(t.clientId||``)):[],r=t.map(e=>e.clientId).filter(Boolean),i=await T(),a=await C(),s=new Map;for(let e of ie)s.set(e.name,e);for(let e of a)s.has(e.name)||s.set(e.name,e);for(let e of i)s.has(e.name)||s.set(e.name,e);if(r.length>0)for(let e of[`shadowclaw_server_send_notification`,`shadowclaw_send_notification`]){let n=s.get(e);n&&s.set(e,{...n,inputSchema:{...n.inputSchema,type:`object`,properties:{...n.inputSchema?.properties||{},clientId:{type:`string`,description:`Target client ID, prefix, or device label of a specific client registered for push notifications (optional; if omitted, broadcasts to all subscribed devices). Available on: ${t.map(e=>`${e.clientId} (${e.deviceLabel||`Client`})`).join(`, `)}`,enum:r}}}})}return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,ttlMs:5e3,cacheScope:`private`,tools:Array.from(s.values()).sort((e,t)=>e.name.localeCompare(t.name)),_meta:{"io.modelcontextprotocol/serverInfo":o}}}}case`tools/call`:{let t=e.params?.name,i=e.params?.arguments||{},s=e.params?.inputResponses;if(!t)return{jsonrpc:`2.0`,id:l,error:{code:-32602,message:`Missing required parameter 'name'`}};if(t===`shadowclaw_server_list_clients`||t===`shadowclaw_list_clients`)try{let e=await n.listClients();return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({clients:e},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error listing clients: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_set_active_client`||t===`shadowclaw_set_active_client`){let e=await c(i.clientId);return e?(a=e,console.error(`[ShadowClaw MCP] Active default client set to: ${a}`),{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:`Active default client set to: ${a}`}],_meta:{activeClientId:a,"io.modelcontextprotocol/serverInfo":o}}}):{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Client '${i.clientId}' not found among connected clients.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_send_message`||t===`shadowclaw_send_message`){let e=await c(i.clientId);if(!e)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: No connected client available.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};try{let t=await n.sendCommand(e,`send-message`,{text:i.text,groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error sending message: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_read_state`||t===`shadowclaw_read_state`){let e=await c(i.clientId);try{let t=await n.sendCommand(e,`read-state`,{});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error reading state: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_list_tasks`||t===`shadowclaw_list_tasks`){let e=await c(i.clientId);try{let t=await n.sendCommand(e,`list-tasks`,{groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error listing tasks: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_manage_backup`||t===`shadowclaw_manage_backup`){let e=i.action||`trigger`,t=await c(i.clientId);try{if(e===`list`){let e=await n.listBackups(t);return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({backups:e},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(e===`delete`){let e=await n.deleteBackup(i.backupId,t);return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify(e,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}let r=await n.sendCommand(t,`trigger-backup`,{groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!r.success,content:[{type:`text`,text:JSON.stringify(r.data||r,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error managing backup: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_status`||t===`shadowclaw_status`)try{let e=await n.listClients();return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({server:`ShadowClaw`,version:o.version,connectedClients:e.length,status:`healthy`},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error querying server status: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_send_notification`||t===`shadowclaw_send_notification`||t===`send_notification`){let e=String(i.body||``).trim();if(!e)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Notification 'body' parameter cannot be empty.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};let t=String(i.title||`ShadowClaw`).trim(),r=typeof i.clientId==`string`&&i.clientId.trim()?i.clientId.trim():void 0;try{let i=await n.broadcastNotification({title:t,body:e,...r?{clientId:r}:{}}),a=i?.sent??0,s=i?.failed??0,c;return c=i?.notFound?`Warning: No push subscriptions found for client '${r}'. Ensure push notifications were registered by this client in ShadowClaw Settings.`:i?.noSubscribers?`Warning: Push notification broadcast completed, but no devices are currently subscribed to push notifications. Ensure push notifications are enabled in ShadowClaw Settings on the client first.`:r?`Push notification sent to client '${r}': ${a} recipient(s) delivered, ${s} failed.`:`Push notification broadcast sent: ${a} recipient(s) delivered, ${s} failed.`,{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!1,content:[{type:`text`,text:c}],_meta:{...i,...r?{targetClientId:r}:{},"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Failed to send push notification: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}let u=P(t);if((u===`ask_user`||t===`ask_user`)&&s&&s.response)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:String(s.response)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};m&&v.size===0&&await C();let f=t.startsWith(R),h=t.startsWith(`shadowclaw_client_`),_=v.get(t);if(!_&&f&&(_=v.get(t.slice(17))),!_&&t.startsWith(`shadowclaw_`)&&!h&&(_=v.get(t.slice(11))),f&&_){let e={...i};return delete e.clientId,await w(_,e,l)}r&&p.size===0&&await T();let y=(d.get(u)||d.get(t)||[]).map(e=>e.clientId||e.id).filter(Boolean),b=[];try{b=await n.listClients()}catch{}if(!h&&_){if(g===`none`&&!i.clientId){let e={...i};return delete e.clientId,await w(_,e,l)}if(!r||!Array.isArray(b)||b.length===0){let e={...i};return delete e.clientId,await w(_,e,l)}}let x=``;if(i.clientId)x=await c(i.clientId);else{let e=await c();x=y.includes(e)?e:y.length>0?y[0]:e}if(!x)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: No connected client available.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};if(y.length>0&&!y.includes(x))return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Tool '${t}' is not enabled or available on client '${x}'. (Available on: ${y.join(`, `)})`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}};try{console.error(`[ShadowClaw MCP] Executing '${u}' on client: ${x}`);let e={...i};delete e.clientId;let t=u===`ask_user`?await n.sendCommand(x,`invoke-tool`,{toolName:u,input:e},3e5):await n.sendCommand(x,`invoke-tool`,{toolName:u,input:e}),r=t.data?.result===void 0?t.data:t.data.result,a=typeof r==`string`?r:JSON.stringify(r,null,2),s=t.error||t.data&&t.data.error||`Unknown tool execution error`;return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:t.success?a||``:a&&a!==`null`&&a!==`{}`?`${a}\n${s}`:`Tool execution error: ${s}`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Tool error: ${e.message}`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}}}}case`tasks/get`:return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,task:{taskId:e.params?.taskId||`task-1`,status:`completed`},_meta:{"io.modelcontextprotocol/serverInfo":o}}};default:return i?null:{jsonrpc:`2.0`,id:l,error:{code:-32601,message:`Method not found: '${e.method}'`}}}}return{handleMessage:E,getActiveClientId:()=>a,setActiveClientId:e=>{a=e},close:async()=>{if(x)try{let e=await x;typeof e?.core?.closeSqliteDatabase==`function`&&e.core.closeSqliteDatabase()}catch{}}}}async function H(e={}){if((e.mcpTransport||(e.http?`http`:`stdio`))===`http`){let t=parseInt(String(e.port||T.env.MCP_PORT||`8888`),10),n=e.host||`127.0.0.1`,r=V(e);E.createServer(async(e,t)=>{if(e.method!==`POST`||e.url?.split(`?`)[0]!==`/mcp`){t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:`Not found`}));return}let n=``;e.on(`data`,e=>n+=e),e.on(`end`,async()=>{let i;try{i=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,id:null,error:{code:-32700,message:`Parse error`}}));return}try{let n={"mcp-protocol-version":e.headers[`mcp-protocol-version`],"mcp-method":e.headers[`mcp-method`],"mcp-name":e.headers[`mcp-name`]},a=await r.handleMessage(i,n);if(a===null){t.writeHead(202),t.end();return}t.writeHead(200,{"Content-Type":`application/json`,"MCP-Protocol-Version":`2026-07-28`}),t.end(JSON.stringify(a))}catch(e){t.writeHead(500,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,id:i?.id??null,error:{code:-32603,message:e?.message||`Internal error`}}))}})}).listen(t,n,()=>{console.error(`[ShadowClaw MCP] HTTP MCP server listening at http://${n}:${t}/mcp (2026-07-28)`)});return}console.log=(...e)=>console.error(...e),console.info=(...e)=>console.error(...e);let t=V(e),n=ee.createInterface({input:T.stdin,output:T.stdout,terminal:!1});n.on(`line`,async e=>{let n=e.trim();if(!n)return;let r;try{r=JSON.parse(n)}catch{T.stdout.write(JSON.stringify({jsonrpc:`2.0`,id:null,error:{code:-32700,message:`Parse error`}})+`
|
|
1
|
+
import{t as e}from"./chunk-uAI_Zi6n.js";import{d as t,f as n,n as r}from"./chunk-DUlIqkaX.js";import{t as i}from"./chunk-63s8NnIS.js";import{c as a,i as o,o as s,s as c}from"./chunk-DHi40kQk.js";import{t as l}from"./chunk-DFh_pp_7.js";import{t as u}from"./chunk-BQCWtrzh.js";import{n as d}from"./chunk-CK6ejMig.js";import{t as f}from"./chunk-BLMC1Bxv.js";import{r as p}from"./chunk-C-5VcG3a.js";import m from"node:fs";import h from"node:path";import{fileURLToPath as g}from"node:url";import _ from"node:process";import{exec as v}from"node:child_process";import{mkdir as y,mkdtemp as b,readFile as x,stat as S,writeFile as C}from"node:fs/promises";import{Command as w}from"commander";import T from"process";import E from"node:http";import{tmpdir as D}from"node:os";import ee from"node:readline";async function O(e={}){let t=new l(e);try{let e=await t.listClients();if(!e||e.length===0){console.log(`No clients currently registered or connected.`);return}console.log(`Connected / registered clients (${e.length}):\n`),e.forEach((e,t)=>{let n=Math.max(0,Math.floor((Date.now()-e.lastSeen)/1e3)),r=n<60?`${n}s ago`:`${Math.floor(n/60)}m ago`;console.log(` ${t+1}. ${e.deviceLabel} (id: ${e.clientId})`),e.peerId&&console.log(` Peer ID: ${e.peerId}`),console.log(` Capabilities: ${e.capabilities.join(`, `)||`none`}`),console.log(` Version: ${e.version}`),console.log(` Last seen: ${r}\n`)})}catch(e){console.error(`Error fetching clients: ${e.message}`),T.exitCode=1}}async function te(e,t={}){if(!e||typeof e!=`string`||!e.trim()){console.error(`Error: Message cannot be empty.`),T.exitCode=1;return}let n=new l(t);try{let r=t.client;if(!r){let e=await n.listClients();if(!e||e.length===0){console.error(`Error: No clients are connected.`),T.exitCode=1;return}r=e[0].clientId,console.log(`Targeting client: ${e[0].deviceLabel||r} (${r})`)}let i=r||``,a=t.timeout?Number(t.timeout)*1e3:12e4,o;if(t.file?(console.log(`Sending message with file "${t.file}" to ${i}...`),o=await n.sendFile(i,t.file,{prompt:e.trim(),groupId:t.group,timeoutMs:a})):(console.log(`Sending message to ${i}...`),o=await n.sendCommand(i,`send-message`,{text:e.trim(),groupId:t.group},a)),o.success)if(console.log(`Message successfully dispatched.`),o.data?.reply||o.data?.text){let e=o.data.reply||o.data.text;console.log(``),console.log(`Response from ${i}:`),console.log(`----------------------------------------`),console.log(e),console.log(`----------------------------------------`)}else o.data&&(t.json,console.log(JSON.stringify(o.data,null,2)));else console.error(`Error from client: ${o.error||`Unknown error`}`),T.exitCode=1}catch(e){console.error(`Error sending message: ${e.message}`),T.exitCode=1}}async function k(e,t={}){if(!e||typeof e!=`string`||!e.trim()){console.error(`Error: File path cannot be empty.`),T.exitCode=1;return}let n=h.resolve(e.trim());if(!m.existsSync(n)){console.error(`Error: File not found: ${e}`),T.exitCode=1;return}let r=m.statSync(n);if(r.isDirectory()){console.error(`Error: Cannot send directory: ${e}`),T.exitCode=1;return}let i=new l(t);try{let e=t.client;if(!e){let t=await i.listClients();if(!t||t.length===0){console.error(`Error: No clients are connected.`),T.exitCode=1;return}e=t[0].clientId,console.log(`Targeting client: ${t[0].deviceLabel||e} (${e})`)}let a=e||``,o=t.name||h.basename(n);console.log(`Sending "${o}" (${r.size} bytes) to ${a}...`);let s=t.timeout?Number(t.timeout)*1e3:12e4,c=await i.sendFile(a,n,{prompt:t.prompt,name:t.name,groupId:t.group,timeoutMs:s});if(c.success)if(console.log(`File "${o}" successfully transferred to ${a}.`),c.data?.path&&console.log(`Remote location: ${c.data.path}`),c.data?.reply||c.data?.text){let e=c.data.reply||c.data.text;console.log(``),console.log(`Response from ${a}:`),console.log(`----------------------------------------`),console.log(e),console.log(`----------------------------------------`)}else t.json&&c.data&&console.log(JSON.stringify(c.data,null,2));else console.error(`Error from client: ${c.error||`Unknown error`}`),T.exitCode=1}catch(e){console.error(`Error sending file: ${e.message}`),T.exitCode=1}}async function A(e=`trigger`,t={}){let n=new l(t);try{if(e===`list`){let e=await n.listBackups(t.client);if(!e||e.length===0){console.log(`No backups found.`);return}console.log(`Available backups (${e.length}):\n`),e.forEach((e,t)=>{let n=new Date(e.timestamp).toISOString(),r=(e.totalBytes/(1024*1024)).toFixed(2);console.log(` ${t+1}. [${e.id}] Client: ${e.clientId}`),console.log(` Date: ${n}`),console.log(` Files: ${e.fileCount} (${r} MB)\n`)});return}if(e===`delete`){if(!t.backupId){console.error(`Error: --backup-id is required for delete action.`),T.exitCode=1;return}await n.deleteBackup(t.backupId,t.client),console.log(`Backup ${t.backupId} deleted.`);return}let r=t.client;if(!r){let e=await n.listClients();if(!e||e.length===0){console.error(`Error: No clients are connected to back up.`),T.exitCode=1;return}r=e[0].clientId}let i=r||``;console.log(`Requesting backup from client ${i}...`);let a=await n.sendCommand(i,`trigger-backup`,{groupId:t.group,token:n.token});a.success?(console.log(`Backup completed successfully.`),console.log(JSON.stringify(a.data,null,2))):(console.error(`Backup failed: ${a.error}`),T.exitCode=1)}catch(e){console.error(`Error executing backup command: ${e.message}`),T.exitCode=1}}async function j(e={}){let t=new l(e);try{let n=e.client;if(!n){let e=await t.listClients();if(!e||e.length===0){console.error(`Error: No clients connected.`),T.exitCode=1;return}n=e[0].clientId}let r=n||``;console.log(`Fetching tasks from client ${r}${e.group?` (group: ${e.group})`:``}...`);let i=await t.sendCommand(r,`list-tasks`,{groupId:e.group});if(i.success){let t=i.data?.tasks||[];if(t.length===0){console.log(e.group?`No tasks configured on client for group "${e.group}".`:`No tasks configured on client.`);return}console.log(`Tasks on ${n}${e.group?` (group: ${e.group})`:``} (${t.length}):\n`),t.forEach((e,t)=>{let n=e.enabled?`[enabled]`:`[disabled]`,r=e.name||e.prompt?.slice(0,30)||`Untitled task`;console.log(` ${t+1}. ${n} ${r} (${e.schedule||`manual`})`)})}else console.error(`Failed to list tasks: ${i.error}`),T.exitCode=1}catch(e){console.error(`Error executing tasks command: ${e.message}`),T.exitCode=1}}async function M(e=`get`,t={}){let n=t.cacheDir,r=o(n),i=!!(t.renew||e===`renew`||e===`generate`||e===`new`),l=t.set||(e===`set`&&t.id?t.id:null),u=``,d=!1;if(l)u=a(l,n),d=!0;else if(i)u=a(void 0,n),d=!0;else{let e=c(n);e?(u=e,d=!1):(u=s(void 0,n),d=!0)}return t.quiet?(console.log(u),{peerId:u,filePath:r,isRenewed:d}):t.json?(console.log(JSON.stringify({peerId:u,filePath:r,renewed:d},null,2)),{peerId:u,filePath:r,isRenewed:d}):(console.log(l?`WebRTC CLI Peer ID set to: ${u}`:d?`WebRTC CLI Peer ID created/renewed: ${u}`:`WebRTC CLI Peer ID: ${u}`),console.log(`Stored in: ${r}`),{peerId:u,filePath:r,isRenewed:d})}function N(e,t){return typeof e==`string`?t===`raw`?e.startsWith(`shadowclaw_client_`)?e.slice(18):e:e.startsWith(`shadowclaw_client_`)?e:`shadowclaw_client_${e}`:e}function P(e){return N(e,`raw`)}function F(e){return N(e,`exposed`)}const I=[{name:`shadowclaw_server_list_clients`,description:`List connected browser and Electron clients, including device type, ID, and active capabilities.`,inputSchema:{type:`object`,properties:{}}},{name:`shadowclaw_server_send_message`,description:`Send a message or prompt to a connected ShadowClaw client's active AI orchestrator queue.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The prompt or message text to dispatch.`},clientId:{type:`string`,description:`Target client ID. If omitted, targets the first available connected client.`},groupId:{type:`string`,description:`Target conversation group ID (e.g. 'br:main'). If omitted, targets the active group.`}},required:[`text`]}},{name:`shadowclaw_server_read_state`,description:`Read the current orchestrator state (idle, responding, etc.), active group ID, and capabilities from a connected client.`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (defaults to first available connected client).`}}}},{name:`shadowclaw_server_list_tasks`,description:`List scheduled background tasks configured on a connected client (optionally filtered by conversation group).`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (defaults to first available connected client).`},groupId:{type:`string`,description:`Optional conversation group ID filter.`}}}},{name:`shadowclaw_server_set_active_client`,description:`Set the active default connected client used when no clientId is explicitly provided in tool calls.`,inputSchema:{type:`object`,properties:{clientId:{type:`string`,description:`Target client ID (or index '0', '1', prefix, or device label) to make active.`}},required:[`clientId`]}},{name:`shadowclaw_server_manage_backup`,description:`Trigger or manage OPFS workspace file backups for a connected client (trigger, list, or delete).`,inputSchema:{type:`object`,properties:{action:{type:`string`,enum:[`trigger`,`list`,`delete`],description:`Backup action to perform (default: 'trigger').`,default:`trigger`},clientId:{type:`string`,description:`Target client ID.`},backupId:{type:`string`,description:`Backup snapshot ID (required for 'delete').`},groupId:{type:`string`,description:`Optional workspace conversation group ID.`}}}},{name:`shadowclaw_server_status`,description:`Query ShadowClaw Node server status, version, and active client count.`,inputSchema:{type:`object`,properties:{}}},{name:`shadowclaw_server_send_notification`,description:`Broadcast an OS-level push notification to subscribed devices via Web Push (VAPID), or send to a specific registered client. Works even when the client browser tab is closed, asleep, or running in the background.`,inputSchema:{type:`object`,properties:{title:{type:`string`,description:`Notification title (default: 'ShadowClaw').`},body:{type:`string`,description:`The notification body message text.`},clientId:{type:`string`,description:`Target client ID, prefix, or device label of a specific client that has registered in the past. If omitted, broadcasts to all subscribed devices.`}},required:[`body`]}}];function L(e,t){try{let n=typeof e.getConnectedClients==`function`?e.getConnectedClients():typeof e.listClients==`function`?e.listClients():[];if(Array.isArray(n)&&n.length>0){if(typeof t==`string`&&t.trim()){let e=t.trim(),r=n.find(t=>(t.clientId||t.id)===e);if(r)return r.clientId||r.id||``;let i=parseInt(e,10);if(!isNaN(i)&&i>=0&&i<n.length)return n[i].clientId||n[i].id||``;let a=n.find(t=>(t.clientId||t.id||``).startsWith(e)||(t.clientId||t.id||``).replace(/^client-/,``).startsWith(e));if(a)return a.clientId||a.id||``;let o=n.find(t=>t.deviceLabel?.toLowerCase().includes(e.toLowerCase()));return o?o.clientId||o.id||``:e}if(typeof e.getActiveClientId==`function`){let t=e.getActiveClientId();if(t)return t}return n[0].clientId||n[0].id||``}}catch{}return typeof t==`string`?t.trim():``}const ne=h.dirname(g(import.meta.url));function re(){try{let e=h.resolve(ne,`../../../package.json`);if(m.existsSync(e)){let t=JSON.parse(m.readFileSync(e,`utf8`));if(t.version)return t.version}}catch{}return`1.27.1`}const R=`shadowclaw_local_`,ie=I;function z(e,t=R){let n=e.inputSchema||e.input_schema,r=n&&typeof n==`object`?{...n,type:n.type||`object`,properties:n.properties||{}}:{type:`object`,properties:{}};return{name:t?`${t}${e.name}`:e.name,description:e.description||`CLI agent tool: ${e.name}`,inputSchema:r,annotations:e.annotations}}function B(e,t,n){let r=!1,i=[];return Array.isArray(e)?i=e.map(e=>e&&typeof e==`object`?e.type===`image`?{type:`image`,data:e.data||``,mimeType:e.media_type||e.mimeType||`image/png`}:e.type===`text`?{type:`text`,text:String(e.text??``)}:{type:`text`,text:JSON.stringify(e,null,2)}:{type:`text`,text:String(e??``)}):typeof e==`string`?((e.toLowerCase().startsWith(`error`)||e.toLowerCase().startsWith(`tool error`)||e.includes(`SecurityError`)||e.startsWith(`Tool "`)&&e.includes(`is not allowed`)||e.startsWith(`Tool "`)&&e.includes(`is not available`))&&(r=!0),i=[{type:`text`,text:e}]):e&&typeof e==`object`?((e.error||e.success===!1)&&(r=!0),i=[{type:`text`,text:JSON.stringify(e,null,2)}]):i=[{type:`text`,text:String(e??``)}],{jsonrpc:`2.0`,id:n,result:{resultType:`complete`,isError:r,content:i,_meta:{"io.modelcontextprotocol/serverInfo":t}}}}function V(e={}){let n=e.client||new l(e),r=e.relayClientTools!==!1,i=e.targetClientId||e.clientTarget,a=i||``,o={name:`shadow-claw`,version:e.version||re()},s={tools:{listChanged:!0},extensions:{"io.modelcontextprotocol/tasks":{}}};async function c(e){let t=e||a||i;try{let e=await n.listClients();return L({getConnectedClients:()=>e},t)}catch{}return L(n,t)}let d=new Map,p=new Map,m=e.localTools!==!1,g=e.toolPrefix??`local`,_=g===`none`||g===``?``:g===`shadowclaw`?`shadowclaw_`:R,v=new Map,x=null;async function S(){return x||=(async()=>{if(e.core&&e.db){let t;if(e.workspaceDir||e.workspace)t=e.workspaceDir||e.workspace;else{let e=h.join(D(),`shadow-claw`);await y(e,{recursive:!0}),t=await b(h.join(e,`workspace-`))}return{db:e.db,workspaceDir:t,core:e.core}}let n=e.core||await f(),r=e.workspaceDir||e.workspace,i=null,a=null,o=null;if(r)i=h.resolve(r),a=e.cacheDir?h.resolve(e.cacheDir):h.join(i,`.cache`),o=e.databaseDir?h.resolve(e.databaseDir):h.join(a,`database`);else try{let t=h.join(D(),`shadow-claw`);await y(t,{recursive:!0}),i=await b(h.join(t,`workspace-`)),a=e.cacheDir?h.resolve(e.cacheDir):await b(h.join(t,`cache-`)),o=e.databaseDir?h.resolve(e.databaseDir):h.join(a,`database`),await y(a,{recursive:!0}),await y(o,{recursive:!0})}catch(e){return console.error(`[ShadowClaw MCP] Warning: No --workspace provided and failed to initialize temporary fallback workspace (${e.message}). Local workspace tools are disabled.`),null}try{let r=await t({...e,workspace:i,cacheDir:a,databaseDir:o,yes:!0,quiet:!0,isTTY:!1,core:n});return{db:r.db,workspaceDir:r.workspaceDir,core:r.core}}catch(e){return console.error(`[ShadowClaw MCP] Warning: Failed to bootstrap headless agent context (${e.message}). Local workspace tools are disabled.`),null}})(),x}async function C(){if(!m)return[];let t;try{t=await S()}catch(e){return console.error(`[ShadowClaw MCP] Failed to initialize local agent context: ${e.message}`),[]}if(!t)return[];let{db:n,core:r}=t,i=e.group||r.DEFAULT_SERVER_GROUP_ID||`server:main`,a=null;if(e.toolsProfile||e.profile){let t=String(e.toolsProfile||e.profile).trim().toLowerCase(),i=r.DEFAULT_BUILTIN_PROFILE||null,o=[];if(typeof r.getConfig==`function`)try{let e=await r.getConfig(n,r.CONFIG_KEYS?.TOOL_PROFILES||`tool_profiles`);typeof e==`string`?o=JSON.parse(e):Array.isArray(e)&&(o=e)}catch{}let s=[i,...o].filter(Boolean).find(e=>e.id&&String(e.id).toLowerCase()===t||e.name&&String(e.name).toLowerCase()===t);s&&(a=new Set(s.enabledToolNames||[]))}let o=null;if(e.tools&&typeof e.tools==`string`&&e.tools.trim()){let t=e.tools.split(`,`).map(e=>e.trim()).filter(Boolean);o=new Set(t)}let s=[...r.TOOL_DEFINITIONS||[]];if(typeof r.loadDeclarativeTools==`function`)try{let e=await r.loadDeclarativeTools(n,i);if(e&&Array.isArray(e.tools))for(let t of e.tools)s.some(e=>e.name===t.name)||s.push(t)}catch{}let c=r.BROWSER_ONLY_TOOLS||u;v.clear();let l=[];for(let e of s){if(!e||!e.name||c&&c.has(e.name)||o&&!o.has(e.name)||a&&!a.has(e.name))continue;let t=z(e,_);v.set(e.name,e),v.set(`shadowclaw_local_${e.name}`,e),v.set(`shadowclaw_${e.name}`,e),l.push(t)}return l}async function w(t,n,r){try{let i=await S();if(!i)return{jsonrpc:`2.0`,id:r,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Local workspace tools are not initialized.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};let a=e.group||i.core.DEFAULT_SERVER_GROUP_ID||`server:main`,s;try{let{resolveAgentProvider:t}=await import(`./chunk-Cj9wl0qx.js`),n=await t(i.db,i.core,i.workspaceDir,{...e,interactive:!1});s={db:i.db,provider:n.providerId,model:n.model,apiKey:n.apiKey}}catch{}return console.error(`[ShadowClaw MCP] Executing local tool '${t.name}' in workspace: ${i.workspaceDir}`),B(await i.core.executeTool(i.db,t.name,n,a,{invokeContext:s}),o,r)}catch(e){return{jsonrpc:`2.0`,id:r,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error executing local tool '${t.name}': ${e.message||String(e)}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}async function T(){if(!r)return[];let e=[];try{e=await n.listClients()}catch{}if(!Array.isArray(e)||e.length===0)return d.clear(),p.clear(),[];d.clear(),p.clear();for(let t of e){let e=t.clientId||t.id;if(e)try{let r=await n.sendCommand(e,`list-tools`,{});if(r&&r.success&&r.data?.tools&&Array.isArray(r.data.tools))for(let e of r.data.tools){let n=P(e.name);n===`send_notification`||n.startsWith(`shadowclaw_`)&&!n.startsWith(`shadowclaw_client_`)||(p.has(n)||(p.set(n,e),d.set(n,[])),d.get(n).push(t))}}catch{}}let t=await c(),i=[];for(let[n,r]of p.entries()){let a=d.get(n)||[],o=a.map(e=>e.clientId||e.id).filter(Boolean),s=a.find(e=>(e.clientId||e.id)===t)||a[0],c=s?.clientId||s?.id||``,l=s?.deviceLabel||`Client`,u=r.inputSchema&&typeof r.inputSchema==`object`?r.inputSchema:{type:`object`,properties:{}},f={...u.properties||{},clientId:{type:`string`,description:`Target ShadowClaw client ID (optional; defaults to ${c} [${l}]). Available on: ${a.map(e=>`${e.clientId||e.id} (${e.deviceLabel||`Client`})`).join(`, `)}`,enum:o}},p=e.length>1?a.length>1?` [Default: ${l} (${c.slice(0,14)}...)]`:` [Client: ${l} (${c.slice(0,14)}...)]`:``,m=F(n);i.push({name:m,description:(r.description||`Relayed tool '${n}' from connected client.`)+p,inputSchema:{...u,type:`object`,properties:f},annotations:r.annotations})}return i}async function E(e,t={}){let i=e.id===void 0||e.id===null,l=e.id??null;if(t[`mcp-method`]&&t[`mcp-method`]!==e.method)return{jsonrpc:`2.0`,id:l,error:{code:-32020,message:`Mcp-Method header '${t[`mcp-method`]}' does not match '${e.method}'`}};switch(e.method){case`server/discover`:return{jsonrpc:`2.0`,id:l,result:{protocolVersion:`2026-07-28`,supportedProtocolVersions:[`2026-07-28`,`2025-11-25`,`2024-11-05`],capabilities:s,serverInfo:o,_meta:{"io.modelcontextprotocol/serverInfo":o}}};case`initialize`:return{jsonrpc:`2.0`,id:l,result:{protocolVersion:e.params?.protocolVersion||`2024-11-05`,capabilities:s,serverInfo:o}};case`notifications/initialized`:return null;case`tools/list`:{let e=[];try{if(typeof n.listPushClients==`function`)e=await n.listPushClients();else if(typeof n.listPushSubscriptions==`function`){let t=await n.listPushSubscriptions();if(Array.isArray(t)){let n=new Map;for(let e of t){let t=(e.client_id||``).trim()||(e.id?String(e.id):``);t&&!n.has(t)&&n.set(t,{clientId:t,deviceLabel:e.device_label||void 0})}e=Array.from(n.values())}}}catch{}let t=Array.isArray(e)?[...e].sort((e,t)=>(e.clientId||``).localeCompare(t.clientId||``)):[],r=t.map(e=>e.clientId).filter(Boolean),i=await T(),a=await C(),s=new Map;for(let e of ie)s.set(e.name,e);for(let e of a)s.has(e.name)||s.set(e.name,e);for(let e of i)s.has(e.name)||s.set(e.name,e);if(r.length>0)for(let e of[`shadowclaw_server_send_notification`,`shadowclaw_send_notification`]){let n=s.get(e);n&&s.set(e,{...n,inputSchema:{...n.inputSchema,type:`object`,properties:{...n.inputSchema?.properties||{},clientId:{type:`string`,description:`Target client ID, prefix, or device label of a specific client registered for push notifications (optional; if omitted, broadcasts to all subscribed devices). Available on: ${t.map(e=>`${e.clientId} (${e.deviceLabel||`Client`})`).join(`, `)}`,enum:r}}}})}return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,ttlMs:5e3,cacheScope:`private`,tools:Array.from(s.values()).sort((e,t)=>e.name.localeCompare(t.name)),_meta:{"io.modelcontextprotocol/serverInfo":o}}}}case`tools/call`:{let t=e.params?.name,i=e.params?.arguments||{},s=e.params?.inputResponses;if(!t)return{jsonrpc:`2.0`,id:l,error:{code:-32602,message:`Missing required parameter 'name'`}};if(t===`shadowclaw_server_list_clients`||t===`shadowclaw_list_clients`)try{let e=await n.listClients();return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({clients:e},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error listing clients: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_set_active_client`||t===`shadowclaw_set_active_client`){let e=await c(i.clientId);return e?(a=e,console.error(`[ShadowClaw MCP] Active default client set to: ${a}`),{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:`Active default client set to: ${a}`}],_meta:{activeClientId:a,"io.modelcontextprotocol/serverInfo":o}}}):{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Client '${i.clientId}' not found among connected clients.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_send_message`||t===`shadowclaw_send_message`){let e=await c(i.clientId);if(!e)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: No connected client available.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};try{let t=await n.sendCommand(e,`send-message`,{text:i.text,groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error sending message: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_read_state`||t===`shadowclaw_read_state`){let e=await c(i.clientId);try{let t=await n.sendCommand(e,`read-state`,{});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error reading state: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_list_tasks`||t===`shadowclaw_list_tasks`){let e=await c(i.clientId);try{let t=await n.sendCommand(e,`list-tasks`,{groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:JSON.stringify(t.data||t,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error listing tasks: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_manage_backup`||t===`shadowclaw_manage_backup`){let e=i.action||`trigger`,t=await c(i.clientId);try{if(e===`list`){let e=await n.listBackups(t);return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({backups:e},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(e===`delete`){let e=await n.deleteBackup(i.backupId,t);return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify(e,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}let r=await n.sendCommand(t,`trigger-backup`,{groupId:i.groupId});return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!r.success,content:[{type:`text`,text:JSON.stringify(r.data||r,null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error managing backup: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}if(t===`shadowclaw_server_status`||t===`shadowclaw_status`)try{let e=await n.listClients();return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:JSON.stringify({server:`ShadowClaw`,version:o.version,connectedClients:e.length,status:`healthy`},null,2)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error querying server status: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}if(t===`shadowclaw_server_send_notification`||t===`shadowclaw_send_notification`||t===`send_notification`){let e=String(i.body||``).trim();if(!e)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Notification 'body' parameter cannot be empty.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};let t=String(i.title||`ShadowClaw`).trim(),r=typeof i.clientId==`string`&&i.clientId.trim()?i.clientId.trim():void 0;try{let i=await n.broadcastNotification({title:t,body:e,...r?{clientId:r}:{}}),a=i?.sent??0,s=i?.failed??0,c;return c=i?.notFound?`Warning: No push subscriptions found for client '${r}'. Ensure push notifications were registered by this client in ShadowClaw Settings.`:i?.noSubscribers?`Warning: Push notification broadcast completed, but no devices are currently subscribed to push notifications. Ensure push notifications are enabled in ShadowClaw Settings on the client first.`:r?`Push notification sent to client '${r}': ${a} recipient(s) delivered, ${s} failed.`:`Push notification broadcast sent: ${a} recipient(s) delivered, ${s} failed.`,{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!1,content:[{type:`text`,text:c}],_meta:{...i,...r?{targetClientId:r}:{},"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Failed to send push notification: ${e.message}`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}}}}let u=P(t);if((u===`ask_user`||t===`ask_user`)&&s&&s.response)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,content:[{type:`text`,text:String(s.response)}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};m&&v.size===0&&await C();let f=t.startsWith(R),h=t.startsWith(`shadowclaw_client_`),_=v.get(t);if(!_&&f&&(_=v.get(t.slice(17))),!_&&t.startsWith(`shadowclaw_`)&&!h&&(_=v.get(t.slice(11))),f&&_){let e={...i};return delete e.clientId,await w(_,e,l)}r&&p.size===0&&await T();let y=(d.get(u)||d.get(t)||[]).map(e=>e.clientId||e.id).filter(Boolean),b=[];try{b=await n.listClients()}catch{}if(!h&&_){if(g===`none`&&!i.clientId){let e={...i};return delete e.clientId,await w(_,e,l)}if(!r||!Array.isArray(b)||b.length===0){let e={...i};return delete e.clientId,await w(_,e,l)}}let x=``;if(i.clientId)x=await c(i.clientId);else{let e=await c();x=y.includes(e)?e:y.length>0?y[0]:e}if(!x)return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: No connected client available.`}],_meta:{"io.modelcontextprotocol/serverInfo":o}}};if(y.length>0&&!y.includes(x))return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Error: Tool '${t}' is not enabled or available on client '${x}'. (Available on: ${y.join(`, `)})`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}};try{console.error(`[ShadowClaw MCP] Executing '${u}' on client: ${x}`);let e={...i};delete e.clientId;let t=u===`ask_user`?await n.sendCommand(x,`invoke-tool`,{toolName:u,input:e},3e5):await n.sendCommand(x,`invoke-tool`,{toolName:u,input:e}),r=t.data?.result===void 0?t.data:t.data.result,a=typeof r==`string`?r:JSON.stringify(r,null,2),s=t.error||t.data&&t.data.error||`Unknown tool execution error`;return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!t.success,content:[{type:`text`,text:t.success?a||``:a&&a!==`null`&&a!==`{}`?`${a}\n${s}`:`Tool execution error: ${s}`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}}}catch(e){return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,isError:!0,content:[{type:`text`,text:`Tool error: ${e.message}`}],_meta:{clientId:x,"io.modelcontextprotocol/serverInfo":o}}}}}case`tasks/get`:return{jsonrpc:`2.0`,id:l,result:{resultType:`complete`,task:{taskId:e.params?.taskId||`task-1`,status:`completed`},_meta:{"io.modelcontextprotocol/serverInfo":o}}};default:return i?null:{jsonrpc:`2.0`,id:l,error:{code:-32601,message:`Method not found: '${e.method}'`}}}}return{handleMessage:E,getActiveClientId:()=>a,setActiveClientId:e=>{a=e},close:async()=>{if(x)try{let e=await x;typeof e?.core?.closeSqliteDatabase==`function`&&e.core.closeSqliteDatabase()}catch{}}}}async function H(e={}){if((e.mcpTransport||(e.http?`http`:`stdio`))===`http`){let t=parseInt(String(e.port||T.env.MCP_PORT||`8888`),10),n=e.host||`127.0.0.1`,r=V(e);E.createServer(async(e,t)=>{if(e.method!==`POST`||e.url?.split(`?`)[0]!==`/mcp`){t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:`Not found`}));return}let n=``;e.on(`data`,e=>n+=e),e.on(`end`,async()=>{let i;try{i=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,id:null,error:{code:-32700,message:`Parse error`}}));return}try{let n={"mcp-protocol-version":e.headers[`mcp-protocol-version`],"mcp-method":e.headers[`mcp-method`],"mcp-name":e.headers[`mcp-name`]},a=await r.handleMessage(i,n);if(a===null){t.writeHead(202),t.end();return}t.writeHead(200,{"Content-Type":`application/json`,"MCP-Protocol-Version":`2026-07-28`}),t.end(JSON.stringify(a))}catch(e){t.writeHead(500,{"Content-Type":`application/json`}),t.end(JSON.stringify({jsonrpc:`2.0`,id:i?.id??null,error:{code:-32603,message:e?.message||`Internal error`}}))}})}).listen(t,n,()=>{console.error(`[ShadowClaw MCP] HTTP MCP server listening at http://${n}:${t}/mcp (2026-07-28)`)});return}console.log=(...e)=>console.error(...e),console.info=(...e)=>console.error(...e);let t=V(e),n=ee.createInterface({input:T.stdin,output:T.stdout,terminal:!1});n.on(`line`,async e=>{let n=e.trim();if(!n)return;let r;try{r=JSON.parse(n)}catch{T.stdout.write(JSON.stringify({jsonrpc:`2.0`,id:null,error:{code:-32700,message:`Parse error`}})+`
|
|
2
2
|
`);return}try{let e=await t.handleMessage(r);e!==null&&T.stdout.write(JSON.stringify(e)+`
|
|
3
3
|
`)}catch(e){let t={jsonrpc:`2.0`,id:r?.id??null,error:{code:-32603,message:e?.message||`Internal error`}};T.stdout.write(JSON.stringify(t)+`
|
|
4
4
|
`)}}),n.on(`close`,async()=>{await t.close?.()}),console.error(`[ShadowClaw MCP] STDIO MCP server active (2026-07-28)`)}const U=e(import.meta.url),W=new Set;function G(e){return typeof e==`function`?(W.add(e),()=>W.delete(e)):()=>!1}let K=!1;const q=(e,t)=>{K&&_.exit(t),K=!0;for(let t of W)try{t(e)}catch{}_.stderr.write(`\nProcess interrupted (${e}).\n`),_.exit(t)};_.on(`SIGINT`,()=>q(`SIGINT`,130)),_.on(`SIGTERM`,()=>q(`SIGTERM`,143)),_.on(`exit`,()=>{for(let e of W)try{e(`exit`)}catch{}});async function J(){try{let e=await x(h.join(U,`package.json`),`utf8`);return JSON.parse(e).version||`1.0.0`}catch{return`1.0.0`}}async function Y(e){try{return await S(e),!0}catch{return!1}}function X(e){return!!(e.a2a||[`1`,`true`,`yes`].includes((_.env.SHADOWCLAW_A2A||``).toLowerCase().trim()))}function Z(e){let t=_.platform===`darwin`?`open`:_.platform===`win32`?`start`:`xdg-open`;try{v(`${t} ${e}`)}catch{}}const ae=await J(),Q=new w;Q.name(`shadow-claw`).description(`Multi-runtime AI assistant and static site publisher`).version(ae,`-v, --version`,`Output the current version`),Q.commandsGroup(`Development:`),Q.command(`build`).description(`Build the static site bundle for production or staging`).optionsGroup(`Build Mode Options:`).option(`--prod, --production`,`Build in production mode with minification and optimizations`,!1).option(`--prerender-pages <mode>`,`Prerender page mode (all, auto, none)`,`auto`).option(`--copy-all-assets`,`Copy entire assets/ directory into output`,!1).optionsGroup(`Path & Routing Options:`).option(`--origin <url>`,`Canonical origin URL (e.g. https://user.github.io/repo/)`).option(`--base-path <path>`,`URL base path prefix (e.g. /repo/)`).option(`--out-dir <dir>`,`Output directory relative to content root`,`dist/public`).option(`--content-root <dir>`,`Content root directory`,_.cwd()).action(async e=>{try{let t=h.resolve(e.contentRoot||_.cwd()),n=!!(e.prod||e.production||_.env.NODE_ENV===`production`);console.log(`Building ShadowClaw site from ${t}...`),await i({contentRoot:t,toolchainRoot:U,outDir:e.outDir||`dist/public`,isProduction:n,pagesOrigin:e.origin||_.env.PAGES_ORIGIN,basePath:e.basePath||_.env.PAGES_BASE_PATH,prerenderPages:e.prerenderPages,copyAllAssets:e.copyAllAssets})}catch(e){console.error(`Build failed:`,e),_.exit(1)}});async function $(e,t){try{let r=h.resolve(t.contentRoot||_.cwd()),a=parseInt(e||t.port||_.env.PORT||`8888`,10),o=t.host||t.ip||_.env.SHADOWCLAW_DEV_IP||`127.0.0.1`,s=t.outDir||`dist/public`,c=h.resolve(r,s),l=await n({contentRoot:r,cacheDir:t.cacheDir,databaseDir:t.databaseDir,tmp:t.tmp||t.temp,yes:t.yes}),u=l.cacheDir,d=l.databaseDir;console.log(`Preparing ShadowClaw dev build for ${r}...`),await i({contentRoot:r,toolchainRoot:U,outDir:s,isProduction:!1,pagesOrigin:t.origin||_.env.PAGES_ORIGIN,basePath:t.basePath||_.env.PAGES_BASE_PATH,prerenderPages:t.prerenderPages||`auto`,copyAllAssets:t.copyAllAssets});let f=await Y(h.join(U,`dist/server.js`))?h.join(U,`dist/server.js`):h.join(U,`src/server/server.ts`);_.env.SHADOWCLAW_ROOT_PATH=c,_.env.SHADOWCLAW_CACHE_DIR=u,_.env.SHADOWCLAW_DATABASE_DIR=d,_.env.SHADOWCLAW_DEV_IP=o;let{startServer:p}=await import(f),m=new Set((t.corsAllowOrigin||_.env.SHADOWCLAW_CORS_ALLOWED_ORIGINS||`https://xt-ml.github.io`).split(`,`).map(e=>e.trim()).filter(Boolean)),g=!!(t.https||[`1`,`true`,`yes`].includes((_.env.SHADOWCLAW_HTTPS||``).toLowerCase().trim())),v=t.cert||(_.env.SHADOWCLAW_TLS_CERT||_.env.SHADOWCLAW_CERT||``).trim()||void 0,y=t.key||(_.env.SHADOWCLAW_TLS_KEY||_.env.SHADOWCLAW_KEY||``).trim()||void 0,b=h.resolve(r,t.sslDir||_.env.SHADOWCLAW_SSL_DIR||_.env.SHADOWCLAW_TLS_DIR||h.join(u,`tls`));await p({port:a,bindHost:o,corsMode:t.corsMode||`localhost`,allowedOrigins:m,verbose:!!t.verbose,peerjs:!!t.peerjs,a2aEnabled:X(t),rootPath:c,cacheDir:u,databaseDir:d,allowPrivateProxy:!!t.allowPrivateProxy,https:g,certPath:v,keyPath:y,sslDir:b});let x=`${g?`https`:`http`}://${o}:${a}`;t.open&&Z(x)}catch(e){console.error(`Dev server error:`,e),_.exit(1)}}Q.command(`dev [port]`).description(`Build and launch the development server`).optionsGroup(`Server & Network Options:`).option(`-p, --port <port>`,`Port to listen on (default: 8888)`).option(`--host <host>`,`Bind host/IP`,`127.0.0.1`).option(`--ip <host>`,`Bind host/IP (alias)`).option(`--open`,`Automatically open default browser`,!1).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).optionsGroup(`Site & Build Options:`).option(`--content-root <dir>`,`Content root directory`,_.cwd()).option(`--out-dir <dir>`,`Output directory relative to content root`,`dist/public`).optionsGroup(`Security & Proxy Options:`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--allow-private-proxy`,`Allow proxy to reach private/loopback addresses`,!1).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--a2a`,`Enable A2A v1.0 agent card, JSON-RPC, and SSE endpoints`,!1).optionsGroup(`TLS / HTTPS Options:`).option(`--https`,`Enable HTTPS dev server`,!1).option(`--cert <path>`,`Path to existing TLS certificate file`).option(`--key <path>`,`Path to existing TLS private key file`).option(`--ssl-dir <path>`,`Directory for TLS certificate generation/storage`).optionsGroup(`Storage & Database Options:`).option(`--database-dir <dir>`,`Directory where SQLite databases are stored`).option(`--cache-dir <dir>`,`Custom cache directory for databases, tokens, and logs`).option(`--tmp, --temp`,`Store cache and databases in system temporary directory`,!1).option(`-y, --yes`,`Skip interactive cache directory prompt and use default .cache`,!1).action($),Q.command(`run [port]`).description(`Alias for dev: build and launch the development server`).optionsGroup(`Server & Network Options:`).option(`-p, --port <port>`,`Port to listen on (default: 8888)`).option(`--host <host>`,`Bind host/IP`,`127.0.0.1`).option(`--ip <host>`,`Bind host/IP (alias)`).option(`--open`,`Automatically open default browser`,!1).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).optionsGroup(`Site & Build Options:`).option(`--content-root <dir>`,`Content root directory`,_.cwd()).option(`--out-dir <dir>`,`Output directory relative to content root`,`dist/public`).optionsGroup(`Security & Proxy Options:`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--allow-private-proxy`,`Allow proxy to reach private/loopback addresses`,!1).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--a2a`,`Enable A2A v1.0 agent card, JSON-RPC, and SSE endpoints`,!1).optionsGroup(`TLS / HTTPS Options:`).option(`--https`,`Enable HTTPS dev server`,!1).option(`--cert <path>`,`Path to existing TLS certificate file`).option(`--key <path>`,`Path to existing TLS private key file`).option(`--ssl-dir <path>`,`Directory for TLS certificate generation/storage`).optionsGroup(`Storage & Database Options:`).option(`--database-dir <dir>`,`Directory where SQLite databases are stored`).option(`--cache-dir <dir>`,`Custom cache directory for databases, tokens, and logs`).option(`--tmp, --temp`,`Store cache and databases in system temporary directory`,!1).option(`-y, --yes`,`Skip interactive cache directory prompt and use default .cache`,!1).action($),Q.commandsGroup(`Server:`),Q.command(`serve [port]`).description(`Serve static files and start backend services (optional: --peerjs, --a2a)`).optionsGroup(`Server & Network Options:`).option(`-p, --port <port>`,`Port to listen on (default: 8888)`).option(`--host <host>`,`Bind host/IP`,`127.0.0.1`).option(`--no-static`,`Disable static file and UI serving (services-only mode)`).option(`--open`,`Automatically open default browser`,!1).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).optionsGroup(`Site Options:`).option(`--content-root <dir>`,`Content root directory`,_.cwd()).option(`--out-dir <dir>`,`Output directory relative to content root`,`dist/public`).optionsGroup(`Security & Proxy Options:`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--allow-private-proxy`,`Allow proxy to reach private/loopback addresses`,!1).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--a2a`,`Enable A2A v1.0 agent card, JSON-RPC, and SSE endpoints`,!1).optionsGroup(`TLS / HTTPS Options:`).option(`--https`,`Enable HTTPS dev server`,!1).option(`--cert <path>`,`Path to existing TLS certificate file`).option(`--key <path>`,`Path to existing TLS private key file`).option(`--ssl-dir <path>`,`Directory for TLS certificate generation/storage`).optionsGroup(`Storage & Database Options:`).option(`--database-dir <dir>`,`Directory where SQLite databases are stored`).option(`--cache-dir <dir>`,`Custom cache directory for databases, tokens, and logs`).option(`--tmp, --temp`,`Store cache and databases in system temporary directory`,!1).option(`-y, --yes`,`Skip interactive cache directory prompt and use default .cache`,!1).action(async(e,t)=>{try{let r=h.resolve(t.contentRoot||_.cwd()),i=parseInt(e||t.port||_.env.PORT||`8888`,10),a=t.host||t.ip||_.env.SHADOWCLAW_DEV_IP||`127.0.0.1`,o=t.outDir||`dist/public`,s=h.resolve(r,o),c=await n({contentRoot:r,cacheDir:t.cacheDir,databaseDir:t.databaseDir,tmp:t.tmp||t.temp,yes:t.yes}),l=c.cacheDir,u=c.databaseDir,d=t.static!==!1;d&&!await Y(h.join(s,`index.html`))&&(console.error(`Error: No index.html found in ${s}. Run "shadow-claw build" first.`),_.exit(1));let f=await Y(h.join(U,`dist/server.js`))?h.join(U,`dist/server.js`):h.join(U,`src/server/server.ts`);_.env.SHADOWCLAW_ROOT_PATH=s,_.env.SHADOWCLAW_CACHE_DIR=l,_.env.SHADOWCLAW_DATABASE_DIR=u,_.env.SHADOWCLAW_DEV_IP=a;let{startServer:p}=await import(f),m=new Set((t.corsAllowOrigin||_.env.SHADOWCLAW_CORS_ALLOWED_ORIGINS||`https://xt-ml.github.io`).split(`,`).map(e=>e.trim()).filter(Boolean)),g=!!(t.https||[`1`,`true`,`yes`].includes((_.env.SHADOWCLAW_HTTPS||``).toLowerCase().trim())),v=t.cert||(_.env.SHADOWCLAW_TLS_CERT||_.env.SHADOWCLAW_CERT||``).trim()||void 0,y=t.key||(_.env.SHADOWCLAW_TLS_KEY||_.env.SHADOWCLAW_KEY||``).trim()||void 0,b=h.resolve(r,t.sslDir||_.env.SHADOWCLAW_SSL_DIR||_.env.SHADOWCLAW_TLS_DIR||h.join(l,`tls`));await p({port:i,bindHost:a,corsMode:t.corsMode||`localhost`,allowedOrigins:m,verbose:!!t.verbose,peerjs:!!t.peerjs,a2aEnabled:X(t),rootPath:s,cacheDir:l,databaseDir:u,allowPrivateProxy:!!t.allowPrivateProxy,https:g,certPath:v,keyPath:y,sslDir:b,serveStatic:d});let x=`${g?`https`:`http`}://${a}:${i}`;d&&t.open&&Z(x)}catch(e){console.error(`Serve error:`,e),_.exit(1)}});async function oe(e,t){try{let r=h.resolve(t.contentRoot||_.cwd()),i=parseInt(e||t.port||_.env.PORT||`8888`,10),a=t.host||t.ip||_.env.SHADOWCLAW_DEV_IP||`127.0.0.1`,o=await n({contentRoot:r,cacheDir:t.cacheDir,databaseDir:t.databaseDir,tmp:t.tmp||t.temp,yes:t.yes}),s=o.cacheDir,c=o.databaseDir,l=await Y(h.join(U,`dist/server.js`))?h.join(U,`dist/server.js`):h.join(U,`src/server/server.ts`);_.env.SHADOWCLAW_CACHE_DIR=s,_.env.SHADOWCLAW_DATABASE_DIR=c,_.env.SHADOWCLAW_DEV_IP=a,_.env.SHADOWCLAW_SERVE_STATIC=`false`;let{startServer:u}=await import(l),d=new Set((t.corsAllowOrigin||_.env.SHADOWCLAW_CORS_ALLOWED_ORIGINS||`https://xt-ml.github.io`).split(`,`).map(e=>e.trim()).filter(Boolean)),f=!!(t.https||[`1`,`true`,`yes`].includes((_.env.SHADOWCLAW_HTTPS||``).toLowerCase().trim())),p=t.cert||(_.env.SHADOWCLAW_TLS_CERT||_.env.SHADOWCLAW_CERT||``).trim()||void 0,m=t.key||(_.env.SHADOWCLAW_TLS_KEY||_.env.SHADOWCLAW_KEY||``).trim()||void 0,g=h.resolve(r,t.sslDir||_.env.SHADOWCLAW_SSL_DIR||_.env.SHADOWCLAW_TLS_DIR||h.join(s,`tls`));await u({port:i,bindHost:a,corsMode:t.corsMode||`localhost`,allowedOrigins:d,verbose:!!t.verbose,peerjs:!!t.peerjs,a2aEnabled:X(t),rootPath:``,cacheDir:s,databaseDir:c,controlToken:t.controlToken||_.env.SHADOWCLAW_CONTROL_TOKEN||void 0,allowPrivateProxy:!!t.allowPrivateProxy,https:f,certPath:p,keyPath:m,sslDir:g,serveStatic:!1})}catch(e){console.error(`Server error:`,e),_.exit(1)}}Q.command(`server [port]`).aliases([`services`,`api`]).description(`Start backend services (HTTP MCP, control plane, scheduler, and proxy) without serving static files (optional: --peerjs, --a2a; aliases: services, api)`).optionsGroup(`Server & Network Options:`).option(`-p, --port <port>`,`Port to listen on (default: 8888)`).option(`--host <host>`,`Bind host/IP`,`127.0.0.1`).option(`--ip <host>`,`Bind host/IP (alias)`).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).optionsGroup(`Security & Proxy Options:`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--cors-allow-origin <origin>`,`Explicit allowed origins (comma-separated)`).option(`--control-token <token>`,`Secret token for control-plane authentication`).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--a2a`,`Enable A2A v1.0 agent card, JSON-RPC, and SSE endpoints`,!1).option(`--allow-private-proxy`,`Allow proxy to reach private/loopback addresses`,!1).optionsGroup(`TLS / HTTPS Options:`).option(`--https`,`Enable HTTPS server`,!1).option(`--cert <path>`,`Path to existing TLS certificate file`).option(`--key <path>`,`Path to existing TLS private key file`).option(`--ssl-dir <path>`,`Directory for TLS certificate generation/storage`).optionsGroup(`Storage & Database Options:`).option(`--content-root <dir>`,`Content root directory`,_.cwd()).option(`--database-dir <dir>`,`Directory where SQLite databases are stored`).option(`--cache-dir <dir>`,`Custom cache directory for databases, tokens, and logs`).option(`--tmp, --temp`,`Store cache and databases in system temporary directory`,!1).option(`-y, --yes`,`Skip interactive cache directory prompt and use default .cache`,!1).action(oe),Q.command(`mcp`).description(`Start the standalone MCP server only (does not start backend services, PeerJS, or A2A)`).optionsGroup(`MCP Protocol Options:`).option(`--mcp-transport <transport>`,`MCP transport: stdio | http`,`stdio`).option(`--relay-client-tools`,`Discover and relay tools from connected browser clients`,!0).option(`--no-relay-client-tools`,`Disable relaying browser client tools`).optionsGroup(`Target Client Options:`).option(`--client <id>`,`Target client ID (defaults to first active client)`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port or HTTP MCP port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Control plane client transport: http | webrtc`,`http`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--local-tools`,`Expose headless CLI agent tools (read_file, write_file, bash, git_*, etc.)`,!0).option(`--no-local-tools`,`Disable exposing headless CLI agent tools`).option(`--tool-prefix <prefix>`,`Tool prefix style for local tools: local | none | shadowclaw (default: local)`,`local`).optionsGroup(`Workspace & Local Agent Tools Options:`).option(`--workspace <dir>`,`Workspace directory for local tools (default: current working directory)`).option(`--database-dir <dir>`,`Directory where SQLite databases are stored`).option(`--group <groupId>`,`Conversation group ID for local tools (default: server:main)`).option(`--tools <tools>`,`Comma-separated list of local agent tools to expose (default: all headless-safe tools)`).option(`--tools-profile <name>`,`Tools profile to activate for local tools`).option(`--allow-internet, --internet-access`,`Allow full internet access for local Bash and JavaScript tools`).action(async e=>{await H(e)}),Q.commandsGroup(`Control Plane & Client Bridge:`),Q.command(`clients`).description(`List connected / registered browser and Electron clients`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Transport to use: http | webrtc`,`http`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--renew-peer-id`,`Renew WebRTC CLI peer ID before connecting`,!1).option(`--cache-dir <dir>`,`Custom cache directory`).action(async e=>{await O(e)}),Q.command(`send <message>`).description(`Send a message/prompt to a connected client or peer agent`).optionsGroup(`Target Options:`).option(`--client <id>`,`Target client ID (defaults to first available)`).option(`--group <groupId>`,`Target conversation group ID`).option(`-f, --file <path>`,`Attach a local file to send with the message`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Transport to use: http | webrtc`,`http`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--renew-peer-id`,`Renew WebRTC CLI peer ID before sending`,!1).option(`--cache-dir <dir>`,`Custom cache directory`).option(`--timeout <seconds>`,`Timeout in seconds to wait for response`,`120`).option(`--json`,`Output response payload as JSON`,!1).action(async(e,t)=>{await te(e,t)}),Q.command(`send-file <file>`).description(`Transfer a file to a connected peer or client over WebRTC or HTTP`).optionsGroup(`Target Options:`).option(`--client <id>`,`Target client ID (defaults to first available)`).option(`--prompt <prompt>`,`Accompanying prompt or instructions for the receiving agent`).option(`--name <fileName>`,`Override remote file name`).option(`--group <groupId>`,`Target conversation group ID`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Transport to use: http | webrtc`,`webrtc`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--renew-peer-id`,`Renew WebRTC CLI peer ID before sending`,!1).option(`--cache-dir <dir>`,`Custom cache directory`).option(`--timeout <seconds>`,`Transfer and execution timeout in seconds`,`120`).option(`--json`,`Output response payload as JSON`,!1).action(async(e,t)=>{await k(e,t)}),Q.command(`tasks`).description(`List scheduled tasks on a connected client`).optionsGroup(`Target Options:`).option(`--client <id>`,`Target client ID`).option(`--group <groupId>`,`Filter tasks by conversation group ID`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Transport to use: http | webrtc`,`http`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--renew-peer-id`,`Renew WebRTC CLI peer ID before connecting`,!1).option(`--cache-dir <dir>`,`Custom cache directory`).action(async e=>{await j(e)}),Q.command(`backup [action]`).description(`Trigger or manage client workspace backups (trigger | list | delete)`).optionsGroup(`Target Options:`).option(`--client <id>`,`Client ID`).option(`--backup-id <id>`,`Backup ID (for delete)`).option(`--group <groupId>`,`Specific workspace group ID`).optionsGroup(`Control Plane Connection Options:`).option(`--host <host>`,`Control plane host`).option(`--port <port>`,`Control plane port`).option(`--token <token>`,`Control token`).option(`--https`,`Connect to server via HTTPS`,!1).option(`-k, --insecure`,`Allow self-signed TLS certificates`,!0).optionsGroup(`Transport & Peer Options:`).option(`--transport <transport>`,`Transport to use: http | webrtc`,`http`).option(`--peer-id <id>`,`Custom WebRTC CLI peer ID`).option(`--renew-peer-id`,`Renew WebRTC CLI peer ID before connecting`,!1).option(`--cache-dir <dir>`,`Custom cache directory`).action(async(e,t)=>{await A(e||`trigger`,t)}),Q.commandsGroup(`WebRTC:`),Q.command(`webrtc [action] [customId]`).summary(`Manage WebRTC CLI configuration and peer identity (.cache/cli-peer-id)`).description(`Manage WebRTC CLI configuration and peer identity (.cache/cli-peer-id)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,
|
|
1
|
+
import{C as e,D as t,E as n,S as r,T as i,_ as a,a as o,b as s,c,d as l,f as u,g as d,h as f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,s as b,t as x,u as S,v as C,w,y as T}from"../../chunk-BATVgkFY.js";export{x as applySidebarVisibilityToTemplate,g as applyStaticPagesContent,y as buildPagesDsdHost,p as buildShadowClawDsdTemplate,o as buildShadowClawDsdTemplateWithoutPages,_ as collectPageSources,b as collectSkillSources,c as collectToolSources,t as escapeHtml,e as escapeJsonForHtmlScript,m as extractTemplateContent,S as injectPageHeaderDsd,l as injectShadowClawTemplate,s as injectStaticManifestScript,u as inlineCriticalAssets,r as insertBeforeClosingHead,v as isPageFile,h as markNoSeedPrerenderHost,f as minifyDsdTemplateHtml,w as normalizePrerenderPagesOption,d as prerenderDsdShell,a as renderPageHtml,n as sanitizeRenderedHtml,C as sortPagePaths,T as splitFrontmatterWithGrayMatter,i as toPosixPath};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.41.
|
|
4
|
+
"version": "1.41.1",
|
|
5
5
|
"description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.41.
|
|
4
|
+
"version": "1.41.1",
|
|
5
5
|
"description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
package/dist/public/AGENTS.md
CHANGED
|
@@ -51,6 +51,7 @@ ShadowClaw has been significantly deduplicated. Instead of a massive `AGENTS.md`
|
|
|
51
51
|
| Control Plane & Client Bridge | [docs/subsystems/control-plane.md](docs/subsystems/control-plane.md) |
|
|
52
52
|
| Stateless MCP Server | [docs/subsystems/mcp-server.md](docs/subsystems/mcp-server.md) |
|
|
53
53
|
| File Backup Subsystem | [docs/subsystems/backup.md](docs/subsystems/backup.md) |
|
|
54
|
+
| Theming & Stylesheets | [docs/subsystems/theming.md](docs/subsystems/theming.md) |
|
|
54
55
|
| OpenAPI & Discoverability | [docs/subsystems/openapi.md](docs/subsystems/openapi.md) |
|
|
55
56
|
| Server A2A Protocol (HTTP) | [docs/decisions/server-a2a-http-binding.md](docs/decisions/server-a2a-http-binding.md) |
|
|
56
57
|
|
|
@@ -174,7 +175,11 @@ Markdown and HTML preview work should preserve the Settings-backed iframe host a
|
|
|
174
175
|
|
|
175
176
|
### Declarative Configuration, Storage Namespacing & Dynamic Navigation
|
|
176
177
|
|
|
177
|
-
- **Declarative Configuration (`shadow-claw.config.json`):** Template repositories configure metadata, branding, tool defaults (`defaultToolsProfile`, `enabledTools`), custom element allowlists, navigation visibility, and server/cache storage (`cacheDir`, `server.cacheDir`) via `shadow-claw.config.json` (a superset format with backward compatibility for legacy `site-config.json`), which is patched into production artifacts at build time via `src/cli/site-config/apply.ts` and seeded into IndexedDB at runtime via `applySiteConfigDefaults()`.
|
|
178
|
+
- **Declarative Configuration (`shadow-claw.config.json`):** Template repositories configure metadata, branding, tool defaults (`defaultToolsProfile`, `enabledTools`), custom element allowlists, navigation visibility, custom stylesheets (`theme.stylesheet`), and server/cache storage (`cacheDir`, `server.cacheDir`) via `shadow-claw.config.json` (a superset format with backward compatibility for legacy `site-config.json`), which is patched into production artifacts at build time via `src/cli/site-config/apply.ts` and seeded into IndexedDB at runtime via `applySiteConfigDefaults()`.
|
|
179
|
+
- **Custom Stylesheet Injection & Theming:** Custom stylesheets declared under `theme.stylesheet` (e.g. `pages/main/theme.css`) are copied into `dist/public` and injected before `</head>` into `dist/public/index.html` and pre-rendered pretty path files. Tag injection uses `findClosingHeadIndex` (`src/cli/prerender/utils/insert-before-closing-head.ts`) to avoid falsely matching `</head>` literals inside inlined `<script>`, `<style>`, `<template>`, or comment blocks.
|
|
180
|
+
- **Layout Tokens & Shell Visibility Overrides:** Built-in web components reflect CSS Custom Properties. Sites can selectively hide default shell chrome by defining layout override variables in their custom stylesheet: `--shadow-claw-sidebar-footer-display: none;` (hides Settings footer), `--shadow-claw-header-main-toggle-display: none;` (hides header menu toggle), and `--shadow-claw-page-header-display: none;` (hides page header).
|
|
181
|
+
- **Light DOM vs. Shadow DOM Styling Boundaries:** Slotted elements (`[slot="sidebar"]`, `.sidebar-custom-sections`, `[slot="header-actions-logo"]`) live in the Light DOM and must be styled with standard CSS rules in `theme.stylesheet`. Set `.sidebar-custom-sections { max-height: calc(100dvh - 4rem); overflow-y: auto; }` and `html:has(shadow-claw), body:has(shadow-claw) { height: 100dvh; overflow: hidden; }` to ensure scrolling sidebars never produce dual window scrollbars.
|
|
182
|
+
- **Preview Iframe Theme Synchronization:** Sandboxed preview iframes automatically load `theme.stylesheet` via `getIframeThemeStylesheetLink()` and mirror computed CSS custom properties via `getIframeThemeStyleHtml()` (`src/ui/iframe-theme.ts`), preserving consistent colors, typography, and dark/light modes.
|
|
178
183
|
- **Per-Deployment Storage Namespacing:** Use `namespacedStorage` for `localStorage` keys and `getDbName()` / `getOpfsRootName()` for IndexedDB/OPFS namespacing per deployment namespace (`getDeploymentNamespace()`) to prevent state leakage across subpath deployments. Legacy database stores are automatically migrated via `migrateLegacyDatabase.ts`.
|
|
179
184
|
- **Dynamic Sidebar Navigation:** Sidebar navigation items (Pages, Chat, Tasks, Files) support runtime toggling and build-time DSD hiding. Ensure navigation fallback logic (`getDefaultSidebarPage`) resolves to the next visible item when active pages are hidden.
|
|
180
185
|
- **Slotted Sidebar & Custom Navigation:** `<shadow-claw>` exposes named slots for sidebar customization: `sidebar-nav`, `sidebar`, `sidebar-content`, and `sidebar-footer`. `shadow-claw.config.json` supports declarative sidebar configuration via `sidebar.slotHtml`, `sidebar.slotPath`, `sidebar.sections` (with nested items/links), or automatic discovery of `pages/main/sidebar.html` (or `sidebar.html`). Slotted navigation links automatically sync active state and `aria-current="page"` via `syncSlottedSidebarActiveLinks` on route and navigation changes, and automatically collapse the mobile sidebar drawer upon click.
|