shared-context-ai 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +42 -42
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}displayWidth(e){return rr(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,r,s){let a=" ".repeat(2);if(!r)return a+e;let
|
|
4
|
-
`+" ".repeat(t+o)),a+
|
|
5
|
-
${a}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,i=[];return r.forEach(a=>{let
|
|
6
|
-
`)}};function rr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}pt.Help=ut;pt.stripColor=rr});var gt=pe(ft=>{"use strict";var{InvalidArgumentError:Ds}=Ee(),dt=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Ns(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Ds(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?sr(this.name().replace(/^no-/,"")):sr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ht=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function sr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ns(n){let e,t,r=/^-[^-]$/,s=/^--[^-]/,i=n.split(/[ |,]+/).concat("guard");if(r.test(i[0])&&(e=i.shift()),s.test(i[0])&&(t=i.shift()),!e&&r.test(i[0])&&(e=i.shift()),!e&&s.test(i[0])&&(e=t,t=i.shift()),i[0].startsWith("-")){let a=i[0],
|
|
2
|
+
"use strict";var vs=Object.create;var nt=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var $s=Object.getOwnPropertyNames;var Ps=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var L=(n,e)=>()=>(n&&(e=n(n=0)),e);var pe=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),it=(n,e)=>{for(var t in e)nt(n,t,{get:e[t],enumerable:!0})},Is=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $s(e))!Ts.call(n,s)&&s!==t&&nt(n,s,{get:()=>e[s],enumerable:!(r=Es(e,s))||r.enumerable});return n};var N=(n,e,t)=>(t=n!=null?vs(Ps(n)):{},Is(e||!n||!n.__esModule?nt(t,"default",{value:n,enumerable:!0}):t,n));var Ee=pe(at=>{"use strict";var Te=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ot=class extends Te{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};at.CommanderError=Te;at.InvalidArgumentError=ot});var Ie=pe(ct=>{"use strict";var{InvalidArgumentError:Rs}=Ee(),lt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Rs(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function js(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ct.Argument=lt;ct.humanReadableArgName=js});var mt=pe(pt=>{"use strict";var{humanReadableArgName:Fs}=Ie(),ut=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>Fs(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth??80;function i(p,m){return t.formatItem(p,r,m,t)}let a=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(a=a.concat([t.boxWrap(t.styleCommandDescription(c),s),""]));let o=t.visibleArguments(e).map(p=>i(t.styleArgumentTerm(t.argumentTerm(p)),t.styleArgumentDescription(t.argumentDescription(p))));o.length>0&&(a=a.concat([t.styleTitle("Arguments:"),...o,""]));let l=t.visibleOptions(e).map(p=>i(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));if(l.length>0&&(a=a.concat([t.styleTitle("Options:"),...l,""])),t.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(m=>i(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));p.length>0&&(a=a.concat([t.styleTitle("Global Options:"),...p,""]))}let u=t.visibleCommands(e).map(p=>i(t.styleSubcommandTerm(t.subcommandTerm(p)),t.styleSubcommandDescription(t.subcommandDescription(p))));return u.length>0&&(a=a.concat([t.styleTitle("Commands:"),...u,""])),a.join(`
|
|
3
|
+
`)}displayWidth(e){return rr(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,r,s){let a=" ".repeat(2);if(!r)return a+e;let c=e.padEnd(t+e.length-s.displayWidth(e)),o=2,u=(this.helpWidth??80)-t-o-2,p;return u<this.minWidthToWrap||s.preformatted(r)?p=r:p=s.boxWrap(r,u).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(t+o)),a+c+" ".repeat(o)+p.replace(/\n/g,`
|
|
5
|
+
${a}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,i=[];return r.forEach(a=>{let c=a.match(s);if(c===null){i.push("");return}let o=[c.shift()],l=this.displayWidth(o[0]);c.forEach(u=>{let p=this.displayWidth(u);if(l+p<=t){o.push(u),l+=p;return}i.push(o.join(""));let m=u.trimStart();o=[m],l=this.displayWidth(m)}),i.push(o.join(""))}),i.join(`
|
|
6
|
+
`)}};function rr(n){let e=/\x1b\[\d*(;\d*)*m/g;return n.replace(e,"")}pt.Help=ut;pt.stripColor=rr});var gt=pe(ft=>{"use strict";var{InvalidArgumentError:Ds}=Ee(),dt=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Ns(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Ds(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?sr(this.name().replace(/^no-/,"")):sr(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ht=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function sr(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ns(n){let e,t,r=/^-[^-]$/,s=/^--[^-]/,i=n.split(/[ |,]+/).concat("guard");if(r.test(i[0])&&(e=i.shift()),s.test(i[0])&&(t=i.shift()),!e&&r.test(i[0])&&(e=i.shift()),!e&&s.test(i[0])&&(e=t,t=i.shift()),i[0].startsWith("-")){let a=i[0],c=`option creation failed due to '${a}' in option flags '${n}'`;throw/^-[^-][^-]/.test(a)?new Error(`${c}
|
|
7
7
|
- a short flag is a single dash and a single character
|
|
8
8
|
- either use a single dash and a single character (for a short flag)
|
|
9
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(a)?new Error(`${
|
|
10
|
-
- too many short flags`):s.test(a)?new Error(`${
|
|
11
|
-
- too many long flags`):new Error(`${
|
|
12
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}ft.Option=dt;ft.DualOptions=ht});var ir=pe(nr=>{"use strict";function Ms(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function Hs(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(a=>a.slice(2)));let r=[],s=3,i=.4;return e.forEach(a=>{if(a.length<=1)return;let
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):r.test(a)?new Error(`${c}
|
|
10
|
+
- too many short flags`):s.test(a)?new Error(`${c}
|
|
11
|
+
- too many long flags`):new Error(`${c}
|
|
12
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:e,longFlag:t}}ft.Option=dt;ft.DualOptions=ht});var ir=pe(nr=>{"use strict";function Ms(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function Hs(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(a=>a.slice(2)));let r=[],s=3,i=.4;return e.forEach(a=>{if(a.length<=1)return;let c=Ms(n,a),o=Math.max(n.length,a.length);(o-c)/o>i&&(c<s?(s=c,r=[a]):c===s&&r.push(a))}),r.sort((a,c)=>a.localeCompare(c)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
|
|
13
13
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
14
|
-
(Did you mean ${r[0]}?)`:""}nr.suggestSimilar=Hs});var cr=pe(xt=>{"use strict";var Ls=require("events").EventEmitter,yt=require("child_process"),
|
|
14
|
+
(Did you mean ${r[0]}?)`:""}nr.suggestSimilar=Hs});var cr=pe(xt=>{"use strict";var Ls=require("events").EventEmitter,yt=require("child_process"),se=require("path"),Re=require("fs"),C=require("process"),{Argument:Ws,humanReadableArgName:Vs}=Ie(),{CommanderError:bt}=Ee(),{Help:Us,stripColor:Bs}=mt(),{Option:or,DualOptions:qs}=gt(),{suggestSimilar:ar}=ir(),wt=class n extends Ls{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>C.stdout.write(t),writeErr:t=>C.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>C.stdout.isTTY?C.stdout.columns:void 0,getErrHelpWidth:()=>C.stderr.isTTY?C.stderr.columns:void 0,getOutHasColors:()=>St()??(C.stdout.isTTY&&C.stdout.hasColors?.()),getErrHasColors:()=>St()??(C.stderr.isTTY&&C.stderr.hasColors?.()),stripColor:t=>Bs(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let s=t,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,a,c]=e.match(/([^ ]+) *(.*)/),o=this.createCommand(a);return s&&(o.description(s),o._executableHandler=!0),i.isDefault&&(this._defaultCommandName=o._name),o._hidden=!!(i.noHelp||i.hidden),o._executableFile=i.executableFile||null,c&&o.arguments(c),this._registerCommand(o),o.parent=this,o.copyInheritedSettings(this),s?this:o}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Us,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
15
|
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Ws(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),s&&a.arguments(s),i&&a.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
16
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new bt(e,t,r)),
|
|
17
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,a,
|
|
16
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new bt(e,t,r)),C.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new or(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let a=`${s} ${i.message}`;this.error(a,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
17
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,a,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let o=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,o,a):i!==null&&e.variadic&&(i=e._concatValue(i,o)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,c)};return this.on("option:"+t,i=>{let a=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let a=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,a,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof or)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof s=="function")a.default(i).argParser(s);else if(s instanceof RegExp){let c=s;s=(o,l)=>{let u=c.exec(o);return u?u[0]:l},a.default(i).argParser(s)}else a.default(s);return this.addOption(a)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){C.versions?.electron&&(t.from="electron");let s=C.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=C.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":C.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
18
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,r){if(Re.existsSync(e))return;let s=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
|
|
19
19
|
- if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
20
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${s}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,p){let m=
|
|
21
|
+
- ${s}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,p){let m=se.resolve(u,p);if(Re.existsSync(m))return m;if(s.includes(se.extname(p)))return;let f=s.find(y=>Re.existsSync(`${m}${y}`));if(f)return`${m}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let u;try{u=Re.realpathSync(this._scriptPath)}catch{u=this._scriptPath}c=se.resolve(se.dirname(u),c)}if(c){let u=i(c,a);if(!u&&!e._executableFile&&this._scriptPath){let p=se.basename(this._scriptPath,se.extname(this._scriptPath));p!==this._name&&(u=i(c,`${p}-${e._name}`))}a=u||a}r=s.includes(se.extname(a));let o;C.platform!=="win32"?r?(t.unshift(a),t=lr(C.execArgv).concat(t),o=yt.spawn(C.argv[0],t,{stdio:"inherit"})):o=yt.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,c,e._name),t.unshift(a),t=lr(C.execArgv).concat(t),o=yt.spawn(C.execPath,t,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{C.on(p,()=>{o.killed===!1&&o.exitCode===null&&o.kill(p)})});let l=this._exitCallback;o.on("close",u=>{u=u??1,l?l(new bt(u,"commander.executeSubCommandAsync","(close)")):C.exit(u)}),o.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(a,c,e._name);else if(u.code==="EACCES")throw new Error(`'${a}' not executable`);if(!l)C.exit(1);else{let p=new bt(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=o}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let a=s;if(s!==null&&r.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,s,i,c)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((a,c)=>e(r,c,a),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(a=>{s.push({hookedCommand:i,callback:a})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(i,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,i=e.slice();function a(o){return o.length>1&&o[0]==="-"}let c=null;for(;i.length;){let o=i.shift();if(o==="--"){s===r&&s.push(o),s.push(...i);break}if(c&&!a(o)){this.emit(`option:${c.name()}`,o);continue}if(c=null,a(o)){let l=this._findOption(o);if(l){if(l.required){let u=i.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;i.length>0&&!a(i[0])&&(u=i.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(o.length>2&&o[0]==="-"&&o[1]!=="-"){let l=this._findOption(`-${o[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,o.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${o.slice(2)}`));continue}}if(/^--[^=]+=/.test(o)){let l=o.indexOf("="),u=this._findOption(o.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,o.slice(l+1));continue}}if(a(o)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(o)){t.push(o),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&o===this._getHelpCommand().name()){t.push(o),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(o),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(o),i.length>0&&s.push(...i);break}s.push(o)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
22
22
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
23
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
25
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>Vs(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=
|
|
24
|
+
`),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in C.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,C.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qs(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=a=>{let c=a.attributeName(),o=this.getOptionValue(c),l=this.options.find(p=>p.negate&&c===p.attributeName()),u=this.options.find(p=>!p.negate&&c===p.attributeName());return l&&(l.presetArg===void 0&&o===!1||l.presetArg!==void 0&&o===l.presetArg)?l:u||a},s=a=>{let c=r(a),o=c.attributeName();return this.getOptionValueSource(o)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let a=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=ar(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=ar(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
25
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>Vs(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=se.basename(e,se.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let s=t.formatHelp(this,t);return r.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,r,s,i;return t?(r=c=>this._outputConfiguration.writeErr(c),s=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(r=c=>this._outputConfiguration.writeOut(c),s=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(s||(c=this._outputConfiguration.stripColor(c)),r(c)),hasColors:s,helpWidth:i}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getOutputContext(e),s={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach(a=>a.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let i=this.helpInformation({error:r.error});if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(a=>a.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(C.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let a;typeof t=="function"?a=t({error:i.error,command:i.command}):a=t,a&&i.write(`${a}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function lr(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}function St(){if(
|
|
28
|
-
`,"utf-8"),t)try{(0,q.chmodSync)(n,384)}catch{}}function
|
|
29
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Jr=L(()=>{"use strict";qr()});async function Yt(n=An){let{stdout:e}=await n("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Gt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),i=r.lastIndexOf("-"),a=s===-1?void 0:r.slice(0,s),
|
|
30
|
-
`)}var qe=require("fs"),Be=require("path");B();W();var Pt=require("fs"),G=require("path"),de=require("os"),be=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function oe(n){if(n){let r=be.find(i=>i.id===n);if(r)return r;let s=be.find(i=>i.dir===`.${n}`||i.dir===n);return s||null}for(let r of be)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,de.homedir)(),t=[];for(let r of be)(0,Pt.existsSync)((0,G.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Tt(){let n=[],e=(0,de.homedir)();for(let t of be)(t.envVars.some(r=>process.env[r])||(0,Pt.existsSync)((0,G.join)(e,t.dir)))&&n.push(t);return n}function ae(){let n=Tt();return n.length>1?`Multiple AI agents detected (${n.map(e=>e.label).join(", ")}). Use --agent to specify: ${n.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${be.map(e=>e.id).join(", ")})`}function
|
|
31
|
-
`,"utf-8")}function Er(n){n.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let
|
|
32
|
-
`})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,
|
|
33
|
-
`,"utf-8")}function nn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var K=require("fs"),xe=require("path");var Rt={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Me=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[];for(let
|
|
34
|
-
`})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,
|
|
35
|
-
`,"utf-8")}function ln(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var R=require("fs"),
|
|
36
|
-
`,"utf-8")}function un(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var Ve=require("fs"),Le=require("path");var We=class{buildFiles(e){let t=[],r=[],s=[];for(let i of e.files){let
|
|
27
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function lr(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}function St(){if(C.env.NO_COLOR||C.env.FORCE_COLOR==="0"||C.env.FORCE_COLOR==="false")return!1;if(C.env.FORCE_COLOR||C.env.CLICOLOR_FORCE!==void 0)return!0}xt.Command=wt;xt.useColor=St});var dr=pe(U=>{"use strict";var{Argument:ur}=Ie(),{Command:Ct}=cr(),{CommanderError:Js,InvalidArgumentError:pr}=Ee(),{Help:Gs}=mt(),{Option:mr}=gt();U.program=new Ct;U.createCommand=n=>new Ct(n);U.createOption=(n,e)=>new mr(n,e);U.createArgument=(n,e)=>new ur(n,e);U.Command=Ct;U.Option=mr;U.Argument=ur;U.Help=Gs;U.CommanderError=Js;U.InvalidArgumentError=pr;U.InvalidOptionArgumentError=pr});var _r={};it(_r,{addToManifest:()=>J,clearAuth:()=>vt,getAuth:()=>Q,getConfig:()=>ie,getManifest:()=>Z,removeFromManifest:()=>Fe,saveAuth:()=>kt,saveConfig:()=>Ar,saveManifest:()=>Et,updateConfig:()=>zs});function je(){let n=process.env.SC_PROFILE;return n?(0,ye.join)(wr,"profiles",n):wr}function At(){return(0,ye.join)(je(),"auth.json")}function xr(){return(0,ye.join)(je(),"config.json")}function Cr(){return(0,ye.join)(je(),"manifest.json")}function Ys(){(0,q.mkdirSync)(je(),{recursive:!0})}function _t(n,e){try{return(0,q.existsSync)(n)?JSON.parse((0,q.readFileSync)(n,"utf-8")):e}catch{return e}}function Ot(n,e,t=!1){if(Ys(),(0,q.writeFileSync)(n,JSON.stringify(e,null,2)+`
|
|
28
|
+
`,"utf-8"),t)try{(0,q.chmodSync)(n,384)}catch{}}function Q(){return _t(At(),null)}function kt(n){Ot(At(),n,!0)}function vt(){try{(0,q.writeFileSync)(At(),"{}","utf-8")}catch{}}function ie(){return _t(xr(),Ks)}function Ar(n){Ot(xr(),n)}function zs(n){let e=ie();Ar({...e,...n})}function Z(){return _t(Cr(),Xs)}function Et(n){Ot(Cr(),n)}function J(n){let e=Z(),t=e.installations.findIndex(r=>r.resourceId===n.resourceId&&r.agent===n.agent);t>=0?e.installations[t]=n:e.installations.push(n),Et(e)}function Fe(n,e){let t=Z();t.installations=t.installations.filter(r=>!(r.resourceId===n&&(!e||r.agent===e))),Et(t)}var q,ye,Sr,wr,Ks,Xs,B=L(()=>{"use strict";q=require("fs"),ye=require("path"),Sr=require("os"),wr=(0,ye.join)((0,Sr.homedir)(),".config","shared-context");Ks={apiBase:"https://sharedcontext.ai"};Xs={installations:[]}});var Or={};it(Or,{del:()=>$t,get:()=>j,isAuthenticated:()=>$,patch:()=>en,post:()=>I});function Qs(){return ie().apiBase||"https://sharedcontext.ai"}function Zs(){let n={"Content-Type":"application/json"},e=Q();return e?.token&&(n.Authorization=`Bearer ${e.token}`),n}function $(){return!!Q()?.token}async function De(n,e,t,r){let s=`${Qs()}${e}`;try{let i={method:n,headers:Zs(),body:t?JSON.stringify(t):void 0};r&&(i.signal=AbortSignal.timeout(r));let a=await fetch(s,i),c=a.headers.get("content-type")||"";if(!c.includes("application/json"))return a.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${c||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${a.status}`,message:a.statusText}};let o=await a.json();return a.ok?{ok:!0,data:o.data??o}:{ok:!1,error:{code:o?.error?.code||`HTTP_${a.status}`,message:o?.error?.message||o?.message||a.statusText}}}catch(i){return{ok:!1,error:{code:"NETWORK_ERROR",message:i instanceof Error?i.message:"Network request failed"}}}}function j(n){return De("GET",n)}function I(n,e,t){return De("POST",n,e,t)}function en(n,e){return De("PATCH",n,e)}function $t(n,e){return De("DELETE",n,e)}var W=L(()=>{"use strict";B()});function gn(){try{return Dt.default.statSync("/.dockerenv"),!0}catch{return!1}}function yn(){try{return Dt.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Nt(){return Ft===void 0&&(Ft=gn()||yn()),Ft}var Dt,Ft,Ir=L(()=>{"use strict";Dt=N(require("fs"),1)});function he(){return Mt===void 0&&(Mt=bn()||Nt()),Mt}var Rr,Mt,bn,Ht=L(()=>{"use strict";Rr=N(require("fs"),1);Ir();bn=()=>{try{return Rr.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Lt,Fr,Je,jr,le,Wt=L(()=>{"use strict";Lt=N(require("process"),1),Fr=N(require("os"),1),Je=N(require("fs"),1);Ht();jr=()=>{if(Lt.default.platform!=="linux")return!1;if(Fr.default.release().toLowerCase().includes("microsoft"))return!he();try{if(Je.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!he()}catch{}return Je.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Je.default.existsSync("/run/WSL")?!he():!1},le=Lt.default.env.__IS_WSL_TEST__?jr:jr()});var Vt,$e,wn,Sn,Ut,Dr=L(()=>{"use strict";Vt=N(require("process"),1),$e=N(require("fs/promises"),1);Wt();Wt();wn=(()=>{let n="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await $e.default.access(t,$e.constants.F_OK),r=!0}catch{}if(!r)return n;let s=await $e.default.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return i?(e=i.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):n}})(),Sn=async()=>`${await wn()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ut=async()=>le?Sn():`${Vt.default.env.SYSTEMROOT||Vt.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function ce(n,e,t){let r=s=>Object.defineProperty(n,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(n,e,{configurable:!0,enumerable:!0,get(){let s=t();return r(s),s},set(s){r(s)}}),n}var Nr=L(()=>{"use strict"});async function Bt(){if(Hr.default.platform!=="darwin")throw new Error("macOS only");let{stdout:n}=await xn("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(n)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var Mr,Hr,Lr,xn,Wr=L(()=>{"use strict";Mr=require("util"),Hr=N(require("process"),1),Lr=require("child_process"),xn=(0,Mr.promisify)(Lr.execFile)});async function Br(n,{humanReadableOutput:e=!0,signal:t}={}){if(Vr.default.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:i}=await Cn("osascript",["-e",n,r],s);return i.trim()}var Vr,Ur,qt,Cn,qr=L(()=>{"use strict";Vr=N(require("process"),1),Ur=require("util"),qt=require("child_process"),Cn=(0,Ur.promisify)(qt.execFile)});async function Jt(n){return Br(`tell application "Finder" to set app_path to application file id "${n}" as string
|
|
29
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Jr=L(()=>{"use strict";qr()});async function Yt(n=An){let{stdout:e}=await n("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Gt(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,s=r.lastIndexOf("."),i=r.lastIndexOf("-"),a=s===-1?void 0:r.slice(0,s),c=i===-1?void 0:r.slice(0,i);return Ge[r]??Ge[a]??Ge[c]??{name:r,id:r}}var Gr,Yr,An,Ge,so,Gt,Kr=L(()=>{"use strict";Gr=require("util"),Yr=require("child_process"),An=(0,Gr.promisify)(Yr.execFile),Ge={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},so=new Map(Object.entries(Ge)),Gt=class extends Error{}});async function Kt(){if(Ye.default.platform==="darwin"){let n=await Bt();return{name:await Jt(n),id:n}}if(Ye.default.platform==="linux"){let{stdout:n}=await _n("xdg-mime",["query","default","x-scheme-handler/http"]),e=n.trim();return{name:On(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Ye.default.platform==="win32")return Yt();throw new Error("Only macOS, Linux, and Windows are supported")}var zr,Ye,Xr,_n,On,Qr=L(()=>{"use strict";zr=require("util"),Ye=N(require("process"),1),Xr=require("child_process");Wr();Jr();Kr();_n=(0,zr.promisify)(Xr.execFile),On=n=>n.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var is={};it(is,{apps:()=>ue,default:()=>Pn,openApp:()=>$n});async function vn(){let n=await Ut(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Qt.Buffer.from(e,"utf16le").toString("base64"),{stdout:r}=await kn(n,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=r.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[s]?{id:i[s]}:{}}function rs(n){if(typeof n=="string"||Array.isArray(n))return n;let{[es]:e}=n;if(!e)throw new Error(`${es} is not supported`);return e}function ze({[_e]:n},{wsl:e}){if(e&&le)return rs(e);if(!n)throw new Error(`${_e} is not supported`);return rs(n)}var Xt,Qt,Zt,ss,ns,er,Ke,Tn,kn,zt,Zr,_e,es,ts,Pe,En,$n,ue,Pn,os=L(()=>{"use strict";Xt=N(require("process"),1),Qt=require("buffer"),Zt=N(require("path"),1),ss=require("url"),ns=require("util"),er=N(require("child_process"),1),Ke=N(require("fs/promises"),1);Dr();Nr();Qr();Ht();Tn={},kn=(0,ns.promisify)(er.default.execFile),zt=Zt.default.dirname((0,ss.fileURLToPath)(Tn.url)),Zr=Zt.default.join(zt,"xdg-open"),{platform:_e,arch:es}=Xt.default;ts=async(n,e)=>{let t;for(let r of n)try{return await e(r)}catch(s){t=s}throw t},Pe=async n=>{if(n={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...n},Array.isArray(n.app))return ts(n.app,c=>Pe({...n,app:c}));let{name:e,arguments:t=[]}=n.app??{};if(t=[...t],Array.isArray(e))return ts(e,c=>Pe({...n,app:{name:c,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},o={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=le?await vn():await Kt();if(l.id in c){let u=c[l.id];return e==="browserPrivate"&&t.push(o[u]),Pe({...n,app:{name:ue[u],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let r,s=[],i={};if(_e==="darwin")r="open",n.wait&&s.push("--wait-apps"),n.background&&s.push("--background"),n.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(_e==="win32"||le&&!he()&&!e){r=await Ut(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),le||(i.windowsVerbatimArguments=!0);let c=["Start"];n.wait&&c.push("-Wait"),e?(c.push(`"\`"${e}\`""`),n.target&&t.push(n.target)):n.target&&c.push(`"${n.target}"`),t.length>0&&(t=t.map(o=>`"\`"${o}\`""`),c.push("-ArgumentList",t.join(","))),n.target=Qt.Buffer.from(c.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let c=!zt||zt==="/",o=!1;try{await Ke.default.access(Zr,Ke.constants.X_OK),o=!0}catch{}r=Xt.default.versions.electron??(_e==="android"||c||!o)?"xdg-open":Zr}t.length>0&&s.push(...t),n.wait||(i.stdio="ignore",i.detached=!0)}_e==="darwin"&&t.length>0&&s.push("--args",...t),n.target&&s.push(n.target);let a=er.default.spawn(r,s,i);return n.wait?new Promise((c,o)=>{a.once("error",o),a.once("close",l=>{if(!n.allowNonzeroExitCode&&l>0){o(new Error(`Exited with code ${l}`));return}c(a)})}):(a.unref(),a)},En=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a `target`");return Pe({...e,target:n})},$n=(n,e)=>{if(typeof n!="string"&&!Array.isArray(n))throw new TypeError("Expected a valid `name`");let{arguments:t=[]}=e??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return Pe({...e,app:{name:n,arguments:t}})};ue={};ce(ue,"chrome",()=>ze({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));ce(ue,"brave",()=>ze({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));ce(ue,"firefox",()=>ze({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));ce(ue,"edge",()=>ze({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));ce(ue,"browser",()=>"browser");ce(ue,"browserPrivate",()=>"browserPrivate");Pn=En});var hr=N(dr(),1),{program:Kn,createCommand:zn,createArgument:Xn,createOption:Qn,CommanderError:Zn,InvalidArgumentError:ei,InvalidOptionArgumentError:ti,Command:fr,Argument:ri,Option:si,Help:ni}=hr.default;var gr=!1,yr=!1;function br(n,e){gr=n,yr=e}function g(){return gr?!0:yr?!1:!process.stdout.isTTY}function k(n,e){console.log(JSON.stringify({ok:!0,command:n,data:e}))}function S(n,e,t){console.log(JSON.stringify({ok:!1,command:n,errors:[{code:e,message:t}]}))}function d(n){console.log(n)}function w(n){console.error(n)}function me(n,e=2){if(n.length===0)return"";let t=[];for(let r of n)for(let s=0;s<r.length;s++)t[s]=Math.max(t[s]||0,r[s].length);return n.map(r=>r.map((s,i)=>i<r.length-1?s.padEnd(t[i]+e):s).join("")).join(`
|
|
30
|
+
`)}var qe=require("fs"),Be=require("path");B();W();var Pt=require("fs"),G=require("path"),de=require("os"),be=[{id:"claude-code",label:"Claude Code",envVars:["CLAUDE_CODE"],dir:".claude",skillsSubdir:"skills",platform:"claude_code"},{id:"cursor",label:"Cursor",envVars:["CURSOR","CURSOR_TRACE_ID"],dir:".cursor",skillsSubdir:"skills",platform:"custom"},{id:"codex",label:"Codex",envVars:["CODEX","CODEX_CI"],dir:".codex",skillsSubdir:"skills",platform:"codex"},{id:"opencode",label:"OpenCode",envVars:["OPENCODE"],dir:".opencode",skillsSubdir:"skills",platform:"custom"},{id:"gemini-cli",label:"Gemini CLI",envVars:["GEMINI_CLI"],dir:".gemini",skillsSubdir:"skills",platform:"gemini"},{id:"antigravity",label:"Antigravity",envVars:["GEMINI_CLI_IDE_WORKSPACE_PATH","GEMINI_CLI_IDE_PID"],dir:".gemini/antigravity",skillsSubdir:"skills",platform:"gemini"}];function oe(n){if(n){let r=be.find(i=>i.id===n);if(r)return r;let s=be.find(i=>i.dir===`.${n}`||i.dir===n);return s||null}for(let r of be)if(r.envVars.some(s=>process.env[s]))return r;let e=(0,de.homedir)(),t=[];for(let r of be)(0,Pt.existsSync)((0,G.join)(e,r.dir))&&t.push(r);return t.length===1?t[0]:null}function Tt(){let n=[],e=(0,de.homedir)();for(let t of be)(t.envVars.some(r=>process.env[r])||(0,Pt.existsSync)((0,G.join)(e,t.dir)))&&n.push(t);return n}function ae(){let n=Tt();return n.length>1?`Multiple AI agents detected (${n.map(e=>e.label).join(", ")}). Use --agent to specify: ${n.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${be.map(e=>e.id).join(", ")})`}function _(n,e){return e?(0,G.join)(process.cwd(),n.dir,n.skillsSubdir):(0,G.join)((0,de.homedir)(),n.dir,n.skillsSubdir)}function F(n,e){return e?(0,G.join)(process.cwd(),n.dir,"agents"):(0,G.join)((0,de.homedir)(),n.dir,"agents")}function M(n,e){return e?(0,G.join)(process.cwd(),".mcp.json"):n.id==="claude-code"?(0,G.join)((0,de.homedir)(),".claude.json"):n.id==="cursor"?(0,G.join)((0,de.homedir)(),".cursor","mcp.json"):(0,G.join)(process.cwd(),".mcp.json")}var Y=require("fs"),Se=require("path");var te=require("fs"),ee=require("path");W();B();var vr={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function v(n,e){let t=(0,ee.resolve)(n);for(let r of e){let s=(0,ee.resolve)((0,ee.join)(n,r.path));if(!s.startsWith(t+"/")&&s!==t)throw new Error(`Invalid file path: ${r.path}`);(0,te.mkdirSync)((0,ee.dirname)(s),{recursive:!0}),(0,te.writeFileSync)(s,r.content,"utf-8")}}function tn(n){let e=n.resource.slug||n.resource.id,t=vr[n.resource.resourceType]||n.resource.resourceType+"s";return n.resource.storageType==="github"&&n.resource.githubOwner?`${t}/external/${n.resource.githubOwner}/${e}`:n.resource.orgSlug?`${t}/${n.resource.orgSlug}/${e}`:`${t}/${e}`}function kr(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function It(n,e,t){let r=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"))||t.files.find(l=>l.path.endsWith(".json")&&l.path.includes("resources/"));if(!r)throw new Error("MCP package does not contain a config file");let s=JSON.parse(r.content),i=M(n,e),a=t.resource.slug||t.resource.id,c={};if((0,te.existsSync)(i))try{c=JSON.parse((0,te.readFileSync)(i,"utf-8"))}catch{c={}}let o=typeof c.mcpServers=="object"&&c.mcpServers&&!Array.isArray(c.mcpServers)?c.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(o,s.mcpServers):o[a]=s,c.mcpServers=o,(0,te.mkdirSync)((0,ee.dirname)(i),{recursive:!0}),(0,te.writeFileSync)(i,JSON.stringify(c,null,2)+`
|
|
31
|
+
`,"utf-8")}function Er(n){n.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let h=ae();g()?S("install","NO_AGENTS",h):w(h),process.exit(1)}let a=$(),o=await j(`${a?"/api/cli/resource":"/api/public/resource"}/${e}`);o.ok||(g()?S("install",o.error.code,o.error.message):w(`Install failed: ${o.error.message}`),process.exit(1));let l=o.data,u=l.resource.slug||l.resource.id,p=tn(l),m;if(l.resource.resourceType==="agent"){let h=F(i,!!s.project);m=(0,ee.join)(h,...kr(l));try{v(m,l.files)}catch(A){g()?S("install","WRITE_FAILED",`Failed to write files: ${A}`):w(`Failed to write files: ${A}`),process.exit(1)}}else if(l.resource.resourceType==="mcp"){m="";try{It(i,!!s.project,l)}catch(h){g()?S("install","WRITE_FAILED",`Failed to install MCP config: ${h}`):w(`Failed to install MCP config: ${h}`),process.exit(1)}}else{let h=_(i,!!s.project);m=(0,ee.join)(h,...kr(l));try{if(l.resource.resourceType==="collection"){let O=await we(i).install(l,s.project?"project":"user",i);if(m=O.installDir,!g())for(let x of O.warnings)w(`Warning: ${x}`)}else v(m,l.files)}catch(A){g()?S("install","WRITE_FAILED",`Failed to write files: ${A}`):w(`Failed to write files: ${A}`),process.exit(1)}}let f;if(a&&l.resource.latestSha){let h=await I("/api/cli/install",{resourceId:l.resource.id,agentPlatform:i.platform,installedSha:l.resource.latestSha});h.ok||(f=`Could not record install on server: ${h.error.message}`,g()||w(`Warning: ${f}`))}let y={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"},b=l.resource.resourceType==="collection";if(J({resourceId:l.resource.id,slug:u,installPath:p,title:l.resource.title,sha:l.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),...b?{pluginFormat:y[i.id]||"directory",memberCount:l.memberResources?.length}:{}}),l.memberResources&&l.resource.resourceType==="collection")for(let h of l.memberResources){let A=h.slug||h.id,O=vr[h.resourceType]||h.resourceType+"s",x=h.orgSlug||l.resource.orgSlug,X=x?`${O}/${x}/${A}`:`${O}/${A}`;J({resourceId:h.id,slug:A,installPath:X,title:h.title,sha:h.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString(),collectionId:l.resource.id}),a&&h.latestSha&&await I("/api/cli/install",{resourceId:h.id,agentPlatform:i.platform,installedSha:h.latestSha}).catch(()=>{})}if(g())k("install",{installPath:p,title:l.resource.title,path:m||void 0,files:l.files.length,...l.resource.resourceType==="mcp"?{mcpConfigPath:M(i,!!s.project)}:{},...l.memberResources?{memberResources:l.memberResources.map(h=>({title:h.title,resourceType:h.resourceType,slug:h.slug}))}:{},...f&&{warning:f}});else{if(l.resource.resourceType==="mcp"?d(`Installed MCP "${l.resource.title}" to ${M(i,!!s.project)}`):l.memberResources&&l.memberResources.length>0?d(`Installed "${l.resource.title}" (${l.memberResources.length} resources)`):d(`Installed "${l.resource.title}" to ${m}`),l.resource.resourceType!=="mcp"&&!(l.memberResources&&l.memberResources.length>0)&&d(` ${l.files.length} file${l.files.length===1?"":"s"} written`),l.memberResources&&l.memberResources.length>0){let h={};for(let O of l.memberResources){let x=O.resourceType||"other";h[x]||(h[x]=[]),h[x].push(O.title)}let A={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};d("");for(let[O,x]of Object.entries(h)){let X=A[O]||O;d(` ${X}: ${x.join(", ")}`)}}a||(d(""),d("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var Ne=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[];for(let c of e.files){let o=c.path.split("/"),l=o[0];if(l==="agents")s.push({path:c.path.slice(7),content:c.content});else if(l==="mcps"){if(c.path.endsWith(".json"))try{let u=JSON.parse(c.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(i,u.mcpServers);else if(c.path.includes("resources/")){let p=o.indexOf("resources"),m=p>0?o[p-1]:o[1];i[m]=u}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(l==="hooks"){if(c.path.endsWith(".json")){let u=o.length>=3?o[1]:"unknown";try{a.push({name:u,config:JSON.parse(c.content)})}catch{t.push(`Failed to parse hook config: ${c.path}`)}}}else l==="skills"||l==="commands"||l==="files"?r.push({path:c.path.slice(l.length+1),content:c.content}):r.push(c)}if(a.length>0){let c=rn(a);r.push({path:"hooks.json",content:JSON.stringify(c,null,2)+`
|
|
32
|
+
`})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,c=_(r,i),o=nn(e),l=(0,Se.join)(c,...o),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(f=>!f.path.includes("/")),m=s.mainFiles.filter(f=>f.path.includes("/"));p.length>0&&(v(l,p),u+=p.length),m.length>0&&(v(c,m),u+=m.length)}if(s.agentFiles.length>0){let p=F(r,i);v(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&sn(M(r,i),s.mcpEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r,s){let i=[],c=_(r,t==="project"),o=(0,Se.join)(c,e),l=!1;return(0,Y.existsSync)(o)&&((0,Y.rmSync)(o,{recursive:!0,force:!0}),l=!0),l||i.push(`Collection directory not found at ${o}`),{removed:l,warnings:i}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Se.join)(s,e)}};function rn(n){let e=[];for(let{config:t}of n)if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.hooks))e.push(...r.hooks);else for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a of i)e.push({event:s,...typeof a=="object"&&a?a:{}})}return{hooks:e}}function sn(n,e){let t={};if((0,Y.existsSync)(n))try{t=JSON.parse((0,Y.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,Y.mkdirSync)((0,Se.dirname)(n),{recursive:!0}),(0,Y.writeFileSync)(n,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8")}function nn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var K=require("fs"),xe=require("path");var Rt={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},Me=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[];for(let c of e.files){let o=c.path.split("/"),l=o[0];if(l==="agents")s.push({path:c.path.slice(7),content:c.content});else if(l==="mcps"){if(c.path.endsWith(".json"))try{let u=JSON.parse(c.content);if(u.mcpServers&&typeof u.mcpServers=="object")Object.assign(i,u.mcpServers);else if(c.path.includes("resources/")){let p=o.indexOf("resources"),m=p>0?o[p-1]:o[1];i[m]=u}}catch{t.push(`Failed to parse MCP config: ${c.path}`)}}else if(l==="hooks"){if(c.path.endsWith(".json")){let u=o.length>=3?o[1]:"unknown";try{a.push({name:u,config:JSON.parse(c.content)})}catch{t.push(`Failed to parse hook config: ${c.path}`)}}}else l==="skills"||l==="commands"||l==="files"?r.push({path:c.path.slice(l.length+1),content:c.content}):r.push(c)}if(a.length>0){let c=on(a);r.push({path:"hooks/hooks.json",content:JSON.stringify(c,null,2)+`
|
|
34
|
+
`})}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=e.resource.slug||e.resource.id,c=_(r,i),o=ln(e),l=(0,xe.join)(c,...o),u=0;if(s.mainFiles.length>0){let p=s.mainFiles.filter(f=>!f.path.includes("/")),m=s.mainFiles.filter(f=>f.path.includes("/"));p.length>0&&(v(l,p),u+=p.length),m.length>0&&(v(c,m),u+=m.length)}if(s.agentFiles.length>0){let p=F(r,i);v(p,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&an(M(r,i),s.mcpEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),c=(0,xe.join)(a,e),o=!1;return(0,K.existsSync)(c)&&((0,K.rmSync)(c,{recursive:!0,force:!0}),o=!0),o||s.push(`Collection directory not found at ${c}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,xe.join)(s,e)}};function on(n){let e=[];for(let{config:t}of n)if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.hooks)){for(let s of r.hooks)if(s&&typeof s=="object"){let i=s;typeof i.event=="string"&&Rt[i.event]?e.push({...i,event:Rt[i.event]}):e.push(s)}}else for(let[s,i]of Object.entries(r)){let a=Rt[s]||s;if(Array.isArray(i))for(let c of i)e.push({event:a,...typeof c=="object"&&c?c:{}})}}return{hooks:e}}function an(n,e){let t={};if((0,K.existsSync)(n))try{t=JSON.parse((0,K.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,K.mkdirSync)((0,xe.dirname)(n),{recursive:!0}),(0,K.writeFileSync)(n,JSON.stringify(t,null,2)+`
|
|
35
|
+
`,"utf-8")}function ln(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var R=require("fs"),ne=require("path");var He=class{buildFiles(e){let t=[],r=[],s=[],i={},a=[],c=e.resource.slug||e.resource.id;for(let o of e.files){let l=o.path.split("/"),u=l[0];if(u==="agents")s.push({path:o.path.slice(7),content:o.content});else if(u==="mcps"){if(o.path.endsWith(".json"))try{let p=JSON.parse(o.content);if(p.mcpServers&&typeof p.mcpServers=="object")Object.assign(i,p.mcpServers);else if(o.path.includes("resources/")){let m=l.indexOf("resources"),f=m>0?l[m-1]:l[1];i[f]=p}}catch{t.push(`Failed to parse MCP config: ${o.path}`)}}else u==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${o.path})`):u==="skills"||u==="commands"||u==="files"?r.push({path:o.path.slice(u.length+1),content:o.content}):r.push(o)}return{mainFiles:r,agentFiles:s,mcpEntries:i,customFiles:a,warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),c=un(e),o=(0,ne.join)(a,...c),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),l+=u.length),p.length>0&&(v(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),l+=s.agentFiles.length}for(let u of s.customFiles)(0,R.mkdirSync)((0,ne.dirname)(u.absolutePath),{recursive:!0}),(0,R.writeFileSync)(u.absolutePath,u.content,"utf-8"),l++;return Object.keys(s.mcpEntries).length>0&&cn(M(r,i),s.mcpEntries),{installDir:o,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),c=(0,ne.join)(a,e),o=!1;(0,R.existsSync)(c)&&((0,R.rmSync)(c,{recursive:!0,force:!0}),o=!0);let l=(0,ne.join)(homedir(),".cursor","rules");if((0,R.existsSync)(l))try{let u=(0,R.readdirSync)(l);for(let p of u)p.startsWith(`${e}-`)&&p.endsWith(".mdc")&&((0,R.unlinkSync)((0,ne.join)(l,p)),o=!0)}catch{s.push("Could not clean up Cursor rules")}return o||s.push(`Collection not found for Cursor at ${c}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,ne.join)(s,e)}};function cn(n,e){let t={};if((0,R.existsSync)(n))try{t=JSON.parse((0,R.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,R.mkdirSync)((0,ne.dirname)(n),{recursive:!0}),(0,R.writeFileSync)(n,JSON.stringify(t,null,2)+`
|
|
36
|
+
`,"utf-8")}function un(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var Ve=require("fs"),Le=require("path");var We=class{buildFiles(e){let t=[],r=[],s=[];for(let i of e.files){let c=i.path.split("/")[0];c==="agents"?s.push({path:i.path.slice(7),content:i.content}):c==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${i.path})`):c==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${i.path})`):c==="commands"?t.push(`Commands are not supported by Codex (skipped: ${i.path})`):c==="skills"||c==="files"?r.push({path:i.path.slice(c.length+1),content:i.content}):r.push(i)}return{mainFiles:r,agentFiles:s,mcpEntries:{},customFiles:[],warnings:t}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),c=pn(e),o=(0,Le.join)(a,...c),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),l+=u.length),p.length>0&&(v(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),l+=s.agentFiles.length}return{installDir:o,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let s=[],a=_(r,t==="project"),c=(0,Le.join)(a,e),o=!1;return(0,Ve.existsSync)(c)&&((0,Ve.rmSync)(c,{recursive:!0,force:!0}),o=!0),o||s.push(`Collection directory not found at ${c}`),{removed:o,warnings:s}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Le.join)(s,e)}};function pn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}var z=require("fs"),Ce=require("path");var Ue=class{buildFiles(e){let t=[],r=[],s={};for(let i of e.files){let a=i.path.split("/"),c=a[0];if(c==="agents")r.push({path:i.path.slice(7),content:i.content});else if(c==="mcps"){if(i.path.endsWith(".json"))try{let o=JSON.parse(i.content);if(o.mcpServers&&typeof o.mcpServers=="object")Object.assign(s,o.mcpServers);else if(i.path.includes("resources/")){let l=a.indexOf("resources"),u=l>0?a[l-1]:a[1];s[u]=o}}catch{}}else c==="skills"||c==="commands"||c==="hooks"||c==="files"?t.push({path:i.path.slice(c.length+1),content:i.content}):t.push(i)}return{mainFiles:t,agentFiles:r,mcpEntries:s,customFiles:[],warnings:[]}}async install(e,t,r){let s=this.buildFiles(e),i=t==="project",a=_(r,i),c=dn(e),o=(0,Ce.join)(a,...c),l=0;if(s.mainFiles.length>0){let u=s.mainFiles.filter(m=>!m.path.includes("/")),p=s.mainFiles.filter(m=>m.path.includes("/"));u.length>0&&(v(o,u),l+=u.length),p.length>0&&(v(a,p),l+=p.length)}if(s.agentFiles.length>0){let u=F(r,i);v(u,s.agentFiles),l+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&mn(M(r,i),s.mcpEntries),{installDir:o,filesWritten:l,warnings:s.warnings}}async uninstall(e,t,r){let i=_(r,t==="project"),a=(0,Ce.join)(i,e),c=!1;return(0,z.existsSync)(a)&&((0,z.rmSync)(a,{recursive:!0,force:!0}),c=!0),{removed:c,warnings:[]}}describeLocation(e,t,r){let s=_(r,t==="project");return(0,Ce.join)(s,e)}};function mn(n,e){let t={};if((0,z.existsSync)(n))try{t=JSON.parse((0,z.readFileSync)(n,"utf-8"))}catch{t={}}let r=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(r,e),t.mcpServers=r,(0,z.mkdirSync)((0,Ce.dirname)(n),{recursive:!0}),(0,z.writeFileSync)(n,JSON.stringify(t,null,2)+`
|
|
37
37
|
`,"utf-8")}function dn(n){let e=n.resource.slug||n.resource.id;return n.resource.storageType==="github"&&n.resource.githubOwner?["external",n.resource.githubOwner,e]:n.resource.orgSlug?[n.resource.orgSlug,e]:[e]}function we(n){switch(n.id){case"claude-code":return new Ne;case"gemini-cli":case"antigravity":return new Me;case"cursor":return new He;case"codex":return new We;default:return new Ue}}var $r=`---
|
|
38
38
|
title: Resource Manager
|
|
39
39
|
description: Search, install, and manage AI resources from the Shared Context library
|
|
@@ -179,26 +179,26 @@ npx shared-context-ai status # Auth status, detected agents, install
|
|
|
179
179
|
\`\`\`
|
|
180
180
|
|
|
181
181
|
**Error codes:** \`NOT_FOUND\`, \`AUTH_MISSING\`, \`NO_AGENTS\`, \`SKILL_NOT_FOUND\`, \`WRITE_FAILED\`, \`API_ERROR\`, \`UNEXPECTED\`
|
|
182
|
-
`;var Ae="resource-manager",Pr="Resource Manager",jt="collections/shared-context/essentials";function hn(n,e){let t=
|
|
183
|
-
${a}`)}setTimeout(()=>{t.close(),g()||w("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function us(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await cs(e.code):t=await In(),process.exit(t?0:1)})}W();var Rn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ps(n){let e=Rn[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${e}/external/${n.githubOwner}/${n.slug}`:n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function ms(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let r=new URLSearchParams({q:e});t.type&&r.set("type",t.type),t.tag&&r.set("tag",t.tag),t.limit&&r.set("limit",t.limit);let s=$()?`/api/cli/search?${r}`:`/api/public/search?${r}`,i=await j(s);i.ok||(g()?S("search",i.error.code,i.error.message):d(`Search failed: ${i.error.message}`),process.exit(1));let a=i.data.results;if(g()){let o=a.map(
|
|
184
|
-
`);let
|
|
185
|
-
Install a skill: npx shared-context-ai install <installPath>`)})}W();B();function ds(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function hs(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if($()){let e=await j("/api/cli/installed");e.ok||(g()?S("list",e.error.code,e.error.message):d(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(g()){let s=t.map(i=>({...i,installPath:ds(i)}));
|
|
186
|
-
`);let r=t.map(s=>[ds(s),s.title,s.hasUpdate?"(update available)":"(current)"]);d(me(r))}else{let t=
|
|
182
|
+
`;var Ae="resource-manager",Pr="Resource Manager",jt="collections/shared-context/essentials";function hn(n,e){let t=_(n,e),r=(0,Be.join)(t,Ae);return(0,qe.mkdirSync)(r,{recursive:!0}),(0,qe.writeFileSync)((0,Be.join)(r,"SKILL.md"),$r,"utf-8"),(0,Be.join)(r,"SKILL.md")}var fn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Tr(n){n.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").action(async(e,t)=>{let r={...e,...t.optsWithGlobals()};if(r.code){let{post:o}=await Promise.resolve().then(()=>(W(),Or)),{saveAuth:l}=await Promise.resolve().then(()=>(B(),_r)),u=await o("/api/cli/auth",{code:r.code});u.ok||(g()?S("init",u.error.code,u.error.message):w(`Auth failed: ${u.error.message}`),process.exit(1)),l({token:u.data.token,email:u.data.user.email,orgId:u.data.org.id,orgSlug:u.data.org.slug,orgName:u.data.org.name,createdAt:new Date().toISOString()}),g()||d(`Authenticated as ${u.data.user.email}`)}else $()||(g()?(S("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(w("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s=oe(r.agent);if(!s){let o=ae();g()?S("init","NO_AGENTS",o):w(o),process.exit(1)}let i=Q();if(i?.token){let o=(await import("os")).hostname(),l=await I("/api/cli/register-agent",{platform:s.platform,name:`CLI (${o})`});!l.ok&&!g()&&w(`Warning: Could not register agent connection: ${l.error.message}`)}let a=!1,c=[];if(i?.token)try{let o=await j(`/api/cli/resource/${jt}`);if(o.ok){let l=o.data,p=await we(s).install(l,r.project?"project":"user",s),m={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};if(J({resourceId:l.resource.id,slug:l.resource.slug||"essentials",installPath:jt,title:l.resource.title,sha:l.resource.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),pluginFormat:m[s.id]||"directory",memberCount:l.memberResources?.length}),l.resource.latestSha&&await I("/api/cli/install",{resourceId:l.resource.id,agentPlatform:s.platform,installedSha:l.resource.latestSha}).catch(()=>{}),l.memberResources)for(let f of l.memberResources){let y=f.slug||f.id,b=fn[f.resourceType]||f.resourceType+"s",h=f.orgSlug||l.resource.orgSlug,A=h?`${b}/${h}/${y}`:`${b}/${y}`;J({resourceId:f.id,slug:y,installPath:A,title:f.title,sha:f.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString(),collectionId:l.resource.id}),c.push({title:f.title,resourceType:f.resourceType}),f.latestSha&&await I("/api/cli/install",{resourceId:f.id,agentPlatform:s.platform,installedSha:f.latestSha}).catch(()=>{})}if(a=!0,!g()&&p.warnings.length>0)for(let f of p.warnings)w(`Warning: ${f}`)}}catch{}if(!a&&(hn(s,!!r.project),J({resourceId:"resource-manager",slug:Ae,installPath:`skills/${Ae}`,title:Pr,sha:"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()}),i?.token))try{let o=`skills/shared-context/${Ae}`,l=await j(`/api/cli/resource/${o}`);if(l.ok&&l.data.resource){let u=l.data.resource;u.latestSha&&await I("/api/cli/install",{resourceId:u.id,agentPlatform:s.platform,installedSha:u.latestSha}),J({resourceId:u.id,slug:u.slug||Ae,installPath:`skills/shared-context/${u.slug||Ae}`,title:u.title||Pr,sha:u.latestSha||"",scope:r.project?"project":"global",agent:s.id,installedAt:new Date().toISOString()})}}catch{}if(g())k("init",{agent:s.id,collection:a?jt:void 0,resourceManagerOnly:!a,...a?{membersInstalled:c.map(o=>({title:o.title,resourceType:o.resourceType}))}:{},authenticated:$()});else{if(d(""),a){d(`Shared Context Essentials installed for ${s.label} (${c.length} resources)`);let o={};for(let u of c)o[u.resourceType]||(o[u.resourceType]=[]),o[u.resourceType].push(u.title);let l={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};d("");for(let[u,p]of Object.entries(o)){let m=l[u]||u;d(` ${m}: ${p.join(", ")}`)}}else d(`Shared Context initialized for ${s.label}`),d("Resource Manager installed");d(""),d("Quick reference:"),d(' shared-context-ai search "query" Search for resources'),d(" shared-context-ai install <installPath> Install a resource"),d(" shared-context-ai list List installed resources"),d(" shared-context-ai check Check for updates"),d(" shared-context-ai preview <installPath> Preview before installing")}})}var as=require("http"),ls=require("crypto");B();W();B();async function cs(n){let e=await I("/api/cli/auth",{code:n});return e.ok?(kt({token:e.data.token,email:e.data.user.email,orgId:e.data.org.id,orgSlug:e.data.org.slug,orgName:e.data.org.name,createdAt:new Date().toISOString()}),g()?k("login",{email:e.data.user.email,org:e.data.org.slug}):d(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(g()?S("login",e.error.code,e.error.message):w(`Login failed: ${e.error.message}`),!1)}async function In(){let n=(0,ls.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,as.createServer)((r,s)=>{let i=new URL(r.url||"/","http://localhost"),a=i.searchParams.get("code"),c=i.searchParams.get("state");if(!a||c!==n){s.writeHead(400,{"Content-Type":"text/html"}),s.end("<h1>Authentication failed</h1><p>Invalid state. Please try again.</p>"),t.close(),e(!1);return}s.writeHead(200,{"Content-Type":"text/html"}),s.end("<h1>Authentication successful!</h1><p>You can close this tab and return to your terminal.</p>"),t.close(),cs(a).then(e)});t.listen(0,"127.0.0.1",async()=>{let r=t.address();if(!r||typeof r=="string"){t.close(),e(!1);return}let s=r.port,a=`${ie().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${n}`;g()||(d("Opening browser for authentication..."),d(`If the browser doesn't open, visit: ${a}`));try{let c=(await Promise.resolve().then(()=>(os(),is))).default;await c(a)}catch{g()||d(`Could not open browser. Please visit:
|
|
183
|
+
${a}`)}setTimeout(()=>{t.close(),g()||w("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function us(n){n.command("login").description("Authenticate with Shared Context").option("--code <code>","Use an auth code directly (skip browser)").action(async e=>{let t;e.code?t=await cs(e.code):t=await In(),process.exit(t?0:1)})}W();var Rn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ps(n){let e=Rn[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${e}/external/${n.githubOwner}/${n.slug}`:n.orgSlug?`${e}/${n.orgSlug}/${n.slug}`:`${e}/${n.slug}`}function ms(n){n.command("search <query>").description("Search for skills in the library").option("--type <type>","Filter by resource type (skill, command, hook, collection, agent, mcp, file)").option("--tag <tag>","Filter by topic tag").option("--limit <n>","Max results","20").action(async(e,t)=>{let r=new URLSearchParams({q:e});t.type&&r.set("type",t.type),t.tag&&r.set("tag",t.tag),t.limit&&r.set("limit",t.limit);let s=$()?`/api/cli/search?${r}`:`/api/public/search?${r}`,i=await j(s);i.ok||(g()?S("search",i.error.code,i.error.message):d(`Search failed: ${i.error.message}`),process.exit(1));let a=i.data.results;if(g()){let o=a.map(l=>{let u=ps(l);return{installPath:u,installCommand:`npx shared-context-ai install ${u}`,title:l.title,description:l.description,resourceType:l.resourceType,installCount:l.installCount,topicTags:l.topicTags}});k("search",{results:o,count:o.length});return}if(a.length===0){let o=t.type?`${t.type}s`:"results";d(`No ${o} found.`);return}d(`Found ${a.length} result${a.length===1?"":"s"}:
|
|
184
|
+
`);let c=a.map(o=>[ps(o),o.title,`\u2193${o.installCount}`]);d(me(c)),d(`
|
|
185
|
+
Install a skill: npx shared-context-ai install <installPath>`)})}W();B();function ds(n){let e=n.slug||n.resourceId;return n.storageType==="github"&&n.githubOwner?`skills/external/${n.githubOwner}/${e}`:n.orgSlug?`skills/${n.orgSlug}/${e}`:`skills/${e}`}function hs(n){n.command("list").description("List installed skills").alias("ls").action(async()=>{if($()){let e=await j("/api/cli/installed");e.ok||(g()?S("list",e.error.code,e.error.message):d(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(g()){let s=t.map(i=>({...i,installPath:ds(i)}));k("list",{installations:s,count:s.length});return}if(t.length===0){d("No skills installed."),d("Use 'shared-context-ai search' to find skills to install.");return}d(`${t.length} skill${t.length===1?"":"s"} installed:
|
|
186
|
+
`);let r=t.map(s=>[ds(s),s.title,s.hasUpdate?"(update available)":"(current)"]);d(me(r))}else{let t=Z().installations;if(g()){k("list",{installations:t,count:t.length});return}if(t.length===0){d("No skills installed locally.");return}d(`${t.length} skill${t.length===1?"":"s"} installed locally:
|
|
187
187
|
`);let r=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);d(me(r)),d(`
|
|
188
|
-
Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}W();function fs(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=$()?"/api/cli/resource":"/api/public/resource",s=await j(`${r}/${e}/preview`);s.ok||(g()?S("preview",s.error.code,s.error.message):w(`Preview failed: ${s.error.message}`),process.exit(1)),g()?
|
|
188
|
+
Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}W();function fs(n){n.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let r=$()?"/api/cli/resource":"/api/public/resource",s=await j(`${r}/${e}/preview`);s.ok||(g()?S("preview",s.error.code,s.error.message):w(`Preview failed: ${s.error.message}`),process.exit(1)),g()?k("preview",s.data):d(s.data.content)})}W();function gs(n){n.command("check").description("Check for skill updates").action(async()=>{$()||(g()?S("check","AUTH_MISSING","Login required to check for updates."):w("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await j("/api/cli/updates");e.ok||(g()?S("check",e.error.code,e.error.message):w(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:r}=e.data;if(g()){k("check",{updates:t,count:r});return}if(r===0){d("All skills are up to date.");return}d(`${r} update${r===1?"":"s"} available:
|
|
189
189
|
`);let s=t.map(i=>{let a=i.slug||i.resourceId;return[i.storageType==="github"&&i.githubOwner?`skills/external/${i.githubOwner}/${a}`:i.orgSlug?`skills/${i.orgSlug}/${a}`:`skills/${a}`,i.title,`${i.installedSha.slice(0,7)} \u2192 ${i.latestSha.slice(0,7)}`]});d(me(s)),d(`
|
|
190
|
-
Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var tr=require("path");W();B();var jn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ys(n){let e=n.slug||n.resourceId,t=jn[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${t}/external/${n.githubOwner}/${e}`:n.orgSlug?`${t}/${n.orgSlug}/${e}`:`${t}/${e}`}function bs(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();$()||(g()?S("update","AUTH_MISSING","Login required to update resources."):w("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let i=oe(s.agent);if(!i){let
|
|
191
|
-
${o.length} resource${o.length===1?"":"s"} updated.`)})}var T=require("fs"),Oe=require("path");W();B();function ws(n){n.command("uninstall <path>").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let
|
|
192
|
-
`,"utf-8"))}}catch{}}else{let fe=
|
|
193
|
-
`,"utf-8"),m=!0)}}catch{}}else{let
|
|
190
|
+
Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var tr=require("path");W();B();var jn={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ys(n){let e=n.slug||n.resourceId,t=jn[n.resourceType]||n.resourceType+"s";return n.storageType==="github"&&n.githubOwner?`${t}/external/${n.githubOwner}/${e}`:n.orgSlug?`${t}/${n.orgSlug}/${e}`:`${t}/${e}`}function bs(n){n.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,r)=>{let s=r.optsWithGlobals();$()||(g()?S("update","AUTH_MISSING","Login required to update resources."):w("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let i=oe(s.agent);if(!i){let l=ae();g()?S("update","NO_AGENTS",l):w(l),process.exit(1)}let a=await j("/api/cli/updates");a.ok||(g()?S("update",a.error.code,a.error.message):w(`Failed to check updates: ${a.error.message}`),process.exit(1));let c=a.data.updates;if(e&&(c=c.filter(l=>ys(l)===e||l.slug===e||l.resourceId===e),c.length===0)){g()?S("update","SKILL_NOT_FOUND",`No update available for "${e}".`):d(`No update available for "${e}".`);return}if(c.length===0){g()?k("update",{updated:[],count:0}):d("All resources are up to date.");return}let o=[];for(let l of c){let u=ys(l),p=await j(`/api/cli/resource/${u}`);if(!p.ok){g()||w(` Failed to fetch ${u}: ${p.error.message}`);continue}let m=p.data,f=u.split("/").slice(1);if(m.resource.resourceType==="agent"){let y=F(i,!!s.project),b=(0,tr.join)(y,...f);v(b,m.files)}else if(m.resource.resourceType==="mcp")It(i,!!s.project,m);else{let y=_(i,!!s.project),b=(0,tr.join)(y,...f);v(b,m.files)}m.resource.latestSha&&await I("/api/cli/update",{resourceId:m.resource.id,installedSha:m.resource.latestSha}),J({resourceId:m.resource.id,slug:m.resource.slug||m.resource.id,installPath:u,title:m.resource.title,sha:m.resource.latestSha||"",scope:s.project?"project":"global",agent:i.id,installedAt:new Date().toISOString()}),o.push({installPath:u,title:m.resource.title}),g()||d(` Updated ${u}`)}g()?k("update",{updated:o,count:o.length}):o.length>0&&d(`
|
|
191
|
+
${o.length} resource${o.length===1?"":"s"} updated.`)})}var T=require("fs"),Oe=require("path");W();B();function ws(n){n.command("uninstall <path>").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=oe(s.agent);if(!i){let f=ae();g()?S("uninstall","NO_AGENTS",f):w(f),process.exit(1)}let c=Z().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),o=e.split("/"),u=["skills","files","commands","hooks","collections","agents","mcps"].includes(o[0])?o[0]:null,p=u?o.slice(1):o,m=!1;if(u==="collections"){let f=we(i),y=p[p.length-1],b=s.project?"project":"user",h=await f.uninstall(y,b,i,c?.resourceId);if(m=h.removed,!g())for(let A of h.warnings)w(`Warning: ${A}`);if(c){let O=Z().installations.filter(x=>x.collectionId===c.resourceId&&x.agent===i.id);for(let x of O){let X=x.installPath.split("/"),D=X[0],V=X.slice(1);if(D==="agents"){let fe=F(i,!!s.project),re=(0,Oe.join)(fe,...V);(0,T.existsSync)(re)&&(0,T.rmSync)(re,{recursive:!0,force:!0})}else if(D==="mcps"){let fe=V[V.length-1],re=M(i,!!s.project);if((0,T.existsSync)(re))try{let ge=JSON.parse((0,T.readFileSync)(re,"utf-8"));if(typeof ge.mcpServers=="object"&&ge.mcpServers&&!Array.isArray(ge.mcpServers)){let st=ge.mcpServers;fe in st&&(delete st[fe],ge.mcpServers=st,(0,T.writeFileSync)(re,JSON.stringify(ge,null,2)+`
|
|
192
|
+
`,"utf-8"))}}catch{}}else{let fe=_(i,!!s.project),re=(0,Oe.join)(fe,...V);(0,T.existsSync)(re)&&(0,T.rmSync)(re,{recursive:!0,force:!0})}Fe(x.resourceId,i.id)}}}else if(u==="agents"){let f=F(i,!!s.project),y=(0,Oe.join)(f,...p);m=(0,T.existsSync)(y),m&&(0,T.rmSync)(y,{recursive:!0,force:!0})}else if(u==="mcps"){let f=p[p.length-1],y=M(i,!!s.project);if((0,T.existsSync)(y))try{let b=JSON.parse((0,T.readFileSync)(y,"utf-8"));if(typeof b.mcpServers=="object"&&b.mcpServers&&!Array.isArray(b.mcpServers)){let h=b.mcpServers;f in h&&(delete h[f],b.mcpServers=h,(0,T.writeFileSync)(y,JSON.stringify(b,null,2)+`
|
|
193
|
+
`,"utf-8"),m=!0)}}catch{}}else{let f=_(i,!!s.project),y=(0,Oe.join)(f,...p);if(m=(0,T.existsSync)(y),m&&(0,T.rmSync)(y,{recursive:!0,force:!0}),!m&&c?.slug){let b=(0,Oe.join)(f,c.slug);(0,T.existsSync)(b)&&(0,T.rmSync)(b,{recursive:!0,force:!0})}}if($()&&c){let f=await I("/api/cli/uninstall",{resourceId:c.resourceId});!f.ok&&!g()&&w(`Warning: Could not record uninstall on server: ${f.error.message}`)}c&&Fe(c.resourceId,i.id),g()?k("uninstall",{path:e,removed:!0}):d(`Uninstalled "${e}"`)})}B();function Ss(n){n.command("status").description("Show CLI status: auth, agents, installed skill counts").action(async()=>{let e=Q(),t=ie(),r=Z(),s=Tt(),i={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(a=>a.id),installedCount:r.installations.length};if(g()){k("status",i);return}d("Shared Context CLI Status"),d("\u2500".repeat(30)),e?.token?d(` Auth: ${e.email} (${e.orgSlug})`):d(" Auth: Not logged in"),d(` API: ${t.apiBase}`),s.length>0?d(` Agents: ${s.map(a=>a.label).join(", ")}`):d(" Agents: None detected"),d(` Skills: ${r.installations.length} installed`)})}B();W();function xs(n){n.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Q();e.revoke&&$()&&await $t("/api/cli/auth"),vt(),g()?k("logout",{email:t?.email||null}):d("Logged out.")})}var tt=require("fs"),_s=require("path");W();var P=require("fs"),E=require("path"),Cs=require("crypto"),Fn=[{folder:"skills",mainFile:"SKILL.md",resourceType:"skill",canHaveChildren:!0},{folder:"commands",mainFile:null,resourceType:"skill",canHaveChildren:!0},{folder:"hooks",mainFile:"hook.json",resourceType:"hook",canHaveChildren:!1},{folder:"agents",mainFile:null,resourceType:"agent",canHaveChildren:!0},{folder:"mcps",mainFile:"mcp.json",resourceType:"mcp",canHaveChildren:!0},{folder:"collections",mainFile:"README.md",resourceType:"collection",canHaveChildren:!1}],Dn=new Set(["py","sh","js","ts","rb","go","rs","bash","zsh"]),Nn=new Set(["json","yaml","yml","toml","xml","csv","txt","env","ini","cfg"]);function Ze(n){let e={name:"",description:"",body:n};if(!n.startsWith(`---
|
|
194
194
|
`)&&!n.startsWith(`---\r
|
|
195
195
|
`))return e;let t=n.indexOf(`
|
|
196
|
-
---`,3);if(t===-1)return e;let r=n.slice(4,t),s=n.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let i={},a={},
|
|
197
|
-
`),u=null,p=!1;for(let m=0;m<
|
|
198
|
-
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Xe(n){let e=Mn(n);return`sha256:${(0,Cs.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Qe(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function
|
|
196
|
+
---`,3);if(t===-1)return e;let r=n.slice(4,t),s=n.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let i={},a={},c=new Set(["requires","tools"]),o={},l=r.split(`
|
|
197
|
+
`),u=null,p=!1;for(let m=0;m<l.length;m++){let f=l[m];if(u&&/^\s+-\s/.test(f)){let A=f.replace(/^\s+-\s/,"").trim();if(A){let O=ke(A);p?o[u].push(O):a[u].push(O)}continue}u=null,p=!1;let y=f.indexOf(":");if(y===-1)continue;let b=f.slice(0,y).trim(),h=f.slice(y+1).trim();if(!h&&b&&m+1<l.length&&/^\s+-\s/.test(l[m+1])){u=b,c.has(b)?(p=!0,o[b]=[]):(p=!1,a[b]=[]);continue}b==="name"||b==="title"?e.name=ke(h):b==="description"?e.description=ke(h):b==="skill_class"?e.skillClass=ke(h):b==="service"?e.service=ke(h):b&&h&&(i[b]=ke(h))}return o.requires?.length&&(e.requires=o.requires),o.tools?.length&&(e.tools=o.tools),Object.keys(i).length&&(e.fields=i),Object.keys(a).length&&(e.arrayFields=a),e}function ke(n){let e=n.trim();if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")){let t=e.slice(1,-1);return e.startsWith('"')?t.replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.replace(/''/g,"'")}return e}function Mn(n){let{body:e}=Ze(n);return e.replace(/\r\n/g,`
|
|
198
|
+
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Xe(n){let e=Mn(n);return`sha256:${(0,Cs.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Qe(n){return n.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ve(n){try{return(0,P.statSync)(n).isDirectory()}catch{return!1}}function Hn(n){try{return(0,P.readdirSync)(n).filter(e=>!e.startsWith(".")&&ve((0,E.join)(n,e)))}catch{return[]}}function et(n){try{return(0,P.readdirSync)(n).filter(e=>!e.startsWith(".")&&!ve((0,E.join)(n,e)))}catch{return[]}}function Ln(n){let e=[],t=(0,E.join)(n,"scripts");if((0,P.existsSync)(t)&&ve(t))for(let s of et(t)){let i=(0,E.extname)(s).slice(1);Dn.has(i)&&e.push({category:"script",extension:i,filename:s,content:(0,P.readFileSync)((0,E.join)(t,s),"utf-8")})}let r=(0,E.join)(n,"resources");if((0,P.existsSync)(r)&&ve(r))for(let s of et(r)){let i=(0,E.extname)(s).slice(1);Nn.has(i)&&e.push({category:"resource",extension:i,filename:s,content:(0,P.readFileSync)((0,E.join)(r,s),"utf-8")})}return e}function As(n){let e=[],t=[],r,s=(0,E.join)(n,".claude-plugin","plugin.json");if((0,P.existsSync)(s))try{r=JSON.parse((0,P.readFileSync)(s,"utf-8")).name||void 0}catch{}for(let o of Fn){let l=(0,E.join)(n,o.folder);if(!(!(0,P.existsSync)(l)||!ve(l))){if(o.folder==="files"){for(let u of et(l)){if(!u.endsWith(".md"))continue;let p=(0,E.join)(l,u),m=(0,P.readFileSync)(p,"utf-8"),f=Ze(m),y=f.name||(0,E.basename)(u,".md"),b=`files/${(0,E.basename)(u,".md")}`;e.push({importPath:b,resourceType:"file",title:y,description:f.description||null,body:f.body,bodyHash:Xe(m),metadata:{},attachments:[]})}continue}for(let u of Hn(l)){let p=o.mainFile||`${u}.md`,m=(0,E.join)(l,u,p);if(!(0,P.existsSync)(m))continue;let f=(0,P.readFileSync)(m,"utf-8"),y=`${o.folder}/${u}`,b,h,A,O={},x=null;if(o.resourceType==="hook"||o.resourceType==="mcp"){try{let D=JSON.parse(f);b=D.name||Qe(u),h=D.description||null}catch{b=Qe(u),h=null}A=f}else x=Ze(f),b=x.name||Qe(u),h=x.description||null,A=x.body,x.skillClass&&(O.skillClass=x.skillClass),x.service&&(O.service=x.service),x.requires?.length&&(O.requires=x.requires),x.tools?.length&&(O.tools=x.tools),x.fields&&Object.keys(x.fields).length&&(O.fields=x.fields);o.folder==="commands"&&(O.fields||(O.fields={}),O.fields["user-invocable"]="true");let X=o.canHaveChildren?Ln((0,E.join)(l,u)):[];e.push({importPath:y,resourceType:o.resourceType,title:b,description:h,body:A,bodyHash:Xe(f),metadata:O,attachments:X}),o.resourceType==="collection"&&x?.arrayFields?.resources&&t.push({collectionImportPath:y,memberImportPaths:x.arrayFields.resources.map(D=>{let V=D.split("/");return V.length>=3?`${V[0]}/${V[V.length-1]}`:D})})}}}let i=(0,E.join)(n,".mcp.json");if((0,P.existsSync)(i))try{let o=JSON.parse((0,P.readFileSync)(i,"utf-8"));if(o.mcpServers&&typeof o.mcpServers=="object")for(let[l,u]of Object.entries(o.mcpServers)){let p=`mcps/${l}`;if(e.some(y=>y.importPath===p))continue;let m=Qe(l),f=JSON.stringify({name:m,description:`MCP server: ${l}`,mcpServers:{[l]:u}},null,2);e.push({importPath:p,resourceType:"mcp",title:m,description:`MCP server: ${l}`,body:f,bodyHash:Xe(f),metadata:{},attachments:[]})}}catch{}let a=(0,E.join)(n,"files");if((0,P.existsSync)(a)&&ve(a)&&!e.some(o=>o.resourceType==="file"))for(let o of et(a)){if(!o.endsWith(".md"))continue;let l=(0,E.join)(a,o),u=(0,P.readFileSync)(l,"utf-8"),p=Ze(u),m=p.name||(0,E.basename)(o,".md"),f=`files/${(0,E.basename)(o,".md")}`;e.some(y=>y.importPath===f)||e.push({importPath:f,resourceType:"file",title:m,description:p.description||null,body:p.body,bodyHash:Xe(u),metadata:{},attachments:[]})}return{resources:[...e.filter(o=>o.resourceType!=="collection"),...e.filter(o=>o.resourceType==="collection")],collectionMemberships:t,pluginName:r}}function Os(n){n.command("import [path]").description("Import resources from a local directory or GitHub URL").option("--github <url>","Import a single resource from a GitHub URL").option("--resource-type <type>","Resource type (skill|command|hook|agent|mcp) \u2014 for GitHub import disambiguation").option("--visibility <level>","Visibility for created resources","org").option("--dry-run","Preview what would happen without making changes",!1).option("--no-recursive","Do not recursively scan subdirectories").option("--tags <tags>","Comma-separated topic tags").option("--on-conflict <strategy>","Conflict resolution strategy (auto|skip|update|clone|error)","auto").action(async(e,t,r)=>{let s=r.optsWithGlobals(),i=t.github;if(i&&e&&(g()?S("import","INVALID_ARGS","Cannot use --github with a local path"):w("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!i&&!e&&(g()?S("import","INVALID_ARGS","Provide a local path or --github <url>"):w("Error: Provide a local path or --github <url>"),process.exit(1)),$()||(g()?S("import","AUTH_MISSING","Authentication required for import"):w("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),i){t.onConflict&&t.onConflict!=="auto"&&(g()?S("import","INVALID_ARGS","--on-conflict is not supported with --github"):w("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(g()?S("import","INVALID_ARGS","--dry-run is not supported with --github"):w("Error: --dry-run is not supported with --github"),process.exit(1));let y={url:i};t.resourceType&&(y.resourceType=t.resourceType),g()||d(`
|
|
199
199
|
Importing from GitHub: ${i}`);let b=await I("/api/cli/github-import",y);b.ok||(g()?S("import",b.error.code,b.error.message):w(`
|
|
200
|
-
Import failed: ${b.error.message}`),process.exit(1));let
|
|
201
|
-
Discovered ${
|
|
200
|
+
Import failed: ${b.error.message}`),process.exit(1));let h=b.data;if(g()){k("import",h);return}d(""),d(` Source: ${h.source.owner}/${h.source.repo}`),d(` Type: ${h.resourceType}`),d(` Title: ${h.title}`),h.slug&&d(` Slug: ${h.slug}`),d(` URL: ${h.url}`),d(""),d("Import complete: 1 created");return}let a=(0,_s.resolve)(e);(!(0,tt.existsSync)(a)||!(0,tt.statSync)(a).isDirectory())&&(g()?S("import","INVALID_PATH",`Not a directory: ${a}`):w(`Error: Not a directory: ${a}`),process.exit(1));let c=As(a);if(c.resources.length===0){g()?k("import",{resources:[],message:"No resources found"}):d("No resources found in the specified directory.");return}if(!g()){let y=new Map;for(let h of c.resources)y.set(h.resourceType,(y.get(h.resourceType)||0)+1);let b=[...y.entries()].map(([h,A])=>`${A} ${h}${A===1?"":"s"}`).join(", ");d(`
|
|
201
|
+
Discovered ${c.resources.length} resources in ${e}:`),d(` ${b}`),c.pluginName&&d(` Plugin: ${c.pluginName}`)}let o=t.tags?t.tags.split(",").map(y=>y.trim()).filter(Boolean):void 0,l={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:o,resources:c.resources,collectionMemberships:c.collectionMemberships.length>0?c.collectionMemberships:void 0};!g()&&!t.dryRun?d(`
|
|
202
202
|
Executing import...`):g()||d(`
|
|
203
|
-
Dry run \u2014 previewing changes...`);let u=await I("/api/cli/import",
|
|
204
|
-
Import failed: ${u.error.message}`),process.exit(1));let p=u.data;if(g()){
|
|
203
|
+
Dry run \u2014 previewing changes...`);let u=await I("/api/cli/import",l,12e4);u.ok||(g()?S("import",u.error.code,u.error.message):w(`
|
|
204
|
+
Import failed: ${u.error.message}`),process.exit(1));let p=u.data;if(g()){k("import",p);return}let m=[...p.created.map(y=>({...y,action:"created"})),...p.updated.map(y=>({...y,action:"updated"})),...p.installed.map(y=>({...y,action:"installed"})),...p.cloned.map(y=>({...y,action:"cloned"})),...p.skipped.map(y=>({...y,action:"skipped"})),...p.errors.map(y=>({...y,action:"error"}))];if(m.length>0){d("");let y=m.length,b=m.map((h,A)=>{let O=`[${String(A+1).padStart(String(y).length)}/${y}]`,x=(h.resourceType||"").padEnd(10),X=(h.importPath.split("/").pop()||"").padEnd(24),D="";switch(h.action){case"created":D=`\u2713 created${h.slug?` (slug: ${h.slug})`:""}`;break;case"updated":D="\u2713 updated";break;case"installed":{let V=h.versionsBehind;D=`\u2713 installed${V?` (${V} versions behind)`:""}`;break}case"cloned":D=`\u2713 cloned${h.slug?` (slug: ${h.slug})`:""}`;break;case"skipped":D=`\u2713 skipped (${h.reason||"up to date"})`;break;case"error":D=`\u2717 error: ${h.error||"unknown"}`;break}return` ${O} ${x} ${X} ${D}`});for(let h of b)d(h)}if(p.collections.length>0)for(let y of p.collections){let b=y.importPath.split("/").pop()||y.importPath;d(` collection ${b.padEnd(20)} \u2713 ${y.membersLinked} members linked${y.membersFailed>0?`, ${y.membersFailed} failed`:""}`)}d("");let f=[p.created.length>0?`${p.created.length} created`:null,p.installed.length>0?`${p.installed.length} installed`:null,p.cloned.length>0?`${p.cloned.length} cloned`:null,p.updated.length>0?`${p.updated.length} updated`:null,p.skipped.length>0?`${p.skipped.length} skipped`:null,p.errors.length>0?`${p.errors.length} errors`:null].filter(Boolean);t.dryRun?d(`Dry run complete: ${f.join(", ")}`):d(`Import complete: ${f.join(", ")}`),p.errors.length>0&&process.exit(1)})}var ks={AUTH_MISSING:"Run 'shared-context-ai login' to authenticate.",AUTH_EXPIRED:"Run 'shared-context-ai login' to re-authenticate.",SKILL_NOT_FOUND:"Check the skill slug and try again.",ALREADY_INSTALLED:"Use 'shared-context-ai update <slug>' to update instead.",NO_AGENTS:"No AI coding agents detected. Run 'shared-context-ai init --agent <name>' to set up manually.",API_ERROR:"The server returned an error. Try again later.",WRITE_FAILED:"Could not write files to disk. Check permissions."},rt=class extends Error{constructor(t,r){super(r||ks[t]);this.code=t;this.name="CliError"}get recovery(){return ks[this.code]}};var H=new fr;H.name("shared-context-ai").description("CLI for Shared Context - search, install, and manage AI skills").version("0.1.0").option("--json","Output as JSON (default when piped)").option("--human","Output as human-readable text (default in TTY)").option("--agent <name>","Override agent detection").option("--project","Use project-local directory instead of global").hook("preAction",n=>{let e=n.opts();br(!!e.json,!!e.human)});Tr(H);us(H);ms(H);Er(H);hs(H);fs(H);gs(H);bs(H);ws(H);Ss(H);xs(H);Os(H);process.on("uncaughtException",n=>{n instanceof rt?g()?S(process.argv[2]||"unknown",n.code,n.message):(w(`Error: ${n.message}`),w(n.recovery)):g()?S(process.argv[2]||"unknown","UNEXPECTED",n.message||"Unexpected error"):w(`Error: ${n.message||n}`),process.exit(1)});H.parse();
|