skill-creator 1.5.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/LICENSE +21 -0
- package/README.md +248 -345
- package/dist/cli.js +51129 -0
- package/dist/cli.js.map +7 -0
- package/dist/daemon.js +52163 -0
- package/dist/daemon.js.map +7 -0
- package/dist/package.json +5 -0
- package/dist/webui/_app/immutable/assets/0.0XN00VKF.css +2 -0
- package/dist/webui/_app/immutable/assets/ProviderView.DEH95hqa.css +1 -0
- package/dist/webui/_app/immutable/assets/inter-cyrillic-ext-wght-normal.BOeWTOD4.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-cyrillic-wght-normal.DqGufNeO.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-greek-ext-wght-normal.DlzME5K_.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-greek-wght-normal.CkhJZR-_.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-latin-ext-wght-normal.DO1Apj_S.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-latin-wght-normal.Dx4kXJAl.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/inter-vietnamese-wght-normal.CBcvBZtf.woff2 +0 -0
- package/dist/webui/_app/immutable/assets/shell.U4CQV8re.css +1 -0
- package/dist/webui/_app/immutable/chunks/0umLG1IN.js +1 -0
- package/dist/webui/_app/immutable/chunks/B2zyE4XX.js +1 -0
- package/dist/webui/_app/immutable/chunks/BD9g8Udg.js +1 -0
- package/dist/webui/_app/immutable/chunks/BEPs9Z9s.js +1 -0
- package/dist/webui/_app/immutable/chunks/BEsyQXpe.js +1 -0
- package/dist/webui/_app/immutable/chunks/BIfnT_mK.js +1 -0
- package/dist/webui/_app/immutable/chunks/BYNWtKcf.js +259 -0
- package/dist/webui/_app/immutable/chunks/B_YFzSAv.js +2 -0
- package/dist/webui/_app/immutable/chunks/BaH4uqzh.js +1 -0
- package/dist/webui/_app/immutable/chunks/Bjy-W4x2.js +81 -0
- package/dist/webui/_app/immutable/chunks/BkEnd9_Z.js +1 -0
- package/dist/webui/_app/immutable/chunks/BrDKAjtR.js +1 -0
- package/dist/webui/_app/immutable/chunks/Bs27XW8_.js +1 -0
- package/dist/webui/_app/immutable/chunks/BySEbwqx.js +1 -0
- package/dist/webui/_app/immutable/chunks/C3mlWJXx.js +1 -0
- package/dist/webui/_app/immutable/chunks/CEpOi93z.js +2 -0
- package/dist/webui/_app/immutable/chunks/CIFG41pU.js +1 -0
- package/dist/webui/_app/immutable/chunks/CNPsST_i.js +1 -0
- package/dist/webui/_app/immutable/chunks/CQD9uzpA.js +1 -0
- package/dist/webui/_app/immutable/chunks/CeR4do8T.js +1 -0
- package/dist/webui/_app/immutable/chunks/Ckw1quWt.js +1 -0
- package/dist/webui/_app/immutable/chunks/CmCJ0SKP.js +3 -0
- package/dist/webui/_app/immutable/chunks/D-V0xBeS.js +1 -0
- package/dist/webui/_app/immutable/chunks/D-ecV3TD.js +1 -0
- package/dist/webui/_app/immutable/chunks/D0xHg31U.js +1 -0
- package/dist/webui/_app/immutable/chunks/D25cXQtk.js +1 -0
- package/dist/webui/_app/immutable/chunks/D8Der6oM.js +1 -0
- package/dist/webui/_app/immutable/chunks/DEtYLPO4.js +8 -0
- package/dist/webui/_app/immutable/chunks/DJNLWtK-.js +1 -0
- package/dist/webui/_app/immutable/chunks/DLuJKUyD.js +1 -0
- package/dist/webui/_app/immutable/chunks/DWcQbrnv.js +52 -0
- package/dist/webui/_app/immutable/chunks/DZ_Kltd5.js +1 -0
- package/dist/webui/_app/immutable/chunks/DecrR9TK.js +1 -0
- package/dist/webui/_app/immutable/chunks/Dl8eQ129.js +5 -0
- package/dist/webui/_app/immutable/chunks/Dnkino9G.js +1 -0
- package/dist/webui/_app/immutable/chunks/HclGiUj8.js +1 -0
- package/dist/webui/_app/immutable/chunks/IYkYSIV6.js +1 -0
- package/dist/webui/_app/immutable/chunks/J36u8XLO.js +1 -0
- package/dist/webui/_app/immutable/chunks/UeEccMjN.js +1 -0
- package/dist/webui/_app/immutable/chunks/Y--VMh3y.js +1 -0
- package/dist/webui/_app/immutable/chunks/iicbWqXp.js +3 -0
- package/dist/webui/_app/immutable/chunks/s48N5eaK.js +67 -0
- package/dist/webui/_app/immutable/chunks/xihTtKlq.js +1 -0
- package/dist/webui/_app/immutable/entry/app.CbFi8HIH.js +2 -0
- package/dist/webui/_app/immutable/entry/start.C3bV1TCO.js +1 -0
- package/dist/webui/_app/immutable/nodes/0.C7-AKGsj.js +231 -0
- package/dist/webui/_app/immutable/nodes/1.raBmjc20.js +1 -0
- package/dist/webui/_app/immutable/nodes/2.ewWz-Ki-.js +1 -0
- package/dist/webui/_app/immutable/nodes/3.DCVfhckZ.js +1 -0
- package/dist/webui/_app/version.json +1 -0
- package/dist/webui/icons/app-icon/darwin-dark.icns +0 -0
- package/dist/webui/icons/app-icon/darwin-light.icns +0 -0
- package/dist/webui/icons/app-icon/win32-dark.ico +0 -0
- package/dist/webui/icons/app-icon/win32-light.ico +0 -0
- package/dist/webui/icons/app-icon.icns +0 -0
- package/dist/webui/icons/app-icon.ico +0 -0
- package/dist/webui/icons/app-icon.json +84 -0
- package/dist/webui/icons/app-icon.png +0 -0
- package/dist/webui/icons/flat-symbol.png +0 -0
- package/dist/webui/icons/linux/128x128/app-icon.png +0 -0
- package/dist/webui/icons/linux/16x16/app-icon.png +0 -0
- package/dist/webui/icons/linux/256x256/app-icon.png +0 -0
- package/dist/webui/icons/linux/32x32/app-icon.png +0 -0
- package/dist/webui/icons/linux/48x48/app-icon.png +0 -0
- package/dist/webui/icons/linux/512x512/app-icon.png +0 -0
- package/dist/webui/icons/linux/64x64/app-icon.png +0 -0
- package/dist/webui/icons/monochrome-mini.png +0 -0
- package/dist/webui/index.html +62 -0
- package/dist/webui/robots.txt +3 -0
- package/package.json +99 -73
- package/dist/buildIndex-B_9ABRtx.mjs +0 -2
- package/dist/buildIndex-B_9ABRtx.mjs.map +0 -1
- package/dist/buildIndex-Cea97e0l.mjs +0 -1
- package/dist/cli.d.mts +0 -1016
- package/dist/cli.d.mts.map +0 -1
- package/dist/cli.mjs +0 -20
- package/dist/cli.mjs.map +0 -1
- package/dist/contentManager-CoVTiSDT.mjs +0 -13
- package/dist/contentManager-CoVTiSDT.mjs.map +0 -1
- package/dist/contentManager-CwquwC1s.mjs +0 -1
- package/dist/context7-BejCCqkm.mjs +0 -1
- package/dist/context7-BxMpyQiW.mjs +0 -2
- package/dist/context7-BxMpyQiW.mjs.map +0 -1
- package/dist/index.d.mts +0 -2158
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -2
- package/dist/index.mjs.map +0 -1
- package/dist/listContext7-DHj9AL-z.mjs +0 -2
- package/dist/listContext7-DHj9AL-z.mjs.map +0 -1
- package/dist/package-CFJazwTO.mjs +0 -2
- package/dist/package-CFJazwTO.mjs.map +0 -1
- package/dist/referenceSearchUtils-DZgupMZp.mjs +0 -2
- package/dist/referenceSearchUtils-DZgupMZp.mjs.map +0 -1
- package/dist/removeContext7-BZtL4_CJ.mjs +0 -3
- package/dist/removeContext7-BZtL4_CJ.mjs.map +0 -1
- package/dist/removeSkill-Bat_plVG.mjs +0 -5
- package/dist/removeSkill-Bat_plVG.mjs.map +0 -1
- package/dist/removeSkill-DjDZjhJU.mjs +0 -1
- package/dist/runScript-CSKqb831.mjs +0 -13
- package/dist/runScript-CSKqb831.mjs.map +0 -1
- package/dist/scopeSelection-BWteJQSv.mjs +0 -2
- package/dist/scopeSelection-BWteJQSv.mjs.map +0 -1
- package/dist/searchQuality-DVdHmamh.mjs +0 -2
- package/dist/searchQuality-DVdHmamh.mjs.map +0 -1
- package/dist/search_format-RyjXACJa.mjs +0 -5
- package/dist/search_format-RyjXACJa.mjs.map +0 -1
- package/dist/shared-DsVh4gOV.mjs +0 -2
- package/dist/shared-DsVh4gOV.mjs.map +0 -1
- package/dist/skillCreator-BomXoqdw.mjs +0 -2
- package/dist/skillCreator-BomXoqdw.mjs.map +0 -1
- package/dist/skillMdManager-DGBZ6M5J.mjs +0 -7
- package/dist/skillMdManager-DGBZ6M5J.mjs.map +0 -1
- package/dist/sqliteVectorSearchAdapter-56kZjbUT.mjs +0 -28
- package/dist/sqliteVectorSearchAdapter-56kZjbUT.mjs.map +0 -1
- package/dist/sqliteVectorSearchAdapter-DNkyKuZs.mjs +0 -1
- package/dist/unifiedSearch-CLdazMYU.mjs +0 -4
- package/dist/unifiedSearch-CLdazMYU.mjs.map +0 -1
- package/dist/unifiedSearch-DCFPrtzZ.mjs +0 -1
- package/templates/SKILL.md +0 -56
- package/templates/SKILL.zh-CN.md +0 -339
- package/templates/skill-creator.md +0 -130
- package/templates/skill-creator.zh-CN.md +0 -133
package/dist/cli.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.mts","names":["LiteralUnion","LiteralType","BaseType","Record","CommanderError","Error","InvalidArgumentError","InvalidOptionArgumentError","ErrorOptions","Argument","T","Option","OptionValues","Help","Command","Map","HelpConfiguration","Partial","ParseOptions","HelpContext","AddHelpTextContext","OutputConfiguration","AddHelpTextPosition","HookEvent","OptionValueSource","CommandOptions","ReturnType","ExecutableCommandOptions","Promise","RegExp","ParseOptionsResult","createCommand","createOption","createArgument","program"],"sources":["../node_modules/.pnpm/commander@14.0.1/node_modules/commander/typings/index.d.ts","../src/cli.ts"],"sourcesContent":["// Type definitions for commander\n// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n// This is a trick to encourage editor to suggest the known literals while still\n// allowing any BaseType value.\n// References:\n// - https://github.com/microsoft/TypeScript/issues/29729\n// - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts\n// - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts\ntype LiteralUnion<LiteralType, BaseType extends string | number> =\n | LiteralType\n | (BaseType & Record<never, never>);\n\nexport class CommanderError extends Error {\n code: string;\n exitCode: number;\n message: string;\n nestedError?: string;\n\n /**\n * Constructs the CommanderError class\n * @param exitCode - suggested exit code which could be used with process.exit\n * @param code - an id string representing the error\n * @param message - human-readable description of the error\n */\n constructor(exitCode: number, code: string, message: string);\n}\n\nexport class InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param message - explanation of why argument is invalid\n */\n constructor(message: string);\n}\nexport { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name\n\nexport interface ErrorOptions {\n // optional parameter for error()\n /** an id string representing the error */\n code?: string;\n /** suggested exit code which could be used with process.exit */\n exitCode?: number;\n}\n\nexport class Argument {\n description: string;\n required: boolean;\n variadic: boolean;\n defaultValue?: any;\n defaultValueDescription?: string;\n parseArg?: <T>(value: string, previous: T) => T;\n argChoices?: string[];\n\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n */\n constructor(arg: string, description?: string);\n\n /**\n * Return argument name.\n */\n name(): string;\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n */\n default(value: unknown, description?: string): this;\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n */\n argParser<T>(fn: (value: string, previous: T) => T): this;\n\n /**\n * Only allow argument value to be one of choices.\n */\n choices(values: readonly string[]): this;\n\n /**\n * Make argument required.\n */\n argRequired(): this;\n\n /**\n * Make argument optional.\n */\n argOptional(): this;\n}\n\nexport class Option {\n flags: string;\n description: string;\n\n required: boolean; // A value must be supplied when the option is specified.\n optional: boolean; // A value is optional when the option is specified.\n variadic: boolean;\n mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.\n short?: string;\n long?: string;\n negate: boolean;\n defaultValue?: any;\n defaultValueDescription?: string;\n presetArg?: unknown;\n envVar?: string;\n parseArg?: <T>(value: string, previous: T) => T;\n hidden: boolean;\n argChoices?: string[];\n helpGroupHeading?: string;\n\n constructor(flags: string, description?: string);\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n */\n default(value: unknown, description?: string): this;\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * ```ts\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n * ```\n */\n preset(arg: unknown): this;\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * ```ts\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n * ```\n */\n conflicts(names: string | string[]): this;\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n */\n implies(optionValues: OptionValues): this;\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variables is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n */\n env(name: string): this;\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n */\n argParser<T>(fn: (value: string, previous: T) => T): this;\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n */\n makeOptionMandatory(mandatory?: boolean): this;\n\n /**\n * Hide option in help.\n */\n hideHelp(hide?: boolean): this;\n\n /**\n * Only allow option value to be one of choices.\n */\n choices(values: readonly string[]): this;\n\n /**\n * Return option name.\n */\n name(): string;\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n */\n attributeName(): string;\n\n /**\n * Set the help group heading.\n */\n helpGroup(heading: string): this;\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n */\n isBoolean(): boolean;\n}\n\nexport class Help {\n /** output helpWidth, long lines are wrapped to fit */\n helpWidth?: number;\n minWidthToWrap: number;\n sortSubcommands: boolean;\n sortOptions: boolean;\n showGlobalOptions: boolean;\n\n constructor();\n\n /*\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the others are provided for subclasses.\n */\n prepareContext(contextOptions: {\n error?: boolean;\n helpWidth?: number;\n outputHasColors?: boolean;\n }): void;\n\n /** Get the command term to show in the list of subcommands. */\n subcommandTerm(cmd: Command): string;\n /** Get the command summary to show in the list of subcommands. */\n subcommandDescription(cmd: Command): string;\n /** Get the option term to show in the list of options. */\n optionTerm(option: Option): string;\n /** Get the option description to show in the list of options. */\n optionDescription(option: Option): string;\n /** Get the argument term to show in the list of arguments. */\n argumentTerm(argument: Argument): string;\n /** Get the argument description to show in the list of arguments. */\n argumentDescription(argument: Argument): string;\n\n /** Get the command usage to be displayed at the top of the built-in help. */\n commandUsage(cmd: Command): string;\n /** Get the description for the command. */\n commandDescription(cmd: Command): string;\n\n /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */\n visibleCommands(cmd: Command): Command[];\n /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */\n visibleOptions(cmd: Command): Option[];\n /** Get an array of the visible global options. (Not including help.) */\n visibleGlobalOptions(cmd: Command): Option[];\n /** Get an array of the arguments which have descriptions. */\n visibleArguments(cmd: Command): Argument[];\n\n /** Get the longest command term length. */\n longestSubcommandTermLength(cmd: Command, helper: Help): number;\n /** Get the longest option term length. */\n longestOptionTermLength(cmd: Command, helper: Help): number;\n /** Get the longest global option term length. */\n longestGlobalOptionTermLength(cmd: Command, helper: Help): number;\n /** Get the longest argument term length. */\n longestArgumentTermLength(cmd: Command, helper: Help): number;\n\n /** Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations. */\n displayWidth(str: string): number;\n\n /** Style the titles. Called with 'Usage:', 'Options:', etc. */\n styleTitle(title: string): string;\n\n /** Usage: <str> */\n styleUsage(str: string): string;\n /** Style for command name in usage string. */\n styleCommandText(str: string): string;\n\n styleCommandDescription(str: string): string;\n styleOptionDescription(str: string): string;\n styleSubcommandDescription(str: string): string;\n styleArgumentDescription(str: string): string;\n /** Base style used by descriptions. */\n styleDescriptionText(str: string): string;\n\n styleOptionTerm(str: string): string;\n styleSubcommandTerm(str: string): string;\n styleArgumentTerm(str: string): string;\n\n /** Base style used in terms and usage for options. */\n styleOptionText(str: string): string;\n /** Base style used in terms and usage for subcommands. */\n styleSubcommandText(str: string): string;\n /** Base style used in terms and usage for arguments. */\n styleArgumentText(str: string): string;\n\n /** Calculate the pad width from the maximum term length. */\n padWidth(cmd: Command, helper: Help): number;\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n */\n boxWrap(str: string, width: number): string;\n\n /** Detect manually wrapped and indented strings by checking for line break followed by whitespace. */\n preformatted(str: string): boolean;\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n */\n formatItem(\n term: string,\n termWidth: number,\n description: string,\n helper: Help,\n ): string;\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n */\n formatItemList(heading: string, items: string[], helper: Help): string[];\n\n /**\n * Group items by their help group heading.\n */\n groupItems<T extends Command | Option>(\n unsortedItems: T[],\n visibleItems: T[],\n getGroup: (item: T) => string,\n ): Map<string, T[]>;\n\n /** Generate the built-in help text. */\n formatHelp(cmd: Command, helper: Help): string;\n}\nexport type HelpConfiguration = Partial<Help>;\n\nexport interface ParseOptions {\n from: 'node' | 'electron' | 'user';\n}\nexport interface HelpContext {\n // optional parameter for .help() and .outputHelp()\n error: boolean;\n}\nexport interface AddHelpTextContext {\n // passed to text function used with .addHelpText()\n error: boolean;\n command: Command;\n}\nexport interface OutputConfiguration {\n writeOut?(str: string): void;\n writeErr?(str: string): void;\n outputError?(str: string, write: (str: string) => void): void;\n\n getOutHelpWidth?(): number;\n getErrHelpWidth?(): number;\n\n getOutHasColors?(): boolean;\n getErrHasColors?(): boolean;\n stripColor?(str: string): string;\n}\n\nexport type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';\nexport type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';\n// The source is a string so author can define their own too.\nexport type OptionValueSource =\n | LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string>\n | undefined;\n\nexport type OptionValues = Record<string, any>;\n\nexport class Command {\n args: string[];\n processedArgs: any[];\n readonly commands: readonly Command[];\n readonly options: readonly Option[];\n readonly registeredArguments: readonly Argument[];\n parent: Command | null;\n\n constructor(name?: string);\n\n /**\n * Set the program version to `str`.\n *\n * This method auto-registers the \"-V, --version\" flag\n * which will print the version number when passed.\n *\n * You can optionally supply the flags and description to override the defaults.\n */\n version(str: string, flags?: string, description?: string): this;\n /**\n * Get the program version.\n */\n version(): string | undefined;\n\n /**\n * Define a command, implemented using an action handler.\n *\n * @remarks\n * The command description is supplied using `.description`, not as a parameter to `.command`.\n *\n * @example\n * ```ts\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n * ```\n *\n * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param opts - configuration options\n * @returns new command\n */\n command(\n nameAndArgs: string,\n opts?: CommandOptions,\n ): ReturnType<this['createCommand']>;\n /**\n * Define a command, implemented in a separate executable file.\n *\n * @remarks\n * The command description is supplied as the second parameter to `.command`.\n *\n * @example\n * ```ts\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n * ```\n *\n * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param description - description of executable command\n * @param opts - configuration options\n * @returns `this` command for chaining\n */\n command(\n nameAndArgs: string,\n description: string,\n opts?: ExecutableCommandOptions,\n ): this;\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n */\n createCommand(name?: string): Command;\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @returns `this` command for chaining\n */\n addCommand(cmd: Command, opts?: CommandOptions): this;\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n */\n createArgument(name: string, description?: string): Argument;\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * ```\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n * ```\n *\n * @returns `this` command for chaining\n */\n argument<T>(\n flags: string,\n description: string,\n parseArg: (value: string, previous: T) => T,\n defaultValue?: T,\n ): this;\n argument(name: string, description?: string, defaultValue?: unknown): this;\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @returns `this` command for chaining\n */\n addArgument(arg: Argument): this;\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * ```\n * program.arguments('<cmd> [env]');\n * ```\n *\n * @returns `this` command for chaining\n */\n arguments(names: string): this;\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * ```ts\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n * ```\n */\n helpCommand(nameAndArgs: string, description?: string): this;\n helpCommand(enable: boolean): this;\n\n /**\n * Add prepared custom help command.\n */\n addHelpCommand(cmd: Command): this;\n /** @deprecated since v12, instead use helpCommand */\n addHelpCommand(nameAndArgs: string, description?: string): this;\n /** @deprecated since v12, instead use helpCommand */\n addHelpCommand(enable?: boolean): this;\n\n /**\n * Add hook for life cycle event.\n */\n hook(\n event: HookEvent,\n listener: (\n thisCommand: Command,\n actionCommand: Command,\n ) => void | Promise<void>,\n ): this;\n\n /**\n * Register callback to use as replacement for calling process.exit.\n */\n exitOverride(callback?: (err: CommanderError) => never | void): this;\n\n /**\n * Display error message and exit (or call exitOverride).\n */\n error(message: string, errorOptions?: ErrorOptions): never;\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n */\n createHelp(): Help;\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n */\n configureHelp(configuration: HelpConfiguration): this;\n /** Get configuration */\n configureHelp(): HelpConfiguration;\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n * ```\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n * ```\n */\n configureOutput(configuration: OutputConfiguration): this;\n /** Get configuration */\n configureOutput(): OutputConfiguration;\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n */\n copyInheritedSettings(sourceCommand: Command): this;\n\n /**\n * Display the help or a custom message after an error occurs.\n */\n showHelpAfterError(displayHelp?: boolean | string): this;\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n */\n showSuggestionAfterError(displaySuggestion?: boolean): this;\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * ```\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n * ```\n *\n * @returns `this` command for chaining\n */\n action(fn: (this: this, ...args: any[]) => void | Promise<void>): this;\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n *\n * ```js\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n * ```\n *\n * @returns `this` command for chaining\n */\n option(\n flags: string,\n description?: string,\n defaultValue?: string | boolean | string[],\n ): this;\n option<T>(\n flags: string,\n description: string,\n parseArg: (value: string, previous: T) => T,\n defaultValue?: T,\n ): this;\n /** @deprecated since v7, instead use choices or a custom function */\n option(\n flags: string,\n description: string,\n regexp: RegExp,\n defaultValue?: string | boolean | string[],\n ): this;\n\n /**\n * Define a required option, which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n */\n requiredOption(\n flags: string,\n description?: string,\n defaultValue?: string | boolean | string[],\n ): this;\n requiredOption<T>(\n flags: string,\n description: string,\n parseArg: (value: string, previous: T) => T,\n defaultValue?: T,\n ): this;\n /** @deprecated since v7, instead use choices or a custom function */\n requiredOption(\n flags: string,\n description: string,\n regexp: RegExp,\n defaultValue?: string | boolean | string[],\n ): this;\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n */\n\n createOption(flags: string, description?: string): Option;\n\n /**\n * Add a prepared Option.\n *\n * See .option() and .requiredOption() for creating and attaching an option in a single call.\n */\n addOption(option: Option): this;\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @returns `this` command for chaining\n */\n storeOptionsAsProperties<T extends OptionValues>(): this & T;\n storeOptionsAsProperties<T extends OptionValues>(\n storeAsProperties: true,\n ): this & T;\n storeOptionsAsProperties(storeAsProperties?: boolean): this;\n\n /**\n * Retrieve option value.\n */\n getOptionValue(key: string): any;\n\n /**\n * Store option value.\n */\n setOptionValue(key: string, value: unknown): this;\n\n /**\n * Store option value and where the value came from.\n */\n setOptionValueWithSource(\n key: string,\n value: unknown,\n source: OptionValueSource,\n ): this;\n\n /**\n * Get source of option value.\n */\n getOptionValueSource(key: string): OptionValueSource | undefined;\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n */\n getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * ```\n * // for `.option('-f,--flag [value]'):\n * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour\n * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n * ```\n *\n * @returns `this` command for chaining\n */\n combineFlagAndOptionalValue(combine?: boolean): this;\n\n /**\n * Allow unknown options on the command line.\n *\n * @returns `this` command for chaining\n */\n allowUnknownOption(allowUnknown?: boolean): this;\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @returns `this` command for chaining\n */\n allowExcessArguments(allowExcess?: boolean): this;\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n *\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @returns `this` command for chaining\n */\n enablePositionalOptions(positional?: boolean): this;\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n *\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @returns `this` command for chaining\n */\n passThroughOptions(passThrough?: boolean): this;\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * ```\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n * ```\n *\n * @returns `this` command for chaining\n */\n parse(argv?: readonly string[], parseOptions?: ParseOptions): this;\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * ```\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n * ```\n *\n * @returns Promise\n */\n parseAsync(\n argv?: readonly string[],\n parseOptions?: ParseOptions,\n ): Promise<this>;\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse(): void;\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse(): void;\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n */\n parseOptions(argv: string[]): ParseOptionsResult;\n\n /**\n * Return an object containing local option values as key-value pairs\n */\n opts<T extends OptionValues>(): T;\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n */\n optsWithGlobals<T extends OptionValues>(): T;\n\n /**\n * Set the description.\n *\n * @returns `this` command for chaining\n */\n\n description(str: string): this;\n /** @deprecated since v8, instead use .argument to add command argument with description */\n description(str: string, argsDescription: Record<string, string>): this;\n /**\n * Get the description.\n */\n description(): string;\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @returns `this` command for chaining\n */\n\n summary(str: string): this;\n /**\n * Get the summary.\n */\n summary(): string;\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @returns `this` command for chaining\n */\n alias(alias: string): this;\n /**\n * Get alias for the command.\n */\n alias(): string;\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @returns `this` command for chaining\n */\n aliases(aliases: readonly string[]): this;\n /**\n * Get aliases for the command.\n */\n aliases(): string[];\n\n /**\n * Set the command usage.\n *\n * @returns `this` command for chaining\n */\n usage(str: string): this;\n /**\n * Get the command usage.\n */\n usage(): string;\n\n /**\n * Set the name of the command.\n *\n * @returns `this` command for chaining\n */\n name(str: string): this;\n /**\n * Get the name of the command.\n */\n name(): string;\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * ```ts\n * program.nameFromFilename(require.main.filename);\n * ```\n *\n * @returns `this` command for chaining\n */\n nameFromFilename(filename: string): this;\n\n /**\n * Set the directory for searching for executable subcommands of this command.\n *\n * @example\n * ```ts\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n * ```\n *\n * @returns `this` command for chaining\n */\n executableDir(path: string): this;\n /**\n * Get the executable search directory.\n */\n executableDir(): string | null;\n\n /**\n * Set the help group heading for this subcommand in parent command's help.\n *\n * @returns `this` command for chaining\n */\n helpGroup(heading: string): this;\n /**\n * Get the help group heading for this subcommand in parent command's help.\n */\n helpGroup(): string;\n\n /**\n * Set the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @returns `this` command for chaining\n */\n commandsGroup(heading: string): this;\n /**\n * Get the default help group heading for subcommands added to this command.\n */\n commandsGroup(): string;\n\n /**\n * Set the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @returns `this` command for chaining\n */\n optionsGroup(heading: string): this;\n /**\n * Get the default help group heading for options added to this command.\n */\n optionsGroup(): string;\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n */\n outputHelp(context?: HelpContext): void;\n /** @deprecated since v7 */\n outputHelp(cb?: (str: string) => string): void;\n\n /**\n * Return command help documentation.\n */\n helpInformation(context?: HelpContext): string;\n\n /**\n * You can pass in flags and a description to override the help\n * flags and help description for your command. Pass in false\n * to disable the built-in help option.\n */\n helpOption(flags?: string | boolean, description?: string): this;\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n */\n addHelpOption(option: Option): this;\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n */\n help(context?: HelpContext): never;\n /** @deprecated since v7 */\n help(cb?: (str: string) => string): never;\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n */\n addHelpText(position: AddHelpTextPosition, text: string): this;\n addHelpText(\n position: AddHelpTextPosition,\n text: (context: AddHelpTextContext) => string,\n ): this;\n\n /**\n * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)\n */\n on(event: string | symbol, listener: (...args: any[]) => void): this;\n}\n\nexport interface CommandOptions {\n hidden?: boolean;\n isDefault?: boolean;\n /** @deprecated since v7, replaced by hidden */\n noHelp?: boolean;\n}\nexport interface ExecutableCommandOptions extends CommandOptions {\n executableFile?: string;\n}\n\nexport interface ParseOptionsResult {\n operands: string[];\n unknown: string[];\n}\n\nexport function createCommand(name?: string): Command;\nexport function createOption(flags: string, description?: string): Option;\nexport function createArgument(name: string, description?: string): Argument;\n\nexport const program: Command;\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;AAeA;AAwBA;AAQA;;KApCKA,YA0C2CU,CAAAA,WAAAA,EAAAA,iBAAAA,MAAAA,GAAAA,MAAAA,CAAAA,GAzC5CT,WAgEyCS,GAAMA,CA/D9CR,QA+D8CQ,GA/DnCP,MA+DmCO,CAAAA,KAAAA,EAAAA,KAAAA,CAAAA,CAAAA;AAkBtCC,cA/EAP,cAAAA,SAAuBC,KAAAA,CA+EjB;EAeuBK,IAAAA,EAAAA,MAAAA;EAAMA,QAAAA,EAAAA,MAAAA;EA8CxBE,OAAAA,EAAAA,MAAAA;EAaqBF,WAAAA,CAAAA,EAAAA,MAAAA;;EAAO;AAyCpD;;;;;EA+ByBD,WAAAA,CAAAA,QAAAA,EAAAA,MAAAA,EAAAA,IAAAA,EAAAA,MAAAA,EAAAA,OAAAA,EAAAA,MAAAA;;AAgBDK;;AAGWA,UA5NlBN,YAAAA,CA4NkBM;EAAiBD;EAErBC;EAAiBD,IAAAA,CAAAA,EAAAA,MAAAA;EAEXC;EAAiBD,QAAAA,CAAAA,EAAAA,MAAAA;;AAkCtCC,cA1PHL,QAAAA,CA0PGK;EAAiBD,WAAAA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AwECN;;;;;;;;;;;;;;;;;;;;;sDAuB9BA,eACdU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gCA8B2BE;;;;;iBAKflB,iBAAiBF;;;;;4BAKNE,iBAAiBF;;;;;;;;;;4CAUDP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAwJrBgB;;;;;;;4BAOKA;;;;;;;;;;;;;wBAaJR;;;;;;;iBAOPQ;;;;;;;;;;wBAUOG;wBAEVA,qCACMF;;;;;;;UASHK,cAAAA;;;;;;UAMAE,wBAAAA,SAAiCF;;;UAIjCK,kBAAAA;;;;;;cC5jCX,ODNU3B,ECMH,ODNGA"}
|
package/dist/cli.mjs
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"./package-CFJazwTO.mjs";import{t}from"./skillCreator-BomXoqdw.mjs";import{a as n,i as r,o as i,r as a,t as o}from"./scopeSelection-BWteJQSv.mjs";import s from"node:path";import{Command as c}from"commander";import l from"gradient-string";async function u(e,n={}){let r=new t;n.json||console.log(l(`cyan`,`magenta`)(`
|
|
3
|
-
🚀 Creating skill...`));let i=await r.createSkill(e);if(i.created)return n.json||(console.log(l(`green`,`cyan`)(`\n✅ ${i.message}`)),console.log(l(`blue`,`cyan`)(`📍 Skill Path: ${i.skillPath}`)),console.log(`
|
|
4
|
-
🎉 Skill created successfully!`),console.log(`
|
|
5
|
-
Next steps:`),console.log(`1. Add content: skill-creator add-skill --pwd "${i.skillPath}" --title "My Note" --content "Your content"`),console.log(`2. Search skill: skill-creator search-skill --pwd "${i.skillPath}" "query"`),console.log(`3. Download docs: skill-creator download-context7 --pwd "${i.skillPath}"`),console.log(`4. Resolve Context7 id explicitly when needed: skill-creator resolve-context7 <package-name> [--package-version <version>]`)),i.skillPath;throw Error(i.message||`Failed to create skill`)}const d=`Skill creation cancelled.`;async function f(e,t,r){let i=r.cwd??process.cwd(),{scope:c,interactive:l,force:u,description:f,name:p,skillName:m}=t,h=m||p||e;if(l){if(console.log(`Skill Creation Configuration:`),!c&&(c=(await r.prompt.prompt([{type:`list`,name:`scope`,message:`Where would you like to store this skill?`,choices:[{name:`Current directory (./.claude/skills/)`,value:`current`},{name:`User home directory (~/.claude/skills)`,value:`user`},...r.prompt.Separator?[new r.prompt.Separator]:[],{name:`Custom directory`,value:`custom`}],default:o(i)}])).scope,c===`custom`)){let e=await r.prompt.prompt([{type:`input`,name:`scope`,message:`Directory to store skills`,validate:e=>e.trim()!==``||`Directory cannot be empty`}]);c=s.join(i,e.scope)}if(!m){let{packageNameConfirmed:e}=await r.prompt.prompt([{type:`confirm`,name:`packageNameConfirmed`,message:`Use '${h}' as the visible skill name?`,default:!0}]);if(!e){let{customSkillName:e}=await r.prompt.prompt([{type:`input`,name:`customSkillName`,message:`Enter the skill name:`,validate:e=>e.trim()!==``||`Skill name cannot be empty`}]);h=e.trim()}}if(!f){let{customDescription:e}=await r.prompt.prompt([{type:`input`,name:`customDescription`,message:`Enter the skill description:`}]);f=e.trim()}}if(c==null)throw Error(`Error: --scope is required. Use --scope current, --scope user, or --scope auto.`);let{requestedScope:g,resolvedScope:_,scopePath:v}=a(c,i);if(l){console.log(`
|
|
6
|
-
Final Configuration:`),console.log(`- Storage location: ${v}`),console.log(`- Skill directory name: ${e}`),console.log(`- Visible Skill Name: ${h}`),console.log(`- Skill Description: ${f}`);let{confirmFinal:t}=await r.prompt.prompt([{type:`confirm`,name:`confirmFinal`,message:`Proceed with skill creation?`,default:!0}]);if(!t)throw Error(d)}let y=p??h,b=n(e);return{createOptions:{baseDir:v,skillDirname:e,skillName:h,skillDescription:f,sourcePackageName:y,sourcePackageVersionHint:b,force:u},summary:{requestedScope:g,resolvedScope:_,scopePath:v,skillDirName:e,skillName:h,sourcePackageName:y,sourcePackageVersionHint:b,skillDescription:f}}}const p=new c;let m={};p.name(`skill-creator`).description(`Create claude-code-skills with documentation management`).version(e.getCurrentPackageInfo()?.version??`0.0.0`).option(`--pwd <path>`,`Global path to the skill directory (used for all commands)`),p.hook(`preAction`,e=>{m.pwd=e.opts().pwd}),p.command(`create-cc-skill`).option(`--interactive`,`Enable interactive confirmation prompts`).option(`--scope <scope>`,`Storage scope (user, current, or auto), or a custom directory to store skills`).option(`--name <name>`,`Source package name stored in SKILL.md for later package-aware workflows`).option(`--skill-name <name>`,`Visible skill name used in SKILL.md and JSON output`).option(`--description <description>`,`Custom description for the skill`).option(`--force`,`Force overwrite existing files in the skill directory`).option(`--json`,`Print machine-readable creation output`).argument(`<skill_dir_name>`,`The name of the skill directory to create`).action(async(e,t)=>{try{let{default:n}=await import(`inquirer`),r=await f(e,t,{cwd:process.cwd(),prompt:{prompt:n.prompt.bind(n),Separator:n.Separator}}),i=await u(r.createOptions,{json:t.json});t.json?console.log(JSON.stringify({skillPath:i,requestedScope:r.summary.requestedScope,resolvedScope:r.summary.resolvedScope,scopePath:r.summary.scopePath,skillDirName:r.summary.skillDirName,skillName:r.summary.skillName,sourcePackageName:r.summary.sourcePackageName,sourcePackageVersionHint:r.summary.sourcePackageVersionHint??``,skillDescription:r.summary.skillDescription??``},null,2)):console.log(`Skill created successfully at: ${i}`)}catch(e){e instanceof Error&&e.message===d&&(console.log(e.message),process.exit(0)),console.error(`Error:`,e instanceof Error?e.stack??e.message:String(e)),process.exit(1)}}),p.command(`init`).description(`Install skill-creator as subagent (interactive mode)`).option(`--scope <scope>`,`Storage scope (user, current, or auto)`).option(`--json`,`Print machine-readable installation output`).action(async e=>{let{runScript:t}=await import(`./runScript-CSKqb831.mjs`),n=[];e.scope&&n.push(`--scope`,e.scope),e.json&&n.push(`--json`),await t(`init`,n)}),p.command(`init-cc`).description(`Install skill-creator as subagent in ~/.claude/agents/`).option(`--json`,`Print machine-readable installation output`).action(async e=>{let{runScript:t}=await import(`./runScript-CSKqb831.mjs`),n=[`--scope`,`user`];e.json&&n.push(`--json`),await t(`init`,n)}),p.command(`search`).argument(`<keywords>`,`Search keywords for npm packages`).option(`-l, --limit <limit>`,`Number of results to show`,`10`).action(async(t,n)=>{let r=t,i=await e.suggestPackages(r,{limit:parseInt(n.limit)});console.log(JSON.stringify(i,null,2))}),p.command(`get-info`).argument(`<package_name>`,`The npm package name to get information for`).action(async t=>{let n=await e.getPackageInfo(t);n||(console.error(`❌ Package "${t}" not found or API error occurred.`),process.exit(1));let r=n.version,i={skill_dir_name:e.createSkillFolderName(t,r),name:n.name,version:r,description:n.description||``,keywords:n.keywords||[],license:n.license||``,author:n.author||``,maintainers:n.maintainers||[],homepage:n.homepage||``,repo:n.repository?.url||``,repository:{url:n.repository?.url||``,type:n.repository?.type||``},bugs:{url:n.bugs?.url||``},funding:n.funding||``,scripts:n.scripts||{},engines:n.engines||{},types:n.types||``,dependencies:n.dependencies||{},devDependencies:n.devDependencies||{},time:{created:n.time?.created||``,modified:n.time?.modified||``}};console.log(JSON.stringify(i,null,2))}),p.command(`resolve-context7`).description(`Resolve the best Context7 library id for an npm package`).argument(`<package_name>`,`The npm package name to resolve against Context7`).option(`--package-version <version>`,`Explicit package version to use in the Context7 query`).option(`-l, --limit <limit>`,`Number of candidates to keep in the response`,`5`).action(async(e,t)=>{let{Context7Utils:n}=await import(`./context7-BejCCqkm.mjs`),r=await n.resolveLibrary(e,{version:t.packageVersion,limit:parseInt(t.limit,10)});r||(console.error(`❌ No Context7 library found for package "${e}".`),process.exit(1)),console.log(JSON.stringify(r,null,2))}),p.command(`search-skill`).argument(`<query>`,`Search query`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).option(`--mode <mode>`,`Search mode: auto, fulltext, fuzzy, or vector`,`auto`).option(`--vector-embedder <mode>`,`Vector embedder mode: deterministic for offline local embeddings, or omit for the default runtime embedder`).option(`--list`,`Show simplified list view (basic info only)`,!1).action(async(e,t)=>{try{let n=i(t,m);console.log(l(`cyan`,`magenta`)(`
|
|
7
|
-
🔍 Searching in skill...`)),console.log(`Skill Path: ${n}`),console.log(`Query: ${e}`);let{chdir:r}=await import(`node:process`),a=process.cwd();r(n);try{let{runScript:n}=await import(`./runScript-CSKqb831.mjs`),r=[`--query`,e];t.mode!==`auto`&&r.push(`--mode`,t.mode),t.vectorEmbedder&&r.push(`--vector-embedder`,t.vectorEmbedder),t.list&&r.push(`--list`),await n(`search-skill`,r)}finally{r(a)}}catch(e){console.error(e),process.exit(1)}}),p.command(`download-context7`).argument(`[project_id]`,`Context7 library ID`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).option(`--package-version <version>`,`Version hint used when resolving a Context7 library from --package`).option(`-f, --force`,`Force update even if up to date`).option(`--skip-indexing`,`Skip automatic local index building after download`).option(`--json`,`Print machine-readable download output`).action(async(e,t)=>{try{let a=i(t,m),o=e,s,c,u;if(!o){let e=r(a),i=t.package||e.packageName,d=t.packageVersion||e.versionHint||n(a);i||(console.error(`❌ Please provide either a Context7 project ID, --package <name>, or a skill created with package metadata`),process.exit(1));let{Context7Utils:f}=await import(`./context7-BejCCqkm.mjs`);t.json||(console.log(l(`cyan`,`magenta`)(`
|
|
8
|
-
🧭 Resolving Context7 library...`)),console.log(`Package: ${i}`),d&&console.log(`Version hint: ${d}`));let p=await f.resolveLibrary(i,{version:d});p||(console.error(`❌ No Context7 library found for package "${i}".`),process.exit(1)),o=p.bestMatch.id,s=p.query,c=i,u=p.version??d,t.json||(console.log(`Resolved Context7 ID: ${o}`),console.log(`Resolution query: ${p.query}`))}t.json||(console.log(l(`cyan`,`magenta`)(`
|
|
9
|
-
📥 Downloading Context7 documentation...`)),console.log(`Skill Path: ${a}`),console.log(`Context7 ID: ${o}`));let{chdir:d}=await import(`node:process`),f=process.cwd();d(a);try{let{runScript:n}=await import(`./runScript-CSKqb831.mjs`),r=[];t.force&&r.push(`--force`),t.skipIndexing&&r.push(`--skip-indexing`),t.json&&r.push(`--json`),c&&r.push(`--package-name`,c),u&&r.push(`--package-version`,u),r.push(`--project-id`,o);let i=await n(`download-context7`,r);t.json&&console.log(JSON.stringify({skillPath:a,requestedProjectId:e??null,resolvedProjectId:o,resolvedPackageName:c??null,resolvedVersionHint:u??null,resolutionQuery:s??null,...i},null,2))}finally{d(f)}t.json||console.log(l(`green`,`cyan`)(`
|
|
10
|
-
✅ Documentation downloaded and sliced!`))}catch(e){console.error(e),process.exit(1)}}),p.command(`add-skill`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).option(`-t, --title <title>`,`Content title`).option(`-c, --content <content>`,`Content text`).option(`-f, --file <file>`,`Read content from file`).option(`--force`,`Replace the closest matching user knowledge note`).option(`--force-append`,`Append content as a knowledge update in the closest matching user note`).option(`--json`,`Print machine-readable add-content output`).action(async e=>{!e.title&&!e.file&&(console.error(`❌ Please provide either --title or --file`),process.exit(1));try{let t=i(e,m);e.json||(console.log(l(`cyan`,`magenta`)(`
|
|
11
|
-
📝 Adding content to skill...`)),console.log(`Skill Path: ${t}`));let{chdir:n}=await import(`node:process`),r=process.cwd();n(t);try{let{runScript:n}=await import(`./runScript-CSKqb831.mjs`),r=[];e.title&&r.push(`--title`,e.title),e.content&&r.push(`--content`,e.content),e.file&&r.push(`--file`,e.file),e.force&&r.push(`--force`),e.forceAppend&&r.push(`--force-append`),e.json&&r.push(`--json`);let i=await n(`add`,r);e.json&&console.log(JSON.stringify({skillPath:t,...i},null,2))}finally{n(r)}}catch(e){console.error(e),process.exit(1)}}),p.command(`build-index`).description(`Build or refresh the local search index for a skill`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).option(`--mode <mode>`,`Index mode: auto, fulltext, or vector`,`auto`).option(`--vector-embedder <mode>`,`Vector embedder mode: deterministic for offline local embeddings, or omit for the default runtime embedder`).option(`--json`,`Print machine-readable index build output`).action(async e=>{try{let t=i(e,m);e.json||(console.log(l(`cyan`,`magenta`)(`
|
|
12
|
-
🔧 Building search index...`)),console.log(`Skill Path: ${t}`));let{chdir:n}=await import(`node:process`),r=process.cwd();n(t);try{let{buildIndex:n}=await import(`./buildIndex-Cea97e0l.mjs`),r=[];e.mode!==`auto`&&r.push(`--mode`,e.mode),e.vectorEmbedder&&r.push(`--vector-embedder`,e.vectorEmbedder),e.json&&r.push(`--json`);let i=await n(r);e.json&&console.log(JSON.stringify({skillPath:t,...i},null,2))}finally{n(r)}e.json||console.log(l(`green`,`cyan`)(`
|
|
13
|
-
✅ Search index ready!`))}catch(e){console.error(e),process.exit(1)}}),p.command(`list-skills`).description(`List all skill content files`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).action(async e=>{try{let t=i(e,m);console.log(l(`cyan`,`magenta`)(`
|
|
14
|
-
📚 Skill Content`)),console.log(`Skill Path: ${t}`);let{chdir:n}=await import(`node:process`),r=process.cwd();n(t);try{let{runScript:t}=await import(`./runScript-CSKqb831.mjs`);await t(`list-skills`,process.argv.slice(3).filter(t=>!t.startsWith(`--pwd`)&&!t.startsWith(`--package`)&&t!==e.pwd&&t!==e.package))}finally{n(r)}}catch(e){console.error(e),process.exit(1)}}),p.command(`remove-skill`).description(`Remove a skill file`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).option(`--type <type>`,`Type: user or context7:<project_id>`,`user`).option(`--file <file>`,`File name to remove`).action(async e=>{try{e.file||(console.error(`❌ Please provide --file <filename>`),process.exit(1));let t=i(e,m);console.log(l(`cyan`,`magenta`)(`
|
|
15
|
-
🗑️ Remove Skill File`)),console.log(`Skill Path: ${t}`),console.log(`Type: ${e.type}`),console.log(`File: ${e.file}`);let{chdir:n}=await import(`node:process`),r=process.cwd();n(t);try{let{removeSkill:t}=await import(`./removeSkill-DjDZjhJU.mjs`);await t([`--type`,e.type,`--file`,e.file])}finally{n(r)}console.log(l(`green`,`cyan`)(`
|
|
16
|
-
✅ Skill file removed!`))}catch(e){console.error(e),process.exit(1)}}),p.command(`list-context7`).description(`List all Context7 projects`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).action(async e=>{try{let t=i(e,m);console.log(l(`cyan`,`magenta`)(`
|
|
17
|
-
📦 Context7 Projects`)),console.log(`Skill Path: ${t}`);let{chdir:n}=await import(`node:process`),r=process.cwd();n(t);try{let{listContext7:e}=await import(`./listContext7-DHj9AL-z.mjs`);await e()}finally{n(r)}}catch(e){console.error(e),process.exit(1)}}),p.command(`remove-context7`).argument(`<project_id>`,`Context7 project ID to remove`).description(`Remove a Context7 project`).option(`--pwd <path>`,`Path to the skill directory`).option(`--package <name>`,`Package name to find skill directory for`).action(async(e,t)=>{try{let n=i(t,m);console.log(l(`cyan`,`magenta`)(`
|
|
18
|
-
🗑️ Remove Context7 Project`)),console.log(`Skill Path: ${n}`),console.log(`Project ID: ${e}`);let{chdir:r}=await import(`node:process`),a=process.cwd();r(n);try{let{removeContext7:t}=await import(`./removeContext7-BZtL4_CJ.mjs`);await t([`--project-id`,e])}finally{r(a)}console.log(l(`green`,`cyan`)(`
|
|
19
|
-
✅ Context7 project removed!`))}catch(e){console.error(e),process.exit(1)}}),p.parse();export{p as program};
|
|
20
|
-
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":["globalOptions: GlobalOptions","resolvedContext7Query: string | undefined","resolvedPackageName: string | undefined","resolvedVersionHint: string | undefined"],"sources":["../src/commands/createSkill.ts","../src/utils/createSkillWorkflow.ts","../src/cli.ts"],"sourcesContent":["import { SkillCreator } from '../core/skillCreator.js'\nimport type { CreateSkillOptions } from '../types/index.js'\nimport gradient from 'gradient-string'\n\n/**\n * Helper function to create a skill for a package with interactive confirmation\n */\nexport async function createSkillForPackage(\n createOptions: CreateSkillOptions,\n options: {\n json?: boolean\n } = {}\n): Promise<string> {\n const creator = new SkillCreator()\n\n // const createOptions: CreateSkillOptions = {\n // packageName: packageName, // Use the user-provided package name directly\n // pwd: scope === 'user' ? undefined : '.claude/skills',\n // scope: scope, // Map 'current' to 'project' for internal storage\n // noInitDocs: true, // Docs are downloaded in a separate step in the new flow\n // force: force, // Pass force option to SkillCreator\n // description: description, // Pass description option to SkillCreator\n // }\n\n if (!options.json) {\n console.log(gradient('cyan', 'magenta')('\\n🚀 Creating skill...'))\n }\n\n const result = await creator.createSkill(createOptions)\n\n if (result.created) {\n if (!options.json) {\n console.log(gradient('green', 'cyan')(`\\n✅ ${result.message}`))\n console.log(gradient('blue', 'cyan')(`📍 Skill Path: ${result.skillPath}`))\n console.log('\\n🎉 Skill created successfully!')\n console.log('\\nNext steps:')\n console.log(\n `1. Add content: skill-creator add-skill --pwd \"${result.skillPath}\" --title \"My Note\" --content \"Your content\"`\n )\n console.log(`2. Search skill: skill-creator search-skill --pwd \"${result.skillPath}\" \"query\"`)\n console.log(\n `3. Download docs: skill-creator download-context7 --pwd \"${result.skillPath}\"`\n )\n console.log(\n `4. Resolve Context7 id explicitly when needed: skill-creator resolve-context7 <package-name> [--package-version <version>]`\n )\n }\n return result.skillPath!\n } else {\n throw new Error(result.message || 'Failed to create skill')\n }\n}\n","import path from 'node:path'\nimport type { CreateSkillOptions } from '../types/index.js'\nimport { inferVersionHintFromSkillDirectory } from './skillIdentity.js'\nimport {\n getDefaultScopedLocation,\n resolveStorageScopeSelection,\n} from './scopeSelection.js'\n\nexport const SKILL_CREATION_CANCELLED_MESSAGE = 'Skill creation cancelled.'\n\nexport interface CreateSkillCliOptions {\n interactive?: boolean\n scope?: string\n name?: string\n skillName?: string\n description?: string\n force?: boolean\n}\n\nexport interface CreateSkillPrompt {\n prompt<T extends Record<string, unknown>>(questions: unknown[]): Promise<T>\n Separator?: new () => unknown\n}\n\nexport interface PreparedCreateSkillWorkflow {\n createOptions: CreateSkillOptions\n summary: {\n requestedScope: string\n resolvedScope: 'current' | 'user' | 'custom'\n scopePath: string\n skillDirName: string\n skillName: string\n sourcePackageName: string\n sourcePackageVersionHint?: string\n skillDescription?: string\n }\n}\n\nexport const resolveScopeSelection = resolveStorageScopeSelection\n\nexport async function prepareCreateSkillWorkflow(\n skillDirName: string,\n options: CreateSkillCliOptions,\n dependencies: {\n cwd?: string\n prompt: CreateSkillPrompt\n }\n): Promise<PreparedCreateSkillWorkflow> {\n const cwd = dependencies.cwd ?? process.cwd()\n let { scope, interactive, force, description, name: sourcePackageName, skillName } = options\n let finalSkillName = skillName || sourcePackageName || skillDirName\n\n if (interactive) {\n console.log('Skill Creation Configuration:')\n\n if (!scope) {\n const scopeAnswer = await dependencies.prompt.prompt<{ scope: string }>([\n {\n type: 'list',\n name: 'scope',\n message: 'Where would you like to store this skill?',\n choices: [\n {\n name: 'Current directory (./.claude/skills/)',\n value: 'current',\n },\n {\n name: 'User home directory (~/.claude/skills)',\n value: 'user',\n },\n ...(dependencies.prompt.Separator ? [new dependencies.prompt.Separator()] : []),\n {\n name: 'Custom directory',\n value: 'custom',\n },\n ],\n default: getDefaultScopedLocation(cwd),\n },\n ])\n scope = scopeAnswer.scope\n if (scope === 'custom') {\n const customScopeAnswer = await dependencies.prompt.prompt<{ scope: string }>([\n {\n type: 'input',\n name: 'scope',\n message: 'Directory to store skills',\n validate: (input: string) => input.trim() !== '' || 'Directory cannot be empty',\n },\n ])\n scope = path.join(cwd, customScopeAnswer.scope)\n }\n }\n\n if (!skillName) {\n const { packageNameConfirmed } = await dependencies.prompt.prompt<{\n packageNameConfirmed: boolean\n }>([\n {\n type: 'confirm',\n name: 'packageNameConfirmed',\n message: `Use '${finalSkillName}' as the visible skill name?`,\n default: true,\n },\n ])\n\n if (!packageNameConfirmed) {\n const { customSkillName } = await dependencies.prompt.prompt<{ customSkillName: string }>([\n {\n type: 'input',\n name: 'customSkillName',\n message: 'Enter the skill name:',\n validate: (input: string) => input.trim() !== '' || 'Skill name cannot be empty',\n },\n ])\n finalSkillName = customSkillName.trim()\n }\n }\n\n if (!description) {\n const { customDescription } = await dependencies.prompt.prompt<{ customDescription: string }>([\n {\n type: 'input',\n name: 'customDescription',\n message: 'Enter the skill description:',\n },\n ])\n description = customDescription.trim()\n }\n }\n\n if (scope == null) {\n throw new Error(\n 'Error: --scope is required. Use --scope current, --scope user, or --scope auto.'\n )\n }\n\n const resolvedScopeSelection = resolveStorageScopeSelection(scope, cwd)\n const { requestedScope, resolvedScope, scopePath } = resolvedScopeSelection\n\n if (interactive) {\n console.log('\\nFinal Configuration:')\n console.log(`- Storage location: ${scopePath}`)\n console.log(`- Skill directory name: ${skillDirName}`)\n console.log(`- Visible Skill Name: ${finalSkillName}`)\n console.log(`- Skill Description: ${description}`)\n\n const { confirmFinal } = await dependencies.prompt.prompt<{ confirmFinal: boolean }>([\n {\n type: 'confirm',\n name: 'confirmFinal',\n message: 'Proceed with skill creation?',\n default: true,\n },\n ])\n\n if (!confirmFinal) {\n throw new Error(SKILL_CREATION_CANCELLED_MESSAGE)\n }\n }\n\n const resolvedSourcePackageName = sourcePackageName ?? finalSkillName\n const sourcePackageVersionHint = inferVersionHintFromSkillDirectory(skillDirName)\n\n return {\n createOptions: {\n baseDir: scopePath,\n skillDirname: skillDirName,\n skillName: finalSkillName,\n skillDescription: description,\n sourcePackageName: resolvedSourcePackageName,\n sourcePackageVersionHint,\n force,\n },\n summary: {\n requestedScope,\n resolvedScope,\n scopePath,\n skillDirName,\n skillName: finalSkillName,\n sourcePackageName: resolvedSourcePackageName,\n sourcePackageVersionHint,\n skillDescription: description,\n },\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI interface for skill creator\n */\n\nimport { Command } from 'commander'\nimport gradient from 'gradient-string'\nimport { PackageUtils } from './utils/package.js'\nimport { createSkillForPackage } from './commands/createSkill.js'\nimport {\n prepareCreateSkillWorkflow,\n SKILL_CREATION_CANCELLED_MESSAGE,\n} from './utils/createSkillWorkflow.js'\nimport {\n inferPackageMetadataFromSkill,\n inferVersionHintFromSkillDirectory,\n resolveSkillDirectoryFromOptions,\n} from './utils/skillIdentity.js'\n\nconst program = new Command()\n\n// Global options storage\ninterface GlobalOptions {\n pwd?: string\n}\n\nlet globalOptions: GlobalOptions = {}\n\nprogram\n .name('skill-creator')\n .description('Create claude-code-skills with documentation management')\n .version(PackageUtils.getCurrentPackageInfo()?.version ?? '0.0.0')\n .option('--pwd <path>', 'Global path to the skill directory (used for all commands)')\n\n// Handle global options\nprogram.hook('preAction', (thisCommand) => {\n const options = thisCommand.opts()\n globalOptions.pwd = options.pwd\n})\n\n// Add create-cc-skill command\nprogram\n .command('create-cc-skill')\n .option('--interactive', 'Enable interactive confirmation prompts')\n .option(\n '--scope <scope>',\n 'Storage scope (user, current, or auto), or a custom directory to store skills'\n )\n .option('--name <name>', 'Source package name stored in SKILL.md for later package-aware workflows')\n .option('--skill-name <name>', 'Visible skill name used in SKILL.md and JSON output')\n .option('--description <description>', 'Custom description for the skill')\n .option('--force', 'Force overwrite existing files in the skill directory')\n .option('--json', 'Print machine-readable creation output')\n .argument('<skill_dir_name>', 'The name of the skill directory to create')\n .action(async (skillDirName, options) => {\n try {\n const { default: inquirer } = await import('inquirer')\n const workflow = await prepareCreateSkillWorkflow(skillDirName, options, {\n cwd: process.cwd(),\n prompt: {\n prompt: inquirer.prompt.bind(inquirer),\n Separator: inquirer.Separator,\n },\n })\n const skillPath = await createSkillForPackage(workflow.createOptions, {\n json: options.json,\n })\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n skillPath,\n requestedScope: workflow.summary.requestedScope,\n resolvedScope: workflow.summary.resolvedScope,\n scopePath: workflow.summary.scopePath,\n skillDirName: workflow.summary.skillDirName,\n skillName: workflow.summary.skillName,\n sourcePackageName: workflow.summary.sourcePackageName,\n sourcePackageVersionHint: workflow.summary.sourcePackageVersionHint ?? '',\n skillDescription: workflow.summary.skillDescription ?? '',\n },\n null,\n 2\n )\n )\n } else {\n console.log(`Skill created successfully at: ${skillPath}`)\n }\n } catch (error) {\n if (error instanceof Error && error.message === SKILL_CREATION_CANCELLED_MESSAGE) {\n console.log(error.message)\n process.exit(0)\n }\n console.error(\n 'Error:',\n error instanceof Error ? (error.stack ?? error.message) : String(error)\n )\n process.exit(1)\n }\n })\n\n// Add interactive init command\nprogram\n .command('init')\n .description('Install skill-creator as subagent (interactive mode)')\n .option('--scope <scope>', 'Storage scope (user, current, or auto)')\n .option('--json', 'Print machine-readable installation output')\n .action(async (options) => {\n const { runScript } = await import('./core/runScript.js')\n const args = []\n\n // Pass scope to init command\n if (options.scope) {\n args.push('--scope', options.scope)\n }\n if (options.json) {\n args.push('--json')\n }\n\n await runScript('init', args)\n })\n\n// Add init command to install subagents (non-interactive version)\nprogram\n .command('init-cc')\n .description('Install skill-creator as subagent in ~/.claude/agents/')\n .option('--json', 'Print machine-readable installation output')\n .action(async (options) => {\n const { runScript } = await import('./core/runScript.js')\n // For init-cc, we want the non-interactive version that installs to user directory\n // Use --scope=user for consistency with other CLI commands\n const args = ['--scope', 'user']\n if (options.json) {\n args.push('--json')\n }\n await runScript('init', args)\n })\n\n// Add search command for package searching\nprogram\n .command('search')\n .argument('<keywords>', 'Search keywords for npm packages')\n .option('-l, --limit <limit>', 'Number of results to show', '10')\n .action(async (keywords: string, options) => {\n const query = keywords\n const suggestions = await PackageUtils.suggestPackages(query, {\n limit: parseInt(options.limit),\n })\n console.log(JSON.stringify(suggestions, null, 2))\n })\n\n// Add get-info command for package information\nprogram\n .command('get-info')\n .argument('<package_name>', 'The npm package name to get information for')\n .action(async (packageName: string) => {\n const packageInfo = await PackageUtils.getPackageInfo(packageName)\n\n if (!packageInfo) {\n console.error(`❌ Package \"${packageName}\" not found or API error occurred.`)\n process.exit(1)\n }\n\n const version = packageInfo.version\n const skillDirName = PackageUtils.createSkillFolderName(packageName, version)\n\n const result = {\n skill_dir_name: skillDirName,\n name: packageInfo.name,\n version: version,\n description: packageInfo.description || '',\n keywords: packageInfo.keywords || [],\n license: packageInfo.license || '',\n author: packageInfo.author || '',\n maintainers: packageInfo.maintainers || [],\n homepage: packageInfo.homepage || '',\n repo: packageInfo.repository?.url || '',\n repository: {\n url: packageInfo.repository?.url || '',\n type: packageInfo.repository?.type || '',\n },\n bugs: {\n url: packageInfo.bugs?.url || '',\n },\n funding: packageInfo.funding || '',\n scripts: packageInfo.scripts || {},\n engines: packageInfo.engines || {},\n types: packageInfo.types || '',\n dependencies: packageInfo.dependencies || {},\n devDependencies: packageInfo.devDependencies || {},\n time: {\n created: packageInfo.time?.created || '',\n modified: packageInfo.time?.modified || '',\n },\n }\n\n console.log(JSON.stringify(result, null, 2))\n })\n\nprogram\n .command('resolve-context7')\n .description('Resolve the best Context7 library id for an npm package')\n .argument('<package_name>', 'The npm package name to resolve against Context7')\n .option('--package-version <version>', 'Explicit package version to use in the Context7 query')\n .option('-l, --limit <limit>', 'Number of candidates to keep in the response', '5')\n .action(async (packageName: string, options) => {\n const { Context7Utils } = await import('./utils/context7.js')\n\n const resolved = await Context7Utils.resolveLibrary(packageName, {\n version: options.packageVersion,\n limit: parseInt(options.limit, 10),\n })\n\n if (!resolved) {\n console.error(`❌ No Context7 library found for package \"${packageName}\".`)\n process.exit(1)\n }\n\n console.log(JSON.stringify(resolved, null, 2))\n })\n\n// Add search-skill command\nprogram\n .command('search-skill')\n .argument('<query>', 'Search query')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .option('--mode <mode>', 'Search mode: auto, fulltext, fuzzy, or vector', 'auto')\n .option(\n '--vector-embedder <mode>',\n 'Vector embedder mode: deterministic for offline local embeddings, or omit for the default runtime embedder'\n )\n .option('--list', 'Show simplified list view (basic info only)', false)\n .action(async (query, options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n console.log(gradient('cyan', 'magenta')('\\n🔍 Searching in skill...'))\n console.log(`Skill Path: ${skillDir}`)\n console.log(`Query: ${query}`)\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { runScript } = await import('./core/runScript.js')\n const args = ['--query', query]\n if (options.mode !== 'auto') args.push('--mode', options.mode)\n if (options.vectorEmbedder) args.push('--vector-embedder', options.vectorEmbedder)\n if (options.list) args.push('--list')\n // Enhanced search is now enabled by default, no need for --enhanced flag\n await runScript('search-skill', args)\n } finally {\n chdir(originalCwd)\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add download-context7 command\nprogram\n .command('download-context7')\n .argument('[project_id]', 'Context7 library ID')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .option(\n '--package-version <version>',\n 'Version hint used when resolving a Context7 library from --package'\n )\n .option('-f, --force', 'Force update even if up to date')\n .option('--skip-indexing', 'Skip automatic local index building after download')\n .option('--json', 'Print machine-readable download output')\n .action(async (projectId, options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n let resolvedProjectId = projectId as string | undefined\n let resolvedContext7Query: string | undefined\n let resolvedPackageName: string | undefined\n let resolvedVersionHint: string | undefined\n\n if (!resolvedProjectId) {\n const inferredMetadata = inferPackageMetadataFromSkill(skillDir)\n const packageName = options.package || inferredMetadata.packageName\n const versionHint =\n options.packageVersion ||\n inferredMetadata.versionHint ||\n inferVersionHintFromSkillDirectory(skillDir)\n\n if (!packageName) {\n console.error(\n '❌ Please provide either a Context7 project ID, --package <name>, or a skill created with package metadata'\n )\n process.exit(1)\n }\n\n const { Context7Utils } = await import('./utils/context7.js')\n\n if (!options.json) {\n console.log(gradient('cyan', 'magenta')('\\n🧭 Resolving Context7 library...'))\n console.log(`Package: ${packageName}`)\n if (versionHint) {\n console.log(`Version hint: ${versionHint}`)\n }\n }\n\n const resolved = await Context7Utils.resolveLibrary(packageName, {\n version: versionHint,\n })\n\n if (!resolved) {\n console.error(`❌ No Context7 library found for package \"${packageName}\".`)\n process.exit(1)\n }\n\n resolvedProjectId = resolved.bestMatch.id\n resolvedContext7Query = resolved.query\n resolvedPackageName = packageName\n resolvedVersionHint = resolved.version ?? versionHint\n if (!options.json) {\n console.log(`Resolved Context7 ID: ${resolvedProjectId}`)\n console.log(`Resolution query: ${resolved.query}`)\n }\n }\n\n if (!options.json) {\n console.log(gradient('cyan', 'magenta')('\\n📥 Downloading Context7 documentation...'))\n console.log(`Skill Path: ${skillDir}`)\n console.log(`Context7 ID: ${resolvedProjectId}`)\n }\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { runScript } = await import('./core/runScript.js')\n const args = []\n\n if (options.force) args.push('--force')\n if (options['skipIndexing']) args.push('--skip-indexing')\n if (options.json) args.push('--json')\n if (resolvedPackageName) args.push('--package-name', resolvedPackageName)\n if (resolvedVersionHint) args.push('--package-version', resolvedVersionHint)\n args.push('--project-id', resolvedProjectId)\n\n const result = await runScript('download-context7', args)\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n skillPath: skillDir,\n requestedProjectId: projectId ?? null,\n resolvedProjectId,\n resolvedPackageName: resolvedPackageName ?? null,\n resolvedVersionHint: resolvedVersionHint ?? null,\n resolutionQuery: resolvedContext7Query ?? null,\n ...(result as Record<string, unknown>),\n },\n null,\n 2\n )\n )\n }\n } finally {\n chdir(originalCwd)\n }\n\n if (!options.json) {\n console.log(gradient('green', 'cyan')('\\n✅ Documentation downloaded and sliced!'))\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add add-skill command\nprogram\n .command('add-skill')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .option('-t, --title <title>', 'Content title')\n .option('-c, --content <content>', 'Content text')\n .option('-f, --file <file>', 'Read content from file')\n .option('--force', 'Replace the closest matching user knowledge note')\n .option(\n '--force-append',\n 'Append content as a knowledge update in the closest matching user note'\n )\n .option('--json', 'Print machine-readable add-content output')\n .action(async (options) => {\n if (!options.title && !options.file) {\n console.error('❌ Please provide either --title or --file')\n process.exit(1)\n }\n\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n if (!options.json) {\n console.log(gradient('cyan', 'magenta')('\\n📝 Adding content to skill...'))\n console.log(`Skill Path: ${skillDir}`)\n }\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { runScript } = await import('./core/runScript.js')\n const args = []\n\n if (options.title) args.push('--title', options.title)\n if (options.content) args.push('--content', options.content)\n if (options.file) args.push('--file', options.file)\n if (options.force) args.push('--force')\n if (options.forceAppend) args.push('--force-append')\n if (options.json) args.push('--json')\n\n const result = await runScript('add', args)\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n skillPath: skillDir,\n ...(result as Record<string, unknown>),\n },\n null,\n 2\n )\n )\n }\n } finally {\n chdir(originalCwd)\n }\n\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add build-index command\nprogram\n .command('build-index')\n .description('Build or refresh the local search index for a skill')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .option('--mode <mode>', 'Index mode: auto, fulltext, or vector', 'auto')\n .option(\n '--vector-embedder <mode>',\n 'Vector embedder mode: deterministic for offline local embeddings, or omit for the default runtime embedder'\n )\n .option('--json', 'Print machine-readable index build output')\n .action(async (options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n if (!options.json) {\n console.log(gradient('cyan', 'magenta')('\\n🔧 Building search index...'))\n console.log(`Skill Path: ${skillDir}`)\n }\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { buildIndex } = await import('./commands/buildIndex.js')\n const args = []\n if (options.mode !== 'auto') args.push('--mode', options.mode)\n if (options.vectorEmbedder) args.push('--vector-embedder', options.vectorEmbedder)\n if (options.json) args.push('--json')\n const result = await buildIndex(args)\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n skillPath: skillDir,\n ...result,\n },\n null,\n 2\n )\n )\n }\n } finally {\n chdir(originalCwd)\n }\n\n if (!options.json) {\n console.log(gradient('green', 'cyan')('\\n✅ Search index ready!'))\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add sub-commands for script execution\nprogram\n .command('list-skills')\n .description('List all skill content files')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .action(async (options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n console.log(gradient('cyan', 'magenta')('\\n📚 Skill Content'))\n console.log(`Skill Path: ${skillDir}`)\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { runScript } = await import('./core/runScript.js')\n await runScript(\n 'list-skills',\n process.argv\n .slice(3)\n .filter(\n (arg) =>\n !arg.startsWith('--pwd') &&\n !arg.startsWith('--package') &&\n arg !== options.pwd &&\n arg !== options.package\n )\n )\n } finally {\n chdir(originalCwd)\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add remove-skill command\nprogram\n .command('remove-skill')\n .description('Remove a skill file')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .option('--type <type>', 'Type: user or context7:<project_id>', 'user')\n .option('--file <file>', 'File name to remove')\n .action(async (options) => {\n try {\n if (!options.file) {\n console.error('❌ Please provide --file <filename>')\n process.exit(1)\n }\n\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n console.log(gradient('cyan', 'magenta')('\\n🗑️ Remove Skill File'))\n console.log(`Skill Path: ${skillDir}`)\n console.log(`Type: ${options.type}`)\n console.log(`File: ${options.file}`)\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { removeSkill } = await import('./commands/removeSkill.js')\n await removeSkill(['--type', options.type, '--file', options.file])\n } finally {\n chdir(originalCwd)\n }\n\n console.log(gradient('green', 'cyan')('\\n✅ Skill file removed!'))\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add list-context7 command\nprogram\n .command('list-context7')\n .description('List all Context7 projects')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .action(async (options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n console.log(gradient('cyan', 'magenta')('\\n📦 Context7 Projects'))\n console.log(`Skill Path: ${skillDir}`)\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { listContext7 } = await import('./commands/listContext7.js')\n await listContext7()\n } finally {\n chdir(originalCwd)\n }\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Add remove-context7 command\nprogram\n .command('remove-context7')\n .argument('<project_id>', 'Context7 project ID to remove')\n .description('Remove a Context7 project')\n .option('--pwd <path>', 'Path to the skill directory')\n .option('--package <name>', 'Package name to find skill directory for')\n .action(async (projectId, options) => {\n try {\n const skillDir = resolveSkillDirectoryFromOptions(options, globalOptions)\n\n console.log(gradient('cyan', 'magenta')('\\n🗑️ Remove Context7 Project'))\n console.log(`Skill Path: ${skillDir}`)\n console.log(`Project ID: ${projectId}`)\n\n const { chdir } = await import('node:process')\n const originalCwd = process.cwd()\n chdir(skillDir)\n\n try {\n const { removeContext7 } = await import('./commands/removeContext7.js')\n await removeContext7(['--project-id', projectId])\n } finally {\n chdir(originalCwd)\n }\n\n console.log(gradient('green', 'cyan')('\\n✅ Context7 project removed!'))\n } catch (error) {\n console.error(error)\n process.exit(1)\n }\n })\n\n// Export for testing\nexport { program }\n\n// Run CLI if this file is executed directly\n// Always parse for now since we're using this as the main CLI entry point\nprogram.parse()\n"],"mappings":";gQAOA,eAAsB,EACpB,EACA,EAEI,EAAE,CACW,CACjB,IAAM,EAAU,IAAI,EAWf,EAAQ,MACX,QAAQ,IAAI,EAAS,OAAQ,UAAU,CAAC;sBAAyB,CAAC,CAGpE,IAAM,EAAS,MAAM,EAAQ,YAAY,EAAc,CAE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@@
|
|
|
1
|
-
import{a as e}from"./referenceSearchUtils-DZgupMZp.mjs";import{t}from"./searchQuality-DVdHmamh.mjs";import{isAbsolute as n,join as r}from"node:path";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,rmSync as c,statSync as l,writeFileSync as u}from"node:fs";import{createHash as d}from"node:crypto";var f=class{options;userDir;context7BaseDir;constructor(e){this.options=e,this.userDir=r(e.referencesDir,`user`),this.context7BaseDir=r(e.referencesDir,`context7`)}getContext7ProjectDir(e){return r(this.context7BaseDir,this.encodeContext7ProjectId(e))}encodeContext7ProjectId(e){return encodeURIComponent(e)}decodeContext7ProjectId(e){return decodeURIComponent(e)}async updateFromContext7(e,t=!1){let n={updated:!1,skipped:!1,filesCreated:0,message:``};try{let o=await this.downloadContext7Doc(e),l=this.getContext7ProjectDir(e);if(!t&&!this.needsUpdate(o,e))return n.skipped=!0,n.message=`Context7 documentation is up to date`,n;if(i(l)){let e=s(l);for(let t of e)t.endsWith(`.md`)&&c(r(l,t))}a(l,{recursive:!0});let u=await this.sliceDocument(o,l);n.filesCreated=u.length,this.saveContentHash(o,e),await this.invalidateSearchIndex(),n.updated=!0,n.message=`Updated ${u.length} documentation slices for project ${e}`}catch(e){n.message=`Failed to update Context7 docs: ${e}`}return n}async addUserContent(e){let t={added:!1,updated:!1,skipped:!1,message:``,similarFound:0};try{await this.prepareSearchEngine();let n=await this.findSimilarContent(e.content),r=this.mergeSimilarResults(n,this.findDirectUserMatches(e.content));if(e.force||e.forceAppend){let n=r.find(e=>e.source===`user`)??this.findBestUserMergeTarget(e.title,e.content)??this.findUserFileByTitle(e.title);if(n){let i=this.resolveSearchResultFilePath(n.file_path),a=o(i,`utf-8`);return e.forceAppend?(u(i,this.appendKnowledgeUpdate(a,e.title,e.content)),t.added=!0,t.filePath=i,t.message=`Appended content to existing knowledge note: ${i.split(`/`).pop()}`):(u(i,this.renderKnowledgeNote(e.title,e.content)),t.added=!0,t.filePath=i,t.message=`Replaced existing knowledge note: ${i.split(`/`).pop()}`),t.similarContent=this.summarizeSimilarContent([n,...r.filter(e=>e.id!==n.id)],e.content),t.similarFound=t.similarContent.length,await this.invalidateSearchIndex(),t}}if(r.length>0&&!e.force){let n=r[0];if(n.source===`user`){let r=this.resolveSearchResultFilePath(n.file_path);this.isContentDuplicate(n,e.content)?(t.skipped=!0,t.message=`Existing content is comprehensive enough`):e.autoUpdate&&this.isContentEnhanced(n,e.content)?(u(r,this.renderKnowledgeNote(e.title,e.content)),t.updated=!0,t.filePath=r,t.message=`Updated existing content: ${n.file_path}`,await this.invalidateSearchIndex()):(t.skipped=!0,t.message=`Existing content is comprehensive enough`)}else if(this.isContentDuplicate(n,e.content))t.skipped=!0,t.message=`Existing context7 content is comprehensive enough`;else{let n=this.writeUserContentFile(e);t.added=!0,t.filePath=n.filePath,t.message=n.message,await this.invalidateSearchIndex()}t.similarContent=this.summarizeSimilarContent(r,e.content),t.similarFound=r.length}else if(!t.added&&!t.updated&&!t.skipped){let n=this.getExpectedUserFilePath(e.title);if(i(n)&&!e.force&&!e.forceAppend){let{readFileSync:r}=await import(`node:fs`),i=r(n,`utf-8`),a={content:i,file_path:n};this.isContentDuplicate(a,e.content)?(t.skipped=!0,t.message=`Existing content is comprehensive enough`,t.similarContent=this.summarizeSimilarContent([{id:`user/${n.split(`/`).pop()??`existing.md`}`,title:e.title,content:i,source:`user`,file_path:n,score:1,metadata:{backendId:`direct-user-match`}}],e.content)):e.autoUpdate&&this.isContentEnhanced(a,e.content)?(u(n,this.renderKnowledgeNote(e.title,e.content)),t.updated=!0,t.filePath=n,t.message=`Updated existing content: ${n.split(`/`).pop()}`,await this.invalidateSearchIndex()):(t.message=`File already exists: ${n.split(`/`).pop()}. Use --force to overwrite or --force-append to append.`,t.existingFile={path:n,content:i})}else{let r=this.writeUserContentFile(e,{overwriteExisting:i(n)&&!!e.force});t.message=r.message,t.filePath=r.filePath,t.added=!0,await this.invalidateSearchIndex()}}}catch(e){t.message=`Failed to add content: ${e}`}return t.similarFound=t.similarContent?.length||0,t}getContentStats(){let e={userFiles:0,context7Files:0,totalFiles:0,userDirExists:i(this.userDir),context7DirExists:i(this.context7BaseDir)};if(e.userDirExists&&(e.userFiles=s(this.userDir).filter(e=>e.endsWith(`.md`)).length),e.context7DirExists){let t=s(this.context7BaseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let n of t){let t=r(this.context7BaseDir,n);i(t)&&(e.context7Files+=s(t).filter(e=>e.endsWith(`.md`)).length)}}return e.totalFiles=e.userFiles+e.context7Files,e}listContent(e){let t=[];if((e===`user`||!e)&&i(this.userDir)){let e=s(this.userDir);for(let n of e){if(!n.endsWith(`.md`))continue;let e=r(this.userDir,n),i=l(e),a=n.replace(`.md`,``);try{let t=o(e,`utf-8`).split(`
|
|
2
|
-
`)[0];t?.startsWith(`# `)&&(a=t.slice(2))}catch{}t.push({title:a,filename:n,source:`user`,path:e,size:i.size,modified:i.mtime||new Date})}}if((e===`context7`||!e)&&i(this.context7BaseDir)){let e=s(this.context7BaseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let n of e){this.decodeContext7ProjectId(n);let e=r(this.context7BaseDir,n);if(i(e)){let n=s(e);for(let i of n){if(!i.endsWith(`.md`))continue;let n=r(e,i),a=l(n),s=i.replace(`.md`,``);try{let e=o(n,`utf-8`).split(`
|
|
3
|
-
`)[0];e?.startsWith(`# `)&&(s=e.slice(2))}catch{}t.push({title:s,filename:i,source:`context7`,path:n,size:a.size,modified:a.mtime||new Date})}}}}return t.sort((e,t)=>t.modified.getTime()-e.modified.getTime())}async downloadContext7Doc(e){let t=`${(process.env.SKILL_CREATOR_CONTEXT7_BASE_URL??`https://context7.com`).replace(/\/$/,``)}${e}/llms.txt?tokens=100000000&topic=*`,n=await(this.options.fetchImpl??fetch)(t);if(!n.ok)throw Error(`Failed to download: ${n.statusText}`);return await n.text()}async sliceDocument(e,t){let n=this.extractSections(e),i=[];for(let e=0;e<n.length;e++){let{title:a,content:o}=n[e];if(!o.trim())continue;let s=r(t,this.createUniqueFileName(a,e,t));u(s,`# ${a}\n\n${o}`),i.push(s)}return i}extractSections(e){let t=[],n=e.split(`
|
|
4
|
-
`),r={title:`Introduction`,content:``},i=[],a=/^(#{1,6})\s+(.+)$/;for(let e=0;e<n.length;e++){let o=n[e],s=a.exec(o);s?(i.length>0&&(r.content=i.join(`
|
|
5
|
-
`).trim(),r.content.length>50&&t.push({...r}),i=[]),r={title:s[2].trim(),content:``}):(o.trim()||i.length>0)&&i.push(o)}return i.length>0&&(r.content=i.join(`
|
|
6
|
-
`).trim(),r.content.length>50&&t.push(r)),this.mergeShortSections(t)}mergeShortSections(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.content.length<200&&n<e.length-1){let i=e[n+1];this.isMajorSection(i.title)?t.push(r):(t.push({title:r.title,content:r.content+`
|
|
7
|
-
|
|
8
|
-
`+i.content}),n++)}else t.push(r)}return t}isMajorSection(e){let t=[`introduction`,`getting started`,`installation`,`setup`,`api`,`reference`,`examples`,`tutorial`,`guide`,`overview`,`quick start`,`basics`,`advanced`],n=e.toLowerCase();return t.some(e=>n.includes(e))}createUniqueFileName(e,t,n){let a=e.replace(/[^\w\s-]/g,``).replace(/[-\s]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,50)||`section`,o=this.extractHeadingLevel(e),s=`${(o>1?`${`0`.repeat(Math.min(o-1,3))}${t}`:t.toString()).padStart(4,`0`)}_${a}`,c=`${s}.md`,l=1;for(;i(r(n,c));)c=`${s}_${l.toString().padStart(2,`0`)}.md`,l++;return c}extractHeadingLevel(e){let t=e.match(/^(#{1,6})\s*(.+)$/);return t?t[1].length:/^(Chapter|Section|Part)\s+\d+/i.test(e)?1:/^\d+\.\d+/i.test(e)?2:/^\d+\.\d+\.\d+/i.test(e)?3:1}createUniqueFilePath(e,t){let n=e.toLowerCase().replace(/[^\w\s-]/g,``).replace(/[-\s]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,50)||`content`,a=`${n}.md`,o=1;for(;i(r(t,a));)a=`${n}_${o.toString().padStart(2,`0`)}.md`,o++;return r(t,a)}async findSimilarContent(e,t=.7,n=10){return(await this.options.searchEngine.search(e,n)).map(e=>({...e,similarity:this.getSimilarityScore(e)})).filter(e=>e.similarity>=t).sort((e,t)=>this.getSourcePriority(t.source)-this.getSourcePriority(e.source)||t.similarity-e.similarity||t.score-e.score)}isContentEnhanced(e,t){let n=e.content.split(/\s+/).length;return t.split(/\s+/).length>n*1.3}isContentDuplicate(e,t){let n=this.normalizeContentForComparison(e.content),r=this.normalizeContentForComparison(t);if(n===r)return!0;let i=Math.min(n.length,r.length);return i===0?!1:(n.includes(r)||r.includes(n))&&i/Math.max(n.length,r.length)>=.85}normalizeContentForComparison(t){return e(t).toLowerCase().replace(/\s+/g,` `).trim()}getSimilarityScore(e){let t=e.metadata?.rerankScore;return typeof t==`number`&&Number.isFinite(t)?this.clamp01(t):e.metadata?.backendId===`minisearch`||e.score>1?this.clamp01(e.score/(e.score+3)):this.clamp01(e.score)}mergeSimilarResults(e,t){let n=new Map;for(let r of[...e,...t]){let e=n.get(r.id);if(!e){n.set(r.id,r);continue}let t=this.getSimilarityScore(e);this.getSimilarityScore(r)>t&&n.set(r.id,r)}return Array.from(n.values()).sort((e,t)=>this.getSourcePriority(t.source)-this.getSourcePriority(e.source)||this.getSimilarityScore(t)-this.getSimilarityScore(e)||t.score-e.score)}findDirectUserMatches(e){if(!i(this.userDir))return[];let t=this.normalizeContentForComparison(e),n=new Set(t.split(/\s+/).filter(Boolean));return s(this.userDir).filter(e=>e.endsWith(`.md`)).map(i=>{let a=r(this.userDir,i),s=o(a,`utf-8`),c=s.split(`
|
|
9
|
-
`)[0]?.replace(/^#+\s*/,``).trim()||i.replace(/\.md$/,``),l=this.normalizeContentForComparison(s),u=new Set(l.split(/\s+/).filter(Boolean)),d=this.calculateTokenOverlap(n,u),f=this.isContentDuplicate({content:s},e)?1:l.includes(t)||t.includes(l)?.9:d;return{id:`user/${i}`,title:c,content:s,source:`user`,file_path:a,score:f,metadata:{backendId:`direct-user-match`}}}).filter(e=>e.score>=.7)}findUserFileByTitle(e){let t=this.getExpectedUserFilePath(e);if(!i(t))return;let n=o(t,`utf-8`);return{id:`user/${t.split(`/`).pop()??`existing.md`}`,title:e,content:n,source:`user`,file_path:t,score:1,metadata:{backendId:`direct-user-match`}}}findBestUserMergeTarget(e,t){if(!i(this.userDir))return;let n=this.normalizeContentForComparison(e),a=new Set(n.split(/\s+/).filter(Boolean)),c=this.normalizeContentForComparison(t),l=new Set(c.split(/\s+/).filter(Boolean)),u=s(this.userDir).filter(e=>e.endsWith(`.md`)).map(e=>{let i=r(this.userDir,e),s=o(i,`utf-8`),u=s.split(`
|
|
10
|
-
`)[0]?.replace(/^#+\s*/,``).trim()||e.replace(/\.md$/,``),d=this.normalizeContentForComparison(u),f=this.normalizeContentForComparison(s),p=this.calculateTokenOverlap(a,new Set(d.split(/\s+/).filter(Boolean))),m=this.calculateTokenOverlap(l,new Set(f.split(/\s+/).filter(Boolean))),h=this.isContentDuplicate({content:s},t)?1:f.includes(c)||c.includes(f)?.9:0,g=d===n?1:0,_=Math.max(h,g,p*.45+m*.55);return{result:{id:`user/${e}`,title:u,content:s,source:`user`,file_path:i,score:_,metadata:{backendId:`direct-user-match`}},mergeScore:_}}).sort((e,t)=>t.mergeScore-e.mergeScore);return u[0]!=null&&u[0].mergeScore>=.2?u[0].result:void 0}calculateTokenOverlap(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/Math.max(e.size,t.size)}getSourcePriority(e){return e===`user`?1:0}clamp01(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}summarizeSimilarContent(e,n){return t(e.slice(0,3),n).results.map(e=>({title:e.result.title,score:Number((e.displayScore*100).toFixed(2)),source:e.result.source,sourceRank:e.index===0?`primary`:`secondary`,preview:e.result.content.slice(0,200)+`...`}))}resolveSearchResultFilePath(e){return n(e)?e:r(this.options.referencesDir,e)}getExpectedUserFilePath(e){a(this.userDir,{recursive:!0});let t=e.toLowerCase().replace(/[^\w\s-]/g,``).replace(/[-\s]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,50)||`content`;return r(this.userDir,`${t}.md`)}renderKnowledgeNote(e,t){return`# ${e}\n\n${this.stripMatchingLeadingHeading(t,e)}`}appendKnowledgeUpdate(e,t,n){let r=e.trimEnd(),i=`## Knowledge updates`,a=`### Update ${this.getNextKnowledgeUpdateIndex(r)}: ${t}\n\n${this.stripMatchingLeadingHeading(n,t)}`;return r.includes(i)?`${r}\n\n${a}\n`:`${r}\n\n${i}\n\n${a}\n`}getNextKnowledgeUpdateIndex(e){return[...e.matchAll(/^### Update (\d+): /gm)].reduce((e,t)=>{let n=Number(t[1]);return Number.isFinite(n)?Math.max(e,n):e},0)+1}stripMatchingLeadingHeading(e,t){let n=e.trim();if(!n)return``;let r=n.split(`
|
|
11
|
-
`),i=r.findIndex(e=>e.trim().length>0);if(i<0)return n;let a=r[i]?.trim()??``,o=/^(#{1,6})\s+(.+)$/.exec(a);if(!o||this.normalizeContentForComparison(o[2]??``)!==this.normalizeContentForComparison(t))return n;let s=r.slice(i+1);for(;s[0]?.trim()===``;)s.shift();return s.join(`
|
|
12
|
-
`).trim()||n}writeUserContentFile(e,t={}){a(this.userDir,{recursive:!0});let n=this.getExpectedUserFilePath(e.title);if(t.overwriteExisting&&i(n))return u(n,this.renderKnowledgeNote(e.title,e.content)),{filePath:n,message:`Overwrote existing content: ${n.split(`/`).pop()}`};let r=this.createUniqueFilePath(e.title,this.userDir);return u(r,this.renderKnowledgeNote(e.title,e.content)),{filePath:r,message:`Created new content: ${r.split(`/`).pop()}`}}getHashFilePath(e){let t=this.encodeContext7ProjectId(e);return r(this.options.referencesDir,`..`,`.context7_hash_${t}`)}saveContentHash(e,t){let n=d(`md5`).update(e).digest(`hex`);u(this.getHashFilePath(t),n)}needsUpdate(e,t){let n=this.getHashFilePath(t);return i(n)?d(`md5`).update(e).digest(`hex`)!==o(n,`utf-8`):!0}async prepareSearchEngine(){typeof this.options.searchEngine.initialize==`function`&&await this.options.searchEngine.initialize(),typeof this.options.searchEngine.buildIndex==`function`&&await this.options.searchEngine.buildIndex(this.options.referencesDir)}async invalidateSearchIndex(){typeof this.options.searchEngine.clearIndex==`function`&&await this.options.searchEngine.clearIndex();let e=r(this.options.referencesDir,`..`,`search`);for(let t of[`index-state.json`,`minisearch-index.json`,`vector-index-state.json`,`vector-index.db`])c(r(e,t),{force:!0})}listContext7Projects(){let e=[];if(!i(this.context7BaseDir))return e;let t=s(this.context7BaseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let n of t){let t=this.decodeContext7ProjectId(n),a=r(this.context7BaseDir,n);if(i(a)){let n=s(a).filter(e=>e.endsWith(`.md`));e.push({projectId:t,filesCount:n.length,directory:a})}}return e}getContext7ProjectFiles(e){let t=this.getContext7ProjectDir(e);return i(t)?s(t).filter(e=>e.endsWith(`.md`)):[]}removeContext7Project(e){let t=this.getContext7ProjectDir(e);if(!i(t))return{success:!1,message:`Context7 project ${e} does not exist`};try{c(t,{recursive:!0,force:!0});let n=this.getHashFilePath(e);return i(n)&&c(n),this.invalidateSearchIndex(),{success:!0,message:`Context7 project ${e} removed successfully`}}catch(t){return{success:!1,message:`Failed to remove Context7 project ${e}: ${t}`}}}};export{f as t};
|
|
13
|
-
//# sourceMappingURL=contentManager-CoVTiSDT.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contentManager-CoVTiSDT.mjs","names":["result: UpdateContext7Result","result: AddContentResult","result","readFileSync","stats: ContentStats","contentList: ContentItem[]","savedFiles: string[]","sections: Array<{ title: string; content: string }>","sectionContent: string[]","merged: Array<{ title: string; content: string }>","projects: Array<{ projectId: string; filesCount: number; directory: string }>"],"sources":["../src/core/contentManager.ts"],"sourcesContent":["/**\n * Content management with Context7 integration\n */\n\nimport { isAbsolute, join } from 'node:path'\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n writeFileSync,\n rmSync,\n statSync,\n readFileSync,\n} from 'node:fs'\nimport { createHash } from 'node:crypto'\nimport type {\n SearchResult,\n ContentStats,\n ContentItem,\n UpdateContext7Result,\n AddContentResult,\n} from '../types/index.js'\nimport { normalizeSearchableText } from './referenceSearchUtils.js'\nimport { analyzeSearchQuality } from './searchQuality.js'\n\nexport interface ContentManagerOptions {\n searchEngine: {\n initialize?(): Promise<void>\n buildIndex?(referencesDir: string): Promise<void>\n clearIndex?(): Promise<void> | void\n search(query: string, topK?: number, where?: any): Promise<any[]>\n }\n referencesDir: string\n fetchImpl?: typeof fetch\n}\n\nexport class ContentManager {\n private options: ContentManagerOptions\n private userDir: string\n private context7BaseDir: string\n\n constructor(options: ContentManagerOptions) {\n this.options = options\n this.userDir = join(options.referencesDir, 'user')\n this.context7BaseDir = join(options.referencesDir, 'context7')\n }\n\n /**\n * Get the directory path for a specific context7 project\n */\n private getContext7ProjectDir(projectId: string): string {\n return join(this.context7BaseDir, this.encodeContext7ProjectId(projectId))\n }\n\n private encodeContext7ProjectId(projectId: string): string {\n return encodeURIComponent(projectId)\n }\n\n private decodeContext7ProjectId(encodedProjectId: string): string {\n return decodeURIComponent(encodedProjectId)\n }\n\n async updateFromContext7(\n libraryId: string,\n force: boolean = false\n ): Promise<UpdateContext7Result> {\n const result: UpdateContext7Result = {\n updated: false,\n skipped: false,\n filesCreated: 0,\n message: '',\n }\n\n try {\n // Download content\n const content = await this.downloadContext7Doc(libraryId)\n\n // Get project-specific directory\n const projectDir = this.getContext7ProjectDir(libraryId)\n\n // Check if update needed\n if (!force && !this.needsUpdate(content, libraryId)) {\n result.skipped = true\n result.message = 'Context7 documentation is up to date'\n return result\n }\n\n // Clear existing context7 docs for this project\n if (existsSync(projectDir)) {\n const files = readdirSync(projectDir)\n for (const file of files) {\n if (file.endsWith('.md')) {\n rmSync(join(projectDir, file))\n }\n }\n }\n\n // Ensure directory exists\n mkdirSync(projectDir, { recursive: true })\n\n // Slice and save\n const savedFiles = await this.sliceDocument(content, projectDir)\n result.filesCreated = savedFiles.length\n\n // Save hash for this project\n this.saveContentHash(content, libraryId)\n\n // Trigger reindex\n await this.invalidateSearchIndex()\n\n result.updated = true\n result.message = `Updated ${savedFiles.length} documentation slices for project ${libraryId}`\n } catch (error) {\n result.message = `Failed to update Context7 docs: ${error}`\n }\n\n return result\n }\n\n async addUserContent(options: {\n title: string\n content: string\n force?: boolean\n forceAppend?: boolean\n autoUpdate?: boolean\n }): Promise<AddContentResult> {\n const result: AddContentResult = {\n added: false,\n updated: false,\n skipped: false,\n message: '',\n similarFound: 0,\n }\n\n try {\n // Search for similar content\n await this.prepareSearchEngine()\n const similar = await this.findSimilarContent(options.content)\n const mergedSimilar = this.mergeSimilarResults(\n similar,\n this.findDirectUserMatches(options.content)\n )\n\n if (options.force || options.forceAppend) {\n const mergeTarget =\n mergedSimilar.find((result) => result.source === 'user') ??\n this.findBestUserMergeTarget(options.title, options.content) ??\n this.findUserFileByTitle(options.title)\n\n if (mergeTarget) {\n const filePath = this.resolveSearchResultFilePath(mergeTarget.file_path)\n const existingContent = readFileSync(filePath, 'utf-8')\n\n if (options.forceAppend) {\n const newContent = this.appendKnowledgeUpdate(existingContent, options.title, options.content)\n writeFileSync(filePath, newContent)\n result.added = true\n result.filePath = filePath\n result.message = `Appended content to existing knowledge note: ${filePath.split('/').pop()}`\n } else {\n writeFileSync(filePath, this.renderKnowledgeNote(options.title, options.content))\n result.added = true\n result.filePath = filePath\n result.message = `Replaced existing knowledge note: ${filePath.split('/').pop()}`\n }\n\n result.similarContent = this.summarizeSimilarContent(\n [mergeTarget, ...mergedSimilar.filter((candidate) => candidate.id !== mergeTarget.id)],\n options.content\n )\n result.similarFound = result.similarContent.length\n\n await this.invalidateSearchIndex()\n return result\n }\n }\n\n if (mergedSimilar.length > 0 && !options.force) {\n const bestMatch = mergedSimilar[0]\n\n if (bestMatch.source === 'user') {\n // Update user file\n const filePath = this.resolveSearchResultFilePath(bestMatch.file_path)\n\n if (this.isContentDuplicate(bestMatch, options.content)) {\n result.skipped = true\n result.message = 'Existing content is comprehensive enough'\n } else if (options.autoUpdate && this.isContentEnhanced(bestMatch, options.content)) {\n writeFileSync(filePath, this.renderKnowledgeNote(options.title, options.content))\n\n result.updated = true\n result.filePath = filePath\n result.message = `Updated existing content: ${bestMatch.file_path}`\n\n // Trigger index update\n await this.invalidateSearchIndex()\n } else {\n result.skipped = true\n result.message = 'Existing content is comprehensive enough'\n }\n } else {\n if (this.isContentDuplicate(bestMatch, options.content)) {\n result.skipped = true\n result.message = 'Existing context7 content is comprehensive enough'\n } else {\n const created = this.writeUserContentFile(options)\n result.added = true\n result.filePath = created.filePath\n result.message = created.message\n\n // Trigger index update\n await this.invalidateSearchIndex()\n }\n }\n result.similarContent = this.summarizeSimilarContent(mergedSimilar, options.content)\n result.similarFound = mergedSimilar.length\n } else if (!result.added && !result.updated && !result.skipped) {\n const existingUserFile = this.getExpectedUserFilePath(options.title)\n\n if (existsSync(existingUserFile) && !options.force && !options.forceAppend) {\n const { readFileSync } = await import('node:fs')\n const existingContent = readFileSync(existingUserFile, 'utf-8')\n const existingEntry = {\n content: existingContent,\n file_path: existingUserFile,\n }\n\n if (this.isContentDuplicate(existingEntry, options.content)) {\n result.skipped = true\n result.message = 'Existing content is comprehensive enough'\n result.similarContent = this.summarizeSimilarContent(\n [\n {\n id: `user/${existingUserFile.split('/').pop() ?? 'existing.md'}`,\n title: options.title,\n content: existingContent,\n source: 'user',\n file_path: existingUserFile,\n score: 1,\n metadata: {\n backendId: 'direct-user-match',\n },\n },\n ],\n options.content\n )\n } else if (options.autoUpdate && this.isContentEnhanced(existingEntry, options.content)) {\n writeFileSync(existingUserFile, this.renderKnowledgeNote(options.title, options.content))\n result.updated = true\n result.filePath = existingUserFile\n result.message = `Updated existing content: ${existingUserFile.split('/').pop()}`\n\n await this.invalidateSearchIndex()\n } else {\n // File exists and no force flag - show error and file content\n result.message = `File already exists: ${existingUserFile.split('/').pop()}. Use --force to overwrite or --force-append to append.`\n result.existingFile = {\n path: existingUserFile,\n content: existingContent,\n }\n }\n } else {\n const created = this.writeUserContentFile(options, {\n overwriteExisting: existsSync(existingUserFile) && Boolean(options.force),\n })\n result.message = created.message\n result.filePath = created.filePath\n\n result.added = true\n\n // Trigger index update\n await this.invalidateSearchIndex()\n }\n }\n } catch (error) {\n result.message = `Failed to add content: ${error}`\n }\n\n result.similarFound = result.similarContent?.length || 0\n return result\n }\n\n getContentStats(): ContentStats {\n const stats: ContentStats = {\n userFiles: 0,\n context7Files: 0,\n totalFiles: 0,\n userDirExists: existsSync(this.userDir),\n context7DirExists: existsSync(this.context7BaseDir),\n }\n\n if (stats.userDirExists) {\n stats.userFiles = readdirSync(this.userDir).filter((f) => f.endsWith('.md')).length\n }\n\n if (stats.context7DirExists) {\n // Count files in all context7 project subdirectories\n const projects = readdirSync(this.context7BaseDir, { withFileTypes: true })\n .filter((dirent) => dirent.isDirectory())\n .map((dirent) => dirent.name)\n\n for (const encodedProjectId of projects) {\n const projectDir = join(this.context7BaseDir, encodedProjectId)\n if (existsSync(projectDir)) {\n stats.context7Files += readdirSync(projectDir).filter((f) => f.endsWith('.md')).length\n }\n }\n }\n\n stats.totalFiles = stats.userFiles + stats.context7Files\n return stats\n }\n\n listContent(source?: 'user' | 'context7'): ContentItem[] {\n const contentList: ContentItem[] = []\n\n // List user content\n if (source === 'user' || !source) {\n if (existsSync(this.userDir)) {\n const files = readdirSync(this.userDir)\n for (const file of files) {\n if (!file.endsWith('.md')) continue\n\n const filePath = join(this.userDir, file)\n const stat = statSync(filePath)\n\n let title = file.replace('.md', '')\n try {\n const content = readFileSync(filePath, 'utf-8')\n const firstLine = content.split('\\n')[0]\n if (firstLine?.startsWith('# ')) {\n title = firstLine.slice(2)\n }\n } catch {\n // Use filename if can't read\n }\n\n contentList.push({\n title,\n filename: file,\n source: 'user',\n path: filePath,\n size: stat.size,\n modified: stat.mtime || new Date(),\n })\n }\n }\n }\n\n // List context7 content from all projects\n if (source === 'context7' || !source) {\n if (existsSync(this.context7BaseDir)) {\n const projects = readdirSync(this.context7BaseDir, { withFileTypes: true })\n .filter((dirent) => dirent.isDirectory())\n .map((dirent) => dirent.name)\n\n for (const encodedProjectId of projects) {\n const projectId = this.decodeContext7ProjectId(encodedProjectId)\n const projectDir = join(this.context7BaseDir, encodedProjectId)\n if (existsSync(projectDir)) {\n const files = readdirSync(projectDir)\n for (const file of files) {\n if (!file.endsWith('.md')) continue\n\n const filePath = join(projectDir, file)\n const stat = statSync(filePath)\n\n let title = file.replace('.md', '')\n try {\n const content = readFileSync(filePath, 'utf-8')\n const firstLine = content.split('\\n')[0]\n if (firstLine?.startsWith('# ')) {\n title = firstLine.slice(2)\n }\n } catch {\n // Use filename if can't read\n }\n\n contentList.push({\n title,\n filename: file,\n source: 'context7',\n path: filePath,\n size: stat.size,\n modified: stat.mtime || new Date(),\n })\n }\n }\n }\n }\n }\n\n return contentList.sort((a, b) => b.modified.getTime() - a.modified.getTime())\n }\n\n private async downloadContext7Doc(libraryId: string): Promise<string> {\n const baseUrl = (process.env.SKILL_CREATOR_CONTEXT7_BASE_URL ?? 'https://context7.com').replace(\n /\\/$/,\n ''\n )\n const url = `${baseUrl}${libraryId}/llms.txt?tokens=100000000&topic=*`\n\n const fetchImpl = this.options.fetchImpl ?? fetch\n const response = await fetchImpl(url)\n if (!response.ok) {\n throw new Error(`Failed to download: ${response.statusText}`)\n }\n\n return await response.text()\n }\n\n private async sliceDocument(content: string, outputDir: string): Promise<string[]> {\n const sections = this.extractSections(content)\n const savedFiles: string[] = []\n\n for (let i = 0; i < sections.length; i++) {\n const { title, content: sectionContent } = sections[i]\n if (!sectionContent.trim()) continue\n\n const filename = this.createUniqueFileName(title, i, outputDir)\n const filePath = join(outputDir, filename)\n\n writeFileSync(filePath, `# ${title}\\n\\n${sectionContent}`)\n savedFiles.push(filePath)\n }\n\n return savedFiles\n }\n\n private extractSections(content: string): Array<{ title: string; content: string }> {\n const sections: Array<{ title: string; content: string }> = []\n const lines = content.split('\\n')\n let currentSection = { title: 'Introduction', content: '' }\n let sectionContent: string[] = []\n\n const headingPattern = /^(#{1,6})\\s+(.+)$/\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n const match = headingPattern.exec(line)\n\n if (match) {\n // Save previous section if it has content\n if (sectionContent.length > 0) {\n currentSection.content = sectionContent.join('\\n').trim()\n\n // Only add section if it meets minimum content threshold\n if (currentSection.content.length > 50) {\n sections.push({ ...currentSection })\n }\n\n sectionContent = []\n }\n\n // Start new section\n currentSection = {\n title: match[2].trim(),\n content: '',\n }\n } else {\n // Add non-heading lines to current section\n if (line.trim() || sectionContent.length > 0) {\n sectionContent.push(line)\n }\n }\n }\n\n // Add the last section\n if (sectionContent.length > 0) {\n currentSection.content = sectionContent.join('\\n').trim()\n if (currentSection.content.length > 50) {\n sections.push(currentSection)\n }\n }\n\n // Post-process sections to merge very short ones\n return this.mergeShortSections(sections)\n }\n\n private mergeShortSections(\n sections: Array<{ title: string; content: string }>\n ): Array<{ title: string; content: string }> {\n const merged: Array<{ title: string; content: string }> = []\n\n for (let i = 0; i < sections.length; i++) {\n const section = sections[i]\n\n // If section is very short and not the last, consider merging with next\n if (section.content.length < 200 && i < sections.length - 1) {\n const nextSection = sections[i + 1]\n\n // Merge if next section is not a major section\n if (!this.isMajorSection(nextSection.title)) {\n merged.push({\n title: section.title,\n content: section.content + '\\n\\n' + nextSection.content,\n })\n i++ // Skip next section\n } else {\n merged.push(section)\n }\n } else {\n merged.push(section)\n }\n }\n\n return merged\n }\n\n private isMajorSection(title: string): boolean {\n const majorKeywords = [\n 'introduction',\n 'getting started',\n 'installation',\n 'setup',\n 'api',\n 'reference',\n 'examples',\n 'tutorial',\n 'guide',\n 'overview',\n 'quick start',\n 'basics',\n 'advanced',\n ]\n\n const titleLower = title.toLowerCase()\n return majorKeywords.some((keyword) => titleLower.includes(keyword))\n }\n\n private createUniqueFileName(title: string, index: number, dir: string): string {\n // Clean up the title for use in filename\n const safeTitle =\n title\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[-\\s]+/g, '_')\n .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores\n .slice(0, 50) || 'section'\n\n // Create hierarchical naming based on heading level if possible\n const headingLevel = this.extractHeadingLevel(title)\n const prefix =\n headingLevel > 1 ? `${'0'.repeat(Math.min(headingLevel - 1, 3))}${index}` : index.toString()\n\n // Use both index and title for better organization\n const baseName = `${prefix.padStart(4, '0')}_${safeTitle}`\n let filename = `${baseName}.md`\n let counter = 1\n\n while (existsSync(join(dir, filename))) {\n filename = `${baseName}_${counter.toString().padStart(2, '0')}.md`\n counter++\n }\n\n return filename\n }\n\n private extractHeadingLevel(title: string): number {\n // Try to extract heading level from title if it contains markdown-like indicators\n const match = title.match(/^(#{1,6})\\s*(.+)$/)\n if (match) {\n return match[1].length\n }\n\n // Look for other indicators in the title\n if (/^(Chapter|Section|Part)\\s+\\d+/i.test(title)) return 1\n if (/^\\d+\\.\\d+/i.test(title)) return 2\n if (/^\\d+\\.\\d+\\.\\d+/i.test(title)) return 3\n\n return 1 // Default to level 1\n }\n\n private createUniqueFilePath(title: string, dir: string): string {\n // Convert to lowercase and clean up for filename\n const safeTitle =\n title\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[-\\s]+/g, '_')\n .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores\n .slice(0, 50) || 'content'\n\n let filename = `${safeTitle}.md`\n let counter = 1\n while (existsSync(join(dir, filename))) {\n filename = `${safeTitle}_${counter.toString().padStart(2, '0')}.md`\n counter++\n }\n return join(dir, filename)\n }\n\n private async findSimilarContent(\n content: string,\n threshold: number = 0.7,\n maxResults: number = 10\n ): Promise<any[]> {\n const results = await this.options.searchEngine.search(content, maxResults)\n return results\n .map((result: any) => ({\n ...result,\n similarity: this.getSimilarityScore(result),\n }))\n .filter((result: any) => result.similarity >= threshold)\n .sort(\n (left: any, right: any) =>\n this.getSourcePriority(right.source) - this.getSourcePriority(left.source) ||\n right.similarity - left.similarity ||\n right.score - left.score\n )\n }\n\n private isContentEnhanced(existing: any, newContent: string): boolean {\n const existingWords = existing.content.split(/\\s+/).length\n const newWords = newContent.split(/\\s+/).length\n return newWords > existingWords * 1.3\n }\n\n private isContentDuplicate(existing: any, newContent: string): boolean {\n const normalizedExisting = this.normalizeContentForComparison(existing.content)\n const normalizedNew = this.normalizeContentForComparison(newContent)\n\n if (normalizedExisting === normalizedNew) {\n return true\n }\n\n const shorterLength = Math.min(normalizedExisting.length, normalizedNew.length)\n if (shorterLength === 0) {\n return false\n }\n\n return (\n (normalizedExisting.includes(normalizedNew) || normalizedNew.includes(normalizedExisting)) &&\n shorterLength / Math.max(normalizedExisting.length, normalizedNew.length) >= 0.85\n )\n }\n\n private normalizeContentForComparison(content: string): string {\n return normalizeSearchableText(content)\n .toLowerCase()\n .replace(/\\s+/g, ' ')\n .trim()\n }\n\n private getSimilarityScore(result: { score: number; metadata?: Record<string, unknown> }): number {\n const rerankScore = result.metadata?.['rerankScore']\n if (typeof rerankScore === 'number' && Number.isFinite(rerankScore)) {\n return this.clamp01(rerankScore)\n }\n\n const backendId = result.metadata?.['backendId']\n if (backendId === 'minisearch' || result.score > 1) {\n return this.clamp01(result.score / (result.score + 3))\n }\n\n return this.clamp01(result.score)\n }\n\n private mergeSimilarResults(primary: SearchResult[], secondary: SearchResult[]): SearchResult[] {\n const merged = new Map<string, SearchResult>()\n\n for (const result of [...primary, ...secondary]) {\n const existing = merged.get(result.id)\n if (!existing) {\n merged.set(result.id, result)\n continue\n }\n\n const existingScore = this.getSimilarityScore(existing)\n const nextScore = this.getSimilarityScore(result)\n if (nextScore > existingScore) {\n merged.set(result.id, result)\n }\n }\n\n return Array.from(merged.values()).sort(\n (left, right) =>\n this.getSourcePriority(right.source) - this.getSourcePriority(left.source) ||\n this.getSimilarityScore(right) - this.getSimilarityScore(left) ||\n right.score - left.score\n )\n }\n\n private findDirectUserMatches(content: string): SearchResult[] {\n if (!existsSync(this.userDir)) {\n return []\n }\n\n const normalizedQuery = this.normalizeContentForComparison(content)\n const queryTokens = new Set(normalizedQuery.split(/\\s+/).filter(Boolean))\n\n return readdirSync(this.userDir)\n .filter((file) => file.endsWith('.md'))\n .map((file) => {\n const filePath = join(this.userDir, file)\n const rawContent = readFileSync(filePath, 'utf-8')\n const title = rawContent.split('\\n')[0]?.replace(/^#+\\s*/, '').trim() || file.replace(/\\.md$/, '')\n const normalizedExisting = this.normalizeContentForComparison(rawContent)\n const existingTokens = new Set(normalizedExisting.split(/\\s+/).filter(Boolean))\n const overlap = this.calculateTokenOverlap(queryTokens, existingTokens)\n const duplicateScore =\n this.isContentDuplicate({ content: rawContent }, content) ? 1 :\n normalizedExisting.includes(normalizedQuery) || normalizedQuery.includes(normalizedExisting) ? 0.9\n : overlap\n\n return {\n id: `user/${file}`,\n title,\n content: rawContent,\n source: 'user' as const,\n file_path: filePath,\n score: duplicateScore,\n metadata: {\n backendId: 'direct-user-match',\n },\n }\n })\n .filter((result) => result.score >= 0.7)\n }\n\n private findUserFileByTitle(title: string): SearchResult | undefined {\n const expectedPath = this.getExpectedUserFilePath(title)\n if (!existsSync(expectedPath)) {\n return undefined\n }\n\n const content = readFileSync(expectedPath, 'utf-8')\n return {\n id: `user/${expectedPath.split('/').pop() ?? 'existing.md'}`,\n title,\n content,\n source: 'user',\n file_path: expectedPath,\n score: 1,\n metadata: {\n backendId: 'direct-user-match',\n },\n }\n }\n\n private findBestUserMergeTarget(title: string, content: string): SearchResult | undefined {\n if (!existsSync(this.userDir)) {\n return undefined\n }\n\n const normalizedTitle = this.normalizeContentForComparison(title)\n const titleTokens = new Set(normalizedTitle.split(/\\s+/).filter(Boolean))\n const normalizedContent = this.normalizeContentForComparison(content)\n const contentTokens = new Set(normalizedContent.split(/\\s+/).filter(Boolean))\n\n const candidates = readdirSync(this.userDir)\n .filter((file) => file.endsWith('.md'))\n .map((file) => {\n const filePath = join(this.userDir, file)\n const rawContent = readFileSync(filePath, 'utf-8')\n const existingTitle =\n rawContent.split('\\n')[0]?.replace(/^#+\\s*/, '').trim() || file.replace(/\\.md$/, '')\n const normalizedExistingTitle = this.normalizeContentForComparison(existingTitle)\n const normalizedExistingContent = this.normalizeContentForComparison(rawContent)\n\n const titleOverlap = this.calculateTokenOverlap(\n titleTokens,\n new Set(normalizedExistingTitle.split(/\\s+/).filter(Boolean))\n )\n const contentOverlap = this.calculateTokenOverlap(\n contentTokens,\n new Set(normalizedExistingContent.split(/\\s+/).filter(Boolean))\n )\n const duplicateScore =\n this.isContentDuplicate({ content: rawContent }, content) ? 1 :\n normalizedExistingContent.includes(normalizedContent) ||\n normalizedContent.includes(normalizedExistingContent) ?\n 0.9\n : 0\n const exactTitleScore = normalizedExistingTitle === normalizedTitle ? 1 : 0\n const mergeScore = Math.max(\n duplicateScore,\n exactTitleScore,\n titleOverlap * 0.45 + contentOverlap * 0.55\n )\n\n return {\n result: {\n id: `user/${file}`,\n title: existingTitle,\n content: rawContent,\n source: 'user' as const,\n file_path: filePath,\n score: mergeScore,\n metadata: {\n backendId: 'direct-user-match',\n },\n } satisfies SearchResult,\n mergeScore,\n }\n })\n .sort((left, right) => right.mergeScore - left.mergeScore)\n\n return candidates[0] != null && candidates[0].mergeScore >= 0.2 ? candidates[0].result : undefined\n }\n\n private calculateTokenOverlap(left: Set<string>, right: Set<string>): number {\n if (left.size === 0 || right.size === 0) {\n return 0\n }\n\n let intersection = 0\n for (const token of left) {\n if (right.has(token)) {\n intersection += 1\n }\n }\n\n return intersection / Math.max(left.size, right.size)\n }\n\n private getSourcePriority(source: string): number {\n return source === 'user' ? 1 : 0\n }\n\n private clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n if (value < 0) return 0\n if (value > 1) return 1\n return value\n }\n\n private summarizeSimilarContent(\n similar: SearchResult[],\n query: string\n ): NonNullable<AddContentResult['similarContent']> {\n const topResults = similar.slice(0, 3)\n const qualitySummary = analyzeSearchQuality(topResults, query)\n\n return qualitySummary.results.map((qualityResult) => ({\n title: qualityResult.result.title,\n score: Number((qualityResult.displayScore * 100).toFixed(2)),\n source: qualityResult.result.source,\n sourceRank: qualityResult.index === 0 ? 'primary' : 'secondary',\n preview: qualityResult.result.content.slice(0, 200) + '...',\n }))\n }\n\n private resolveSearchResultFilePath(filePath: string): string {\n return isAbsolute(filePath) ? filePath : join(this.options.referencesDir, filePath)\n }\n\n private getExpectedUserFilePath(title: string): string {\n mkdirSync(this.userDir, { recursive: true })\n const safeTitle =\n title\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '')\n .replace(/[-\\s]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 50) || 'content'\n return join(this.userDir, `${safeTitle}.md`)\n }\n\n private renderKnowledgeNote(title: string, content: string): string {\n const body = this.stripMatchingLeadingHeading(content, title)\n return `# ${title}\\n\\n${body}`\n }\n\n private appendKnowledgeUpdate(existingContent: string, title: string, content: string): string {\n const trimmedExisting = existingContent.trimEnd()\n const updateSectionHeading = '## Knowledge updates'\n const nextUpdateIndex = this.getNextKnowledgeUpdateIndex(trimmedExisting)\n const updateBody = this.stripMatchingLeadingHeading(content, title)\n const updateEntry = `### Update ${nextUpdateIndex}: ${title}\\n\\n${updateBody}`\n\n if (trimmedExisting.includes(updateSectionHeading)) {\n return `${trimmedExisting}\\n\\n${updateEntry}\\n`\n }\n\n return `${trimmedExisting}\\n\\n${updateSectionHeading}\\n\\n${updateEntry}\\n`\n }\n\n private getNextKnowledgeUpdateIndex(content: string): number {\n const matches = [...content.matchAll(/^### Update (\\d+): /gm)]\n const maxIndex = matches.reduce((currentMax, match) => {\n const nextValue = Number(match[1])\n return Number.isFinite(nextValue) ? Math.max(currentMax, nextValue) : currentMax\n }, 0)\n\n return maxIndex + 1\n }\n\n private stripMatchingLeadingHeading(content: string, expectedTitle: string): string {\n const trimmed = content.trim()\n if (!trimmed) {\n return ''\n }\n\n const lines = trimmed.split('\\n')\n const firstContentIndex = lines.findIndex((line) => line.trim().length > 0)\n if (firstContentIndex < 0) {\n return trimmed\n }\n\n const firstLine = lines[firstContentIndex]?.trim() ?? ''\n const headingMatch = /^(#{1,6})\\s+(.+)$/.exec(firstLine)\n if (!headingMatch) {\n return trimmed\n }\n\n const headingTitle = this.normalizeContentForComparison(headingMatch[2] ?? '')\n const normalizedExpectedTitle = this.normalizeContentForComparison(expectedTitle)\n if (headingTitle !== normalizedExpectedTitle) {\n return trimmed\n }\n\n const remainingLines = lines.slice(firstContentIndex + 1)\n while (remainingLines[0]?.trim() === '') {\n remainingLines.shift()\n }\n\n return remainingLines.join('\\n').trim() || trimmed\n }\n\n private writeUserContentFile(\n options: {\n title: string\n content: string\n },\n behavior: {\n overwriteExisting?: boolean\n } = {}\n ): { filePath: string; message: string } {\n mkdirSync(this.userDir, { recursive: true })\n const expectedFilePath = this.getExpectedUserFilePath(options.title)\n\n if (behavior.overwriteExisting && existsSync(expectedFilePath)) {\n writeFileSync(expectedFilePath, this.renderKnowledgeNote(options.title, options.content))\n return {\n filePath: expectedFilePath,\n message: `Overwrote existing content: ${expectedFilePath.split('/').pop()}`,\n }\n }\n\n const filePath = this.createUniqueFilePath(options.title, this.userDir)\n writeFileSync(filePath, this.renderKnowledgeNote(options.title, options.content))\n return {\n filePath,\n message: `Created new content: ${filePath.split('/').pop()}`,\n }\n }\n\n private getHashFilePath(projectId: string): string {\n // Sanitize project ID for use in filename (replace slashes with underscores)\n const safeProjectId = this.encodeContext7ProjectId(projectId)\n return join(this.options.referencesDir, '..', `.context7_hash_${safeProjectId}`)\n }\n\n private saveContentHash(content: string, projectId: string): void {\n const hash = createHash('md5').update(content).digest('hex')\n const hashFile = this.getHashFilePath(projectId)\n writeFileSync(hashFile, hash)\n }\n\n private needsUpdate(content: string, projectId: string): boolean {\n const hashFile = this.getHashFilePath(projectId)\n\n if (!existsSync(hashFile)) {\n return true\n }\n\n const currentHash = createHash('md5').update(content).digest('hex')\n const storedHash = readFileSync(hashFile, 'utf-8')\n\n return currentHash !== storedHash\n }\n\n private async prepareSearchEngine(): Promise<void> {\n if (typeof this.options.searchEngine.initialize === 'function') {\n await this.options.searchEngine.initialize()\n }\n if (typeof this.options.searchEngine.buildIndex === 'function') {\n await this.options.searchEngine.buildIndex(this.options.referencesDir)\n }\n }\n\n private async invalidateSearchIndex(): Promise<void> {\n if (typeof this.options.searchEngine.clearIndex === 'function') {\n await this.options.searchEngine.clearIndex()\n }\n\n const searchDir = join(this.options.referencesDir, '..', 'search')\n const searchArtifacts = [\n 'index-state.json',\n 'minisearch-index.json',\n 'vector-index-state.json',\n 'vector-index.db',\n ]\n\n for (const artifact of searchArtifacts) {\n rmSync(join(searchDir, artifact), { force: true })\n }\n }\n\n /**\n * List all context7 projects\n */\n listContext7Projects(): Array<{ projectId: string; filesCount: number; directory: string }> {\n const projects: Array<{ projectId: string; filesCount: number; directory: string }> = []\n\n if (!existsSync(this.context7BaseDir)) {\n return projects\n }\n\n const projectDirs = readdirSync(this.context7BaseDir, { withFileTypes: true })\n .filter((dirent) => dirent.isDirectory())\n .map((dirent) => dirent.name)\n\n for (const encodedProjectId of projectDirs) {\n const projectId = this.decodeContext7ProjectId(encodedProjectId)\n const projectDir = join(this.context7BaseDir, encodedProjectId)\n if (existsSync(projectDir)) {\n const files = readdirSync(projectDir).filter((f) => f.endsWith('.md'))\n projects.push({\n projectId,\n filesCount: files.length,\n directory: projectDir,\n })\n }\n }\n\n return projects\n }\n\n /**\n * Get files for a specific context7 project\n */\n getContext7ProjectFiles(projectId: string): string[] {\n const projectDir = this.getContext7ProjectDir(projectId)\n\n if (!existsSync(projectDir)) {\n return []\n }\n\n return readdirSync(projectDir).filter((f) => f.endsWith('.md'))\n }\n\n /**\n * Remove a context7 project\n */\n removeContext7Project(projectId: string): { success: boolean; message: string } {\n const projectDir = this.getContext7ProjectDir(projectId)\n\n if (!existsSync(projectDir)) {\n return {\n success: false,\n message: `Context7 project ${projectId} does not exist`,\n }\n }\n\n try {\n // Remove project directory\n rmSync(projectDir, { recursive: true, force: true })\n\n // Remove project hash file\n const hashFile = this.getHashFilePath(projectId)\n if (existsSync(hashFile)) {\n rmSync(hashFile)\n }\n\n // Trigger reindex\n void this.invalidateSearchIndex()\n\n return {\n success: true,\n message: `Context7 project ${projectId} removed successfully`,\n }\n } catch (error) {\n return {\n success: false,\n message: `Failed to remove Context7 project ${projectId}: ${error}`,\n }\n }\n }\n}\n"],"mappings":"kUAoCA,IAAa,EAAb,KAA4B,CAC1B,QACA,QACA,gBAEA,YAAY,EAAgC,CAC1C,KAAK,QAAU,EACf,KAAK,QAAU,EAAK,EAAQ,cAAe,OAAO,CAClD,KAAK,gBAAkB,EAAK,EAAQ,cAAe,WAAW,CAMhE,sBAA8B,EAA2B,CACvD,OAAO,EAAK,KAAK,gBAAiB,KAAK,wBAAwB,EAAU,CAAC,CAG5E,wBAAgC,EAA2B,CACzD,OAAO,mBAAmB,EAAU,CAGtC,wBAAgC,EAAkC,CAChE,OAAO,mBAAmB,EAAiB,CAG7C,MAAM,mBACJ,EACA,EAAiB,GACc,CAC/B,IAAMA,EAA+B,CACnC,QAAS,GACT,QAAS,GACT,aAAc,EACd,QAAS,GACV,CAED,GAAI,CAEF,IAAM,EAAU,MAAM,KAAK,oBAAoB,EAAU,CAGnD,EAAa,KAAK,sBAAsB,EAAU,CAGxD,GAAI,CAAC,GAAS,CAAC,KAAK,YAAY,EAAS,EAAU,CAGjD,MAFA,GAAO,QAAU,GACjB,EAAO,QAAU,uCACV,EAIT,GAAI,EAAW,EAAW,CAAE,CAC1B,IAAM,EAAQ,EAAY,EAAW,CACrC,IAAK,IAAM,KAAQ,EACb,EAAK,SAAS,MAAM,EACtB,EAAO,EAAK,EAAY,EAAK,CAAC,CAMpC,EAAU,EAAY,CAAE,UAAW,GAAM,CAAC,CAG1C,IAAM,EAAa,MAAM,KAAK,cAAc,EAAS,EAAW,CAChE,EAAO,aAAe,EAAW,OAGjC,KAAK,gBAAgB,EAAS,EAAU,CAGxC,MAAM,KAAK,uBAAuB,CAElC,EAAO,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
import"./referenceSearchUtils-DZgupMZp.mjs";import"./searchQuality-DVdHmamh.mjs";import{t as e}from"./contentManager-CoVTiSDT.mjs";export{e as ContentManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./package-CFJazwTO.mjs";import{t as e}from"./context7-BxMpyQiW.mjs";export{e as Context7Utils};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./package-CFJazwTO.mjs";import{z as t}from"zod";const n=t.object({id:t.string(),title:t.string(),description:t.string().optional().default(``),branch:t.string().optional(),lastUpdateDate:t.string().optional(),state:t.string().optional(),totalTokens:t.number().optional().default(0),totalSnippets:t.number().optional().default(0),stars:t.number().optional().default(0),trustScore:t.number().optional().default(0),benchmarkScore:t.number().optional().default(0),versions:t.array(t.string()).optional().default([])}),r=t.object({results:t.array(n),searchFilterApplied:t.boolean().optional().default(!1)});var i=class{static async resolveLibrary(t,n={}){let r=n.version??await e.getPackageVersion(t)??void 0,i=this.createSearchQuery(t,r),a=(await this.searchLibraries(t,i,n)).results.map(e=>this.annotateCandidate(e,t,r)).sort((e,t)=>t.selectionScore-e.selectionScore).slice(0,n.limit??10),o=a[0];return!o||!this.acceptBestMatch(o).accepted?null:{packageName:t,version:r,query:i,bestMatch:o,candidates:a}}static createSearchQuery(t,n){let r=this.getPackageBaseName(t),i=n?e.formatVersion(n):``;return i?`${r} v${i}`:r}static async searchLibraries(e,t,n){let i=n.fetchImpl??fetch,a=this.getLibrarySearchNames(e),o=new Map;for(let e of a){let n=new URL(process.env.SKILL_CREATOR_CONTEXT7_SEARCH_BASE_URL??`https://context7.com/api/v2/libs/search`);n.searchParams.set(`libraryName`,e),n.searchParams.set(`query`,t);let a=await i(n.toString());if(!a.ok)throw Error(`Failed to search Context7 libraries: ${a.status} ${a.statusText}`);let s=r.parse(await a.json());for(let e of s.results){let t=o.get(e.id);(!t||this.getCandidateMergeScore(e)>this.getCandidateMergeScore(t))&&o.set(e.id,e)}}return{results:Array.from(o.values()),searchFilterApplied:!1}}static getLibrarySearchNames(e){let t=e,n=this.getPackageBaseName(e);return Array.from(new Set([t,n]))}static getPackageBaseName(e){return e.replace(/^@/,``).split(`/`).pop()??e}static tokenizeIdentifier(e){return e.toLowerCase().replace(/^@/,``).split(/[^a-z0-9]+/g).filter(Boolean)}static acceptBestMatch(e){return e?e.matchKind===`package-path`||e.matchKind===`package-slug`?{accepted:!0}:e.matchKind===`website`?{accepted:!1,reason:`website-without-package-match`}:{accepted:!1,reason:`unrelated-match`}:{accepted:!1,reason:`empty`}}static annotateCandidate(e,t,n){let r=this.classifyCandidate(e.id,t),i=this.matchesVersion(e.versions,n),a=(r===`package-path`?4:r===`package-slug`?3:r===`website`?2:1)*1e9+(i?1e8:0)+e.totalSnippets*1e3+Math.round(e.trustScore*100)*10+Math.round(e.benchmarkScore);return{...e,matchKind:r,versionMatched:i,selectionScore:a}}static classifyCandidate(e,t){let n=e.replace(/^\/+/,``).toLowerCase().split(`/`).filter(Boolean),r=t.replace(/^@/,``).toLowerCase().split(`/`).filter(Boolean);if(n[0]===`websites`)return`website`;let i=r.flatMap(e=>this.tokenizeIdentifier(e)),a=n.flatMap(e=>this.tokenizeIdentifier(e));if(n.slice(-r.length).join(`/`)===r.join(`/`)||a.slice(-i.length).join(`/`)===i.join(`/`))return`package-path`;let o=r[r.length-1],s=n[n.length-1]??``;if(s===o)return`package-slug`;let c=this.tokenizeIdentifier(o);return this.tokenizeIdentifier(s).join(`/`)===c.join(`/`)?`package-slug`:`other`}static matchesVersion(t,n){if(!n)return!1;let r=e.formatVersion(n);return t.some(e=>{let t=e.toLowerCase().replace(/^v/,``).replace(/_/g,`.`);return t===r||t.startsWith(`${r}.`)})}static getCandidateMergeScore(e){return e.totalSnippets*1e3+Math.round(e.trustScore*100)*10+Math.round(e.benchmarkScore)}};export{i as t};
|
|
2
|
-
//# sourceMappingURL=context7-BxMpyQiW.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context7-BxMpyQiW.mjs","names":[],"sources":["../src/utils/context7.ts"],"sourcesContent":["import { z } from 'zod'\nimport { PackageUtils } from './package.js'\n\nconst Context7SearchCandidateSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string().optional().default(''),\n branch: z.string().optional(),\n lastUpdateDate: z.string().optional(),\n state: z.string().optional(),\n totalTokens: z.number().optional().default(0),\n totalSnippets: z.number().optional().default(0),\n stars: z.number().optional().default(0),\n trustScore: z.number().optional().default(0),\n benchmarkScore: z.number().optional().default(0),\n versions: z.array(z.string()).optional().default([]),\n})\n\nconst Context7SearchResponseSchema = z.object({\n results: z.array(Context7SearchCandidateSchema),\n searchFilterApplied: z.boolean().optional().default(false),\n})\n\nexport type Context7SearchCandidate = z.infer<typeof Context7SearchCandidateSchema>\n\nexport interface ResolvedContext7Candidate extends Context7SearchCandidate {\n matchKind: 'package-path' | 'package-slug' | 'website' | 'other'\n versionMatched: boolean\n selectionScore: number\n}\n\nexport interface ResolveContext7Result {\n packageName: string\n version?: string\n query: string\n bestMatch: ResolvedContext7Candidate\n candidates: ResolvedContext7Candidate[]\n}\n\nexport interface ResolveContext7Options {\n version?: string\n limit?: number\n fetchImpl?: typeof fetch\n}\n\ninterface Context7CandidateAcceptance {\n accepted: boolean\n reason?:\n | 'empty'\n | 'unrelated-match'\n | 'website-without-package-match'\n}\n\nexport class Context7Utils {\n static async resolveLibrary(\n packageName: string,\n options: ResolveContext7Options = {}\n ): Promise<ResolveContext7Result | null> {\n const version = options.version ?? (await PackageUtils.getPackageVersion(packageName)) ?? undefined\n const query = this.createSearchQuery(packageName, version)\n const response = await this.searchLibraries(packageName, query, options)\n const candidates = response.results\n .map((candidate) => this.annotateCandidate(candidate, packageName, version))\n .sort((left, right) => right.selectionScore - left.selectionScore)\n .slice(0, options.limit ?? 10)\n\n const bestMatch = candidates[0]\n if (!bestMatch) return null\n const acceptance = this.acceptBestMatch(bestMatch)\n if (!acceptance.accepted) {\n return null\n }\n\n return {\n packageName,\n version,\n query,\n bestMatch,\n candidates,\n }\n }\n\n static createSearchQuery(packageName: string, version?: string): string {\n const baseName = this.getPackageBaseName(packageName)\n const formattedVersion = version ? PackageUtils.formatVersion(version) : ''\n return formattedVersion ? `${baseName} v${formattedVersion}` : baseName\n }\n\n private static async searchLibraries(\n packageName: string,\n query: string,\n options: ResolveContext7Options\n ): Promise<z.infer<typeof Context7SearchResponseSchema>> {\n const fetchImpl = options.fetchImpl ?? fetch\n const attempts = this.getLibrarySearchNames(packageName)\n const mergedResults = new Map<string, Context7SearchCandidate>()\n\n for (const libraryName of attempts) {\n const url = new URL(\n process.env.SKILL_CREATOR_CONTEXT7_SEARCH_BASE_URL ?? 'https://context7.com/api/v2/libs/search'\n )\n url.searchParams.set('libraryName', libraryName)\n url.searchParams.set('query', query)\n\n const response = await fetchImpl(url.toString())\n if (!response.ok) {\n throw new Error(`Failed to search Context7 libraries: ${response.status} ${response.statusText}`)\n }\n\n const payload = Context7SearchResponseSchema.parse(await response.json())\n for (const candidate of payload.results) {\n const existing = mergedResults.get(candidate.id)\n if (!existing || this.getCandidateMergeScore(candidate) > this.getCandidateMergeScore(existing)) {\n mergedResults.set(candidate.id, candidate)\n }\n }\n }\n\n return {\n results: Array.from(mergedResults.values()),\n searchFilterApplied: false,\n }\n }\n\n private static getLibrarySearchNames(packageName: string): string[] {\n const exact = packageName\n const baseName = this.getPackageBaseName(packageName)\n return Array.from(new Set([exact, baseName]))\n }\n\n private static getPackageBaseName(packageName: string): string {\n return packageName.replace(/^@/, '').split('/').pop() ?? packageName\n }\n\n private static tokenizeIdentifier(value: string): string[] {\n return value\n .toLowerCase()\n .replace(/^@/, '')\n .split(/[^a-z0-9]+/g)\n .filter(Boolean)\n }\n\n private static acceptBestMatch(\n candidate: ResolvedContext7Candidate\n ): Context7CandidateAcceptance {\n if (!candidate) {\n return { accepted: false, reason: 'empty' }\n }\n\n if (candidate.matchKind === 'package-path' || candidate.matchKind === 'package-slug') {\n return { accepted: true }\n }\n\n if (candidate.matchKind === 'website') {\n return {\n accepted: false,\n reason: 'website-without-package-match',\n }\n }\n\n return {\n accepted: false,\n reason: 'unrelated-match',\n }\n }\n\n private static annotateCandidate(\n candidate: Context7SearchCandidate,\n packageName: string,\n version?: string\n ): ResolvedContext7Candidate {\n const matchKind = this.classifyCandidate(candidate.id, packageName)\n const versionMatched = this.matchesVersion(candidate.versions, version)\n const matchWeight =\n matchKind === 'package-path' ? 4 :\n matchKind === 'package-slug' ? 3 :\n matchKind === 'website' ? 2 :\n 1\n const selectionScore =\n matchWeight * 1_000_000_000 +\n (versionMatched ? 100_000_000 : 0) +\n candidate.totalSnippets * 1_000 +\n Math.round(candidate.trustScore * 100) * 10 +\n Math.round(candidate.benchmarkScore)\n\n return {\n ...candidate,\n matchKind,\n versionMatched,\n selectionScore,\n }\n }\n\n private static classifyCandidate(\n candidateId: string,\n packageName: string\n ): ResolvedContext7Candidate['matchKind'] {\n const candidateSegments = candidateId\n .replace(/^\\/+/, '')\n .toLowerCase()\n .split('/')\n .filter(Boolean)\n const packageSegments = packageName\n .replace(/^@/, '')\n .toLowerCase()\n .split('/')\n .filter(Boolean)\n\n if (candidateSegments[0] === 'websites') {\n return 'website'\n }\n\n const packageTokens = packageSegments.flatMap((segment) => this.tokenizeIdentifier(segment))\n const candidateTokens = candidateSegments.flatMap((segment) => this.tokenizeIdentifier(segment))\n const candidateTail = candidateSegments.slice(-packageSegments.length)\n if (candidateTail.join('/') === packageSegments.join('/')) {\n return 'package-path'\n }\n\n const candidateTokenTail = candidateTokens.slice(-packageTokens.length)\n if (candidateTokenTail.join('/') === packageTokens.join('/')) {\n return 'package-path'\n }\n\n const packageBaseName = packageSegments[packageSegments.length - 1]\n const candidateLastSegment = candidateSegments[candidateSegments.length - 1] ?? ''\n if (candidateLastSegment === packageBaseName) {\n return 'package-slug'\n }\n\n const packageBaseTokens = this.tokenizeIdentifier(packageBaseName)\n const candidateLastTokens = this.tokenizeIdentifier(candidateLastSegment)\n if (candidateLastTokens.join('/') === packageBaseTokens.join('/')) {\n return 'package-slug'\n }\n\n return 'other'\n }\n\n private static matchesVersion(versions: string[], version?: string): boolean {\n if (!version) return false\n const formattedVersion = PackageUtils.formatVersion(version)\n return versions.some((candidateVersion) => {\n const normalizedVersion = candidateVersion.toLowerCase().replace(/^v/, '').replace(/_/g, '.')\n return (\n normalizedVersion === formattedVersion ||\n normalizedVersion.startsWith(`${formattedVersion}.`)\n )\n })\n }\n\n private static getCandidateMergeScore(candidate: Context7SearchCandidate): number {\n return (\n candidate.totalSnippets * 1_000 +\n Math.round(candidate.trustScore * 100) * 10 +\n Math.round(candidate.benchmarkScore)\n )\n }\n}\n"],"mappings":"mEAGA,MAAM,EAAgC,EAAE,OAAO,CAC7C,GAAI,EAAE,QAAQ,CACd,MAAO,EAAE,QAAQ,CACjB,YAAa,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,GAAG,CAC9C,OAAQ,EAAE,QAAQ,CAAC,UAAU,CAC7B,eAAgB,EAAE,QAAQ,CAAC,UAAU,CACrC,MAAO,EAAE,QAAQ,CAAC,UAAU,CAC5B,YAAa,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,EAAE,CAC7C,cAAe,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,EAAE,CAC/C,MAAO,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,EAAE,CACvC,WAAY,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,EAAE,CAC5C,eAAgB,EAAE,QAAQ,CAAC,UAAU,CAAC,QAAQ,EAAE,CAChD,SAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CACrD,CAAC,CAEI,EAA+B,EAAE,OAAO,CAC5C,QAAS,EAAE,MAAM,EAA8B,CAC/C,oBAAqB,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,GAAM,CAC3D,CAAC,CAgCF,IAAa,EAAb,KAA2B,CACzB,aAAa,eACX,EACA,EAAkC,EAAE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