@longzai-intelligence-port/cli 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -153,6 +153,6 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
153
153
  - ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function l(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=r.resolve(r.dirname(e),d)}if(d){let t=l(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=l(d,`${n}-${e._name}`))}u=t||u}o=s.includes(r.extname(u));let f;a.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.argv[0],t,{stdio:`inherit`})):f=n.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)a.exit(1);else{let e=new c(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l)))this.emit(`option:${o.name()}`,l);else{if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
154
154
  `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=p(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=p(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>s(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=r.basename(e,r.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(a.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
155
155
  Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:wu,createCommand:Tu,createArgument:Eu,createOption:Du,CommanderError:Ou,InvalidArgumentError:ku,InvalidOptionArgumentError:Au,Command:ju,Argument:Mu,Option:Nu,Help:Pu}=(/* @__PURE__ */ E((/* @__PURE__ */ w((e=>{let{Argument:t}=yu(),{Command:n}=Cu(),{CommanderError:r,InvalidArgumentError:i}=vu(),{Help:a}=bu(),{Option:o}=xu();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i})))(),1)).default,Fu=_u(`@longzai-intelligence-cli/core/provider`),Iu={red:e=>e,green:e=>e,yellow:e=>e,blue:e=>e,cyan:e=>e,magenta:e=>e,gray:e=>e,bold:e=>e,dim:e=>e};let Lu={select:async(e,t)=>t[0]?.value??``,textInput:async(e,t)=>t?.defaultValue??``,confirm:async(e,t)=>t?.defaultValue??!1,spinner:()=>({start:e=>Fu.info(e),stop:e=>Fu.info(e)}),note:(e,t)=>{t?Fu.info(`${t}: ${e}`):Fu.info(e)},log:{info:e=>Fu.info(e),success:e=>Fu.info(e),warn:e=>Fu.warn(e),error:e=>Fu.error(e),step:e=>Fu.info(e)}},Ru=Iu;function zu(e){Lu=e}function Bu(e){Ru=e}function Vu(){return Lu}function Hu(){return Ru}const Uu=()=>`0.0.10`;function Wu(e){let t=e.version??Uu();e.interaction&&zu(e.interaction),e.color&&Bu(e.color);let n=new ju;return n.name(e.name).version(t,`-v, --version`,`输出 ${e.name} 的版本号`),e.description&&n.description(e.description),n}_u(`@longzai-intelligence-cli/core/output`),_u(`@longzai-intelligence-cli/core/progress`);const Gu=_u(`@longzai-intelligence-cli/core/define-command`);function Ku(e,t){let n=e.commands.find(e=>e.name()===t);return n===void 0?e.command(t):n}function qu(e,t){if(t.length===1){let n=t[0];if(n===void 0)throw Error(`defineCommand: segments 为空,无法解析命令名`);return e.command(n)}let[n,...r]=t;if(n===void 0)throw Error(`defineCommand: segments 首段为空,无法解析父命令名`);let i=r.pop();if(i===void 0)throw Error(`defineCommand: segments 末段为空,无法解析子命令名`);let a=Ku(e,n);for(let e of r)a=Ku(a,e);return a.command(i)}function Ju(e,t){let n=qu(e,t.name.split(` `).filter(e=>e.length>0));t.description&&n.description(t.description);for(let e of t.arguments??[])e.description?n.argument(e.signature,e.description):n.argument(e.signature);for(let e of t.options??[])e.defaultValue===void 0?n.option(e.flags,e.description??``):n.option(e.flags,e.description??``,e.defaultValue);n.action(async(...e)=>{let n=e[e.length-1];if(!(n instanceof ju))return;let r=n.opts(),i=n.args,a=t.schema.safeParse(r);if(!a.success){let e=a.error.issues.map(e=>e.message).join(`, `);Gu.error(Hu().red(`参数校验失败: ${e}`)),Vu().log.error(`参数校验失败: ${e}`),process.exit(1)}await t.action(a.data,i)})}var Yu=class extends Error{constructor(){super(`注册表目录五档锚定链全部落空,DEV_PORTS_DIR 与 registryDir 与 LZI_GLOBALS_ROOT 与 globals 结构锚与机器级位均未命中,正本见 architecture 仓 ADR 0172`),this.name=`PortRegistryDirUnresolvedError`}};const Xu=c(`.lzi`,`dev-tools`,`ports`),Zu=e=>{try{return process.kill(e,0),!0}catch{return!1}},Qu=e=>{let t=c(e,`package.json`);if(!n(t))return!1;try{let e=JSON.parse(r(t,`utf-8`));return e.workspaces!==void 0&&e.workspaces!==null}catch{return!1}},$u=(e=process.cwd())=>{let t=e;for(;;){if(Qu(t))return t;let e=s(t);if(e===t)break;t=e}return e},ed=(e=process.cwd())=>{let t=e;for(;;){if(n(c(t,`longzai-intelligence-globals`)))return t;let e=s(t);if(e===t)break;t=e}return null},td=(e=t())=>{let r=c(e,`.lzi`);return n(r)?c(r,`dev-tools`,`ports`):null},nd=e=>{let t=process.env.DEV_PORTS_DIR;if(t)return t;if(e?.registryDir)return e.registryDir;let r=process.env.LZI_GLOBALS_ROOT;if(r&&n(r))return c(s(r),Xu);let i=ed();if(i)return c(i,Xu);let a=td();if(a)return a;throw new Yu},rd=async e=>{n(e)||await f(e,{recursive:!0})},id=(e,t)=>c(e,`${t}.json`),ad=async(e,t)=>{let n=`${e}.tmp`,r=JSON.stringify(t,null,2);await _(n,r,`utf-8`),await h(n,e)},od=e=>{let t=nd(e),r=/* @__PURE__ */ new Map,o=!1,s=/* @__PURE__ */ new Set,l=()=>{if(o)return;o=!0;let e=()=>{for(let e of s){let r=id(t,e);try{n(r)&&i(r)}catch{}}};process.on(`exit`,e),process.on(`SIGINT`,()=>{e(),process.exit(130)}),process.on(`SIGTERM`,()=>{e(),process.exit(143)})},u=(e,t)=>{let n=r.get(e);if(n)for(let e of n)e(t)},d=async e=>{let r=id(t,e);if(!n(r))return null;try{let t=await p(r,`utf-8`),n=JSON.parse(t);return Zu(n.pid)?n:(await g(r),u(e,null),null)}catch{return null}};return{register:async(e,n)=>{await rd(t);let r={name:e,...n},i=id(t,e);await ad(i,r),s.add(e),l(),u(e,r)},resolve:d,deregister:async e=>{let r=id(t,e);try{n(r)&&await g(r)}catch{}s.delete(e),u(e,null)},watch:(e,i)=>{let o=r.get(e);o||(o=[],r.set(e,o)),o.push(i);let s=null;return(()=>{try{rd(t),s=a(t,(r,a)=>{if(a===`${e}.json`){let r=id(t,e);n(r)?p(r,`utf-8`).then(e=>{try{let t=JSON.parse(e);Zu(t.pid)?i(t):i(null)}catch{i(null)}}).catch(()=>i(null)):i(null)}})}catch{}})(),()=>{let t=r.get(e);if(t){let n=t.indexOf(i);n!==-1&&t.splice(n,1),t.length===0&&r.delete(e)}s&&=(s.close(),null)}},list:async()=>{if(!n(t))return[];try{let e=(await m(t)).filter(e=>e.endsWith(`.json`)),n=[];for(let r of e){let e=c(t,r);try{let t=await p(e,`utf-8`),r=JSON.parse(t);Zu(r.pid)?n.push(r):await g(e).catch(()=>{})}catch{}}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}catch{return[]}},resolveUrl:async(e,t)=>{let n=await d(e);if(!n)return null;let r=`http://${n.host===`0.0.0.0`?`localhost`:n.host}:${n.port}`;return t?`${r}${t}`:r}}},sd={RED:`\x1B[0;31m`,GREEN:`\x1B[0;32m`,YELLOW:`\x1B[1;33m`,BLUE:`\x1B[0;34m`,RESET:`\x1B[0m`};function cd(e){return e.map(e=>{if(typeof e==`string`)return e;if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `)}function $(...e){process.stdout.write(`${cd(e)}\n`)}function ld(...e){process.stderr.write(`${cd(e)}\n`)}const ud=[`get-port`,`get-port-plus`,`portfinder`,`detect-port`,`find-free-port`,`tcp-port-used`],dd=[`findAvailablePort`,`findFreePort`,`getFreePort`,`getAvailablePort`,`isPortAvailable`,`isPortFree`,`checkPort`,`checkPortAvailable`,`detectPort`,`ensurePort`,`portCounter`],fd=RegExp(`(?:from\\s+|require\\(\\s*['"])(?:${ud.join(`|`)})['"]`),pd=/import\s*\{[^}]*\b(getPort|getFreePort|detectPort)\b[^}]*\}\s*from\s+['"]licia['"]/,md=dd.map(e=>[e,RegExp(`\\b${e}\\s*[:(=]`)]),hd=/\.listen\(\s*(\d{3,5})\b/,gd=/^.*\bPORT\b.*(?:\?\?|\|\|)\s*['"]?(\d{3,5})\b.*$/,_d=/\.code\s*===?\s*['"]EADDRINUSE['"]|['"]EADDRINUSE['"]\s*===?/,vd=/\b(?:localhost|127\.0\.0\.1):(\d{3,5})\b/g,yd=/* @__PURE__ */ new Set([`local-server.ts`,`local-server.service.ts`,`local-server.utils.ts`]),bd=`@longzai-intelligence-electron/local-server`,xd=/* @__PURE__ */ new Set([`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`]),Sd=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.turbo`,`.git`,`.lzi`,`coverage`,`.cache`,`tsconfig`]),Cd=[`-data`,`-markdown`],wd=/* @__PURE__ */ new Set([`longzai-intelligence-older`]),Td=[`__tests__/`,`.test.`,`.spec.`,`__mocks__/`];function Ed(e){let t=e.replace(/\\/g,`/`);return Td.some(e=>t.includes(e))}function Dd(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}async function Od(e){let t=null;try{t=await Bun.file(c(e,`package.json`)).json()}catch{t=null}let n=t?.workspaces,r=Dd(n);if(r.length===0&&typeof n==`object`&&n&&`packages`in n){let e=n.packages;r=Dd(e)}let i=(await m(e,{withFileTypes:!0})).filter(e=>e.isDirectory());if(r.length>0){let t=new Set(r.map(e=>e.replace(/\/.*$/,``).replace(/\*.*$/,``)));return i.filter(e=>t.has(e.name)).map(t=>c(e,t.name))}let a=[];for(let t of i)if(t.name.startsWith(`longzai-intelligence-`)&&!Cd.some(e=>t.name.endsWith(e))&&!wd.has(t.name))try{await Bun.file(c(e,t.name,`package.json`)).json(),a.push(c(e,t.name))}catch{}return a}async function kd(e,t){let n=[],r;try{r=await m(e,{withFileTypes:!0})}catch{return n}for(let i of r){let r=c(e,i.name);if(i.isDirectory()){if(Sd.has(i.name)||i.name.startsWith(`.`))continue;n.push(...await kd(r,t));continue}if(!i.isFile())continue;let a=i.name.slice(i.name.lastIndexOf(`.`));xd.has(a)&&(i.name.endsWith(`.d.ts`)||Ed(l(t,r))||n.push({absolutePath:r,relativePath:l(t,r)}))}return n}function Ad(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n+1}function jd(e,t,n){let r=[],i=o(t),a=i.startsWith(`vite.config.`),s=(n,i,a)=>{r.push({level:`error`,kind:n,repo:e,file:t,line:a,detail:i})},c=(n,i,a)=>{r.push({level:`inventory`,kind:n,repo:e,file:t,line:a,detail:i})},l=fd.exec(n);l&&s(`探测库导入`,`引入端口探测库`,Ad(n,l.index));let u=pd.exec(n);u&&s(`探测库导入`,`自 licia 引入端口探测函数 ${u[1]}`,Ad(n,u.index));for(let[e,t]of md){let r=t.exec(n);r&&s(`探测标识符`,`声明或调用探测语义标识符 ${e}`,Ad(n,r.index))}let d=_d.exec(n);if(d&&s(`占用重试`,`出现 EADDRINUSE 错误码比较处理痕迹`,Ad(n,d.index)),a&&!n.includes(`portDiscovery`)){let e=n.search(/strictPort\s*:\s*false/);if(e>=0&&s(`vite 自动加一`,`显式置 strictPort 为 false 依赖占用自动加一`,Ad(n,e)),!/strictPort\s*:\s*true/.test(n)){let e=/(?:^|[^.\w])port\s*:\s*([1-9]\d{2,4})\b/m.exec(n);e&&s(`vite 自动加一`,`写死端口 ${e[1]} 且未开快速失败,占用时将静默改用相邻端口`,Ad(n,e.index))}}let f=hd.exec(n);f&&c(`固定监听端口`,`监听固定端口 ${f[1]}`,Ad(n,f.index)),yd.has(i)&&t.includes(`src/main`)&&!n.includes(bd)&&s(`本地服务拷贝`,`主进程本地服务实现未引用共享包`,1);let p=0;for(let e of n.split(`
156
- `)){let t=gd.exec(e);t&&c(`环境变量默认端口`,`环境变量回落固定端口 ${t[1]}`,Ad(n,p)),p+=e.length+1}vd.lastIndex=0;let m=vd.exec(n);for(;m;)c(`客户端硬编码`,`硬编码本机地址端口 ${m[1]}`,Ad(n,m.index)),m=vd.exec(n);return r}function Md(e){for(let t of e.findings)t.level===`error`&&ld(`${sd.RED}[端口避让]${sd.RESET} ${t.repo}:${t.file}:第 ${t.line} 行 ${t.detail}`);let t=/* @__PURE__ */ new Map;for(let n of e.findings){if(n.level!==`inventory`)continue;let e=/(\d{3,5})/.exec(n.detail)?.[1];if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}$(`固定端口分布:共 ${t.size} 个端口`);for(let[e,n]of t){let t=[...new Set(n.map(e=>e.repo))];$(`端口 ${e}:${n.length} 处,分布于 ${t.length} 仓`);for(let e of n)$(` ${e.repo}:${e.file}:第 ${e.line} 行 ${e.kind}`)}$(`审计完成:error 级 ${e.errorCount} 项,盘点级 ${e.inventoryCount} 项,覆盖 ${e.memberCount} 仓`)}const Nd=async e=>{let t=u(e?.root??$u()),n=await Od(t),r=[];for(let e of n){let t=o(e),n=await kd(e,e);for(let e of n)try{let n=Bun.file(e.absolutePath);if(n.size>1048576)continue;let i=await n.text();r.push(...jd(t,e.relativePath,i))}catch{}}let i=await new Bun.Glob(`longzai-intelligence-*/apps/desktop/src/main/**/local-server*.ts`).scan({cwd:t,onlyFiles:!0});for(let e of i){if(e.includes(`node_modules`)||e.includes(`/dist/`))continue;let n=o(e);if(yd.has(n))try{(await Bun.file(c(t,e)).text()).includes(bd)||r.push({level:`error`,kind:`本地服务拷贝`,repo:e.split(`/`)[0]??e,file:e,line:1,detail:`主进程本地服务实现未引用共享包`})}catch{}}let a=r.filter(e=>e.level===`error`).length,s=r.length-a,l={generatedAt:(/* @__PURE__ */ new Date()).toISOString(),root:t,memberCount:n.length,errorCount:a,inventoryCount:s,findings:r};return e?.jsonPath&&(await _(e.jsonPath,`${JSON.stringify(l,null,2)}\n`,`utf-8`),$(`审计快照已写入:${e.jsonPath}`)),Md(l),l},Pd=new Bun.Glob(`*.json`),Fd=e=>{try{return process.kill(e,0),!0}catch{return!1}},Id=async e=>{let t=nd(e?.registry);if(!n(t)){$(`没有需要清理的僵尸注册文件`);return}let r=0;for await(let n of Pd.scan({cwd:t})){let i=`${t}/${n}`;try{let t=await Bun.file(i).json();Fd(t.pid)||(e?.dryRun?$(`[dry-run] 将删除: ${i}`):await Bun.file(i).unlink(),r++)}catch{}}$(r>0?`${e?.dryRun?`[dry-run] 将清理`:`已清理`} ${r} 个僵尸注册文件`:`没有需要清理的僵尸注册文件`)},Ld=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)} ${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`},Rd=e=>{if(!e)return`-`;let t=[];return e.health!==void 0&&t.push(`health`),e.mcp!==void 0&&t.push(`mcp`),t.length===0?`-`:t.join(`,`)},zd=e=>{let t=[`服务名称`,`生产者`,`端口`,`能力`,`PID`,`启动时间`],n=t.map(e=>e.length),r=e.map(e=>[e.name,e.producer??`-`,String(e.port),Rd(e.capabilities),String(e.pid),Ld(e.startedAt)]);for(let e of r)for(let t=0;t<e.length;t++)n[t]=Math.max(n[t]??0,e[t]?.length??0);let i=(e,t)=>e.padEnd(t);return[t.map((e,t)=>i(e,n[t]??0)).join(` `),...r.map(e=>e.map((e,t)=>i(e,n[t]??0)).join(` `))].join(`
156
+ `)){let t=gd.exec(e);t&&c(`环境变量默认端口`,`环境变量回落固定端口 ${t[1]}`,Ad(n,p)),p+=e.length+1}vd.lastIndex=0;let m=vd.exec(n);for(;m;)c(`客户端硬编码`,`硬编码本机地址端口 ${m[1]}`,Ad(n,m.index)),m=vd.exec(n);return r}function Md(e){for(let t of e.findings)t.level===`error`&&ld(`${sd.RED}[端口避让]${sd.RESET} ${t.repo}:${t.file}:第 ${t.line} 行 ${t.detail}`);let t=/* @__PURE__ */ new Map;for(let n of e.findings){if(n.level!==`inventory`)continue;let e=/(\d{3,5})/.exec(n.detail)?.[1];if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}$(`固定端口分布:共 ${t.size} 个端口`);for(let[e,n]of t){let t=[...new Set(n.map(e=>e.repo))];$(`端口 ${e}:${n.length} 处,分布于 ${t.length} 仓`);for(let e of n)$(` ${e.repo}:${e.file}:第 ${e.line} 行 ${e.kind}`)}$(`审计完成:error 级 ${e.errorCount} 项,盘点级 ${e.inventoryCount} 项,覆盖 ${e.memberCount} 仓`)}const Nd=async e=>{let t=u(e?.root??$u()),n=await Od(t),r=[];for(let e of n){let t=o(e),n=await kd(e,e);for(let e of n)try{let n=Bun.file(e.absolutePath);if(n.size>1048576)continue;let i=await n.text();r.push(...jd(t,e.relativePath,i))}catch{}}let i=new Set(n.map(e=>o(e))),a=new Bun.Glob(`longzai-intelligence-*/apps/desktop/src/main/**/local-server*.ts`);for await(let e of a.scan({cwd:t,onlyFiles:!0})){if(i.has(e.split(`/`)[0]??``)||e.includes(`node_modules`)||e.includes(`/dist/`))continue;let n=o(e);if(yd.has(n))try{(await Bun.file(c(t,e)).text()).includes(bd)||r.push({level:`error`,kind:`本地服务拷贝`,repo:e.split(`/`)[0]??e,file:e,line:1,detail:`主进程本地服务实现未引用共享包`})}catch{}}let s=r.filter(e=>e.level===`error`).length,l=r.length-s,d={generatedAt:(/* @__PURE__ */ new Date()).toISOString(),root:t,memberCount:n.length,errorCount:s,inventoryCount:l,findings:r};return e?.jsonPath&&(await _(e.jsonPath,`${JSON.stringify(d,null,2)}\n`,`utf-8`),$(`审计快照已写入:${e.jsonPath}`)),Md(d),d},Pd=new Bun.Glob(`*.json`),Fd=e=>{try{return process.kill(e,0),!0}catch{return!1}},Id=async e=>{let t=nd(e?.registry);if(!n(t)){$(`没有需要清理的僵尸注册文件`);return}let r=0;for await(let n of Pd.scan({cwd:t})){let i=`${t}/${n}`;try{let t=await Bun.file(i).json();Fd(t.pid)||(e?.dryRun?$(`[dry-run] 将删除: ${i}`):await Bun.file(i).unlink(),r++)}catch{}}$(r>0?`${e?.dryRun?`[dry-run] 将清理`:`已清理`} ${r} 个僵尸注册文件`:`没有需要清理的僵尸注册文件`)},Ld=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)} ${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`},Rd=e=>{if(!e)return`-`;let t=[];return e.health!==void 0&&t.push(`health`),e.mcp!==void 0&&t.push(`mcp`),t.length===0?`-`:t.join(`,`)},zd=e=>{let t=[`服务名称`,`生产者`,`端口`,`能力`,`PID`,`启动时间`],n=t.map(e=>e.length),r=e.map(e=>[e.name,e.producer??`-`,String(e.port),Rd(e.capabilities),String(e.pid),Ld(e.startedAt)]);for(let e of r)for(let t=0;t<e.length;t++)n[t]=Math.max(n[t]??0,e[t]?.length??0);let i=(e,t)=>e.padEnd(t);return[t.map((e,t)=>i(e,n[t]??0)).join(` `),...r.map(e=>e.map((e,t)=>i(e,n[t]??0)).join(` `))].join(`
157
157
  `)},Bd=async e=>{let t=await od(e?.registry).list();e?.json?$(JSON.stringify(t,null,2)):t.length===0?$(`没有已注册的服务`):$(zd(t))},Vd=async(e,t)=>{let n=od(t),r=await n.resolve(e);r===null&&(ld(`错误: 服务 '${e}' 未注册`),process.exit(1));let i=await n.resolveUrl(e);$(i??`http://${r.host}:${r.port}`),r.producer&&$(`生产者 ${r.producer}`),r.capabilities?.health&&$(`健康端点 ${i??``}${r.capabilities.health}`),r.capabilities?.mcp&&$(`MCP 端点 ${i??``}${r.capabilities.mcp}`)};function Hd(e){Ju(e,{name:`list`,description:`列出所有运行中的服务`,options:[{flags:`--json`,description:`以 JSON 形态输出完整实例档`}],schema:Ts({json:gs().optional()}),action:async e=>{await Bd({json:e.json===!0})}}),Ju(e,{name:`resolve`,description:`查询指定服务的基址与能力端点`,arguments:[{signature:`<name>`,description:`服务名称`}],schema:Ts({}),action:async(e,[t])=>{t||(process.stderr.write(`错误: resolve 需要指定服务名称
158
- `),process.exit(1)),await Vd(t)}}),Ju(e,{name:`clean`,description:`清理僵尸注册`,options:[{flags:`--dry-run`,description:`仅预览,不实际删除`}],schema:Ts({dryRun:gs().optional()}),action:async e=>{await Id({dryRun:e.dryRun===!0})}}),Ju(e,{name:`check`,description:`审计端口使用形态并拦截避让违规`,options:[{flags:`--root <path>`,description:`工作区根目录,缺省锚定当前工作区`},{flags:`--json <path>`,description:`审计快照 JSON 输出路径`}],schema:Ts({root:Z().optional(),json:Z().optional()}),action:async e=>{(await Nd({root:e.root,jsonPath:e.json})).errorCount>0&&process.exit(1)}})}function Ud(){let e=Wu({name:`lzi-port`,description:`Longzai Intelligence 端口协调工具`,version:`0.0.4`});return Hd(e),e}async function Wd(){await Ud().parseAsync(process.argv)}import.meta.main===!0&&await Wd();export{Ud as buildProgram};
158
+ `),process.exit(1)),await Vd(t)}}),Ju(e,{name:`clean`,description:`清理僵尸注册`,options:[{flags:`--dry-run`,description:`仅预览,不实际删除`}],schema:Ts({dryRun:gs().optional()}),action:async e=>{await Id({dryRun:e.dryRun===!0})}}),Ju(e,{name:`check`,description:`审计端口使用形态并拦截避让违规`,options:[{flags:`--root <path>`,description:`工作区根目录,缺省锚定当前工作区`},{flags:`--json <path>`,description:`审计快照 JSON 输出路径`}],schema:Ts({root:Z().optional(),json:Z().optional()}),action:async e=>{(await Nd({root:e.root,jsonPath:e.json})).errorCount>0&&process.exit(1)}})}function Ud(){let e=Wu({name:`lzi-port`,description:`Longzai Intelligence 端口协调工具`,version:`0.0.5`});return Hd(e),e}async function Wd(){await Ud().parseAsync(process.argv)}import.meta.main===!0&&await Wd();export{Ud as buildProgram};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@longzai-intelligence-port/cli",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Longzai Intelligence 端口工具 CLI,bin 为 lzi-port",
5
5
  "keywords": [
6
6
  "cli",
@@ -38,6 +38,6 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@longzai-intelligence-cli/core": "^0.0.10",
41
- "@longzai-intelligence-port/core": "0.0.4"
41
+ "@longzai-intelligence-port/core": "0.0.5"
42
42
  }
43
43
  }