shared-context-ai 0.1.31 → 0.1.33
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/discovery.d.ts +42 -0
- package/dist/discovery.js +9 -0
- package/dist/index.js +56 -56
- package/package.json +9 -1
package/dist/index.js
CHANGED
|
@@ -1,51 +1,52 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}displayWidth(e){return
|
|
2
|
+
"use strict";var Ci=Object.create;var wr=Object.defineProperty;var wi=Object.getOwnPropertyDescriptor;var bi=Object.getOwnPropertyNames;var Ii=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var be=(r,e)=>()=>(r&&(e=r(r=0)),e);var X=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Nt=(r,e)=>{for(var t in e)wr(r,t,{get:e[t],enumerable:!0})},_i=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bi(e))!Ai.call(r,s)&&s!==t&&wr(r,s,{get:()=>e[s],enumerable:!(n=wi(e,s))||n.enumerable});return r};var we=(r,e,t)=>(t=r!=null?Ci(Ii(r)):{},_i(e||!r||!r.__esModule?wr(t,"default",{value:r,enumerable:!0}):t,r));var Et=X(Ir=>{"use strict";var $t=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},br=class extends $t{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ir.CommanderError=$t;Ir.InvalidArgumentError=br});var Lt=X(_r=>{"use strict";var{InvalidArgumentError:xi}=Et(),Ar=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,n)=>{if(!this.argChoices.includes(t))throw new xi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function vi(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}_r.Argument=Ar;_r.humanReadableArgName=vi});var Or=X(vr=>{"use strict";var{humanReadableArgName:Oi}=Lt(),xr=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),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.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(n=>Oi(n)).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((n,s)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(s)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(s)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(s)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+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(n=>JSON.stringify(n)).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(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth??80;function o(h,I){return t.formatItem(h,n,I,t)}let c=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(c=c.concat([t.boxWrap(t.styleCommandDescription(a),s),""]));let l=t.visibleArguments(e).map(h=>o(t.styleArgumentTerm(t.argumentTerm(h)),t.styleArgumentDescription(t.argumentDescription(h))));l.length>0&&(c=c.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(h=>o(t.styleOptionTerm(t.optionTerm(h)),t.styleOptionDescription(t.optionDescription(h))));if(u.length>0&&(c=c.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(I=>o(t.styleOptionTerm(t.optionTerm(I)),t.styleOptionDescription(t.optionDescription(I))));h.length>0&&(c=c.concat([t.styleTitle("Global Options:"),...h,""]))}let g=t.visibleCommands(e).map(h=>o(t.styleSubcommandTerm(t.subcommandTerm(h)),t.styleSubcommandDescription(t.subcommandDescription(h))));return g.length>0&&(c=c.concat([t.styleTitle("Commands:"),...g,""])),c.join(`
|
|
3
|
+
`)}displayWidth(e){return Ln(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,n,s){let c=" ".repeat(2);if(!n)return c+e;let a=e.padEnd(t+e.length-s.displayWidth(e)),l=2,g=(this.helpWidth??80)-t-l-2,h;return g<this.minWidthToWrap||s.preformatted(n)?h=n:h=s.boxWrap(n,g).replace(/\n/g,`
|
|
4
4
|
`+" ".repeat(t+l)),c+a+" ".repeat(l)+h.replace(/\n/g,`
|
|
5
5
|
${c}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,o=[];return n.forEach(c=>{let a=c.match(s);if(a===null){o.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(g=>{let h=this.displayWidth(g);if(u+h<=t){l.push(g),u+=h;return}o.push(l.join(""));let I=g.trimStart();l=[I],u=this.displayWidth(I)}),o.push(l.join(""))}),o.join(`
|
|
6
|
-
`)}};function
|
|
6
|
+
`)}};function Ln(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}vr.Help=xr;vr.stripColor=Ln});var Tr=X(Pr=>{"use strict";var{InvalidArgumentError:ki}=Et(),kr=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 n=Ri(e);this.short=n.shortFlag,this.long=n.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,n)=>{if(!this.argChoices.includes(t))throw new ki(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Fn(this.name().replace(/^no-/,"")):Fn(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Rr=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,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function Fn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ri(r){let e,t,n=/^-[^-]$/,s=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),s.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&s.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let c=o[0],a=`option creation failed due to '${c}' in option flags '${r}'`;throw/^-[^-][^-]/.test(c)?new Error(`${a}
|
|
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
9
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(c)?new Error(`${a}
|
|
10
10
|
- too many short flags`):s.test(c)?new Error(`${a}
|
|
11
11
|
- too many long flags`):new Error(`${a}
|
|
12
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}Pr.Option=kr;Pr.DualOptions=Rr});var
|
|
12
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${r}'.`);return{shortFlag:e,longFlag:t}}Pr.Option=kr;Pr.DualOptions=Rr});var Hn=X(Mn=>{"use strict";function Pi(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let o=1;r[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Ti(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(c=>c.slice(2)));let n=[],s=3,o=.4;return e.forEach(c=>{if(c.length<=1)return;let a=Pi(r,c),l=Math.max(r.length,c.length);(l-a)/l>o&&(a<s?(s=a,n=[c]):a===s&&n.push(c))}),n.sort((c,a)=>c.localeCompare(a)),t&&(n=n.map(c=>`--${c}`)),n.length>1?`
|
|
13
13
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
14
|
-
(Did you mean ${n[0]}?)`:""}
|
|
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
|
|
16
|
-
Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Dr(e,t,n)),B.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new
|
|
17
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,c,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,c):o!==null&&e.variadic&&(o=e._concatValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let c=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,c,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let c=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,c,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof
|
|
14
|
+
(Did you mean ${n[0]}?)`:""}Mn.suggestSimilar=Ti});var Wn=X(Lr=>{"use strict";var ji=require("events").EventEmitter,jr=require("child_process"),Me=require("path"),Ft=require("fs"),B=require("process"),{Argument:Di,humanReadableArgName:Ni}=Lt(),{CommanderError:Dr}=Et(),{Help:$i,stripColor:Li}=Or(),{Option:Un,DualOptions:Fi}=Tr(),{suggestSimilar:Bn}=Hn(),Nr=class r extends ji{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=>B.stdout.write(t),writeErr:t=>B.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>$r()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>$r()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:t=>Li(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,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,c,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(c);return s&&(l.description(s),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new r(e)}createHelp(){return Object.assign(new $i,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
|
+
- 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 Di(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),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[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",c=this.createCommand(n);return c.helpOption(!1),s&&c.arguments(s),o&&c.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=c,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 n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
16
|
+
Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Dr(e,t,n)),B.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new Un(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let c=`${s} ${o.message}`;this.error(c,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=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 '${n}'
|
|
17
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,c,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,c):o!==null&&e.variadic&&(o=e._concatValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let c=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,c,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let c=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,c,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof Un)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let c=this.createOption(t,n);if(c.makeOptionMandatory(!!e.mandatory),typeof s=="function")c.default(o).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,u)=>{let g=a.exec(l);return g?g[0]:u},c.default(o).argParser(s)}else c.default(s);return this.addOption(c)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,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,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.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){B.versions?.electron&&(t.from="electron");let s=B.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=B.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":B.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=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",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),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,n){if(Ft.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",o=`'${e}' does not exist
|
|
19
19
|
- if '${n}' 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(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(g,h){let I=Me.resolve(g,h);if(Ft.existsSync(I))return I;if(s.includes(Me.extname(h)))return;let f=s.find(d=>Ft.existsSync(`${I}${d}`));if(f)return`${I}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let c=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let g;try{g=Ft.realpathSync(this._scriptPath)}catch{g=this._scriptPath}a=Me.resolve(Me.dirname(g),a)}if(a){let g=o(a,c);if(!g&&!e._executableFile&&this._scriptPath){let h=Me.basename(this._scriptPath,Me.extname(this._scriptPath));h!==this._name&&(g=o(a,`${h}-${e._name}`))}c=g||c}n=s.includes(Me.extname(c));let l;B.platform!=="win32"?n?(t.unshift(c),t=
|
|
21
|
+
- ${s}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(g,h){let I=Me.resolve(g,h);if(Ft.existsSync(I))return I;if(s.includes(Me.extname(h)))return;let f=s.find(d=>Ft.existsSync(`${I}${d}`));if(f)return`${I}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let c=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let g;try{g=Ft.realpathSync(this._scriptPath)}catch{g=this._scriptPath}a=Me.resolve(Me.dirname(g),a)}if(a){let g=o(a,c);if(!g&&!e._executableFile&&this._scriptPath){let h=Me.basename(this._scriptPath,Me.extname(this._scriptPath));h!==this._name&&(g=o(a,`${h}-${e._name}`))}c=g||c}n=s.includes(Me.extname(c));let l;B.platform!=="win32"?n?(t.unshift(c),t=Vn(B.execArgv).concat(t),l=jr.spawn(B.argv[0],t,{stdio:"inherit"})):l=jr.spawn(c,t,{stdio:"inherit"}):(this._checkForMissingExecutable(c,a,e._name),t.unshift(c),t=Vn(B.execArgv).concat(t),l=jr.spawn(B.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{B.on(h,()=>{l.killed===!1&&l.exitCode===null&&l.kill(h)})});let u=this._exitCallback;l.on("close",g=>{g=g??1,u?u(new Dr(g,"commander.executeSubCommandAsync","(close)")):B.exit(g)}),l.on("error",g=>{if(g.code==="ENOENT")this._checkForMissingExecutable(c,a,e._name);else if(g.code==="EACCES")throw new Error(`'${c}' not executable`);if(!u)B.exit(1);else{let h=new Dr(1,"commander.executeSubCommandAsync","(error)");h.nestedError=g,u(h)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_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=(n,s,o)=>{let c=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;c=this._callParseArg(n,s,o,a)}return c};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((c,a)=>e(n,a,c),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(c=>{s.push({hookedCommand:o,callback:c})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let c;return c=this._chainOrCallHooks(c,"preAction"),c=this._chainOrCall(c,()=>this._actionHandler(this.processedArgs)),this.parent&&(c=this._chainOrCall(c,()=>{this.parent.emit(o,e,t)})),c=this._chainOrCallHooks(c,"postAction"),c}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,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(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function c(l){return l.length>1&&l[0]==="-"}let a=null;for(;o.length;){let l=o.shift();if(l==="--"){s===n&&s.push(l),s.push(...o);break}if(a&&!c(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,c(l)){let u=this._findOption(l);if(u){if(u.required){let g=o.shift();g===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,g)}else if(u.optional){let g=null;o.length>0&&!c(o[0])&&(g=o.shift()),this.emit(`option:${u.name()}`,g)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),o.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),g=this._findOption(l.slice(0,u));if(g&&(g.required||g.optional)){this.emit(`option:${g.name()}`,l.slice(u+1));continue}}if(c(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(l),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(l),o.length>0&&s.push(...o);break}s.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].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 n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in B.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()}`,B.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
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 n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.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(n=>
|
|
24
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in B.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()}`,B.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Fi(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.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 n=c=>{let a=c.attributeName(),l=this.getOptionValue(a),u=this.options.find(h=>h.negate&&a===h.attributeName()),g=this.options.find(h=>!h.negate&&a===h.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:g||c},s=c=>{let a=n(c),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let c=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(c),o=o.parent}while(o&&!o._enablePositionalOptions);t=Bn(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Bn(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);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 n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.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(n=>Ni(n));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=Me.basename(e,Me.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=t.formatHelp(this,t);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let t=!!e.error,n,s,o;return t?(n=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:s,helpWidth:o}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(c=>c.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(c=>c.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(B.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let c;typeof t=="function"?c=t({error:o.error,command:o.command}):c=t,c&&o.write(`${c}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
28
|
-
`)}var
|
|
29
|
-
`,"utf-8"),t)try{(0,xe.chmodSync)(r,384)}catch{}}function Pe(){return wt(Hr(),null)}function It(r){bt(Hr(),r,!0)}function Ur(){try{(0,xe.writeFileSync)(Hr(),"{}","utf-8")}catch{}}function ve(){return wt(ts(),Hi)}function rs(r){bt(ts(),r)}function Mt(r){let e=ve();rs({...e,...r})}function Bi(r){if(r.version&&r.version>=Br)return r;let e=r;if(!r.version||r.version<2){e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))};let t=Vr(),n=wt(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,xe.unlinkSync)(t)}catch{}}return(!e.version||e.version<3)&&(e={...e,version:3}),e}function z(){let r=wt(Mr(),Ui),e=Bi(r);return(!r.version||r.version<Br)&&bt(Mr(),e),e}function Be(r){bt(Mr(),r)}function me(r){let e=z(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Be(e)}function At(r,e){let t=z();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Be(t)}function Ve(){let r=z();delete r.lastSyncAt,Be(r)}function Ht(r){let e=z();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Be(e)}function Vr(){return(0,tt.join)(Ct(),"last-sync.json")}function Wi(){return wt(Vr(),null)}function qi(r){bt(Vr(),r)}function Wr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:Vi,t=z();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var xe,tt,es,Qn,Hi,Br,Ui,Vi,ge=be(()=>{"use strict";xe=require("fs"),tt=require("path"),es=require("os"),Qn=(0,tt.join)((0,es.homedir)(),".config","shared-context");Hi={apiBase:"https://sharedcontext.ai"};Br=3,Ui={version:Br,installations:[]};Vi=720*60*1e3});var os={};Nt(os,{del:()=>_t,fetchRaw:()=>qr,get:()=>J,isAuthenticated:()=>U,patch:()=>Gi,post:()=>F});function ns(){return ve().apiBase||"https://sharedcontext.ai"}function ss(){let r={"Content-Type":"application/json"},e=Pe();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function U(){return!!Pe()?.token}async function Bt(r,e,t,n){let s=`${ns()}${e}`;try{let o={method:r,headers:ss(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let c=await fetch(s,o),a=c.headers.get("content-type")||"";if(!a.includes("application/json"))return c.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${a||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${c.status}`,message:c.statusText}};let l=await c.json();return c.ok?{ok:!0,data:l.data??l}:{ok:!1,error:{code:l?.error?.code||`HTTP_${c.status}`,message:l?.error?.message||l?.message||c.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function J(r){return Bt("GET",r)}function F(r,e,t){return Bt("POST",r,e,t)}function Gi(r,e){return Bt("PATCH",r,e)}function _t(r,e){return Bt("DELETE",r,e)}async function qr(r){let e=`${ns()}${r}`,t=await fetch(e,{headers:ss()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var le=be(()=>{"use strict";ge()});var zr=Y((Vc,is)=>{"use strict";is.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Vt=Y(cs=>{"use strict";var as={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function zi(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(as))cs[r]=zi(as[r])});var ps=Y((qc,ds)=>{"use strict";var Zi=require("fs"),de=require("path"),ls=zr(),Ji=Vt(),Ki=typeof process=="object"&&process.platform==="win32",us=r=>typeof r=="object"&&r!==null,fs=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function re(r){this.sep=de.sep,this.fs=Zi,us(r)&&us(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}ds.exports=re;re.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var c;try{c=e.fs.statSync(s)}catch{e.fs.mkdirSync(s)}if(c&&c.isFile())throw Ji.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};re.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var c=de.dirname(r);s.fs.existsSync(c)||s.makeDir(c);var a;try{a=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),a=s.fs.openSync(r,"w",438)}if(a)try{s.fs.writeSync(a,e,0,e.length,0)}finally{s.fs.closeSync(a)}return s.fs.chmodSync(r,n||438),!0};re.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(c){if(c&&!t)return s(!1);o.fs.stat(r,function(a,l){if(c&&l.isDirectory())return s(!1);var u=de.dirname(r);o.fs.exists(u,function(g){g||o.makeDir(u),o.fs.open(r,"w",438,function(h,I){h?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(f,d){o.fs.write(d,e,0,e.length,0,function(){o.fs.close(d,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):I?o.fs.write(I,e,0,e.length,0,function(){o.fs.close(I,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};re.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(a){let l=de.join(n,a),u=e.fs.statSync(l);(!s||s.test(l))&&c.push(de.normalize(l)+(u.isDirectory()?e.sep:"")),u.isDirectory()&&o&&(c=c.concat(t(l,s,o)))}),c}return t(r,void 0,!0)};re.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let c=o.length;if(!c)return e(null,n);o.forEach(function(a){a=de.join(r,a),t.fs.stat(a,function(l,u){if(l)return e(l);u&&(n.push(de.normalize(a)+(u.isDirectory()?t.sep:"")),u.isDirectory()?t.findFilesAsync(a,function(g,h){if(g)return e(g);n=n.concat(h),--c||e(null,n)}):--c||e(null,n))})})})};re.prototype.getAttributes=function(){};re.prototype.setAttributes=function(){};re.crc32update=function(r,e){return fs[(r^e)&255]^r>>>8};re.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=re.crc32update(t,r[n++]);return~t>>>0};re.methodToString=function(r){switch(r){case ls.STORED:return"STORED ("+r+")";case ls.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};re.canonical=function(r){if(!r)return"";let e=de.posix.normalize("/"+r.split("\\").join("/"));return de.join(".",e)};re.zipnamefix=function(r){if(!r)return"";let e=de.posix.normalize("/"+r.split("\\").join("/"));return de.posix.join(".",e)};re.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};re.sanitize=function(r,e){r=de.resolve(de.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=de.normalize(de.join(r,t.slice(n,s).join(de.sep)));if(o.indexOf(r)===0)return o}return de.normalize(de.join(r,de.basename(e)))};re.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};re.readBigUInt64LE=function(r,e){var t=Buffer.from(r.slice(e,e+8));return t.swap64(),parseInt(`0x${t.toString("hex")}`)};re.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};re.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};re.isWin=Ki;re.crcTable=fs});var gs=Y((Gc,ms)=>{"use strict";var Xi=require("path");ms.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=Xi.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ys=Y((zc,hs)=>{"use strict";hs.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var dt=Y((Zc,ft)=>{"use strict";ft.exports=ps();ft.exports.Constants=zr();ft.exports.Errors=Vt();ft.exports.FileAttr=gs();ft.exports.decoder=ys()});var Es=Y((Jc,Ss)=>{"use strict";var ze=dt(),T=ze.Constants;Ss.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,c=0,a=0,l=0,u=0,g=0,h=0,I=0,f=0,d=0;r|=ze.isWin?2560:768,t|=T.FLG_EFS;let E={extraLen:0},S=i=>Math.max(0,i)>>>0,C=i=>Math.max(0,i)&65535,p=i=>Math.max(0,i)&255;return s=ze.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&T.FLG_EFS)>0},set flags_efs(i){i?t|=T.FLG_EFS:t&=~T.FLG_EFS},get flags_desc(){return(t&T.FLG_DESC)>0},set flags_desc(i){i?t|=T.FLG_DESC:t&=~T.FLG_DESC},get method(){return n},set method(i){switch(i){case T.STORED:this.version=10;case T.DEFLATED:default:this.version=20}n=i},get time(){return ze.fromDOS2Date(this.timeval)},set time(i){this.timeval=ze.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=S(i)},get timeHighByte(){return p(s>>>8)},get crc(){return o},set crc(i){o=S(i)},get compressedSize(){return c},set compressedSize(i){c=S(i)},get size(){return a},set size(i){a=S(i)},get fileNameLength(){return l},set fileNameLength(i){l=i},get extraLength(){return u},set extraLength(i){u=i},get extraLocalLength(){return E.extraLen},set extraLocalLength(i){E.extraLen=i},get commentLength(){return g},set commentLength(i){g=i},get diskNumStart(){return h},set diskNumStart(i){h=S(i)},get inAttr(){return I},set inAttr(i){I=S(i)},get attr(){return f},set attr(i){f=S(i)},get fileAttr(){return(f||0)>>16&4095},get offset(){return d},set offset(i){d=S(i)},get encrypted(){return(t&T.FLG_ENC)===T.FLG_ENC},get centralHeaderSize(){return T.CENHDR+l+u+g},get realDataOffset(){return d+T.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:function(i){var m=i.slice(d,d+T.LOCHDR);if(m.readUInt32LE(0)!==T.LOCSIG)throw ze.Errors.INVALID_LOC();E.version=m.readUInt16LE(T.LOCVER),E.flags=m.readUInt16LE(T.LOCFLG),E.method=m.readUInt16LE(T.LOCHOW),E.time=m.readUInt32LE(T.LOCTIM),E.crc=m.readUInt32LE(T.LOCCRC),E.compressedSize=m.readUInt32LE(T.LOCSIZ),E.size=m.readUInt32LE(T.LOCLEN),E.fnameLen=m.readUInt16LE(T.LOCNAM),E.extraLen=m.readUInt16LE(T.LOCEXT);let y=d+T.LOCHDR+E.fnameLen,x=y+E.extraLen;return i.slice(y,x)},loadFromBinary:function(i){if(i.length!==T.CENHDR||i.readUInt32LE(0)!==T.CENSIG)throw ze.Errors.INVALID_CEN();r=i.readUInt16LE(T.CENVEM),e=i.readUInt16LE(T.CENVER),t=i.readUInt16LE(T.CENFLG),n=i.readUInt16LE(T.CENHOW),s=i.readUInt32LE(T.CENTIM),o=i.readUInt32LE(T.CENCRC),c=i.readUInt32LE(T.CENSIZ),a=i.readUInt32LE(T.CENLEN),l=i.readUInt16LE(T.CENNAM),u=i.readUInt16LE(T.CENEXT),g=i.readUInt16LE(T.CENCOM),h=i.readUInt16LE(T.CENDSK),I=i.readUInt16LE(T.CENATT),f=i.readUInt32LE(T.CENATX),d=i.readUInt32LE(T.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(T.LOCHDR);return i.writeUInt32LE(T.LOCSIG,0),i.writeUInt16LE(e,T.LOCVER),i.writeUInt16LE(t,T.LOCFLG),i.writeUInt16LE(n,T.LOCHOW),i.writeUInt32LE(s,T.LOCTIM),i.writeUInt32LE(o,T.LOCCRC),i.writeUInt32LE(c,T.LOCSIZ),i.writeUInt32LE(a,T.LOCLEN),i.writeUInt16LE(l,T.LOCNAM),i.writeUInt16LE(E.extraLen,T.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(T.CENHDR+l+u+g);return i.writeUInt32LE(T.CENSIG,0),i.writeUInt16LE(r,T.CENVEM),i.writeUInt16LE(e,T.CENVER),i.writeUInt16LE(t,T.CENFLG),i.writeUInt16LE(n,T.CENHOW),i.writeUInt32LE(s,T.CENTIM),i.writeUInt32LE(o,T.CENCRC),i.writeUInt32LE(c,T.CENSIZ),i.writeUInt32LE(a,T.CENLEN),i.writeUInt16LE(l,T.CENNAM),i.writeUInt16LE(u,T.CENEXT),i.writeUInt16LE(g,T.CENCOM),i.writeUInt16LE(h,T.CENDSK),i.writeUInt16LE(I,T.CENATT),i.writeUInt32LE(f,T.CENATX),i.writeUInt32LE(d,T.CENOFF),i},toJSON:function(){let i=function(m){return m+" bytes"};return{made:r,version:e,flags:t,method:ze.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(c),size:i(a),fileNameLength:i(l),extraLength:i(u),commentLength:i(g),diskNumStart:h,inAttr:I,attr:f,offset:d,centralHeaderSize:i(T.CENHDR+l+u+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ws=Y((Kc,Cs)=>{"use strict";var pt=dt(),ee=pt.Constants;Cs.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return ee.ENDHDR+s},loadFromBinary:function(o){if((o.length!==ee.ENDHDR||o.readUInt32LE(0)!==ee.ENDSIG)&&(o.length<ee.ZIP64HDR||o.readUInt32LE(0)!==ee.ZIP64SIG))throw pt.Errors.INVALID_END();o.readUInt32LE(0)===ee.ENDSIG?(r=o.readUInt16LE(ee.ENDSUB),e=o.readUInt16LE(ee.ENDTOT),t=o.readUInt32LE(ee.ENDSIZ),n=o.readUInt32LE(ee.ENDOFF),s=o.readUInt16LE(ee.ENDCOM)):(r=pt.readBigUInt64LE(o,ee.ZIP64SUB),e=pt.readBigUInt64LE(o,ee.ZIP64TOT),t=pt.readBigUInt64LE(o,ee.ZIP64SIZE),n=pt.readBigUInt64LE(o,ee.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(ee.ENDHDR+s);return o.writeUInt32LE(ee.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,ee.ENDSUB),o.writeUInt16LE(e,ee.ENDTOT),o.writeUInt32LE(t,ee.ENDSIZ),o.writeUInt32LE(n,ee.ENDOFF),o.writeUInt16LE(s,ee.ENDCOM),o.fill(" ",ee.ENDHDR),o},toJSON:function(){let o=function(c,a){let l=c.toString(16).toUpperCase();for(;l.length<a;)l="0"+l;return"0x"+l};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Jr=Y(Zr=>{"use strict";Zr.EntryHeader=Es();Zr.MainHeader=ws()});var Is=Y((Yc,bs)=>{"use strict";bs.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],c=0;s.on("data",function(a){o.push(a),c+=a.length}),s.on("end",function(){var a=Buffer.alloc(c),l=0;a.fill(0);for(var u=0;u<o.length;u++){var g=o[u];g.copy(a,l),l+=g.length}n&&n(a)}),s.end(r)}}}});var _s=Y((Qc,As)=>{"use strict";var Yi=+(process.versions?process.versions.node:"").split(".")[0]||0;As.exports=function(r,e){var t=require("zlib");let n=Yi>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),c=[],a=0;o.on("data",function(l){c.push(l),a+=l.length}),o.on("end",function(){var l=Buffer.alloc(a),u=0;l.fill(0);for(var g=0;g<c.length;g++){var h=c[g];h.copy(l,u),u+=h.length}s&&s(l)}),o.end(r)}}}});var Rs=Y((el,ks)=>{"use strict";var{randomFillSync:xs}=require("crypto"),Qi=Vt(),ea=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Os=(r,e)=>Math.imul(r,e)>>>0,vs=(r,e)=>ea[(r^e)&255]^r>>>8,xt=()=>typeof xs=="function"?xs(Buffer.alloc(12)):xt.node();xt.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var Wt={genSalt:xt};function qt(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}qt.prototype.updateKeys=function(r){let e=this.keys;return e[0]=vs(e[0],r),e[1]+=e[0]&255,e[1]=Os(e[1],134775813)+1,e[2]=vs(e[2],e[1]>>>24),r};qt.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return Os(r,r^1)>>8&255};function ta(r){let e=new qt(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function ra(r){let e=new qt(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let c=e.next();n[s++]=o^c,e.updateKeys(o)}return n}}function na(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=ta(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw Qi.WRONG_PASSWORD();return n(r.slice(12))}function sa(r){Buffer.isBuffer(r)&&r.length>=12?Wt.genSalt=function(){return r.slice(0,12)}:r==="node"?Wt.genSalt=xt.node:Wt.genSalt=xt}function oa(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=ra(t),o=Wt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let c=Buffer.alloc(r.length+12);return s(o,c),s(r,c,12)}ks.exports={decrypt:na,encrypt:oa,_salter:sa}});var Ps=Y(Gt=>{"use strict";Gt.Deflater=Is();Gt.Inflater=_s();Gt.ZipCrypto=Rs()});var Xr=Y((rl,Ts)=>{"use strict";var G=dt(),ia=Jr(),ne=G.Constants,Kr=Ps();Ts.exports=function(r,e){var t=new ia.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,c=null,a=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let g=r,h=typeof g.decoder=="object"?g.decoder:G.decoder;u=h.hasOwnProperty("efs")?h.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function f(i){if(t.flags_desc){let m={},y=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(y)==ne.LOCSIG||e.readUInt32LE(y)==ne.CENSIG)throw G.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(y)==ne.EXTSIG)m.crc=e.readUInt32LE(y+ne.EXTCRC),m.compressedSize=e.readUInt32LE(y+ne.EXTSIZ),m.size=e.readUInt32LE(y+ne.EXTLEN);else if(e.readUInt16LE(y+12)===19280)m.crc=e.readUInt32LE(y+ne.EXTCRC-4),m.compressedSize=e.readUInt32LE(y+ne.EXTSIZ-4),m.size=e.readUInt32LE(y+ne.EXTLEN-4);else throw G.Errors.DESCRIPTOR_UNKNOWN();if(m.compressedSize!==t.compressedSize||m.size!==t.size||m.crc!==t.crc)throw G.Errors.DESCRIPTOR_FAULTY();if(G.crc32(i)!==m.crc)return!1}else if(G.crc32(i)!==t.localHeader.crc)return!1;return!0}function d(i,m,y){if(typeof m>"u"&&typeof i=="string"&&(y=i,i=void 0),o)return i&&m&&m(Buffer.alloc(0),G.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var x=I();if(x.length===0)return i&&m&&m(x),x;if(t.encrypted){if(typeof y!="string"&&!Buffer.isBuffer(y))throw G.Errors.INVALID_PASS_PARAM();x=Kr.ZipCrypto.decrypt(x,t,y)}var _=Buffer.alloc(t.size);switch(t.method){case G.Constants.STORED:if(x.copy(_),f(_))return i&&m&&m(_),_;throw i&&m&&m(_,G.Errors.BAD_CRC()),G.Errors.BAD_CRC();case G.Constants.DEFLATED:var b=new Kr.Inflater(x,t.size);if(i)b.inflateAsync(function(v){v.copy(v,0),m&&(f(v)?m(v):m(v,G.Errors.BAD_CRC()))});else{if(b.inflate(_).copy(_,0),!f(_))throw G.Errors.BAD_CRC(`"${h.decode(n)}"`);return _}break;default:throw i&&m&&m(Buffer.alloc(0),G.Errors.UNKNOWN_METHOD()),G.Errors.UNKNOWN_METHOD()}}function E(i,m){if((!c||!c.length)&&Buffer.isBuffer(e))return i&&m&&m(I()),I();if(c.length&&!o){var y;switch(t.method){case G.Constants.STORED:return t.compressedSize=t.size,y=Buffer.alloc(c.length),c.copy(y),i&&m&&m(y),y;default:case G.Constants.DEFLATED:var x=new Kr.Deflater(c);if(i)x.deflateAsync(function(b){y=Buffer.alloc(b.length),t.compressedSize=b.length,b.copy(y),m&&m(y)});else{var _=x.deflate();return t.compressedSize=_.length,_}x=null;break}}else if(i&&m)m(Buffer.alloc(0));else return Buffer.alloc(0)}function S(i,m){return(i.readUInt32LE(m+4)<<4)+i.readUInt32LE(m)}function C(i){try{for(var m=0,y,x,_;m+4<i.length;)y=i.readUInt16LE(m),m+=2,x=i.readUInt16LE(m),m+=2,_=i.slice(m,m+x),m+=x,ne.ID_ZIP64===y&&p(_)}catch{throw G.Errors.EXTRA_FIELD_PARSE_ERROR()}}function p(i){var m,y,x,_;i.length>=ne.EF_ZIP64_SCOMP&&(m=S(i,ne.EF_ZIP64_SUNCOMP),t.size===ne.EF_ZIP64_OR_32&&(t.size=m)),i.length>=ne.EF_ZIP64_RHO&&(y=S(i,ne.EF_ZIP64_SCOMP),t.compressedSize===ne.EF_ZIP64_OR_32&&(t.compressedSize=y)),i.length>=ne.EF_ZIP64_DSN&&(x=S(i,ne.EF_ZIP64_RHO),t.offset===ne.EF_ZIP64_OR_32&&(t.offset=x)),i.length>=ne.EF_ZIP64_DSN+4&&(_=i.readUInt32LE(ne.EF_ZIP64_DSN),t.diskNumStart===ne.EF_ZIP64_OR_16&&(t.diskNumStart=_))}return{get entryName(){return h.decode(n)},get rawEntryName(){return n},set entryName(i){n=G.toBuffer(i,h.encode);var m=n[n.length-1];o=m===47||m===92,t.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return a},set extra(i){a=i,t.extraLength=i.length,C(i)},get comment(){return h.decode(s)},set comment(i){if(s=G.toBuffer(i,h.encode),t.commentLength=s.length,s.length>65535)throw G.Errors.COMMENT_TOO_LONG()},get name(){var i=h.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(i){E(!0,i)},setData:function(i){c=G.toBuffer(i,G.decoder.encode),!o&&c.length?(t.size=c.length,t.method=G.Constants.DEFLATED,t.crc=G.crc32(i),t.changed=!0):t.method=G.Constants.STORED},getData:function(i){return t.changed?c:d(!1,null,i)},getDataAsync:function(i,m){t.changed?i(c):d(!0,i,m)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=a.length;var i=t.centralHeaderToBinary(),m=G.Constants.CENHDR;return n.copy(i,m),m+=n.length,a.copy(i,m),m+=t.extraLength,s.copy(i,m),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=l.length;let m=t.localHeaderToBinary(),y=Buffer.alloc(m.length+n.length+t.extraLocalLength);return m.copy(y,i),i+=m.length,n.copy(y,i),i+=n.length,l.copy(y,i),i+=l.length,y},toJSON:function(){let i=function(m){return"<"+(m&&m.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(c)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ns=Y((nl,Ds)=>{"use strict";var js=Xr(),aa=Jr(),Ce=dt();Ds.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new aa.MainHeader,c=!1,a=null;let l=new Set,u=e,{noSort:g,decoder:h}=u;r?d(u.readEntries):c=!0;function I(){let S=new Set;for(let C of Object.keys(n)){let p=C.split("/");if(p.pop(),!!p.length)for(let i=0;i<p.length;i++){let m=p.slice(0,i+1).join("/")+"/";S.add(m)}}for(let C of S)if(!(C in n)){let p=new js(u);p.entryName=C,p.attr=16,p.temporary=!0,t.push(p),n[p.entryName]=p,l.add(p)}}function f(){if(c=!0,n={},o.diskEntries>(r.length-o.offset)/Ce.Constants.CENHDR)throw Ce.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var S=o.offset,C=0;C<t.length;C++){var p=S,i=new js(u,r);i.header=r.slice(p,p+=Ce.Constants.CENHDR),i.entryName=r.slice(p,p+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(p,p+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(p,p+i.header.commentLength)),S+=i.header.centralHeaderSize,t[C]=i,n[i.entryName]=i}l.clear(),I()}function d(S){var C=r.length-Ce.Constants.ENDHDR,p=Math.max(0,C-65535),i=p,m=r.length,y=-1,x=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(p=0),C;C>=i;C--)if(r[C]===80){if(r.readUInt32LE(C)===Ce.Constants.ENDSIG){y=C,x=C,m=C+Ce.Constants.ENDHDR,i=C-Ce.Constants.END64HDR;continue}if(r.readUInt32LE(C)===Ce.Constants.END64SIG){i=p;continue}if(r.readUInt32LE(C)===Ce.Constants.ZIP64SIG){y=C,m=C+Ce.readBigUInt64LE(r,C+Ce.Constants.ZIP64SIZE)+Ce.Constants.ZIP64LEAD;break}}if(y==-1)throw Ce.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(y,m)),o.commentLength&&(s=r.slice(x+Ce.Constants.ENDHDR)),S&&f()}function E(){t.length>1&&!g&&t.sort((S,C)=>S.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return c||f(),t.filter(S=>!l.has(S))},get comment(){return h.decode(s)},set comment(S){s=Ce.toBuffer(S,h.encode),o.commentLength=s.length},getEntryCount:function(){return c?t.length:o.diskEntries},forEach:function(S){this.entries.forEach(S)},getEntry:function(S){return c||f(),n[S]||null},setEntry:function(S){c||f(),t.push(S),n[S.entryName]=S,o.totalEntries=t.length},deleteFile:function(S,C=!0){c||f();let p=n[S];this.getEntryChildren(p,C).map(m=>m.entryName).forEach(this.deleteEntry)},deleteEntry:function(S){c||f();let C=n[S],p=t.indexOf(C);p>=0&&(t.splice(p,1),delete n[S],o.totalEntries=t.length)},getEntryChildren:function(S,C=!0){if(c||f(),typeof S=="object")if(S.isDirectory&&C){let p=[],i=S.entryName;for(let m of t)m.entryName.startsWith(i)&&p.push(m);return p}else return[S];return[]},getChildCount:function(S){if(S&&S.isDirectory){let C=this.getEntryChildren(S);return C.includes(S)?C.length-1:C.length}return 0},compressToBuffer:function(){c||f(),E();let S=[],C=[],p=0,i=0;o.size=0,o.offset=0;let m=0;for(let _ of this.entries){let b=_.getCompressedData();_.header.offset=i;let v=_.packLocalHeader(),k=v.length+b.length;i+=k,S.push(v),S.push(b);let P=_.packCentralHeader();C.push(P),o.size+=P.length,p+=k+P.length,m++}p+=o.mainHeaderSize,o.offset=i,o.totalEntries=m,i=0;let y=Buffer.alloc(p);for(let _ of S)_.copy(y,i),i+=_.length;for(let _ of C)_.copy(y,i),i+=_.length;let x=o.toBinary();return s&&s.copy(x,Ce.Constants.ENDHDR),x.copy(y,i),r=y,c=!1,y},toAsyncBuffer:function(S,C,p,i){try{c||f(),E();let m=[],y=[],x=0,_=0,b=0;o.size=0,o.offset=0;let v=function(k){if(k.length>0){let P=k.shift(),j=P.entryName+P.extra.toString();p&&p(j),P.getCompressedDataAsync(function($){i&&i(j),P.header.offset=_;let K=P.packLocalHeader(),ae=K.length+$.length;_+=ae,m.push(K),m.push($);let O=P.packCentralHeader();y.push(O),o.size+=O.length,x+=ae+O.length,b++,v(k)})}else{x+=o.mainHeaderSize,o.offset=_,o.totalEntries=b,_=0;let P=Buffer.alloc(x);m.forEach(function($){$.copy(P,_),_+=$.length}),y.forEach(function($){$.copy(P,_),_+=$.length});let j=o.toBinary();s&&s.copy(j,Ce.Constants.ENDHDR),j.copy(P,_),r=P,c=!1,S(P)}};v(Array.from(this.entries))}catch(m){C(m)}}}}});var Fs=Y((sl,Ls)=>{"use strict";var te=dt(),se=require("path"),ca=Xr(),la=Ns(),rt=(...r)=>te.findLast(r,e=>typeof e=="boolean"),$s=(...r)=>te.findLast(r,e=>typeof e=="string"),ua=(...r)=>te.findLast(r,e=>typeof e=="function"),fa={noSort:!1,readEntries:!1,method:te.Constants.NONE,fs:null};Ls.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),fa);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=te.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new te(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=te.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=te.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw te.Errors.INVALID_FILENAME();let o=new la(t,n),{canonical:c,sanitize:a,zipnamefix:l}=te;function u(f){if(f&&o){var d;if(typeof f=="string"&&(d=o.getEntry(se.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(d=o.getEntry(f.entryName)),d)return d}return null}function g(f){let{join:d,normalize:E,sep:S}=se.posix;return d(".",E(S+f.split("\\").join(S)+S))}function h(f){return f instanceof RegExp?(function(d){return function(E){return d.test(E)}})(f):typeof f!="function"?()=>!0:f}let I=(f,d)=>{let E=d.slice(-1);return E=E===s.sep?s.sep:"",se.relative(f,d)+E};return{readFile:function(f,d){var E=u(f);return E&&E.getData(d)||null},childCount:function(f){let d=u(f);if(d)return o.getChildCount(d)},readFileAsync:function(f,d){var E=u(f);E?E.getDataAsync(d):d(null,"getEntry failed for:"+f)},readAsText:function(f,d){var E=u(f);if(E){var S=E.getData();if(S&&S.length)return S.toString(d||"utf8")}return""},readAsTextAsync:function(f,d,E){var S=u(f);S?S.getDataAsync(function(C,p){if(p){d(C,p);return}C&&C.length?d(C.toString(E||"utf8")):d("")}):d("")},deleteFile:function(f,d=!0){var E=u(f);E&&o.deleteFile(E.entryName,d)},deleteEntry:function(f){var d=u(f);d&&o.deleteEntry(d.entryName)},addZipComment:function(f){o.comment=f},getZipComment:function(){return o.comment||""},addZipEntryComment:function(f,d){var E=u(f);E&&(E.comment=d)},getZipEntryComment:function(f){var d=u(f);return d&&d.comment||""},updateFile:function(f,d){var E=u(f);E&&E.setData(d)},addLocalFile:function(f,d,E,S){if(s.fs.existsSync(f)){d=d?g(d):"";let C=se.win32.basename(se.win32.normalize(f));d+=E||C;let p=s.fs.statSync(f),i=p.isFile()?s.fs.readFileSync(f):Buffer.alloc(0);p.isDirectory()&&(d+=s.sep),this.addFile(d,i,S,p)}else throw te.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,d){f=typeof f=="object"?f:{localPath:f};let E=se.resolve(f.localPath),{comment:S}=f,{zipPath:C,zipName:p}=f,i=this;s.fs.stat(E,function(m,y){if(m)return d(m,!1);C=C?g(C):"";let x=se.win32.basename(se.win32.normalize(E));if(C+=p||x,y.isFile())s.fs.readFile(E,function(_,b){return _?d(_,!1):(i.addFile(C,b,S,y),setImmediate(d,void 0,!0))});else if(y.isDirectory())return C+=s.sep,i.addFile(C,Buffer.alloc(0),S,y),setImmediate(d,void 0,!0)})},addLocalFolder:function(f,d,E){if(E=h(E),d=d?g(d):"",f=se.normalize(f),s.fs.existsSync(f)){let S=s.findFiles(f),C=this;if(S.length)for(let p of S){let i=se.join(d,I(f,p));E(i)&&C.addLocalFile(p,se.dirname(i))}}else throw te.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,d,E,S){S=h(S),E=E?g(E):"",f=se.normalize(f);var C=this;s.fs.open(f,"r",function(p){if(p&&p.code==="ENOENT")d(void 0,te.Errors.FILE_NOT_FOUND(f));else if(p)d(void 0,p);else{var i=s.findFiles(f),m=-1,y=function(){if(m+=1,m<i.length){var x=i[m],_=I(f,x).split("\\").join("/");_=_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(_)?s.fs.stat(x,function(b,v){b&&d(void 0,b),v.isFile()?s.fs.readFile(x,function(k,P){k?d(void 0,k):(C.addFile(E+_,P,"",v),y())}):(C.addFile(E+_+"/",Buffer.alloc(0),"",v),y())}):process.nextTick(()=>{y()})}else d(!0,void 0)};y()}})},addLocalFolderAsync2:function(f,d){let E=this;f=typeof f=="object"?f:{localPath:f},localPath=se.resolve(g(f.localPath));let{zipPath:S,filter:C,namefix:p}=f;C instanceof RegExp?C=(function(y){return function(x){return y.test(x)}})(C):typeof C!="function"&&(C=function(){return!0}),S=S?g(S):"",p=="latin1"&&(p=y=>y.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof p!="function"&&(p=y=>y);let i=y=>se.join(S,p(I(localPath,y))),m=y=>se.win32.basename(se.win32.normalize(p(y)));s.fs.open(localPath,"r",function(y){y&&y.code==="ENOENT"?d(void 0,te.Errors.FILE_NOT_FOUND(localPath)):y?d(void 0,y):s.findFilesAsync(localPath,function(x,_){if(x)return d(x);_=_.filter(b=>C(i(b))),_.length||d(void 0,!1),setImmediate(_.reverse().reduce(function(b,v){return function(k,P){if(k||P===!1)return setImmediate(b,k,!1);E.addLocalFileAsync({localPath:v,zipPath:se.dirname(i(v)),zipName:m(v)},b)}},d))})})},addLocalFolderPromise:function(f,d){return new Promise((E,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},d),(C,p)=>{C&&S(C),p&&E(this)})})},addFile:function(f,d,E,S){f=l(f);let C=u(f),p=C!=null;p||(C=new ca(n),C.entryName=f),C.comment=E||"";let i=typeof S=="object"&&S instanceof s.fs.Stats;i&&(C.header.time=S.mtime);var m=C.isDirectory?16:0;let y=C.isDirectory?16384:32768;return i?y|=4095&S.mode:typeof S=="number"?y|=4095&S:y|=C.isDirectory?493:420,m=(m|y<<16)>>>0,C.attr=m,C.setData(d),p||o.setEntry(C),C},getEntries:function(f){return o.password=f,o?o.entries:[]},getEntry:function(f){return u(f)},getEntryCount:function(){return o.getEntryCount()},forEach:function(f){return o.forEach(f)},extractEntryTo:function(f,d,E,S,C,p){S=rt(!1,S),C=rt(!1,C),E=rt(!0,E),p=$s(C,p);var i=u(f);if(!i)throw te.Errors.NO_ENTRY();var m=c(i.entryName),y=a(d,p&&!i.isDirectory?p:E?m:se.basename(m));if(i.isDirectory){var x=o.getEntryChildren(i);return x.forEach(function(v){if(v.isDirectory)return;var k=v.getData();if(!k)throw te.Errors.CANT_EXTRACT_FILE();var P=c(v.entryName),j=a(d,E?P:se.basename(P));let $=C?v.header.fileAttr:void 0;s.writeFileTo(j,k,S,$)}),!0}var _=i.getData(o.password);if(!_)throw te.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(y)&&!S)throw te.Errors.CANT_OVERRIDE();let b=C?f.header.fileAttr:void 0;return s.writeFileTo(y,_,S,b),!0},test:function(f){if(!o)return!1;for(var d in o.entries)try{if(d.isDirectory)continue;var E=o.entries[d].getData(f);if(!E)return!1}catch{return!1}return!0},extractAllTo:function(f,d,E,S){if(E=rt(!1,E),S=$s(E,S),d=rt(!1,d),!o)throw te.Errors.NO_ZIP();o.entries.forEach(function(C){var p=a(f,c(C.entryName));if(C.isDirectory){s.makeDir(p);return}var i=C.getData(S);if(!i)throw te.Errors.CANT_EXTRACT_FILE();let m=E?C.header.fileAttr:void 0;s.writeFileTo(p,i,d,m);try{s.fs.utimesSync(p,C.header.time,C.header.time)}catch{throw te.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,d,E,S){if(S=ua(d,E,S),E=rt(!1,E),d=rt(!1,d),!S)return new Promise((y,x)=>{this.extractAllToAsync(f,d,E,function(_){_?x(_):y(this)})});if(!o){S(te.Errors.NO_ZIP());return}f=se.resolve(f);let C=y=>a(f,se.normalize(c(y.entryName))),p=(y,x)=>new Error(y+': "'+x+'"'),i=[],m=[];o.entries.forEach(y=>{y.isDirectory?i.push(y):m.push(y)});for(let y of i){let x=C(y),_=E?y.header.fileAttr:void 0;try{s.makeDir(x),_&&s.fs.chmodSync(x,_),s.fs.utimesSync(x,y.header.time,y.header.time)}catch{S(p("Unable to create folder",x))}}m.reverse().reduce(function(y,x){return function(_){if(_)y(_);else{let b=se.normalize(c(x.entryName)),v=a(f,b);x.getDataAsync(function(k,P){if(P)y(P);else if(!k)y(te.Errors.CANT_EXTRACT_FILE());else{let j=E?x.header.fileAttr:void 0;s.writeFileToAsync(v,k,d,j,function($){$||y(p("Unable to write file",v)),s.fs.utimes(v,x.header.time,x.header.time,function(K){K?y(p("Unable to set times",v)):y()})})}})}}},S)()},writeZip:function(f,d){if(arguments.length===1&&typeof f=="function"&&(d=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var E=o.compressToBuffer();if(E){var S=s.writeFileTo(f,E,!0);typeof d=="function"&&d(S?null:new Error("failed"),"")}}},writeZipPromise:function(f,d){let{overwrite:E,perm:S}=Object.assign({overwrite:!0},d);return new Promise((C,p)=>{!f&&n.filename&&(f=n.filename),f||p("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let m=y=>y?C(y):p("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(f,i,E,S,m)},p)})},toBufferPromise:function(){return new Promise((f,d)=>{o.toAsyncBuffer(f,d)})},toBuffer:function(f,d,E,S){return typeof f=="function"?(o.toAsyncBuffer(f,d,E,S),null):o.compressToBuffer()}}}});function Ba(){try{return un.default.statSync("/.dockerenv"),!0}catch{return!1}}function Va(){try{return un.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function fn(){return ln===void 0&&(ln=Ba()||Va()),ln}var un,ln,ao=be(()=>{"use strict";un=we(require("fs"),1)});function ct(){return dn===void 0&&(dn=Wa()||fn()),dn}var co,dn,Wa,pn=be(()=>{"use strict";co=we(require("fs"),1);ao();Wa=()=>{try{return co.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var mn,uo,ur,lo,Ke,gn=be(()=>{"use strict";mn=we(require("process"),1),uo=we(require("os"),1),ur=we(require("fs"),1);pn();lo=()=>{if(mn.default.platform!=="linux")return!1;if(uo.default.release().toLowerCase().includes("microsoft"))return!ct();try{if(ur.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!ct()}catch{}return ur.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||ur.default.existsSync("/run/WSL")?!ct():!1},Ke=mn.default.env.__IS_WSL_TEST__?lo:lo()});var hn,kt,qa,Ga,yn,fo=be(()=>{"use strict";hn=we(require("process"),1),kt=we(require("fs/promises"),1);gn();gn();qa=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await kt.default.access(t,kt.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await kt.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Ga=async()=>`${await qa()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,yn=async()=>Ke?Ga():`${hn.default.env.SYSTEMROOT||hn.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Xe(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var po=be(()=>{"use strict"});async function Sn(){if(go.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await za("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var mo,go,ho,za,yo=be(()=>{"use strict";mo=require("util"),go=we(require("process"),1),ho=require("child_process"),za=(0,mo.promisify)(ho.execFile)});async function Co(r,{humanReadableOutput:e=!0,signal:t}={}){if(So.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await Za("osascript",["-e",r,n],s);return o.trim()}var So,Eo,En,Za,wo=be(()=>{"use strict";So=we(require("process"),1),Eo=require("util"),En=require("child_process"),Za=(0,Eo.promisify)(En.execFile)});async function Cn(r){return Co(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
30
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var bo=be(()=>{"use strict";wo()});async function bn(r=Ja){let{stdout:e}=await r("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 wn(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),c=s===-1?void 0:n.slice(0,s),a=o===-1?void 0:n.slice(0,o);return fr[n]??fr[c]??fr[a]??{name:n,id:n}}var Io,Ao,Ja,fr,xu,wn,_o=be(()=>{"use strict";Io=require("util"),Ao=require("child_process"),Ja=(0,Io.promisify)(Ao.execFile),fr={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"}},xu=new Map(Object.entries(fr)),wn=class extends Error{}});async function In(){if(dr.default.platform==="darwin"){let r=await Sn();return{name:await Cn(r),id:r}}if(dr.default.platform==="linux"){let{stdout:r}=await Ka("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:Xa(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(dr.default.platform==="win32")return bn();throw new Error("Only macOS, Linux, and Windows are supported")}var xo,dr,vo,Ka,Xa,Oo=be(()=>{"use strict";xo=require("util"),dr=we(require("process"),1),vo=require("child_process");yo();bo();_o();Ka=(0,xo.promisify)(vo.execFile),Xa=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var No={};Nt(No,{apps:()=>Ye,default:()=>rc,openApp:()=>tc});async function Qa(){let r=await yn(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=xn.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await Ya(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function To(r){if(typeof r=="string"||Array.isArray(r))return r;let{[Ro]:e}=r;if(!e)throw new Error(`${Ro} is not supported`);return e}function mr({[yt]:r},{wsl:e}){if(e&&Ke)return To(e);if(!r)throw new Error(`${yt} is not supported`);return To(r)}var _n,xn,vn,jo,Do,On,pr,nc,Ya,An,ko,yt,Ro,Po,Rt,ec,tc,Ye,rc,$o=be(()=>{"use strict";_n=we(require("process"),1),xn=require("buffer"),vn=we(require("path"),1),jo=require("url"),Do=require("util"),On=we(require("child_process"),1),pr=we(require("fs/promises"),1);fo();po();Oo();pn();nc={},Ya=(0,Do.promisify)(On.default.execFile),An=vn.default.dirname((0,jo.fileURLToPath)(nc.url)),ko=vn.default.join(An,"xdg-open"),{platform:yt,arch:Ro}=_n.default;Po=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},Rt=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Po(r.app,a=>Rt({...r,app:a}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Po(e,a=>Rt({...r,app:{name:a,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let a={"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"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},u=Ke?await Qa():await In();if(u.id in a){let g=a[u.id];return e==="browserPrivate"&&t.push(l[g]),Rt({...r,app:{name:Ye[g],arguments:t}})}throw new Error(`${u.name} is not supported as a default browser`)}let n,s=[],o={};if(yt==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(yt==="win32"||Ke&&!ct()&&!e){n=await yn(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Ke||(o.windowsVerbatimArguments=!0);let a=["Start"];r.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&a.push(`"${r.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),r.target=xn.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let a=!An||An==="/",l=!1;try{await pr.default.access(ko,pr.constants.X_OK),l=!0}catch{}n=_n.default.versions.electron??(yt==="android"||a||!l)?"xdg-open":ko}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}yt==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let c=On.default.spawn(n,s,o);return r.wait?new Promise((a,l)=>{c.once("error",l),c.once("close",u=>{if(!r.allowNonzeroExitCode&&u>0){l(new Error(`Exited with code ${u}`));return}a(c)})}):(c.unref(),c)},ec=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return Rt({...e,target:r})},tc=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))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 Rt({...e,app:{name:r,arguments:t}})};Ye={};Xe(Ye,"chrome",()=>mr({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"]}}));Xe(Ye,"brave",()=>mr({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"]}}));Xe(Ye,"firefox",()=>mr({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Xe(Ye,"edge",()=>mr({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Xe(Ye,"browser",()=>"browser");Xe(Ye,"browserPrivate",()=>"browserPrivate");rc=ec});var ii={};Nt(ii,{collectTelemetry:()=>oi,pushTelemetry:()=>si,registerTelemetry:()=>Pn});function ni(){let r=process.env.SC_PROFILE;return r?(0,Pt.join)((0,kn.homedir)(),".config","shared-context","profiles",r):(0,Pt.join)((0,kn.homedir)(),".config","shared-context")}function Rn(){return(0,Pt.join)(ni(),"usage.jsonl")}function lc(){let r=Rn();if(!(0,_e.existsSync)(r))return[];try{let e=(0,_e.readFileSync)(r,"utf8").trim().split(`
|
|
31
|
-
`).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function
|
|
27
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Vn(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}function $r(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0}Lr.Command=Nr;Lr.useColor=$r});var Zn=X(Re=>{"use strict";var{Argument:qn}=Lt(),{Command:Fr}=Wn(),{CommanderError:Mi,InvalidArgumentError:Gn}=Et(),{Help:Hi}=Or(),{Option:zn}=Tr();Re.program=new Fr;Re.createCommand=r=>new Fr(r);Re.createOption=(r,e)=>new zn(r,e);Re.createArgument=(r,e)=>new qn(r,e);Re.Command=Fr;Re.Option=zn;Re.Argument=qn;Re.Help=Hi;Re.CommanderError=Mi;Re.InvalidArgumentError=Gn;Re.InvalidOptionArgumentError=Gn});function Qn(r,e){Yn=r,Xn=e}function A(){return Yn?!0:Xn?!1:!process.stdout.isTTY}function L(r,e){console.log(JSON.stringify({ok:!0,command:r,data:e}))}function D(r,e,t){console.log(JSON.stringify({ok:!1,command:r,errors:[{code:e,message:t}]}))}function w(r){console.log(r)}function R(r){console.error(r)}function Se(r,e=2){if(r.length===0)return"";let t=[];for(let n of r)for(let s=0;s<n.length;s++)t[s]=Math.max(t[s]||0,n[s].length);return r.map(n=>n.map((s,o)=>o<n.length-1?s.padEnd(t[o]+e):s).join("")).join(`
|
|
28
|
+
`)}var Yn,Xn,ce=be(()=>{"use strict";Yn=!1,Xn=!1});var Ut={};Nt(Ut,{addToManifest:()=>me,clearAuth:()=>Ur,clearLastSyncAt:()=>Ve,getAuth:()=>Pe,getConfig:()=>ve,getManifest:()=>z,getSyncState:()=>Gi,removeFromManifest:()=>At,saveAuth:()=>It,saveConfig:()=>ns,saveManifest:()=>Be,saveSyncState:()=>zi,shouldSync:()=>Wr,updateConfig:()=>Mt,updateManifestMeta:()=>Ht});function Ct(){let r=process.env.SC_PROFILE;return r?(0,tt.join)(es,"profiles",r):es}function Hr(){return(0,tt.join)(Ct(),"auth.json")}function rs(){return(0,tt.join)(Ct(),"config.json")}function Mr(){return(0,tt.join)(Ct(),"manifest.json")}function Ui(){(0,xe.mkdirSync)(Ct(),{recursive:!0})}function wt(r,e){try{return(0,xe.existsSync)(r)?JSON.parse((0,xe.readFileSync)(r,"utf-8")):e}catch{return e}}function bt(r,e,t=!1){if(Ui(),(0,xe.writeFileSync)(r,JSON.stringify(e,null,2)+`
|
|
29
|
+
`,"utf-8"),t)try{(0,xe.chmodSync)(r,384)}catch{}}function Pe(){return wt(Hr(),null)}function It(r){bt(Hr(),r,!0)}function Ur(){try{(0,xe.writeFileSync)(Hr(),"{}","utf-8")}catch{}}function ve(){return wt(rs(),Bi)}function ns(r){bt(rs(),r)}function Mt(r){let e=ve();ns({...e,...r})}function Wi(r){if(r.version&&r.version>=Br)return r;let e=r;if(!r.version||r.version<2){e={version:2,installations:r.installations.map(s=>({...s,serverSynced:!1}))};let t=Vr(),n=wt(t,null);n?.lastSyncAt&&(e.lastSyncAt=n.lastSyncAt);try{(0,xe.unlinkSync)(t)}catch{}}return(!e.version||e.version<3)&&(e={...e,version:3}),e}function z(){let r=wt(Mr(),Vi),e=Wi(r);return(!r.version||r.version<Br)&&bt(Mr(),e),e}function Be(r){bt(Mr(),r)}function me(r){let e=z(),t=e.installations.findIndex(n=>n.resourceId===r.resourceId&&n.agent===r.agent);t>=0?e.installations[t]=r:e.installations.push(r),Be(e)}function At(r,e){let t=z();t.installations=t.installations.filter(n=>!(n.resourceId===r&&(!e||n.agent===e))),Be(t)}function Ve(){let r=z();delete r.lastSyncAt,Be(r)}function Ht(r){let e=z();r.lastSyncAt!==void 0&&(e.lastSyncAt=r.lastSyncAt),Be(e)}function Vr(){return(0,tt.join)(Ct(),"last-sync.json")}function Gi(){return wt(Vr(),null)}function zi(r){bt(Vr(),r)}function Wr(){let r=parseInt(process.env.SC_SYNC_COOLDOWN||"",10),e=r>=0?r:qi,t=z();return t.lastSyncAt?Date.now()-new Date(t.lastSyncAt).getTime()>=e:!0}var xe,tt,ts,es,Bi,Br,Vi,qi,ge=be(()=>{"use strict";xe=require("fs"),tt=require("path"),ts=require("os"),es=(0,tt.join)((0,ts.homedir)(),".config","shared-context");Bi={apiBase:"https://sharedcontext.ai"};Br=3,Vi={version:Br,installations:[]};qi=720*60*1e3});var is={};Nt(is,{del:()=>_t,fetchRaw:()=>qr,get:()=>Z,isAuthenticated:()=>U,patch:()=>Zi,post:()=>F});function ss(){return ve().apiBase||"https://sharedcontext.ai"}function os(){let r={"Content-Type":"application/json"},e=Pe();return e?.token&&(r.Authorization=`Bearer ${e.token}`),r}function U(){return!!Pe()?.token}async function Bt(r,e,t,n){let s=`${ss()}${e}`;try{let o={method:r,headers:os(),body:t?JSON.stringify(t):void 0};n&&(o.signal=AbortSignal.timeout(n));let c=await fetch(s,o),a=c.headers.get("content-type")||"";if(!a.includes("application/json"))return c.ok?{ok:!1,error:{code:"INVALID_RESPONSE",message:`Expected JSON, got ${a||"unknown content type"}`}}:{ok:!1,error:{code:`HTTP_${c.status}`,message:c.statusText}};let l=await c.json();return c.ok?{ok:!0,data:l.data??l}:{ok:!1,error:{code:l?.error?.code||`HTTP_${c.status}`,message:l?.error?.message||l?.message||c.statusText}}}catch(o){return{ok:!1,error:{code:"NETWORK_ERROR",message:o instanceof Error?o.message:"Network request failed"}}}}function Z(r){return Bt("GET",r)}function F(r,e,t){return Bt("POST",r,e,t)}function Zi(r,e){return Bt("PATCH",r,e)}function _t(r,e){return Bt("DELETE",r,e)}async function qr(r){let e=`${ss()}${r}`,t=await fetch(e,{headers:os()});if(!t.ok)throw new Error(`Download failed: ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}var le=be(()=>{"use strict";ge()});function Ji(){try{return Zr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Ki(){try{return Zr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Jr(){return zr===void 0&&(zr=Ji()||Ki()),zr}var Zr,zr,as=be(()=>{"use strict";Zr=we(require("fs"),1)});function rt(){return Kr===void 0&&(Kr=Yi()||Jr()),Kr}var cs,Kr,Yi,Yr=be(()=>{"use strict";cs=we(require("fs"),1);as();Yi=()=>{try{return cs.default.statSync("/run/.containerenv"),!0}catch{return!1}}});var Xr,us,Vt,ls,ze,Qr=be(()=>{"use strict";Xr=we(require("process"),1),us=we(require("os"),1),Vt=we(require("fs"),1);Yr();ls=()=>{if(Xr.default.platform!=="linux")return!1;if(us.default.release().toLowerCase().includes("microsoft"))return!rt();try{if(Vt.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!rt()}catch{}return Vt.default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Vt.default.existsSync("/run/WSL")?!rt():!1},ze=Xr.default.env.__IS_WSL_TEST__?ls:ls()});var en,xt,Xi,Qi,tn,fs=be(()=>{"use strict";en=we(require("process"),1),xt=we(require("fs/promises"),1);Qr();Qr();Xi=(()=>{let r="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await xt.default.access(t,xt.constants.F_OK),n=!0}catch{}if(!n)return r;let s=await xt.default.readFile(t,{encoding:"utf8"}),o=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return o?(e=o.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):r}})(),Qi=async()=>`${await Xi()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,tn=async()=>ze?Qi():`${en.default.env.SYSTEMROOT||en.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`});function Ze(r,e,t){let n=s=>Object.defineProperty(r,e,{value:s,enumerable:!0,writable:!0});return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get(){let s=t();return n(s),s},set(s){n(s)}}),r}var ds=be(()=>{"use strict"});async function rn(){if(ms.default.platform!=="darwin")throw new Error("macOS only");let{stdout:r}=await ea("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(r)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}var ps,ms,gs,ea,hs=be(()=>{"use strict";ps=require("util"),ms=we(require("process"),1),gs=require("child_process"),ea=(0,ps.promisify)(gs.execFile)});async function Es(r,{humanReadableOutput:e=!0,signal:t}={}){if(ys.default.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],s={};t&&(s.signal=t);let{stdout:o}=await ta("osascript",["-e",r,n],s);return o.trim()}var ys,Ss,nn,ta,Cs=be(()=>{"use strict";ys=we(require("process"),1),Ss=require("util"),nn=require("child_process"),ta=(0,Ss.promisify)(nn.execFile)});async function sn(r){return Es(`tell application "Finder" to set app_path to application file id "${r}" as string
|
|
30
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var ws=be(()=>{"use strict";Cs()});async function an(r=ra){let{stdout:e}=await r("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 on(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,s=n.lastIndexOf("."),o=n.lastIndexOf("-"),c=s===-1?void 0:n.slice(0,s),a=o===-1?void 0:n.slice(0,o);return Wt[n]??Wt[c]??Wt[a]??{name:n,id:n}}var bs,Is,ra,Wt,sl,on,As=be(()=>{"use strict";bs=require("util"),Is=require("child_process"),ra=(0,bs.promisify)(Is.execFile),Wt={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"}},sl=new Map(Object.entries(Wt)),on=class extends Error{}});async function cn(){if(qt.default.platform==="darwin"){let r=await rn();return{name:await sn(r),id:r}}if(qt.default.platform==="linux"){let{stdout:r}=await na("xdg-mime",["query","default","x-scheme-handler/http"]),e=r.trim();return{name:sa(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(qt.default.platform==="win32")return an();throw new Error("Only macOS, Linux, and Windows are supported")}var _s,qt,xs,na,sa,vs=be(()=>{"use strict";_s=require("util"),qt=we(require("process"),1),xs=require("child_process");hs();ws();As();na=(0,_s.promisify)(xs.execFile),sa=r=>r.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase())});var Ds={};Nt(Ds,{apps:()=>Je,default:()=>la,openApp:()=>ca});async function ia(){let r=await tn(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=fn.Buffer.from(e,"utf16le").toString("base64"),{stdout:n}=await oa(r,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),s=n.trim(),o={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return o[s]?{id:o[s]}:{}}function Ps(r){if(typeof r=="string"||Array.isArray(r))return r;let{[ks]:e}=r;if(!e)throw new Error(`${ks} is not supported`);return e}function zt({[ft]:r},{wsl:e}){if(e&&ze)return Ps(e);if(!r)throw new Error(`${ft} is not supported`);return Ps(r)}var un,fn,dn,Ts,js,pn,Gt,ua,oa,ln,Os,ft,ks,Rs,vt,aa,ca,Je,la,Ns=be(()=>{"use strict";un=we(require("process"),1),fn=require("buffer"),dn=we(require("path"),1),Ts=require("url"),js=require("util"),pn=we(require("child_process"),1),Gt=we(require("fs/promises"),1);fs();ds();vs();Yr();ua={},oa=(0,js.promisify)(pn.default.execFile),ln=dn.default.dirname((0,Ts.fileURLToPath)(ua.url)),Os=dn.default.join(ln,"xdg-open"),{platform:ft,arch:ks}=un.default;Rs=async(r,e)=>{let t;for(let n of r)try{return await e(n)}catch(s){t=s}throw t},vt=async r=>{if(r={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...r},Array.isArray(r.app))return Rs(r.app,a=>vt({...r,app:a}));let{name:e,arguments:t=[]}=r.app??{};if(t=[...t],Array.isArray(e))return Rs(e,a=>vt({...r,app:{name:a,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let a={"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"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},u=ze?await ia():await cn();if(u.id in a){let g=a[u.id];return e==="browserPrivate"&&t.push(l[g]),vt({...r,app:{name:Je[g],arguments:t}})}throw new Error(`${u.name} is not supported as a default browser`)}let n,s=[],o={};if(ft==="darwin")n="open",r.wait&&s.push("--wait-apps"),r.background&&s.push("--background"),r.newInstance&&s.push("--new"),e&&s.push("-a",e);else if(ft==="win32"||ze&&!rt()&&!e){n=await tn(),s.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),ze||(o.windowsVerbatimArguments=!0);let a=["Start"];r.wait&&a.push("-Wait"),e?(a.push(`"\`"${e}\`""`),r.target&&t.push(r.target)):r.target&&a.push(`"${r.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),r.target=fn.Buffer.from(a.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let a=!ln||ln==="/",l=!1;try{await Gt.default.access(Os,Gt.constants.X_OK),l=!0}catch{}n=un.default.versions.electron??(ft==="android"||a||!l)?"xdg-open":Os}t.length>0&&s.push(...t),r.wait||(o.stdio="ignore",o.detached=!0)}ft==="darwin"&&t.length>0&&s.push("--args",...t),r.target&&s.push(r.target);let c=pn.default.spawn(n,s,o);return r.wait?new Promise((a,l)=>{c.once("error",l),c.once("close",u=>{if(!r.allowNonzeroExitCode&&u>0){l(new Error(`Exited with code ${u}`));return}a(c)})}):(c.unref(),c)},aa=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a `target`");return vt({...e,target:r})},ca=(r,e)=>{if(typeof r!="string"&&!Array.isArray(r))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 vt({...e,app:{name:r,arguments:t}})};Je={};Ze(Je,"chrome",()=>zt({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"]}}));Ze(Je,"brave",()=>zt({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"]}}));Ze(Je,"firefox",()=>zt({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Ze(Je,"edge",()=>zt({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Ze(Je,"browser",()=>"browser");Ze(Je,"browserPrivate",()=>"browserPrivate");la=aa});var gn=X((El,Hs)=>{"use strict";Hs.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Zt=X(Bs=>{"use strict";var Us={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function fa(r){return function(...e){return e.length&&(r=r.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+r)}}for(let r of Object.keys(Us))Bs[r]=fa(Us[r])});var zs=X((wl,Gs)=>{"use strict";var da=require("fs"),de=require("path"),Vs=gn(),pa=Zt(),ma=typeof process=="object"&&process.platform==="win32",Ws=r=>typeof r=="object"&&r!==null,qs=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function re(r){this.sep=de.sep,this.fs=da,Ws(r)&&Ws(r.fs)&&typeof r.fs.statSync=="function"&&(this.fs=r.fs)}Gs.exports=re;re.prototype.makeDir=function(r){let e=this;function t(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(o){if(!(!o||o.substr(-1,1)===":")){s+=e.sep+o;var c;try{c=e.fs.statSync(s)}catch{e.fs.mkdirSync(s)}if(c&&c.isFile())throw pa.FILE_IN_THE_WAY(`"${s}"`)}})}t(r)};re.prototype.writeFileTo=function(r,e,t,n){let s=this;if(s.fs.existsSync(r)){if(!t)return!1;var o=s.fs.statSync(r);if(o.isDirectory())return!1}var c=de.dirname(r);s.fs.existsSync(c)||s.makeDir(c);var a;try{a=s.fs.openSync(r,"w",438)}catch{s.fs.chmodSync(r,438),a=s.fs.openSync(r,"w",438)}if(a)try{s.fs.writeSync(a,e,0,e.length,0)}finally{s.fs.closeSync(a)}return s.fs.chmodSync(r,n||438),!0};re.prototype.writeFileToAsync=function(r,e,t,n,s){typeof n=="function"&&(s=n,n=void 0);let o=this;o.fs.exists(r,function(c){if(c&&!t)return s(!1);o.fs.stat(r,function(a,l){if(c&&l.isDirectory())return s(!1);var u=de.dirname(r);o.fs.exists(u,function(g){g||o.makeDir(u),o.fs.open(r,"w",438,function(h,I){h?o.fs.chmod(r,438,function(){o.fs.open(r,"w",438,function(f,d){o.fs.write(d,e,0,e.length,0,function(){o.fs.close(d,function(){o.fs.chmod(r,n||438,function(){s(!0)})})})})}):I?o.fs.write(I,e,0,e.length,0,function(){o.fs.close(I,function(){o.fs.chmod(r,n||438,function(){s(!0)})})}):o.fs.chmod(r,n||438,function(){s(!0)})})})})})};re.prototype.findFiles=function(r){let e=this;function t(n,s,o){typeof s=="boolean"&&(o=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(a){let l=de.join(n,a),u=e.fs.statSync(l);(!s||s.test(l))&&c.push(de.normalize(l)+(u.isDirectory()?e.sep:"")),u.isDirectory()&&o&&(c=c.concat(t(l,s,o)))}),c}return t(r,void 0,!0)};re.prototype.findFilesAsync=function(r,e){let t=this,n=[];t.fs.readdir(r,function(s,o){if(s)return e(s);let c=o.length;if(!c)return e(null,n);o.forEach(function(a){a=de.join(r,a),t.fs.stat(a,function(l,u){if(l)return e(l);u&&(n.push(de.normalize(a)+(u.isDirectory()?t.sep:"")),u.isDirectory()?t.findFilesAsync(a,function(g,h){if(g)return e(g);n=n.concat(h),--c||e(null,n)}):--c||e(null,n))})})})};re.prototype.getAttributes=function(){};re.prototype.setAttributes=function(){};re.crc32update=function(r,e){return qs[(r^e)&255]^r>>>8};re.crc32=function(r){typeof r=="string"&&(r=Buffer.from(r,"utf8"));let e=r.length,t=-1;for(let n=0;n<e;)t=re.crc32update(t,r[n++]);return~t>>>0};re.methodToString=function(r){switch(r){case Vs.STORED:return"STORED ("+r+")";case Vs.DEFLATED:return"DEFLATED ("+r+")";default:return"UNSUPPORTED ("+r+")"}};re.canonical=function(r){if(!r)return"";let e=de.posix.normalize("/"+r.split("\\").join("/"));return de.join(".",e)};re.zipnamefix=function(r){if(!r)return"";let e=de.posix.normalize("/"+r.split("\\").join("/"));return de.posix.join(".",e)};re.findLast=function(r,e){if(!Array.isArray(r))throw new TypeError("arr is not array");let t=r.length>>>0;for(let n=t-1;n>=0;n--)if(e(r[n],n,r))return r[n]};re.sanitize=function(r,e){r=de.resolve(de.normalize(r));for(var t=e.split("/"),n=0,s=t.length;n<s;n++){var o=de.normalize(de.join(r,t.slice(n,s).join(de.sep)));if(o.indexOf(r)===0)return o}return de.normalize(de.join(r,de.basename(e)))};re.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};re.readBigUInt64LE=function(r,e){var t=Buffer.from(r.slice(e,e+8));return t.swap64(),parseInt(`0x${t.toString("hex")}`)};re.fromDOS2Date=function(r){return new Date((r>>25&127)+1980,Math.max((r>>21&15)-1,0),Math.max(r>>16&31,1),r>>11&31,r>>5&63,(r&31)<<1)};re.fromDate2DOS=function(r){let e=0,t=0;return r.getFullYear()>1979&&(e=(r.getFullYear()-1980&127)<<9|r.getMonth()+1<<5|r.getDate(),t=r.getHours()<<11|r.getMinutes()<<5|r.getSeconds()>>1),e<<16|t};re.isWin=ma;re.crcTable=qs});var Js=X((bl,Zs)=>{"use strict";var ga=require("path");Zs.exports=function(r,{fs:e}){var t=r||"",n=o(),s=null;function o(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(s=e.statSync(t),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=ga.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ys=X((Il,Ks)=>{"use strict";Ks.exports={efs:!0,encode:r=>Buffer.from(r,"utf8"),decode:r=>r.toString("utf8")}});var pt=X((Al,dt)=>{"use strict";dt.exports=zs();dt.exports.Constants=gn();dt.exports.Errors=Zt();dt.exports.FileAttr=Js();dt.exports.decoder=Ys()});var Qs=X((_l,Xs)=>{"use strict";var Ke=pt(),T=Ke.Constants;Xs.exports=function(){var r=20,e=10,t=0,n=0,s=0,o=0,c=0,a=0,l=0,u=0,g=0,h=0,I=0,f=0,d=0;r|=Ke.isWin?2560:768,t|=T.FLG_EFS;let E={extraLen:0},S=i=>Math.max(0,i)>>>0,C=i=>Math.max(0,i)&65535,p=i=>Math.max(0,i)&255;return s=Ke.fromDate2DOS(new Date),{get made(){return r},set made(i){r=i},get version(){return e},set version(i){e=i},get flags(){return t},set flags(i){t=i},get flags_efs(){return(t&T.FLG_EFS)>0},set flags_efs(i){i?t|=T.FLG_EFS:t&=~T.FLG_EFS},get flags_desc(){return(t&T.FLG_DESC)>0},set flags_desc(i){i?t|=T.FLG_DESC:t&=~T.FLG_DESC},get method(){return n},set method(i){switch(i){case T.STORED:this.version=10;case T.DEFLATED:default:this.version=20}n=i},get time(){return Ke.fromDOS2Date(this.timeval)},set time(i){this.timeval=Ke.fromDate2DOS(i)},get timeval(){return s},set timeval(i){s=S(i)},get timeHighByte(){return p(s>>>8)},get crc(){return o},set crc(i){o=S(i)},get compressedSize(){return c},set compressedSize(i){c=S(i)},get size(){return a},set size(i){a=S(i)},get fileNameLength(){return l},set fileNameLength(i){l=i},get extraLength(){return u},set extraLength(i){u=i},get extraLocalLength(){return E.extraLen},set extraLocalLength(i){E.extraLen=i},get commentLength(){return g},set commentLength(i){g=i},get diskNumStart(){return h},set diskNumStart(i){h=S(i)},get inAttr(){return I},set inAttr(i){I=S(i)},get attr(){return f},set attr(i){f=S(i)},get fileAttr(){return(f||0)>>16&4095},get offset(){return d},set offset(i){d=S(i)},get encrypted(){return(t&T.FLG_ENC)===T.FLG_ENC},get centralHeaderSize(){return T.CENHDR+l+u+g},get realDataOffset(){return d+T.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:function(i){var m=i.slice(d,d+T.LOCHDR);if(m.readUInt32LE(0)!==T.LOCSIG)throw Ke.Errors.INVALID_LOC();E.version=m.readUInt16LE(T.LOCVER),E.flags=m.readUInt16LE(T.LOCFLG),E.method=m.readUInt16LE(T.LOCHOW),E.time=m.readUInt32LE(T.LOCTIM),E.crc=m.readUInt32LE(T.LOCCRC),E.compressedSize=m.readUInt32LE(T.LOCSIZ),E.size=m.readUInt32LE(T.LOCLEN),E.fnameLen=m.readUInt16LE(T.LOCNAM),E.extraLen=m.readUInt16LE(T.LOCEXT);let y=d+T.LOCHDR+E.fnameLen,x=y+E.extraLen;return i.slice(y,x)},loadFromBinary:function(i){if(i.length!==T.CENHDR||i.readUInt32LE(0)!==T.CENSIG)throw Ke.Errors.INVALID_CEN();r=i.readUInt16LE(T.CENVEM),e=i.readUInt16LE(T.CENVER),t=i.readUInt16LE(T.CENFLG),n=i.readUInt16LE(T.CENHOW),s=i.readUInt32LE(T.CENTIM),o=i.readUInt32LE(T.CENCRC),c=i.readUInt32LE(T.CENSIZ),a=i.readUInt32LE(T.CENLEN),l=i.readUInt16LE(T.CENNAM),u=i.readUInt16LE(T.CENEXT),g=i.readUInt16LE(T.CENCOM),h=i.readUInt16LE(T.CENDSK),I=i.readUInt16LE(T.CENATT),f=i.readUInt32LE(T.CENATX),d=i.readUInt32LE(T.CENOFF)},localHeaderToBinary:function(){var i=Buffer.alloc(T.LOCHDR);return i.writeUInt32LE(T.LOCSIG,0),i.writeUInt16LE(e,T.LOCVER),i.writeUInt16LE(t,T.LOCFLG),i.writeUInt16LE(n,T.LOCHOW),i.writeUInt32LE(s,T.LOCTIM),i.writeUInt32LE(o,T.LOCCRC),i.writeUInt32LE(c,T.LOCSIZ),i.writeUInt32LE(a,T.LOCLEN),i.writeUInt16LE(l,T.LOCNAM),i.writeUInt16LE(E.extraLen,T.LOCEXT),i},centralHeaderToBinary:function(){var i=Buffer.alloc(T.CENHDR+l+u+g);return i.writeUInt32LE(T.CENSIG,0),i.writeUInt16LE(r,T.CENVEM),i.writeUInt16LE(e,T.CENVER),i.writeUInt16LE(t,T.CENFLG),i.writeUInt16LE(n,T.CENHOW),i.writeUInt32LE(s,T.CENTIM),i.writeUInt32LE(o,T.CENCRC),i.writeUInt32LE(c,T.CENSIZ),i.writeUInt32LE(a,T.CENLEN),i.writeUInt16LE(l,T.CENNAM),i.writeUInt16LE(u,T.CENEXT),i.writeUInt16LE(g,T.CENCOM),i.writeUInt16LE(h,T.CENDSK),i.writeUInt16LE(I,T.CENATT),i.writeUInt32LE(f,T.CENATX),i.writeUInt32LE(d,T.CENOFF),i},toJSON:function(){let i=function(m){return m+" bytes"};return{made:r,version:e,flags:t,method:Ke.methodToString(n),time:this.time,crc:"0x"+o.toString(16).toUpperCase(),compressedSize:i(c),size:i(a),fileNameLength:i(l),extraLength:i(u),commentLength:i(g),diskNumStart:h,inAttr:I,attr:f,offset:d,centralHeaderSize:i(T.CENHDR+l+u+g)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var to=X((xl,eo)=>{"use strict";var mt=pt(),ee=mt.Constants;eo.exports=function(){var r=0,e=0,t=0,n=0,s=0;return{get diskEntries(){return r},set diskEntries(o){r=e=o},get totalEntries(){return e},set totalEntries(o){e=r=o},get size(){return t},set size(o){t=o},get offset(){return n},set offset(o){n=o},get commentLength(){return s},set commentLength(o){s=o},get mainHeaderSize(){return ee.ENDHDR+s},loadFromBinary:function(o){if((o.length!==ee.ENDHDR||o.readUInt32LE(0)!==ee.ENDSIG)&&(o.length<ee.ZIP64HDR||o.readUInt32LE(0)!==ee.ZIP64SIG))throw mt.Errors.INVALID_END();o.readUInt32LE(0)===ee.ENDSIG?(r=o.readUInt16LE(ee.ENDSUB),e=o.readUInt16LE(ee.ENDTOT),t=o.readUInt32LE(ee.ENDSIZ),n=o.readUInt32LE(ee.ENDOFF),s=o.readUInt16LE(ee.ENDCOM)):(r=mt.readBigUInt64LE(o,ee.ZIP64SUB),e=mt.readBigUInt64LE(o,ee.ZIP64TOT),t=mt.readBigUInt64LE(o,ee.ZIP64SIZE),n=mt.readBigUInt64LE(o,ee.ZIP64OFF),s=0)},toBinary:function(){var o=Buffer.alloc(ee.ENDHDR+s);return o.writeUInt32LE(ee.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(r,ee.ENDSUB),o.writeUInt16LE(e,ee.ENDTOT),o.writeUInt32LE(t,ee.ENDSIZ),o.writeUInt32LE(n,ee.ENDOFF),o.writeUInt16LE(s,ee.ENDCOM),o.fill(" ",ee.ENDHDR),o},toJSON:function(){let o=function(c,a){let l=c.toString(16).toUpperCase();for(;l.length<a;)l="0"+l;return"0x"+l};return{diskEntries:r,totalEntries:e,size:t+" bytes",offset:o(n,4),commentLength:s}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var yn=X(hn=>{"use strict";hn.EntryHeader=Qs();hn.MainHeader=to()});var no=X((Ol,ro)=>{"use strict";ro.exports=function(r){var e=require("zlib"),t={chunkSize:(parseInt(r.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(r,t)},deflateAsync:function(n){var s=e.createDeflateRaw(t),o=[],c=0;s.on("data",function(a){o.push(a),c+=a.length}),s.on("end",function(){var a=Buffer.alloc(c),l=0;a.fill(0);for(var u=0;u<o.length;u++){var g=o[u];g.copy(a,l),l+=g.length}n&&n(a)}),s.end(r)}}}});var oo=X((kl,so)=>{"use strict";var ha=+(process.versions?process.versions.node:"").split(".")[0]||0;so.exports=function(r,e){var t=require("zlib");let n=ha>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(r,n)},inflateAsync:function(s){var o=t.createInflateRaw(n),c=[],a=0;o.on("data",function(l){c.push(l),a+=l.length}),o.on("end",function(){var l=Buffer.alloc(a),u=0;l.fill(0);for(var g=0;g<c.length;g++){var h=c[g];h.copy(l,u),u+=h.length}s&&s(l)}),o.end(r)}}}});var uo=X((Rl,lo)=>{"use strict";var{randomFillSync:io}=require("crypto"),ya=Zt(),Sa=new Uint32Array(256).map((r,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),co=(r,e)=>Math.imul(r,e)>>>0,ao=(r,e)=>Sa[(r^e)&255]^r>>>8,Ot=()=>typeof io=="function"?io(Buffer.alloc(12)):Ot.node();Ot.node=()=>{let r=Buffer.alloc(12),e=r.length;for(let t=0;t<e;t++)r[t]=Math.random()*256&255;return r};var Jt={genSalt:Ot};function Kt(r){let e=Buffer.isBuffer(r)?r:Buffer.from(r);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}Kt.prototype.updateKeys=function(r){let e=this.keys;return e[0]=ao(e[0],r),e[1]+=e[0]&255,e[1]=co(e[1],134775813)+1,e[2]=ao(e[2],e[1]>>>24),r};Kt.prototype.next=function(){let r=(this.keys[2]|2)>>>0;return co(r,r^1)>>8&255};function Ea(r){let e=new Kt(r);return function(t){let n=Buffer.alloc(t.length),s=0;for(let o of t)n[s++]=e.updateKeys(o^e.next());return n}}function Ca(r){let e=new Kt(r);return function(t,n,s=0){n||(n=Buffer.alloc(t.length));for(let o of t){let c=e.next();n[s++]=o^c,e.updateKeys(o)}return n}}function wa(r,e,t){if(!r||!Buffer.isBuffer(r)||r.length<12)return Buffer.alloc(0);let n=Ea(t),s=n(r.slice(0,12)),o=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==o)throw ya.WRONG_PASSWORD();return n(r.slice(12))}function ba(r){Buffer.isBuffer(r)&&r.length>=12?Jt.genSalt=function(){return r.slice(0,12)}:r==="node"?Jt.genSalt=Ot.node:Jt.genSalt=Ot}function Ia(r,e,t,n=!1){r==null&&(r=Buffer.alloc(0)),Buffer.isBuffer(r)||(r=Buffer.from(r.toString()));let s=Ca(t),o=Jt.genSalt();o[11]=e.crc>>>24&255,n&&(o[10]=e.crc>>>16&255);let c=Buffer.alloc(r.length+12);return s(o,c),s(r,c,12)}lo.exports={decrypt:wa,encrypt:Ia,_salter:ba}});var fo=X(Yt=>{"use strict";Yt.Deflater=no();Yt.Inflater=oo();Yt.ZipCrypto=uo()});var En=X((Tl,po)=>{"use strict";var G=pt(),Aa=yn(),ne=G.Constants,Sn=fo();po.exports=function(r,e){var t=new Aa.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),o=!1,c=null,a=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let g=r,h=typeof g.decoder=="object"?g.decoder:G.decoder;u=h.hasOwnProperty("efs")?h.efs:!1;function I(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function f(i){if(t.flags_desc){let m={},y=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(y)==ne.LOCSIG||e.readUInt32LE(y)==ne.CENSIG)throw G.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(y)==ne.EXTSIG)m.crc=e.readUInt32LE(y+ne.EXTCRC),m.compressedSize=e.readUInt32LE(y+ne.EXTSIZ),m.size=e.readUInt32LE(y+ne.EXTLEN);else if(e.readUInt16LE(y+12)===19280)m.crc=e.readUInt32LE(y+ne.EXTCRC-4),m.compressedSize=e.readUInt32LE(y+ne.EXTSIZ-4),m.size=e.readUInt32LE(y+ne.EXTLEN-4);else throw G.Errors.DESCRIPTOR_UNKNOWN();if(m.compressedSize!==t.compressedSize||m.size!==t.size||m.crc!==t.crc)throw G.Errors.DESCRIPTOR_FAULTY();if(G.crc32(i)!==m.crc)return!1}else if(G.crc32(i)!==t.localHeader.crc)return!1;return!0}function d(i,m,y){if(typeof m>"u"&&typeof i=="string"&&(y=i,i=void 0),o)return i&&m&&m(Buffer.alloc(0),G.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var x=I();if(x.length===0)return i&&m&&m(x),x;if(t.encrypted){if(typeof y!="string"&&!Buffer.isBuffer(y))throw G.Errors.INVALID_PASS_PARAM();x=Sn.ZipCrypto.decrypt(x,t,y)}var _=Buffer.alloc(t.size);switch(t.method){case G.Constants.STORED:if(x.copy(_),f(_))return i&&m&&m(_),_;throw i&&m&&m(_,G.Errors.BAD_CRC()),G.Errors.BAD_CRC();case G.Constants.DEFLATED:var b=new Sn.Inflater(x,t.size);if(i)b.inflateAsync(function(v){v.copy(v,0),m&&(f(v)?m(v):m(v,G.Errors.BAD_CRC()))});else{if(b.inflate(_).copy(_,0),!f(_))throw G.Errors.BAD_CRC(`"${h.decode(n)}"`);return _}break;default:throw i&&m&&m(Buffer.alloc(0),G.Errors.UNKNOWN_METHOD()),G.Errors.UNKNOWN_METHOD()}}function E(i,m){if((!c||!c.length)&&Buffer.isBuffer(e))return i&&m&&m(I()),I();if(c.length&&!o){var y;switch(t.method){case G.Constants.STORED:return t.compressedSize=t.size,y=Buffer.alloc(c.length),c.copy(y),i&&m&&m(y),y;default:case G.Constants.DEFLATED:var x=new Sn.Deflater(c);if(i)x.deflateAsync(function(b){y=Buffer.alloc(b.length),t.compressedSize=b.length,b.copy(y),m&&m(y)});else{var _=x.deflate();return t.compressedSize=_.length,_}x=null;break}}else if(i&&m)m(Buffer.alloc(0));else return Buffer.alloc(0)}function S(i,m){return(i.readUInt32LE(m+4)<<4)+i.readUInt32LE(m)}function C(i){try{for(var m=0,y,x,_;m+4<i.length;)y=i.readUInt16LE(m),m+=2,x=i.readUInt16LE(m),m+=2,_=i.slice(m,m+x),m+=x,ne.ID_ZIP64===y&&p(_)}catch{throw G.Errors.EXTRA_FIELD_PARSE_ERROR()}}function p(i){var m,y,x,_;i.length>=ne.EF_ZIP64_SCOMP&&(m=S(i,ne.EF_ZIP64_SUNCOMP),t.size===ne.EF_ZIP64_OR_32&&(t.size=m)),i.length>=ne.EF_ZIP64_RHO&&(y=S(i,ne.EF_ZIP64_SCOMP),t.compressedSize===ne.EF_ZIP64_OR_32&&(t.compressedSize=y)),i.length>=ne.EF_ZIP64_DSN&&(x=S(i,ne.EF_ZIP64_RHO),t.offset===ne.EF_ZIP64_OR_32&&(t.offset=x)),i.length>=ne.EF_ZIP64_DSN+4&&(_=i.readUInt32LE(ne.EF_ZIP64_DSN),t.diskNumStart===ne.EF_ZIP64_OR_16&&(t.diskNumStart=_))}return{get entryName(){return h.decode(n)},get rawEntryName(){return n},set entryName(i){n=G.toBuffer(i,h.encode);var m=n[n.length-1];o=m===47||m===92,t.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return a},set extra(i){a=i,t.extraLength=i.length,C(i)},get comment(){return h.decode(s)},set comment(i){if(s=G.toBuffer(i,h.encode),t.commentLength=s.length,s.length>65535)throw G.Errors.COMMENT_TOO_LONG()},get name(){var i=h.decode(n);return o?i.substr(i.length-1).split("/").pop():i.split("/").pop()},get isDirectory(){return o},getCompressedData:function(){return E(!1,null)},getCompressedDataAsync:function(i){E(!0,i)},setData:function(i){c=G.toBuffer(i,G.decoder.encode),!o&&c.length?(t.size=c.length,t.method=G.Constants.DEFLATED,t.crc=G.crc32(i),t.changed=!0):t.method=G.Constants.STORED},getData:function(i){return t.changed?c:d(!1,null,i)},getDataAsync:function(i,m){t.changed?i(c):d(!0,i,m)},set attr(i){t.attr=i},get attr(){return t.attr},set header(i){t.loadFromBinary(i)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=a.length;var i=t.centralHeaderToBinary(),m=G.Constants.CENHDR;return n.copy(i,m),m+=n.length,a.copy(i,m),m+=t.extraLength,s.copy(i,m),i},packLocalHeader:function(){let i=0;t.flags_efs=this.efs,t.extraLocalLength=l.length;let m=t.localHeaderToBinary(),y=Buffer.alloc(m.length+n.length+t.extraLocalLength);return m.copy(y,i),i+=m.length,n.copy(y,i),i+=n.length,l.copy(y,i),i+=l.length,y},toJSON:function(){let i=function(m){return"<"+(m&&m.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:i(e),data:i(c)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ho=X((jl,go)=>{"use strict";var mo=En(),_a=yn(),Ce=pt();go.exports=function(r,e){var t=[],n={},s=Buffer.alloc(0),o=new _a.MainHeader,c=!1,a=null;let l=new Set,u=e,{noSort:g,decoder:h}=u;r?d(u.readEntries):c=!0;function I(){let S=new Set;for(let C of Object.keys(n)){let p=C.split("/");if(p.pop(),!!p.length)for(let i=0;i<p.length;i++){let m=p.slice(0,i+1).join("/")+"/";S.add(m)}}for(let C of S)if(!(C in n)){let p=new mo(u);p.entryName=C,p.attr=16,p.temporary=!0,t.push(p),n[p.entryName]=p,l.add(p)}}function f(){if(c=!0,n={},o.diskEntries>(r.length-o.offset)/Ce.Constants.CENHDR)throw Ce.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(o.diskEntries);for(var S=o.offset,C=0;C<t.length;C++){var p=S,i=new mo(u,r);i.header=r.slice(p,p+=Ce.Constants.CENHDR),i.entryName=r.slice(p,p+=i.header.fileNameLength),i.header.extraLength&&(i.extra=r.slice(p,p+=i.header.extraLength)),i.header.commentLength&&(i.comment=r.slice(p,p+i.header.commentLength)),S+=i.header.centralHeaderSize,t[C]=i,n[i.entryName]=i}l.clear(),I()}function d(S){var C=r.length-Ce.Constants.ENDHDR,p=Math.max(0,C-65535),i=p,m=r.length,y=-1,x=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(p=0),C;C>=i;C--)if(r[C]===80){if(r.readUInt32LE(C)===Ce.Constants.ENDSIG){y=C,x=C,m=C+Ce.Constants.ENDHDR,i=C-Ce.Constants.END64HDR;continue}if(r.readUInt32LE(C)===Ce.Constants.END64SIG){i=p;continue}if(r.readUInt32LE(C)===Ce.Constants.ZIP64SIG){y=C,m=C+Ce.readBigUInt64LE(r,C+Ce.Constants.ZIP64SIZE)+Ce.Constants.ZIP64LEAD;break}}if(y==-1)throw Ce.Errors.INVALID_FORMAT();o.loadFromBinary(r.slice(y,m)),o.commentLength&&(s=r.slice(x+Ce.Constants.ENDHDR)),S&&f()}function E(){t.length>1&&!g&&t.sort((S,C)=>S.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return c||f(),t.filter(S=>!l.has(S))},get comment(){return h.decode(s)},set comment(S){s=Ce.toBuffer(S,h.encode),o.commentLength=s.length},getEntryCount:function(){return c?t.length:o.diskEntries},forEach:function(S){this.entries.forEach(S)},getEntry:function(S){return c||f(),n[S]||null},setEntry:function(S){c||f(),t.push(S),n[S.entryName]=S,o.totalEntries=t.length},deleteFile:function(S,C=!0){c||f();let p=n[S];this.getEntryChildren(p,C).map(m=>m.entryName).forEach(this.deleteEntry)},deleteEntry:function(S){c||f();let C=n[S],p=t.indexOf(C);p>=0&&(t.splice(p,1),delete n[S],o.totalEntries=t.length)},getEntryChildren:function(S,C=!0){if(c||f(),typeof S=="object")if(S.isDirectory&&C){let p=[],i=S.entryName;for(let m of t)m.entryName.startsWith(i)&&p.push(m);return p}else return[S];return[]},getChildCount:function(S){if(S&&S.isDirectory){let C=this.getEntryChildren(S);return C.includes(S)?C.length-1:C.length}return 0},compressToBuffer:function(){c||f(),E();let S=[],C=[],p=0,i=0;o.size=0,o.offset=0;let m=0;for(let _ of this.entries){let b=_.getCompressedData();_.header.offset=i;let v=_.packLocalHeader(),k=v.length+b.length;i+=k,S.push(v),S.push(b);let P=_.packCentralHeader();C.push(P),o.size+=P.length,p+=k+P.length,m++}p+=o.mainHeaderSize,o.offset=i,o.totalEntries=m,i=0;let y=Buffer.alloc(p);for(let _ of S)_.copy(y,i),i+=_.length;for(let _ of C)_.copy(y,i),i+=_.length;let x=o.toBinary();return s&&s.copy(x,Ce.Constants.ENDHDR),x.copy(y,i),r=y,c=!1,y},toAsyncBuffer:function(S,C,p,i){try{c||f(),E();let m=[],y=[],x=0,_=0,b=0;o.size=0,o.offset=0;let v=function(k){if(k.length>0){let P=k.shift(),j=P.entryName+P.extra.toString();p&&p(j),P.getCompressedDataAsync(function($){i&&i(j),P.header.offset=_;let K=P.packLocalHeader(),ae=K.length+$.length;_+=ae,m.push(K),m.push($);let O=P.packCentralHeader();y.push(O),o.size+=O.length,x+=ae+O.length,b++,v(k)})}else{x+=o.mainHeaderSize,o.offset=_,o.totalEntries=b,_=0;let P=Buffer.alloc(x);m.forEach(function($){$.copy(P,_),_+=$.length}),y.forEach(function($){$.copy(P,_),_+=$.length});let j=o.toBinary();s&&s.copy(j,Ce.Constants.ENDHDR),j.copy(P,_),r=P,c=!1,S(P)}};v(Array.from(this.entries))}catch(m){C(m)}}}}});var Eo=X((Dl,So)=>{"use strict";var te=pt(),se=require("path"),xa=En(),va=ho(),nt=(...r)=>te.findLast(r,e=>typeof e=="boolean"),yo=(...r)=>te.findLast(r,e=>typeof e=="string"),Oa=(...r)=>te.findLast(r,e=>typeof e=="function"),ka={noSort:!1,readEntries:!1,method:te.Constants.NONE,fs:null};So.exports=function(r,e){let t=null,n=Object.assign(Object.create(null),ka);r&&typeof r=="object"&&(r instanceof Uint8Array||(Object.assign(n,r),r=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(r)&&(t=r,n.method=te.Constants.BUFFER,r=void 0)),Object.assign(n,e);let s=new te(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=te.decoder),r&&typeof r=="string")if(s.fs.existsSync(r))n.method=te.Constants.FILE,n.filename=r,t=s.fs.readFileSync(r);else throw te.Errors.INVALID_FILENAME();let o=new va(t,n),{canonical:c,sanitize:a,zipnamefix:l}=te;function u(f){if(f&&o){var d;if(typeof f=="string"&&(d=o.getEntry(se.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(d=o.getEntry(f.entryName)),d)return d}return null}function g(f){let{join:d,normalize:E,sep:S}=se.posix;return d(".",E(S+f.split("\\").join(S)+S))}function h(f){return f instanceof RegExp?(function(d){return function(E){return d.test(E)}})(f):typeof f!="function"?()=>!0:f}let I=(f,d)=>{let E=d.slice(-1);return E=E===s.sep?s.sep:"",se.relative(f,d)+E};return{readFile:function(f,d){var E=u(f);return E&&E.getData(d)||null},childCount:function(f){let d=u(f);if(d)return o.getChildCount(d)},readFileAsync:function(f,d){var E=u(f);E?E.getDataAsync(d):d(null,"getEntry failed for:"+f)},readAsText:function(f,d){var E=u(f);if(E){var S=E.getData();if(S&&S.length)return S.toString(d||"utf8")}return""},readAsTextAsync:function(f,d,E){var S=u(f);S?S.getDataAsync(function(C,p){if(p){d(C,p);return}C&&C.length?d(C.toString(E||"utf8")):d("")}):d("")},deleteFile:function(f,d=!0){var E=u(f);E&&o.deleteFile(E.entryName,d)},deleteEntry:function(f){var d=u(f);d&&o.deleteEntry(d.entryName)},addZipComment:function(f){o.comment=f},getZipComment:function(){return o.comment||""},addZipEntryComment:function(f,d){var E=u(f);E&&(E.comment=d)},getZipEntryComment:function(f){var d=u(f);return d&&d.comment||""},updateFile:function(f,d){var E=u(f);E&&E.setData(d)},addLocalFile:function(f,d,E,S){if(s.fs.existsSync(f)){d=d?g(d):"";let C=se.win32.basename(se.win32.normalize(f));d+=E||C;let p=s.fs.statSync(f),i=p.isFile()?s.fs.readFileSync(f):Buffer.alloc(0);p.isDirectory()&&(d+=s.sep),this.addFile(d,i,S,p)}else throw te.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,d){f=typeof f=="object"?f:{localPath:f};let E=se.resolve(f.localPath),{comment:S}=f,{zipPath:C,zipName:p}=f,i=this;s.fs.stat(E,function(m,y){if(m)return d(m,!1);C=C?g(C):"";let x=se.win32.basename(se.win32.normalize(E));if(C+=p||x,y.isFile())s.fs.readFile(E,function(_,b){return _?d(_,!1):(i.addFile(C,b,S,y),setImmediate(d,void 0,!0))});else if(y.isDirectory())return C+=s.sep,i.addFile(C,Buffer.alloc(0),S,y),setImmediate(d,void 0,!0)})},addLocalFolder:function(f,d,E){if(E=h(E),d=d?g(d):"",f=se.normalize(f),s.fs.existsSync(f)){let S=s.findFiles(f),C=this;if(S.length)for(let p of S){let i=se.join(d,I(f,p));E(i)&&C.addLocalFile(p,se.dirname(i))}}else throw te.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,d,E,S){S=h(S),E=E?g(E):"",f=se.normalize(f);var C=this;s.fs.open(f,"r",function(p){if(p&&p.code==="ENOENT")d(void 0,te.Errors.FILE_NOT_FOUND(f));else if(p)d(void 0,p);else{var i=s.findFiles(f),m=-1,y=function(){if(m+=1,m<i.length){var x=i[m],_=I(f,x).split("\\").join("/");_=_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(_)?s.fs.stat(x,function(b,v){b&&d(void 0,b),v.isFile()?s.fs.readFile(x,function(k,P){k?d(void 0,k):(C.addFile(E+_,P,"",v),y())}):(C.addFile(E+_+"/",Buffer.alloc(0),"",v),y())}):process.nextTick(()=>{y()})}else d(!0,void 0)};y()}})},addLocalFolderAsync2:function(f,d){let E=this;f=typeof f=="object"?f:{localPath:f},localPath=se.resolve(g(f.localPath));let{zipPath:S,filter:C,namefix:p}=f;C instanceof RegExp?C=(function(y){return function(x){return y.test(x)}})(C):typeof C!="function"&&(C=function(){return!0}),S=S?g(S):"",p=="latin1"&&(p=y=>y.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof p!="function"&&(p=y=>y);let i=y=>se.join(S,p(I(localPath,y))),m=y=>se.win32.basename(se.win32.normalize(p(y)));s.fs.open(localPath,"r",function(y){y&&y.code==="ENOENT"?d(void 0,te.Errors.FILE_NOT_FOUND(localPath)):y?d(void 0,y):s.findFilesAsync(localPath,function(x,_){if(x)return d(x);_=_.filter(b=>C(i(b))),_.length||d(void 0,!1),setImmediate(_.reverse().reduce(function(b,v){return function(k,P){if(k||P===!1)return setImmediate(b,k,!1);E.addLocalFileAsync({localPath:v,zipPath:se.dirname(i(v)),zipName:m(v)},b)}},d))})})},addLocalFolderPromise:function(f,d){return new Promise((E,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},d),(C,p)=>{C&&S(C),p&&E(this)})})},addFile:function(f,d,E,S){f=l(f);let C=u(f),p=C!=null;p||(C=new xa(n),C.entryName=f),C.comment=E||"";let i=typeof S=="object"&&S instanceof s.fs.Stats;i&&(C.header.time=S.mtime);var m=C.isDirectory?16:0;let y=C.isDirectory?16384:32768;return i?y|=4095&S.mode:typeof S=="number"?y|=4095&S:y|=C.isDirectory?493:420,m=(m|y<<16)>>>0,C.attr=m,C.setData(d),p||o.setEntry(C),C},getEntries:function(f){return o.password=f,o?o.entries:[]},getEntry:function(f){return u(f)},getEntryCount:function(){return o.getEntryCount()},forEach:function(f){return o.forEach(f)},extractEntryTo:function(f,d,E,S,C,p){S=nt(!1,S),C=nt(!1,C),E=nt(!0,E),p=yo(C,p);var i=u(f);if(!i)throw te.Errors.NO_ENTRY();var m=c(i.entryName),y=a(d,p&&!i.isDirectory?p:E?m:se.basename(m));if(i.isDirectory){var x=o.getEntryChildren(i);return x.forEach(function(v){if(v.isDirectory)return;var k=v.getData();if(!k)throw te.Errors.CANT_EXTRACT_FILE();var P=c(v.entryName),j=a(d,E?P:se.basename(P));let $=C?v.header.fileAttr:void 0;s.writeFileTo(j,k,S,$)}),!0}var _=i.getData(o.password);if(!_)throw te.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(y)&&!S)throw te.Errors.CANT_OVERRIDE();let b=C?f.header.fileAttr:void 0;return s.writeFileTo(y,_,S,b),!0},test:function(f){if(!o)return!1;for(var d in o.entries)try{if(d.isDirectory)continue;var E=o.entries[d].getData(f);if(!E)return!1}catch{return!1}return!0},extractAllTo:function(f,d,E,S){if(E=nt(!1,E),S=yo(E,S),d=nt(!1,d),!o)throw te.Errors.NO_ZIP();o.entries.forEach(function(C){var p=a(f,c(C.entryName));if(C.isDirectory){s.makeDir(p);return}var i=C.getData(S);if(!i)throw te.Errors.CANT_EXTRACT_FILE();let m=E?C.header.fileAttr:void 0;s.writeFileTo(p,i,d,m);try{s.fs.utimesSync(p,C.header.time,C.header.time)}catch{throw te.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,d,E,S){if(S=Oa(d,E,S),E=nt(!1,E),d=nt(!1,d),!S)return new Promise((y,x)=>{this.extractAllToAsync(f,d,E,function(_){_?x(_):y(this)})});if(!o){S(te.Errors.NO_ZIP());return}f=se.resolve(f);let C=y=>a(f,se.normalize(c(y.entryName))),p=(y,x)=>new Error(y+': "'+x+'"'),i=[],m=[];o.entries.forEach(y=>{y.isDirectory?i.push(y):m.push(y)});for(let y of i){let x=C(y),_=E?y.header.fileAttr:void 0;try{s.makeDir(x),_&&s.fs.chmodSync(x,_),s.fs.utimesSync(x,y.header.time,y.header.time)}catch{S(p("Unable to create folder",x))}}m.reverse().reduce(function(y,x){return function(_){if(_)y(_);else{let b=se.normalize(c(x.entryName)),v=a(f,b);x.getDataAsync(function(k,P){if(P)y(P);else if(!k)y(te.Errors.CANT_EXTRACT_FILE());else{let j=E?x.header.fileAttr:void 0;s.writeFileToAsync(v,k,d,j,function($){$||y(p("Unable to write file",v)),s.fs.utimes(v,x.header.time,x.header.time,function(K){K?y(p("Unable to set times",v)):y()})})}})}}},S)()},writeZip:function(f,d){if(arguments.length===1&&typeof f=="function"&&(d=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var E=o.compressToBuffer();if(E){var S=s.writeFileTo(f,E,!0);typeof d=="function"&&d(S?null:new Error("failed"),"")}}},writeZipPromise:function(f,d){let{overwrite:E,perm:S}=Object.assign({overwrite:!0},d);return new Promise((C,p)=>{!f&&n.filename&&(f=n.filename),f||p("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(i=>{let m=y=>y?C(y):p("ADM-ZIP: Wasn't able to write zip file");s.writeFileToAsync(f,i,E,S,m)},p)})},toBufferPromise:function(){return new Promise((f,d)=>{o.toAsyncBuffer(f,d)})},toBuffer:function(f,d,E,S){return typeof f=="function"?(o.toAsyncBuffer(f,d,E,S),null):o.compressToBuffer()}}}});var ci={};Nt(ci,{collectTelemetry:()=>ai,pushTelemetry:()=>ii,registerTelemetry:()=>Tn});function oi(){let r=process.env.SC_PROFILE;return r?(0,Pt.join)((0,Rn.homedir)(),".config","shared-context","profiles",r):(0,Pt.join)((0,Rn.homedir)(),".config","shared-context")}function Pn(){return(0,Pt.join)(oi(),"usage.jsonl")}function fc(){let r=Pn();if(!(0,_e.existsSync)(r))return[];try{let e=(0,_e.readFileSync)(r,"utf8").trim().split(`
|
|
31
|
+
`).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function dc(r){let e=Pn();if((0,_e.existsSync)(e))try{let t=(0,_e.readFileSync)(e,"utf8").trim().split(`
|
|
32
32
|
`).filter(Boolean);if(t.length<=r)return;let n=t.slice(-r);(0,_e.writeFileSync)(e,n.join(`
|
|
33
33
|
`)+`
|
|
34
|
-
`,"utf8")}catch{}}async function
|
|
35
|
-
`,"utf8")}catch{}}async function
|
|
36
|
-
|
|
37
|
-
`,"utf-8")}function ma(r,e,t,n){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),c=ke(r,e),a=mt(o);if(Object.keys(a).length===0)throw new Error("Hook package does not contain any hook event handlers");return nn(c,a,n),c}function tn(r,e,t,n={}){let s=r.slug||r.id,o=Ks[r.resourceType]||r.resourceType+"s",c=e.orgSlug?`${e.orgSlug}/`:"";return{resourceId:r.id,slug:s,installPath:`${o}/${c}${s}`,title:r.title,sha:r.latestSha||"",scope:n.projectId?"project":"global",agent:t,installedAt:new Date().toISOString(),collectionId:e.id,resourceType:r.resourceType,latestSha:r.latestSha||void 0,serverSynced:!0,...n.projectId?{projectId:n.projectId}:{}}}async function rn(r,e,t){let n=[],s=[],o=r.resource.slug||r.resource.id,c=en(r),a,l="decomposed",u,g=!1,h={},I=[],f=t.dryRun===!0;if(r.resource.resourceType==="agent"){let d=Q(e,t.project),E=Gs(d,o,r.resource.id,r,t.manifest);E.renamed&&(o=E.slug,c=en({...r,resource:{...r.resource,slug:o}}),g=!0),a=(0,ie.join)(d,o);let S=Z(a,r.files,{baselineHashes:t.baselineHashes,dryRun:f});h=S.contentHashes,I=S.preserved}else if(r.resource.resourceType==="mcp")a="",f||Xt(e,t.project,r);else if(r.resource.resourceType==="hook")a="",f||ma(e,t.project,r,c);else{let d=V(e,t.project);if(r.resource.resourceType!=="collection"){let E=Gs(d,o,r.resource.id,r,t.manifest);E.renamed&&(o=E.slug,c=en({...r,resource:{...r.resource,slug:o}}),g=!0)}if(a=(0,ie.join)(d,o),r.resource.resourceType==="collection"){let E=!1;try{let S=r.resource.slug||r.resource.id,C=r.resource.orgSlug||"",p=Kt(e.id),i=t.authed?`/api/cli/resource/collections/${C}/${S}?format=plugin&platform=${p}`:`/api/public/resource/collections/${C}/${S}?format=plugin&platform=${p}`,m=await Jt(i,S),y=ha(m,e.id);if(y.length>0){let x={...r,files:y},b=await Le(e).install(x,t.project?"project":"user",e);a=b.installDir,l="plugin",u=m,E=!0,s.push("Installed from plugin package");for(let v of b.warnings)n.push(v)}}catch(S){n.push(`Plugin install failed, falling back to decomposed: ${S}`)}if(!E){let C=await Le(e).install(r,t.project?"project":"user",e);a=C.installDir;for(let p of C.warnings)n.push(p)}}else{let E=Z(a,r.files,{baselineHashes:t.baselineHashes,dryRun:f});h=E.contentHashes,I=E.preserved}}return{installDir:a,installPath:c,installMode:l,pluginDir:u,slug:o,renamed:g,warnings:n,notes:s,contentHashes:h,preserved:I}}function Xs(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").option("--code <code>","Bootstrap CLI auth using an auth code from the web app").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=$e(s.agent);if(!o){let i=Ge();A()?D("install","NO_AGENTS",i):R(i),process.exit(1)}if(s.code){let i=await F("/api/cli/auth",{code:s.code});i.ok?(It({token:i.data.token,email:i.data.user.email,orgId:i.data.org.id,orgSlug:i.data.org.slug,orgName:i.data.org.name,createdAt:new Date().toISOString()}),A()||w(`Authenticated as ${i.data.user.email}`)):U()?A()||w("Auth code already used, continuing with saved credentials."):(A()?D("install",i.error.code,i.error.message):R(`Auth failed: ${i.error.message}`),process.exit(1))}let c=U(),l=await J(`${c?"/api/cli/resource":"/api/public/resource"}/${e}`);l.ok||(A()?D("install",l.error.code,l.error.message):R(`Install failed: ${l.error.message}`),process.exit(1));let u=l.data,g;try{g=await rn(u,o,{project:!!s.project,manifest:z(),authed:c})}catch(i){A()?D("install","WRITE_FAILED",`Failed to install: ${i}`):R(`Failed to install: ${i}`),process.exit(1)}if(g.renamed&&!A()&&w(`Note: Renamed to "${g.slug}" (collision with existing resource)`),!A()){for(let i of g.notes)w(i);for(let i of g.warnings)R(`Warning: ${i}`)}let h=g.installDir,I=g.installPath,f=g.slug,d=g.installMode,E=g.pluginDir,S;if(c&&u.resource.latestSha){let i=await F("/api/cli/install",{resourceId:u.resource.id,agentPlatform:o.platform,installedSha:u.resource.latestSha});i.ok||(S=`Could not record install on server: ${i.error.message}`,A()||R(`Warning: ${S}`))}let C=s.project?Ie():null;C&&c&&await F(`/api/cli/projects/${C.projectId}/resources`,{resourceId:u.resource.id}).catch(()=>{});let p=u.resource.resourceType==="collection";if(me({resourceId:u.resource.id,slug:f,installPath:I,title:u.resource.title,sha:u.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:u.resource.latestSha||void 0,resourceType:u.resource.resourceType,serverSynced:!0,...Object.keys(g.contentHashes).length>0?{contentHashes:g.contentHashes}:{},...p?{pluginFormat:zt(o.id),memberCount:u.memberResources?.length,installMode:d,pluginDir:E}:{},...C?{projectId:C.projectId}:{}}),u.memberResources&&u.resource.resourceType==="collection"){if(d==="decomposed")for(let i of u.memberResources)me(tn(i,u.resource,o.id,{projectId:C?.projectId}));for(let i of u.memberResources)c&&i.latestSha&&await F("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(Ve(),A())L("install",{installPath:I,title:u.resource.title,path:h||void 0,files:u.files.length,...u.resource.resourceType==="mcp"?{mcpConfigPath:Ee(o,!!s.project)}:{},...u.resource.resourceType==="hook"?{settingsPath:ke(o,!!s.project)}:{},...u.memberResources?{memberResources:u.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...S&&{warning:S}});else{if(u.resource.resourceType==="mcp"?w(`Installed MCP "${u.resource.title}" to ${Ee(o,!!s.project)}`):u.resource.resourceType==="hook"?w(`Installed hook "${u.resource.title}" to ${ke(o,!!s.project)}`):u.memberResources&&u.memberResources.length>0?w(`Installed "${u.resource.title}" (${u.memberResources.length} resources)`):w(`Installed "${u.resource.title}" to ${h}`),u.resource.resourceType!=="mcp"&&u.resource.resourceType!=="hook"&&!(u.memberResources&&u.memberResources.length>0)&&w(` ${u.files.length} file${u.files.length===1?"":"s"} written`),u.memberResources&&u.memberResources.length>0){let i={};for(let y of u.memberResources){let x=y.resourceType||"other";i[x]||(i[x]=[]),i[x].push(y.title)}let m={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[y,x]of Object.entries(i)){let _=m[y]||y;w(` ${_}: ${x.join(", ")}`)}}c||(w(""),w("Tip: Sign up at sharedcontext.ai to track installations and get updates."))}})}var ga={"claude-code":[".claude"],cursor:[".cursor"],"gemini-cli":[".gemini"],codex:[".codex"],antigravity:[".gemini"]},zs=new Set(["skills","commands","agents","hooks","mcps"]);function ha(r,e){let t=ga[e]||[];for(let o of t){let c=(0,ie.join)(r,o);if((0,ue.existsSync)(c)){let l=Zs(c).filter(u=>zs.has(u.path.split("/")[0]));if(l.length>0)return l}}return Zs(r).filter(o=>zs.has(o.path.split("/")[0]))}var ya=new Set([".git","node_modules","__pycache__",".venv"]);function Zs(r){let e=[];function t(n){let s;try{s=(0,ue.readdirSync)(n,{withFileTypes:!0})}catch{return}for(let o of s)if(o.isDirectory()){if(ya.has(o.name))continue;t((0,ie.join)(n,o.name))}else if(o.isFile()){let c=(0,ie.join)(n,o.name);try{let a=(0,ue.readFileSync)(c,"utf-8");e.push({path:(0,ie.relative)(r,c),content:a})}catch{}}}return t(r),e}var Yt=class{buildFiles(e){let t=[],n=[],s=[],o={},c={};for(let a of e.files){let l=a.path.split("/"),u=l[0];if(u==="agents")s.push({path:a.path.slice(7),content:a.content});else if(u==="mcps"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content);if(g.mcpServers&&typeof g.mcpServers=="object")Object.assign(o,g.mcpServers);else if(a.path.includes("resources/")){let h=l.indexOf("resources"),I=h>0?l[h-1]:l[1];o[I]=g}}catch{t.push(`Failed to parse MCP config: ${a.path}`)}}else if(u==="hooks"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content),h=a.path.replace(/\/[^/]+$/,"");Sa(g,c,h)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else u==="skills"||u==="commands"||u==="files"?n.push({path:a.path.slice(u.length+1),content:a.content}):n.push(a)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:c,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=e.resource.slug||e.resource.id,a=V(n,o),l=wa(e),u=(0,st.join)(a,...l),g=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(f=>!f.path.includes("/")),I=s.mainFiles.filter(f=>f.path.includes("/"));if(h.length>0){let f=h.find(d=>d.path==="README.md");f&&h.push({path:"SKILL.md",content:Ca(e,f.content)}),Z(u,h),g+=h.length}I.length>0&&(Z(a,I),g+=I.length)}if(s.agentFiles.length>0){let h=Q(n,o);Z(h,s.agentFiles),g+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Ea(Ee(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&nn(ke(n,o),s.hookEntries),{installDir:u,filesWritten:g,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],a=V(n,t==="project"),l=(0,st.join)(a,e),u=!1;return(0,he.existsSync)(l)&&((0,he.rmSync)(l,{recursive:!0,force:!0}),u=!0),u||o.push(`Collection directory not found at ${l}`),{removed:u,warnings:o}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,st.join)(s,e)}};function Sa(r,e,t){let n=mt(r);for(let[s,o]of Object.entries(n)){e[s]||(e[s]=[]);for(let c of o){let a=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[s].push(a)}}}function nn(r,e,t){let n={};if((0,he.existsSync)(r))try{n=JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{},o=new Set;t&&o.add(t);for(let c of Object.values(e))for(let a of c)a&&typeof a=="object"&&typeof a._sc=="string"&&o.add(a._sc);if(o.size>0)for(let[c,a]of Object.entries(s))Array.isArray(a)&&(s[c]=a.filter(l=>!l||typeof l!="object"||!o.has(l._sc)),s[c].length===0&&delete s[c]);for(let[c,a]of Object.entries(e)){Array.isArray(s[c])||(s[c]=[]);for(let l of a){let u=t&&typeof l=="object"&&l!==null?{...l,_sc:t}:l,g=JSON.stringify(u);s[c].some(I=>JSON.stringify(I)===g)||s[c].push(u)}}n.hooks=s,(0,he.mkdirSync)((0,st.dirname)(r),{recursive:!0}),(0,he.writeFileSync)(r,JSON.stringify(n,null,2)+`
|
|
38
|
-
`,"utf-8")}function sn(r,e){if(!(0,he.existsSync)(r))return!1;let t;try{t=JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,c]of Object.entries(n)){if(!Array.isArray(c))continue;let a=c.filter(l=>!l||typeof l!="object"||l._sc!==e);a.length!==c.length&&(s=!0,a.length===0?delete n[o]:n[o]=a)}return s&&(t.hooks=n,(0,he.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
39
|
-
`,"utf-8")
|
|
40
|
-
`,"utf-8")}function
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`,"utf-8")}function
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
`)}function
|
|
48
|
-
|
|
34
|
+
`,"utf8")}catch{}}async function ii(r=!1){if(!ve().telemetry)return{uploaded:0};if(!U())return{uploaded:0};let e=fc();if(e.length===0)return{uploaded:0};let t=e.slice(0,cc),n=await F("/api/cli/telemetry",{events:t},1e4);if(n.ok){if(dc(lc),!r){let s=n.data?.accepted??0;A()?L("telemetry",{uploaded:s}):s>0&&w(`Uploaded ${s} usage event${s===1?"":"s"}`)}return{uploaded:n.data?.accepted??0}}return!r&&!A()&&R("Telemetry upload failed \u2014 will retry next session"),{uploaded:0}}function pc(r){if(!r)return null;try{let e=(0,Pt.join)(oi(),"manifest.json"),t=(0,_e.readFileSync)(e,"utf8"),n=JSON.parse(t),s=r.toLowerCase();return n.installations?.find(o=>o.slug===s)??null}catch{return null}}function mc(r){let e=Pn();try{if((0,_e.existsSync)(e)&&(0,_e.statSync)(e).size>uc)return;(0,_e.appendFileSync)(e,JSON.stringify(r)+`
|
|
35
|
+
`,"utf8")}catch{}}async function ai(){if(!ve().telemetry)return;let r=await new Promise(c=>{let a="";process.stdin.setEncoding("utf8"),process.stdin.on("data",l=>{a+=l}),process.stdin.on("end",()=>c(a)),setTimeout(()=>c(a),5e3)}),e;try{e=JSON.parse(r)}catch{return}let t=e.tool_name;if(t!=="Skill"&&t!=="Agent")return;let n=t==="Skill"?e.tool_input?.skill:e.tool_input?.subagent_type,s=pc(n);if(!s||!s.resourceId)return;let o={v:1,ts:new Date().toISOString(),sid:e.session_id??"",event:t==="Skill"?"skill_invoked":"agent_invoked",slug:s.slug??n??"",rid:s.resourceId,ver:s.sha??"",ok:t==="Skill"?e.tool_response?.success!==!1:e.tool_response?.status==="completed"};t==="Agent"&&(e.tool_response?.totalDurationMs!=null&&(o.dur_ms=e.tool_response.totalDurationMs),e.tool_response?.totalTokens!=null&&(o.tokens=e.tool_response.totalTokens)),mc(o)}function Tn(r){let e=r.command("telemetry").description("Manage usage telemetry");e.command("push").description("Upload local usage data to Shared Context").option("--quiet","Suppress output").action(async t=>{await ii(t.quiet)}),e.command("collect").description("Append a PostToolUse event from stdin to local usage buffer").action(async()=>{try{await ai()}catch{}process.exit(0)})}var _e,Pt,Rn,cc,lc,uc,jn=be(()=>{"use strict";_e=require("fs"),Pt=require("path"),Rn=require("os");le();ge();ce();cc=1e3,lc=100,uc=10*1024*1024});var Jn=we(Zn(),1),{program:Pc,createCommand:Tc,createArgument:jc,createOption:Dc,CommanderError:Nc,InvalidArgumentError:$c,InvalidOptionArgumentError:Lc,Command:Kn,Argument:Fc,Option:Mc,Help:Hc}=Jn.default;ce();var ct=require("fs"),Xe=require("path"),Ho=require("os");ge();le();ce();var Gr=require("fs"),Oe=require("path"),We=require("os"),ut=[{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 $e(r){if(r){let n=ut.find(o=>o.id===r);if(n)return n;let s=ut.find(o=>o.dir===`.${r}`||o.dir===r);return s||null}for(let n of ut)if(n.envVars.some(s=>process.env[s]))return n;let e=(0,We.homedir)(),t=[];for(let n of ut)(0,Gr.existsSync)((0,Oe.join)(e,n.dir))&&t.push(n);return t.length===1?t[0]:null}function qe(){let r=[],e=(0,We.homedir)();for(let t of ut)(t.envVars.some(n=>process.env[n])||(0,Gr.existsSync)((0,Oe.join)(e,t.dir)))&&r.push(t);return r}function Ge(){let r=qe();return r.length>1?`Multiple AI agents detected (${r.map(e=>e.label).join(", ")}). Use --agent to specify: ${r.map(e=>e.id).join(", ")}`:`No AI agent detected. Use --agent to specify one (${ut.map(e=>e.id).join(", ")})`}function V(r,e){return e?(0,Oe.join)(process.cwd(),r.dir,r.skillsSubdir):(0,Oe.join)((0,We.homedir)(),r.dir,r.skillsSubdir)}function Q(r,e){return e?(0,Oe.join)(process.cwd(),r.dir,"agents"):(0,Oe.join)((0,We.homedir)(),r.dir,"agents")}function Ee(r,e){return e?(0,Oe.join)(process.cwd(),".mcp.json"):r.id==="claude-code"?(0,Oe.join)((0,We.homedir)(),".claude.json"):r.id==="cursor"?(0,Oe.join)((0,We.homedir)(),".cursor","mcp.json"):(0,Oe.join)(process.cwd(),".mcp.json")}function ke(r,e){return e?(0,Oe.join)(process.cwd(),r.dir,"settings.json"):(0,Oe.join)((0,We.homedir)(),r.dir,"settings.json")}var he=require("fs"),ot=require("path");var ue=require("fs"),ie=require("path"),Ro=require("crypto"),Po=require("readline");le();var $s=require("http"),Ls=require("crypto");ge();le();ge();ce();async function Fs(r){let e=await F("/api/cli/auth",{code:r});return e.ok?(It({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()}),A()?L("login",{email:e.data.user.email,org:e.data.org.slug}):w(`Logged in as ${e.data.user.email} (org: ${e.data.org.name})`),!0):(A()?D("login",e.error.code,e.error.message):R(`Login failed: ${e.error.message}`),!1)}async function mn(){let r=(0,Ls.randomBytes)(16).toString("hex");return new Promise(e=>{let t=(0,$s.createServer)((n,s)=>{let o=new URL(n.url||"/","http://localhost"),c=o.searchParams.get("code"),a=o.searchParams.get("state");if(!c||a!==r){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(),Fs(c).then(e)});t.listen(0,"127.0.0.1",async()=>{let n=t.address();if(!n||typeof n=="string"){t.close(),e(!1);return}let s=n.port,c=`${ve().apiBase||"https://sharedcontext.ai"}/cli/login?port=${s}&state=${r}`;A()||(w("Opening browser for authentication..."),w(`If the browser doesn't open, visit: ${c}`));try{let a=(await Promise.resolve().then(()=>(Ns(),Ds))).default;await a(c)}catch{A()||w(`Could not open browser. Please visit:
|
|
36
|
+
${c}`)}setTimeout(()=>{t.close(),A()||R("Login timed out after 5 minutes."),e(!1)},300*1e3)})})}function Ms(r){r.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 Fs(e.code):t=await mn(),process.exit(t?0:1)})}var Co=require("child_process"),wo=require("fs"),bo=require("path"),Io=require("os"),Ao=we(Eo());le();var Ra={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};function Xt(r){return Ra[r]||"directory"}function Qt(r){let t={"claude-code":"claude",cursor:"cursor","gemini-cli":"gemini"}[r];if(!t)return null;try{return(0,Co.execSync)(`which ${t}`,{stdio:"pipe"}),t}catch{return null}}async function er(r,e){let t=await qr(r),n=(0,bo.join)((0,Io.tmpdir)(),`sc-plugin-${e}-${Date.now()}`);return(0,wo.mkdirSync)(n,{recursive:!0}),new Ao.default(t).extractAllTo(n,!0),n}function tr(r){return{"claude-code":"claude","gemini-cli":"gemini",cursor:"cursor"}[r]||"claude"}ge();ce();function gt(r){let e={};if(!r||typeof r!="object")return e;let t=r;if(Array.isArray(t.hooks)){for(let s of t.hooks){if(!s||typeof s!="object")continue;let o=s,c=typeof o.event=="string"?o.event:null,a=typeof o.command=="string"?o.command:null;!c||!a||(e[c]||(e[c]=[]),e[c].push({hooks:[{type:"command",command:a}]}))}return e}let n=t.hooks&&typeof t.hooks=="object"&&!Array.isArray(t.hooks)?t.hooks:t;for(let[s,o]of Object.entries(n))if(!(s==="name"||s==="description")&&Array.isArray(o)){e[s]||(e[s]=[]);for(let c of o)e[s].push(c)}return e}var De=require("fs"),kt=require("path"),Cn=".shared-context",wn="project.json";function Ie(){let r=(0,kt.join)(process.cwd(),Cn,wn);if(!(0,De.existsSync)(r))return null;try{let e=JSON.parse((0,De.readFileSync)(r,"utf-8"));return e.projectId&&e.projectName&&e.projectSlug?e:null}catch{return null}}function st(r){let e=(0,kt.join)(process.cwd(),Cn);(0,De.mkdirSync)(e,{recursive:!0}),(0,De.writeFileSync)((0,kt.join)(e,wn),JSON.stringify(r,null,2)+`
|
|
37
|
+
`,"utf-8")}function _o(){let r=(0,kt.join)(process.cwd(),Cn,wn);return(0,De.existsSync)(r)?((0,De.unlinkSync)(r),!0):!1}var To={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function xo(r){return(0,Ro.createHash)("sha256").update(r,"utf-8").digest("hex")}function J(r,e,t={}){let n=(0,ie.resolve)(r),s={},o=[],c=t.baselineHashes,a=t.dryRun===!0;for(let l of e){let u=(0,ie.resolve)((0,ie.join)(r,l.path));if(!u.startsWith(n+"/")&&u!==n)throw new Error(`Invalid file path: ${l.path}`);if(c?.[l.path]&&(0,ue.existsSync)(u)){let g=(0,ue.readFileSync)(u,"utf-8");if(xo(g)!==c[l.path]){let I=Pa(r,l.path,g,a);o.push({filePath:l.path,preservedPath:I})}}s[l.path]=xo(l.content),a||((0,ue.mkdirSync)((0,ie.dirname)(u),{recursive:!0}),(0,ue.writeFileSync)(u,l.content,"utf-8"))}return{contentHashes:s,preserved:o}}function Pa(r,e,t,n){let s=(0,ie.join)(r,".local"),o=(0,ie.join)(s,e);if((0,ue.existsSync)(o)){let c=new Date().toISOString().replace(/[:.]/g,"-"),a=(0,ie.dirname)(o),l=e.split("/").pop()||"file",u=l.lastIndexOf("."),g=u>0?l.slice(0,u):l,h=u>0?l.slice(u):"";o=(0,ie.join)(a,`${g}-${c}${h}`)}return n||((0,ue.mkdirSync)((0,ie.dirname)(o),{recursive:!0}),(0,ue.writeFileSync)(o,t,"utf-8")),o}function bn(r){let e=r.resource.slug||r.resource.id;return`${To[r.resource.resourceType]||r.resource.resourceType+"s"}/${e}`}function vo(r,e,t,n,s){let o=(0,ie.join)(r,e);if(!(0,ue.existsSync)(o))return{slug:e,renamed:!1};if(!s.installations.find(l=>{let u=l.installPath.split("/");return u[u.length-1]===e&&l.resourceId!==t}))return{slug:e,renamed:!1};let a=n.resource.orgSlug||n.resource.githubOwner||n.resource.id.slice(0,8);return{slug:`${e}-${a}`,renamed:!0}}function rr(r,e,t){let n=t.files.find(u=>u.path.endsWith(".json")&&!u.path.includes("/"))||t.files.find(u=>u.path.endsWith(".json")&&u.path.includes("resources/"));if(!n)throw new Error("MCP package does not contain a config file");let s=JSON.parse(n.content),o=Ee(r,e),c=t.resource.slug||t.resource.id,a={};if((0,ue.existsSync)(o))try{a=JSON.parse((0,ue.readFileSync)(o,"utf-8"))}catch{a={}}let l=typeof a.mcpServers=="object"&&a.mcpServers&&!Array.isArray(a.mcpServers)?a.mcpServers:{};s.mcpServers&&typeof s.mcpServers=="object"?Object.assign(l,s.mcpServers):l[c]=s,a.mcpServers=l,(0,ue.mkdirSync)((0,ie.dirname)(o),{recursive:!0}),(0,ue.writeFileSync)(o,JSON.stringify(a,null,2)+`
|
|
38
|
+
`,"utf-8")}function Ta(r,e,t,n){let s=t.files.find(l=>l.path.endsWith(".json")&&!l.path.includes("/"));if(!s)throw new Error("Hook package does not contain a hook.json file");let o=JSON.parse(s.content),c=ke(r,e),a=gt(o);if(Object.keys(a).length===0)throw new Error("Hook package does not contain any hook event handlers");return _n(c,a,n),c}function In(r,e,t,n={}){let s=r.slug||r.id,o=To[r.resourceType]||r.resourceType+"s",c=e.orgSlug?`${e.orgSlug}/`:"";return{resourceId:r.id,slug:s,installPath:`${o}/${c}${s}`,title:r.title,sha:r.latestSha||"",scope:n.projectId?"project":"global",agent:t,installedAt:new Date().toISOString(),collectionId:e.id,resourceType:r.resourceType,latestSha:r.latestSha||void 0,serverSynced:!0,...n.projectId?{projectId:n.projectId}:{}}}async function An(r,e,t){let n=[],s=[],o=r.resource.slug||r.resource.id,c=bn(r),a,l="decomposed",u,g=!1,h={},I=[],f=t.dryRun===!0;if(r.resource.resourceType==="agent"){let d=Q(e,t.project),E=vo(d,o,r.resource.id,r,t.manifest);E.renamed&&(o=E.slug,c=bn({...r,resource:{...r.resource,slug:o}}),g=!0),a=(0,ie.join)(d,o);let S=J(a,r.files,{baselineHashes:t.baselineHashes,dryRun:f});h=S.contentHashes,I=S.preserved}else if(r.resource.resourceType==="mcp")a="",f||rr(e,t.project,r);else if(r.resource.resourceType==="hook")a="",f||Ta(e,t.project,r,c);else{let d=V(e,t.project);if(r.resource.resourceType!=="collection"){let E=vo(d,o,r.resource.id,r,t.manifest);E.renamed&&(o=E.slug,c=bn({...r,resource:{...r.resource,slug:o}}),g=!0)}if(a=(0,ie.join)(d,o),r.resource.resourceType==="collection"){let E=!1;try{let S=r.resource.slug||r.resource.id,C=r.resource.orgSlug||"",p=tr(e.id),i=t.authed?`/api/cli/resource/collections/${C}/${S}?format=plugin&platform=${p}`:`/api/public/resource/collections/${C}/${S}?format=plugin&platform=${p}`,m=await er(i,S),y=Na(m,e.id);if(y.length>0){let x={...r,files:y},b=await Le(e).install(x,t.project?"project":"user",e);a=b.installDir,l="plugin",u=m,E=!0,s.push("Installed from plugin package");for(let v of b.warnings)n.push(v)}}catch(S){n.push(`Plugin install failed, falling back to decomposed: ${S}`)}if(!E){let C=await Le(e).install(r,t.project?"project":"user",e);a=C.installDir;for(let p of C.warnings)n.push(p)}}else{let E=J(a,r.files,{baselineHashes:t.baselineHashes,dryRun:f});h=E.contentHashes,I=E.preserved}}return{installDir:a,installPath:c,installMode:l,pluginDir:u,slug:o,renamed:g,warnings:n,notes:s,contentHashes:h,preserved:I}}async function ja(r){let e=(0,Po.createInterface)({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close();let s=n.trim().toLowerCase();t(s===""||s==="y"||s==="yes")})})}function jo(r){r.command("install <path>").description("Install a resource (e.g., skills/acme/api-testing)").option("--code <code>","Bootstrap CLI auth using an auth code from the web app").action(async(e,t,n)=>{let s=n.optsWithGlobals(),o=$e(s.agent);if(!o){let i=Ge();A()?D("install","NO_AGENTS",i):R(i),process.exit(1)}if(s.code){let i=await F("/api/cli/auth",{code:s.code});i.ok?(It({token:i.data.token,email:i.data.user.email,orgId:i.data.org.id,orgSlug:i.data.org.slug,orgName:i.data.org.name,createdAt:new Date().toISOString()}),A()||w(`Authenticated as ${i.data.user.email}`)):U()?A()||w("Auth code already used, continuing with saved credentials."):(A()?D("install",i.error.code,i.error.message):R(`Auth failed: ${i.error.message}`),process.exit(1))}let c=U(),l=await Z(`${c?"/api/cli/resource":"/api/public/resource"}/${e}`);l.ok||(l.error.code==="AUTH_REQUIRED"&&!c?(A()&&(D("install","AUTH_REQUIRED",l.error.message),process.exit(1)),process.stdin.isTTY||(R(`${l.error.message} Run 'shared-context-ai login' and re-run.`),process.exit(1)),w(l.error.message),await ja("Sign in now? [Y/n] ")||process.exit(1),await mn()||process.exit(1),c=!0,l=await Z(`/api/cli/resource/${e}`),l.ok||(R(`Install failed: ${l.error.message}`),process.exit(1))):(A()?D("install",l.error.code,l.error.message):R(`Install failed: ${l.error.message}`),process.exit(1)));let u=l.data,g;try{g=await An(u,o,{project:!!s.project,manifest:z(),authed:c})}catch(i){A()?D("install","WRITE_FAILED",`Failed to install: ${i}`):R(`Failed to install: ${i}`),process.exit(1)}if(g.renamed&&!A()&&w(`Note: Renamed to "${g.slug}" (collision with existing resource)`),!A()){for(let i of g.notes)w(i);for(let i of g.warnings)R(`Warning: ${i}`)}let h=g.installDir,I=g.installPath,f=g.slug,d=g.installMode,E=g.pluginDir,S;if(c&&u.resource.latestSha){let i=await F("/api/cli/install",{resourceId:u.resource.id,agentPlatform:o.platform,installedSha:u.resource.latestSha});i.ok||(S=`Could not record install on server: ${i.error.message}`,A()||R(`Warning: ${S}`))}let C=s.project?Ie():null;C&&c&&await F(`/api/cli/projects/${C.projectId}/resources`,{resourceId:u.resource.id}).catch(()=>{});let p=u.resource.resourceType==="collection";if(me({resourceId:u.resource.id,slug:f,installPath:I,title:u.resource.title,sha:u.resource.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),latestSha:u.resource.latestSha||void 0,resourceType:u.resource.resourceType,serverSynced:!0,...Object.keys(g.contentHashes).length>0?{contentHashes:g.contentHashes}:{},...p?{pluginFormat:Xt(o.id),memberCount:u.memberResources?.length,installMode:d,pluginDir:E}:{},...C?{projectId:C.projectId}:{}}),u.memberResources&&u.resource.resourceType==="collection"){if(d==="decomposed")for(let i of u.memberResources)me(In(i,u.resource,o.id,{projectId:C?.projectId}));for(let i of u.memberResources)c&&i.latestSha&&await F("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{})}if(Ve(),A())L("install",{installPath:I,title:u.resource.title,path:h||void 0,files:u.files.length,...u.resource.resourceType==="mcp"?{mcpConfigPath:Ee(o,!!s.project)}:{},...u.resource.resourceType==="hook"?{settingsPath:ke(o,!!s.project)}:{},...u.memberResources?{memberResources:u.memberResources.map(i=>({title:i.title,resourceType:i.resourceType,slug:i.slug}))}:{},...S&&{warning:S}});else{if(u.resource.resourceType==="mcp"?w(`Installed MCP "${u.resource.title}" to ${Ee(o,!!s.project)}`):u.resource.resourceType==="hook"?w(`Installed hook "${u.resource.title}" to ${ke(o,!!s.project)}`):u.memberResources&&u.memberResources.length>0?w(`Installed "${u.resource.title}" (${u.memberResources.length} resources)`):w(`Installed "${u.resource.title}" to ${h}`),u.resource.resourceType!=="mcp"&&u.resource.resourceType!=="hook"&&!(u.memberResources&&u.memberResources.length>0)&&w(` ${u.files.length} file${u.files.length===1?"":"s"} written`),u.memberResources&&u.memberResources.length>0){let i={};for(let y of u.memberResources){let x=y.resourceType||"other";i[x]||(i[x]=[]),i[x].push(y.title)}let m={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections",file:"Files"};w("");for(let[y,x]of Object.entries(i)){let _=m[y]||y;w(` ${_}: ${x.join(", ")}`)}}c||(w(""),w("Tip: run 'shared-context-ai login' to track installs and get update notifications."))}})}var Da={"claude-code":[".claude"],cursor:[".cursor"],"gemini-cli":[".gemini"],codex:[".codex"],antigravity:[".gemini"]},Oo=new Set(["skills","commands","agents","hooks","mcps"]);function Na(r,e){let t=Da[e]||[];for(let o of t){let c=(0,ie.join)(r,o);if((0,ue.existsSync)(c)){let l=ko(c).filter(u=>Oo.has(u.path.split("/")[0]));if(l.length>0)return l}}return ko(r).filter(o=>Oo.has(o.path.split("/")[0]))}var $a=new Set([".git","node_modules","__pycache__",".venv"]);function ko(r){let e=[];function t(n){let s;try{s=(0,ue.readdirSync)(n,{withFileTypes:!0})}catch{return}for(let o of s)if(o.isDirectory()){if($a.has(o.name))continue;t((0,ie.join)(n,o.name))}else if(o.isFile()){let c=(0,ie.join)(n,o.name);try{let a=(0,ue.readFileSync)(c,"utf-8");e.push({path:(0,ie.relative)(r,c),content:a})}catch{}}}return t(r),e}var nr=class{buildFiles(e){let t=[],n=[],s=[],o={},c={};for(let a of e.files){let l=a.path.split("/"),u=l[0];if(u==="agents")s.push({path:a.path.slice(7),content:a.content});else if(u==="mcps"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content);if(g.mcpServers&&typeof g.mcpServers=="object")Object.assign(o,g.mcpServers);else if(a.path.includes("resources/")){let h=l.indexOf("resources"),I=h>0?l[h-1]:l[1];o[I]=g}}catch{t.push(`Failed to parse MCP config: ${a.path}`)}}else if(u==="hooks"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content),h=a.path.replace(/\/[^/]+$/,"");La(g,c,h)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else u==="skills"||u==="commands"||u==="files"?n.push({path:a.path.slice(u.length+1),content:a.content}):n.push(a)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:c,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=e.resource.slug||e.resource.id,a=V(n,o),l=Ha(e),u=(0,ot.join)(a,...l),g=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(f=>!f.path.includes("/")),I=s.mainFiles.filter(f=>f.path.includes("/"));if(h.length>0){let f=h.find(d=>d.path==="README.md");f&&h.push({path:"SKILL.md",content:Ma(e,f.content)}),J(u,h),g+=h.length}I.length>0&&(J(a,I),g+=I.length)}if(s.agentFiles.length>0){let h=Q(n,o);J(h,s.agentFiles),g+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Fa(Ee(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&_n(ke(n,o),s.hookEntries),{installDir:u,filesWritten:g,warnings:s.warnings}}async uninstall(e,t,n,s){let o=[],a=V(n,t==="project"),l=(0,ot.join)(a,e),u=!1;return(0,he.existsSync)(l)&&((0,he.rmSync)(l,{recursive:!0,force:!0}),u=!0),u||o.push(`Collection directory not found at ${l}`),{removed:u,warnings:o}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,ot.join)(s,e)}};function La(r,e,t){let n=gt(r);for(let[s,o]of Object.entries(n)){e[s]||(e[s]=[]);for(let c of o){let a=t&&typeof c=="object"&&c!==null?{...c,_sc:t}:c;e[s].push(a)}}}function _n(r,e,t){let n={};if((0,he.existsSync)(r))try{n=JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch{n={}}let s=typeof n.hooks=="object"&&n.hooks&&!Array.isArray(n.hooks)?n.hooks:{},o=new Set;t&&o.add(t);for(let c of Object.values(e))for(let a of c)a&&typeof a=="object"&&typeof a._sc=="string"&&o.add(a._sc);if(o.size>0)for(let[c,a]of Object.entries(s))Array.isArray(a)&&(s[c]=a.filter(l=>!l||typeof l!="object"||!o.has(l._sc)),s[c].length===0&&delete s[c]);for(let[c,a]of Object.entries(e)){Array.isArray(s[c])||(s[c]=[]);for(let l of a){let u=t&&typeof l=="object"&&l!==null?{...l,_sc:t}:l,g=JSON.stringify(u);s[c].some(I=>JSON.stringify(I)===g)||s[c].push(u)}}n.hooks=s,(0,he.mkdirSync)((0,ot.dirname)(r),{recursive:!0}),(0,he.writeFileSync)(r,JSON.stringify(n,null,2)+`
|
|
39
|
+
`,"utf-8")}function xn(r,e){if(!(0,he.existsSync)(r))return!1;let t;try{t=JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch{return!1}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:null;if(!n)return!1;let s=!1;for(let[o,c]of Object.entries(n)){if(!Array.isArray(c))continue;let a=c.filter(l=>!l||typeof l!="object"||l._sc!==e);a.length!==c.length&&(s=!0,a.length===0?delete n[o]:n[o]=a)}return s&&(t.hooks=n,(0,he.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
40
|
+
`,"utf-8")),s}function Fa(r,e){let t={};if((0,he.existsSync)(r))try{t=JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,he.mkdirSync)((0,ot.dirname)(r),{recursive:!0}),(0,he.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
41
|
+
`,"utf-8")}function Ma(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
|
|
42
|
+
`)}function Ha(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Ae=require("fs"),it=require("path");var Ua={SessionStart:"SessionStart",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",Stop:"AfterAgent",UserPromptSubmit:"BeforeAgent",PreCompact:"PreCompress"},sr=class{buildFiles(e){let t=[],n=[],s=[],o={},c={};for(let a of e.files){let l=a.path.split("/"),u=l[0];if(u==="agents")s.push({path:a.path.slice(7),content:a.content});else if(u==="mcps"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content);if(g.mcpServers&&typeof g.mcpServers=="object")Object.assign(o,g.mcpServers);else if(a.path.includes("resources/")){let h=l.indexOf("resources"),I=h>0?l[h-1]:l[1];o[I]=g}}catch{t.push(`Failed to parse MCP config: ${a.path}`)}}else if(u==="hooks"){if(a.path.endsWith(".json"))try{let g=JSON.parse(a.content),h=a.path.replace(/\/[^/]+$/,"");Ba(g,c,h)}catch{t.push(`Failed to parse hook config: ${a.path}`)}}else u==="skills"||u==="commands"||u==="files"?n.push({path:a.path.slice(u.length+1),content:a.content}):n.push(a)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:c,customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=e.resource.slug||e.resource.id,a=V(n,o),l=Ga(e),u=(0,it.join)(a,...l),g=0;if(s.mainFiles.length>0){let h=s.mainFiles.filter(f=>!f.path.includes("/")),I=s.mainFiles.filter(f=>f.path.includes("/"));if(h.length>0){let f=h.find(d=>d.path==="README.md");f&&h.push({path:"SKILL.md",content:qa(e,f.content)}),J(u,h),g+=h.length}I.length>0&&(J(a,I),g+=I.length)}if(s.agentFiles.length>0){let h=Q(n,o);J(h,s.agentFiles),g+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Wa(Ee(n,o),s.mcpEntries),Object.keys(s.hookEntries).length>0&&Va(ke(n,o),s.hookEntries),{installDir:u,filesWritten:g,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=V(n,t==="project"),a=(0,it.join)(c,e),l=!1;return(0,Ae.existsSync)(a)&&((0,Ae.rmSync)(a,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${a}`),{removed:l,warnings:s}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,it.join)(s,e)}};function Ba(r,e,t){let n=gt(r);for(let[s,o]of Object.entries(n)){let c=Ua[s]||s;e[c]||(e[c]=[]);for(let a of o){let l=t&&typeof a=="object"&&a!==null?{...a,_sc:t}:a;e[c].push(l)}}}function Va(r,e){let t={};if((0,Ae.existsSync)(r))try{t=JSON.parse((0,Ae.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.hooks=="object"&&t.hooks&&!Array.isArray(t.hooks)?t.hooks:{},s=new Set;for(let o of Object.values(e))for(let c of o)c&&typeof c=="object"&&typeof c._sc=="string"&&s.add(c._sc);if(s.size>0)for(let[o,c]of Object.entries(n))Array.isArray(c)&&(n[o]=c.filter(a=>!a||typeof a!="object"||!s.has(a._sc)),n[o].length===0&&delete n[o]);for(let[o,c]of Object.entries(e)){Array.isArray(n[o])||(n[o]=[]);for(let a of c){let l=JSON.stringify(a);n[o].some(g=>JSON.stringify(g)===l)||n[o].push(a)}}t.hooks=n,(0,Ae.mkdirSync)((0,it.dirname)(r),{recursive:!0}),(0,Ae.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
43
|
+
`,"utf-8")}function Wa(r,e){let t={};if((0,Ae.existsSync)(r))try{t=JSON.parse((0,Ae.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Ae.mkdirSync)((0,it.dirname)(r),{recursive:!0}),(0,Ae.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
44
|
+
`,"utf-8")}function qa(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
|
|
45
|
+
`)}function Ga(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var ye=require("fs"),He=require("path");var or=class{buildFiles(e){let t=[],n=[],s=[],o={},c=[],a=e.resource.slug||e.resource.id;for(let l of e.files){let u=l.path.split("/"),g=u[0];if(g==="agents")s.push({path:l.path.slice(7),content:l.content});else if(g==="mcps"){if(l.path.endsWith(".json"))try{let h=JSON.parse(l.content);if(h.mcpServers&&typeof h.mcpServers=="object")Object.assign(o,h.mcpServers);else if(l.path.includes("resources/")){let I=u.indexOf("resources"),f=I>0?u[I-1]:u[1];o[f]=h}}catch{t.push(`Failed to parse MCP config: ${l.path}`)}}else g==="hooks"?t.push(`Hooks are not supported by Cursor (skipped: ${l.path})`):g==="skills"||g==="commands"||g==="files"?n.push({path:l.path.slice(g.length+1),content:l.content}):n.push(l)}return{mainFiles:n,agentFiles:s,mcpEntries:o,hookEntries:{},customFiles:c,warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=V(n,o),a=Ja(e),l=(0,He.join)(c,...a),u=0;if(s.mainFiles.length>0){let g=s.mainFiles.filter(I=>!I.path.includes("/")),h=s.mainFiles.filter(I=>I.path.includes("/"));if(g.length>0){let I=g.find(f=>f.path==="README.md");I&&g.push({path:"SKILL.md",content:Za(e,I.content)}),J(l,g),u+=g.length}h.length>0&&(J(c,h),u+=h.length)}if(s.agentFiles.length>0){let g=Q(n,o);J(g,s.agentFiles),u+=s.agentFiles.length}for(let g of s.customFiles)(0,ye.mkdirSync)((0,He.dirname)(g.absolutePath),{recursive:!0}),(0,ye.writeFileSync)(g.absolutePath,g.content,"utf-8"),u++;return Object.keys(s.mcpEntries).length>0&&za(Ee(n,o),s.mcpEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=V(n,t==="project"),a=(0,He.join)(c,e),l=!1;(0,ye.existsSync)(a)&&((0,ye.rmSync)(a,{recursive:!0,force:!0}),l=!0);let u=(0,He.join)(homedir(),".cursor","rules");if((0,ye.existsSync)(u))try{let g=(0,ye.readdirSync)(u);for(let h of g)h.startsWith(`${e}-`)&&h.endsWith(".mdc")&&((0,ye.unlinkSync)((0,He.join)(u,h)),l=!0)}catch{s.push("Could not clean up Cursor rules")}return l||s.push(`Collection not found for Cursor at ${a}`),{removed:l,warnings:s}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,He.join)(s,e)}};function za(r,e){let t={};if((0,ye.existsSync)(r))try{t=JSON.parse((0,ye.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,ye.mkdirSync)((0,He.dirname)(r),{recursive:!0}),(0,ye.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
46
|
+
`,"utf-8")}function Za(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
|
|
47
|
+
`)}function Ja(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var cr=require("fs"),ir=require("path");var ar=class{buildFiles(e){let t=[],n=[],s=[];for(let o of e.files){let a=o.path.split("/")[0];a==="agents"?s.push({path:o.path.slice(7),content:o.content}):a==="mcps"?t.push(`MCP servers are not yet supported by Codex adapter (skipped: ${o.path})`):a==="hooks"?t.push(`Hooks are not supported by Codex (skipped: ${o.path})`):a==="commands"?t.push(`Commands are not supported by Codex (skipped: ${o.path})`):a==="skills"||a==="files"?n.push({path:o.path.slice(a.length+1),content:o.content}):n.push(o)}return{mainFiles:n,agentFiles:s,mcpEntries:{},hookEntries:{},customFiles:[],warnings:t}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=V(n,o),a=Ya(e),l=(0,ir.join)(c,...a),u=0;if(s.mainFiles.length>0){let g=s.mainFiles.filter(I=>!I.path.includes("/")),h=s.mainFiles.filter(I=>I.path.includes("/"));if(g.length>0){let I=g.find(f=>f.path==="README.md");I&&g.push({path:"SKILL.md",content:Ka(e,I.content)}),J(l,g),u+=g.length}h.length>0&&(J(c,h),u+=h.length)}if(s.agentFiles.length>0){let g=Q(n,o);J(g,s.agentFiles),u+=s.agentFiles.length}return{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,n){let s=[],c=V(n,t==="project"),a=(0,ir.join)(c,e),l=!1;return(0,cr.existsSync)(a)&&((0,cr.rmSync)(a,{recursive:!0,force:!0}),l=!0),l||s.push(`Collection directory not found at ${a}`),{removed:l,warnings:s}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,ir.join)(s,e)}};function Ka(r,e){let t=r.resource.title,n=r.resource.description||"",s=["---",`name: ${t}`];return n&&s.push(`description: ${n}`),s.push("user-invocable: true"),s.push("---","",e),s.join(`
|
|
48
|
+
`)}function Ya(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}var Ne=require("fs"),ht=require("path");var lr=class{buildFiles(e){let t=[],n=[],s={};for(let o of e.files){let c=o.path.split("/"),a=c[0];if(a==="agents")n.push({path:o.path.slice(7),content:o.content});else if(a==="mcps"){if(o.path.endsWith(".json"))try{let l=JSON.parse(o.content);if(l.mcpServers&&typeof l.mcpServers=="object")Object.assign(s,l.mcpServers);else if(o.path.includes("resources/")){let u=c.indexOf("resources"),g=u>0?c[u-1]:c[1];s[g]=l}}catch{}}else a==="skills"||a==="commands"||a==="hooks"||a==="files"?t.push({path:o.path.slice(a.length+1),content:o.content}):t.push(o)}return{mainFiles:t,agentFiles:n,mcpEntries:s,hookEntries:{},customFiles:[],warnings:[]}}async install(e,t,n){let s=this.buildFiles(e),o=t==="project",c=V(n,o),a=Qa(e),l=(0,ht.join)(c,...a),u=0;if(s.mainFiles.length>0){let g=s.mainFiles.filter(I=>!I.path.includes("/")),h=s.mainFiles.filter(I=>I.path.includes("/"));g.length>0&&(J(l,g),u+=g.length),h.length>0&&(J(c,h),u+=h.length)}if(s.agentFiles.length>0){let g=Q(n,o);J(g,s.agentFiles),u+=s.agentFiles.length}return Object.keys(s.mcpEntries).length>0&&Xa(Ee(n,o),s.mcpEntries),{installDir:l,filesWritten:u,warnings:s.warnings}}async uninstall(e,t,n){let o=V(n,t==="project"),c=(0,ht.join)(o,e),a=!1;return(0,Ne.existsSync)(c)&&((0,Ne.rmSync)(c,{recursive:!0,force:!0}),a=!0),{removed:a,warnings:[]}}describeLocation(e,t,n){let s=V(n,t==="project");return(0,ht.join)(s,e)}};function Xa(r,e){let t={};if((0,Ne.existsSync)(r))try{t=JSON.parse((0,Ne.readFileSync)(r,"utf-8"))}catch{t={}}let n=typeof t.mcpServers=="object"&&t.mcpServers&&!Array.isArray(t.mcpServers)?t.mcpServers:{};Object.assign(n,e),t.mcpServers=n,(0,Ne.mkdirSync)((0,ht.dirname)(r),{recursive:!0}),(0,Ne.writeFileSync)(r,JSON.stringify(t,null,2)+`
|
|
49
|
+
`,"utf-8")}function Qa(r){let e=r.resource.slug||r.resource.id;return r.resource.storageType==="github"&&r.resource.githubOwner?["external",r.resource.githubOwner,e]:r.resource.orgSlug?[r.resource.orgSlug,e]:[e]}function Le(r){switch(r.id){case"claude-code":return new nr;case"gemini-cli":case"antigravity":return new sr;case"cursor":return new or;case"codex":return new ar;default:return new lr}}var Do=`---
|
|
49
50
|
name: Context Manager
|
|
50
51
|
description: "Your AI chief of staff \u2014 distills expert knowledge into resources, finds off-the-shelf solutions, and manages your working context"
|
|
51
52
|
tools:
|
|
@@ -134,50 +135,49 @@ When building custom resources, follow these patterns:
|
|
|
134
135
|
- **Specificity over comprehensiveness** \u2014 Only include instructions that meaningfully change Claude's output
|
|
135
136
|
- **Filesystem as memory** \u2014 Design persistent storage so resources accumulate knowledge over time
|
|
136
137
|
- **Search before building** \u2014 Check the Shared Context library before creating from scratch
|
|
137
|
-
`;le();ge();var W=require("fs"),
|
|
138
|
+
`;le();ge();var W=require("fs"),Y=require("path"),Fo=require("crypto");var ur=".context-collection",fr="manifest.json";function No(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function ec(r,e){return{version:1,name:r.name||"Untitled Extension",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}function tc(r,e){return{version:1,name:r.name||"Untitled Plugin",description:r.description||void 0,resources:e.map(t=>t.resourceRef),...r.author?{author:typeof r.author=="string"?{name:r.author}:{name:r.author.name||"",url:r.author.url}}:{},...r.homepage?{homepage:r.homepage}:{},...r.license?{license:r.license}:{}}}var vn=[{path:`${ur}/${fr}`,converter:()=>{throw new Error("Use parseCollectionManifest for native format")},formatLabel:"Shared Context"},{path:".claude-plugin/plugin.json",converter:No,formatLabel:"Claude Plugin"},{path:".claude/plugin.json",converter:No,formatLabel:"Claude Plugin"},{path:"gemini-extension.json",converter:ec,formatLabel:"Gemini Extension"},{path:".cursor-plugin/plugin.json",converter:tc,formatLabel:"Cursor Plugin"}];var $o=[{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}],Lo=`${ur}/${fr}`;function at(r){let e={name:"",description:"",body:r};if(!r.startsWith(`---
|
|
138
139
|
`)&&!r.startsWith(`---\r
|
|
139
140
|
`))return e;let t=r.indexOf(`
|
|
140
141
|
---`,3);if(t===-1)return e;let n=r.slice(4,t),s=r.slice(t+4);e.body=s.replace(/^\r?\n/,"").replace(/^\r?\n/,"");let o={},c={},a=new Set(["requires","tools"]),l={},u=n.split(`
|
|
141
|
-
`),g=null,h=!1;for(let I=0;I<u.length;I++){let f=u[I];if(g&&/^\s+-\s/.test(f)){let p=f.replace(/^\s+-\s/,"").trim();if(p){let i=
|
|
142
|
+
`),g=null,h=!1;for(let I=0;I<u.length;I++){let f=u[I];if(g&&/^\s+-\s/.test(f)){let p=f.replace(/^\s+-\s/,"").trim();if(p){let i=yt(p);h?l[g].push(i):c[g].push(i)}continue}g=null,h=!1;let d=f.indexOf(":");if(d===-1)continue;let E=f.slice(0,d).trim(),S=f.slice(d+1).trim();if(!S&&E&&I+1<u.length&&/^\s+-\s/.test(u[I+1])){g=E,a.has(E)?(h=!0,l[E]=[]):(h=!1,c[E]=[]);continue}let C=E?S.match(/^([|>])([+-]?)\s*$/):null;if(C){let p=C[1],i=C[2],m=I+1;for(;m<u.length&&u[m].trim()==="";)m++;let y="";if(m<u.length){let x=u[m].match(/^(\s+)/);if(x){let _=x[1].length,b=[];for(;m<u.length;){let v=u[m];if(v.trim()===""){b.push(""),m++;continue}let k=v.match(/^(\s*)/);if(!k||k[1].length<_)break;b.push(v.slice(_)),m++}if(i!=="+")for(;b.length>0&&b[b.length-1]==="";)b.pop();if(p==="|")y=b.join(`
|
|
142
143
|
`);else for(let v=0;v<b.length;v++)v>0&&(y+=b[v]===""||b[v-1]===""?`
|
|
143
|
-
`:" "),y+=b[v]}}E==="name"||E==="title"?e.name=y:E==="description"?e.description=y:E==="skill_class"?e.skillClass=y:E==="service"?e.service=y:y&&(o[E]=y),I=m-1;continue}E==="name"||E==="title"?e.name=
|
|
144
|
-
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Ue(r){let e=La(r);return`sha256:${(0,ro.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Te(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ot(r){try{return(0,W.statSync)(r).isDirectory()}catch{return!1}}function an(r){try{return(0,W.readdirSync)(r).filter(e=>!e.startsWith(".")&&Ot((0,X.join)(r,e)))}catch{return[]}}function cn(r){try{return(0,W.readdirSync)(r).filter(e=>!e.startsWith(".")&&!Ot((0,X.join)(r,e)))}catch{return[]}}function ar(r,e){let t=[],n=[],s,o;function c(f,d){let E=[],S=[];for(let C of eo){let p=(0,X.join)(f,C.folder);if(!(0,W.existsSync)(p)||!Ot(p))continue;let i=d?`${d}/${C.folder}`:C.folder;if(C.folder==="files"){for(let m of cn(p)){if(!m.endsWith(".md"))continue;let y=(0,X.join)(p,m),x=(0,W.readFileSync)(y,"utf-8"),_=it(x),b=_.name||(0,X.basename)(m,".md"),v=`${i}/${(0,X.basename)(m,".md")}`;E.push({importPath:v,resourceType:"file",title:b,description:_.description||null,body:_.body,bodyHash:Ue(x),metadata:{}})}continue}if(C.mainFile===null)for(let m of cn(p)){if(!m.endsWith(".md"))continue;let y=(0,X.basename)(m,".md"),x=`${i}/${y}`;if(Ot((0,X.join)(p,y)))continue;let _=(0,W.readFileSync)((0,X.join)(p,m),"utf-8"),b=it(_),v=b.name||Te(y),k={};b.skillClass&&(k.skillClass=b.skillClass),b.service&&(k.service=b.service),b.requires?.length&&(k.requires=b.requires),b.tools?.length&&(k.tools=b.tools),b.fields&&Object.keys(b.fields).length&&(k.fields=b.fields),C.folder==="commands"&&(k.fields||(k.fields={}),k.fields["user-invocable"]="true"),E.push({importPath:x,resourceType:C.resourceType,title:v,description:b.description||null,body:b.body,bodyHash:Ue(_),metadata:k})}for(let m of an(p)){let y=C.mainFile||`${m}.md`,x=(0,X.join)(p,m,y);if(!(0,W.existsSync)(x)){if(C.mainFile===null)for(let K of an((0,X.join)(p,m))){let ae=`${K}.md`,O=(0,X.join)(p,m,K,ae);if(!(0,W.existsSync)(O))continue;let N=(0,W.readFileSync)(O,"utf-8"),M=it(N),q=M.name||Te(K),H={};M.skillClass&&(H.skillClass=M.skillClass),M.service&&(H.service=M.service),M.requires?.length&&(H.requires=M.requires),M.tools?.length&&(H.tools=M.tools),M.fields&&Object.keys(M.fields).length&&(H.fields=M.fields),E.push({importPath:`${i}/${K}`,resourceType:C.resourceType,title:q,description:M.description||null,body:M.body,bodyHash:Ue(N),metadata:H})}continue}let _=(0,W.readFileSync)(x,"utf-8"),b=`${i}/${m}`,v,k,P,j={},$=null;if(C.resourceType==="hook"||C.resourceType==="mcp"){try{let K=JSON.parse(_);v=K.name||Te(m),k=K.description||null}catch{v=Te(m),k=null}P=_}else if(C.resourceType==="collection"){let K=(0,X.join)(p,m,or,ir);if((0,W.existsSync)(K))try{let ae=JSON.parse((0,W.readFileSync)(K,"utf-8"));v=ae.name||Te(m),k=ae.description||null,P=_,ae.resources&&Array.isArray(ae.resources)&&S.push({collectionImportPath:b,memberImportPaths:ae.resources.map(O=>{let N=O.split("/");return N.length>=3?`${N[0]}/${N[N.length-1]}`:O})})}catch{v=Te(m),k=null,P=_}else $=it(_),v=$.name||Te(m),k=$.description||null,P=$.body,$.arrayFields?.resources&&S.push({collectionImportPath:b,memberImportPaths:$.arrayFields.resources.map(ae=>{let O=ae.split("/");return O.length>=3?`${O[0]}/${O[O.length-1]}`:ae})})}else $=it(_),v=$.name||Te(m),k=$.description||null,P=$.body,$.skillClass&&(j.skillClass=$.skillClass),$.service&&(j.service=$.service),$.requires?.length&&(j.requires=$.requires),$.tools?.length&&(j.tools=$.tools),$.fields&&Object.keys($.fields).length&&(j.fields=$.fields);C.folder==="commands"&&(j.fields||(j.fields={}),j.fields["user-invocable"]="true"),E.push({importPath:b,resourceType:C.resourceType,title:v,description:k,body:P,bodyHash:Ue(_),metadata:j})}}return{resources:E,memberships:S}}let a=c(r,"");t.push(...a.resources),n.push(...a.memberships);let l=new Set;e?.mcpConfigPath&&l.add(e.mcpConfigPath);let u=(0,X.join)(r,".mcp.json");(0,W.existsSync)(u)&&l.add(u);for(let f of l)if((0,W.existsSync)(f))try{let d=JSON.parse((0,W.readFileSync)(f,"utf-8"));if(d.mcpServers&&typeof d.mcpServers=="object")for(let[E,S]of Object.entries(d.mcpServers)){let C=`mcps/${E}`;if(t.some(m=>m.importPath===C))continue;let p=Te(E),i=JSON.stringify({name:p,description:`MCP server: ${E}`,mcpServers:{[E]:S}},null,2);t.push({importPath:C,resourceType:"mcp",title:p,description:`MCP server: ${E}`,body:i,bodyHash:Ue(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,W.existsSync)(e.settingsPath))try{let f=JSON.parse((0,W.readFileSync)(e.settingsPath,"utf-8"));if(f.hooks&&typeof f.hooks=="object"&&!Array.isArray(f.hooks)){let d={};for(let[E,S]of Object.entries(f.hooks))if(Array.isArray(S))for(let C of S){if(!C||typeof C!="object")continue;let p=C,i=p._sc;if(!i)continue;d[i]||(d[i]={}),d[i][E]||(d[i][E]=[]);let{_sc:m,...y}=p;d[i][E].push(y)}for(let[E,S]of Object.entries(d)){let C=E;if(t.some(y=>y.importPath===C))continue;let p=E.split("/").pop()||E,i=Te(p),m=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:S},null,2);t.push({importPath:C,resourceType:"hook",title:i,description:`Hook: ${i}`,body:m,bodyHash:Ue(m),metadata:{}})}}}catch{}for(let f of on){if(f.path===to)continue;let d=(0,X.join)(r,f.path);if((0,W.existsSync)(d)){try{let E=JSON.parse((0,W.readFileSync)(d,"utf-8"));if(s=s||E.name||void 0,o=f.formatLabel,!t.some(S=>S.resourceType==="collection")){let S=t.filter(y=>y.resourceType!=="collection").map(y=>({resourceRef:y.importPath})),C=f.converter(E,S),p=(0,X.join)(r,"README.md"),i=(0,W.existsSync)(p)?(0,W.readFileSync)(p,"utf-8"):"",m="collections/_root";t.push({importPath:m,resourceType:"collection",title:Te(C.name),description:C.description||null,body:i,bodyHash:Ue(i),metadata:{},manifestMetadata:{...C.author?{author:C.author}:{},...C.homepage?{homepage:C.homepage}:{},...C.license?{license:C.license}:{}}}),C.resources.length>0&&n.push({collectionImportPath:m,memberImportPaths:C.resources})}}catch{}break}}{let S=function(C,p,i){if(!(i>4))for(let m of an(C)){if(E.has(m))continue;let y=(0,X.join)(C,m),x=p?`${p}/${m}`:m;for(let _ of on){if(_.path===to)continue;let b=(0,X.join)(y,_.path);if((0,W.existsSync)(b)){if(f.has(x))break;f.add(x);try{let v=JSON.parse((0,W.readFileSync)(b,"utf-8")),k=c(y,x);if(k.resources.length===0)break;t.push(...k.resources),n.push(...k.memberships);let P=k.resources.filter(O=>O.resourceType!=="collection").map(O=>({resourceRef:O.importPath})),j=_.converter(v,P),$=(0,X.join)(y,"README.md"),K=(0,W.existsSync)($)?(0,W.readFileSync)($,"utf-8"):"",ae=`${x}/_collection`;t.push({importPath:ae,resourceType:"collection",title:Te(j.name),description:j.description||null,body:K,bodyHash:Ue(K),metadata:{},manifestMetadata:{...j.author?{author:j.author}:{},...j.homepage?{homepage:j.homepage}:{},...j.license?{license:j.license}:{}}}),n.push({collectionImportPath:ae,memberImportPaths:k.resources.map(O=>O.importPath)}),s||(s=v.name||void 0),o||(o=_.formatLabel)}catch{}break}}S(y,x,i+1)}};var I=S;let f=new Set,d=new Set(eo.map(C=>C.folder)),E=new Set([...d,"worktrees","plugins","node_modules","todos"]);S(r,"",0)}let g=(0,X.join)(r,"files");if((0,W.existsSync)(g)&&Ot(g)&&!t.some(f=>f.resourceType==="file"))for(let f of cn(g)){if(!f.endsWith(".md"))continue;let d=(0,X.join)(g,f),E=(0,W.readFileSync)(d,"utf-8"),S=it(E),C=S.name||(0,X.basename)(f,".md"),p=`files/${(0,X.basename)(f,".md")}`;t.some(i=>i.importPath===p)||t.push({importPath:p,resourceType:"file",title:C,description:S.description||null,body:S.body,bodyHash:Ue(E),metadata:{}})}return{resources:[...t.filter(f=>f.resourceType!=="collection"),...t.filter(f=>f.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}async function cr(r){let{scanRoots:e,agentId:t,platformInternals:n=[".claude-plugin"],registerToProject:s=!1,skipImport:o=!1}=r,c=[],a=[],l=new Set;for(let{root:b,agent:v,isProject:k}of e){let P=ar(b,{settingsPath:ke(v,k),mcpConfigPath:Ee(v,k)});for(let j of P.resources)l.has(j.importPath)||(l.add(j.importPath),c.push({...j,scope:k?"project":"global"}));for(let j of P.collectionMemberships)l.has(`cm:${j.collectionImportPath}`)||(l.add(`cm:${j.collectionImportPath}`),a.push(j))}let u=c.map(b=>b.importPath),g=z(),h=new Set(g.installations.map(b=>b.installPath)),I=new Map;for(let b of g.installations){let v=b.installPath.split("/"),k=v[0],P=v[v.length-1];I.has(k)||I.set(k,new Set),I.get(k).add(P)}let f=new Set(n),d=c.filter(b=>{if(h.has(b.importPath))return!1;let v=b.importPath.split("/"),k=v[0],P=v[v.length-1];return!((k==="mcps"||k==="hooks")&&I.get(k)?.has(P)||b.importPath.startsWith(".")||f.has(P)||b.importPath.startsWith("plugins/"))});for(let b of d)b.description&&b.description.length>1e3&&(b.description=b.description.slice(0,997)+"...");let E=d.length,S=d.map(b=>({importPath:b.importPath,resourceType:b.resourceType,title:b.title}));if(d.length===0||o)return{imported:[],errors:0,projectRegistered:0,untrackedCount:E,discoveredPaths:u,untracked:S};let C={dryRun:!1,onConflict:"auto",visibility:"me",resources:d,collectionMemberships:a.length>0?a:void 0},p=await F("/api/cli/import",C,12e4);if(!p.ok)return{imported:[],errors:d.length,projectRegistered:0,untrackedCount:E,discoveredPaths:u,untracked:S};let i=[...p.data.created,...p.data.updated,...p.data.installed],m=new Map;for(let b of c)m.set(b.importPath,b.scope);let y=Ie();for(let b of i){if(!b.id)continue;let v=m.get(b.importPath)||"global";me({resourceId:b.id,slug:b.slug||b.importPath.split("/").pop()||b.id,installPath:b.importPath,title:b.importPath.split("/").pop()||b.id,sha:b.commitSha||"",scope:v,agent:t,installedAt:new Date().toISOString(),resourceType:b.resourceType,serverSynced:!0,...v==="project"&&y?{projectId:y.projectId}:{}})}let x=0;if(s&&y){let b=[...i,...p.data.skipped];for(let v of b){let k=v.id||v.existingId;if(!k||m.get(v.importPath)!=="project")continue;let j=await F(`/api/cli/projects/${y.projectId}/resources`,{resourceId:k});j.ok&&j.data.added&&x++}}return{imported:i.map(b=>({resourceType:b.resourceType||b.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:b.slug||b.importPath.split("/").pop()||"",title:b.importPath.split("/").pop()||"",importPath:b.importPath,id:b.id})),errors:p.data.errors.length,projectRegistered:x,untrackedCount:E,discoveredPaths:u,untracked:[]}}var oo=require("readline");function Fa(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Ze="context-manager",no="Context Manager",lr="collections/shared-context/context-manager";function Ma(r,e){let t=Q(r,e),n=(0,Je.join)(t,Ze);return(0,at.mkdirSync)(n,{recursive:!0}),(0,at.writeFileSync)((0,Je.join)(n,`${Ze}.md`),Ys,"utf-8"),(0,Je.join)(n,`${Ze}.md`)}var Ha={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Ua(r){return z().installations.some(t=>t.installPath===lr&&t.agent===r)}function io(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:p}=await Promise.resolve().then(()=>(le(),os)),{saveAuth:i}=await Promise.resolve().then(()=>(ge(),Ut)),m=await p("/api/cli/auth",{code:n.code});m.ok?(i({token:m.data.token,email:m.data.user.email,orgId:m.data.org.id,orgSlug:m.data.org.slug,orgName:m.data.org.name,createdAt:new Date().toISOString()}),A()||w(`Authenticated as ${m.data.user.email}`)):U()?A()||w("Auth code already used, continuing with saved credentials."):(A()?D("init",m.error.code,m.error.message):R(`Auth failed: ${m.error.message}`),process.exit(1))}else U()||(A()?(D("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(R("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let p=$e(n.agent);if(!p){let i=`Unknown agent: ${n.agent}. Available: ${qe().map(m=>m.id).join(", ")||"none detected"}`;A()?D("init","NO_AGENTS",i):R(i),process.exit(1)}s=[p]}else if(s=qe(),s.length===0){let p=Ge();A()?D("init","NO_AGENTS",p):R(p),process.exit(1)}let o=Pe(),c=Fa(),a;if(n.linkProject){if(!o?.token){let k="Authentication required for project linking. Run init with --code first.";A()?D("init","AUTH_REQUIRED",k):R(k),process.exit(1)}let p=s[0],i=await F("/api/cli/register-agent",{platform:p.platform,name:`CLI (${c})`});i.ok&&(a=i.data.connectionId);let m=await F(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});m.ok||(A()?D("init",m.error.code,m.error.message):R(`Failed to join project: ${m.error.message}`),process.exit(1));let{project:y,resources:x,members:_}=m.data;nt({projectId:y.id,projectName:y.name,projectSlug:y.slug});let b=Le(p),v=[];for(let k of x)try{let P=k.installPath,j=await J(`/api/cli/resource/${P}`);if(!j.ok)continue;let $=j.data;await b.install($,"project",p),me({resourceId:k.id,slug:k.slug||k.id,installPath:P,title:k.title,sha:k.latestSha||"",scope:"project",agent:p.id,installedAt:new Date().toISOString(),projectId:y.id}),k.latestSha&&await F("/api/cli/install",{resourceId:k.id,agentPlatform:p.platform,installedSha:k.latestSha}).catch(()=>{}),v.push({title:k.title,resourceType:k.resourceType})}catch{}if(await F(`/api/cli/projects/${y.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Ht({lastSyncAt:new Date().toISOString()}),A())L("init",{project:{id:y.id,name:y.name,slug:y.slug},agent:p.id,resourcesInstalled:v.length,memberCount:_.length});else{if(w(""),w(`Joined project: ${y.name}`),y.description&&w(`"${y.description}"`),w(""),v.length>0){w(`Installed ${v.length} resource${v.length===1?"":"s"}:`);let k={};for(let j of v)k[j.resourceType]||(k[j.resourceType]=[]),k[j.resourceType].push(j.title);let P={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[j,$]of Object.entries(k))w(` ${P[j]||j}: ${$.join(", ")}`)}else w("No resources to install (project is empty)");_.length>0&&(w(""),w(`Team (${_.length}): ${_.map(k=>k.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let l=!1,u,g=(0,Je.basename)(process.cwd()),h=Ie();if(o?.token&&!h&&g&&g!=="/")try{let p=await F("/api/cli/projects",{name:g});if(p.ok){let{id:i,name:m,slug:y}=p.data;nt({projectId:i,projectName:m,projectSlug:y}),l=!0,A()||w(`Created project: ${m}`)}else u=p.error.message,A()||R(`Project creation failed: ${u}`)}catch(p){u=p instanceof Error?p.message:String(p),A()||R(`Project creation error: ${u}`)}else h?l=!1:o?.token||(u="not authenticated");let I=[],f={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let p of s){let i=!1,m=!1,y=[],x=[];if(o?.token){let _=await F("/api/cli/register-agent",{platform:p.platform,name:`CLI (${c})`});if(_.ok){if(!a){a=_.data.connectionId;let{saveAuth:b}=await Promise.resolve().then(()=>(ge(),Ut));b({...o,connectionId:a})}}else A()||R(`Warning: Could not register ${p.label} connection: ${_.error.message}`)}if(o?.token&&Ua(p.id))m=!0,i=!0;else if(o?.token)try{let _=await J(`/api/cli/resource/${lr}`);if(_.ok){let b=_.data,k=await Le(p).install(b,n.project?"project":"user",p);if(me({resourceId:b.resource.id,slug:b.resource.slug||"context-manager",installPath:lr,title:b.resource.title,sha:b.resource.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),pluginFormat:f[p.id]||"directory",memberCount:b.memberResources?.length}),b.resource.latestSha&&await F("/api/cli/install",{resourceId:b.resource.id,agentPlatform:p.platform,installedSha:b.resource.latestSha}).catch(()=>{}),b.memberResources)for(let P of b.memberResources){let j=P.slug||P.id,$=Ha[P.resourceType]||P.resourceType+"s",K=P.orgSlug||b.resource.orgSlug,ae=K?`${$}/${K}/${j}`:`${$}/${j}`;me({resourceId:P.id,slug:j,installPath:ae,title:P.title,sha:P.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),collectionId:b.resource.id}),y.push({title:P.title,resourceType:P.resourceType}),P.latestSha&&await F("/api/cli/install",{resourceId:P.id,agentPlatform:p.platform,installedSha:P.latestSha}).catch(()=>{})}if(i=!0,!A()&&k.warnings.length>0)for(let P of k.warnings)R(`Warning: ${P}`)}}catch{}if(!i&&(Ma(p,!!n.project),me({resourceId:"context-manager",slug:Ze,installPath:`agents/${Ze}`,title:no,sha:"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()}),o?.token))try{let _=`agents/shared-context/${Ze}`,b=await J(`/api/cli/resource/${_}`);if(b.ok&&b.data.resource){let v=b.data.resource;v.latestSha&&await F("/api/cli/install",{resourceId:v.id,agentPlatform:p.platform,installedSha:v.latestSha}),me({resourceId:v.id,slug:v.slug||Ze,installPath:`agents/shared-context/${v.slug||Ze}`,title:v.title||no,sha:v.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let _=[],b=(0,Je.join)(process.cwd(),p.dir),v=(0,Je.join)((0,so.homedir)(),p.dir);(0,at.existsSync)(b)&&_.push({root:b,agent:p,isProject:!0}),b!==v&&(0,at.existsSync)(v)&&_.push({root:v,agent:p,isProject:!1}),_.length>0&&(x=(await cr({scanRoots:_,agentId:p.id,platformInternals:["context-manager",".claude-plugin"],registerToProject:!0})).imported.map(P=>({resourceType:P.resourceType,slug:P.slug,title:P.title})))}catch{}I.push({agent:p,collectionInstalled:i,installedMembers:y,importedResources:x,skippedEssentials:m})}if(Ht({lastSyncAt:new Date().toISOString()}),I.some(p=>!p.skippedEssentials)&&!A()&&process.stdin.isTTY){let{getConfig:p,updateConfig:i}=await Promise.resolve().then(()=>(ge(),Ut));if(p().telemetry===void 0)try{await new Promise(x=>{let _=(0,oo.createInterface)({input:process.stdin,output:process.stdout});_.question(`
|
|
144
|
+
`:" "),y+=b[v]}}E==="name"||E==="title"?e.name=y:E==="description"?e.description=y:E==="skill_class"?e.skillClass=y:E==="service"?e.service=y:y&&(o[E]=y),I=m-1;continue}E==="name"||E==="title"?e.name=yt(S):E==="description"?e.description=yt(S):E==="skill_class"?e.skillClass=yt(S):E==="service"?e.service=yt(S):E&&S&&(o[E]=yt(S))}return l.requires?.length&&(e.requires=l.requires),l.tools?.length&&(e.tools=l.tools),Object.keys(o).length&&(e.fields=o),Object.keys(c).length&&(e.arrayFields=c),e}function yt(r){let e=r.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 rc(r){let{body:e}=at(r);return e.replace(/\r\n/g,`
|
|
145
|
+
`).replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function Ue(r){let e=rc(r);return`sha256:${(0,Fo.createHash)("sha256").update(e,"utf8").digest("hex")}`}function Te(r){return r.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Rt(r){try{return(0,W.statSync)(r).isDirectory()}catch{return!1}}function On(r){try{return(0,W.readdirSync)(r).filter(e=>!e.startsWith(".")&&Rt((0,Y.join)(r,e)))}catch{return[]}}function kn(r){try{return(0,W.readdirSync)(r).filter(e=>!e.startsWith(".")&&!Rt((0,Y.join)(r,e)))}catch{return[]}}function dr(r,e){let t=[],n=[],s,o;function c(f,d){let E=[],S=[];for(let C of $o){let p=(0,Y.join)(f,C.folder);if(!(0,W.existsSync)(p)||!Rt(p))continue;let i=d?`${d}/${C.folder}`:C.folder;if(C.folder==="files"){for(let m of kn(p)){if(!m.endsWith(".md"))continue;let y=(0,Y.join)(p,m),x=(0,W.readFileSync)(y,"utf-8"),_=at(x),b=_.name||(0,Y.basename)(m,".md"),v=`${i}/${(0,Y.basename)(m,".md")}`;E.push({importPath:v,resourceType:"file",title:b,description:_.description||null,body:_.body,bodyHash:Ue(x),metadata:{}})}continue}if(C.mainFile===null)for(let m of kn(p)){if(!m.endsWith(".md"))continue;let y=(0,Y.basename)(m,".md"),x=`${i}/${y}`;if(Rt((0,Y.join)(p,y)))continue;let _=(0,W.readFileSync)((0,Y.join)(p,m),"utf-8"),b=at(_),v=b.name||Te(y),k={};b.skillClass&&(k.skillClass=b.skillClass),b.service&&(k.service=b.service),b.requires?.length&&(k.requires=b.requires),b.tools?.length&&(k.tools=b.tools),b.fields&&Object.keys(b.fields).length&&(k.fields=b.fields),C.folder==="commands"&&(k.fields||(k.fields={}),k.fields["user-invocable"]="true"),E.push({importPath:x,resourceType:C.resourceType,title:v,description:b.description||null,body:b.body,bodyHash:Ue(_),metadata:k})}for(let m of On(p)){let y=C.mainFile||`${m}.md`,x=(0,Y.join)(p,m,y);if(!(0,W.existsSync)(x)){if(C.mainFile===null)for(let K of On((0,Y.join)(p,m))){let ae=`${K}.md`,O=(0,Y.join)(p,m,K,ae);if(!(0,W.existsSync)(O))continue;let N=(0,W.readFileSync)(O,"utf-8"),M=at(N),q=M.name||Te(K),H={};M.skillClass&&(H.skillClass=M.skillClass),M.service&&(H.service=M.service),M.requires?.length&&(H.requires=M.requires),M.tools?.length&&(H.tools=M.tools),M.fields&&Object.keys(M.fields).length&&(H.fields=M.fields),E.push({importPath:`${i}/${K}`,resourceType:C.resourceType,title:q,description:M.description||null,body:M.body,bodyHash:Ue(N),metadata:H})}continue}let _=(0,W.readFileSync)(x,"utf-8"),b=`${i}/${m}`,v,k,P,j={},$=null;if(C.resourceType==="hook"||C.resourceType==="mcp"){try{let K=JSON.parse(_);v=K.name||Te(m),k=K.description||null}catch{v=Te(m),k=null}P=_}else if(C.resourceType==="collection"){let K=(0,Y.join)(p,m,ur,fr);if((0,W.existsSync)(K))try{let ae=JSON.parse((0,W.readFileSync)(K,"utf-8"));v=ae.name||Te(m),k=ae.description||null,P=_,ae.resources&&Array.isArray(ae.resources)&&S.push({collectionImportPath:b,memberImportPaths:ae.resources.map(O=>{let N=O.split("/");return N.length>=3?`${N[0]}/${N[N.length-1]}`:O})})}catch{v=Te(m),k=null,P=_}else $=at(_),v=$.name||Te(m),k=$.description||null,P=$.body,$.arrayFields?.resources&&S.push({collectionImportPath:b,memberImportPaths:$.arrayFields.resources.map(ae=>{let O=ae.split("/");return O.length>=3?`${O[0]}/${O[O.length-1]}`:ae})})}else $=at(_),v=$.name||Te(m),k=$.description||null,P=$.body,$.skillClass&&(j.skillClass=$.skillClass),$.service&&(j.service=$.service),$.requires?.length&&(j.requires=$.requires),$.tools?.length&&(j.tools=$.tools),$.fields&&Object.keys($.fields).length&&(j.fields=$.fields);C.folder==="commands"&&(j.fields||(j.fields={}),j.fields["user-invocable"]="true"),E.push({importPath:b,resourceType:C.resourceType,title:v,description:k,body:P,bodyHash:Ue(_),metadata:j})}}return{resources:E,memberships:S}}let a=c(r,"");t.push(...a.resources),n.push(...a.memberships);let l=new Set;e?.mcpConfigPath&&l.add(e.mcpConfigPath);let u=(0,Y.join)(r,".mcp.json");(0,W.existsSync)(u)&&l.add(u);for(let f of l)if((0,W.existsSync)(f))try{let d=JSON.parse((0,W.readFileSync)(f,"utf-8"));if(d.mcpServers&&typeof d.mcpServers=="object")for(let[E,S]of Object.entries(d.mcpServers)){let C=`mcps/${E}`;if(t.some(m=>m.importPath===C))continue;let p=Te(E),i=JSON.stringify({name:p,description:`MCP server: ${E}`,mcpServers:{[E]:S}},null,2);t.push({importPath:C,resourceType:"mcp",title:p,description:`MCP server: ${E}`,body:i,bodyHash:Ue(i),metadata:{}})}}catch{}if(e?.settingsPath&&(0,W.existsSync)(e.settingsPath))try{let f=JSON.parse((0,W.readFileSync)(e.settingsPath,"utf-8"));if(f.hooks&&typeof f.hooks=="object"&&!Array.isArray(f.hooks)){let d={};for(let[E,S]of Object.entries(f.hooks))if(Array.isArray(S))for(let C of S){if(!C||typeof C!="object")continue;let p=C,i=p._sc;if(!i)continue;d[i]||(d[i]={}),d[i][E]||(d[i][E]=[]);let{_sc:m,...y}=p;d[i][E].push(y)}for(let[E,S]of Object.entries(d)){let C=E;if(t.some(y=>y.importPath===C))continue;let p=E.split("/").pop()||E,i=Te(p),m=JSON.stringify({name:i,description:`Hook: ${i}`,hooks:S},null,2);t.push({importPath:C,resourceType:"hook",title:i,description:`Hook: ${i}`,body:m,bodyHash:Ue(m),metadata:{}})}}}catch{}for(let f of vn){if(f.path===Lo)continue;let d=(0,Y.join)(r,f.path);if((0,W.existsSync)(d)){try{let E=JSON.parse((0,W.readFileSync)(d,"utf-8"));if(s=s||E.name||void 0,o=f.formatLabel,!t.some(S=>S.resourceType==="collection")){let S=t.filter(y=>y.resourceType!=="collection").map(y=>({resourceRef:y.importPath})),C=f.converter(E,S),p=(0,Y.join)(r,"README.md"),i=(0,W.existsSync)(p)?(0,W.readFileSync)(p,"utf-8"):"",m="collections/_root";t.push({importPath:m,resourceType:"collection",title:Te(C.name),description:C.description||null,body:i,bodyHash:Ue(i),metadata:{},manifestMetadata:{...C.author?{author:C.author}:{},...C.homepage?{homepage:C.homepage}:{},...C.license?{license:C.license}:{}}}),C.resources.length>0&&n.push({collectionImportPath:m,memberImportPaths:C.resources})}}catch{}break}}{let S=function(C,p,i){if(!(i>4))for(let m of On(C)){if(E.has(m))continue;let y=(0,Y.join)(C,m),x=p?`${p}/${m}`:m;for(let _ of vn){if(_.path===Lo)continue;let b=(0,Y.join)(y,_.path);if((0,W.existsSync)(b)){if(f.has(x))break;f.add(x);try{let v=JSON.parse((0,W.readFileSync)(b,"utf-8")),k=c(y,x);if(k.resources.length===0)break;t.push(...k.resources),n.push(...k.memberships);let P=k.resources.filter(O=>O.resourceType!=="collection").map(O=>({resourceRef:O.importPath})),j=_.converter(v,P),$=(0,Y.join)(y,"README.md"),K=(0,W.existsSync)($)?(0,W.readFileSync)($,"utf-8"):"",ae=`${x}/_collection`;t.push({importPath:ae,resourceType:"collection",title:Te(j.name),description:j.description||null,body:K,bodyHash:Ue(K),metadata:{},manifestMetadata:{...j.author?{author:j.author}:{},...j.homepage?{homepage:j.homepage}:{},...j.license?{license:j.license}:{}}}),n.push({collectionImportPath:ae,memberImportPaths:k.resources.map(O=>O.importPath)}),s||(s=v.name||void 0),o||(o=_.formatLabel)}catch{}break}}S(y,x,i+1)}};var I=S;let f=new Set,d=new Set($o.map(C=>C.folder)),E=new Set([...d,"worktrees","plugins","node_modules","todos"]);S(r,"",0)}let g=(0,Y.join)(r,"files");if((0,W.existsSync)(g)&&Rt(g)&&!t.some(f=>f.resourceType==="file"))for(let f of kn(g)){if(!f.endsWith(".md"))continue;let d=(0,Y.join)(g,f),E=(0,W.readFileSync)(d,"utf-8"),S=at(E),C=S.name||(0,Y.basename)(f,".md"),p=`files/${(0,Y.basename)(f,".md")}`;t.some(i=>i.importPath===p)||t.push({importPath:p,resourceType:"file",title:C,description:S.description||null,body:S.body,bodyHash:Ue(E),metadata:{}})}return{resources:[...t.filter(f=>f.resourceType!=="collection"),...t.filter(f=>f.resourceType==="collection")],collectionMemberships:n,pluginName:s,formatLabel:o}}async function pr(r){let{scanRoots:e,agentId:t,platformInternals:n=[".claude-plugin"],registerToProject:s=!1,skipImport:o=!1}=r,c=[],a=[],l=new Set;for(let{root:b,agent:v,isProject:k}of e){let P=dr(b,{settingsPath:ke(v,k),mcpConfigPath:Ee(v,k)});for(let j of P.resources)l.has(j.importPath)||(l.add(j.importPath),c.push({...j,scope:k?"project":"global"}));for(let j of P.collectionMemberships)l.has(`cm:${j.collectionImportPath}`)||(l.add(`cm:${j.collectionImportPath}`),a.push(j))}let u=c.map(b=>b.importPath),g=z(),h=new Set(g.installations.map(b=>b.installPath)),I=new Map;for(let b of g.installations){let v=b.installPath.split("/"),k=v[0],P=v[v.length-1];I.has(k)||I.set(k,new Set),I.get(k).add(P)}let f=new Set(n),d=c.filter(b=>{if(h.has(b.importPath))return!1;let v=b.importPath.split("/"),k=v[0],P=v[v.length-1];return!((k==="mcps"||k==="hooks")&&I.get(k)?.has(P)||b.importPath.startsWith(".")||f.has(P)||b.importPath.startsWith("plugins/"))});for(let b of d)b.description&&b.description.length>1e3&&(b.description=b.description.slice(0,997)+"...");let E=d.length,S=d.map(b=>({importPath:b.importPath,resourceType:b.resourceType,title:b.title}));if(d.length===0||o)return{imported:[],errors:0,projectRegistered:0,untrackedCount:E,discoveredPaths:u,untracked:S};let C={dryRun:!1,onConflict:"auto",visibility:"me",resources:d,collectionMemberships:a.length>0?a:void 0},p=await F("/api/cli/import",C,12e4);if(!p.ok)return{imported:[],errors:d.length,projectRegistered:0,untrackedCount:E,discoveredPaths:u,untracked:S};let i=[...p.data.created,...p.data.updated,...p.data.installed],m=new Map;for(let b of c)m.set(b.importPath,b.scope);let y=Ie();for(let b of i){if(!b.id)continue;let v=m.get(b.importPath)||"global";me({resourceId:b.id,slug:b.slug||b.importPath.split("/").pop()||b.id,installPath:b.importPath,title:b.importPath.split("/").pop()||b.id,sha:b.commitSha||"",scope:v,agent:t,installedAt:new Date().toISOString(),resourceType:b.resourceType,serverSynced:!0,...v==="project"&&y?{projectId:y.projectId}:{}})}let x=0;if(s&&y){let b=[...i,...p.data.skipped];for(let v of b){let k=v.id||v.existingId;if(!k||m.get(v.importPath)!=="project")continue;let j=await F(`/api/cli/projects/${y.projectId}/resources`,{resourceId:k});j.ok&&j.data.added&&x++}}return{imported:i.map(b=>({resourceType:b.resourceType||b.importPath.split("/")[0]?.replace(/s$/,"")||"unknown",slug:b.slug||b.importPath.split("/").pop()||"",title:b.importPath.split("/").pop()||"",importPath:b.importPath,id:b.id})),errors:p.data.errors.length,projectRegistered:x,untrackedCount:E,discoveredPaths:u,untracked:[]}}var Uo=require("readline");function nc(){if(process.platform==="darwin")try{let{execSync:r}=require("child_process"),e=r("scutil --get ComputerName",{encoding:"utf-8"}).trim();if(e)return e}catch{}return require("os").hostname()}var Ye="context-manager",Mo="Context Manager",mr="collections/shared-context/context-manager";function sc(r,e){let t=Q(r,e),n=(0,Xe.join)(t,Ye);return(0,ct.mkdirSync)(n,{recursive:!0}),(0,ct.writeFileSync)((0,Xe.join)(n,`${Ye}.md`),Do,"utf-8"),(0,Xe.join)(n,`${Ye}.md`)}var oc={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function ic(r){return z().installations.some(t=>t.installPath===mr&&t.agent===r)}function Bo(r){r.command("init").description("Initialize Shared Context CLI for your agent").option("--code <code>","Auth code from the web app").option("--link-project <id>","Link to a Shared Context project by ID").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()};if(n.code){let{post:p}=await Promise.resolve().then(()=>(le(),is)),{saveAuth:i}=await Promise.resolve().then(()=>(ge(),Ut)),m=await p("/api/cli/auth",{code:n.code});m.ok?(i({token:m.data.token,email:m.data.user.email,orgId:m.data.org.id,orgSlug:m.data.org.slug,orgName:m.data.org.name,createdAt:new Date().toISOString()}),A()||w(`Authenticated as ${m.data.user.email}`)):U()?A()||w("Auth code already used, continuing with saved credentials."):(A()?D("init",m.error.code,m.error.message):R(`Auth failed: ${m.error.message}`),process.exit(1))}else U()||(A()?(D("init","AUTH_MISSING","Not authenticated. Run 'shared-context-ai login' first or pass --code."),process.exit(1)):(R("Not authenticated. Run 'shared-context-ai login' first or pass --code <code>."),process.exit(1)));let s;if(n.agent){let p=$e(n.agent);if(!p){let i=`Unknown agent: ${n.agent}. Available: ${qe().map(m=>m.id).join(", ")||"none detected"}`;A()?D("init","NO_AGENTS",i):R(i),process.exit(1)}s=[p]}else if(s=qe(),s.length===0){let p=Ge();A()?D("init","NO_AGENTS",p):R(p),process.exit(1)}let o=Pe(),c=nc(),a;if(n.linkProject){if(!o?.token){let k="Authentication required for project linking. Run init with --code first.";A()?D("init","AUTH_REQUIRED",k):R(k),process.exit(1)}let p=s[0],i=await F("/api/cli/register-agent",{platform:p.platform,name:`CLI (${c})`});i.ok&&(a=i.data.connectionId);let m=await F(`/api/cli/projects/${n.linkProject}/join`,{localPath:process.cwd()});m.ok||(A()?D("init",m.error.code,m.error.message):R(`Failed to join project: ${m.error.message}`),process.exit(1));let{project:y,resources:x,members:_}=m.data;st({projectId:y.id,projectName:y.name,projectSlug:y.slug});let b=Le(p),v=[];for(let k of x)try{let P=k.installPath,j=await Z(`/api/cli/resource/${P}`);if(!j.ok)continue;let $=j.data;await b.install($,"project",p),me({resourceId:k.id,slug:k.slug||k.id,installPath:P,title:k.title,sha:k.latestSha||"",scope:"project",agent:p.id,installedAt:new Date().toISOString(),projectId:y.id}),k.latestSha&&await F("/api/cli/install",{resourceId:k.id,agentPlatform:p.platform,installedSha:k.latestSha}).catch(()=>{}),v.push({title:k.title,resourceType:k.resourceType})}catch{}if(await F(`/api/cli/projects/${y.id}/sync`,{localPath:process.cwd()}).catch(()=>{}),Ht({lastSyncAt:new Date().toISOString()}),A())L("init",{project:{id:y.id,name:y.name,slug:y.slug},agent:p.id,resourcesInstalled:v.length,memberCount:_.length});else{if(w(""),w(`Joined project: ${y.name}`),y.description&&w(`"${y.description}"`),w(""),v.length>0){w(`Installed ${v.length} resource${v.length===1?"":"s"}:`);let k={};for(let j of v)k[j.resourceType]||(k[j.resourceType]=[]),k[j.resourceType].push(j.title);let P={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};for(let[j,$]of Object.entries(k))w(` ${P[j]||j}: ${$.join(", ")}`)}else w("No resources to install (project is empty)");_.length>0&&(w(""),w(`Team (${_.length}): ${_.map(k=>k.name).join(", ")}`)),w(""),w("Quick reference:"),w(" shared-context-ai status View project sync status"),w(" shared-context-ai sync Check for resource updates")}return}let l=!1,u,g=(0,Xe.basename)(process.cwd()),h=Ie();if(o?.token&&!h&&g&&g!=="/")try{let p=await F("/api/cli/projects",{name:g});if(p.ok){let{id:i,name:m,slug:y}=p.data;st({projectId:i,projectName:m,projectSlug:y}),l=!0,A()||w(`Created project: ${m}`)}else u=p.error.message,A()||R(`Project creation failed: ${u}`)}catch(p){u=p instanceof Error?p.message:String(p),A()||R(`Project creation error: ${u}`)}else h?l=!1:o?.token||(u="not authenticated");let I=[],f={"claude-code":"claude-plugin","gemini-cli":"gemini-extension",antigravity:"gemini-extension",cursor:"cursor",codex:"codex"};for(let p of s){let i=!1,m=!1,y=[],x=[];if(o?.token){let _=await F("/api/cli/register-agent",{platform:p.platform,name:`CLI (${c})`});if(_.ok){if(!a){a=_.data.connectionId;let{saveAuth:b}=await Promise.resolve().then(()=>(ge(),Ut));b({...o,connectionId:a})}}else A()||R(`Warning: Could not register ${p.label} connection: ${_.error.message}`)}if(o?.token&&ic(p.id))m=!0,i=!0;else if(o?.token)try{let _=await Z(`/api/cli/resource/${mr}`);if(_.ok){let b=_.data,k=await Le(p).install(b,n.project?"project":"user",p);if(me({resourceId:b.resource.id,slug:b.resource.slug||"context-manager",installPath:mr,title:b.resource.title,sha:b.resource.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),pluginFormat:f[p.id]||"directory",memberCount:b.memberResources?.length}),b.resource.latestSha&&await F("/api/cli/install",{resourceId:b.resource.id,agentPlatform:p.platform,installedSha:b.resource.latestSha}).catch(()=>{}),b.memberResources)for(let P of b.memberResources){let j=P.slug||P.id,$=oc[P.resourceType]||P.resourceType+"s",K=P.orgSlug||b.resource.orgSlug,ae=K?`${$}/${K}/${j}`:`${$}/${j}`;me({resourceId:P.id,slug:j,installPath:ae,title:P.title,sha:P.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString(),collectionId:b.resource.id}),y.push({title:P.title,resourceType:P.resourceType}),P.latestSha&&await F("/api/cli/install",{resourceId:P.id,agentPlatform:p.platform,installedSha:P.latestSha}).catch(()=>{})}if(i=!0,!A()&&k.warnings.length>0)for(let P of k.warnings)R(`Warning: ${P}`)}}catch{}if(!i&&(sc(p,!!n.project),me({resourceId:"context-manager",slug:Ye,installPath:`agents/${Ye}`,title:Mo,sha:"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()}),o?.token))try{let _=`agents/shared-context/${Ye}`,b=await Z(`/api/cli/resource/${_}`);if(b.ok&&b.data.resource){let v=b.data.resource;v.latestSha&&await F("/api/cli/install",{resourceId:v.id,agentPlatform:p.platform,installedSha:v.latestSha}),me({resourceId:v.id,slug:v.slug||Ye,installPath:`agents/shared-context/${v.slug||Ye}`,title:v.title||Mo,sha:v.latestSha||"",scope:n.project?"project":"global",agent:p.id,installedAt:new Date().toISOString()})}}catch{}if(o?.token)try{let _=[],b=(0,Xe.join)(process.cwd(),p.dir),v=(0,Xe.join)((0,Ho.homedir)(),p.dir);(0,ct.existsSync)(b)&&_.push({root:b,agent:p,isProject:!0}),b!==v&&(0,ct.existsSync)(v)&&_.push({root:v,agent:p,isProject:!1}),_.length>0&&(x=(await pr({scanRoots:_,agentId:p.id,platformInternals:["context-manager",".claude-plugin"],registerToProject:!0})).imported.map(P=>({resourceType:P.resourceType,slug:P.slug,title:P.title})))}catch{}I.push({agent:p,collectionInstalled:i,installedMembers:y,importedResources:x,skippedEssentials:m})}if(Ht({lastSyncAt:new Date().toISOString()}),I.some(p=>!p.skippedEssentials)&&!A()&&process.stdin.isTTY){let{getConfig:p,updateConfig:i}=await Promise.resolve().then(()=>(ge(),Ut));if(p().telemetry===void 0)try{await new Promise(x=>{let _=(0,Uo.createInterface)({input:process.stdin,output:process.stdout});_.question(`
|
|
145
146
|
Help improve Shared Context skills? We collect anonymous usage data
|
|
146
147
|
(which skills you use, never conversation content). Change anytime with
|
|
147
|
-
\`shared-context-ai config set telemetry off\`. [y/N] `,b=>{_.close(),x(b.trim().toLowerCase()==="y"||b.trim().toLowerCase()==="yes")})})?(i({telemetry:!0}),w("Telemetry enabled.")):(i({telemetry:!1}),w("Telemetry disabled."))}catch{}}if(a){let p=I.reduce((i,m)=>i+m.importedResources.length,0);F("/api/cli/sync-report",{connectionId:a,lastSyncResult:{updatesAvailable:0,importedCount:p}}).catch(()=>{})}let E=I.every(p=>p.skippedEssentials),S=I.some(p=>!p.skippedEssentials),C=I.some(p=>p.importedResources.length>0);if(A()){let p=m=>({agent:m.agent.id,collection:m.collectionInstalled?
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
`);let n=t.map(s=>[Vo(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(Se(n))}else{let t=z().installations;if(A()){L("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
|
|
148
|
+
\`shared-context-ai config set telemetry off\`. [y/N] `,b=>{_.close(),x(b.trim().toLowerCase()==="y"||b.trim().toLowerCase()==="yes")})})?(i({telemetry:!0}),w("Telemetry enabled.")):(i({telemetry:!1}),w("Telemetry disabled."))}catch{}}if(a){let p=I.reduce((i,m)=>i+m.importedResources.length,0);F("/api/cli/sync-report",{connectionId:a,lastSyncResult:{updatesAvailable:0,importedCount:p}}).catch(()=>{})}let E=I.every(p=>p.skippedEssentials),S=I.some(p=>!p.skippedEssentials),C=I.some(p=>p.importedResources.length>0);if(A()){let p=m=>({agent:m.agent.id,collection:m.collectionInstalled?mr:void 0,contextManagerOnly:!m.collectionInstalled,skipped:m.skippedEssentials,...m.collectionInstalled&&!m.skippedEssentials?{membersInstalled:m.installedMembers.map(y=>({title:y.title,resourceType:y.resourceType}))}:{},...m.importedResources.length>0?{importedResources:m.importedResources.map(y=>({resourceType:y.resourceType,slug:y.slug,title:y.title}))}:{}}),i=Ie();L("init",{...p(I[0]),agents:I.map(p),...l?{projectCreated:!0,projectId:i?.projectId}:{},...i&&!l?{projectLinked:!0,projectId:i.projectId}:{},...u?{projectError:u}:{},authenticated:U()})}else{for(let p of I)if(!p.skippedEssentials){if(w(""),p.collectionInstalled){w(`Context Manager installed for ${p.agent.label} (${p.installedMembers.length} resources)`);let i={};for(let y of p.installedMembers)i[y.resourceType]||(i[y.resourceType]=[]),i[y.resourceType].push(y.title);let m={skill:"Skills",agent:"Agents",hook:"Hooks",mcp:"MCPs",collection:"Collections"};w("");for(let[y,x]of Object.entries(i)){let _=m[y]||y;w(` ${_}: ${x.join(", ")}`)}}else w(`Context Manager installed for ${p.agent.label} (offline)`),w("Context Manager agent written locally");if(p.importedResources.length>0){w(""),w(`Imported ${p.importedResources.length} existing resource${p.importedResources.length===1?"":"s"}:`);for(let i of p.importedResources)w(` ${i.resourceType.padEnd(12)} ${i.slug.padEnd(24)} ${i.title}`)}}E&&!l&&!C&&(w(""),w("Already initialized. Nothing to do.")),(S||l||C)&&(w(""),w("Quick reference:"),w(' shared-context-ai search "query" Search for resources'),w(" shared-context-ai install <installPath> Install a resource"),w(" shared-context-ai list List installed resources"),w(" shared-context-ai sync Check updates & discover resources"),w(" shared-context-ai preview <installPath> Preview before installing"))}})}le();ce();var ac={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Vo(r){let e=ac[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${e}/external/${r.githubOwner}/${r.slug}`:r.orgSlug?`${e}/${r.orgSlug}/${r.slug}`:`${e}/${r.slug}`}function Wo(r){r.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("--scope <scope>","Scope: all | mine | org | public","all").option("--freshness <days>","Only include resources updated within the last N days").option("--min-installs <n>","Minimum install count floor").option("--limit <n>","Max results","20").action(async(e,t)=>{let n=new URLSearchParams({q:e,source:"cli"});t.type&&n.set("type",t.type),t.tag&&n.set("tag",t.tag),t.scope&&n.set("scope",t.scope),t.freshness&&n.set("freshness",t.freshness),t.minInstalls&&n.set("minInstalls",t.minInstalls),t.limit&&n.set("limit",t.limit);let s=await Z(`/api/search?${n}`);s.ok||(A()?D("search",s.error.code,s.error.message):w(`Search failed: ${s.error.message}`),process.exit(1));let o=s.data.results;if(A()){let a=o.map(l=>{let u=Vo(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}});L("search",{results:a,count:a.length});return}if(o.length===0){let a=t.type?`${t.type}s`:"results";w(`No ${a} found.`);return}w(`Found ${o.length} result${o.length===1?"":"s"}:
|
|
149
|
+
`);let c=o.map(a=>[Vo(a),a.title,`\u2193${a.installCount}`]);w(Se(c)),w(`
|
|
150
|
+
Install a skill: npx shared-context-ai install <installPath>`)})}le();ge();ce();function qo(r){let e=r.slug||r.resourceId;return r.storageType==="github"&&r.githubOwner?`skills/external/${r.githubOwner}/${e}`:r.orgSlug?`skills/${r.orgSlug}/${e}`:`skills/${e}`}function Go(r){r.command("list").description("List installed skills").alias("ls").action(async()=>{if(U()){let e=await Z("/api/cli/installed");e.ok||(A()?D("list",e.error.code,e.error.message):w(`Failed to fetch installations: ${e.error.message}`),process.exit(1));let t=e.data.installations;if(A()){let s=t.map(o=>({...o,installPath:qo(o)}));L("list",{installations:s,count:s.length});return}if(t.length===0){w("No skills installed."),w("Use 'shared-context-ai search' to find skills to install.");return}w(`${t.length} skill${t.length===1?"":"s"} installed:
|
|
151
|
+
`);let n=t.map(s=>[qo(s),s.title,s.hasUpdate?"(update available)":"(current)"]);w(Se(n))}else{let t=z().installations;if(A()){L("list",{installations:t,count:t.length});return}if(t.length===0){w("No skills installed locally.");return}w(`${t.length} skill${t.length===1?"":"s"} installed locally:
|
|
152
152
|
`);let n=t.map(s=>[s.installPath||s.slug,s.title,`(${s.agent})`]);w(Se(n)),w(`
|
|
153
|
-
Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}le();ce();function
|
|
153
|
+
Tip: Run 'shared-context-ai login' to sync with sharedcontext.ai and check for updates.`)}})}le();ce();function zo(r){r.command("preview <path>").description("Preview a skill's content (e.g., skills/acme/api-testing)").action(async e=>{let n=U()?"/api/cli/resource":"/api/public/resource",s=await Z(`${n}/${e}/preview`);s.ok||(A()?D("preview",s.error.code,s.error.message):R(`Preview failed: ${s.error.message}`),process.exit(1)),A()?L("preview",s.data):w(s.data.content)})}le();ce();function Zo(r){r.command("check").description("Check for skill updates").action(async()=>{U()||(A()?D("check","AUTH_MISSING","Login required to check for updates."):R("Login required to check for updates. Run 'shared-context-ai login'."),process.exit(1));let e=await Z("/api/cli/updates");e.ok||(A()?D("check",e.error.code,e.error.message):R(`Check failed: ${e.error.message}`),process.exit(1));let{updates:t,count:n}=e.data;if(A()){L("check",{updates:t,count:n});return}if(n===0){w("All skills are up to date.");return}w(`${n} update${n===1?"":"s"} available:
|
|
154
154
|
`);let s=t.map(o=>{let c=o.slug||o.resourceId;return[o.storageType==="github"&&o.githubOwner?`skills/external/${o.githubOwner}/${c}`:o.orgSlug?`skills/${o.orgSlug}/${c}`:`skills/${c}`,o.title,`${o.installedSha.slice(0,7)} \u2192 ${o.latestSha.slice(0,7)}`]});w(Se(s)),w(`
|
|
155
|
-
Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var lt=require("path"),gr=require("fs"),
|
|
156
|
-
${l.length} resource${l.length===1?"":"s"} updated.`)})}var fe=require("fs"),St=require("path"),
|
|
155
|
+
Run 'shared-context-ai update' to update all, or 'shared-context-ai update <installPath>' to update one.`)})}var lt=require("path"),gr=require("fs"),Ko=require("child_process");le();ge();ce();var Yo={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function Jo(r){let e=r.slug||r.resourceId;return`${Yo[r.resourceType]||r.resourceType+"s"}/${e}`}function Xo(r){r.command("update [path]").description("Update installed resources (all or by install path)").action(async(e,t,n)=>{let s=n.optsWithGlobals();U()||(A()?D("update","AUTH_MISSING","Login required to update resources."):R("Login required to update resources. Run 'shared-context-ai login'."),process.exit(1));let o=$e(s.agent);if(!o){let u=Ge();A()?D("update","NO_AGENTS",u):R(u),process.exit(1)}let c=await Z("/api/cli/updates");c.ok||(A()?D("update",c.error.code,c.error.message):R(`Failed to check updates: ${c.error.message}`),process.exit(1));let a=c.data.updates;if(e&&(a=a.filter(u=>Jo(u)===e||u.slug===e||u.resourceId===e),a.length===0)){A()?D("update","SKILL_NOT_FOUND",`No update available for "${e}".`):w(`No update available for "${e}".`);return}if(a.length===0){A()?L("update",{updated:[],count:0}):w("All resources are up to date.");return}let l=[];for(let u of a){let h=z().installations.find(C=>C.resourceId===u.resourceId&&C.agent===o.id),I;if(h?.installPath){let C=h.installPath.split("/");C[C.length-1]=u.slug||u.resourceId,I=C.join("/")}else I=Jo(u);if(h?.installMode==="plugin"&&u.resourceType==="collection"){try{let C=u.orgSlug||"",p=u.slug||u.resourceId,i=tr(o.id),m=`/api/cli/resource/collections/${C}/${p}?format=plugin&platform=${i}`,y=await er(m,p),x=Qt(o.id);x&&(0,Ko.execSync)(`${x} plugin install "${y}"`,{stdio:"pipe"}),u.latestSha&&await F("/api/cli/update",{resourceId:u.resourceId,installedSha:u.latestSha}),me({...h,sha:u.latestSha,installedAt:new Date().toISOString()}),l.push({installPath:I,title:u.title}),A()||w(` Updated plugin: ${I}`)}catch(C){A()||R(` Plugin update failed for ${I}: ${C}`)}continue}let f=await Z(`/api/cli/resource/${I}`);if(!f.ok){A()||R(` Failed to fetch ${I}: ${f.error.message}`);continue}let d=f.data,E=I.split("/").slice(1);if(d.resource.resourceType==="agent"){let C=Q(o,!!s.project),p=(0,lt.join)(C,...E);J(p,d.files)}else if(d.resource.resourceType==="mcp")rr(o,!!s.project,d);else{let C=V(o,!!s.project),p=(0,lt.join)(C,...E);J(p,d.files)}if(h&&h.installPath&&h.installPath!==I){let C=h.installPath.split("/").slice(1),p;d.resource.resourceType==="agent"?p=(0,lt.join)(Q(o,!!s.project),...C):d.resource.resourceType!=="mcp"&&(p=(0,lt.join)(V(o,!!s.project),...C)),p&&(0,gr.existsSync)(p)&&((0,gr.rmSync)(p,{recursive:!0}),A()||w(` Removed old path: ${h.installPath}`))}let S=u.latestSha||d.resource.latestSha;if(S&&await F("/api/cli/update",{resourceId:u.resourceId,installedSha:S}),me({...h||{},resourceId:u.resourceId,slug:u.slug||u.resourceId,installPath:I,title:d.resource.title,sha:S||"",scope:h?.scope||(s.project?"project":"global"),agent:o.id,installedAt:new Date().toISOString(),latestSha:S||void 0,resourceType:u.resourceType||d.resource.resourceType,serverSynced:!0}),l.push({installPath:I,title:d.resource.title}),A()||w(` Updated ${I}`),d.resource.resourceType==="collection"&&d.memberResources&&h?.installMode!=="plugin"){let C=z(),p=new Set(C.installations.map(i=>i.resourceId));for(let i of d.memberResources){if(p.has(i.id))continue;let m=i.slug||i.id,y=Yo[i.resourceType]||i.resourceType+"s",x=u.orgSlug?`${u.orgSlug}/`:"",_=`${y}/${x}${m}`,b=await Z(`/api/cli/resource/${_}`);if(!b.ok){A()||R(` Failed to fetch new member ${_}: ${b.error.message}`);continue}let v=b.data,k=_.split("/").slice(1);if(v.resource.resourceType==="agent"){let P=Q(o,!!s.project);J((0,lt.join)(P,...k),v.files)}else if(v.resource.resourceType==="mcp")rr(o,!!s.project,v);else{let P=V(o,!!s.project);J((0,lt.join)(P,...k),v.files)}i.latestSha&&await F("/api/cli/install",{resourceId:i.id,agentPlatform:o.platform,installedSha:i.latestSha}).catch(()=>{}),me({resourceId:i.id,slug:m,installPath:_,title:i.title,sha:i.latestSha||"",scope:s.project?"project":"global",agent:o.id,installedAt:new Date().toISOString(),collectionId:d.resource.id,resourceType:i.resourceType,serverSynced:!0}),A()||w(` + New member: ${_}`)}}}l.length>0&&Ve(),A()?L("update",{updated:l,count:l.length}):l.length>0&&w(`
|
|
156
|
+
${l.length} resource${l.length===1?"":"s"} updated.`)})}var fe=require("fs"),St=require("path"),Qo=require("child_process");le();ge();ce();function ei(r){r.command("uninstall [path]").description("Uninstall a resource by install path (e.g., skills/acme/api-testing)").action(async(e,t,n)=>{if(!e){let d=z().installations;if(d.length===0&&(A()?D("uninstall","NOTHING_INSTALLED","No resources installed."):w("No resources installed."),process.exit(0)),A())L("uninstall",{installations:d.map(E=>({path:E.installPath||E.slug,title:E.title,agent:E.agent}))});else{w(`Installed resources:
|
|
157
157
|
`);let E=d.map(S=>[S.installPath||S.slug,S.title||"",`(${S.agent})`]);w(Se(E)),w(`
|
|
158
|
-
Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=$e(s.agent);if(!o){let f=Ge();A()?D("uninstall","NO_AGENTS",f):R(f),process.exit(1)}let a=z().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),l=e.split("/"),g=["skills","files","commands","hooks","collections","agents","mcps"].includes(l[0])?l[0]:null,h=g?l.slice(1):l,I=!1;if(g==="collections")if(a?.installMode==="plugin"){let f=
|
|
159
|
-
`,"utf-8"))}}catch{}}else if(y==="hooks")
|
|
160
|
-
`,"utf-8"),I=!0)}}catch{}}else if(g==="hooks"){let f=ke(o,!!s.project);I=
|
|
158
|
+
Usage: shared-context-ai uninstall <path>`)}return}let s=n.optsWithGlobals(),o=$e(s.agent);if(!o){let f=Ge();A()?D("uninstall","NO_AGENTS",f):R(f),process.exit(1)}let a=z().installations.find(f=>f.installPath===e||f.slug===e||f.resourceId===e),l=e.split("/"),g=["skills","files","commands","hooks","collections","agents","mcps"].includes(l[0])?l[0]:null,h=g?l.slice(1):l,I=!1;if(g==="collections")if(a?.installMode==="plugin"){let f=Qt(o.id);if(f)try{(0,Qo.execSync)(`${f} plugin uninstall "${a.slug}"`,{stdio:"pipe"}),A()||w(`Uninstalled native ${f} plugin: ${a.slug}`)}catch(d){A()||R(`Native uninstall failed: ${d}. Removing tracking only.`)}At(a.resourceId,o.id),U()&&await F("/api/cli/uninstall",{resourceId:a.resourceId,agentPlatform:o.platform}).catch(()=>{}),Ve(),A()?L("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`);return}else{let f=Le(o),d=h[h.length-1],E=s.project?"project":"user",S=await f.uninstall(d,E,o,a?.resourceId);if(I=S.removed,!A())for(let C of S.warnings)R(`Warning: ${C}`);if(a){let p=z().installations.filter(i=>i.collectionId===a.resourceId&&i.agent===o.id);for(let i of p){let m=i.installPath.split("/"),y=m[0],x=m.slice(1);if(y==="agents"){let _=Q(o,!!s.project),b=(0,St.join)(_,...x);(0,fe.existsSync)(b)&&(0,fe.rmSync)(b,{recursive:!0,force:!0})}else if(y==="mcps"){let _=x[x.length-1],b=Ee(o,!!s.project);if((0,fe.existsSync)(b))try{let v=JSON.parse((0,fe.readFileSync)(b,"utf-8"));if(typeof v.mcpServers=="object"&&v.mcpServers&&!Array.isArray(v.mcpServers)){let k=v.mcpServers;_ in k&&(delete k[_],v.mcpServers=k,(0,fe.writeFileSync)(b,JSON.stringify(v,null,2)+`
|
|
159
|
+
`,"utf-8"))}}catch{}}else if(y==="hooks")xn(ke(o,!!s.project),i.installPath);else{let _=V(o,!!s.project),b=(0,St.join)(_,...x);(0,fe.existsSync)(b)&&(0,fe.rmSync)(b,{recursive:!0,force:!0})}At(i.resourceId,o.id)}}}else if(g==="agents"){let f=Q(o,!!s.project),d=(0,St.join)(f,...h);I=(0,fe.existsSync)(d),I&&(0,fe.rmSync)(d,{recursive:!0,force:!0})}else if(g==="mcps"){let f=h[h.length-1],d=Ee(o,!!s.project);if((0,fe.existsSync)(d))try{let E=JSON.parse((0,fe.readFileSync)(d,"utf-8"));if(typeof E.mcpServers=="object"&&E.mcpServers&&!Array.isArray(E.mcpServers)){let S=E.mcpServers;f in S&&(delete S[f],E.mcpServers=S,(0,fe.writeFileSync)(d,JSON.stringify(E,null,2)+`
|
|
160
|
+
`,"utf-8"),I=!0)}}catch{}}else if(g==="hooks"){let f=ke(o,!!s.project);I=xn(f,e),!I&&!A()&&R(`Note: No tagged hook entries found in ${f} \u2014 may need manual removal if installed before v0.1.10`)}else{let f=V(o,!!s.project),d=(0,St.join)(f,...h);if(I=(0,fe.existsSync)(d),I&&(0,fe.rmSync)(d,{recursive:!0,force:!0}),!I&&a?.slug){let E=(0,St.join)(f,a.slug);(0,fe.existsSync)(E)&&(0,fe.rmSync)(E,{recursive:!0,force:!0})}}if(U()&&a){let f=await F("/api/cli/uninstall",{resourceId:a.resourceId});!f.ok&&!A()&&R(`Warning: Could not record uninstall on server: ${f.error.message}`)}a&&At(a.resourceId,o.id),Ve(),A()?L("uninstall",{path:e,removed:!0}):w(`Uninstalled "${e}"`)})}ge();le();ce();function ti(r){r.command("status").description("Show CLI status: auth, agents, installed resources, project sync state").action(async()=>{let e=Pe(),t=ve(),n=z(),s=qe(),o=Ie(),c=n.installations.filter(h=>!h.projectId),a=n.installations.filter(h=>h.projectId),l=new Map;for(let h of a){let I=h.projectId;l.has(I)||l.set(I,[]),l.get(I).push(h)}let u=[];if(U()&&l.size>0)for(let[h,I]of l){let f=await Z(`/api/cli/projects/${h}/resources`).catch(()=>null),d=f&&f.ok?f.data.resources.length:I.length,E=o?.projectId===h?o.projectName:`Project ${h.slice(0,8)}`;u.push({projectId:h,projectName:E,localCount:I.length,serverCount:d,synced:I.length>=d})}let g={authenticated:!!e?.token,email:e?.email||null,org:e?.orgSlug||null,apiBase:t.apiBase,detectedAgents:s.map(h=>h.id),installedCount:n.installations.length,globalCount:c.length,projects:u};if(A()){L("status",g);return}if(w("Shared Context CLI Status"),w("\u2500".repeat(40)),e?.token?w(` Auth: ${e.email} (${e.orgSlug})`):w(" Auth: Not logged in"),w(` API: ${t.apiBase}`),s.length>0?w(` Agents: ${s.map(h=>h.label).join(", ")}`):w(" Agents: None detected"),w(` Global: ${c.length} resource${c.length===1?"":"s"} installed`),u.length>0){w(""),w("Projects:");for(let h of u){let I=h.synced?"\u2713 synced":`\u26A0 ${h.serverCount-h.localCount} new`;w(` ${h.projectName}: ${h.localCount}/${h.serverCount} resources (${I})`)}}else o&&(w(""),w(` Project: ${o.projectName} (linked)`))})}ge();le();ce();function ri(r){r.command("logout").description("Clear saved credentials").option("--revoke","Also revoke the token on the server").action(async e=>{let t=Pe();e.revoke&&U()&&await _t("/api/cli/auth"),Ur(),A()?L("logout",{email:t?.email||null}):w("Logged out.")})}var hr=require("fs"),ni=require("path");le();ce();function si(r){r.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,n)=>{let s=n.optsWithGlobals(),o=t.github;if(o&&e&&(A()?D("import","INVALID_ARGS","Cannot use --github with a local path"):R("Error: Cannot use --github with a local path. Use one or the other."),process.exit(1)),!o&&!e&&(A()?D("import","INVALID_ARGS","Provide a local path or --github <url>"):R("Error: Provide a local path or --github <url>"),process.exit(1)),U()||(A()?D("import","AUTH_MISSING","Authentication required for import"):R("Error: Authentication required. Run 'shared-context-ai login' first."),process.exit(1)),o){t.onConflict&&t.onConflict!=="auto"&&(A()?D("import","INVALID_ARGS","--on-conflict is not supported with --github"):R("Error: --on-conflict is not supported with --github"),process.exit(1)),t.dryRun&&(A()?D("import","INVALID_ARGS","--dry-run is not supported with --github"):R("Error: --dry-run is not supported with --github"),process.exit(1));let d={url:o};t.resourceType&&(d.resourceType=t.resourceType),A()||w(`
|
|
161
161
|
Importing from GitHub: ${o}`);let E=await F("/api/cli/github-import",d);E.ok||(A()?D("import",E.error.code,E.error.message):R(`
|
|
162
|
-
Import failed: ${E.error.message}`),process.exit(1));let S=E.data;if(A()){L("import",S);return}w(""),w(` Source: ${S.source.owner}/${S.source.repo}`),w(` Type: ${S.resourceType}`),w(` Title: ${S.title}`),S.slug&&w(` Slug: ${S.slug}`),w(` URL: ${S.url}`),w(""),w("Import complete: 1 created");return}let c=(0,
|
|
162
|
+
Import failed: ${E.error.message}`),process.exit(1));let S=E.data;if(A()){L("import",S);return}w(""),w(` Source: ${S.source.owner}/${S.source.repo}`),w(` Type: ${S.resourceType}`),w(` Title: ${S.title}`),S.slug&&w(` Slug: ${S.slug}`),w(` URL: ${S.url}`),w(""),w("Import complete: 1 created");return}let c=(0,ni.resolve)(e);(!(0,hr.existsSync)(c)||!(0,hr.statSync)(c).isDirectory())&&(A()?D("import","INVALID_PATH",`Not a directory: ${c}`):R(`Error: Not a directory: ${c}`),process.exit(1));let a=dr(c);if(a.resources.length===0){A()?L("import",{resources:[],message:"No resources found"}):w("No resources found in the specified directory.");return}if(!A()){let d=new Map;for(let S of a.resources)d.set(S.resourceType,(d.get(S.resourceType)||0)+1);let E=[...d.entries()].map(([S,C])=>`${C} ${S}${C===1?"":"s"}`).join(", ");w(`
|
|
163
163
|
Discovered ${a.resources.length} resources in ${e}:`),w(` ${E}`),a.formatLabel&&a.pluginName?w(` ${a.formatLabel}: ${a.pluginName}`):a.pluginName&&w(` Plugin: ${a.pluginName}`)}let l=t.tags?t.tags.split(",").map(d=>d.trim()).filter(Boolean):void 0,u={dryRun:!!t.dryRun,onConflict:t.onConflict||"auto",visibility:t.visibility||"org",topicTags:l,resources:a.resources,collectionMemberships:a.collectionMemberships.length>0?a.collectionMemberships:void 0};!A()&&!t.dryRun?w(`
|
|
164
164
|
Executing import...`):A()||w(`
|
|
165
165
|
Dry run \u2014 previewing changes...`);let g=await F("/api/cli/import",u,12e4);g.ok||(A()?D("import",g.error.code,g.error.message):R(`
|
|
166
|
-
Import failed: ${g.error.message}`),process.exit(1));let h=g.data;if(A()){L("import",h);return}let I=[...h.created.map(d=>({...d,action:"created"})),...h.updated.map(d=>({...d,action:"updated"})),...h.installed.map(d=>({...d,action:"installed"})),...h.cloned.map(d=>({...d,action:"cloned"})),...h.skipped.map(d=>({...d,action:"skipped"})),...h.errors.map(d=>({...d,action:"error"}))];if(I.length>0){w("");let d=I.length,E=I.map((S,C)=>{let p=`[${String(C+1).padStart(String(d).length)}/${d}]`,i=(S.resourceType||"").padEnd(10),m=(S.importPath.split("/").pop()||"").padEnd(24),y="";switch(S.action){case"created":y=`\u2713 created${S.slug?` (slug: ${S.slug})`:""}`;break;case"updated":y="\u2713 updated";break;case"installed":{let x=S.versionsBehind;y=`\u2713 installed${x?` (${x} versions behind)`:""}`;break}case"cloned":y=`\u2713 cloned${S.slug?` (slug: ${S.slug})`:""}`;break;case"skipped":y=`\u2713 skipped (${S.reason||"up to date"})`;break;case"error":y=`\u2717 error: ${S.error||"unknown"}`;break}return` ${p} ${i} ${m} ${y}`});for(let S of E)w(S)}if(h.collections.length>0)for(let d of h.collections){let E=d.importPath.split("/").pop()||d.importPath;w(` collection ${E.padEnd(20)} \u2713 ${d.membersLinked} members linked${d.membersFailed>0?`, ${d.membersFailed} failed`:""}`)}w("");let f=[h.created.length>0?`${h.created.length} created`:null,h.installed.length>0?`${h.installed.length} installed`:null,h.cloned.length>0?`${h.cloned.length} cloned`:null,h.updated.length>0?`${h.updated.length} updated`:null,h.skipped.length>0?`${h.skipped.length} skipped`:null,h.errors.length>0?`${h.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${f.join(", ")}`):w(`Import complete: ${f.join(", ")}`),h.errors.length>0&&process.exit(1)})}var Tt=require("path"),
|
|
166
|
+
Import failed: ${g.error.message}`),process.exit(1));let h=g.data;if(A()){L("import",h);return}let I=[...h.created.map(d=>({...d,action:"created"})),...h.updated.map(d=>({...d,action:"updated"})),...h.installed.map(d=>({...d,action:"installed"})),...h.cloned.map(d=>({...d,action:"cloned"})),...h.skipped.map(d=>({...d,action:"skipped"})),...h.errors.map(d=>({...d,action:"error"}))];if(I.length>0){w("");let d=I.length,E=I.map((S,C)=>{let p=`[${String(C+1).padStart(String(d).length)}/${d}]`,i=(S.resourceType||"").padEnd(10),m=(S.importPath.split("/").pop()||"").padEnd(24),y="";switch(S.action){case"created":y=`\u2713 created${S.slug?` (slug: ${S.slug})`:""}`;break;case"updated":y="\u2713 updated";break;case"installed":{let x=S.versionsBehind;y=`\u2713 installed${x?` (${x} versions behind)`:""}`;break}case"cloned":y=`\u2713 cloned${S.slug?` (slug: ${S.slug})`:""}`;break;case"skipped":y=`\u2713 skipped (${S.reason||"up to date"})`;break;case"error":y=`\u2717 error: ${S.error||"unknown"}`;break}return` ${p} ${i} ${m} ${y}`});for(let S of E)w(S)}if(h.collections.length>0)for(let d of h.collections){let E=d.importPath.split("/").pop()||d.importPath;w(` collection ${E.padEnd(20)} \u2713 ${d.membersLinked} members linked${d.membersFailed>0?`, ${d.membersFailed} failed`:""}`)}w("");let f=[h.created.length>0?`${h.created.length} created`:null,h.installed.length>0?`${h.installed.length} installed`:null,h.cloned.length>0?`${h.cloned.length} cloned`:null,h.updated.length>0?`${h.updated.length} updated`:null,h.skipped.length>0?`${h.skipped.length} skipped`:null,h.errors.length>0?`${h.errors.length} errors`:null].filter(Boolean);t.dryRun?w(`Dry run complete: ${f.join(", ")}`):w(`Import complete: ${f.join(", ")}`),h.errors.length>0&&process.exit(1)})}var Tt=require("path"),fi=require("os"),di=require("fs");le();ge();ce();var gc={skill:"skills",file:"files",command:"commands",hook:"hooks",collection:"collections",agent:"agents",mcp:"mcps"};function li(r,e){let t=r.installations.findIndex(n=>n.resourceId===e.resourceId&&n.agent===e.agent);t>=0?r.installations[t]=e:r.installations.push(e)}function hc(r,e,t){if(!e)return null;let n=r.installPath.split("/").slice(1);return n.length===0?null:r.resourceType==="agent"?(0,Tt.join)(Q(e,t),...n):(0,Tt.join)(V(e,t),...n)}function ui(r){let e=r.slug||r.resourceId,t=gc[r.resourceType]||r.resourceType+"s";return r.storageType==="github"&&r.githubOwner?`${t}/external/${r.githubOwner}/${e}`:r.orgSlug?`${t}/${r.orgSlug}/${e}`:`${t}/${e}`}function pi(r){r.command("sync").description("Synchronize resource state \u2014 check for updates and discover untracked resources").option("--quiet","Minimal output (one-line summary)").option("--force","Bypass throttle and sync now").option("--no-import","Skip auto-importing untracked resources").option("--dry-run","Report what sync would do without writing to disk or server").action(async(e,t)=>{let n={...e,...t.optsWithGlobals()},s=n.dryRun===!0,o=[],c=[];if(!n.force&&!Wr()){let O=z(),N=O.installations.filter(H=>H.latestSha&&H.sha&&H.latestSha!==H.sha),M=O.lastSyncAt?Math.floor((Date.now()-new Date(O.lastSyncAt).getTime())/6e4):void 0,q={updatesAvailable:N.length,untrackedResources:0,driftRepairs:0,autoInstalled:0,autoInstallFailures:0,updates:N.map(H=>({installPath:H.installPath,title:H.title,sha:H.sha,latestSha:H.latestSha,version:H.publicationVersion??null,latestVersion:H.latestPublicationVersion??null})),untracked:[],summary:Dn({updatesAvailable:N.length,untrackedResources:0})+(M!==void 0?` (cached ${M}m ago, run --force to refresh)`:""),throttled:!0,cacheAge:M,conflicts:[],deletedLocally:[],dryRun:s};Nn(q,!!n.quiet);return}U()||(A()?D("sync","AUTH_MISSING","Login required to sync."):R("Login required. Run 'shared-context-ai login'."),process.exit(1));let a=$e(n.agent),l=await Z("/api/cli/installed");if(!l.ok){let N=z().installations.filter(q=>q.latestSha&&q.sha&&q.latestSha!==q.sha);!A()&&!n.quiet&&R(`Warning: Could not reach server (${l.error.message}). Showing cached state.`);let M={updatesAvailable:N.length,untrackedResources:0,driftRepairs:0,autoInstalled:0,autoInstallFailures:0,updates:N.map(q=>({installPath:q.installPath,title:q.title,sha:q.sha,latestSha:q.latestSha,version:q.publicationVersion??null,latestVersion:q.latestPublicationVersion??null})),untracked:[],summary:Dn({updatesAvailable:N.length,untrackedResources:0})+" (offline)",throttled:!1,conflicts:[],deletedLocally:[],dryRun:s};Nn(M,!!n.quiet);return}let u=l.data.installations,g=new Map(u.map(O=>[O.resourceId,O])),h=z(),I=0;for(let O of h.installations){if(!O.installPath||O.resourceType==="mcp"||O.resourceType==="hook")continue;let N=hc(O,a,!!n.project);N&&!(0,di.existsSync)(N)&&(c.push({installPath:O.installPath,title:O.title}),!s&&O.serverSynced!==!1&&await F("/api/cli/uninstall",{resourceId:O.resourceId,agentPlatform:a?.platform||"claude_code"}).catch(()=>{}),O.resourceId="")}h.installations=h.installations.filter(O=>O.resourceId!=="");for(let O of h.installations){let N=g.get(O.resourceId);if(N)O.latestSha=N.latestSha||void 0,O.resourceType=O.resourceType||N.resourceType,O.serverSynced=!0,N.publicationVersion!==void 0&&(O.publicationVersion=N.publicationVersion),N.publicationId!==void 0&&(O.publicationId=N.publicationId),N.latestPublicationVersion!==void 0&&(O.latestPublicationVersion=N.latestPublicationVersion),N.latestPublicationId!==void 0&&(O.latestPublicationId=N.latestPublicationId),N.installedSha&&O.sha&&N.installedSha!==O.sha&&(!A()&&!n.quiet&&w(` Drift repaired: ${O.installPath} (local=${O.sha.slice(0,7)} \u2192 server=${N.installedSha.slice(0,7)})`),O.sha=N.installedSha,I++),g.delete(O.resourceId);else if(O.serverSynced!==!1){if(s)continue;let M=await F("/api/cli/install",{resourceId:O.resourceId,agentPlatform:a?.platform||"claude_code",installedSha:O.sha});M.ok?O.serverSynced=!0:(M.error.code==="NOT_FOUND"||M.error.code==="RESOURCE_NOT_FOUND")&&(O.serverSynced=!1,O.resourceId="",I++)}}h.installations=h.installations.filter(O=>O.resourceId!=="");let f=Array.from(g.values()),d=0,E=0,S=!1;if(f.length>0&&a){for(let O of f){if(S){E++;continue}let N=ui(O);try{let M=await Z(`/api/cli/resource/${N}`);if(!M.ok){if(E++,M.error.code==="RATE_LIMITED"||M.error.code==="429"){S=!0,!A()&&!n.quiet&&R(` Auto-install rate-limited after ${d} resource(s). Remaining will retry on next sync.`);continue}!A()&&!n.quiet&&R(` Auto-install skipped: ${N} \u2014 ${M.error.message}`);continue}let q=M.data,H=await An(q,a,{project:!1,manifest:h,authed:!0,dryRun:s});for(let oe of H.warnings)!A()&&!n.quiet&&R(` Warning: ${oe}`);for(let oe of H.notes)!A()&&!n.quiet&&w(` ${oe}`);for(let oe of H.preserved)o.push({installPath:H.installPath,filePath:oe.filePath,preservedPath:oe.preservedPath});let Qe=q.resource.resourceType==="collection",je={resourceId:q.resource.id,slug:H.slug,installPath:H.installPath,title:q.resource.title,sha:q.resource.latestSha||O.installedSha||"",scope:"global",agent:a.id,installedAt:new Date().toISOString(),latestSha:q.resource.latestSha||void 0,resourceType:q.resource.resourceType,serverSynced:!0,...Object.keys(H.contentHashes).length>0?{contentHashes:H.contentHashes}:{},...Qe?{pluginFormat:Xt(a.id),memberCount:q.memberResources?.length,installMode:H.installMode,pluginDir:H.pluginDir}:{}};if(s||li(h,je),Qe&&q.memberResources&&H.installMode==="decomposed"&&!s)for(let oe of q.memberResources)li(h,In(oe,q.resource,a.id));d++}catch(M){E++,!A()&&!n.quiet&&R(` Auto-install failed: ${N} \u2014 ${M}`)}}d>0&&!A()&&!n.quiet&&w(`
|
|
167
167
|
Auto-installed ${d} resource${d===1?"":"s"} from web dashboard`)}else if(f.length>0&&!A()&&!n.quiet){w(`
|
|
168
|
-
${f.length} resource${f.length===1?"":"s"} installed elsewhere (use --agent to auto-install):`);for(let O of f.slice(0,5))w(` ${
|
|
168
|
+
${f.length} resource${f.length===1?"":"s"} installed elsewhere (use --agent to auto-install):`);for(let O of f.slice(0,5))w(` ${ui(O)} \u2014 ${O.title}`);f.length>5&&w(` ...and ${f.length-5} more`)}s||Be(h);let C=a?[a]:qe();C.length===0&&!A()&&!n.quiet&&R("No AI agents detected \u2014 resource discovery skipped. Use --agent to specify one.");let p=C.map(O=>({root:n.project?(0,Tt.join)(process.cwd(),O.dir):(0,Tt.join)((0,fi.homedir)(),O.dir),agent:O,isProject:!!n.project})),i={imported:[],errors:0,projectRegistered:0,untrackedCount:0,discoveredPaths:[],untracked:[]};if(p.length>0){if(i=await pr({scanRoots:p,agentId:a?.id||C[0]?.id||"unknown",registerToProject:!!n.project,skipImport:n.import===!1||s}),i.imported.length>0&&!A()&&!n.quiet){w(`
|
|
169
169
|
Imported ${i.imported.length} resource${i.imported.length===1?"":"s"}:`);let O=i.imported.map(N=>[` ${(N.resourceType||"").padEnd(12)}`,(N.slug||N.importPath.split("/").pop()||"").padEnd(24),N.importPath]);w(Se(O))}if(i.errors>0&&!A()&&R(`
|
|
170
170
|
${i.errors} import error(s)`),i.projectRegistered>0&&!A()&&!n.quiet){let O=Ie();w(`
|
|
171
|
-
Project "${O?.projectName}": registered ${i.projectRegistered} resource${i.projectRegistered===1?"":"s"}`)}}let m=i.untrackedCount,y=s?null:Ie(),x=0;if(y){let O=await
|
|
172
|
-
Project "${y.projectName}" has ${Qe.length} new resource${Qe.length===1?"":"s"} \u2014 use --agent to install them.`);else{let je=Le(a);for(let oe of Qe){let et=oe.installPath;try{let Fe=await
|
|
171
|
+
Project "${O?.projectName}": registered ${i.projectRegistered} resource${i.projectRegistered===1?"":"s"}`)}}let m=i.untrackedCount,y=s?null:Ie(),x=0;if(y){let O=await Z(`/api/cli/projects/${y.projectId}/resources`);if(!O.ok)!A()&&!n.quiet&&(R(`Warning: Project "${y.projectName}" not found on server (may have been deleted).`),R(" Remove .shared-context/project.json to unlink this directory."));else{let N=O.data.project;N&&(N.name!==y.projectName||N.slug!==y.projectSlug)&&st({projectId:y.projectId,projectName:N.name,projectSlug:N.slug});let M=O.data.resources,q=h.installations.filter(je=>je.projectId===y.projectId),H=new Set(q.map(je=>je.resourceId)),Qe=M.filter(je=>!H.has(je.id));if(Qe.length>0)if(!a)!A()&&!n.quiet&&R(`
|
|
172
|
+
Project "${y.projectName}" has ${Qe.length} new resource${Qe.length===1?"":"s"} \u2014 use --agent to install them.`);else{let je=Le(a);for(let oe of Qe){let et=oe.installPath;try{let Fe=await Z(`/api/cli/resource/${et}`);if(!Fe.ok)continue;await je.install(Fe.data,"project",a),me({resourceId:oe.id,slug:oe.slug||oe.id,installPath:et,title:oe.title,sha:oe.latestSha||"",scope:"project",agent:a.id,installedAt:new Date().toISOString(),projectId:y.projectId,resourceType:oe.resourceType,serverSynced:!0}),oe.latestSha&&await F("/api/cli/install",{resourceId:oe.id,agentPlatform:a.platform,installedSha:oe.latestSha}).catch(()=>{}),x++}catch{}}!A()&&!n.quiet&&x>0&&w(`
|
|
173
173
|
Project "${y.projectName}": installed ${x} new resource${x===1?"":"s"}`)}if(n.project){let je=new Set(M.map(Fe=>Fe.id)),oe=new Set(i.discoveredPaths),et=0;for(let Fe of h.installations){if(je.has(Fe.resourceId)||!oe.has(Fe.installPath))continue;(await F(`/api/cli/projects/${y.projectId}/resources`,{resourceId:Fe.resourceId})).ok&&(Fe.projectId=y.projectId,et++)}et>0&&!A()&&!n.quiet&&w(`
|
|
174
|
-
Project "${y.projectName}": registered ${et} existing resource${et===1?"":"s"}`)}await F(`/api/cli/projects/${y.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let _=i.imported.length,b=z(),v=new Set(b.installations.map(O=>`${O.resourceId}:${O.agent}`)),k=[...b.installations,...h.installations.filter(O=>!v.has(`${O.resourceId}:${O.agent}`))];h.installations=k;let P=o.length>0;if(n.force){let O=h.lastSyncAt;h.lastSyncAt=O||new Date().toISOString()}else E===0&&!P&&(h.lastSyncAt=new Date().toISOString());s||Be(h);let j=h.installations.filter(O=>O.latestSha&&O.sha&&O.latestSha!==O.sha),$=Pe();if($?.connectionId&&!s&&F("/api/cli/sync-report",{connectionId:$.connectionId,lastSyncResult:{updatesAvailable:j.length,importedCount:_}}).catch(()=>{}),!s)try{let{pushTelemetry:O}=await Promise.resolve().then(()=>(
|
|
174
|
+
Project "${y.projectName}": registered ${et} existing resource${et===1?"":"s"}`)}await F(`/api/cli/projects/${y.projectId}/sync`,{localPath:process.cwd()}).catch(()=>{})}}let _=i.imported.length,b=z(),v=new Set(b.installations.map(O=>`${O.resourceId}:${O.agent}`)),k=[...b.installations,...h.installations.filter(O=>!v.has(`${O.resourceId}:${O.agent}`))];h.installations=k;let P=o.length>0;if(n.force){let O=h.lastSyncAt;h.lastSyncAt=O||new Date().toISOString()}else E===0&&!P&&(h.lastSyncAt=new Date().toISOString());s||Be(h);let j=h.installations.filter(O=>O.latestSha&&O.sha&&O.latestSha!==O.sha),$=Pe();if($?.connectionId&&!s&&F("/api/cli/sync-report",{connectionId:$.connectionId,lastSyncResult:{updatesAvailable:j.length,importedCount:_}}).catch(()=>{}),!s)try{let{pushTelemetry:O}=await Promise.resolve().then(()=>(jn(),ci));await O(!0)}catch{}let K=i.untracked,ae={updatesAvailable:j.length,untrackedResources:K.length,driftRepairs:I,autoInstalled:d,autoInstallFailures:E,updates:j.map(O=>({installPath:O.installPath,title:O.title,sha:O.sha,latestSha:O.latestSha,version:O.publicationVersion??null,latestVersion:O.latestPublicationVersion??null})),untracked:K,summary:Dn({updatesAvailable:j.length,untrackedResources:K.length,driftRepairs:I,autoInstalled:d,autoInstallFailures:E,conflicts:o.length,deletedLocally:c.length,dryRun:s}),throttled:!1,conflicts:o,deletedLocally:c,dryRun:s};Nn(ae,!!n.quiet),o.length>0&&(A()||!process.stdout.isTTY)&&process.exit(2)})}function Dn(r){let e=[];return r.dryRun&&e.push("DRY RUN"),r.autoInstalled&&e.push(`${r.autoInstalled} auto-installed`),r.updatesAvailable>0&&e.push(`${r.updatesAvailable} update${r.updatesAvailable===1?"":"s"} available`),r.untrackedResources>0&&e.push(`${r.untrackedResources} untracked resource${r.untrackedResources===1?"":"s"}`),r.driftRepairs&&e.push(`${r.driftRepairs} drift repair${r.driftRepairs===1?"":"s"}`),r.conflicts&&e.push(`${r.conflicts} local edit${r.conflicts===1?"":"s"} preserved to .local/`),r.deletedLocally&&e.push(`${r.deletedLocally} uninstalled-by-deletion`),r.autoInstallFailures&&e.push(`${r.autoInstallFailures} auto-install failure${r.autoInstallFailures===1?"":"s"}`),e.length===0?"Everything is up to date.":e.join(", ")}function Nn(r,e){if(A()){L("sync",r);return}if(e){let t=r.summary;r.updatesAvailable>0&&(t+=" \u2014 run 'shared-context-ai update'"),r.untrackedResources>0&&(t+=` \u2014 ${r.untrackedResources} untracked`),w(t);return}if(w(""),r.dryRun&&w(`[DRY RUN] No disk or server writes performed. Re-run without --dry-run to apply.
|
|
175
175
|
`),r.updates.length>0){w(`${r.updates.length} update${r.updates.length===1?"":"s"} available:
|
|
176
176
|
`);let t=r.updates.map(n=>{let s=n.version??`${n.sha.slice(0,7)}`,o=n.latestVersion??`${n.latestSha.slice(0,7)}`;return[` ${n.installPath}`,n.title,`${s} \u2192 ${o}`]});w(Se(t)),w("")}if(r.untracked.length>0){w(`${r.untracked.length} untracked resource${r.untracked.length===1?"":"s"}:
|
|
177
177
|
`);let t=r.untracked.map(n=>[` ${n.resourceType.padEnd(12)}`,n.importPath.padEnd(30),n.title]);w(Se(t)),w("")}if(r.conflicts.length>0){w(`${r.conflicts.length} local edit${r.conflicts.length===1?"":"s"} preserved before overwrite:
|
|
178
178
|
`);let t=r.conflicts.map(n=>[` ${n.installPath}`,n.filePath,`\u2192 ${n.preservedPath}`]);w(Se(t)),w(""),w(" Review the .local/ copies, then either keep them or remove them."),w(` The next 'sync' will re-surface this list until lastSyncAt advances.
|
|
179
179
|
`)}if(r.deletedLocally.length>0){w(`${r.deletedLocally.length} resource${r.deletedLocally.length===1?"":"s"} uninstalled by local deletion:
|
|
180
|
-
`);for(let t of r.deletedLocally)w(` ${t.installPath} \u2014 ${t.title}`);w("")}r.updatesAvailable===0&&r.untrackedResources===0&&r.conflicts.length===0&&r.deletedLocally.length===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var
|
|
181
|
-
`).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function
|
|
182
|
-
`),c.size>0){w("Skills:");let l=[...c.entries()].sort((u,g)=>g[1].count-u[1].count).map(([u,g])=>[` ${u}`,`${g.count} use${g.count===1?"":"s"}`,`${Math.round(g.ok/g.count*100)}% ok`]);w(Se(l))}if(a.size>0){c.size>0&&w(""),w("Agents:");let l=[...a.entries()].sort((u,g)=>g[1].count-u[1].count).map(([u,g])=>{let h=g.count>0?Math.round(g.totalMs/g.count):0;return[` ${u}`,`${g.count} use${g.count===1?"":"s"}`,`${Math.round(g.ok/g.count*100)}% ok`,h>0?`avg ${(h/1e3).toFixed(1)}s`:""]});w(Se(l))}})}var jt=require("fs"),Dt=require("path"),Er=require("os");ge();ce();function
|
|
183
|
-
`,"utf8")}}}catch{}}function
|
|
180
|
+
`);for(let t of r.deletedLocally)w(` ${t.installPath} \u2014 ${t.title}`);w("")}r.updatesAvailable===0&&r.untrackedResources===0&&r.conflicts.length===0&&r.deletedLocally.length===0?w("Everything is up to date."):(r.updatesAvailable>0&&w("Run 'shared-context-ai update' to update installed resources."),r.untrackedResources>0&&w("Run 'shared-context-ai sync --force' to re-sync and import untracked resources.")),w("")}var mi=require("path"),gi=require("readline");le();le();ce();function hi(r){let e=r.command("project").description("Manage projects");e.command("create").description("Create a project for the current folder").argument("[name]","Project name (defaults to folder name)").action(async t=>{if(!U()){let u="Not authenticated. Run 'shared-context-ai login' first.";A()?D("project create","AUTH_MISSING",u):R(u),process.exit(1)}let n=Ie();if(n){A()?L("project create",{alreadyExists:!0,project:{id:n.projectId,name:n.projectName,slug:n.projectSlug}}):w(`Project already linked: ${n.projectName}`);return}let s=t?.trim()||(0,mi.basename)(process.cwd());if(!s||s==="/"){let u='Could not determine project name. Provide one: shared-context-ai project create "My Project"';A()?D("project create","INVALID_NAME",u):R(u),process.exit(1)}let o=await F("/api/cli/projects",{name:s});o.ok||(A()?D("project create",o.error.code,o.error.message):R(`Failed to create project: ${o.error.message}`),process.exit(1));let{id:c,name:a,slug:l}=o.data;st({projectId:c,projectName:a,projectSlug:l}),A()?L("project create",{id:c,name:a,slug:l}):(w(`Created project: ${a}`),w(""),w("Quick reference:"),w(" shared-context-ai install <installPath> Add a resource to this project"),w(" shared-context-ai sync Check for resource updates"),w(" shared-context-ai status View project sync status"))}),e.command("delete").description("Delete the project linked to the current folder").option("--id <projectId>","Project ID to delete (overrides local config)").option("--force","Skip confirmation prompt").action(async t=>{if(!U()){let a="Not authenticated. Run 'shared-context-ai login' first.";A()?D("project delete","AUTH_MISSING",a):R(a),process.exit(1)}let n=Ie(),s=t.id||n?.projectId,o=n?.projectName||s;if(!s){let a="No project linked to this folder. Use --id <projectId> to specify one.";A()?D("project delete","NO_PROJECT",a):R(a),process.exit(1)}if(!t.force&&!A()&&process.stdin.isTTY&&!await new Promise(l=>{let u=(0,gi.createInterface)({input:process.stdin,output:process.stdout});u.question(`Delete project "${o}"? This cannot be undone. [y/N] `,g=>{u.close(),l(g.trim().toLowerCase()==="y"||g.trim().toLowerCase()==="yes")})})){w("Cancelled.");return}let c=await _t(`/api/cli/projects/${s}`);c.ok||(A()?D("project delete",c.error.code,c.error.message):R(`Failed to delete project: ${c.error.message}`),process.exit(1)),n?.projectId===s&&_o(),A()?L("project delete",{deleted:!0,projectId:s}):w(`Deleted project: ${c.data.name}`)})}jn();var Sr=require("fs"),yr=require("path"),$n=require("os");ce();function yc(){let r=process.env.SC_PROFILE;return r?(0,yr.join)((0,$n.homedir)(),".config","shared-context","profiles",r):(0,yr.join)((0,$n.homedir)(),".config","shared-context")}function Sc(){let r=(0,yr.join)(yc(),"usage.jsonl");if(!(0,Sr.existsSync)(r))return[];try{let e=(0,Sr.readFileSync)(r,"utf8").trim().split(`
|
|
181
|
+
`).filter(Boolean),t=[];for(let n of e)try{let s=JSON.parse(n);s.v&&s.ts&&s.event&&s.rid&&t.push(s)}catch{}return t}catch{return[]}}function yi(r){r.command("stats").description("Show local usage statistics").option("--days <n>","Number of days to show","7").action(e=>{let t=parseInt(e.days,10)||7,n=new Date;n.setDate(n.getDate()-t);let o=Sc().filter(l=>new Date(l.ts)>=n);if(o.length===0){A()?L("stats",{days:t,events:0,skills:[],agents:[]}):w("No usage data yet");return}let c=new Map,a=new Map;for(let l of o)if(l.event==="skill_invoked"){let u=c.get(l.slug)||{count:0,ok:0};u.count++,l.ok&&u.ok++,c.set(l.slug,u)}else if(l.event==="agent_invoked"){let u=a.get(l.slug)||{count:0,ok:0,totalMs:0,totalTokens:0};u.count++,l.ok&&u.ok++,l.dur_ms&&(u.totalMs+=l.dur_ms),l.tokens&&(u.totalTokens+=l.tokens),a.set(l.slug,u)}if(A()){L("stats",{days:t,events:o.length,skills:[...c.entries()].map(([l,u])=>({slug:l,...u})),agents:[...a.entries()].map(([l,u])=>({slug:l,...u,avgMs:u.count>0?Math.round(u.totalMs/u.count):0,avgTokens:u.count>0?Math.round(u.totalTokens/u.count):0}))});return}if(w(`Usage over the last ${t} day${t===1?"":"s"} (${o.length} event${o.length===1?"":"s"})
|
|
182
|
+
`),c.size>0){w("Skills:");let l=[...c.entries()].sort((u,g)=>g[1].count-u[1].count).map(([u,g])=>[` ${u}`,`${g.count} use${g.count===1?"":"s"}`,`${Math.round(g.ok/g.count*100)}% ok`]);w(Se(l))}if(a.size>0){c.size>0&&w(""),w("Agents:");let l=[...a.entries()].sort((u,g)=>g[1].count-u[1].count).map(([u,g])=>{let h=g.count>0?Math.round(g.totalMs/g.count):0;return[` ${u}`,`${g.count} use${g.count===1?"":"s"}`,`${Math.round(g.ok/g.count*100)}% ok`,h>0?`avg ${(h/1e3).toFixed(1)}s`:""]});w(Se(l))}})}var jt=require("fs"),Dt=require("path"),Er=require("os");ge();ce();function Ec(){let r=process.env.SC_PROFILE;return r?(0,Dt.join)((0,Er.homedir)(),".config","shared-context","profiles",r):(0,Dt.join)((0,Er.homedir)(),".config","shared-context")}var Cc=new Set(["hooks/shared-context/telemetry","platform/telemetry-push"]);function wc(){Mt({telemetry:!1});let r=(0,Dt.join)(Ec(),"usage.jsonl");try{(0,jt.existsSync)(r)&&(0,jt.unlinkSync)(r)}catch{}try{let e=(0,Dt.join)((0,Er.homedir)(),".claude","settings.json");if((0,jt.existsSync)(e)){let{readFileSync:t,writeFileSync:n}=require("fs"),s=JSON.parse(t(e,"utf8"));if(s.hooks){let o=!1;for(let[c,a]of Object.entries(s.hooks))if(Array.isArray(a)){let l=a.filter(u=>!Cc.has(u._sc));l.length!==a.length&&(s.hooks[c]=l,o=!0)}for(let[c,a]of Object.entries(s.hooks))Array.isArray(a)&&a.length===0&&delete s.hooks[c];o&&n(e,JSON.stringify(s,null,2)+`
|
|
183
|
+
`,"utf8")}}}catch{}}function Si(r){let e=r.command("config").description("Manage CLI configuration");e.command("set <key> <value>").description("Set a configuration value (e.g., telemetry on/off)").action((t,n)=>{if(t==="telemetry"){let s=n==="on"||n==="true"||n==="1",o=n==="off"||n==="false"||n==="0";if(!s&&!o){A()?D("config","INVALID_VALUE","Telemetry value must be on or off"):R("Usage: shared-context-ai config set telemetry on|off");return}o?(wc(),A()?L("config",{key:"telemetry",value:!1}):w("Telemetry disabled. Usage data and hooks removed.")):(Mt({telemetry:!0}),A()?L("config",{key:"telemetry",value:!0}):w("Telemetry enabled. Run `shared-context-ai sync` to install the telemetry hook if it is not already installed."));return}A()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}. Available: telemetry`)}),e.command("get [key]").description("Show configuration values").action(t=>{let n=ve();if(t==="telemetry"){let s=n.telemetry??!1;A()?L("config",{key:"telemetry",value:s}):w(`telemetry: ${s?"on":"off"}`);return}if(t){A()?D("config","UNKNOWN_KEY",`Unknown config key: ${t}`):R(`Unknown config key: ${t}`);return}A()?L("config",{telemetry:n.telemetry??!1}):w(`telemetry: ${n.telemetry?"on":"off"}`)})}var Ei={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."},Cr=class extends Error{constructor(t,n){super(n||Ei[t]);this.code=t;this.name="CliError"}get recovery(){return Ei[this.code]}};ce();var pe=new Kn;pe.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",r=>{let e=r.opts();Qn(!!e.json,!!e.human)});Bo(pe);Ms(pe);Wo(pe);jo(pe);Go(pe);zo(pe);Zo(pe);Xo(pe);ei(pe);ti(pe);ri(pe);si(pe);pi(pe);hi(pe);Tn(pe);yi(pe);Si(pe);process.on("uncaughtException",r=>{r instanceof Cr?A()?D(process.argv[2]||"unknown",r.code,r.message):(R(`Error: ${r.message}`),R(r.recovery)):A()?D(process.argv[2]||"unknown","UNEXPECTED",r.message||"Unexpected error"):R(`Error: ${r.message||r}`),process.exit(1)});pe.parse();
|