@ts-org/jenkins-cli 3.0.6 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,16 +7,13 @@
7
7
  - 交互式 CLI,引导你选择分支和部署环境。
8
8
  - 智能触发,自动停止进行中的构建,并复用队列中相同的任务。
9
9
  - 灵活的参数化构建,支持在运行时传入额外参数。
10
+ - 支持全局 `--debug` 打印 Jenkins 请求信息。
10
11
  - 丰富的命令集,覆盖 Job、Builds、Queue 等常用操作。
11
12
  - 支持 `jenkins-cli.yaml` 或 `package.json` 进行项目级配置。
12
13
 
13
14
  ### 📦 安装
14
15
 
15
16
  ```bash
16
- # Node.js >= 16
17
- npm install -g @ts-org/jenkins-cli
18
-
19
- # Node.js >= 18,推荐使用pnpm
20
17
  pnpm install -g @ts-org/jenkins-cli
21
18
  ```
22
19
 
@@ -42,10 +39,10 @@ CLI 会自动加载配置,列出 Git 分支和部署环境供你选择。
42
39
  # Jenkins API 地址,格式: http(s)://username:token@host:port
43
40
  apiToken: http://user:token@jenkins.example.com
44
41
 
45
- # Jenkins Job 名称 (可被 -j 参数覆盖)
42
+ # Jenkins Job 名称 (可被 -j 参数覆盖,也可用函数引用)
46
43
  job: your-project-job
47
44
 
48
- # 部署环境列表 (将作为参数 `mode` 传入 Jenkins)
45
+ # 部署环境列表 (将作为参数 `mode` 传入 Jenkins,也可用函数引用)
49
46
  # 选项要与Jenkins配置的对上
50
47
  # 这里配置了Jenkins上没有的,比如prod,那么在提交mode = prod时会报500
51
48
  modes:
@@ -56,6 +53,27 @@ modes:
56
53
 
57
54
  建议在 `jenkins-cli.yaml` 顶部添加 `# yaml-language-server: $schema=https://cdn.jsdelivr.net/npm/@ts-org/jenkins-cli@latest/schemas/jenkins.json`,以有更好的开发体验,如示例。
58
55
 
56
+ #### 动态 job / modes
57
+
58
+ `job` 和 `modes` 支持函数引用(`path:exportName`),函数会收到 `answers` 参数,返回最终值。
59
+
60
+ 示例:
61
+
62
+ ```yaml
63
+ job: jenkins-utils.ts:dynamicJob
64
+ modes: jenkins-utils.ts:dynamicModes
65
+ ```
66
+
67
+ ```ts
68
+ export function dynamicJob(answers: Record<string, unknown>) {
69
+ return answers.isElectron ? 'remote-client-web' : 'remote-web-order'
70
+ }
71
+
72
+ export function dynamicModes(answers: Record<string, unknown>) {
73
+ return Number(answers.buildNumber) > 100 ? ['dev', 'sit', 'uat', 'prod'] : ['dev', 'sit', 'uat']
74
+ }
75
+ ```
76
+
59
77
  #### 扩展交互参数
60
78
 
61
79
  通过 `configs` 字段,你可以添加自定义的交互式提问,其结果将作为参数传递给 Jenkins。
@@ -63,12 +81,19 @@ modes:
63
81
  - `type`: 支持 `input`, `number`, `confirm`, `list`, `rawlist`, `checkbox`, `password`等类型。
64
82
  - `choices`, `default`, `validate`, `when`, `filter`, `transformer`: 支持从本地 TS/JS 文件动态加载。
65
83
  - `path:exportName`:自动判断并使用导出值;如果是函数则调用 (支持 async)。
84
+ - `offset`: 负数可调整提问顺序
85
+ - `-1`:插到 branch 后、modes 前
86
+ - `<= -2`:插到 branch 前
66
87
  - `name`: 参数名,注意不要使用 `branch`, `mode`, `modes` 等保留字。
67
88
 
68
89
  **示例:**
69
90
 
70
91
  ```yaml
71
92
  configs:
93
+ - type: number
94
+ name: buildNumber
95
+ message: '请选择构建号:'
96
+ offset: -2
72
97
  - type: input
73
98
  name: version
74
99
  message: '请输入版本号:'
@@ -120,24 +145,24 @@ export function validateTicket(input: unknown, answers: Record<string, unknown>)
120
145
 
121
146
  **四个函数的完整入参说明**:
122
147
 
123
- - `when(answers)`
124
- - `answers`: 当前已回答的所有答案对象(键为问题的 `name`)。
148
+ - `when(answers)`
149
+ - `answers`: 当前已回答的所有答案对象(键为问题的 `name`)。
125
150
  - 返回 `boolean | Promise<boolean>`,用于决定是否显示该问题。
126
151
 
127
- - `validate(input, answers)`
128
- - `input`: 用户当前输入的原始值。
129
- - `answers`: 当前已回答的所有答案对象。
152
+ - `validate(input, answers)`
153
+ - `input`: 用户当前输入的原始值。
154
+ - `answers`: 当前已回答的所有答案对象。
130
155
  - 返回 `true` 表示通过;返回 `string` 作为错误提示;也可返回 `Promise<true | string>`。
131
156
 
132
- - `filter(input, answers)`
133
- - `input`: 用户当前输入的原始值。
134
- - `answers`: 当前已回答的所有答案对象。
157
+ - `filter(input, answers)`
158
+ - `input`: 用户当前输入的原始值。
159
+ - `answers`: 当前已回答的所有答案对象。
135
160
  - 返回转换后的值(可同步或返回 Promise)。
136
161
 
137
- - `transformer(input, answers, meta)`
138
- - `input`: 用户当前输入的原始值。
139
- - `answers`: 当前已回答的所有答案对象。
140
- - `meta`: 渲染相关的元信息(例如 `isFinal`),不同版本可能略有差异。
162
+ - `transformer(input, answers, meta)`
163
+ - `input`: 用户当前输入的原始值。
164
+ - `answers`: 当前已回答的所有答案对象。
165
+ - `meta`: 渲染相关的元信息(例如 `isFinal`),不同版本可能略有差异。
141
166
  - 返回显示用的字符串,不会修改answers的值(可同步或返回 Promise)。
142
167
 
143
168
  > **提示**: 配置也支持写在 `package.json` 的 `jenkins-cli` 字段里。
package/dist/cli.d.ts CHANGED
File without changes
package/dist/cli.js CHANGED
@@ -1,42 +1,42 @@
1
1
  #!/usr/bin/env node
2
2
  import { program, CommanderError } from 'commander';
3
- import fn from 'inquirer';
4
- import w from 'chalk';
5
- import Vt from 'ora';
3
+ import oe from 'inquirer';
4
+ import y from 'chalk';
5
+ import en from 'ora';
6
6
  import { exec, spawn } from 'child_process';
7
- import gn, { promisify } from 'util';
8
- import T from 'fs-extra';
9
- import Ht from 'js-yaml';
10
- import V from 'path';
11
- import Zt from 'axios';
7
+ import En, { promisify } from 'util';
8
+ import M from 'fs-extra';
9
+ import fn from 'js-yaml';
10
+ import z from 'path';
11
+ import bn from 'axios';
12
12
  import { Buffer } from 'buffer';
13
- import cn from 'jiti';
13
+ import vn from 'jiti';
14
14
  import { fileURLToPath } from 'url';
15
15
  import { promises } from 'fs';
16
16
  import { XMLParser } from 'fast-xml-parser';
17
- import Cn from 'os';
17
+ import Gn from 'os';
18
18
 
19
- var Te="3.0.6",Ve="Jenkins deployment CLI";var f=class extends Error{hint;example;details;exitCode;constructor(n,e={}){super(n),this.name="UserError",this.hint=e.hint,this.example=e.example,this.details=e.details,this.exitCode=e.exitCode??1;}};function Mt(t){return t instanceof f?t:t instanceof CommanderError?new f(t.message,{hint:"Check the command usage and options.",example:"jenkins-cli --help",exitCode:t.exitCode??1}):t instanceof Error?new f(t.message,{hint:"Check your input and try again.",example:"jenkins-cli --help"}):new f("Unknown error",{example:"jenkins-cli --help"})}function U(t){let n=Mt(t);if(console.error(w.red(`
20
- \u274C ${n.message}
21
- `)),n.details&&console.error(w.gray(n.details)),n.hint&&console.error(w.yellow(`Hint: ${n.hint}`)),n.example!==""){let e=n.example??"jenkins-cli --help";console.error(w.cyan(`Example: ${e}`));}console.error(w.gray('Run "jenkins-cli --help" for usage.')),process.exitCode=n.exitCode;}var we=promisify(exec);async function Ie(){try{let{stdout:t}=await we("git branch --show-current"),n=t.trim();if(!n)throw new f("Not on any branch (detached HEAD state).",{hint:"Checkout a branch before running this command.",example:"git checkout main"});return n}catch{throw new f("Failed to get current branch.",{hint:"Make sure you are inside a git repository.",example:"cd /path/to/repo && jenkins-cli"})}}async function Oe(){try{let{stdout:t}=await we('git branch -r --format="%(refname:short)"');return t.split(`
22
- `).filter(n=>n.includes("/")&&!n.includes("HEAD"))}catch{throw new f("Failed to list branches.",{hint:"Make sure you are inside a git repository.",example:"cd /path/to/repo && jenkins-cli"})}}async function te(){try{let{stdout:t}=await we("git config user.name"),n=t.trim();return n||void 0}catch{return}}var L="jenkins-cli.yaml",re="package.json",ne="jenkins-cli",Qt="jenkinsCli";function De(t,n=process.cwd()){let e=n;for(;;){let r=V.join(e,t);if(T.existsSync(r))return r;let o=V.dirname(e);if(o===e)return null;e=o;}}function Gt(t=process.cwd()){return De(L,t)}function Kt(t=process.cwd()){let n=De(re,t);return n?V.dirname(n):null}function Yt(t){return !!(t.apiToken&&t.job&&Array.isArray(t.modes)&&t.modes.length>0)}async function qe(t){let n=await T.readFile(t,"utf-8"),e=Ht.load(n);if(!e||typeof e!="object")throw new f(`Invalid config in ${L}. Expected a YAML object.`,{hint:"Top-level config must be key/value pairs.",example:`${L}:
19
+ var Ze="3.1.1",et="Jenkins deployment CLI";var d=class extends Error{hint;example;details;exitCode;constructor(t,e={}){super(t),this.name="UserError",this.hint=e.hint,this.example=e.example,this.details=e.details,this.exitCode=e.exitCode??1;}};function ln(n){return n instanceof d?n:n instanceof CommanderError?new d(n.message,{hint:"Check the command usage and options.",example:"jenkins-cli --help",exitCode:n.exitCode??1}):n instanceof Error?new d(n.message,{hint:"Check your input and try again.",example:"jenkins-cli --help"}):new d("Unknown error",{example:"jenkins-cli --help"})}function q(n){let t=ln(n);if(console.error(y.red(`
20
+ \u274C ${t.message}
21
+ `)),t.details&&console.error(y.gray(t.details)),t.hint&&console.error(y.yellow(`Hint: ${t.hint}`)),t.example!==""){let e=t.example??"jenkins-cli --help";console.error(y.cyan(`Example: ${e}`));}console.error(y.gray('Run "jenkins-cli --help" for usage.')),process.exitCode=t.exitCode;}var Ee=promisify(exec);async function tt(){try{let{stdout:n}=await Ee("git branch --show-current"),t=n.trim();if(!t)throw new d("Not on any branch (detached HEAD state).",{hint:"Checkout a branch before running this command.",example:"git checkout main"});return t}catch{throw new d("Failed to get current branch.",{hint:"Make sure you are inside a git repository.",example:"cd /path/to/repo && jenkins-cli"})}}async function nt(){try{let{stdout:n}=await Ee('git branch -r --format="%(refname:short)"');return n.split(`
22
+ `).filter(t=>t.includes("/")&&!t.includes("HEAD"))}catch{throw new d("Failed to list branches.",{hint:"Make sure you are inside a git repository.",example:"cd /path/to/repo && jenkins-cli"})}}async function le(){try{let{stdout:n}=await Ee("git config user.name"),t=n.trim();return t||void 0}catch{return}}var D="jenkins-cli.yaml",me="package.json",ue="jenkins-cli",pn="jenkinsCli";function ot(n,t=process.cwd()){let e=t;for(;;){let r=z.join(e,n);if(M.existsSync(r))return r;let o=z.dirname(e);if(o===e)return null;e=o;}}function dn(n=process.cwd()){return ot(D,n)}function gn(n=process.cwd()){let t=ot(me,n);return t?z.dirname(t):null}function wn(n){let t=Array.isArray(n.modes)&&n.modes.length>0||typeof n.modes=="string";return !!(n.apiToken&&n.job&&t)}async function rt(n){let t=await M.readFile(n,"utf-8"),e=fn.load(t);if(!e||typeof e!="object")throw new d(`Invalid config in ${D}. Expected a YAML object.`,{hint:"Top-level config must be key/value pairs.",example:`${D}:
23
23
  apiToken: http://user:token@host
24
24
  job: my-job
25
- modes: [dev]`});return e}async function Xt(t){let n=V.join(t,re);if(!await T.pathExists(n))return {};let e=await T.readFile(n,"utf-8"),r=JSON.parse(e),o=r[ne]??r[Qt];if(o==null)return {};if(typeof o!="object"||Array.isArray(o))throw new f(`Invalid ${re} config: "${ne}" must be an object.`,{hint:"Use an object for the config section.",example:`"${ne}": { "apiToken": "http://user:token@host", "job": "my-job", "modes": ["dev"] }`});return o}async function Me(){let t=process.cwd(),n=Kt(t)??t,e=V.join(n,L),r={},o=V.dirname(n),s=Gt(o);s&&await T.pathExists(s)&&(r=await qe(s));let i=await Xt(n);r={...r,...i};let a=await T.pathExists(e)?await qe(e):{};if(r={...r,...a},!Yt(r))throw new f("Config incomplete or not found.",{hint:`Tried ${L} in project root, "${ne}" in ${re}, and walking up from cwd. Required: apiToken, job, modes (non-empty array).`,example:`${L}:
25
+ modes: [dev]`});return e}async function hn(n){let t=z.join(n,me);if(!await M.pathExists(t))return {};let e=await M.readFile(t,"utf-8"),r=JSON.parse(e),o=r[ue]??r[pn];if(o==null)return {};if(typeof o!="object"||Array.isArray(o))throw new d(`Invalid ${me} config: "${ue}" must be an object.`,{hint:"Use an object for the config section.",example:`"${ue}": { "apiToken": "http://user:token@host", "job": "my-job", "modes": ["dev"] }`});return o}async function it(){let n=process.cwd(),t=gn(n)??n,e=z.join(t,D),r={},o=z.dirname(t),s=dn(o);s&&await M.pathExists(s)&&(r=await rt(s));let i=await hn(t);r={...r,...i};let a=await M.pathExists(e)?await rt(e):{};if(r={...r,...a},!wn(r))throw new d("Config incomplete or not found.",{hint:`Tried ${D} in project root, "${ue}" in ${me}, and walking up from cwd. Required: apiToken, job, modes (non-empty array).`,example:`${D}:
26
26
  apiToken: http://user:token@host
27
27
  job: my-job
28
28
  modes:
29
- - dev`});return {...r,projectRoot:n}}var N={maxRedirects:0,validateStatus:t=>t>=200&&t<400};function x(t){return `job/${t.split("/").map(e=>e.trim()).filter(Boolean).map(encodeURIComponent).join("/job/")}`}function ie(t){let n=Array.isArray(t)?t.find(o=>o?.parameters):void 0,e=Array.isArray(n?.parameters)?n.parameters:[],r={};for(let o of e)o?.name&&(r[String(o.name)]=o?.value);return r}function He(t){try{let e=new URL(t).pathname.split("/").filter(Boolean),r=[];for(let o=0;o<e.length-1;o++)e[o]==="job"&&e[o+1]&&r.push(decodeURIComponent(e[o+1]));return r.join("/")}catch{return ""}}async function en(t,n){let r=(await t.axios.get(new URL("api/json?tree=number,url,building,result,timestamp,duration,estimatedDuration,fullDisplayName,displayName,actions[parameters[name,value]]",n).toString())).data??{};return {...r,parameters:ie(r.actions)}}function Qe(t,n=400){try{let r=(typeof t=="string"?t:JSON.stringify(t??"",null,2)).trim();return r?r.length>n?`${r.slice(0,n)}...`:r:""}catch{return ""}}function z(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}}function _(t){let n=z(t);if(n!==void 0)return n;if(typeof t=="string"){let e=Date.parse(t);if(!Number.isNaN(e))return e}}function v(t){return t.split("/").map(e=>e.trim()).filter(Boolean).map(encodeURIComponent).join("/")}function ye(t,n){let e=t.replace(/\/+$/,""),r=n.replace(/^\/+/,"");return /^https?:\/\//i.test(e)?new URL(`${r}`,`${e}/`).toString():`${e}/${r}`}function I(t){return t.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function oe(t){return t.replace(/<[^>]*>/g,"")}function tn(t){return /<!doctype\s+html|<html\b|<body\b/i.test(t)}function nn(t){let n=t.match(/<pre[^>]*>([\s\S]*?)<\/pre>/i),e=t.match(/<code[^>]*>([\s\S]*?)<\/code>/i),r=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i),s=(n?.[1]??e?.[1]??r?.[1]??t).replace(/<br\s*\/?>/gi,`
30
- `);return I(oe(s))}function rn(t){let n=[...t.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/gi)],e=[],r=new Set;for(let s of n){let i=s[1]??"",a=[...i.matchAll(/<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)],c="",l="";for(let D of a){let Ue=D[1]??"",ee=I(oe(D[2]??"")).trim();if(!(!ee||ee==="..")&&!/all\s+files\s+in\s+zip/i.test(ee)){c=Ue,l=ee;break}}if(!c||!l||c==="../"||c==="..")continue;let u=/class="[^"]*folder[^"]*"/i.test(i)||c.endsWith("/")?"dir":"file",p=I(c.split("?")[0]??"").replace(/\/+$/,"")||l,m=i.match(/class="last-modified"[^>]*>([\s\S]*?)<\/td>/i),h=m?I(oe(m[1]??"")).trim():"",d=h?_(h):void 0,y=`${l}|${p}`;r.has(y)||(r.add(y),e.push({name:l,path:p,type:u,modified:d}));}if(e.length)return e;let o=[...t.matchAll(/<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)];for(let s of o){let i=String(s[1]??"").trim(),a=I(oe(s[2]??"")).trim();if(!a||a===".."||/all\s+files\s+in\s+zip/i.test(a)||!i||i==="../"||i===".."||/^https?:\/\//i.test(i)||i.startsWith("/")||i.startsWith("?")||i.startsWith("#")||/\/job\//i.test(i)||/\/view\//i.test(i))continue;let c=i.endsWith("/")?"dir":"file",l=I(i.split("?")[0]??"").replace(/\/+$/,"")||a,u=`${a}|${l}`;r.has(u)||(r.add(u),e.push({name:a,path:l,type:c}));}return e}async function ke(t,n,e){let r=ye(n,`ws/${e}`),o=[`${r}?format=raw`,`${r}?format=txt`,`${r}?format=plain`,`${r}?plain=1`,`${r}?raw=1`,r],s;for(let i of o)try{let a=await t.axios.get(i,{responseType:"arraybuffer",headers:{Accept:"*/*"}}),c=a.data??new ArrayBuffer(0),l=Buffer.from(c);if(!l.length)continue;let u=a.headers?.["content-type"];return {data:l,contentType:u?String(u):void 0}}catch(a){if(s=a,a?.response?.status===404)continue;throw a}throw s||new Error("Workspace file not found")}async function xe(t,n,e){let r=ye(n,`ws/${e}`),o=[`${r}?format=raw`,`${r}?format=txt`,`${r}?format=plain`,`${r}?plain=1`,`${r}?raw=1`,r],s;for(let i of o)try{let a=await t.axios.get(i,{responseType:"text",headers:{Accept:"text/plain,*/*"}}),c=typeof a.data=="string"?a.data:String(a.data??"");if(!c)continue;if(tn(c)){let l=nn(c);if(l.trim())return l;continue}return c}catch(a){if(s=a,a?.response?.status===404)continue;throw a}throw s||new Error("Workspace file not found")}async function je(t,n,e){let r=ye(n,`ws/${e}`),o=r.endsWith("/")?r:`${r}/`,s=[`${o}api/json?depth=1`,`${o}?format=json&depth=1`,`${o}?depth=1&format=json`,`${o}?format=json`,`${o}?depth=1`],i;for(let a of s)try{let l=(await t.axios.get(a,{headers:{Accept:"application/json"}})).data;if(typeof l=="string")try{l=JSON.parse(l);}catch{continue}if(l&&typeof l=="object")return l}catch(c){if(i=c,c?.response?.status===404)continue;throw c}try{let a=await t.axios.get(o,{headers:{Accept:"text/html"}});if(typeof a.data=="string"){let c=rn(a.data);if(c.length)return {children:c}}}catch(a){i=a;}throw i||new Error("Workspace listing not found")}function on(t){if(Array.isArray(t))return t;let n=[t?.children,t?.files,t?.childs,t?.items,t?.entries,t?.content,t?.tree];for(let e of n){if(Array.isArray(e))return e;if(e&&Array.isArray(e.children))return e.children}return t?.children&&Array.isArray(t.children?.children)?t.children.children:[]}function Ce(t){return on(t).map(e=>{let r=String(e?.name??e?.displayName??"").trim(),o=String(e?.path??e?.relativePath??e?.filePath??e?.href??e?.url??"").trim(),s=o?o.split("/").filter(Boolean).pop()??o:"",i=r||s||"-",a=o||r||i,c=(()=>e?.directory===!0||e?.isDirectory===!0||e?.isFolder===!0||e?.type==="directory"||e?.type==="dir"||e?.kind==="directory"||e?.kind==="dir"?"dir":e?.file===!0||e?.type==="file"||e?.kind==="file"?"file":"unknown")(),l=z(e?.size)??z(e?.length)??z(e?.fileSize)??z(e?.bytes)??void 0,u=_(e?.lastModified)??_(e?.modified)??_(e?.mtime)??_(e?.timestamp)??void 0,p=String(e?.href??e?.url??e?.link??"").trim()||void 0;return {name:i,path:a,url:p,size:l,modified:u,type:c}})}function Ge(t){let n=t.match(/^(https?):\/\/([^:]+):([^@]+)@(.+)$/);if(!n)throw new f("Invalid apiToken format.",{hint:"Expected: http(s)://username:token@host:port",example:"http://user:token@jenkins.example.com:8080"});let[,e,r,o,s]=n,i=`${e}://${s.replace(/\/$/,"")}/`,a=Zt.create({baseURL:i,auth:{username:r,password:o},proxy:!1,timeout:3e4});return {baseURL:i,auth:{username:r,password:o},axios:a,crumbForm:void 0}}async function Ke(t,n=5e3){try{let e=await t.axios.get("crumbIssuer/api/json",{timeout:n}),{data:r}=e;r?.crumbRequestField&&r?.crumb&&(t.axios.defaults.headers.common[r.crumbRequestField]=r.crumb,t.crumbForm={field:r.crumbRequestField,value:r.crumb});let o=e.headers["set-cookie"];if(o){let s=Array.isArray(o)?o.map(i=>i.split(";")[0].trim()):[String(o).split(";")[0].trim()];t.axios.defaults.headers.common.Cookie=s.join("; ");}}catch{}}function Se(t){return t.crumbPromise||(t.crumbPromise=Ke(t,5e3)),t.crumbPromise}async function A(t){await Se(t),t.crumbForm||(t.crumbPromise=Ke(t,15e3),await t.crumbPromise);}async function O(t,n){let r=(await t.axios.get("queue/api/json?tree=items[id,task[name],actions[parameters[name,value]],why]")).data.items;if(n){let o=n.trim(),s=o.split("/").filter(Boolean).pop();return r.filter(i=>{let a=i.task?.name;return a===o||(s?a===s:!1)})}return r}async function H(t,n){let e=await t.axios.get(`${x(n)}/api/json?tree=builds[number,url,building,result,timestamp,duration,estimatedDuration,actions[parameters[name,value]]]`);return (Array.isArray(e.data?.builds)?e.data.builds:[]).filter(o=>o?.building).map(o=>({...o,parameters:ie(o.actions)}))}async function se(t){let n=await t.axios.get("computer/api/json?tree=computer[displayName,executors[currentExecutable[number,url]],oneOffExecutors[currentExecutable[number,url]]]"),e=Array.isArray(n.data?.computer)?n.data.computer:[],r=[];for(let i of e){let a=Array.isArray(i?.executors)?i.executors:[],c=Array.isArray(i?.oneOffExecutors)?i.oneOffExecutors:[];for(let l of [...a,...c]){let u=l?.currentExecutable;u?.url&&r.push({number:Number(u.number),url:String(u.url)});}}let o=new Map;for(let i of r)i.url&&o.set(i.url,i);return (await Promise.all([...o.values()].map(async i=>{let a=await en(t,i.url),c=He(String(a?.url??i.url));return {...a,job:c}}))).filter(i=>i?.building)}async function Q(t,n){return await A(t),await t.axios.post("queue/cancelItem",new URLSearchParams({id:n.toString()}),N),!0}async function G(t,n,e){try{await A(t),await t.axios.post(`${x(n)}/${e}/stop/`,new URLSearchParams({}),N);}catch(r){let o=r.response?.status;if(o===403){let s=typeof r.response?.data=="string"?r.response.data.slice(0,200):JSON.stringify(r.response?.data??"").slice(0,200),i=/crumb|csrf/i.test(s);console.log(w.red("[Error] 403 Forbidden: Jenkins refused the stop request (likely permissions or CSRF).")),console.log(w.yellow('[Hint] Confirm the current user has "Job" -> "Cancel" permission on this job.')),console.log(i?"[Hint] Jenkins returned a crumb/CSRF error. Ensure crumb + session cookie are sent, or use API token (not password).":s?`[Hint] Jenkins response: ${s}`:'[Hint] If "Job/Cancel" is already granted, also try granting "Run" -> "Update" (some versions use it for stop).');return}if(o===404||o===400||o===500){console.log(`[Info] Build #${e} could not be stopped (HTTP ${o}). Assuming it finished.`);return}throw r}}async function $e(t,n,e){await A(t);let r=`view/${encodeURIComponent(n)}/addJobToView`;try{await t.axios.post(r,new URLSearchParams({name:e}),N);}catch(o){let s=o?.response?.status;throw s===404?new f(`View not found: ${n}`,{hint:'Check the view name using "jenkins-cli view list".'}):s===400?new f(`Job not found: ${e}`,{hint:'Check the job name using "jenkins-cli job list".'}):o}}async function Je(t,n,e){await A(t);let r=`view/${encodeURIComponent(n)}/removeJobFromView`;try{await t.axios.post(r,new URLSearchParams({name:e}),N);}catch(o){let s=o?.response?.status;throw s===404?new f(`View not found: ${n}`,{hint:'Check the view name using "jenkins-cli view list".'}):s===400?new f(`Job not found: ${e}`,{hint:'Check the job name using "jenkins-cli job list".'}):o}}async function Ye(t,n){await A(t);let e=new URLSearchParams({name:n,mode:"hudson.model.ListView",json:JSON.stringify({name:n,mode:"hudson.model.ListView"})});try{await t.axios.post("createView",e,N);}catch(r){let o=r?.response?.status;throw o===400?new f(`View already exists: ${n}`,{hint:'Use "jenkins-cli view list" to see existing views.'}):o===403?new f(`Forbidden to create view: ${n}`,{hint:'Check Jenkins permissions for "Overall/Manage" or "View/Create".'}):r}}async function Xe(t,n){await A(t);let e=`view/${encodeURIComponent(n)}/doDelete`;try{await t.axios.post(e,new URLSearchParams({}),N);}catch(r){let o=r?.response?.status;throw o===404?new f(`View not found: ${n}`,{hint:'Check the view name using "jenkins-cli view list".'}):o===403?new f(`Forbidden to delete view: ${n}`,{hint:'Check Jenkins permissions for "Overall/Manage" or "View/Delete".'}):r}}async function ae(t,n,e){let r="branch",o="mode",s=e[o];s&&console.log(`Checking for conflicting builds for mode: ${s}...`);let[i,a]=await Promise.all([O(t,n),H(t,n)]),c=(p,m)=>{let h=p.actions?.find(y=>y.parameters);return h?h.parameters.find(y=>y.name===m)?.value:void 0},l=e[r];if(s&&l){let p=i.find(m=>c(m,o)===s&&c(m,r)===l);if(p)return new URL(`queue/item/${p.id}/`,t.baseURL).toString()}let u=!1;if(s)for(let p of a)c(p,o)===s&&(console.log(`Stopping running build #${p.number} (mode=${s})...`),await G(t,n,p.number),u=!0);u&&await new Promise(p=>setTimeout(p,1e3));try{return await A(t),(await t.axios.post(`${x(n)}/buildWithParameters/`,new URLSearchParams({...e}),N)).headers.location||""}catch(p){let m=p?.response?.status,h=Qe(p?.response?.data);if(m===400){let d=h?`Jenkins response (snippet):
31
- ${h}`:void 0;throw new f("Jenkins rejected the request (400).",{hint:`Common causes: job is not parameterized, parameter names do not match, or the job endpoint differs (e.g. multibranch jobs). This CLI sends parameters "${r}" and "${o}".`,example:"jenkins-cli build -b origin/main -m dev",details:d})}if(m){let d=h?`Jenkins response (snippet):
32
- ${h}`:void 0;throw new f(`Request failed with status code ${m}.`,{hint:"Check Jenkins job permissions and parameters.",example:"jenkins-cli me",details:d})}throw p}}async function Ze(t){return (await t.axios.get("whoAmI/api/json")).data}async function W(t){return (await t.axios.get("api/json?tree=jobs[name,url,color]")).data.jobs??[]}async function et(t,n,e){let r=String(n??"").trim();if(!r)return;let o=Math.max(1,e?.depth??5),s="jobs[name,url]";for(let u=0;u<o;u+=1)s=`jobs[name,url,${s}]`;let i=await t.axios.get(`api/json?tree=${encodeURIComponent(s)}`),a=Array.isArray(i.data?.jobs)?i.data.jobs:[],c=[],l=[...a];for(;l.length;){let u=l.shift();if(!u)continue;let p=String(u.name??"").trim();if(p&&p===r&&u.url){let m=He(String(u.url));m&&c.push(m);}Array.isArray(u.jobs)&&l.push(...u.jobs);}if(c.length)return c[0]}async function ce(t,n){try{let r=(await t.axios.get(`${x(n)}/api/json?tree=name,fullName,url,buildable,inQueue,nextBuildNumber,color,healthReport[description,score],lastBuild[number,url,building,result,timestamp,duration],lastCompletedBuild[number,url,result,timestamp,duration],lastSuccessfulBuild[number,url,building,result,timestamp,duration],lastFailedBuild[number,url,building,result,timestamp,duration]`)).data??{},o=typeof r?.fullName=="string"?r.fullName:"",s=typeof r?.name=="string"?r.name:"",i=String(n??"").trim();if(!o&&!s)throw new f(`Job not found: ${i}`,{hint:"Check the job name or use -j/--job to specify the correct job.",example:"jenkins-cli job show -j my-job"});if(i&&i!==o&&i!==s)throw new f(`Job not found: ${i}`,{hint:`Jenkins returned job "${o||s}".`,example:"jenkins-cli console last -j my-job -s success"});return r}catch(e){if(e?.response?.status===404){let o=String(n??"").trim();throw new f(`Job not found: ${o}`,{hint:"Check the job name or use -j/--job to specify the correct job.",example:"jenkins-cli console last -j my-job -s success"})}throw e}}async function tt(t,n,e){let r=Math.max(1,e?.limit??20);return ((await t.axios.get(`${x(n)}/api/json?tree=builds[number,url,building,result,timestamp,duration,actions[parameters[name,value]]]{0,${r}}`)).data.builds??[]).map(i=>({number:i.number,result:i.result,building:i.building,timestamp:i.timestamp,duration:i.duration,url:i.url,parameters:ie(i.actions)}))}async function nt(t,n,e){let r=Math.max(1,e?.limit??20);return ((await t.axios.get(`${x(n)}/api/json?tree=builds[number,url,timestamp,changeSet[items[msg,author[fullName,id,absoluteUrl],authorEmail,authorId,date]]]{0,${r}}`)).data.builds??[]).map(i=>({number:i.number,timestamp:i.timestamp,url:i.url,changeSet:i.changeSet??{}}))}async function le(t,n,e){let o=(await t.axios.get(`${x(n)}/${e}/api/json?tree=number,url,building,result,timestamp,duration,estimatedDuration,fullDisplayName,displayName,description,actions[parameters[name,value]],changeSet[items[msg,author[fullName,id,absoluteUrl],authorEmail,authorId,date]],culprits[fullName],executor[number,progress]`)).data??{};return {...o,parameters:ie(o.actions)}}async function rt(t,n,e){let r=await t.axios.get(`${x(n)}/${e}/consoleText`,{responseType:"text"});return String(r.data??"")}async function ot(t,n){return ((await t.axios.get(`${x(n)}/api/json?tree=property[parameterDefinitions[name,type,description,defaultParameterValue[value],choices]]`)).data?.property??[]).flatMap(s=>s?.parameterDefinitions??[]).filter(Boolean).map(s=>({name:s.name,type:s.type,description:s.description,default:s.defaultParameterValue?.value,choices:s.choices}))}async function ve(t,n,e){let r=String(e?.path??"").trim(),o=r?`${v(r)}/`:"",s=await je(t,x(n),o);return Ce(s??{})}async function it(t,n,e,r){let o=String(r?.path??"").trim(),s=o?`${v(o)}/`:"",i=`view/${encodeURIComponent(n)}/${x(e)}`,a=await je(t,i,s);return Ce(a??{})}async function st(t,n,e,r){let o=String(r?.path??"").trim(),s=o?`${v(o)}/`:"",i=new URL(`${x(e)}/`,n).toString(),a=await je(t,i,s);return Ce(a??{})}async function at(t,n,e){let r=v(String(e??"").trim());return await xe(t,x(n),r)}async function ct(t,n,e){let r=v(String(e??"").trim());return await ke(t,x(n),r)}async function lt(t,n,e,r){let o=v(String(r??"").trim()),s=`view/${encodeURIComponent(n)}/${x(e)}`;return await xe(t,s,o)}async function ut(t,n,e,r){let o=v(String(r??"").trim()),s=`view/${encodeURIComponent(n)}/${x(e)}`;return await ke(t,s,o)}async function mt(t,n,e,r){let o=v(String(r??"").trim()),s=new URL(`${x(e)}/`,n).toString();return await xe(t,s,o)}async function pt(t,n,e,r){let o=v(String(r??"").trim()),s=new URL(`${x(e)}/`,n).toString();return await ke(t,s,o)}async function ft(t,n){try{return await A(t),await t.axios.post(`${x(n)}/doWipeOutWorkspace`,new URLSearchParams({}),N),!0}catch(e){let r=e?.response?.status;if(r){let o=Qe(e?.response?.data);throw new f(`Workspace wipe failed (HTTP ${r}).`,{hint:"Check Job/Workspace permission or CSRF settings.",example:"jenkins-cli workspace wipe -j my-job",details:o?`Jenkins response (snippet):
33
- ${o}`:void 0})}throw e}}async function Pe(t,n){let e=await t.axios.get(`${x(n)}/config.xml`,{responseType:"text"});return String(e.data??"")}async function dt(t,n,e,r){let o=`${x(n)}/${e}/logText/progressiveText`,s=new URLSearchParams;s.append("start",String(r));let i=await t.axios.post(o,s,{responseType:"text"}),a=String(i.data??""),c=i.headers["x-text-size"],l=i.headers["x-more-data"],u=c?Number(c):r+Buffer.byteLength(a);return {text:a,newOffset:u,hasMoreData:l==="true"}}async function K(t,n){let e=n?.raw?"views[*]":"views[name,url]";return (await t.axios.get(`api/json?tree=${e}`)).data.views??[]}async function q(t,n){let e=`view/${encodeURIComponent(n)}`;try{return (await t.axios.get(`${e}/api/json?tree=jobs[name,url,color]`)).data.jobs??[]}catch(r){throw r?.response?.status===404?new f(`View not found: ${n}`,{hint:'Check the view name using "jenkins-cli view list".',example:"jenkins-cli view show MyView"}):r}}async function gt(t,n){let e=String(n??"").trim();if(!e)return;let r=e.split("/").filter(Boolean).pop()??e,o=await K(t,{raw:!1});for(let s of o){let i=String(s?.name??"").trim();if(i)try{if((await q(t,i)).some(c=>{let l=String(c?.name??"").trim();return l===e||l===r}))return i}catch{}}}async function b(){let t=Vt("Loading configuration...").start();try{let n=await Me();t.succeed("Configuration loaded");let e=Ge(n.apiToken);return Se(e),{config:n,jenkins:e}}catch(n){U(n),process.exit(1);}}var un=cn(fileURLToPath(import.meta.url),{interopDefault:!0});async function bt(t){return await Promise.resolve(t)}function mn(t){let n=String(t??"").trim();if(!n)return null;let e=n.split(":");if(e.length<2)return null;if(e.length===2){let[s,i]=e;return !s||!i?null:{file:s,exportName:i}}let r=e.at(-1);if(!r)return null;let o=e.slice(0,-2).join(":");return o?{file:o,exportName:r}:null}function pn(t,n){return V.isAbsolute(n)?n:V.join(t,n)}function yt(t){return !!t&&typeof t=="object"&&!Array.isArray(t)}async function kt(t,n){let e=mn(n);if(!e)return null;let r=pn(t,e.file);if(!await T.pathExists(r))throw new f(`configs reference not found: ${e.file}`,{hint:"Check the file path (relative to project root) and file name.",example:'configs: [{ choices: "./scripts/prompts.ts:choices" }]'});let o=un(r),s=yt(o)?o:{default:o},i=e.exportName==="default"?s.default:s[e.exportName];if(i===void 0)throw new f(`configs reference export not found: ${n}`,{hint:"Make sure the export exists in the referenced file.",example:'export const choices = ["dev", "uat"]'});return {value:i}}async function ue(t,n,e){if(typeof n!="string")return n;let r=await kt(t,n);if(!r)return n;if(!e.allow(r.value))throw new f(e.error(n),{hint:e.hint,example:e.example});return r.value}async function wt(t,n){if(typeof n!="string")return n;let e=await kt(t,n);if(!e)return n;if(typeof e.value=="function"){let r=e.value();return await bt(r)}return await bt(e.value)}async function xt(t,n){let e=Array.isArray(t)?t:[];if(e.length===0)return [];let r=String(n.projectRoot??"").trim()||process.cwd(),o=[];for(let s of e){if(!yt(s))continue;let i={...s};if(i.choices!==void 0){i.choices=await wt(r,i.choices);let a=String(i.type??"").toLowerCase(),c=i.choices;if((a==="list"||a==="rawlist"||a==="checkbox")&&typeof c!="function"&&!Array.isArray(c))if(c==null)i.choices=[];else if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")i.choices=[String(c)];else if(typeof c[Symbol.iterator]=="function")i.choices=Array.from(c).map(u=>String(u));else throw new f(`configs "${String(i.name??"")}" choices must resolve to an array (got ${typeof c}).`,{hint:"Return an array for list/rawlist/checkbox choices.",example:'export const choices = ["dev", "uat"]'})}i.default!==void 0&&(i.default=await wt(r,i.default)),i.when!==void 0&&(i.when=await ue(r,i.when,{allow:a=>typeof a=="function"||typeof a=="boolean",error:a=>`when reference must be a function or boolean: ${a}`,hint:"Export a function or boolean from the referenced file.",example:'export const when = (answers) => answers.env === "dev"'})),i.validate!==void 0&&(i.validate=await ue(r,i.validate,{allow:a=>typeof a=="function",error:a=>`validate reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:'export const validate = (input) => !!input || "required"'})),i.filter!==void 0&&(i.filter=await ue(r,i.filter,{allow:a=>typeof a=="function",error:a=>`filter reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:"export const filter = (input) => input.trim()"})),i.transformer!==void 0&&(i.transformer=await ue(r,i.transformer,{allow:a=>typeof a=="function",error:a=>`transformer reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:"export const transformer = (input) => input.toUpperCase()"})),o.push(i);}return o}function jt(t,n){let e=new Set(n),r={};for(let[o,s]of Object.entries(t))if(!e.has(o)&&s!==void 0){if(s===null){r[o]="";continue}if(Array.isArray(s)){r[o]=s.map(i=>String(i)).join(",");continue}if(typeof s=="object"){try{r[o]=JSON.stringify(s);}catch{r[o]=String(s);}continue}r[o]=String(s);}return r}async function Ct(){console.log(w.bold.blue(`
29
+ - dev`});return {...r,projectRoot:t}}var B={maxRedirects:0,validateStatus:n=>n>=200&&n<400};function x(n){return `job/${n.split("/").map(e=>e.trim()).filter(Boolean).map(encodeURIComponent).join("/job/")}`}function pe(n){let t=Array.isArray(n)?n.find(o=>o?.parameters):void 0,e=Array.isArray(t?.parameters)?t.parameters:[],r={};for(let o of e)o?.name&&(r[String(o.name)]=o?.value);return r}function st(n){try{let e=new URL(n).pathname.split("/").filter(Boolean),r=[];for(let o=0;o<e.length-1;o++)e[o]==="job"&&e[o+1]&&r.push(decodeURIComponent(e[o+1]));return r.join("/")}catch{return ""}}async function yn(n,t){let r=(await n.axios.get(new URL("api/json?tree=number,url,building,result,timestamp,duration,estimatedDuration,fullDisplayName,displayName,actions[parameters[name,value]]",t).toString())).data??{};return {...r,parameters:pe(r.actions)}}function at(n,t=400){try{let r=(typeof n=="string"?n:JSON.stringify(n??"",null,2)).trim();return r?r.length>t?`${r.slice(0,t)}...`:r:""}catch{return ""}}function X(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let t=Number(n);if(Number.isFinite(t))return t}}function Z(n){let t=X(n);if(t!==void 0)return t;if(typeof n=="string"){let e=Date.parse(n);if(!Number.isNaN(e))return e}}function N(n){return n.split("/").map(e=>e.trim()).filter(Boolean).map(encodeURIComponent).join("/")}function We(n,t){let e=n.replace(/\/+$/,""),r=t.replace(/^\/+/,"");return /^https?:\/\//i.test(e)?new URL(`${r}`,`${e}/`).toString():`${e}/${r}`}function _(n){return n.replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function fe(n){return n.replace(/<[^>]*>/g,"")}function kn(n){return /<!doctype\s+html|<html\b|<body\b/i.test(n)}function xn(n){let t=n.match(/<pre[^>]*>([\s\S]*?)<\/pre>/i),e=n.match(/<code[^>]*>([\s\S]*?)<\/code>/i),r=n.match(/<body[^>]*>([\s\S]*?)<\/body>/i),s=(t?.[1]??e?.[1]??r?.[1]??n).replace(/<br\s*\/?>/gi,`
30
+ `);return _(fe(s))}function jn(n){let t=[...n.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/gi)],e=[],r=new Set;for(let s of t){let i=s[1]??"",a=[...i.matchAll(/<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)],c="",l="";for(let S of a){let L=S[1]??"",R=_(fe(S[2]??"")).trim();if(!(!R||R==="..")&&!/all\s+files\s+in\s+zip/i.test(R)){c=L,l=R;break}}if(!c||!l||c==="../"||c==="..")continue;let u=/class="[^"]*folder[^"]*"/i.test(i)||c.endsWith("/")?"dir":"file",f=_(c.split("?")[0]??"").replace(/\/+$/,"")||l,m=i.match(/class="last-modified"[^>]*>([\s\S]*?)<\/td>/i),p=m?_(fe(m[1]??"")).trim():"",g=p?Z(p):void 0,b=`${l}|${f}`;r.has(b)||(r.add(b),e.push({name:l,path:f,type:u,modified:g}));}if(e.length)return e;let o=[...n.matchAll(/<a[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi)];for(let s of o){let i=String(s[1]??"").trim(),a=_(fe(s[2]??"")).trim();if(!a||a===".."||/all\s+files\s+in\s+zip/i.test(a)||!i||i==="../"||i===".."||/^https?:\/\//i.test(i)||i.startsWith("/")||i.startsWith("?")||i.startsWith("#")||/\/job\//i.test(i)||/\/view\//i.test(i))continue;let c=i.endsWith("/")?"dir":"file",l=_(i.split("?")[0]??"").replace(/\/+$/,"")||a,u=`${a}|${l}`;r.has(u)||(r.add(u),e.push({name:a,path:l,type:c}));}return e}async function Ue(n,t,e){let r=We(t,`ws/${e}`),o=[`${r}?format=raw`,`${r}?format=txt`,`${r}?format=plain`,`${r}?plain=1`,`${r}?raw=1`,r],s;for(let i of o)try{let a=await n.axios.get(i,{responseType:"arraybuffer",headers:{Accept:"*/*"}}),c=a.data??new ArrayBuffer(0),l=Buffer.from(c);if(!l.length)continue;let u=a.headers?.["content-type"];return {data:l,contentType:u?String(u):void 0}}catch(a){if(s=a,a?.response?.status===404)continue;throw a}throw s||new Error("Workspace file not found")}async function Le(n,t,e){let r=We(t,`ws/${e}`),o=[`${r}?format=raw`,`${r}?format=txt`,`${r}?format=plain`,`${r}?plain=1`,`${r}?raw=1`,r],s;for(let i of o)try{let a=await n.axios.get(i,{responseType:"text",headers:{Accept:"text/plain,*/*"}}),c=typeof a.data=="string"?a.data:String(a.data??"");if(!c)continue;if(kn(c)){let l=xn(c);if(l.trim())return l;continue}return c}catch(a){if(s=a,a?.response?.status===404)continue;throw a}throw s||new Error("Workspace file not found")}async function Te(n,t,e){let r=We(t,`ws/${e}`),o=r.endsWith("/")?r:`${r}/`,s=[`${o}api/json?depth=1`,`${o}?format=json&depth=1`,`${o}?depth=1&format=json`,`${o}?format=json`,`${o}?depth=1`],i;for(let a of s)try{let l=(await n.axios.get(a,{headers:{Accept:"application/json"}})).data;if(typeof l=="string")try{l=JSON.parse(l);}catch{continue}if(l&&typeof l=="object")return l}catch(c){if(i=c,c?.response?.status===404)continue;throw c}try{let a=await n.axios.get(o,{headers:{Accept:"text/html"}});if(typeof a.data=="string"){let c=jn(a.data);if(c.length)return {children:c}}}catch(a){i=a;}throw i||new Error("Workspace listing not found")}function Cn(n){if(Array.isArray(n))return n;let t=[n?.children,n?.files,n?.childs,n?.items,n?.entries,n?.content,n?.tree];for(let e of t){if(Array.isArray(e))return e;if(e&&Array.isArray(e.children))return e.children}return n?.children&&Array.isArray(n.children?.children)?n.children.children:[]}function Oe(n){return Cn(n).map(e=>{let r=String(e?.name??e?.displayName??"").trim(),o=String(e?.path??e?.relativePath??e?.filePath??e?.href??e?.url??"").trim(),s=o?o.split("/").filter(Boolean).pop()??o:"",i=r||s||"-",a=o||r||i,c=(()=>e?.directory===!0||e?.isDirectory===!0||e?.isFolder===!0||e?.type==="directory"||e?.type==="dir"||e?.kind==="directory"||e?.kind==="dir"?"dir":e?.file===!0||e?.type==="file"||e?.kind==="file"?"file":"unknown")(),l=X(e?.size)??X(e?.length)??X(e?.fileSize)??X(e?.bytes)??void 0,u=Z(e?.lastModified)??Z(e?.modified)??Z(e?.mtime)??Z(e?.timestamp)??void 0,f=String(e?.href??e?.url??e?.link??"").trim()||void 0;return {name:i,path:a,url:f,size:l,modified:u,type:c}})}function ct(n){let t=n.match(/^(https?):\/\/([^:]+):([^@]+)@(.+)$/);if(!t)throw new d("Invalid apiToken format.",{hint:"Expected: http(s)://username:token@host:port",example:"http://user:token@jenkins.example.com:8080"});let[,e,r,o,s]=t,i=`${e}://${s.replace(/\/$/,"")}/`,a=bn.create({baseURL:i,auth:{username:r,password:o},proxy:!1,timeout:3e4});return process.argv.includes("--debug")&&a.interceptors.request.use(l=>{let u=String(l.method??"get").toUpperCase(),f=new URL(String(l.url??""),l.baseURL??i).toString(),m=l.params,p=l.data;p instanceof URLSearchParams?p=Object.fromEntries(p):typeof p=="string"?String(l.headers?.["Content-Type"]??l.headers?.["content-type"]??"").includes("application/x-www-form-urlencoded")?p=Object.fromEntries(new URLSearchParams(p)):p=p.trim()?p:void 0:Buffer.isBuffer(p)&&(p=`[Buffer ${p.length} bytes]`);let g={method:u,url:f};return m&&Object.keys(m).length>0&&(g.params=m),p!=null&&p!==""&&(g.data=p),console.log(y.cyan("[Jenkins Debug] Request")),console.log(JSON.stringify(g,null,2)),l}),{baseURL:i,auth:{username:r,password:o},axios:a,crumbForm:void 0}}async function lt(n,t=5e3){try{let e=await n.axios.get("crumbIssuer/api/json",{timeout:t}),{data:r}=e;r?.crumbRequestField&&r?.crumb&&(n.axios.defaults.headers.common[r.crumbRequestField]=r.crumb,n.crumbForm={field:r.crumbRequestField,value:r.crumb});let o=e.headers["set-cookie"];if(o){let s=Array.isArray(o)?o.map(i=>i.split(";")[0].trim()):[String(o).split(";")[0].trim()];n.axios.defaults.headers.common.Cookie=s.join("; ");}}catch{}}function Ve(n){return n.crumbPromise||(n.crumbPromise=lt(n,5e3)),n.crumbPromise}async function W(n){await Ve(n),n.crumbForm||(n.crumbPromise=lt(n,15e3),await n.crumbPromise);}async function H(n,t){let r=(await n.axios.get("queue/api/json?tree=items[id,task[name],actions[parameters[name,value]],why]")).data.items;if(t){let o=t.trim(),s=o.split("/").filter(Boolean).pop();return r.filter(i=>{let a=i.task?.name;return a===o||(s?a===s:!1)})}return r}async function ee(n,t){let e=await n.axios.get(`${x(t)}/api/json?tree=builds[number,url,building,result,timestamp,duration,estimatedDuration,actions[parameters[name,value]]]`);return (Array.isArray(e.data?.builds)?e.data.builds:[]).filter(o=>o?.building).map(o=>({...o,parameters:pe(o.actions)}))}async function de(n){let t=await n.axios.get("computer/api/json?tree=computer[displayName,executors[currentExecutable[number,url]],oneOffExecutors[currentExecutable[number,url]]]"),e=Array.isArray(t.data?.computer)?t.data.computer:[],r=[];for(let i of e){let a=Array.isArray(i?.executors)?i.executors:[],c=Array.isArray(i?.oneOffExecutors)?i.oneOffExecutors:[];for(let l of [...a,...c]){let u=l?.currentExecutable;u?.url&&r.push({number:Number(u.number),url:String(u.url)});}}let o=new Map;for(let i of r)i.url&&o.set(i.url,i);return (await Promise.all([...o.values()].map(async i=>{let a=await yn(n,i.url),c=st(String(a?.url??i.url));return {...a,job:c}}))).filter(i=>i?.building)}async function te(n,t){return await W(n),await n.axios.post("queue/cancelItem",new URLSearchParams({id:t.toString()}),B),!0}async function ne(n,t,e){try{await W(n),await n.axios.post(`${x(t)}/${e}/stop/`,new URLSearchParams({}),B);}catch(r){let o=r.response?.status;if(o===403){let s=typeof r.response?.data=="string"?r.response.data.slice(0,200):JSON.stringify(r.response?.data??"").slice(0,200),i=/crumb|csrf/i.test(s);console.log(y.red("[Error] 403 Forbidden: Jenkins refused the stop request (likely permissions or CSRF).")),console.log(y.yellow('[Hint] Confirm the current user has "Job" -> "Cancel" permission on this job.')),console.log(i?"[Hint] Jenkins returned a crumb/CSRF error. Ensure crumb + session cookie are sent, or use API token (not password).":s?`[Hint] Jenkins response: ${s}`:'[Hint] If "Job/Cancel" is already granted, also try granting "Run" -> "Update" (some versions use it for stop).');return}if(o===404||o===400||o===500){console.log(`[Info] Build #${e} could not be stopped (HTTP ${o}). Assuming it finished.`);return}throw r}}async function Ie(n,t,e){await W(n);let r=`view/${encodeURIComponent(t)}/addJobToView`;try{await n.axios.post(r,new URLSearchParams({name:e}),B);}catch(o){let s=o?.response?.status;throw s===404?new d(`View not found: ${t}`,{hint:'Check the view name using "jenkins-cli view list".'}):s===400?new d(`Job not found: ${e}`,{hint:'Check the job name using "jenkins-cli job list".'}):o}}async function qe(n,t,e){await W(n);let r=`view/${encodeURIComponent(t)}/removeJobFromView`;try{await n.axios.post(r,new URLSearchParams({name:e}),B);}catch(o){let s=o?.response?.status;throw s===404?new d(`View not found: ${t}`,{hint:'Check the view name using "jenkins-cli view list".'}):s===400?new d(`Job not found: ${e}`,{hint:'Check the job name using "jenkins-cli job list".'}):o}}async function ut(n,t){await W(n);let e=new URLSearchParams({name:t,mode:"hudson.model.ListView",json:JSON.stringify({name:t,mode:"hudson.model.ListView"})});try{await n.axios.post("createView",e,B);}catch(r){let o=r?.response?.status;throw o===400?new d(`View already exists: ${t}`,{hint:'Use "jenkins-cli view list" to see existing views.'}):o===403?new d(`Forbidden to create view: ${t}`,{hint:'Check Jenkins permissions for "Overall/Manage" or "View/Create".'}):r}}async function mt(n,t){await W(n);let e=`view/${encodeURIComponent(t)}/doDelete`;try{await n.axios.post(e,new URLSearchParams({}),B);}catch(r){let o=r?.response?.status;throw o===404?new d(`View not found: ${t}`,{hint:'Check the view name using "jenkins-cli view list".'}):o===403?new d(`Forbidden to delete view: ${t}`,{hint:'Check Jenkins permissions for "Overall/Manage" or "View/Delete".'}):r}}async function ge(n,t,e){let r="branch",o="mode",s=e[o];s&&console.log(`Checking for conflicting builds for mode: ${s}...`);let[i,a]=await Promise.all([H(n,t),ee(n,t)]),c=(f,m)=>{let p=f.actions?.find(b=>b.parameters);return p?p.parameters.find(b=>b.name===m)?.value:void 0},l=e[r];if(s&&l){let f=i.find(m=>c(m,o)===s&&c(m,r)===l);if(f)return new URL(`queue/item/${f.id}/`,n.baseURL).toString()}let u=!1;if(s)for(let f of a)c(f,o)===s&&(console.log(`Stopping running build #${f.number} (mode=${s})...`),await ne(n,t,f.number),u=!0);u&&await new Promise(f=>setTimeout(f,1e3));try{return await W(n),(await n.axios.post(`${x(t)}/buildWithParameters/`,new URLSearchParams({...e}),B)).headers.location||""}catch(f){let m=f?.response?.status,p=at(f?.response?.data);if(m===400){let g=p?`Jenkins response (snippet):
31
+ ${p}`:void 0;throw new d("Jenkins rejected the request (400).",{hint:`Common causes: job is not parameterized, parameter names do not match, or the job endpoint differs (e.g. multibranch jobs). This CLI sends parameters "${r}" and "${o}".`,example:"jenkins-cli build -b origin/main -m dev",details:g})}if(m){let g=p?`Jenkins response (snippet):
32
+ ${p}`:void 0;throw new d(`Request failed with status code ${m}.`,{hint:"Check Jenkins job permissions and parameters.",example:"jenkins-cli me",details:g})}throw f}}async function ft(n){return (await n.axios.get("whoAmI/api/json")).data}async function T(n){return (await n.axios.get("api/json?tree=jobs[name,url,color]")).data.jobs??[]}async function pt(n,t,e){let r=String(t??"").trim();if(!r)return;let o=Math.max(1,e?.depth??5),s="jobs[name,url]";for(let u=0;u<o;u+=1)s=`jobs[name,url,${s}]`;let i=await n.axios.get(`api/json?tree=${encodeURIComponent(s)}`),a=Array.isArray(i.data?.jobs)?i.data.jobs:[],c=[],l=[...a];for(;l.length;){let u=l.shift();if(!u)continue;let f=String(u.name??"").trim();if(f&&f===r&&u.url){let m=st(String(u.url));m&&c.push(m);}Array.isArray(u.jobs)&&l.push(...u.jobs);}if(c.length)return c[0]}async function we(n,t){try{let r=(await n.axios.get(`${x(t)}/api/json?tree=name,fullName,url,buildable,inQueue,nextBuildNumber,color,healthReport[description,score],lastBuild[number,url,building,result,timestamp,duration],lastCompletedBuild[number,url,result,timestamp,duration],lastSuccessfulBuild[number,url,building,result,timestamp,duration],lastFailedBuild[number,url,building,result,timestamp,duration]`)).data??{},o=typeof r?.fullName=="string"?r.fullName:"",s=typeof r?.name=="string"?r.name:"",i=String(t??"").trim();if(!o&&!s)throw new d(`Job not found: ${i}`,{hint:"Check the job name or use -j/--job to specify the correct job.",example:"jenkins-cli job show -j my-job"});if(i&&i!==o&&i!==s)throw new d(`Job not found: ${i}`,{hint:`Jenkins returned job "${o||s}".`,example:"jenkins-cli console last -j my-job -s success"});return r}catch(e){if(e?.response?.status===404){let o=String(t??"").trim();throw new d(`Job not found: ${o}`,{hint:"Check the job name or use -j/--job to specify the correct job.",example:"jenkins-cli console last -j my-job -s success"})}throw e}}async function dt(n,t,e){let r=Math.max(1,e?.limit??20);return ((await n.axios.get(`${x(t)}/api/json?tree=builds[number,url,building,result,timestamp,duration,actions[parameters[name,value]]]{0,${r}}`)).data.builds??[]).map(i=>({number:i.number,result:i.result,building:i.building,timestamp:i.timestamp,duration:i.duration,url:i.url,parameters:pe(i.actions)}))}async function gt(n,t,e){let r=Math.max(1,e?.limit??20);return ((await n.axios.get(`${x(t)}/api/json?tree=builds[number,url,timestamp,changeSet[items[msg,author[fullName,id,absoluteUrl],authorEmail,authorId,date]]]{0,${r}}`)).data.builds??[]).map(i=>({number:i.number,timestamp:i.timestamp,url:i.url,changeSet:i.changeSet??{}}))}async function he(n,t,e){let o=(await n.axios.get(`${x(t)}/${e}/api/json?tree=number,url,building,result,timestamp,duration,estimatedDuration,fullDisplayName,displayName,description,actions[parameters[name,value]],changeSet[items[msg,author[fullName,id,absoluteUrl],authorEmail,authorId,date]],culprits[fullName],executor[number,progress]`)).data??{};return {...o,parameters:pe(o.actions)}}async function wt(n,t,e){let r=await n.axios.get(`${x(t)}/${e}/consoleText`,{responseType:"text"});return String(r.data??"")}async function ht(n,t){return ((await n.axios.get(`${x(t)}/api/json?tree=property[parameterDefinitions[name,type,description,defaultParameterValue[value],choices]]`)).data?.property??[]).flatMap(s=>s?.parameterDefinitions??[]).filter(Boolean).map(s=>({name:s.name,type:s.type,description:s.description,default:s.defaultParameterValue?.value,choices:s.choices}))}async function De(n,t,e){let r=String(e?.path??"").trim(),o=r?`${N(r)}/`:"",s=await Te(n,x(t),o);return Oe(s??{})}async function bt(n,t,e,r){let o=String(r?.path??"").trim(),s=o?`${N(o)}/`:"",i=`view/${encodeURIComponent(t)}/${x(e)}`,a=await Te(n,i,s);return Oe(a??{})}async function yt(n,t,e,r){let o=String(r?.path??"").trim(),s=o?`${N(o)}/`:"",i=new URL(`${x(e)}/`,t).toString(),a=await Te(n,i,s);return Oe(a??{})}async function kt(n,t,e){let r=N(String(e??"").trim());return await Le(n,x(t),r)}async function xt(n,t,e){let r=N(String(e??"").trim());return await Ue(n,x(t),r)}async function jt(n,t,e,r){let o=N(String(r??"").trim()),s=`view/${encodeURIComponent(t)}/${x(e)}`;return await Le(n,s,o)}async function Ct(n,t,e,r){let o=N(String(r??"").trim()),s=`view/${encodeURIComponent(t)}/${x(e)}`;return await Ue(n,s,o)}async function St(n,t,e,r){let o=N(String(r??"").trim()),s=new URL(`${x(e)}/`,t).toString();return await Le(n,s,o)}async function $t(n,t,e,r){let o=N(String(r??"").trim()),s=new URL(`${x(e)}/`,t).toString();return await Ue(n,s,o)}async function vt(n,t){try{return await W(n),await n.axios.post(`${x(t)}/doWipeOutWorkspace`,new URLSearchParams({}),B),!0}catch(e){let r=e?.response?.status;if(r){let o=at(e?.response?.data);throw new d(`Workspace wipe failed (HTTP ${r}).`,{hint:"Check Job/Workspace permission or CSRF settings.",example:"jenkins-cli workspace wipe -j my-job",details:o?`Jenkins response (snippet):
33
+ ${o}`:void 0})}throw e}}async function Me(n,t){let e=await n.axios.get(`${x(t)}/config.xml`,{responseType:"text"});return String(e.data??"")}async function Jt(n,t,e,r){let o=`${x(t)}/${e}/logText/progressiveText`,s=new URLSearchParams;s.append("start",String(r));let i=await n.axios.post(o,s,{responseType:"text"}),a=String(i.data??""),c=i.headers["x-text-size"],l=i.headers["x-more-data"],u=c?Number(c):r+Buffer.byteLength(a);return {text:a,newOffset:u,hasMoreData:l==="true"}}async function re(n,t){let e=t?.raw?"views[*]":"views[name,url]";return (await n.axios.get(`api/json?tree=${e}`)).data.views??[]}async function Q(n,t){let e=`view/${encodeURIComponent(t)}`;try{return (await n.axios.get(`${e}/api/json?tree=jobs[name,url,color]`)).data.jobs??[]}catch(r){throw r?.response?.status===404?new d(`View not found: ${t}`,{hint:'Check the view name using "jenkins-cli view list".',example:"jenkins-cli view show MyView"}):r}}async function Rt(n,t){let e=String(t??"").trim();if(!e)return;let r=e.split("/").filter(Boolean).pop()??e,o=await re(n,{raw:!1});for(let s of o){let i=String(s?.name??"").trim();if(i)try{if((await Q(n,i)).some(c=>{let l=String(c?.name??"").trim();return l===e||l===r}))return i}catch{}}}async function h(){let n=en("Loading configuration...").start();try{let t=await it();n.succeed("Configuration loaded");let e=ct(t.apiToken);return Ve(e),{config:t,jenkins:e}}catch(t){q(t),process.exit(1);}}var Rn=vn(fileURLToPath(import.meta.url),{interopDefault:!0});async function ye(n){return await Promise.resolve(n)}function Pn(n){let t=String(n??"").trim();if(!t)return null;let e=t.split(":");if(e.length<2)return null;if(e.length===2){let[s,i]=e;return !s||!i?null:{file:s,exportName:i}}let r=e.at(-1);if(!r)return null;let o=e.slice(0,-2).join(":");return o?{file:o,exportName:r}:null}function An(n,t){return z.isAbsolute(t)?t:z.join(n,t)}function Nt(n){return !!n&&typeof n=="object"&&!Array.isArray(n)}async function ke(n,t){let e=Pn(t);if(!e)return null;let r=An(n,e.file);if(!await M.pathExists(r))throw new d(`configs reference not found: ${e.file}`,{hint:"Check the file path (relative to project root) and file name.",example:'configs: [{ choices: "./scripts/prompts.ts:choices" }]'});let o=Rn(r),s=Nt(o)?o:{default:o},i=e.exportName==="default"?s.default:s[e.exportName];if(i===void 0)throw new d(`configs reference export not found: ${t}`,{hint:"Make sure the export exists in the referenced file.",example:'export const choices = ["dev", "uat"]'});return {value:i}}async function Et(n,t){if(typeof t!="string")return {isRef:!1,isFunction:!1,value:t};let e=await ke(n,t);return e?{isRef:!0,isFunction:typeof e.value=="function",value:e.value}:{isRef:!1,isFunction:!1,value:t}}async function be(n,t,e){if(typeof t!="string")return t;let r=await ke(n,t);if(!r)return t;if(!e.allow(r.value))throw new d(e.error(t),{hint:e.hint,example:e.example});return r.value}async function At(n,t){if(typeof t!="string")return t;let e=await ke(n,t);if(!e)return t;if(typeof e.value=="function"){let r=e.value();return await ye(r)}return await ye(e.value)}async function O(n,t,e){if(typeof t!="string")return t;let r=await ke(n,t);if(!r)return t;if(typeof r.value=="function"){let o=r.value(e);return await ye(o)}return await ye(r.value)}async function xe(n,t){let e=Array.isArray(n)?n:[];if(e.length===0)return [];let r=String(t.projectRoot??"").trim()||process.cwd(),o=[];for(let s of e){if(!Nt(s))continue;let i={...s};if(i.choices!==void 0){i.choices=await At(r,i.choices);let a=String(i.type??"").toLowerCase(),c=i.choices;if((a==="list"||a==="rawlist"||a==="checkbox")&&typeof c!="function"&&!Array.isArray(c))if(c==null)i.choices=[];else if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")i.choices=[String(c)];else if(typeof c[Symbol.iterator]=="function")i.choices=Array.from(c).map(u=>String(u));else throw new d(`configs "${String(i.name??"")}" choices must resolve to an array (got ${typeof c}).`,{hint:"Return an array for list/rawlist/checkbox choices.",example:'export const choices = ["dev", "uat"]'})}i.default!==void 0&&(i.default=await At(r,i.default)),i.when!==void 0&&(i.when=await be(r,i.when,{allow:a=>typeof a=="function"||typeof a=="boolean",error:a=>`when reference must be a function or boolean: ${a}`,hint:"Export a function or boolean from the referenced file.",example:'export const when = (answers) => answers.env === "dev"'})),i.validate!==void 0&&(i.validate=await be(r,i.validate,{allow:a=>typeof a=="function",error:a=>`validate reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:'export const validate = (input) => !!input || "required"'})),i.filter!==void 0&&(i.filter=await be(r,i.filter,{allow:a=>typeof a=="function",error:a=>`filter reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:"export const filter = (input) => input.trim()"})),i.transformer!==void 0&&(i.transformer=await be(r,i.transformer,{allow:a=>typeof a=="function",error:a=>`transformer reference must be a function: ${a}`,hint:"Export a function from the referenced file.",example:"export const transformer = (input) => input.toUpperCase()"})),o.push(i);}return o}function Ft(n,t){let e=new Set(t),r={};for(let[o,s]of Object.entries(n))if(!e.has(o)&&s!==void 0){if(s===null){r[o]="";continue}if(Array.isArray(s)){r[o]=s.map(i=>String(i)).join(",");continue}if(typeof s=="object"){try{r[o]=JSON.stringify(s);}catch{r[o]=String(s);}continue}r[o]=String(s);}return r}async function Bt(n,t,e={}){let r=(t??"").trim();if(r)return r;let o=e.projectRoot??process.cwd(),s=await O(o,n,e.answers??{});return String(s??"").trim()||n}function E(n,t){let e=Number(n);if(!Number.isInteger(e)||e<0)throw new d(`${t} must be a non-negative integer.`,{hint:`Provide a valid ${t}.`,example:`jenkins-cli console ${t==="id"?"123":"last -t 100"}`});return e}function je(n,t){let e=String(t??"").trim();if(!e)return !0;if(!/[*?]/.test(e))return n.includes(e);let s=`^${e.replace(/[$()*+.?[\\\]^{|}]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,".")}$`;try{return new RegExp(s).test(n)}catch{return n.includes(e)}}function Ce(n){let t=n,e=t?.name?String(t.name):"",r=t?.code?String(t.code):"",o=t?.message?String(t.message):String(t??"");if(e==="ExitPromptError"||e==="AbortError"||e==="PromptAbortError"||r==="ABORT_ERR")return !0;let s=o.toLowerCase();return s.includes("cancelled")||s.includes("canceled")}async function Wt(){console.log(y.bold.blue(`
34
34
  \u{1F680} Jenkins CLI - Jenkins Deployment CLI
35
- `));let{config:t,jenkins:n}=await b(),[e,r]=await Promise.all([Oe(),Ie()]),o=()=>{console.log(w.yellow(`
36
- \u{1F44B} Cancelled by user`)),process.exit(130);},s,i={};try{process.prependOnceListener("SIGINT",o);let p=await xt(t.configs,{projectRoot:t.projectRoot}),m=new Set(["branch","modes","mode","triggered_by"]);for(let d of p){let y=String(d?.name??"").trim();if(m.has(y))throw new f(`configs name "${y}" is reserved.`,{hint:"Use another name in your extra prompt config.",example:"name: env"})}let h=await fn.prompt([{type:"list",name:"branch",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u5206\u652F:",choices:e,default:e.indexOf(r)},{type:"checkbox",name:"modes",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u73AF\u5883:",choices:t.modes,validate:d=>d.length===0?"You must select at least one environment":!0},...p]);s={branch:String(h.branch??""),modes:h.modes??[]},i=jt(h,["branch","modes"]);}catch(p){let m=p,h=m?.message?String(m.message):String(m),d=m?.name?String(m.name):"";(d==="ExitPromptError"||h.toLowerCase().includes("cancelled")||h.toLowerCase().includes("canceled"))&&(console.log(w.yellow(`
37
- \u{1F44B} Cancelled by user`)),process.exit(0)),U(new f(`Prompt failed: ${h}`,{hint:d?`Error: ${d}`:""})),process.exit(1);}finally{process.off("SIGINT",o);}console.log();let a=!1,c=()=>{a||(a=!0,console.log());},l=await te();l&&!("triggered_by"in i)&&(i.triggered_by=l);let u=s.modes.map(async p=>{let m=Vt(`Triggering build for ${w.yellow(p)}...`).start();try{let h=await ae(n,t.job,{...i,branch:s.branch,mode:p});c(),m.succeed(`${w.green(p)} - Triggered! Queue: ${h}`);}catch(h){throw c(),m.fail(`${w.red(p)} - ${h.message}`),h}});try{await Promise.all(u);}catch{console.log(w.bold.red(`
35
+ `));let{config:n,jenkins:t}=await h(),[e,r]=await Promise.all([nt(),tt()]),o=()=>{process.exit(130);},s,i=n.job,a={};try{process.prependOnceListener("SIGINT",o);let p=await xe(n.configs,{projectRoot:n.projectRoot}),g=new Set(["branch","modes","mode","triggered_by"]);for(let $ of p){let I=String($?.name??"").trim();if(g.has(I))throw new d(`configs name "${I}" is reserved.`,{hint:"Use another name in your extra prompt config.",example:"name: env"})}let b={type:"list",name:"branch",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u5206\u652F:",choices:e,default:e.indexOf(r)},S=[],L=[],R=[];for(let $ of p){let I=Number($.offset);if(Number.isFinite(I)&&I<=-2){S.push($);continue}if(I===-1){L.push($);continue}R.push($);}let C={};Object.assign(C,await oe.prompt(S,C)),Object.assign(C,await oe.prompt([b],C)),Object.assign(C,await oe.prompt(L,C));let Ke=String(n.projectRoot??"").trim()||process.cwd(),G=await O(Ke,n.modes,C),K=[];if(Array.isArray(G))K=G.map($=>String($).trim()).filter(Boolean);else if(G!=null){let $=String(G).trim();$&&(K=[$]);}K.length===0&&Array.isArray(n.modes)&&(K=n.modes);let sn={type:"checkbox",name:"modes",message:"\u8BF7\u9009\u62E9\u8981\u6253\u5305\u7684\u73AF\u5883:",choices:K,validate:$=>$.length===0?"You must select at least one environment":!0};Object.assign(C,await oe.prompt([sn],C)),Object.assign(C,await oe.prompt(R,C)),s={branch:String(C.branch??""),modes:C.modes??[]},a=Ft(C,["branch","modes"]);let an=await O(Ke,n.job,C),Ye=String(an??"").trim();Ye&&(i=Ye);}catch(p){let g=p,b=g?.message?String(g.message):String(g),S=g?.name?String(g.name):"";Ce(p)&&process.exit(0),q(new d(`Prompt failed: ${b}`,{hint:S?`Error: ${S}`:""})),process.exit(1);}finally{process.off("SIGINT",o);}console.log();let c=!1,l=()=>{c||(c=!0,console.log());},u=await le();u&&!("triggered_by"in a)&&(a.triggered_by=u);let m=s.modes.map(async p=>{let g=en(`Triggering build for ${y.yellow(p)}...`).start();try{let b=await ge(t,i,{...a,branch:s.branch,mode:p});l(),g.succeed(`${y.green(p)} - Triggered! Queue: ${b}`);}catch(b){throw l(),g.fail(`${y.red(p)} - ${b.message}`),b}});try{await Promise.all(m);}catch{console.log(y.bold.red(`
38
36
  \u274C Some builds failed. Check the output above.
39
- `)),process.exit(1);}}function k(t,n){return (n??"").trim()||t}function P(t,n){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new f(`${n} must be a non-negative integer.`,{hint:`Provide a valid ${n}.`,example:`jenkins-cli console ${n==="id"?"123":"last -t 100"}`});return e}function me(t,n){let e=String(n??"").trim();if(!e)return !0;if(!/[*?]/.test(e))return t.includes(e);let s=`^${e.replace(/[$()*+.?[\\\]^{|}]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,".")}$`;try{return new RegExp(s).test(t)}catch{return t.includes(e)}}function St(t){let n=t.command("queue").description("Operations for the build queue");n.command("list").alias("ls").description("List items waiting in the build queue").option("-j, --job <job>","Show only queue items for the specified job").action(async e=>{let{config:r,jenkins:o}=await b(),s=e.job?k(r.job,e.job):void 0,i=await O(o,s);console.table((i??[]).map(a=>({id:a.id,job:a.task?.name,why:a.why})));}),n.command("cancel").description("Cancel a queued build item").argument("<id...>","Queue id(s)").action(async e=>{let{jenkins:r}=await b(),o=Array.isArray(e)?e:[String(e??"")],s=await Promise.all(o.map(async a=>{let c=P(String(a),"id");try{return await Q(r,c),{id:c,ok:!0}}catch(l){return {id:c,ok:!1,message:String(l?.message??l)}}})),i=s.filter(a=>!a.ok);if(i.length===0){console.log(w.green(`Cancelled ${s.length} queue item(s).`));return}console.log(w.yellow(`Cancelled ${s.length-i.length} item(s), failed ${i.length} item(s).`));for(let a of i)console.log(w.red(`- ${a.id}: ${a.message??"Cancel failed"}`));});}function g(t){return {[gn.inspect.custom]:()=>t}}function B(t,n){return String(t??"").padEnd(n," ")}function j(t){return Math.max(0,...t.map(n=>String(n??"").length))}function C(t,n){return g(B(t,n))}function S(t){let n=String(t??""),e=n.trim();if(!e)return g(w.gray("-"));let r=s=>g(s),o=e.toLowerCase();if(o.startsWith("http://")||o.startsWith("https://"))try{let i=(new URL(e).hostname??"").toLowerCase(),a=i==="localhost"||i==="127.0.0.1"||i==="::1",c=/^10\./.test(i)||/^192\.168\./.test(i)||/^127\./.test(i)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(i);return r(a||c?w.cyanBright(n):w.hex("#4EA1FF")(n))}catch{return r(w.hex("#4EA1FF")(n))}return o.startsWith("ws://")||o.startsWith("wss://")?r(w.cyan(n)):o.startsWith("ssh://")||o.startsWith("git+ssh://")||o.startsWith("git@")?r(w.magenta(n)):o.startsWith("file://")?r(w.yellow(n)):o.startsWith("mailto:")?r(w.green(n)):o.startsWith("javascript:")||o.startsWith("data:")?r(w.red(n)):e.startsWith("/")||e.startsWith("./")||e.startsWith("../")?r(w.cyan(n)):/^[a-z0-9.-]+(?::\d+)?(\/|$)/i.test(e)?r(w.blue(n)):r(n)}function $(t){let n=new Date(t),e=r=>String(r).padStart(2,"0");return `${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}:${e(n.getSeconds())}`}function Y(t,n){if(n===!0)return g(w.cyan("BUILDING"));let e=String(t??"").toUpperCase();return g(e?e==="SUCCESS"?w.green(e):e==="ABORTED"?w.gray(e):e==="FAILURE"?w.red(e):e==="UNSTABLE"?w.yellow(e):e==="NOT_BUILT"?w.gray(e):e:"-")}function X(t){let n=String(t??"");if(!n)return g("-");let e=n.endsWith("_anime"),r=e?n.slice(0,-6):n,o=(()=>{switch(r){case"blue":return e?w.blueBright(n):w.blue(n);case"red":return e?w.redBright(n):w.red(n);case"yellow":return e?w.yellowBright(n):w.yellow(n);case"aborted":return w.gray(n);case"disabled":case"notbuilt":case"grey":case"gray":return w.gray(n);default:return n}})();return g(o)}function $t(t){let n=Number(t);if(!Number.isFinite(n)||n<0)return g("-");if(n<1024)return g(`${n} B`);let e=["KB","MB","GB","TB"],r=n,o=-1;for(;r>=1024&&o<e.length-1;)r/=1024,o+=1;let s=r>=10||o===0?r.toFixed(1):r.toFixed(2);return g(`${s} ${e[o]}`)}function pe(t){let n=process.argv,e=0;if(t){let r=n.lastIndexOf(t);r>=0&&(e=r+1);}for(let r=e;r<n.length;r+=1){let o=n[r];if(o==="-j"||o==="--job"){let s=n[r+1];return !s||s.startsWith("-")?"":s}}}function Jt(t){let n=Object.entries(t??{}).filter(([r])=>r);return n.length?(n.sort(([r],[o])=>r.localeCompare(o,"en",{sensitivity:"base"})),n.map(([r,o])=>{if(o===void 0)return `${r}=`;if(o===null)return `${r}=null`;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return `${r}=${o}`;try{return `${r}=${JSON.stringify(o)}`}catch{return `${r}=${String(o)}`}}).join(", ")):"-"}function vt(t){let n=t.command("builds").description("Build operations");n.option("-j, --job <job>","Specify job").option("-n, --limit <n>","Limit","20").action(async e=>{let{config:r,jenkins:o}=await b(),s=e.job??pe("builds")??pe(),i=k(r.job,s),c=(await tt(o,i,{limit:Number(e.limit)})).map(u=>({number:u.number,result:Y(u.result,u.building),building:u.building,"duration(s)":Number((Number(u.duration??0)/1e3).toFixed(3)),date:g($(Number(u.timestamp??0))),parameters:Jt(u.parameters),url:S(String(u.url??""))})),l=j(c.map(u=>u.parameters));console.table(c.map(u=>({...u,parameters:C(u.parameters,l)})));}),n.command("active").description("List active builds").option("-j, --job <job>","Specify job").option("-a, --all","Query all running builds on Jenkins").action(async e=>{let{config:r,jenkins:o}=await b(),s=e.job??pe("active")??pe("builds"),a=((e.all?await se(o):await H(o,k(r.job,s)))??[]).map(l=>({...e.all?{job:g(String(l.job??""))}:{},number:l.number,date:g(l.timestamp?$(Number(l.timestamp)):"-"),parameters:Jt(l.parameters),url:S(String(l.url??""))})),c=j(a.map(l=>l.parameters));console.table(a.map(l=>({...l,parameters:C(l.parameters,c)})));});}function hn(t){let n=String(t?.authorEmail??"").trim(),e=n?n.split("@")[0]??"":"";return e||n}function Pt(t){let n=[];for(let e of t){let r=Number(e?.number),o=Number.isInteger(r)?`#${r}`:g("-"),s=e?.timestamp?$(Number(e.timestamp)):"-",i=e?.changeSet?.items??[];if(!i.length){n.push({build:o,date:g(s),author:g("-"),message:g("-")});continue}for(let a of i){let c=hn(a),l=String(a?.msg??"").trim();n.push({build:o,date:g(s),author:g(c||"-"),message:g(l||"-")});}}return n}function Rt(t){t.command("changes").description("List build changes").argument("[id]").option("-j, --job <job>","Specify job").option("-n, --limit <n>","Limit","20").option("--raw","Output raw changeSet payload").action(async(n,e)=>{let{config:r,jenkins:o}=await b(),s=k(r.job,e.job);if(n){let c=P(n,"id"),l=await le(o,s,c);if(e.raw){console.log(JSON.stringify({build:l.number,changeSet:l.changeSet??{}},null,2));return}console.table(Pt([l]));return}let i=Math.max(1,P(e.limit,"limit")),a=await nt(o,s,{limit:i});if(e.raw){console.log(JSON.stringify(a.map(c=>({build:c.number,changeSet:c.changeSet??{}})),null,2));return}console.table(Pt(a));});}function Nt(){let t=process.argv,n=t.findIndex(r=>r==="-j"||r==="--job");if(n<0)return;let e=t[n+1];return !e||e.startsWith("-")?"":e}function At(t){let n=t.command("console").description("Fetch build console log"),e=async(r,o,s,i)=>{if(!i.follow){let l=await rt(r,o,s);process.stdout.write(l);return}let a=0,c=!0;for(console.log(w.blue(`--- Following log for build #${s} ---`));;)try{let{text:l,newOffset:u,hasMoreData:p}=await dt(r,o,s,a);if(l.length>0&&(process.stdout.write(l),a=u),c&&l.length>0&&(c=!1),l.length>0&&p)continue;if(!p){let h=(await le(r,o,s)).result||"UNKNOWN",d=h==="SUCCESS"?w.green:w.red;console.log(d(`
40
- --- Build Finished: ${h} ---`));break}await new Promise(m=>setTimeout(m,1e3));}catch{await new Promise(l=>setTimeout(l,2e3));}};n.argument("<id>","Build number").option("-j, --job <job>","Specify job").option("--no-follow","Do not follow the build log").action(async(r,o)=>{let{config:s,jenkins:i}=await b(),a=o.job??Nt();if(a==="")throw new f("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli console 123 -j my-job"});let c=k(s.job,a),l=P(r,"id");await e(i,c,l,o);}),n.command("last").description("Fetch the latest build log").option("-j, --job <job>","Specify job").option("-s, --status <status>","success | failed | any","any").option("--no-follow","Do not follow the build log").action(async r=>{let{config:o,jenkins:s}=await b(),i=r.job??Nt();if(i==="")throw new f("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli console last -j my-job -s success"});let a=k(o.job,i),c=String(r.status??"any").toLowerCase();if(!["any","success","failed"].includes(c))throw new f(`Invalid status: ${r.status}.`,{hint:"Use success | failed | any.",example:"jenkins-cli console last -s success"});let l=await ce(s,a),u=c==="success"?l?.lastSuccessfulBuild:c==="failed"?l?.lastFailedBuild:l?.lastBuild,p=Number(u?.number);if(!p){let m=c==="success"?"successful":c==="failed"?"failed":"last";console.log(w.yellow(`No ${m} build found for job: ${a}. Try checking the job name or status filter.`));return}await e(s,a,p,r);});}function Bt(t){t.command("stop").description("Clear queued builds and stop running builds").argument("[id]","Build number").option("-j, --job <job>","Specify Jenkins job").option("-a, --all","Cancel queued items for this job and stop all running builds for it").option("-A, --ALL","Cancel all queued items and stop all running builds on Jenkins").action(async(n,e)=>{let{config:r,jenkins:o}=await b(),s=k(r.job,e.job);if(e.ALL){let[i,a]=await Promise.all([O(o),se(o)]),c=(i??[]).map(u=>Number(u.id)).filter(u=>!Number.isNaN(u)),l=(a??[]).map(u=>({number:Number(u.number),job:String(u.job??"")})).filter(u=>u.job&&!Number.isNaN(u.number));for(let u of c)await Q(o,u);for(let u of l)await G(o,u.job,u.number);console.log(w.green(`Requested: cancelled ${c.length} queue item(s), stopped ${l.length} running build(s).`));return}if(e.all){let[i,a]=await Promise.all([O(o,s),H(o,s)]),c=(i??[]).map(u=>Number(u.id)).filter(u=>!Number.isNaN(u)),l=(a??[]).map(u=>Number(u.number)).filter(u=>!Number.isNaN(u));for(let u of c)await Q(o,u);for(let u of l)await G(o,s,u);console.log(w.green(`Requested: cancelled ${c.length} queue item(s), stopped ${l.length} running build(s).`));return}if(!n){console.log(w.red("Missing build id. Provide <id> or use -a/--all."));return}await G(o,s,P(n,"id")),console.log(w.green("Stop requested"));});}function Wt(t){t.command("params").description("Show job parameter definitions").option("-j, --job <job>","Specify job").action(async n=>{let{config:e,jenkins:r}=await b(),o=k(e.job,n.job),s=await ot(r,o),i=j(s.map(a=>a?.name));console.table((s??[]).map(a=>({name:C(a?.name??"",i),type:g(String(a?.type??"")),description:g(String(a?.description??"")),default:g(a?.default===void 0?"-":String(a.default)),choices:g(Array.isArray(a?.choices)?a.choices.join(", "):a?.choices??"-")})));});}function Et(t){t.command("me").description("Show Jenkins user info for the current token").option("--raw","Print raw response").action(async n=>{let{jenkins:e}=await b(),r=await Ze(e);if(n.raw){console.log(r&&typeof r=="object"?JSON.stringify(r,null,2):String(r));return}let o=r&&typeof r=="object"?r:{value:r},s=(u,p)=>{let m=u.length;if(m>=p)return u;let h=p-m,d=Math.floor(h/2),y=h-d;return `${" ".repeat(d)}${u}${" ".repeat(y)}`},i=o.name??o.fullName??o.id??"",a=i==null?"":String(i),c=Math.max(20,a.length),l={};l.name=g(s(a,c));for(let u of Object.keys(o).sort((p,m)=>p.localeCompare(m,"en"))){if(u==="name")continue;let p=o[u],m=u.toLowerCase();if((m==="url"||m.endsWith("url")||m.includes("url"))&&(typeof p=="string"||typeof p=="number")){l[u]=S(String(p));continue}let d=p==null?"":typeof p=="object"?JSON.stringify(p):String(p);l[u]=g(d);}console.table([l]);});}function Ft(t){let n=t.command("config").description("Show Jenkins job configuration");n.command("show").description("Show job configuration").option("-j, --job <job>","Specify job").option("-f, --format <format>","Output format: xml or json","xml").action(async e=>{let{config:r,jenkins:o}=await b(),s=k(r.job,e.job),i=String(e.format??"xml").toLowerCase();if(i!=="xml"&&i!=="json")throw new f(`Invalid format: ${e.format}.`,{hint:"Use xml or json.",example:"jenkins-cli config show -f json"});let a=await Pe(o,s);if(i==="xml"){process.stdout.write(a);return}let l=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(a);console.log(JSON.stringify(l,null,2));}),n.command("backup").description("Backup job configuration to files").requiredOption("-d, --destination <path>","Destination folder").option("-a, --all","Backup all jobs").option("-j, --job <job>","Specify job").option("--filter <pattern>","Filter jobs by name (supports glob)").action(async e=>{let{config:r,jenkins:o}=await b(),s=String(e.destination??"").trim();if(!s)throw new f("Destination is required.",{hint:"Provide a destination folder with -d or --destination.",example:"jenkins-cli config backup -d ./jenkins-backup"});if(e.all&&e.filter)throw new f("Options --all and --filter are mutually exclusive.",{hint:"Use either -a/--all or --filter, not both.",example:"jenkins-cli config backup -d ./jenkins-backup -a"});let i=String(e.filter??"").trim(),a=e.all?await W(o):i?(await W(o)).filter(l=>me(String(l.name??""),i)):[{name:k(r.job,e.job)}];if(a.length===0)throw new f(`No jobs matched filter: ${i}`,{hint:"Check the pattern or remove --filter to use the default job.",example:"jenkins-cli config backup -d ./jenkins-backup --filter 'remote-*'"});await promises.mkdir(s,{recursive:!0});let c=[];for(let l of a){let u=String(l?.name??"").trim();if(!u)continue;let p=await Pe(o,u),m=V.join(s,u,"config.xml");await promises.mkdir(V.dirname(m),{recursive:!0}),await promises.writeFile(m,p),c.push(m);}console.log(`Backup completed. ${c.length} file(s) saved to ${V.resolve(s)}`);});}function Ut(t){let n=t.command("job").description("Job operations");n.command("list").alias("ls").description("List all jobs").option("--search <keyword>","Filter by name (supports glob)").action(async e=>{let{jenkins:r}=await b(),o=await W(r),s=(e.search??"").trim(),i=s?o.filter(l=>me(String(l.name??""),s)):o;i.sort((l,u)=>String(l?.name??"").localeCompare(String(u?.name??""),"en",{sensitivity:"base"}));let a=j(i.map(l=>l?.name)),c=j(i.map(l=>l?.url));console.table((i??[]).map(l=>({name:C(l.name??"",a),color:X(l.color),url:S(B(l.url??"",c))})));}),n.command("info").description("Show job info").option("-j, --job <job>","Specify job").option("--json","Output raw JSON").action(async e=>{let{config:r,jenkins:o}=await b(),s=k(r.job,e.job),i=await ce(o,s);if(e.json){console.log(JSON.stringify(i,null,2));return}let a=i?.lastBuild,c=i?.lastCompletedBuild,l=Array.isArray(i?.healthReport)?i.healthReport:[];console.table([{name:g(String(i?.name??"")),url:S(String(i?.url??"")),color:X(i?.color),buildable:i?.buildable,inQueue:i?.inQueue,nextBuildNumber:i?.nextBuildNumber,healthScore:l[0]?.score??"-",lastBuild:g(a?.number?`#${a.number}`:"-"),lastResult:Y(a?.result,a?.building),"lastDuration(s)":a?.duration===void 0?"-":Number((Number(a.duration)/1e3).toFixed(3)),lastDate:g(a?.timestamp?$(Number(a.timestamp)):"-"),lastCompleted:g(c?.number?`#${c.number}`:"-"),lastCompletedResult:Y(c?.result,!1),lastCompletedDate:g(c?.timestamp?$(Number(c.timestamp)):"-")}]);});}function yn(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function kn(t){let n=t.split("=");if(n.length<2)throw new f(`Invalid --param: "${t}".`,{hint:"Use the format key=value.",example:"jenkins-cli build -b origin/main -m dev --param foo=bar"});let e=n[0].trim(),r=n.slice(1).join("=").trim();if(!e)throw new f(`Invalid --param: "${t}". Key is empty.`,{hint:'Provide a non-empty key before "=".',example:"jenkins-cli build -b origin/main -m dev --param foo=bar"});return {key:e,value:r}}function Lt(t){t.command("build").description("Trigger Jenkins builds non-interactively").requiredOption("-b, --branch <branch>","Branch (e.g., origin/develop)").option("-m, --mode <mode>","Deployment environment (repeatable or comma-separated: -m dev -m uat / -m dev,uat)",(n,e)=>e.concat(yn(n)),[]).option("--param <key=value>","Extra parameters (repeatable, e.g., --param foo=bar)",(n,e)=>e.concat(n),[]).option("-j, --job <job>","Specify job").action(async n=>{let{config:e,jenkins:r}=await b(),o=k(e.job,n.job),s=String(n.branch??"").trim();if(!s)throw new f("branch is required.",{hint:"Pass a branch with -b or --branch.",example:"jenkins-cli build -b origin/develop -m dev"});let i=(n.mode??[]).map(String).map(h=>h.trim()).filter(Boolean),a=Array.from(new Set(i));if(a.length===0)throw new f("mode is required.",{hint:"Pass at least one -m/--mode.",example:"jenkins-cli build -b origin/develop -m dev -m uat"});let c={};for(let h of n.param??[]){let{key:d,value:y}=kn(String(h));c[d]=y;}let l=await te();l&&!("triggered_by"in c)&&(c.triggered_by=l),console.log();let u=!1,p=()=>{u||(u=!0,console.log());},m=a.map(async h=>{let d=Vt(`Triggering build for ${w.yellow(h)}...`).start();try{let y=await ae(r,o,{...c,branch:s,mode:h});p(),d.succeed(`${w.green(h)} - Triggered! Queue: ${y}`);}catch(y){throw p(),d.fail(`${w.red(h)} - ${y.message}`),y}});try{await Promise.all(m);}catch{console.log(w.bold.red(`
37
+ `)),process.exit(1);}}function Ut(n){let t=n.command("queue").description("Operations for the build queue");t.command("list").alias("ls").description("List items waiting in the build queue").option("-j, --job <job>","Show only queue items for the specified job").action(async e=>{let{config:r,jenkins:o}=await h(),s=e.job?await Bt(r.job,e.job,{projectRoot:r.projectRoot}):void 0,i=await H(o,s);console.table((i??[]).map(a=>({id:a.id,job:a.task?.name,why:a.why})));}),t.command("cancel").description("Cancel a queued build item").argument("<id...>","Queue id(s)").action(async e=>{let{jenkins:r}=await h(),o=Array.isArray(e)?e:[String(e??"")],s=await Promise.all(o.map(async a=>{let c=E(String(a),"id");try{return await te(r,c),{id:c,ok:!0}}catch(l){return {id:c,ok:!1,message:String(l?.message??l)}}})),i=s.filter(a=>!a.ok);if(i.length===0){console.log(y.green(`Cancelled ${s.length} queue item(s).`));return}console.log(y.yellow(`Cancelled ${s.length-i.length} item(s), failed ${i.length} item(s).`));for(let a of i)console.log(y.red(`- ${a.id}: ${a.message??"Cancel failed"}`));});}function w(n){return {[En.inspect.custom]:()=>n}}function U(n,t){return String(n??"").padEnd(t," ")}function j(n){return Math.max(0,...n.map(t=>String(t??"").length))}function v(n,t){return w(U(n,t))}function J(n){let t=String(n??""),e=t.trim();if(!e)return w(y.gray("-"));let r=s=>w(s),o=e.toLowerCase();if(o.startsWith("http://")||o.startsWith("https://"))try{let i=(new URL(e).hostname??"").toLowerCase(),a=i==="localhost"||i==="127.0.0.1"||i==="::1",c=/^10\./.test(i)||/^192\.168\./.test(i)||/^127\./.test(i)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(i);return r(a||c?y.cyanBright(t):y.hex("#4EA1FF")(t))}catch{return r(y.hex("#4EA1FF")(t))}return o.startsWith("ws://")||o.startsWith("wss://")?r(y.cyan(t)):o.startsWith("ssh://")||o.startsWith("git+ssh://")||o.startsWith("git@")?r(y.magenta(t)):o.startsWith("file://")?r(y.yellow(t)):o.startsWith("mailto:")?r(y.green(t)):o.startsWith("javascript:")||o.startsWith("data:")?r(y.red(t)):e.startsWith("/")||e.startsWith("./")||e.startsWith("../")?r(y.cyan(t)):/^[a-z0-9.-]+(?::\d+)?(\/|$)/i.test(e)?r(y.blue(t)):r(t)}function P(n){let t=new Date(n),e=r=>String(r).padStart(2,"0");return `${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function se(n,t){if(t===!0)return w(y.cyan("BUILDING"));let e=String(n??"").toUpperCase();return w(e?e==="SUCCESS"?y.green(e):e==="ABORTED"?y.gray(e):e==="FAILURE"?y.red(e):e==="UNSTABLE"?y.yellow(e):e==="NOT_BUILT"?y.gray(e):e:"-")}function ae(n){let t=String(n??"");if(!t)return w("-");let e=t.endsWith("_anime"),r=e?t.slice(0,-6):t,o=(()=>{switch(r){case"blue":return e?y.blueBright(t):y.blue(t);case"red":return e?y.redBright(t):y.red(t);case"yellow":return e?y.yellowBright(t):y.yellow(t);case"aborted":return y.gray(t);case"disabled":case"notbuilt":case"grey":case"gray":return y.gray(t);default:return t}})();return w(o)}function Lt(n){let t=Number(n);if(!Number.isFinite(t)||t<0)return w("-");if(t<1024)return w(`${t} B`);let e=["KB","MB","GB","TB"],r=t,o=-1;for(;r>=1024&&o<e.length-1;)r/=1024,o+=1;let s=r>=10||o===0?r.toFixed(1):r.toFixed(2);return w(`${s} ${e[o]}`)}var Se=64;function Bn(n){return n!=null&&typeof n=="object"?n.value??n.name??n:n}function Ot(n){let t=String(n?.toString?.()??"").trim();if(!t)return "";let e=t.indexOf("=>");if(e>=0){let s=t.slice(e+2).trim();return s.startsWith("{")&&s.endsWith("}")&&(s=s.slice(1,-1)),s}let r=t.indexOf("{"),o=t.lastIndexOf("}");return r>=0&&o>r?t.slice(r+1,o):""}function Vt(n){let t=new Set,e,r=/\b(\d+)\b/g;for(;e=r.exec(n);){let s=parseInt(e[1],10);Number.isFinite(s)&&t.add(s);}let o=Array.from(t).sort((s,i)=>s-i);return o.length>Se?o.slice(0,Se):o}function Wn(n,t){let e=String(n.type??"").toLowerCase();if(e==="confirm")return [!0,!1];if(e==="number"){let s=n,i=typeof s.min=="number"&&Number.isFinite(s.min)?s.min:null,a=typeof s.max=="number"&&Number.isFinite(s.max)?s.max:null;if(i!=null&&a!=null)return i===a?[i]:i<a?[i,a]:[a,i];if(i!=null)return [i,i+1];if(a!=null)return [a-1,a];if(t){let c=Vt(Ot(t));if(c.length)return c}return [0,1,99,100,101]}let r=Array.isArray(n.choices)?n.choices:null;if(!r?.length)return null;let o=r.map(Bn);if(e==="list"||e==="rawlist")return o;if(e==="checkbox"){let s=[[]];return o.forEach(i=>s.push([i])),o.length<=4&&s.push(o),s}return null}async function Un(n,t){let e=n.when;if(e===void 0||typeof e=="boolean")return e!==!1;if(typeof e!="function")return !0;try{return !!await Promise.resolve(e(t))}catch{return !0}}async function Ln(n,t,e){let r=await xe(n.configs,{projectRoot:t}),o=[{}];for(let s of r){let i=String(s.name??"").trim();if(!i)continue;let a=Wn(s,e);if(!a?.length||o.length*a.length>Se)continue;let c=[];for(let l of o){if(!await Un(s,l)){c.push(l);continue}for(let u of a)c.push({...l,[i]:u});}c.length&&(o=c);}return o}function Tn(n){let t=new Map,e=/answers\.(\w+)\s*===\s*(\d+)/g,r;for(;r=e.exec(n);){let s=r[1],i=parseInt(r[2],10);Number.isFinite(i)&&(t.has(s)||t.set(s,new Set),t.get(s).add(i));}let o=new Map;return t.forEach((s,i)=>o.set(i,Array.from(s).sort((a,c)=>a-c))),o}function On(n){return n.split(`
38
+ `).filter(t=>{let e=t.trim();return e&&!e.startsWith("//")}).join(`
39
+ `)}function Vn(n){let t=Ot(n);if(!t)return [];t=On(t);let e=Vt(t),r=Tn(t),o=new Set,s=/return\s+([^;]+?)(?=;|$)/gm,i=/`((?:[^`\\]|\\.|\$\{[^}]*\})*)`/g,a=/\$\{\s*answers\.(\w+)\s*\}/,c;for(;c=s.exec(t);){let l=c[1];for(let f of Tt(l))f&&o.add(f);let u;for(;u=i.exec(l);){let f=u[1];if(!f.includes("${"))continue;let m=f.match(a),p=m&&r.has(m[1])?r.get(m[1]):m?[]:e,g=f.split(/\$\{[^}]*\}/);if(g.length<2)continue;let b=g[0]??"",S=g.slice(1).join("");for(let L of p){let R=b+String(L)+S;R&&o.add(R);}}}if(o.size===0&&!t.includes("{"))for(let l of Tt(t))l&&o.add(l);return Array.from(o).sort((l,u)=>l.localeCompare(u,"en",{sensitivity:"base"}))}function Tt(n){let t=[],e=/(['"`])((?:\\.|(?!\1).)*)\1/g,r;for(;r=e.exec(n);)if(!(r[1]==="`"&&r[2].includes("${")))try{let o=r[1]==="`"?r[2]:JSON.parse(r[1]+r[2]+r[1]);String(o).trim()&&t.push(String(o).trim());}catch{String(r[2]??"").trim()&&t.push(String(r[2]).trim());}return t}async function In(n,t,e){let r=new Set;for(let i of Vn(n))r.add(i);let o=await Ln(t,e,n),s=async i=>{let a=await Promise.resolve(n(i)),c=typeof a=="string"?String(a).trim():"";return c&&r.add(c),r.size>=Se};if(!o.length)await s({});else for(let i of o)if(await s(i))break;return Array.from(r).sort((i,a)=>i.localeCompare(a,"en",{sensitivity:"base"}))}async function k(n,t){if(t==="")throw new d("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli job info -j my-job"});let e=String(t??"").trim();if(e)return e;let r=String(n.projectRoot??"").trim()||process.cwd(),o=await Et(r,n.job);if(o.isRef&&o.isFunction){let i=await In(o.value,n,r);if(!i.length)throw new d("Job choices not found from config reference.",{hint:"Ensure the job function returns a string (job name).",example:'export function dynamicJob(answers) { return "my-job" }'});if(i.length===1)return i[0];let{job:a}=await oe.prompt([{type:"list",name:"job",message:"\u8BF7\u9009\u62E9\u8981\u64CD\u4F5C\u7684 Job:",choices:i}]);return String(a??"").trim()}let s=await O(r,n.job,{});return String(s??n.job??"").trim()||String(n.job??"")}function $e(n){let t=process.argv,e=0;if(n){let r=t.lastIndexOf(n);r>=0&&(e=r+1);}for(let r=e;r<t.length;r+=1){let o=t[r];if(o==="-j"||o==="--job"){let s=t[r+1];return !s||s.startsWith("-")?"":s}}}function It(n){let t=Object.entries(n??{}).filter(([r])=>r);return t.length?(t.sort(([r],[o])=>r.localeCompare(o,"en",{sensitivity:"base"})),t.map(([r,o])=>{if(o===void 0)return `${r}=`;if(o===null)return `${r}=null`;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return `${r}=${o}`;try{return `${r}=${JSON.stringify(o)}`}catch{return `${r}=${String(o)}`}}).join(", ")):"-"}function qt(n){let t=n.command("builds").description("Build operations");t.option("-j, --job <job>","Specify job").option("-n, --limit <n>","Limit","20").action(async e=>{let{config:r,jenkins:o}=await h(),s=e.job??$e("builds")??$e(),i=await k(r,s),c=(await dt(o,i,{limit:Number(e.limit)})).map(u=>({number:u.number,result:se(u.result,u.building),building:u.building,"duration(s)":Number((Number(u.duration??0)/1e3).toFixed(3)),date:w(P(Number(u.timestamp??0))),parameters:It(u.parameters),url:J(String(u.url??""))})),l=j(c.map(u=>u.parameters));console.table(c.map(u=>({...u,parameters:v(u.parameters,l)})));}),t.command("active").description("List active builds").option("-j, --job <job>","Specify job").option("-a, --all","Query all running builds on Jenkins").action(async e=>{let{config:r,jenkins:o}=await h(),s=e.job??$e("active")??$e("builds"),i=await k(r,s),c=((e.all?await de(o):await ee(o,i))??[]).map(u=>({...e.all?{job:w(String(u.job??""))}:{},number:u.number,date:w(u.timestamp?P(Number(u.timestamp)):"-"),parameters:It(u.parameters),url:J(String(u.url??""))})),l=j(c.map(u=>u.parameters));console.table(c.map(u=>({...u,parameters:v(u.parameters,l)})));});}function qn(n){let t=String(n?.authorEmail??"").trim(),e=t?t.split("@")[0]??"":"";return e||t}function Dt(n){let t=[];for(let e of n){let r=Number(e?.number),o=Number.isInteger(r)?`#${r}`:w("-"),s=e?.timestamp?P(Number(e.timestamp)):"-",i=e?.changeSet?.items??[];if(!i.length){t.push({build:o,date:w(s),author:w("-"),message:w("-")});continue}for(let a of i){let c=qn(a),l=String(a?.msg??"").trim();t.push({build:o,date:w(s),author:w(c||"-"),message:w(l||"-")});}}return t}function Mt(n){n.command("changes").description("List build changes").argument("[id]").option("-j, --job <job>","Specify job").option("-n, --limit <n>","Limit","20").option("--raw","Output raw changeSet payload").action(async(t,e)=>{let{config:r,jenkins:o}=await h(),s=await k(r,e.job);if(t){let c=E(t,"id"),l=await he(o,s,c);if(e.raw){console.log(JSON.stringify({build:l.number,changeSet:l.changeSet??{}},null,2));return}console.table(Dt([l]));return}let i=Math.max(1,E(e.limit,"limit")),a=await gt(o,s,{limit:i});if(e.raw){console.log(JSON.stringify(a.map(c=>({build:c.number,changeSet:c.changeSet??{}})),null,2));return}console.table(Dt(a));});}function zt(){let n=process.argv,t=n.findIndex(r=>r==="-j"||r==="--job");if(t<0)return;let e=n[t+1];return !e||e.startsWith("-")?"":e}function _t(n){let t=n.command("console").description("Fetch build console log"),e=async(r,o,s,i)=>{if(!i.follow){let l=await wt(r,o,s);process.stdout.write(l);return}let a=0,c=!0;for(console.log(y.blue(`--- Following log for ${o} build #${s} ---`));;)try{let{text:l,newOffset:u,hasMoreData:f}=await Jt(r,o,s,a);if(l.length>0&&(process.stdout.write(l),a=u),c&&l.length>0&&(c=!1),l.length>0&&f)continue;if(!f){let p=(await he(r,o,s)).result||"UNKNOWN",g=p==="SUCCESS"?y.green:y.red;console.log(g(`
40
+ --- Build Finished: ${p} ---`));break}await new Promise(m=>setTimeout(m,1e3));}catch{await new Promise(l=>setTimeout(l,2e3));}};t.argument("<id>","Build number").option("-j, --job <job>","Specify job").option("--no-follow","Do not follow the build log").action(async(r,o)=>{let{config:s,jenkins:i}=await h(),a=o.job??zt();if(a==="")throw new d("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli console 123 -j my-job"});let c=await k(s,a),l=E(r,"id");await e(i,c,l,o);}),t.command("last").description("Fetch the latest build log").option("-j, --job <job>","Specify job").option("-s, --status <status>","success | failed | any","any").option("--no-follow","Do not follow the build log").action(async r=>{let{config:o,jenkins:s}=await h(),i=r.job??zt();if(i==="")throw new d("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli console last -j my-job -s success"});let a=await k(o,i),c=String(r.status??"any").toLowerCase();if(!["any","success","failed"].includes(c))throw new d(`Invalid status: ${r.status}.`,{hint:"Use success | failed | any.",example:"jenkins-cli console last -s success"});let l=await we(s,a),u=c==="success"?l?.lastSuccessfulBuild:c==="failed"?l?.lastFailedBuild:l?.lastBuild,f=Number(u?.number);if(!f){let m=c==="success"?"successful":c==="failed"?"failed":"last";console.log(y.yellow(`No ${m} build found for job: ${a}. Try checking the job name or status filter.`));return}await e(s,a,f,r);});}function Ht(n){n.command("stop").description("Clear queued builds and stop running builds").argument("[id]","Build number").option("-j, --job <job>","Specify Jenkins job").option("-a, --all","Cancel queued items for this job and stop all running builds for it").option("-A, --ALL","Cancel all queued items and stop all running builds on Jenkins").action(async(t,e)=>{let{config:r,jenkins:o}=await h(),s=await k(r,e.job);if(e.ALL){let[i,a]=await Promise.all([H(o),de(o)]),c=(i??[]).map(u=>Number(u.id)).filter(u=>!Number.isNaN(u)),l=(a??[]).map(u=>({number:Number(u.number),job:String(u.job??"")})).filter(u=>u.job&&!Number.isNaN(u.number));for(let u of c)await te(o,u);for(let u of l)await ne(o,u.job,u.number);console.log(y.green(`Requested: cancelled ${c.length} queue item(s), stopped ${l.length} running build(s).`));return}if(e.all){let[i,a]=await Promise.all([H(o,s),ee(o,s)]),c=(i??[]).map(u=>Number(u.id)).filter(u=>!Number.isNaN(u)),l=(a??[]).map(u=>Number(u.number)).filter(u=>!Number.isNaN(u));for(let u of c)await te(o,u);for(let u of l)await ne(o,s,u);console.log(y.green(`Requested: cancelled ${c.length} queue item(s), stopped ${l.length} running build(s).`));return}if(!t){console.log(y.red("Missing build id. Provide <id> or use -a/--all."));return}await ne(o,s,E(t,"id")),console.log(y.green("Stop requested"));});}function Qt(n){n.command("params").description("Show job parameter definitions").option("-j, --job <job>","Specify job").action(async t=>{let{config:e,jenkins:r}=await h(),o=await k(e,t.job),s=await ht(r,o),i=j(s.map(a=>a?.name));console.table((s??[]).map(a=>({name:v(a?.name??"",i),type:w(String(a?.type??"")),description:w(String(a?.description??"")),default:w(a?.default===void 0?"-":String(a.default)),choices:w(Array.isArray(a?.choices)?a.choices.join(", "):a?.choices??"-")})));});}function Gt(n){n.command("me").description("Show Jenkins user info for the current token").option("--raw","Print raw response").action(async t=>{let{jenkins:e}=await h(),r=await ft(e);if(t.raw){console.log(r&&typeof r=="object"?JSON.stringify(r,null,2):String(r));return}let o=r&&typeof r=="object"?r:{value:r},s=(u,f)=>{let m=u.length;if(m>=f)return u;let p=f-m,g=Math.floor(p/2),b=p-g;return `${" ".repeat(g)}${u}${" ".repeat(b)}`},i=o.name??o.fullName??o.id??"",a=i==null?"":String(i),c=Math.max(20,a.length),l={};l.name=w(s(a,c));for(let u of Object.keys(o).sort((f,m)=>f.localeCompare(m,"en"))){if(u==="name")continue;let f=o[u],m=u.toLowerCase();if((m==="url"||m.endsWith("url")||m.includes("url"))&&(typeof f=="string"||typeof f=="number")){l[u]=J(String(f));continue}let g=f==null?"":typeof f=="object"?JSON.stringify(f):String(f);l[u]=w(g);}console.table([l]);});}function Kt(n){let t=n.command("config").description("Show Jenkins job configuration");t.command("show").description("Show job configuration").option("-j, --job <job>","Specify job").option("-f, --format <format>","Output format: xml or json","xml").action(async e=>{let{config:r,jenkins:o}=await h(),s=await k(r,e.job),i=String(e.format??"xml").toLowerCase();if(i!=="xml"&&i!=="json")throw new d(`Invalid format: ${e.format}.`,{hint:"Use xml or json.",example:"jenkins-cli config show -f json"});let a=await Me(o,s);if(i==="xml"){process.stdout.write(a);return}let l=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(a);console.log(JSON.stringify(l,null,2));}),t.command("backup").description("Backup job configuration to files").requiredOption("-d, --destination <path>","Destination folder").option("-a, --all","Backup all jobs").option("-j, --job <job>","Specify job").option("--filter <pattern>","Filter jobs by name (supports glob)").action(async e=>{let{config:r,jenkins:o}=await h(),s=String(e.destination??"").trim();if(!s)throw new d("Destination is required.",{hint:"Provide a destination folder with -d or --destination.",example:"jenkins-cli config backup -d ./jenkins-backup"});if(e.all&&e.filter)throw new d("Options --all and --filter are mutually exclusive.",{hint:"Use either -a/--all or --filter, not both.",example:"jenkins-cli config backup -d ./jenkins-backup -a"});let i=String(e.filter??"").trim(),a=e.all?await T(o):i?(await T(o)).filter(l=>je(String(l.name??""),i)):[{name:await k(r,e.job)}];if(a.length===0)throw new d(`No jobs matched filter: ${i}`,{hint:"Check the pattern or remove --filter to use the default job.",example:"jenkins-cli config backup -d ./jenkins-backup --filter 'remote-*'"});await promises.mkdir(s,{recursive:!0});let c=[];for(let l of a){let u=String(l?.name??"").trim();if(!u)continue;let f=await Me(o,u),m=z.join(s,u,"config.xml");await promises.mkdir(z.dirname(m),{recursive:!0}),await promises.writeFile(m,f),c.push(m);}console.log(`Backup completed. ${c.length} file(s) saved to ${z.resolve(s)}`);});}function Yt(n){let t=n.command("job").description("Job operations");t.command("list").alias("ls").description("List all jobs").option("--search <keyword>","Filter by name (supports glob)").action(async e=>{let{jenkins:r}=await h(),o=await T(r),s=(e.search??"").trim(),i=s?o.filter(l=>je(String(l.name??""),s)):o;i.sort((l,u)=>String(l?.name??"").localeCompare(String(u?.name??""),"en",{sensitivity:"base"}));let a=j(i.map(l=>l?.name)),c=j(i.map(l=>l?.url));console.table((i??[]).map(l=>({name:v(l.name??"",a),color:ae(l.color),url:J(U(l.url??"",c))})));}),t.command("info").description("Show job info").option("-j, --job <job>","Specify job").option("--json","Output raw JSON").action(async e=>{let{config:r,jenkins:o}=await h(),s=await k(r,e.job),i=await we(o,s);if(e.json){console.log(JSON.stringify(i,null,2));return}let a=i?.lastBuild,c=i?.lastCompletedBuild,l=Array.isArray(i?.healthReport)?i.healthReport:[];console.table([{name:w(String(i?.name??"")),url:J(String(i?.url??"")),color:ae(i?.color),buildable:i?.buildable,inQueue:i?.inQueue,nextBuildNumber:i?.nextBuildNumber,healthScore:l[0]?.score??"-",lastBuild:w(a?.number?`#${a.number}`:"-"),lastResult:se(a?.result,a?.building),"lastDuration(s)":a?.duration===void 0?"-":Number((Number(a.duration)/1e3).toFixed(3)),lastDate:w(a?.timestamp?P(Number(a.timestamp)):"-"),lastCompleted:w(c?.number?`#${c.number}`:"-"),lastCompletedResult:se(c?.result,!1),lastCompletedDate:w(c?.timestamp?P(Number(c.timestamp)):"-")}]);});}function zn(n){return n.split(",").map(t=>t.trim()).filter(Boolean)}function _n(n){let t=n.split("=");if(t.length<2)throw new d(`Invalid --param: "${n}".`,{hint:"Use the format key=value.",example:"jenkins-cli build -b origin/main -m dev --param foo=bar"});let e=t[0].trim(),r=t.slice(1).join("=").trim();if(!e)throw new d(`Invalid --param: "${n}". Key is empty.`,{hint:'Provide a non-empty key before "=".',example:"jenkins-cli build -b origin/main -m dev --param foo=bar"});return {key:e,value:r}}function Xt(n){n.command("build").description("Trigger Jenkins builds non-interactively").requiredOption("-b, --branch <branch>","Branch (e.g., origin/develop)").option("-m, --mode <mode>","Deployment environment (repeatable or comma-separated: -m dev -m uat / -m dev,uat)",(t,e)=>e.concat(zn(t)),[]).option("--param <key=value>","Extra parameters (repeatable, e.g., --param foo=bar)",(t,e)=>e.concat(t),[]).option("-j, --job <job>","Specify job").action(async t=>{let{config:e,jenkins:r}=await h(),o=await k(e,t.job),s=String(t.branch??"").trim();if(!s)throw new d("branch is required.",{hint:"Pass a branch with -b or --branch.",example:"jenkins-cli build -b origin/develop -m dev"});let i=(t.mode??[]).map(String).map(p=>p.trim()).filter(Boolean),a=Array.from(new Set(i));if(a.length===0)throw new d("mode is required.",{hint:"Pass at least one -m/--mode.",example:"jenkins-cli build -b origin/develop -m dev -m uat"});let c={};for(let p of t.param??[]){let{key:g,value:b}=_n(String(p));c[g]=b;}let l=await le();l&&!("triggered_by"in c)&&(c.triggered_by=l),console.log();let u=!1,f=()=>{u||(u=!0,console.log());},m=a.map(async p=>{let g=en(`Triggering build for ${y.yellow(p)}...`).start();try{let b=await ge(r,o,{...c,branch:s,mode:p});f(),g.succeed(`${y.green(p)} - Triggered! Queue: ${b}`);}catch(b){throw f(),g.fail(`${y.red(p)} - ${b.message}`),b}});try{await Promise.all(m);}catch{console.log(y.bold.red(`
41
41
  \u274C Some builds failed. Check the output above.
42
- `)),process.exit(1);}});}function Tt(t){let n=t.command("view").description("View operations");n.command("list").alias("ls").description("List all views").option("--raw","Output raw JSON").action(async e=>{let{jenkins:r}=await b(),o=await K(r,{raw:e.raw});if(e.raw){console.log(JSON.stringify(o,null,2));return}o.sort((c,l)=>String(c?.name??"").localeCompare(String(l?.name??""),"en",{sensitivity:"base"}));let s=(o??[]).map(c=>({name:String(c?.name??""),url:String(c?.url??"")})),i=j(s.map(c=>c.name)),a=j(s.map(c=>c.url));console.table(s.map(c=>({name:C(c.name,i),url:S(B(c.url,a))})));}),n.command("show").description("Show jobs in a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await b(),o=await q(r,e);if(!o.length){console.log("No jobs found in this view.");return}o.sort((a,c)=>String(a?.name??"").localeCompare(String(c?.name??""),"en",{sensitivity:"base"}));let s=j(o.map(a=>a?.name)),i=j(o.map(a=>a?.url));console.table(o.map(a=>({name:C(a.name??"",s),color:X(a.color),url:S(B(a.url??"",i))})));}),n.command("add").description("Add a job to a view").argument("<view>","View name").argument("<job>","Job name").action(async(e,r)=>{let{jenkins:o}=await b();if((await q(o,e)).some(i=>i.name===r)){console.log(w.yellow(`Job "${r}" is already in view "${e}".`));return}await $e(o,e,r),console.log(w.green(`Job "${r}" added to view "${e}".`));}),n.command("remove").alias("rm").description("Remove a job from a view").argument("<view>","View name").argument("<job>","Job name").action(async(e,r)=>{let{jenkins:o}=await b();if(!(await q(o,e)).some(i=>i.name===r))throw new f(`Job "${r}" is not in view "${e}".`,{hint:'Use "jc view show <name>" to see jobs in this view.'});await Je(o,e,r),console.log(w.green(`Job "${r}" removed from view "${e}".`));}),n.command("edit").description("Edit jobs in a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await b(),[o,s]=await Promise.all([W(r),q(r,e)]);if(!o.length){console.log("No jobs found.");return}o.sort((m,h)=>String(m?.name??"").localeCompare(String(h?.name??""),"en",{sensitivity:"base"}));let i=new Set(s.map(m=>String(m?.name??"").trim())),a=o.map(m=>String(m?.name??"").trim()).filter(Boolean).map(m=>({name:m,checked:i.has(m)})),c=await fn.prompt([{type:"checkbox",name:"jobs",message:`Select jobs for view "${e}"`,choices:a,pageSize:20}]),l=new Set((c.jobs??[]).map(m=>String(m).trim())),u=[...l].filter(m=>!i.has(m)),p=[...i].filter(m=>m&&!l.has(m));if(!u.length&&!p.length){console.log(w.yellow("No changes to apply."));return}for(let m of u)await $e(r,e,m);for(let m of p)await Je(r,e,m);console.log(w.green(`View "${e}" updated.`));}),n.command("create").description("Create a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await b();await Ye(r,e),console.log(w.green(`View "${e}" created.`));}),n.command("delete").alias("del").description("Delete a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await b();await Xe(r,e),console.log(w.green(`View "${e}" deleted.`));});}function $n(t){return g(t?$(t):"-")}function be(t){let n=process.argv,e=0;if(t){let r=n.lastIndexOf(t);r>=0&&(e=r+1);}for(let r=e;r<n.length;r+=1){let o=n[r];if(o==="-j"||o==="--job"){let s=n[r+1];return !s||s.startsWith("-")?"":s}}}function Be(t,n,e){let r=n?.parent?.opts()?.job,o=be(e)??be(n?.name())??be("ws")??be("workspace");return t??r??o}function We(t,n){if(n==="")throw new f("Job is required.",{hint:"Provide a job name after -j/--job.",example:"jenkins-cli ws -j my-job"});return k(t,n)}function It(t){return t.replace(/^\/+/,"").replace(/\/+$/,"")}function Jn(t,n){let e=It(t),r=It(n);return e?r?r===e||r.startsWith(`${e}/`)?r:`${e}/${r}`:e:r||""}function vn(t){let n=process.platform,e="",r=[];n==="darwin"?(e="open",r=[t]):n==="win32"?(e="cmd",r=["/c","start","",t]):(e="xdg-open",r=[t]);try{spawn(e,r,{stdio:"ignore",detached:!0}).unref();}catch{}}async function J(t){try{return await t()}catch(n){if(n?.response?.status===404)return null;throw n}}async function Pn(t,n){try{return await et(t,n)}catch{return}}async function Rn(t,n){try{return await gt(t,n)}catch{return}}async function Nn(t){try{return await K(t,{raw:!1})}catch{return []}}async function Ee(t,n,e){let r=await e.direct(n);if(r!==null)return r;let o=await Pn(t,n);if(o&&o!==n){let a=await e.direct(o);if(a!==null)return a}if(e.beforeView){let a=await e.beforeView();if(a!==null)return a}let s=await Rn(t,n);if(s){let a=await e.byViewName(s);if(a!==null)return a}let i=await Nn(t);for(let a of i){let c=String(a?.url??"").trim();if(!c)continue;let l=await e.byViewUrl(c);if(l!==null)return l}return null}async function An(t,n,e){return await Ee(t,n,{direct:r=>J(()=>ve(t,r,{path:e})),byViewName:r=>J(()=>it(t,r,n,{path:e})),byViewUrl:r=>J(()=>st(t,r,n,{path:e})),beforeView:async()=>{if(e)return null;let r=n.split("/").pop();return r?await J(()=>ve(t,n,{path:r})):null}})}async function Bn(t,n,e){return await Ee(t,n,{direct:r=>J(()=>at(t,r,e)),byViewName:r=>J(()=>lt(t,r,n,e)),byViewUrl:r=>J(()=>mt(t,r,n,e))})}async function Wn(t,n,e){return await Ee(t,n,{direct:r=>J(()=>ct(t,r,e)),byViewName:r=>J(()=>ut(t,r,n,e)),byViewUrl:r=>J(()=>pt(t,r,n,e))})}function Ot(t){let n=t.command("workspace").alias("ws").description("Workspace operations");n.option("-j, --job <job>","Specify job").option("-p, --path <path>","Workspace sub path").action(async(e,r)=>{let{config:o,jenkins:s}=await b(),i=Be(e.job,r,"workspace"),a=We(o.job,i),c=String(e.path??"").trim(),l=Vt(`Loading workspace for job "${a}"...`).start(),u=await An(s,a,c);if(!u){l.warn(`Workspace not found for job: ${a}. The job may be inside a folder, not run yet, or workspace is disabled.`);return}if(l.succeed(`Workspace loaded for job: ${a}`),!u.length){console.table([{name:"-",type:"-",size:"-",modified:"-",path:"-",url:"-"}]);return}let p=u.map(d=>({name:String(d.name??""),typeRaw:d.type,size:$t(d.size),modified:$n(d.modified),path:Jn(c,String(d.path??d.name??""))})),m=j(p.map(d=>d.name)),h=j(p.map(d=>d.path));console.table(p.map(d=>{let y=B(String(d.name??""),m),D=String(d.typeRaw??"");return {name:D==="dir"?g(w.bold.cyan(y)):D==="file"?g(w.green(y)):g(w.gray(y)),size:d.size,modified:d.modified,path:C(String(d.path??""),h)}}));}),n.command("cat").description("Show file content in workspace").argument("<path>","Workspace file path").option("-j, --job <job>","Specify job").option("-o, --out <file>","Save file to path").option("--open","Open file with default application").action(async(e,r,o)=>{let{config:s,jenkins:i}=await b(),a=Be(r.job,o,"cat"),c=We(s.job,a),l=String(e??"").trim();if(!l)throw new f("Path is required.",{hint:'Provide a file path after "cat".',example:"jenkins-cli ws cat dist/index.html"});let u=String(r.out??"").trim(),p=r.open===!0;if(u||p){let h=await Wn(i,c,l);if(h===null){console.log(w.yellow(`Workspace file not found: ${l} (job: ${c}).`));return}let d=u||V.join(Cn.tmpdir(),V.basename(l)||"file");try{u&&await T.pathExists(u)&&(await T.stat(u)).isDirectory()&&(d=V.join(u,V.basename(l)||"file"));}catch{}await T.ensureDir(V.dirname(d)),await T.writeFile(d,h.data),p?(vn(d),console.log(w.green(`Opened: ${d}`))):console.log(w.green(`Saved to: ${d}`));return}let m=await Bn(i,c,l);if(m===null){console.log(w.yellow(`Workspace file not found: ${l} (job: ${c}).`));return}process.stdout.write(String(m));}),n.command("wipe").description("Wipe out current workspace").option("-j, --job <job>","Specify job").action(async(e,r)=>{let{config:o,jenkins:s}=await b(),i=Be(e.job,r,"wipe"),a=We(o.job,i);try{if(!(await fn.prompt([{type:"confirm",name:"confirm",message:`Wipe workspace for job "${a}"? This cannot be undone.`,default:!1}]))?.confirm){console.log(w.yellow("Cancelled."));return}}catch(l){let u=l?.message?String(l.message):String(l);if((l?.name?String(l.name):"")==="ExitPromptError"||u.toLowerCase().includes("cancelled")||u.toLowerCase().includes("canceled")){console.log(w.yellow("Cancelled."));return}throw l}let c=Vt(`Wiping workspace for job "${a}"...`).start();try{await ft(s,a),c.succeed(`Workspace wiped for job: ${a}`);}catch(l){throw c.fail(`Failed to wipe workspace for job: ${a}`),l}});}function qt(t){vt(t),Rt(t),Ft(t),Ut(t),At(t),Wt(t),St(t),Bt(t),Lt(t),Et(t),Tt(t),Ot(t);}program.name("jenkins-cli").description(Ve).version(Te,"-v, --version").helpOption("-h, --help").allowExcessArguments(!1).configureHelp({sortSubcommands:!0,sortOptions:!0}).action(Ct);qt(program);async function En(){try{await program.parseAsync(process.argv);}catch(t){U(t);}}En();
42
+ `)),process.exit(1);}});}function Zt(n){let t=n.command("view").description("View operations");t.command("list").alias("ls").description("List all views").option("--raw","Output raw JSON").action(async e=>{let{jenkins:r}=await h(),o=await re(r,{raw:e.raw});if(e.raw){console.log(JSON.stringify(o,null,2));return}o.sort((c,l)=>String(c?.name??"").localeCompare(String(l?.name??""),"en",{sensitivity:"base"}));let s=(o??[]).map(c=>({name:String(c?.name??""),url:String(c?.url??"")})),i=j(s.map(c=>c.name)),a=j(s.map(c=>c.url));console.table(s.map(c=>({name:v(c.name,i),url:J(U(c.url,a))})));}),t.command("show").description("Show jobs in a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await h(),o=await Q(r,e);if(!o.length){console.log("No jobs found in this view.");return}o.sort((a,c)=>String(a?.name??"").localeCompare(String(c?.name??""),"en",{sensitivity:"base"}));let s=j(o.map(a=>a?.name)),i=j(o.map(a=>a?.url));console.table(o.map(a=>({name:v(a.name??"",s),color:ae(a.color),url:J(U(a.url??"",i))})));}),t.command("add").description("Add a job to a view").argument("<view>","View name").argument("<job>","Job name").action(async(e,r)=>{let{jenkins:o}=await h();if((await Q(o,e)).some(i=>i.name===r)){console.log(y.yellow(`Job "${r}" is already in view "${e}".`));return}await Ie(o,e,r),console.log(y.green(`Job "${r}" added to view "${e}".`));}),t.command("remove").alias("rm").description("Remove a job from a view").argument("<view>","View name").argument("<job>","Job name").action(async(e,r)=>{let{jenkins:o}=await h();if(!(await Q(o,e)).some(i=>i.name===r))throw new d(`Job "${r}" is not in view "${e}".`,{hint:'Use "jc view show <name>" to see jobs in this view.'});await qe(o,e,r),console.log(y.green(`Job "${r}" removed from view "${e}".`));}),t.command("edit").description("Edit jobs in a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await h(),[o,s]=await Promise.all([T(r),Q(r,e)]);if(!o.length){console.log("No jobs found.");return}o.sort((m,p)=>String(m?.name??"").localeCompare(String(p?.name??""),"en",{sensitivity:"base"}));let i=new Set(s.map(m=>String(m?.name??"").trim())),a=o.map(m=>String(m?.name??"").trim()).filter(Boolean).map(m=>({name:m,checked:i.has(m)})),c=await oe.prompt([{type:"checkbox",name:"jobs",message:`Select jobs for view "${e}"`,choices:a,pageSize:20}]),l=new Set((c.jobs??[]).map(m=>String(m).trim())),u=[...l].filter(m=>!i.has(m)),f=[...i].filter(m=>m&&!l.has(m));if(!u.length&&!f.length){console.log(y.yellow("No changes to apply."));return}for(let m of u)await Ie(r,e,m);for(let m of f)await qe(r,e,m);console.log(y.green(`View "${e}" updated.`));}),t.command("create").description("Create a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await h();await ut(r,e),console.log(y.green(`View "${e}" created.`));}),t.command("delete").alias("del").description("Delete a view").argument("<name>","View name").action(async e=>{let{jenkins:r}=await h();await mt(r,e),console.log(y.green(`View "${e}" deleted.`));});}function Yn(n){return w(n?P(n):"-")}function Ae(n){let t=process.argv,e=0;if(n){let r=t.lastIndexOf(n);r>=0&&(e=r+1);}for(let r=e;r<t.length;r+=1){let o=t[r];if(o==="-j"||o==="--job"){let s=t[r+1];return !s||s.startsWith("-")?"":s}}}function Qe(n,t,e){let r=t?.parent?.opts()?.job,o=Ae(e)??Ae(t?.name())??Ae("ws")??Ae("workspace");return n??r??o}function tn(n){return n.replace(/^\/+/,"").replace(/\/+$/,"")}function Xn(n,t){let e=tn(n),r=tn(t);return e?r?r===e||r.startsWith(`${e}/`)?r:`${e}/${r}`:e:r||""}function Zn(n){let t=process.platform,e="",r=[];t==="darwin"?(e="open",r=[n]):t==="win32"?(e="cmd",r=["/c","start","",n]):(e="xdg-open",r=[n]);try{spawn(e,r,{stdio:"ignore",detached:!0}).unref();}catch{}}async function A(n){try{return await n()}catch(t){if(t?.response?.status===404)return null;throw t}}async function er(n,t){try{return await pt(n,t)}catch{return}}async function tr(n,t){try{return await Rt(n,t)}catch{return}}async function nr(n){try{return await re(n,{raw:!1})}catch{return []}}async function Ge(n,t,e){let r=await e.direct(t);if(r!==null)return r;let o=await er(n,t);if(o&&o!==t){let a=await e.direct(o);if(a!==null)return a}if(e.beforeView){let a=await e.beforeView();if(a!==null)return a}let s=await tr(n,t);if(s){let a=await e.byViewName(s);if(a!==null)return a}let i=await nr(n);for(let a of i){let c=String(a?.url??"").trim();if(!c)continue;let l=await e.byViewUrl(c);if(l!==null)return l}return null}async function rr(n,t,e){return await Ge(n,t,{direct:r=>A(()=>De(n,r,{path:e})),byViewName:r=>A(()=>bt(n,r,t,{path:e})),byViewUrl:r=>A(()=>yt(n,r,t,{path:e})),beforeView:async()=>{if(e)return null;let r=t.split("/").pop();return r?await A(()=>De(n,t,{path:r})):null}})}async function or(n,t,e){return await Ge(n,t,{direct:r=>A(()=>kt(n,r,e)),byViewName:r=>A(()=>jt(n,r,t,e)),byViewUrl:r=>A(()=>St(n,r,t,e))})}async function ir(n,t,e){return await Ge(n,t,{direct:r=>A(()=>xt(n,r,e)),byViewName:r=>A(()=>Ct(n,r,t,e)),byViewUrl:r=>A(()=>$t(n,r,t,e))})}function nn(n){let t=n.command("workspace").alias("ws").description("Workspace operations");t.option("-j, --job <job>","Specify job").option("-p, --path <path>","Workspace sub path").action(async(e,r)=>{let{config:o,jenkins:s}=await h(),i=Qe(e.job,r,"workspace"),a=await k(o,i),c=String(e.path??"").trim(),l=en(`Loading workspace for job "${a}"...`).start(),u=await rr(s,a,c);if(!u){l.warn(`Workspace not found for job: ${a}. The job may be inside a folder, not run yet, or workspace is disabled.`);return}if(l.succeed(`Workspace loaded for job: ${a}`),!u.length){console.table([{name:"-",type:"-",size:"-",modified:"-",path:"-",url:"-"}]);return}let f=u.map(g=>({name:String(g.name??""),typeRaw:g.type,size:Lt(g.size),modified:Yn(g.modified),path:Xn(c,String(g.path??g.name??""))})),m=j(f.map(g=>g.name)),p=j(f.map(g=>g.path));console.table(f.map(g=>{let b=U(String(g.name??""),m),S=String(g.typeRaw??"");return {name:S==="dir"?w(y.bold.cyan(b)):S==="file"?w(y.green(b)):w(y.gray(b)),size:g.size,modified:g.modified,path:v(String(g.path??""),p)}}));}),t.command("cat").description("Show file content in workspace").argument("<path>","Workspace file path").option("-j, --job <job>","Specify job").option("-o, --out <file>","Save file to path").option("--open","Open file with default application").action(async(e,r,o)=>{let{config:s,jenkins:i}=await h(),a=Qe(r.job,o,"cat"),c=await k(s,a),l=String(e??"").trim();if(!l)throw new d("Path is required.",{hint:'Provide a file path after "cat".',example:"jenkins-cli ws cat dist/index.html"});let u=String(r.out??"").trim(),f=r.open===!0;if(u||f){let p=await ir(i,c,l);if(p===null){console.log(y.yellow(`Workspace file not found: ${l} (job: ${c}).`));return}let g=u||z.join(Gn.tmpdir(),z.basename(l)||"file");try{u&&await M.pathExists(u)&&(await M.stat(u)).isDirectory()&&(g=z.join(u,z.basename(l)||"file"));}catch{}await M.ensureDir(z.dirname(g)),await M.writeFile(g,p.data),f?(Zn(g),console.log(y.green(`Opened: ${g}`))):console.log(y.green(`Saved to: ${g}`));return}let m=await or(i,c,l);if(m===null){console.log(y.yellow(`Workspace file not found: ${l} (job: ${c}).`));return}process.stdout.write(String(m));}),t.command("wipe").description("Wipe out current workspace").option("-j, --job <job>","Specify job").action(async(e,r)=>{let{config:o,jenkins:s}=await h(),i=Qe(e.job,r,"wipe"),a=await k(o,i);try{if(!(await oe.prompt([{type:"confirm",name:"confirm",message:`Wipe workspace for job "${a}"? This cannot be undone.`,default:!1}]))?.confirm){console.log(y.yellow("Cancelled."));return}}catch(l){if(Ce(l)){console.log(y.yellow("Cancelled."));return}throw l}let c=en(`Wiping workspace for job "${a}"...`).start();try{await vt(s,a),c.succeed(`Workspace wiped for job: ${a}`);}catch(l){throw c.fail(`Failed to wipe workspace for job: ${a}`),l}});}function rn(n){qt(n),Mt(n),Kt(n),Yt(n),_t(n),Qt(n),Ut(n),Ht(n),Xt(n),Gt(n),Zt(n),nn(n);}function on(n,t,e){let r=s=>s.options.some(i=>i.long===t||i.short===t),o=s=>{r(s)||s.option(t,e);for(let i of s.commands)o(i);};for(let s of n.commands)o(s);}program.name("jenkins-cli").description(et).version(Ze,"-v, --version").helpOption("-h, --help").option("--debug","Print Jenkins request params").allowExcessArguments(!1).configureHelp({sortSubcommands:!0,sortOptions:!0}).action(Wt);rn(program);on(program,"--debug","Print Jenkins request params");async function sr(){try{await program.parseAsync(process.argv);}catch(n){q(n);}}sr();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ts-org/jenkins-cli",
3
- "version": "3.0.6",
3
+ "version": "3.1.1",
4
4
  "description": "Jenkins deployment CLI",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -8,13 +8,6 @@
8
8
  "jenkins-cli": "dist/cli.js",
9
9
  "jc": "dist/cli.js"
10
10
  },
11
- "scripts": {
12
- "build": "tsup",
13
- "dev": "NODE_ENV=development tsup --watch",
14
- "prepublishOnly": "npm run build",
15
- "link:test": "npm run build && npm link",
16
- "format": "eslint . --fix && prettier . --write"
17
- },
18
11
  "keywords": [
19
12
  "jenkins",
20
13
  "cli",
@@ -66,5 +59,11 @@
66
59
  "directories": {
67
60
  "doc": "docs"
68
61
  },
69
- "types": "./dist/index.d.ts"
70
- }
62
+ "types": "./dist/index.d.ts",
63
+ "scripts": {
64
+ "build": "tsup",
65
+ "dev": "NODE_ENV=development tsup --watch",
66
+ "link:test": "npm run build && npm link",
67
+ "format": "eslint . --fix && prettier . --write"
68
+ }
69
+ }
@@ -7,14 +7,21 @@
7
7
  },
8
8
  "job": {
9
9
  "type": "string",
10
- "description": "Jenkins job name"
10
+ "description": "Jenkins job name (or reference string like jenkins-utils.ts:fn)"
11
11
  },
12
12
  "modes": {
13
- "type": "array",
14
- "description": "Available deployment environments, such as dev, sit, uat",
15
- "items": {
16
- "type": "string"
17
- }
13
+ "description": "Available deployment environments (array) or reference string like jenkins-utils.ts:fn",
14
+ "oneOf": [
15
+ {
16
+ "type": "array",
17
+ "items": {
18
+ "type": "string"
19
+ }
20
+ },
21
+ {
22
+ "type": "string"
23
+ }
24
+ ]
18
25
  },
19
26
  "configs": {
20
27
  "type": "array",
@@ -35,6 +42,10 @@
35
42
  "type": "string",
36
43
  "description": "Parameter message"
37
44
  },
45
+ "offset": {
46
+ "type": "number",
47
+ "description": "Negative offsets control prompt ordering (-1 between branch/modes, <=-2 before branch)"
48
+ },
38
49
  "default": {
39
50
  "description": "Parameter default value"
40
51
  },