@stackone/cli 1.15.3 โ 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cliCore-DYoF7lqY.mjs +38 -0
- package/dist/cliCore-Emt0KqdF.cjs +38 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +10 -9
- package/dist/cliCore-VnX1Z2bB.mjs +0 -66
- package/dist/cliCore-fjMX19Ck.cjs +0 -66
package/dist/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const e=require(`./cliCore-
|
|
2
|
+
const e=require(`./cliCore-Emt0KqdF.cjs`);new e.t().run();
|
package/dist/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{t as e}from"./cliCore-
|
|
2
|
+
import{t as e}from"./cliCore-DYoF7lqY.mjs";new e().run();export{};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";import t from"chalk";import{Argument as n,Command as r}from"commander";import{exec as i,execSync as a}from"node:child_process";import{access as o,readFile as s,writeFile as c}from"node:fs/promises";import{join as l}from"node:path";import{promisify as u}from"node:util";import d from"ora";import f,{existsSync as p,lstatSync as m,readFileSync as h,readdirSync as g,rmSync as _,statSync as v,writeFileSync as y}from"fs";import{homedir as b}from"os";import x,{basename as ee,dirname as S,join as C,resolve as te}from"path";import{createConsola as w}from"consola";import{color as T,colorize as ne}from"json-colorizer";import{stdin as E,stdout as re}from"node:process";import{createInterface as ie}from"node:readline";import D from"inquirer";import{getConfig as ae}from"@stackone/agent-config";import{isMissing as O,isObject as oe,notMissing as k,z as A}from"@stackone/utils";import{cancel as j,confirm as se,intro as ce,isCancel as M,outro as le,password as ue,select as de,text as fe}from"@clack/prompts";import{loadConnector as N,runAction as pe,validateYamlConnector as P}from"@stackone/connect-sdk";import{diffLines as me}from"diff";import{createInterface as he}from"readline";import{HttpClient as ge}from"@stackone/transport";import{existsSync as F,mkdirSync as _e,readFileSync as ve,writeFileSync as ye}from"node:fs";import be from"semver";import{fileURLToPath as xe}from"url";import{readdir as Se,stat as Ce}from"fs/promises";import{homedir as we}from"node:os";var Te=e(import.meta.url);const Ee=`config.json`,De=`agent-config.json`,I=w({level:4,formatOptions:{columns:80,colors:!0,compact:!1,date:!1}}),L=e=>{I.log(ne(e,{indent:2,colors:{Whitespace:T.gray,Brace:T.gray,Bracket:T.gray,Colon:T.gray,Comma:T.gray,StringKey:T.white,StringLiteral:T.yellow,NumberLiteral:T.green,BooleanLiteral:T.cyan,NullLiteral:T.white}}))},R=(e=[],t)=>{e.length!==0&&(I.log(`${e.length} error${e.length>1?`s`:``} found:`),e.forEach(e=>{let n=`line`in e?e.line:void 0,r=t&&n?`L${n}: `:``;I.log(`- ${r}${e.message}`)}))},z=async(e,t=`Request failed`)=>{I.error(`${t}: ${e.status} - ${e.statusText}`);let n=await e.text();if(!n)return;let r;try{r=JSON.parse(n)}catch{}r?L(r):I.log(n)},B=e=>t.cyan(e),V=e=>t.yellow(e),H=e=>t.red(e),U=()=>{process.stdout.write(`\x1Bc`)};var W=class{static{this.configDir=C(b(),`.stackone`)}static ensureConfigDir(){if(p(this.configDir)){if(!m(this.configDir).isDirectory()){let e=null;try{I.info(`.stackone exists as a file, checking for migration to config directory...`),e=h(this.configDir,`utf8`)}catch{}if(_(this.configDir,{force:!0}),Te(`fs`).mkdirSync(this.configDir,{recursive:!0}),e)try{JSON.parse(e),y(C(this.configDir,Ee),e,`utf8`),I.success(`Migrated existing .stackone file content to config.json`)}catch{I.warn(`Note: Existing .stackone file was not valid JSON, skipping migration`)}else I.warn(`Note: Existing .stackone file was not valid JSON, skipping migration`)}}else Te(`fs`).mkdirSync(this.configDir,{recursive:!0})}static getConfigDir(){return this.configDir}static writeConfigFile(e,t,n){this.ensureConfigDir();let r=C(this.configDir,e);y(r,t,`utf8`),n?.mode!==void 0&&Te(`fs`).chmodSync(r,n.mode)}static readConfigFile(e){this.ensureConfigDir();let t=C(this.configDir,e);if(!p(t))return null;try{return h(t,`utf8`)}catch{return null}}static deleteConfigFile(e){let t=C(this.configDir,e);p(t)&&_(t,{force:!0})}};const Oe=process.env.STACKONE_AGENT_SERVER_URL||`https://mcp-internal-falcon.stackonehq.workers.dev/mcp`;async function ke(e){W.writeConfigFile(De,JSON.stringify(e,null,2),{mode:384})}async function Ae(){let e=W.readConfigFile(De);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function je(){W.deleteConfigFile(De)}function G(){return Oe}function Me(){return`stackone-agent-global`}function K(){return`stackone-agent-local`}function Ne(e){return new Date(e)<=new Date}function Pe(e){return!!e?.apiKey&&!Ne(e.expiresAt)}const Fe=u(i);async function Ie(e){try{let t=await s(e,`utf-8`),n=JSON.parse(t),r=!1;if(n.mcpServers&&typeof n.mcpServers==`object`){for(let[e,t]of Object.entries(n.mcpServers))if(t&&typeof t==`object`&&`transport`in t){let e=t.transport;if(e&&typeof e==`object`&&`headers`in e){let t=e.headers;if(t&&typeof t==`object`&&`Authorization`in t){let e=t.Authorization;typeof e==`string`&&e.startsWith(`Bearer `)&&!e.includes("${")&&(t.Authorization="Bearer ${STACKONE_AGENT_MCP_TOKEN}",r=!0)}}}}return r&&await c(e,JSON.stringify(n,null,2)),r}catch{return!1}}var Le=class{async execute(){I.log(t.blue.bold(`๐งน StackOne Agent Cleanup
|
|
2
|
+
`));let e={configsCleaned:0};try{let n=d(`Removing stored configuration...`).start();await je(),n.succeed(`Removed ~/.stackone/agent-config.json`);let r=d(`Removing MCP servers from Claude...`).start(),i=0;try{await Fe(`claude mcp remove ${Me()} 2>/dev/null`),i++}catch{}try{await Fe(`claude mcp remove ${K()} 2>/dev/null`),i++}catch{}i>0?r.succeed(`Removed ${i} MCP server(s) from Claude`):r.warn(`No MCP servers found in Claude (already removed or not configured)`);let a=d(`Checking for .mcp.json file...`).start(),o=l(process.cwd(),`.mcp.json`);try{await Ie(o)?(e.configsCleaned=1,a.succeed(`Cleaned .mcp.json (replaced tokens with environment variables)`)):a.info(`.mcp.json already uses environment variables or not found`)}catch{a.info(`.mcp.json not found (already cleaned or not created)`)}I.success(`Cleanup complete!`),I.log(t.white(`
|
|
3
|
+
What was removed:`)),I.log(t.cyan(` โข ~/.stackone/agent-config.json`)),I.log(t.cyan(` โข MCP server from Claude configuration`)),e.configsCleaned>0&&I.log(t.cyan(` โข Hardcoded credentials from .mcp.json`)),I.log(t.dim(`
|
|
4
|
+
To authenticate again:`)),I.log(t.cyan(` stackone agent setup --global`),t.dim(`(for global setup)`)),I.log(t.cyan(` stackone agent setup --local`),t.dim(`(for local project setup)`)),I.log(``),process.exit(0)}catch(e){e instanceof Error?I.error(e.message):I.error(`Unknown error occurred`),process.exit(1)}}};const Re=new class{constructor(e){this.baseUrl=e||process.env.AUTH_SERVER_URL||`https://idp-api.stackone.com`}async login(e,t){try{let n=`${this.baseUrl}/auth/sign-in/mcp`,r=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({email:e,password:t})});if(!r.ok){let e=await r.text(),t={};try{t=JSON.parse(e)}catch{}return{success:!1,error:t.error||`HTTP ${r.status}: ${r.statusText}`}}let i=await r.text(),a=JSON.parse(i);return a.apiKey?{success:!0,apiKey:a.apiKey}:{success:!1,error:`Invalid response format`}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async validateKey(e){try{let t=`${this.baseUrl}/api-key/verify`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({key:e})});if(!n.ok){let e=await n.text(),t={};try{t=JSON.parse(e)}catch{}return{valid:!1,error:t.error||`HTTP ${n.status}: ${n.statusText}`}}let r=await n.text();return JSON.parse(r)}catch(e){return{valid:!1,error:e instanceof Error?e.message:`Network error occurred`}}}},ze=u(i);function Be(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime(),i=Math.floor(r/(3600*1e3)),a=t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,hour12:!0});return`${t.toDateString()===n.toDateString()?`Today`:t.toDateString()===new Date(n.getTime()+864e5).toDateString()?`Tomorrow`:t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`})} at ${a} (${i} hours from now)`}var Ve=class{async execute(){I.log(t.blue.bold(`๐ค StackOne Agent Setup - Global Configuration
|
|
5
|
+
`));try{let e=process.cwd(),n=await o(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await o(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){I.warn(`Existing local setup detected:`),n&&I.log(t.dim(` โข CLAUDE.md found in current directory`)),r&&I.log(t.dim(` โข .mcp.json found in current directory`)),I.log(``);let{proceed:e}=await D.prompt([{type:`confirm`,name:`proceed`,message:`Re-authenticate globally despite existing local setup?`,default:!0}]);e||(I.log(t.dim(`
|
|
6
|
+
Setup cancelled.`)),process.exit(0)),I.log(``)}let i=await Ae(),a;if(i?.email){I.log(t.dim(`Last used email: ${i.email}\n`));let{useExisting:e}=await D.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);if(e)a=i.email;else{let e=ie({input:E,output:re});a=await new Promise(n=>{e.question(t.white(`Email: `),e=>{n(e.trim())})}),e.close(),a||(I.error(`Email is required`),process.exit(1))}}else{let e=ie({input:E,output:re});a=await new Promise(n=>{e.question(t.white(`Email: `),e=>{n(e.trim())})}),e.close(),a||(I.error(`Email is required`),process.exit(1))}let s=await D.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);s.password||(I.error(`Password is required`),process.exit(1)),I.log(``);let c=d(`Authenticating...`).start(),l=await Re.login(a,s.password);(!l.success||!l.apiKey)&&(c.fail(`Authentication failed`),I.error(`${l.error||`Invalid credentials`}`),I.log(t.dim(`Please check your email and password and try again.
|
|
7
|
+
`)),process.exit(1)),c.succeed(`Login successful!`);let u=new Date(Date.now()+1440*60*1e3).toISOString();await ke({apiKey:l.apiKey,userId:a,email:a,expiresAt:u,serverUrl:G()}),I.success(`API key saved to ~/.stackone/agent-config.json`),I.log(t.white(`โ Key expires at`),t.cyan(Be(u)));let f=d(`Setting up global MCP configuration...`).start();try{let e=Me(),n=G();try{await ze(`claude mcp remove ${e} 2>/dev/null`)}catch{}await ze(`claude mcp add ${e} ${n} --scope user --transport http --header "Authorization: Bearer ${l.apiKey}"`),f.succeed(`Installed to Claude (global)`),I.success(`Global setup complete!`),I.log(t.white(`Config location:`),t.cyan(`~/.claude.json`)),I.log(t.blue(`
|
|
8
|
+
Verify:`),t.cyan(`claude mcp list`)),I.log(t.dim(`
|
|
9
|
+
๐ก Tip: Run Claude without permission prompts:`),t.cyan(`claude --dangerously-skip-permissions`)),I.log(t.dim(`
|
|
10
|
+
To setup for a specific project, run:`),t.cyan(`stackone agent setup --local`)),I.log(``)}catch(e){f.fail(`Installation to Claude failed`),e instanceof Error&&(I.error(e.message),I.log(t.dim(`You can manually add the server later with:`)),I.log(t.cyan(` claude mcp add ${Me()} ${G()} --scope user --transport http --header "Authorization: Bearer ${l.apiKey}"`)))}process.exit(0)}catch(e){e instanceof Error?I.error(e.message):I.error(`Unknown error occurred`),process.exit(1)}}};const He=u(i);async function Ue(){return ae()}async function We(){let e=`.mcp.json`,t;try{let n=await s(e,`utf-8`);t=JSON.parse(n)}catch{t={mcpServers:{}}}t.mcpServers||={},t.mcpServers[K()]={url:G(),transport:{type:`http`,headers:{Authorization:"Bearer ${STACKONE_AGENT_MCP_TOKEN}"}}},await c(e,JSON.stringify(t,null,2))}var Ge=class{async execute(){I.log(t.blue.bold(`๐ค StackOne Agent Setup - Local Project
|
|
11
|
+
`));try{let e=process.cwd(),n=await o(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await o(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){I.warn(`Existing local setup detected:`),n&&I.log(t.dim(` โข CLAUDE.md found`)),r&&I.log(t.dim(` โข .mcp.json found`)),I.log(``);let{proceed:e}=await D.prompt([{type:`confirm`,name:`proceed`,message:`Overwrite existing local configuration?`,default:!1}]);e||(I.log(t.dim(`
|
|
12
|
+
Setup cancelled.`)),process.exit(0)),I.log(``)}let i=await Ae();if(!i||!Pe(i)){I.warn(`Not authenticated globally.`),I.log(t.white(`Let's authenticate now...
|
|
13
|
+
`));let e=ie({input:E,output:re}),n=await new Promise(n=>{e.question(t.white(`Email: `),e=>{n(e.trim())})});e.close(),n||(I.error(`Email is required`),process.exit(1));let r=await D.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);r.password||(I.error(`Password is required`),process.exit(1)),I.log(``);let a=d(`Authenticating...`).start(),o=await Re.login(n,r.password);(!o.success||!o.apiKey)&&(a.fail(`Authentication failed`),I.error(`${o.error||`Invalid credentials`}`),I.log(t.dim(`Please check your email and password and try again.
|
|
14
|
+
`)),process.exit(1)),a.succeed(`Login successful!`);let s=new Date(Date.now()+1440*60*1e3).toISOString();await ke({apiKey:o.apiKey,userId:n,email:n,expiresAt:s,serverUrl:G()}),i={apiKey:o.apiKey,userId:n,email:n,expiresAt:s,serverUrl:G()},I.log(``)}let a=d(`Setting up local project configuration...`).start();a.text=`Creating CLAUDE.md...`,await c(`CLAUDE.md`,await Ue()),a.succeed(`Created CLAUDE.md`);let s=d(`Creating .mcp.json...`).start();await We(),s.succeed(`Created .mcp.json (using STACKONE_AGENT_MCP_TOKEN env var)`);let l=d(`Installing to Claude (local)...`).start();try{let e=K();try{await He(`claude mcp remove ${e} 2>/dev/null`)}catch{}await He(`claude mcp add ${e} ${G()} --scope local --transport http --header "Authorization: Bearer ${i.apiKey}"`),l.succeed(`Installed to Claude (local)`),I.success(`Local setup complete!`),I.log(t.white(`Files created:`)),I.log(t.cyan(` - CLAUDE.md`)),I.log(t.cyan(` - .mcp.json`)),I.log(t.dim(`
|
|
15
|
+
๐ก The stackone-agent-local MCP server is now available in this project`)),I.log(t.dim(`
|
|
16
|
+
๐ก Tip: Run Claude without permission prompts:`),t.cyan(`claude --dangerously-skip-permissions`)),I.log(t.blue(`
|
|
17
|
+
Verify:`),t.cyan(`claude mcp list`)),I.log(``)}catch(e){l.fail(`Installation to Claude failed`),e instanceof Error&&(I.error(e.message),I.log(t.dim(`Configuration files created, but Claude setup failed.`)),I.log(t.dim(`You can manually add the server later with:`)),I.log(t.cyan(` claude mcp add ${K()} ${G()} --scope local --transport http --header "Authorization: Bearer ${i.apiKey}"`))),I.log(``)}process.exit(0)}catch(e){e instanceof Error?I.error(e.message):I.error(`Unknown error occurred`),process.exit(1)}}};const Ke={profiles:{}},q=()=>{let e=W.readConfigFile(Ee);if(!e)return Ke;try{return JSON.parse(e)}catch{return Ke}},J=e=>q().profiles[e],Y=e=>!!q().profiles[e],qe=(e,t)=>{let n=q();n.profiles[e]=t,W.writeConfigFile(Ee,JSON.stringify(n,null,2))},X=()=>{let e=q();return Object.keys(e.profiles)},Je=`https://api.stackone.com`;var Ye=class{async execute({profile:e,connector:n,apiUrl:r,apiKey:i}={}){if(!e&&!i&&(I.error(`Profile or API key is required`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`To create a profile, run ${B(`stackone init`)}.`),process.exit(1)),e&&i&&(I.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&I.warn(`Specifying ${B(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Y(e)){I.error(`Configuration profile ${B(e)} not found`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.\n`);let n=X();n.length>0&&(I.info(`Available configuration profiles:`),n.forEach(e=>{I.log(` - ${t.blue(e)}`)})),process.exit(1)}let a=e?J(e):{apiUrl:r??Je,apiKey:i};a?.apiKey||(I.error(`API key is missing`),I.log(`Please provide a valid API key in the profile or via the ${B(`--api-key`)} option.`),process.exit(1)),n||(I.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let o=n.split(`@`);(o.length!==2||!o[0]||!o[1])&&(I.error(`Invalid connector format ${H(n)}. Expected format: ${B(`provider_key@version`)}`),process.exit(1));let s=a.apiUrl??Je,c=await this.dropConnector(n,s,a.apiKey);process.exit(c?0:1)}async dropConnector(e,t,n){let r=d(`๐๏ธ Dropping connector ${B(e)}...`).start();try{let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${i}`}});return r.stop(),a.status===204?(I.success(`Successfully dropped connector ${B(e)} from the registry`),!0):a.status===404?(I.error(`Connector ${B(e)} not found in the registry`),!1):a.status===401||a.status===403?(I.error(`You do not have permission to drop this connector`),!1):a.status===409?(I.error(`Connector ${B(e)} has associated configs and cannot be dropped`),I.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(a.ok||await z(a,`Failed to drop connector ${B(e)} from the registry`),!1)}catch(n){return r.stop(),I.error(`Failed to drop connector ${B(e)} from registry: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),!1}}};const Xe=`https://api.stackone.com`;var Ze=class{async execute({profile:e,connector:n,accountId:r,format:i,outputFile:a,apiUrl:o,apiKey:s}={}){if(!e&&!s&&(I.error(`Profile or API key is required`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`To create a profile, run ${B(`stackone init`)}.`),process.exit(1)),e&&s&&(I.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&o&&I.warn(`Specifying ${B(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Y(e)){I.error(`Configuration profile ${B(e)} not found`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.\n`);let n=X();n.length>0&&(I.info(`Available configuration profiles:`),n.forEach(e=>{I.log(` - ${t.blue(e)}`)})),process.exit(1)}let c=e?J(e):{apiUrl:o??Xe,apiKey:s};c?.apiKey||(I.error(`API key is missing`),I.log(`Please provide a valid API key in the profile or via the ${B(`--api-key`)} option.`),process.exit(1)),O(n)&&O(r)&&(I.error(`Either ${B(`--connector`)} or ${B(`--account-id`)} must be provided`),process.exit(1)),k(n)&&k(r)&&(I.error(`Please provide either ${B(`--connector`)} or ${B(`--account-id`)}, not both.`),process.exit(1)),k(i)&&i!==`yaml`&&i!==`json`&&(I.error(`Format must be either ${B(`yaml`)} or ${B(`json`)}.`),process.exit(1));let l=c.apiUrl??Xe,u;if(k(n)){this.#t(n)||(I.error(`Invalid connector format ${H(n)}. Expected format: ${B(`provider_key@version`)} or ${B(`provider_key`)}`),process.exit(1));let e=this.#n(n);u=await this.#r(e,l,c.apiKey,i)}else k(r)?u=await this.#i(r,l,c.apiKey,i):(I.error(`Either ${B(`--connector`)} or ${B(`--account-id`)} must be provided`),process.exit(1));if(k(a))try{f.writeFileSync(a,u,`utf-8`),I.success(`Connector written to file: ${B(a)}`)}catch(e){I.error(`Failed to write connector to file ${B(a)}: ${e.message}`),process.exit(1)}else if(I.log(`\n${t.blue.inverse(` CONNECTOR CONTENT `)}\n`),!i||i===`yaml`)I.log(this.#e(u));else if(i===`json`)try{L(JSON.parse(u))}catch{I.log(u)}else I.log(u);process.exit(0)}#e(e){return e.split(`
|
|
18
|
+
`).map(e=>{if(e.trim().startsWith(`#`))return t.gray(e);if(e.includes(`:`)){let n=e.indexOf(`:`),r=e.substring(0,n+1),i=e.substring(n+1),a=i,o=i.trim();return o===`true`||o===`false`?a=i.replace(o,t.cyan(o)):o===`null`||o===`~`?a=i.replace(o,t.gray(o)):/^-?\d+(\.\d+)?$/.test(o)?a=i.replace(o,t.green(o)):(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`)||o&&!o.startsWith(`-`))&&(a=i.replace(o,t.yellow(o))),t.red(r)+a}return e.trim().startsWith(`-`)?e.replace(`-`,t.gray(`-`)):e}).join(`
|
|
19
|
+
`)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,t,n,r){let i=d(`Getting connector ${B(e)} from registry...`).start();try{let a=Buffer.from(n).toString(`base64`),o=r?`?format=${r}`:``,s=await fetch(`${t}/registry/connectors/${e}${o}`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await z(s,`Failed to get connector ${B(e)} from the registry`),process.exit(1)),await s.text()}catch(n){i.stop(),I.error(`Failed to get connector ${B(e)} from the registry: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,t,n,r){let i=d(`Getting connector from account ${B(e)}...`).start();try{let a=Buffer.from(n).toString(`base64`),o=r?`?format=${r}`:``,s=await fetch(`${t}/accounts/${e}/connector${o}`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await z(s,`Failed to get connector from account ${B(e)}`),process.exit(1)),await s.text()}catch(n){i.stop(),I.error(`Failed to get connector from account ${B(e)}: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),process.exit(1)}}};const Qe=`http://localhost:4000`;var $e=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{ce(`${t.inverse(` Initialize profile `)}`);let e=await fe({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if(M(e))return j(`Configuration profile initialization cancelled`),process.exit(0);if(Y(e)){let t=await se({message:`Configuration profile with name ${B(e)} already exists. Do you want to overwrite it?`});if(M(t)||!t)return j(`Configuration profile initialization cancelled`),process.exit(0)}let r;if(n===`production`)r=`https://api.stackone.com`;else if(n===`staging`)r=`https://api.stackone-dev.com`;else{let e=await fe({message:`API URL`,placeholder:Qe,initialValue:Qe,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if(M(e))return j(`Configuration profile initialization cancelled`),process.exit(0);r=e}let i=await ue({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if(M(i))return j(`Configuration profile initialization cancelled`),process.exit(0);qe(e,{label:e,environment:n,apiUrl:r,apiKey:i}),le(`${t.green(`โ`)} Configuration profile ${B(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?I.error(`Prompt couldn't be rendered in the current environment`):I.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const Z={pending:`โ`,acceptRemote:`โ`,acceptLocal:`โ`,acceptBoth:`โ`,current:`โ`,arrow:`โ`,check:`โ`,cross:`โ`,warning:`โ `};var et=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=he({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
|
|
20
|
+
`:this.allResolved()?(this.cleanup(t),e({cancelled:!1,states:this.conflicts})):(this.moveToNextUnresolved(),this.render());break;case`q`:case`Q`:this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});break;case`a`:case`A`:this.acceptAllRemaining(`remote`),this.render();break;case`u`:case`U`:this.setCurrentChoice(`pending`),this.render();break}};process.stdin.on(`data`,n),this.currentCleanup=()=>{process.stdin.removeListener(`data`,n),process.stdin.isTTY&&process.stdin.setRawMode(!1),t.close()}}))}cleanup(e){this.currentCleanup?(this.currentCleanup(),this.currentCleanup=null):(process.stdin.isTTY&&process.stdin.setRawMode(!1),e.close())}advanceAfterChoice(e){this.allResolved()||this.moveToNextUnresolved(),this.render()}render(){U();let e=process.stdout.columns||80;this.renderHeader(e),this.renderProgressBar(e),this.renderCurrentConflict(e),this.renderControls(e)}renderHeader(e){let n=this.connectorId,r=`${this.localVersion} ${Z.arrow} ${this.remoteVersion}`,i=Math.max(0,e-17),a=Math.floor(i/2),o=i-a,s=` `.repeat(a)+`CONFLICT RESOLVER`+` `.repeat(o);I.log(``),I.log(t.bgBlue.white.bold(s)),I.log(t.gray(this.centerText(n,e))),I.log(t.gray(this.centerText(r,e))),I.log(``)}renderProgressBar(e){let n=this.conflicts.filter(e=>e.conflict.type===`conflict`),r=this.getCurrentConflictIndex(),i=n.map((e,n)=>{let i=n===r,a,o;switch(e.choice){case`remote`:a=i?Z.current:Z.acceptRemote,o=t.green;break;case`local`:a=i?Z.current:Z.acceptLocal,o=t.yellow;break;case`both`:a=i?Z.current:Z.acceptBoth,o=t.cyan;break;default:a=i?Z.current:Z.pending,o=i?t.white:t.gray}return o(a)}),a=n.filter(e=>e.choice!==`pending`).length,o=` Conflict ${r+1} of ${this.totalConflicts} โข ${a}/${this.totalConflicts} resolved `;I.log(t.gray(this.centerText(o,e))),I.log(this.centerText(i.join(` `),e)),I.log(``)}renderCurrentConflict(e){let n=this.conflicts[this.currentIndex];if(!n||n.conflict.type!==`conflict`)return;let r=n.conflict;if(I.log(t.gray(`_`.repeat(e))),I.log(`
|
|
21
|
+
|
|
22
|
+
`),r.local){let e=n.choice===`local`||n.choice===`both`?t.yellow.bold(`${Z.check} LOCAL (keeping)`):t.red.bold(`${Z.cross} LOCAL (removing)`),i=r.local.split(`
|
|
23
|
+
`).filter(e=>e!==``),a=i.slice(0,20),o=n.choice===`local`||n.choice===`both`?t.yellow:t.red,s=a.map(e=>o(`- ${e}`)).join(`
|
|
24
|
+
`),c=i.length>20?`\n${t.gray(`... and ${i.length-20} more lines`)}`:``;I.log(`${e}\n\n${s}${c}`)}if(I.log(`
|
|
25
|
+
|
|
26
|
+
`),I.log(t.gray(`_`.repeat(e))),I.log(`
|
|
27
|
+
|
|
28
|
+
`),r.remote){let e=n.choice===`remote`||n.choice===`both`?t.green.bold(`${Z.check} REMOTE (accepting)`):t.gray.bold(`${Z.pending} REMOTE (skipping)`),i=r.remote.split(`
|
|
29
|
+
`).filter(e=>e!==``),a=i.slice(0,20),o=n.choice===`remote`||n.choice===`both`?t.green:t.gray,s=a.map(e=>o(`+ ${e}`)).join(`
|
|
30
|
+
`),c=i.length>20?`\n${t.gray(`... and ${i.length-20} more lines`)}`:``;I.log(`${e}\n\n${s}${c}`)}I.log(`
|
|
31
|
+
|
|
32
|
+
`),I.log(t.gray(`_`.repeat(e))),I.log(``)}renderControls(e){let n=[t.green(`[R] Accept Remote`),t.yellow(`[L] Keep Local`),t.cyan(`[B] Keep Both`),t.gray(`[U] Undo`)],r=[t.gray(`[โ/โ] Navigate`),t.gray(`[A] Accept all remaining`)],i=this.allResolved()?[t.green.bold(`[Enter] Apply Changes`),t.gray(`[Esc] Cancel`)]:[t.gray(`[Enter] Next Unresolved`),t.gray(`[Esc] Cancel`)];I.log(this.centerText(n.join(` `),e)),I.log(``),I.log(this.centerText(r.join(` `),e)),I.log(``),I.log(this.centerText(i.join(` `),e)),this.allResolved()&&(I.log(``),I.log(t.green.bold(this.centerText(`โ All conflicts resolved!`,e))))}renderFinalSummary(){U();let e=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=0,r=0,i=0;for(let t of e)switch(t.choice){case`remote`:n++;break;case`local`:r++;break;case`both`:i++;break}let a=[t.green.bold(`Conflict resolution complete`),``,`${t.bold(this.totalConflicts)} conflicts resolved:`,``,`${t.green(Z.acceptRemote)} Accepted remote: ${n}`,`${t.yellow(Z.acceptLocal)} Kept local: ${r}`,`${t.cyan(Z.acceptBoth)} Kept both: ${i}`];I.box(a.join(`
|
|
33
|
+
`))}renderCancelled(){U(),I.log(t.yellow(`Conflict resolution cancelled`)),I.log(``),I.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const tt=`https://api.stackone.com`;var nt=class{async execute({profile:e,connector:n,outputPath:r,apiUrl:i,apiKey:a}={}){if(O(n)&&(I.error(`Connector identifier is required`),I.log(`Please provide a connector identifier using the ${B(`--connector`)} option in the format: ${B(`provider_key@version`)} or ${B(`provider_key`)}`),I.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!a&&(I.error(`Profile or API key is required`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`To create a profile, run ${B(`stackone init`)}.`),process.exit(1)),e&&a&&(I.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&i&&I.warn(`Specifying ${B(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Y(e)){I.error(`Configuration profile ${B(e)} not found`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.\n`);let n=X();n.length>0&&(I.info(`Available configuration profiles:`),n.forEach(e=>{I.log(` - ${t.blue(e)}`)})),process.exit(1)}let o=e?J(e):{apiUrl:i??tt,apiKey:a};o?.apiKey||(I.error(`API key is missing`),I.log(`Please provide a valid API key in the profile or via the ${B(`--api-key`)} option.`),process.exit(1));let s=o.apiUrl??tt,[c,l]=n.split(`@`),u=await this.#f(c,s,o.apiKey,l??`latest`),d=this.#e(u),f=d.version??`unknown`,p=this.#t(r,d.key,f),m=this.#r(p),h=m===null,g=u;if(!h){let e=this.#i(m,p);e&&(I.warn(e.message),e.errors.length>0&&R(e.errors,!1),I.log(``));let t=e?void 0:this.#e(m);if(this.#o(m,u)){this.#a(m,u,p);let e=t?.version??`unknown`,r=await this.#s(m,u,n,e,f);r.action===`cancel`&&(j(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(I.log(``),I.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(g=r.resolvedContent)}else I.info(`No changes detected in connector configuration.`),process.exit(0)}let _=P(g).connector,v=_?.key??d.key,y=_?.version??f,b=this.#t(r,v,y),x=b;if(b!==p){let e=await this.#n(b);I.log(``),e!==void 0&&(x=e)}await this.#d(x,g),h?I.success(`Connector ${B(v)}@${B(y)} pulled successfully (new connector)`):I.success(`Connector ${B(v)}@${B(y)} updated successfully`);let ee=v===d.key?B(v):`${B(d.key)} ${t.whiteBright(`โ`)} ${B(v)}`,S=y===f?B(y):`${B(f)} ${t.whiteBright(`โ`)} ${B(y)}`,C=x===p?B(x):`${B(p)}\n ${t.whiteBright(`โ`)} ${B(x)}`;I.log(`\n${t.blue.inverse(` CONNECTOR DETAILS `)}\n`),I.log(` Provider: ${ee}`),I.log(` Version: ${S}`),I.log(` Output file: ${C}`),process.exit(0)}#e(e){let t=P(e),n=t?.errors??[];if(t.success)return t.connector;I.error(`Connector pulled from the registry is not valid`),I.log(`Please make sure you are using the latest version of the StackOne CLI by running ${B(`stackone update`)}`),n.length>0&&R(n,!0),process.exit(1)}#t(e,t,n){let r=`${t}_v${n.replaceAll(`.`,`-`)}.s1.yaml`;return e?(f.existsSync(e)&&(f.statSync(e).isDirectory()||(I.error(`Output path ${B(e)} is not a directory`),I.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),x.resolve(e,t,r)):x.resolve(process.cwd(),`connectors`,t,r)}async#n(e){if(!f.existsSync(e))return;let t=x.basename(e),n=x.dirname(e);I.warn(`File ${B(t)} already exists at ${B(n)}`);let r=await de({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((M(r)||r===`cancel`)&&(j(`Operation cancelled. No local changes were made.`),process.exit(0)),r===`override`)return;let i=await fe({message:`Enter the new filename:`,placeholder:t,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=x.join(n,e.trim());if(f.existsSync(t))return`File ${e} already exists`}});return M(i)&&(j(`Operation cancelled. No local changes were made.`),process.exit(0)),x.join(n,i.trim())}#r(e){if(!f.existsSync(e))return null;try{return f.readFileSync(e,`utf-8`)}catch{return null}}#i(e,t){try{let n=P(e);if(!n.success){let e=n.errors??[];return{message:`Local connector ${B(x.basename(t))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${B(x.basename(t))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,n,r){let i=me(e,n);if(!i.some(e=>e.added||e.removed)){I.info(`No changes detected in connector configuration.`);return}I.log(`${t.blue.inverse(` CHANGES `)}\n`),I.log(t.gray(`--- local: ${r}`)),I.log(t.gray(`+++ remote: StackOne Registry`)),I.log(``);let a=0,o=0;for(let e of i){let n=e.value.split(`
|
|
34
|
+
`).filter(e=>e!==``);if(e.added){a+=n.length;for(let e of n)I.log(t.green(`+ ${e}`))}else if(e.removed){o+=n.length;for(let e of n)I.log(t.red(`- ${e}`))}else if(n.length<=6)for(let e of n)I.log(t.gray(` ${e}`));else{for(let e=0;e<3;e++)I.log(t.gray(` ${n[e]}`));I.log(t.gray(` ... (${n.length-6} unchanged lines)`));for(let e=n.length-3;e<n.length;e++)I.log(t.gray(` ${n[e]}`))}}I.log(``),I.log(t.gray(`Summary: ${t.green(`+${a}`)} additions, ${t.red(`-${o}`)} deletions`))}#o(e,t){return me(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){I.log(``);let a=await de({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(M(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=me(e,t),o=this.#u(a);if(o.length===0)return I.info(`No conflicts to resolve.`),t;let s=new et(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=P(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return U(),I.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return U(),I.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:n}=await import(`readline`);return new Promise(r=>{U();let i=(e||[{message:`Unknown validation error`}]).map(e=>` โข ${e.message}`).join(`
|
|
35
|
+
`);I.box({title:`โ ๏ธ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${i}`,style:{borderColor:`yellow`,padding:1}}),I.log(``),I.log(t.bold(` Choose an action:`)),I.log(``),I.log(t.cyan(` [B]`)+` โ Go back to conflict resolution`),I.log(t.dim(` Modify your choices to fix the validation errors`)),I.log(``),I.log(t.yellow(` [S]`)+` ๐พ Save anyway`),I.log(t.dim(` Save the invalid configuration (not recommended)`)),I.log(``),I.log(t.red(` [C]`)+` โ Cancel`),I.log(t.dim(` Discard all changes`)),I.log(``);let a=n({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let o=e=>{let t=e.toString().toLowerCase(),n=()=>{process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(!1),a.close()};if(t===``||t===`\x1B`){n(),r(`cancel`);return}switch(t){case`b`:n(),r(`back`);break;case`s`:n(),r(`save`);break;case`c`:case`q`:n(),r(`cancel`);break}};process.stdin.on(`data`,o)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,t){let n=x.dirname(e);f.existsSync(n)||f.mkdirSync(n,{recursive:!0});try{f.writeFileSync(e,t,`utf-8`)}catch(t){I.error(`Failed to write connector to file ${B(e)}: ${t.message}`),process.exit(1)}}async#f(e,t,n,r){let i=d(`Pulling connector ${B(e)}@${B(r)} from registry...`).start();try{let a=Buffer.from(n).toString(`base64`),o=`${t}/registry/connectors/${e}@${r}`,s=await fetch(o,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await this.#p(s,e,r),process.exit(1)),await s.text()}catch(n){i.stop(),I.error(`Failed to pull connector ${B(e)}@${B(r)} from the registry: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,t,n){switch(e.status){case 401:case 403:I.error(`Access denied`),I.log(`Please ensure that your API key is valid and has the ${B(`connectors:read`)} scope required to pull connectors.`);break;case 404:I.error(`Connector ${B(t)}@${B(n)} was not found in the registry`),await this.#m(t);break;case 429:I.error(`Rate limit exceeded`),I.log(`Too many requests. Please wait a moment before trying again.`);break;default:await z(e,`Failed to pull connector ${B(t)}`)}}async#m(e){I.info(`To see available versions, check the connector documentation or contact support.`)}};const rt=`https://api.stackone.com`;var it=class{async execute({profile:e,fileOrDir:n,apiUrl:r,apiKey:i}={}){if(!e&&!i&&(I.error(`Profile or API key is required`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`To create a profile, run ${B(`stackone init`)}.`),process.exit(1)),e&&i&&(I.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&I.warn(`Specifying ${B(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!Y(e)){I.error(`Configuration profile ${B(e)} not found`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.\n`);let n=X();n.length>0&&(I.info(`Available configuration profiles:`),n.forEach(e=>{I.log(` - ${t.blue(e)}`)})),process.exit(1)}let a=e?J(e):{apiUrl:r??rt,apiKey:i};a?.apiKey||(I.error(`API key is missing`),I.log(`Please provide a valid API key in the profile or via the ${B(`--api-key`)} option.`),process.exit(1)),n||(I.error(`File or directory is required.`),process.exit(1));try{v(n)}catch{I.error(`File or directory not found: ${t.red(n)}`),process.exit(1)}let o=v(n),s=a.apiUrl??rt;if(o.isDirectory()){let e=ot(n),r=0;e.length===0?(I.error(`No .s1.yaml connector files found in the directory: ${n}.`),process.exit(1)):(I.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),I.log(``));for(let t of e)await this.uploadFile(t,s,a.apiKey)&&r++;r===0?I.error(`Error while pushing connectors: no files were uploaded`):(I.log(``),I.info(`Upload completed: ${t.green(r)} of ${t.blue(e.length)} file(s) uploaded successfully.`)),process.exit(r>0?0:1)}else n.endsWith(`.s1.yaml`)||(I.error(`Only ${B(`.s1.yaml`)} files are supported for upload`),process.exit(1));let c=await this.uploadFile(n,s,a.apiKey);process.exit(c?0:1)}async uploadFile(e,t,n){let r=d(`๐ค Pushing connector in ${ee(e)}...`).start();try{let i=at(e);if(!i)return!1;let a=ee(e),o=new FormData,s=new Blob([i],{type:`application/x-yaml`});o.append(`file`,s,a);let c=Buffer.from(n).toString(`base64`),l=await fetch(`${t}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${c}`},body:o});if(r.stop(),!l.ok)return await z(l,`Failed to push connector in ${B(a)} to the registry`),!1;let u=await l.json();return I.success(`Successfully uploaded ${B(a)} with connector ${B(u.provider)}@${B(u.version)}`),!0}catch(n){return r.stop(),I.error(`Failed to upload file ${B(e)}: ${n}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),!1}}};const at=e=>{let t=N(e),n=P(t),r=n?.errors??[];if(n.success)return t;r.length>0?(I.error(`Connector in ${H(e)} is not valid`),R(r,!0)):I.error(`Connector in ${H(e)} is not valid. Please check the file for errors.`)},ot=e=>{let t=[],n=g(e,{withFileTypes:!0});for(let r of n){let n=C(e,r.name);r.isDirectory()?t.push(...ot(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},st=A.object({provider_key:A.string().optional(),provider_version:A.string().optional(),auth_config_key:A.string(),environment:A.string().default(`production`),organization_id:A.string().default(`cli-organization-id`),account_id:A.string().default(`cli-account-secure-id`),project_id:A.string().default(`cli-project-secure-id`),credentials:A.record(A.string(),A.any()).default({})}),ct=A.record(A.string(),A.any()),lt=A.object({path:A.record(A.string(),A.any()).default({}),queryParams:A.record(A.string(),A.any()).default({}),header:A.record(A.string(),A.any()).default({}),body:A.record(A.string(),A.any()).default({})}),Q=`https://api.stackone.com`;var ut=class{async execute({connector:e,action:n,actionId:r,account:i,accountId:a,params:o,credentials:s,profile:c,outputFile:l,debug:u,apiUrl:d,apiKey:p}={}){if(!c&&!p&&a&&(I.error(`Profile or API key is required when providing an account ID`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`To create a profile, run ${B(`stackone init`)}.`),process.exit(1)),c&&p&&(I.error(`Please provide either a profile or an API key, not both`),process.exit(1)),c&&d&&I.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),c&&!Y(c)){I.error(`Configuration profile ${B(c)} not found`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.\n`);let e=X();e.length>0&&(I.info(`Available configuration profiles:`),e.forEach(e=>{I.log(` - ${t.blue(e)}`)})),process.exit(1)}let m=c?J(c):{apiUrl:d??Q,apiKey:p};O(i)&&O(a)&&(I.error(`A valid account or account ID is required to run an action`),process.exit(1));let h;if(k(e))if(this.#a(e)){!c&&!p&&(I.error(`Profile or API key is required when using a connector identifier`),I.log(`Please provide a profile using the ${B(`--profile`)} option or an API key using the ${B(`--api-key`)} option.`),I.log(`Run ${B(`stackone init`)} to create a new configuration profile.`),process.exit(1));let t=this.#o(e);h=await this.#s(t,m?.apiUrl??Q,m?.apiKey)}else h=this.#e(e);else k(a)&&(h=await this.#c(a,m?.apiUrl??Q,m?.apiKey));let g=k(n)?this.#r(n,e):h;O(g)&&(I.error(`A valid connector is required to run an action.`),process.exit(1));let _=k(g?.actions)?Object.keys(g?.actions).length:0,v=k(g?.actions)?Object.keys(g.actions)[_-1]:void 0,y=k(v)?g?.actions?.[v]?.id:void 0,b=(k(r)&&!r?.startsWith(`${g.key}_`)?`${g.key}_${r}`:r)??y;O(b)&&(I.error(`A valid action ID is required to run an action`),process.exit(1));let x=k(a)?await this.#l(a,m?.apiUrl??Q,m?.apiKey):{},ee=k(i)?this.#i(i,g.key??`unknown`,g.version??`unknown`):void 0,S=k(s)?this.#u(s):{},C={...x,...ee,credentials:{...x.credentials??{},...S}};O(C)&&(I.error(`A valid account data is required to run an action.`),process.exit(1));let te=g.actions?.[b];O(te)&&(I.error(`Action ID ${B(b)} not found in the connector ${B(g.key)}@${B(g.version)}.`),process.exit(1));let w=k(o)?this.#d(o,b):{path:{},queryParams:{},header:{},body:{}},T=Date.now(),ne=await this.#f({connector:g,actionId:b,account:C,queryParams:{...w.queryParams,...u?{debug:`true`}:{}},pathParams:w.path,body:w.body,headers:w.header}),E=Date.now()-T;if(k(l))try{f.writeFileSync(l,JSON.stringify(ne.output,null,2),`utf-8`),I.info(`Output written to file: ${l}`)}catch(e){I.error(`Failed to write output to file ${l}: ${e.message}`),process.exit(1)}else I.log(`\n${t.blue.inverse(` ACTION OUTPUT `)}`),L(ne.output);I.log(``),I.info(`Action ${B(b)} from connector ${B(g?.key)}@${B(g?.version)} finished in ${t.yellowBright((E/1e3).toFixed(2))} seconds.`),process.exit(0)}#e=e=>{let t=e;try{t=N(e)}catch{}return t?this.#n(t):void 0};#t=e=>{try{return N(e)}catch(t){I.error(`Failed to load connector file from ${B(e)}: ${t.message}`),process.exit(1)}};#n=e=>{let t=P(e),n=t?.errors??[];if(t.success)return t.connector||(I.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(I.error(`Connector is not valid`),R(n,!0),process.exit(1)):(I.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#r=(e,t)=>{let n=e;try{n=f.readFileSync(e,`utf-8`)}catch{}O(t)&&(I.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#t(t)} - ${n.split(`
|
|
36
|
+
`).map((e,t)=>t===0?e:` ${e}`).join(`
|
|
37
|
+
`)}`;return this.#n(r)};#i=(e,t,n)=>{let r=e;try{r=f.readFileSync(e,`utf-8`)}catch{}try{let e=st.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}I.error(`Failed to parse account information`),R(t,!1),t.length===0&&I.log(e.message),process.exit(1)}};#a=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#o=e=>e.includes(`@`)?e:`${e}@latest`;#s=async(e,t,n)=>{(O(e)||O(t)||O(n))&&(I.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let r=d();try{r.text=`Fetching connector ${B(e)} from registry...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/registry/connectors/${e}`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await z(a,`Failed to fetch connector ${B(e)} from registry`),process.exit(1));let o=await a.text(),s=this.#n(o);return I.success(`Fetched connector ${B(s.key)}@${B(s.version)} from registry`),s}catch(n){r.stop(),I.error(`Failed to fetch connector ${B(e)} from registry: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),process.exit(1)}};#c=async(e,t,n)=>{(O(e)||O(t)||O(n))&&(I.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let r=d();try{r.text=`Fetching connector for account ${B(e)} from API...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await z(a,`Failed to fetch connector`),process.exit(1));let o=await a.text(),s=this.#n(o);return I.success(`Fetched connector ${B(s.key)}@${B(s.version)} for account ${B(e)}`),s}catch(e){r.stop(),I.error(`Failed to fetch connector: ${e.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),process.exit(1)}};#l=async(e,t,n)=>{(O(e)||O(t)||O(n))&&(I.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let r=d();try{r.text=`Fetching account ${B(e)} information from API...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await z(a,`Failed to fetch account ${B(e)} information`),process.exit(1));let o=await a.json();return I.success(`Fetched account ${B(e)} information from project ${B(o.project_id)}`),{providerKey:o.provider_key,providerVersion:o.provider_version,authConfigKey:o.auth_config_key,environment:o.environment,organizationId:o.organization_id,secureId:o.account_id,projectSecureId:o.project_id,credentials:o.credentials}}catch(n){r.stop(),I.error(`Failed to fetch account ${B(e)} information: ${n.message}`),I.log(`Please ensure that the API at ${V(t)} is reachable and the API key is valid`),process.exit(1)}};#u=e=>{let t=e;try{t=f.readFileSync(e,`utf-8`)}catch{}try{return ct.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}I.error(`Failed to parse credentials`),R(t,!1),t.length===0&&I.log(e.message),process.exit(1)}};#d=(e,t)=>{let n=e;try{n=f.readFileSync(e,`utf-8`)}catch{}try{return lt.parse(JSON.parse(n))}catch(e){let n=[];try{n=JSON.parse(e.message)}catch{}I.error(`Invalid parameters for action ${B(t)}.`),R(n,!1),n.length===0&&I.log(e.message),process.exit(1)}};async#f({connector:e,actionId:n,account:r,pathParams:i={},queryParams:a={},body:o={},headers:s={}}){try{let c=await pe({mode:`action_id`,actionId:n,account:r,connector:e,pathParams:i,queryParams:a,body:o,headers:s,getHttpClient:async()=>new ge});if(c.response?.successful){let e={...this.#p(a,c.steps),...oe(c.outputs)?c.outputs:{data:c.outputs}};return{statusCode:c.response?.statusCode,output:e}}else{let r=c.response?.message??`An error occurred while processing the request`;I.error(`Action ID ${B(n)} from connector ${B(e.key)}@${B(e.version)} failed with status ${c.response?.statusCode}: ${r}`);let i={...this.#p(a,c.steps)};Object.keys(i).length>0&&(I.log(`${t.yellow.inverse(` EXECUTION DETAILS `)}`),L(i)),process.exit(1)}}catch(e){this.#m(e)}}#p(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#m(e){let t=e;switch(O(t.errorType)&&(I.error(`An unknown error occurred`),I.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:I.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;I.error(`Invalid action inputs`),R(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:I.error(`Invalid cursor: ${t.message}`);break;default:I.error(`An error occurred: ${t.message}`)}process.exit(1)}};const $=()=>{try{let e=C(S(xe(import.meta.url)),`..`,`package.json`);return JSON.parse(h(e,`utf8`)).version}catch{return`unknown`}},dt=u(i);var ft=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=d(),this.currentVersion=$()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let n=await this.getLatestVersion();this.spinner.stop(),n||(I.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(n,this.currentVersion)?(I.box(`New version available: ${t.yellow(this.currentVersion)} โ ${t.green(n)}`),await this.performUpdate(n)):e.force?(I.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(n)):I.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),I.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await dt(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return be.gt(e,t)}isUsingVolta(){if(typeof process.env.VOLTA_HOME!=`string`||process.env.VOLTA_HOME.length===0)return!1;let e=l(process.env.VOLTA_HOME,`bin`),t=l(e,`stackone`),n=l(e,`stackone.exe`);return F(t)||F(n)}async performUpdate(e){let t=this.isUsingVolta();this.spinner.text=`Updating to latest version (${B(e)})...`,this.spinner.start();try{await dt(t?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`,{encoding:`utf-8`}),this.spinner.stop(),I.success(`StackOne CLI updated successfully to latest version (${B(e)})`)}catch{this.spinner.stop();let e=t?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`;throw Error(`Failed to install update. Please try manually: ${e}`)}}};const pt=()=>{I.log(`${t.gray.inverse(` CONNECTORS VALIDATION `)} ${t.yellow.inverse(` WATCH MODE `)}\n`)};var mt=class{async execute(e){let{watchMode:n,fileOrDir:r}=e,i=d(`Watching for file changes... ${t.gray(`(press "q" to quit)`)}`);if(!r)return;let a=te(r);try{await Ce(a)}catch{I.error(`The specified path does not exist: ${a}\n`),process.exit(1)}if(n){U();let e={},{watch:n}=await import(`chokidar`),r=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let o=()=>{c.close(),i.stop(),r.close(),I.log(t.grey(`
|
|
38
|
+
Exiting watch mode...`)),process.exit(0)};pt(),I.start(`Validating connectors...`);let s=await vt(a);e=ht(e,s||{}),gt(e,a),i.start();let c=n(a,{persistent:!0,ignoreInitial:!0}),l=async n=>{if(!n.endsWith(`.s1.yaml`)&&!n.endsWith(`s1.partial.yaml`))return;let r=n.endsWith(`s1.partial.yaml`)?await bt(n):[n];if(!(!r||r.length===0)){U(),i.stop(),pt(),I.log(t.gray(`File change detected: ${n}`)),I.start(`Validating connectors...`);for(let t of r){let n=await vt(t);e=ht(e,n||{})}gt(e,a),i.start()}};c.on(`change`,async e=>await l(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&o()}),process.on(`SIGINT`,()=>{o()})}else await vt(a,I),process.exit(0)}};const ht=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},gt=(e,n)=>{U(),pt();let r=0,i=0;for(let[t,n]of Object.entries(e))n===null?r++:(I?.error(`Connector ${B(t)} is not valid`),R(n,!0),i++);I.log(``),I.log(t.blue.inverse(` Validation Summary `)),I.log(`Connectors path: ${B(n)}`),I.log(`${r===0?t.red(`0`):t.green(r)} valid, ${i===0?t.green(`0`):t.red(i)} invalid connectors\n`)},_t=async e=>{let t=[],n=await Se(e);for(let r of n){let n=C(e,r),i=await Ce(n);i.isDirectory()?t.push(...await _t(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},vt=async(e,n)=>{let r=await Ce(e),i={};if(r.isDirectory()){let r=await _t(e);if(r.length===0)return n?.error(`No StackOne connector found in ${H(e)}`),n?.log(`Connector files need to have the extension ${B(`*.s1.yaml`)}`),null;let a=0,o=0;for(let e of r){let t=await yt(e,n);t===null?a++:(n?.log(``),o++),i[e]=t}return n?.log(``),n?.log(t.blue.inverse(` Validation Summary `)),n?.log(`${a===0?t.red(`0`):t.green(a)} valid, ${o===0?t.green(`0`):t.red(o)} invalid connectors`),i}else if(r.isFile()&&e.endsWith(`s1.yaml`))return i[e]=await yt(e,n),i;else if(r.isFile()&&e.endsWith(`partial.yaml`)){n?.error(`Partial connector files cannot be validated directly`),n?.log(`The file ${H(e)} is a partial connector file.`);let t=await bt(e);return t&&t?.length>0&&n?.log(`Did you mean ${B(t[0])}?`),null}else return n?.error(`No StackOne connector found in ${H(e)}`),n?.log(`Connector files need to have the extension ${B(`*.s1.yaml`)}`),null},yt=async(e,t)=>{let n=P(N(e)),r=n?.errors??[];if(n.success){let n=e.split(`/`).pop()||e;return t?.success(`Connector ${B(n)} is valid!`),null}else if(r.length>0)return t?.error(`Connector ${B(e)} is not valid`),t&&R(r,!0),r;else return t?.error(`Connector ${B(e)} is not valid. Please check the file for errors`),[]},bt=async e=>{let t=S(e);try{return(await Se(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>C(t,e))}catch{}},xt=l(we(),`.stackone`),St=l(xt,`version-check.json`),Ct=(e=!1)=>{let t=Dt(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=wt();e&&Tt(e)&&Et(e),Ot({lastCheckTime:n})}},wt=()=>{try{return a(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},Tt=e=>{try{let t=$();return be.gt(e,t)}catch{return!1}},Et=e=>{let n=$(),r=`Update available: ${t.dim(n)} โ ${t.green(e)}`,i=`\n\nRun ${t.cyan(`stackone update`)} to update`;I.box(r,i)},Dt=()=>{try{if(!F(St))return null;let e=ve(St,`utf-8`);return JSON.parse(e)}catch{return null}},Ot=e=>{try{F(xt)||_e(xt,{recursive:!0}),ye(St,JSON.stringify(e,null,2),`utf-8`)}catch{}};var kt=class{constructor(e=new r,t=$()){this.program=e,this.version=t,this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new $e,r=new it,i=new nt,a=new Ye,o=new Ze,s=new mt,c=new Ve,l=new Ge,u=new Le,d=new ut,f=new ft;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,n)=>{n(t.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new n(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,fileOrDir:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new n(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{a.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).description(`Get a connector from the StackOne registry`).action(e=>{o.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{i.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new n(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{s.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).description(`Run a connector action`).action(e=>{d.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey})});let p=this.program.command(`agent`).description(`StackOne agent commands`);p.command(`setup`).option(`-g, --global`,`Setup global configuration`).option(`-l, --local`,`Setup local project configuration`).description(`Setup StackOne agent (global or local)`).action(e=>{e.global?c.execute():l.execute()}),p.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{u.execute()}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{f.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{I.log(`${t.inverse.greenBright(`StackOne`)} ${t.grey(`CLI`)} ${t.whiteBright(this.version)}`),Ct(!0),process.exit(0)})}run(){process.argv.includes(`version`)||Ct(),this.program.parse(process.argv)}};export{kt as t};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`chalk`);c=s(c);let l=require(`commander`),u=require(`node:child_process`),d=require(`node:fs/promises`),f=require(`node:path`),p=require(`node:util`),m=require(`ora`);m=s(m);let h=require(`fs`);h=s(h);let g=require(`os`),_=require(`path`);_=s(_);let v=require(`consola`),y=require(`json-colorizer`),b=require(`node:process`),x=require(`node:readline`),S=require(`inquirer`);S=s(S);let C=require(`@stackone/agent-config`),w=require(`@stackone/utils`),T=require(`@clack/prompts`),E=require(`@stackone/connect-sdk`),D=require(`diff`),ee=require(`readline`),O=require(`@stackone/transport`),k=require(`node:fs`),A=require(`semver`);A=s(A);let te=require(`url`),j=require(`fs/promises`),ne=require(`node:os`);const M=`config.json`,N=`agent-config.json`,P=(0,v.createConsola)({level:4,formatOptions:{columns:80,colors:!0,compact:!1,date:!1}}),F=e=>{P.log((0,y.colorize)(e,{indent:2,colors:{Whitespace:y.color.gray,Brace:y.color.gray,Bracket:y.color.gray,Colon:y.color.gray,Comma:y.color.gray,StringKey:y.color.white,StringLiteral:y.color.yellow,NumberLiteral:y.color.green,BooleanLiteral:y.color.cyan,NullLiteral:y.color.white}}))},I=(e=[],t)=>{e.length!==0&&(P.log(`${e.length} error${e.length>1?`s`:``} found:`),e.forEach(e=>{let n=`line`in e?e.line:void 0,r=t&&n?`L${n}: `:``;P.log(`- ${r}${e.message}`)}))},L=async(e,t=`Request failed`)=>{P.error(`${t}: ${e.status} - ${e.statusText}`);let n=await e.text();if(!n)return;let r;try{r=JSON.parse(n)}catch{}r?F(r):P.log(n)},R=e=>c.default.cyan(e),z=e=>c.default.yellow(e),B=e=>c.default.red(e),V=()=>{process.stdout.write(`\x1Bc`)};var H=class{static{this.configDir=(0,_.join)((0,g.homedir)(),`.stackone`)}static ensureConfigDir(){if((0,h.existsSync)(this.configDir)){if(!(0,h.lstatSync)(this.configDir).isDirectory()){let e=null;try{P.info(`.stackone exists as a file, checking for migration to config directory...`),e=(0,h.readFileSync)(this.configDir,`utf8`)}catch{}if((0,h.rmSync)(this.configDir,{force:!0}),require(`fs`).mkdirSync(this.configDir,{recursive:!0}),e)try{JSON.parse(e),(0,h.writeFileSync)((0,_.join)(this.configDir,M),e,`utf8`),P.success(`Migrated existing .stackone file content to config.json`)}catch{P.warn(`Note: Existing .stackone file was not valid JSON, skipping migration`)}else P.warn(`Note: Existing .stackone file was not valid JSON, skipping migration`)}}else require(`fs`).mkdirSync(this.configDir,{recursive:!0})}static getConfigDir(){return this.configDir}static writeConfigFile(e,t,n){this.ensureConfigDir();let r=(0,_.join)(this.configDir,e);(0,h.writeFileSync)(r,t,`utf8`),n?.mode!==void 0&&require(`fs`).chmodSync(r,n.mode)}static readConfigFile(e){this.ensureConfigDir();let t=(0,_.join)(this.configDir,e);if(!(0,h.existsSync)(t))return null;try{return(0,h.readFileSync)(t,`utf8`)}catch{return null}}static deleteConfigFile(e){let t=(0,_.join)(this.configDir,e);(0,h.existsSync)(t)&&(0,h.rmSync)(t,{force:!0})}};const re=`stackone-agent-global`,ie=`stackone-agent-local`,ae=process.env.STACKONE_AGENT_SERVER_URL||`https://mcp-internal-falcon.stackonehq.workers.dev/mcp`;async function oe(e){H.writeConfigFile(N,JSON.stringify(e,null,2),{mode:384})}async function se(){let e=H.readConfigFile(N);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function ce(){H.deleteConfigFile(N)}function U(){return ae}function W(){return`stackone-agent-global`}function G(){return`stackone-agent-local`}function le(e){return new Date(e)<=new Date}function ue(e){return!!e?.apiKey&&!le(e.expiresAt)}const de=(0,p.promisify)(u.exec);async function fe(e){try{let t=await(0,d.readFile)(e,`utf-8`),n=JSON.parse(t),r=!1;if(n.mcpServers&&typeof n.mcpServers==`object`){for(let[e,t]of Object.entries(n.mcpServers))if(t&&typeof t==`object`&&`transport`in t){let e=t.transport;if(e&&typeof e==`object`&&`headers`in e){let t=e.headers;if(t&&typeof t==`object`&&`Authorization`in t){let e=t.Authorization;typeof e==`string`&&e.startsWith(`Bearer `)&&!e.includes("${")&&(t.Authorization="Bearer ${STACKONE_AGENT_MCP_TOKEN}",r=!0)}}}}return r&&await(0,d.writeFile)(e,JSON.stringify(n,null,2)),r}catch{return!1}}var pe=class{async execute(){P.log(c.default.blue.bold(`๐งน StackOne Agent Cleanup
|
|
2
|
+
`));let e={configsCleaned:0};try{let t=(0,m.default)(`Removing stored configuration...`).start();await ce(),t.succeed(`Removed ~/.stackone/agent-config.json`);let n=(0,m.default)(`Removing MCP servers from Claude...`).start(),r=0;try{await de(`claude mcp remove ${W()} 2>/dev/null`),r++}catch{}try{await de(`claude mcp remove ${G()} 2>/dev/null`),r++}catch{}r>0?n.succeed(`Removed ${r} MCP server(s) from Claude`):n.warn(`No MCP servers found in Claude (already removed or not configured)`);let i=(0,m.default)(`Checking for .mcp.json file...`).start(),a=(0,f.join)(process.cwd(),`.mcp.json`);try{await fe(a)?(e.configsCleaned=1,i.succeed(`Cleaned .mcp.json (replaced tokens with environment variables)`)):i.info(`.mcp.json already uses environment variables or not found`)}catch{i.info(`.mcp.json not found (already cleaned or not created)`)}P.success(`Cleanup complete!`),P.log(c.default.white(`
|
|
3
|
+
What was removed:`)),P.log(c.default.cyan(` โข ~/.stackone/agent-config.json`)),P.log(c.default.cyan(` โข MCP server from Claude configuration`)),e.configsCleaned>0&&P.log(c.default.cyan(` โข Hardcoded credentials from .mcp.json`)),P.log(c.default.dim(`
|
|
4
|
+
To authenticate again:`)),P.log(c.default.cyan(` stackone agent setup --global`),c.default.dim(`(for global setup)`)),P.log(c.default.cyan(` stackone agent setup --local`),c.default.dim(`(for local project setup)`)),P.log(``),process.exit(0)}catch(e){e instanceof Error?P.error(e.message):P.error(`Unknown error occurred`),process.exit(1)}}},me=class{constructor(e){this.baseUrl=e||process.env.AUTH_SERVER_URL||`https://idp-api.stackone.com`}async login(e,t){try{let n=`${this.baseUrl}/auth/sign-in/mcp`,r=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({email:e,password:t})});if(!r.ok){let e=await r.text(),t={};try{t=JSON.parse(e)}catch{}return{success:!1,error:t.error||`HTTP ${r.status}: ${r.statusText}`}}let i=await r.text(),a=JSON.parse(i);return a.apiKey?{success:!0,apiKey:a.apiKey}:{success:!1,error:`Invalid response format`}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Network error occurred`}}}async validateKey(e){try{let t=`${this.baseUrl}/api-key/verify`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({key:e})});if(!n.ok){let e=await n.text(),t={};try{t=JSON.parse(e)}catch{}return{valid:!1,error:t.error||`HTTP ${n.status}: ${n.statusText}`}}let r=await n.text();return JSON.parse(r)}catch(e){return{valid:!1,error:e instanceof Error?e.message:`Network error occurred`}}}};const he=new me,ge=(0,p.promisify)(u.exec);function _e(e){let t=new Date(e),n=new Date,r=t.getTime()-n.getTime(),i=Math.floor(r/(3600*1e3)),a=t.toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,hour12:!0});return`${t.toDateString()===n.toDateString()?`Today`:t.toDateString()===new Date(n.getTime()+864e5).toDateString()?`Tomorrow`:t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`})} at ${a} (${i} hours from now)`}var ve=class{async execute(){P.log(c.default.blue.bold(`๐ค StackOne Agent Setup - Global Configuration
|
|
5
|
+
`));try{let e=process.cwd(),t=await(0,d.access)(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),n=await(0,d.access)(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(t||n){P.warn(`Existing local setup detected:`),t&&P.log(c.default.dim(` โข CLAUDE.md found in current directory`)),n&&P.log(c.default.dim(` โข .mcp.json found in current directory`)),P.log(``);let{proceed:e}=await S.default.prompt([{type:`confirm`,name:`proceed`,message:`Re-authenticate globally despite existing local setup?`,default:!0}]);e||(P.log(c.default.dim(`
|
|
6
|
+
Setup cancelled.`)),process.exit(0)),P.log(``)}let r=await se(),i;if(r?.email){P.log(c.default.dim(`Last used email: ${r.email}\n`));let{useExisting:e}=await S.default.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);if(e)i=r.email;else{let e=(0,x.createInterface)({input:b.stdin,output:b.stdout});i=await new Promise(t=>{e.question(c.default.white(`Email: `),e=>{t(e.trim())})}),e.close(),i||(P.error(`Email is required`),process.exit(1))}}else{let e=(0,x.createInterface)({input:b.stdin,output:b.stdout});i=await new Promise(t=>{e.question(c.default.white(`Email: `),e=>{t(e.trim())})}),e.close(),i||(P.error(`Email is required`),process.exit(1))}let a=await S.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);a.password||(P.error(`Password is required`),process.exit(1)),P.log(``);let o=(0,m.default)(`Authenticating...`).start(),s=await he.login(i,a.password);(!s.success||!s.apiKey)&&(o.fail(`Authentication failed`),P.error(`${s.error||`Invalid credentials`}`),P.log(c.default.dim(`Please check your email and password and try again.
|
|
7
|
+
`)),process.exit(1)),o.succeed(`Login successful!`);let l=new Date(Date.now()+1440*60*1e3).toISOString();await oe({apiKey:s.apiKey,userId:i,email:i,expiresAt:l,serverUrl:U()}),P.success(`API key saved to ~/.stackone/agent-config.json`),P.log(c.default.white(`โ Key expires at`),c.default.cyan(_e(l)));let u=(0,m.default)(`Setting up global MCP configuration...`).start();try{let e=W(),t=U();try{await ge(`claude mcp remove ${e} 2>/dev/null`)}catch{}await ge(`claude mcp add ${e} ${t} --scope user --transport http --header "Authorization: Bearer ${s.apiKey}"`),u.succeed(`Installed to Claude (global)`),P.success(`Global setup complete!`),P.log(c.default.white(`Config location:`),c.default.cyan(`~/.claude.json`)),P.log(c.default.blue(`
|
|
8
|
+
Verify:`),c.default.cyan(`claude mcp list`)),P.log(c.default.dim(`
|
|
9
|
+
๐ก Tip: Run Claude without permission prompts:`),c.default.cyan(`claude --dangerously-skip-permissions`)),P.log(c.default.dim(`
|
|
10
|
+
To setup for a specific project, run:`),c.default.cyan(`stackone agent setup --local`)),P.log(``)}catch(e){u.fail(`Installation to Claude failed`),e instanceof Error&&(P.error(e.message),P.log(c.default.dim(`You can manually add the server later with:`)),P.log(c.default.cyan(` claude mcp add ${W()} ${U()} --scope user --transport http --header "Authorization: Bearer ${s.apiKey}"`)))}process.exit(0)}catch(e){e instanceof Error?P.error(e.message):P.error(`Unknown error occurred`),process.exit(1)}}};const ye=(0,p.promisify)(u.exec);async function be(){return(0,C.getConfig)()}async function xe(){let e=`.mcp.json`,t;try{let n=await(0,d.readFile)(e,`utf-8`);t=JSON.parse(n)}catch{t={mcpServers:{}}}t.mcpServers||={},t.mcpServers[G()]={url:U(),transport:{type:`http`,headers:{Authorization:"Bearer ${STACKONE_AGENT_MCP_TOKEN}"}}},await(0,d.writeFile)(e,JSON.stringify(t,null,2))}var Se=class{async execute(){P.log(c.default.blue.bold(`๐ค StackOne Agent Setup - Local Project
|
|
11
|
+
`));try{let e=process.cwd(),t=await(0,d.access)(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),n=await(0,d.access)(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(t||n){P.warn(`Existing local setup detected:`),t&&P.log(c.default.dim(` โข CLAUDE.md found`)),n&&P.log(c.default.dim(` โข .mcp.json found`)),P.log(``);let{proceed:e}=await S.default.prompt([{type:`confirm`,name:`proceed`,message:`Overwrite existing local configuration?`,default:!1}]);e||(P.log(c.default.dim(`
|
|
12
|
+
Setup cancelled.`)),process.exit(0)),P.log(``)}let r=await se();if(!r||!ue(r)){P.warn(`Not authenticated globally.`),P.log(c.default.white(`Let's authenticate now...
|
|
13
|
+
`));let e=(0,x.createInterface)({input:b.stdin,output:b.stdout}),t=await new Promise(t=>{e.question(c.default.white(`Email: `),e=>{t(e.trim())})});e.close(),t||(P.error(`Email is required`),process.exit(1));let n=await S.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);n.password||(P.error(`Password is required`),process.exit(1)),P.log(``);let i=(0,m.default)(`Authenticating...`).start(),a=await he.login(t,n.password);(!a.success||!a.apiKey)&&(i.fail(`Authentication failed`),P.error(`${a.error||`Invalid credentials`}`),P.log(c.default.dim(`Please check your email and password and try again.
|
|
14
|
+
`)),process.exit(1)),i.succeed(`Login successful!`);let o=new Date(Date.now()+1440*60*1e3).toISOString();await oe({apiKey:a.apiKey,userId:t,email:t,expiresAt:o,serverUrl:U()}),r={apiKey:a.apiKey,userId:t,email:t,expiresAt:o,serverUrl:U()},P.log(``)}let i=(0,m.default)(`Setting up local project configuration...`).start();i.text=`Creating CLAUDE.md...`,await(0,d.writeFile)(`CLAUDE.md`,await be()),i.succeed(`Created CLAUDE.md`);let a=(0,m.default)(`Creating .mcp.json...`).start();await xe(),a.succeed(`Created .mcp.json (using STACKONE_AGENT_MCP_TOKEN env var)`);let o=(0,m.default)(`Installing to Claude (local)...`).start();try{let e=G();try{await ye(`claude mcp remove ${e} 2>/dev/null`)}catch{}await ye(`claude mcp add ${e} ${U()} --scope local --transport http --header "Authorization: Bearer ${r.apiKey}"`),o.succeed(`Installed to Claude (local)`),P.success(`Local setup complete!`),P.log(c.default.white(`Files created:`)),P.log(c.default.cyan(` - CLAUDE.md`)),P.log(c.default.cyan(` - .mcp.json`)),P.log(c.default.dim(`
|
|
15
|
+
๐ก The stackone-agent-local MCP server is now available in this project`)),P.log(c.default.dim(`
|
|
16
|
+
๐ก Tip: Run Claude without permission prompts:`),c.default.cyan(`claude --dangerously-skip-permissions`)),P.log(c.default.blue(`
|
|
17
|
+
Verify:`),c.default.cyan(`claude mcp list`)),P.log(``)}catch(e){o.fail(`Installation to Claude failed`),e instanceof Error&&(P.error(e.message),P.log(c.default.dim(`Configuration files created, but Claude setup failed.`)),P.log(c.default.dim(`You can manually add the server later with:`)),P.log(c.default.cyan(` claude mcp add ${G()} ${U()} --scope local --transport http --header "Authorization: Bearer ${r.apiKey}"`))),P.log(``)}process.exit(0)}catch(e){e instanceof Error?P.error(e.message):P.error(`Unknown error occurred`),process.exit(1)}}};const Ce={profiles:{}},K=()=>{let e=H.readConfigFile(M);if(!e)return Ce;try{return JSON.parse(e)}catch{return Ce}},q=e=>K().profiles[e],J=e=>!!K().profiles[e],we=(e,t)=>{let n=K();n.profiles[e]=t,H.writeConfigFile(M,JSON.stringify(n,null,2))},Y=()=>{let e=K();return Object.keys(e.profiles)},Te=`https://api.stackone.com`;var Ee=class{async execute({profile:e,connector:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(P.error(`Profile or API key is required`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`To create a profile, run ${R(`stackone init`)}.`),process.exit(1)),e&&r&&(P.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&n&&P.warn(`Specifying ${R(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!J(e)){P.error(`Configuration profile ${R(e)} not found`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.\n`);let t=Y();t.length>0&&(P.info(`Available configuration profiles:`),t.forEach(e=>{P.log(` - ${c.default.blue(e)}`)})),process.exit(1)}let i=e?q(e):{apiUrl:n??Te,apiKey:r};i?.apiKey||(P.error(`API key is missing`),P.log(`Please provide a valid API key in the profile or via the ${R(`--api-key`)} option.`),process.exit(1)),t||(P.error(`Connector identifier is required in the format provider_key@version.`),process.exit(1));let a=t.split(`@`);(a.length!==2||!a[0]||!a[1])&&(P.error(`Invalid connector format ${B(t)}. Expected format: ${R(`provider_key@version`)}`),process.exit(1));let o=i.apiUrl??Te,s=await this.dropConnector(t,o,i.apiKey);process.exit(s?0:1)}async dropConnector(e,t,n){let r=(0,m.default)(`๐๏ธ Dropping connector ${R(e)}...`).start();try{let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/registry/connectors/${e}`,{method:`DELETE`,headers:{Authorization:`Basic ${i}`}});return r.stop(),a.status===204?(P.success(`Successfully dropped connector ${R(e)} from the registry`),!0):a.status===404?(P.error(`Connector ${R(e)} not found in the registry`),!1):a.status===401||a.status===403?(P.error(`You do not have permission to drop this connector`),!1):a.status===409?(P.error(`Connector ${R(e)} has associated configs and cannot be dropped`),P.log(`Please delete all associated integration configurations before dropping the connector.`),!1):(a.ok||await L(a,`Failed to drop connector ${R(e)} from the registry`),!1)}catch(n){return r.stop(),P.error(`Failed to drop connector ${R(e)} from registry: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),!1}}};const De=`https://api.stackone.com`;var Oe=class{async execute({profile:e,connector:t,accountId:n,format:r,outputFile:i,apiUrl:a,apiKey:o}={}){if(!e&&!o&&(P.error(`Profile or API key is required`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`To create a profile, run ${R(`stackone init`)}.`),process.exit(1)),e&&o&&(P.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&a&&P.warn(`Specifying ${R(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!J(e)){P.error(`Configuration profile ${R(e)} not found`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.\n`);let t=Y();t.length>0&&(P.info(`Available configuration profiles:`),t.forEach(e=>{P.log(` - ${c.default.blue(e)}`)})),process.exit(1)}let s=e?q(e):{apiUrl:a??De,apiKey:o};s?.apiKey||(P.error(`API key is missing`),P.log(`Please provide a valid API key in the profile or via the ${R(`--api-key`)} option.`),process.exit(1)),(0,w.isMissing)(t)&&(0,w.isMissing)(n)&&(P.error(`Either ${R(`--connector`)} or ${R(`--account-id`)} must be provided`),process.exit(1)),(0,w.notMissing)(t)&&(0,w.notMissing)(n)&&(P.error(`Please provide either ${R(`--connector`)} or ${R(`--account-id`)}, not both.`),process.exit(1)),(0,w.notMissing)(r)&&r!==`yaml`&&r!==`json`&&(P.error(`Format must be either ${R(`yaml`)} or ${R(`json`)}.`),process.exit(1));let l=s.apiUrl??De,u;if((0,w.notMissing)(t)){this.#t(t)||(P.error(`Invalid connector format ${B(t)}. Expected format: ${R(`provider_key@version`)} or ${R(`provider_key`)}`),process.exit(1));let e=this.#n(t);u=await this.#r(e,l,s.apiKey,r)}else (0,w.notMissing)(n)?u=await this.#i(n,l,s.apiKey,r):(P.error(`Either ${R(`--connector`)} or ${R(`--account-id`)} must be provided`),process.exit(1));if((0,w.notMissing)(i))try{h.default.writeFileSync(i,u,`utf-8`),P.success(`Connector written to file: ${R(i)}`)}catch(e){P.error(`Failed to write connector to file ${R(i)}: ${e.message}`),process.exit(1)}else if(P.log(`\n${c.default.blue.inverse(` CONNECTOR CONTENT `)}\n`),!r||r===`yaml`)P.log(this.#e(u));else if(r===`json`)try{F(JSON.parse(u))}catch{P.log(u)}else P.log(u);process.exit(0)}#e(e){return e.split(`
|
|
18
|
+
`).map(e=>{if(e.trim().startsWith(`#`))return c.default.gray(e);if(e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t+1),r=e.substring(t+1),i=r,a=r.trim();return a===`true`||a===`false`?i=r.replace(a,c.default.cyan(a)):a===`null`||a===`~`?i=r.replace(a,c.default.gray(a)):/^-?\d+(\.\d+)?$/.test(a)?i=r.replace(a,c.default.green(a)):(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`)||a&&!a.startsWith(`-`))&&(i=r.replace(a,c.default.yellow(a))),c.default.red(n)+i}return e.trim().startsWith(`-`)?e.replace(`-`,c.default.gray(`-`)):e}).join(`
|
|
19
|
+
`)}#t=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#n=e=>e.includes(`@`)?e:`${e}@latest`;async#r(e,t,n,r){let i=(0,m.default)(`Getting connector ${R(e)} from registry...`).start();try{let a=Buffer.from(n).toString(`base64`),o=r?`?format=${r}`:``,s=await fetch(`${t}/registry/connectors/${e}${o}`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await L(s,`Failed to get connector ${R(e)} from the registry`),process.exit(1)),await s.text()}catch(n){i.stop(),P.error(`Failed to get connector ${R(e)} from the registry: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),process.exit(1)}}async#i(e,t,n,r){let i=(0,m.default)(`Getting connector from account ${R(e)}...`).start();try{let a=Buffer.from(n).toString(`base64`),o=r?`?format=${r}`:``,s=await fetch(`${t}/accounts/${e}/connector${o}`,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await L(s,`Failed to get connector from account ${R(e)}`),process.exit(1)),await s.text()}catch(n){i.stop(),P.error(`Failed to get connector from account ${R(e)}: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),process.exit(1)}}};const ke=`https://api.stackone.com`,Ae=`https://api.stackone-dev.com`,je=`http://localhost:4000`;var Me=class{async execute({environment:e}={}){let t=e?.toLowerCase()??`production`;try{(0,T.intro)(`${c.default.inverse(` Initialize profile `)}`);let e=await(0,T.text)({message:`Profile label`,validate:e=>{if(!e||e.trim().length===0)return`The profile label is required`;if(e.includes(` `))return`The profile label cannot contain spaces`}});if((0,T.isCancel)(e))return(0,T.cancel)(`Configuration profile initialization cancelled`),process.exit(0);if(J(e)){let t=await(0,T.confirm)({message:`Configuration profile with name ${R(e)} already exists. Do you want to overwrite it?`});if((0,T.isCancel)(t)||!t)return(0,T.cancel)(`Configuration profile initialization cancelled`),process.exit(0)}let n;if(t===`production`)n=`https://api.stackone.com`;else if(t===`staging`)n=`https://api.stackone-dev.com`;else{let e=await(0,T.text)({message:`API URL`,placeholder:je,initialValue:je,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{new URL(e)}catch{return`Please enter a valid URL`}}});if((0,T.isCancel)(e))return(0,T.cancel)(`Configuration profile initialization cancelled`),process.exit(0);n=e}let r=await(0,T.password)({message:`API Key`,validate:e=>{if(!e||e.trim().length===0)return`API Key is required`}});if((0,T.isCancel)(r))return(0,T.cancel)(`Configuration profile initialization cancelled`),process.exit(0);we(e,{label:e,environment:t,apiUrl:n,apiKey:r}),(0,T.outro)(`${c.default.green(`โ`)} Configuration profile ${R(e)} initialized successfully!`),process.exit(0)}catch(e){e?.isTtyError?P.error(`Prompt couldn't be rendered in the current environment`):P.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const Ne=20,X={pending:`โ`,acceptRemote:`โ`,acceptLocal:`โ`,acceptBoth:`โ`,current:`โ`,arrow:`โ`,check:`โ`,cross:`โ`,warning:`โ `};var Pe=class{constructor(e,t,n,r){this.conflicts=[],this.currentIndex=0,this.totalConflicts=0,this.currentCleanup=null,this.connectorId=t,this.localVersion=n,this.remoteVersion=r,this.conflicts=e.map(e=>({conflict:e,choice:e.type===`unchanged`?`remote`:`pending`})),this.totalConflicts=e.filter(e=>e.type===`conflict`).length}resetForReResolution(){this.currentIndex=0}async resolve(){return this.totalConflicts===0?{cancelled:!1,states:this.conflicts}:(this.moveToNextConflict(),new Promise(e=>{let t=(0,ee.createInterface)({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),this.render();let n=n=>{let r=n.toString();if(r===``){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r===`\x1B`&&n.length===1){this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});return}if(r.startsWith(`\x1B[`)){switch(r.slice(2)){case`D`:this.moveToPrevConflict(),this.render();break;case`C`:this.moveToNextConflict(),this.render();break}return}switch(r){case`r`:case`R`:this.setCurrentChoice(`remote`),this.advanceAfterChoice(t);break;case`l`:case`L`:this.setCurrentChoice(`local`),this.advanceAfterChoice(t);break;case`b`:case`B`:this.setCurrentChoice(`both`),this.advanceAfterChoice(t);break;case`\r`:case`
|
|
20
|
+
`:this.allResolved()?(this.cleanup(t),e({cancelled:!1,states:this.conflicts})):(this.moveToNextUnresolved(),this.render());break;case`q`:case`Q`:this.cleanup(t),this.renderCancelled(),e({cancelled:!0,states:this.conflicts});break;case`a`:case`A`:this.acceptAllRemaining(`remote`),this.render();break;case`u`:case`U`:this.setCurrentChoice(`pending`),this.render();break}};process.stdin.on(`data`,n),this.currentCleanup=()=>{process.stdin.removeListener(`data`,n),process.stdin.isTTY&&process.stdin.setRawMode(!1),t.close()}}))}cleanup(e){this.currentCleanup?(this.currentCleanup(),this.currentCleanup=null):(process.stdin.isTTY&&process.stdin.setRawMode(!1),e.close())}advanceAfterChoice(e){this.allResolved()||this.moveToNextUnresolved(),this.render()}render(){V();let e=process.stdout.columns||80;this.renderHeader(e),this.renderProgressBar(e),this.renderCurrentConflict(e),this.renderControls(e)}renderHeader(e){let t=this.connectorId,n=`${this.localVersion} ${X.arrow} ${this.remoteVersion}`,r=Math.max(0,e-17),i=Math.floor(r/2),a=r-i,o=` `.repeat(i)+`CONFLICT RESOLVER`+` `.repeat(a);P.log(``),P.log(c.default.bgBlue.white.bold(o)),P.log(c.default.gray(this.centerText(t,e))),P.log(c.default.gray(this.centerText(n,e))),P.log(``)}renderProgressBar(e){let t=this.conflicts.filter(e=>e.conflict.type===`conflict`),n=this.getCurrentConflictIndex(),r=t.map((e,t)=>{let r=t===n,i,a;switch(e.choice){case`remote`:i=r?X.current:X.acceptRemote,a=c.default.green;break;case`local`:i=r?X.current:X.acceptLocal,a=c.default.yellow;break;case`both`:i=r?X.current:X.acceptBoth,a=c.default.cyan;break;default:i=r?X.current:X.pending,a=r?c.default.white:c.default.gray}return a(i)}),i=t.filter(e=>e.choice!==`pending`).length,a=` Conflict ${n+1} of ${this.totalConflicts} โข ${i}/${this.totalConflicts} resolved `;P.log(c.default.gray(this.centerText(a,e))),P.log(this.centerText(r.join(` `),e)),P.log(``)}renderCurrentConflict(e){let t=this.conflicts[this.currentIndex];if(!t||t.conflict.type!==`conflict`)return;let n=t.conflict;if(P.log(c.default.gray(`_`.repeat(e))),P.log(`
|
|
21
|
+
|
|
22
|
+
`),n.local){let e=t.choice===`local`||t.choice===`both`?c.default.yellow.bold(`${X.check} LOCAL (keeping)`):c.default.red.bold(`${X.cross} LOCAL (removing)`),r=n.local.split(`
|
|
23
|
+
`).filter(e=>e!==``),i=r.slice(0,20),a=t.choice===`local`||t.choice===`both`?c.default.yellow:c.default.red,o=i.map(e=>a(`- ${e}`)).join(`
|
|
24
|
+
`),s=r.length>20?`\n${c.default.gray(`... and ${r.length-20} more lines`)}`:``;P.log(`${e}\n\n${o}${s}`)}if(P.log(`
|
|
25
|
+
|
|
26
|
+
`),P.log(c.default.gray(`_`.repeat(e))),P.log(`
|
|
27
|
+
|
|
28
|
+
`),n.remote){let e=t.choice===`remote`||t.choice===`both`?c.default.green.bold(`${X.check} REMOTE (accepting)`):c.default.gray.bold(`${X.pending} REMOTE (skipping)`),r=n.remote.split(`
|
|
29
|
+
`).filter(e=>e!==``),i=r.slice(0,20),a=t.choice===`remote`||t.choice===`both`?c.default.green:c.default.gray,o=i.map(e=>a(`+ ${e}`)).join(`
|
|
30
|
+
`),s=r.length>20?`\n${c.default.gray(`... and ${r.length-20} more lines`)}`:``;P.log(`${e}\n\n${o}${s}`)}P.log(`
|
|
31
|
+
|
|
32
|
+
`),P.log(c.default.gray(`_`.repeat(e))),P.log(``)}renderControls(e){let t=[c.default.green(`[R] Accept Remote`),c.default.yellow(`[L] Keep Local`),c.default.cyan(`[B] Keep Both`),c.default.gray(`[U] Undo`)],n=[c.default.gray(`[โ/โ] Navigate`),c.default.gray(`[A] Accept all remaining`)],r=this.allResolved()?[c.default.green.bold(`[Enter] Apply Changes`),c.default.gray(`[Esc] Cancel`)]:[c.default.gray(`[Enter] Next Unresolved`),c.default.gray(`[Esc] Cancel`)];P.log(this.centerText(t.join(` `),e)),P.log(``),P.log(this.centerText(n.join(` `),e)),P.log(``),P.log(this.centerText(r.join(` `),e)),this.allResolved()&&(P.log(``),P.log(c.default.green.bold(this.centerText(`โ All conflicts resolved!`,e))))}renderFinalSummary(){V();let e=this.conflicts.filter(e=>e.conflict.type===`conflict`),t=0,n=0,r=0;for(let i of e)switch(i.choice){case`remote`:t++;break;case`local`:n++;break;case`both`:r++;break}let i=[c.default.green.bold(`Conflict resolution complete`),``,`${c.default.bold(this.totalConflicts)} conflicts resolved:`,``,`${c.default.green(X.acceptRemote)} Accepted remote: ${t}`,`${c.default.yellow(X.acceptLocal)} Kept local: ${n}`,`${c.default.cyan(X.acceptBoth)} Kept both: ${r}`];P.box(i.join(`
|
|
33
|
+
`))}renderCancelled(){V(),P.log(c.default.yellow(`Conflict resolution cancelled`)),P.log(``),P.log(`No changes were made to your local connector file.`)}getCurrentConflictIndex(){let e=-1;for(let t=0;t<=this.currentIndex&&t<this.conflicts.length;t++)this.conflicts[t].conflict.type===`conflict`&&e++;return e}moveToNextConflict(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToPrevConflict(){for(let e=this.currentIndex-1;e>=0;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}for(let e=this.conflicts.length-1;e>this.currentIndex;e--)if(this.conflicts[e].conflict.type===`conflict`){this.currentIndex=e;return}}moveToNextUnresolved(){for(let e=this.currentIndex+1;e<this.conflicts.length;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}for(let e=0;e<this.currentIndex;e++)if(this.conflicts[e].conflict.type===`conflict`&&this.conflicts[e].choice===`pending`){this.currentIndex=e;return}}setCurrentChoice(e){this.conflicts[this.currentIndex]?.conflict.type===`conflict`&&(this.conflicts[this.currentIndex].choice=e)}allResolved(){return this.conflicts.filter(e=>e.conflict.type===`conflict`).every(e=>e.choice!==`pending`)}acceptAllRemaining(e){for(let t of this.conflicts)t.conflict.type===`conflict`&&t.choice===`pending`&&(t.choice=e)}centerText(e,t){let n=this.stripAnsi(e),r=Math.max(0,Math.floor((t-n.length)/2));return` `.repeat(r)+e}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}getResolvedContent(){let e=[];for(let t of this.conflicts)if(t.conflict.type===`unchanged`)e.push(t.conflict.content||``);else if(t.conflict.type===`conflict`)switch(t.choice){case`remote`:t.conflict.remote&&e.push(t.conflict.remote);break;case`local`:t.conflict.local&&e.push(t.conflict.local);break;case`both`:t.conflict.local&&e.push(t.conflict.local),t.conflict.remote&&e.push(t.conflict.remote);break;case`pending`:t.conflict.remote&&e.push(t.conflict.remote);break}return e.join(``)}};const Fe=`https://api.stackone.com`,Ie=3;var Le=class{async execute({profile:e,connector:t,outputPath:n,apiUrl:r,apiKey:i}={}){if((0,w.isMissing)(t)&&(P.error(`Connector identifier is required`),P.log(`Please provide a connector identifier using the ${R(`--connector`)} option in the format: ${R(`provider_key@version`)} or ${R(`provider_key`)}`),P.log(`If no version is specified, the latest version will be pulled.`),process.exit(1)),!e&&!i&&(P.error(`Profile or API key is required`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`To create a profile, run ${R(`stackone init`)}.`),process.exit(1)),e&&i&&(P.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&r&&P.warn(`Specifying ${R(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!J(e)){P.error(`Configuration profile ${R(e)} not found`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.\n`);let t=Y();t.length>0&&(P.info(`Available configuration profiles:`),t.forEach(e=>{P.log(` - ${c.default.blue(e)}`)})),process.exit(1)}let a=e?q(e):{apiUrl:r??Fe,apiKey:i};a?.apiKey||(P.error(`API key is missing`),P.log(`Please provide a valid API key in the profile or via the ${R(`--api-key`)} option.`),process.exit(1));let o=a.apiUrl??Fe,[s,l]=t.split(`@`),u=await this.#f(s,o,a.apiKey,l??`latest`),d=this.#e(u),f=d.version??`unknown`,p=this.#t(n,d.key,f),m=this.#r(p),h=m===null,g=u;if(!h){let e=this.#i(m,p);e&&(P.warn(e.message),e.errors.length>0&&I(e.errors,!1),P.log(``));let n=e?void 0:this.#e(m);if(this.#o(m,u)){this.#a(m,u,p);let e=n?.version??`unknown`,r=await this.#s(m,u,t,e,f);r.action===`cancel`&&((0,T.cancel)(`Pull cancelled`),process.exit(0)),r.action===`keep-local`&&(P.log(``),P.info(`Keeping local version. No changes made.`),process.exit(0)),r.action===`interactive-cancel`&&process.exit(0),r.action===`interactive`&&(g=r.resolvedContent)}else P.info(`No changes detected in connector configuration.`),process.exit(0)}let _=(0,E.validateYamlConnector)(g).connector,v=_?.key??d.key,y=_?.version??f,b=this.#t(n,v,y),x=b;if(b!==p){let e=await this.#n(b);P.log(``),e!==void 0&&(x=e)}await this.#d(x,g),h?P.success(`Connector ${R(v)}@${R(y)} pulled successfully (new connector)`):P.success(`Connector ${R(v)}@${R(y)} updated successfully`);let S=v===d.key?R(v):`${R(d.key)} ${c.default.whiteBright(`โ`)} ${R(v)}`,C=y===f?R(y):`${R(f)} ${c.default.whiteBright(`โ`)} ${R(y)}`,D=x===p?R(x):`${R(p)}\n ${c.default.whiteBright(`โ`)} ${R(x)}`;P.log(`\n${c.default.blue.inverse(` CONNECTOR DETAILS `)}\n`),P.log(` Provider: ${S}`),P.log(` Version: ${C}`),P.log(` Output file: ${D}`),process.exit(0)}#e(e){let t=(0,E.validateYamlConnector)(e),n=t?.errors??[];if(t.success)return t.connector;P.error(`Connector pulled from the registry is not valid`),P.log(`Please make sure you are using the latest version of the StackOne CLI by running ${R(`stackone update`)}`),n.length>0&&I(n,!0),process.exit(1)}#t(e,t,n){let r=`${t}_v${n.replaceAll(`.`,`-`)}.s1.yaml`;return e?(h.default.existsSync(e)&&(h.default.statSync(e).isDirectory()||(P.error(`Output path ${R(e)} is not a directory`),P.log(`Please provide a valid directory path to store connectors or use the default path.`),process.exit(1))),_.default.resolve(e,t,r)):_.default.resolve(process.cwd(),`connectors`,t,r)}async#n(e){if(!h.default.existsSync(e))return;let t=_.default.basename(e),n=_.default.dirname(e);P.warn(`File ${R(t)} already exists at ${R(n)}`);let r=await(0,T.select)({message:`How would you like to proceed?`,options:[{value:`override`,label:`Override existing file`,hint:`Replace the existing file with the new content`},{value:`rename`,label:`Save with a different name`,hint:`Provide a new filename for the connector`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if(((0,T.isCancel)(r)||r===`cancel`)&&((0,T.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),r===`override`)return;let i=await(0,T.text)({message:`Enter the new filename:`,placeholder:t,validate:e=>{if(!e||e.trim()===``)return`Filename cannot be empty`;if(!e.endsWith(`.s1.yaml`))return`Filename must end with .s1.yaml`;let t=_.default.join(n,e.trim());if(h.default.existsSync(t))return`File ${e} already exists`}});return(0,T.isCancel)(i)&&((0,T.cancel)(`Operation cancelled. No local changes were made.`),process.exit(0)),_.default.join(n,i.trim())}#r(e){if(!h.default.existsSync(e))return null;try{return h.default.readFileSync(e,`utf-8`)}catch{return null}}#i(e,t){try{let n=(0,E.validateYamlConnector)(e);if(!n.success){let e=n.errors??[];return{message:`Local connector ${R(_.default.basename(t))} has validation errors:`,errors:e}}}catch(e){return{message:`Local connector ${R(_.default.basename(t))} could not be validated: ${e.message}`,errors:[]}}return null}#a(e,t,n){let r=(0,D.diffLines)(e,t);if(!r.some(e=>e.added||e.removed)){P.info(`No changes detected in connector configuration.`);return}P.log(`${c.default.blue.inverse(` CHANGES `)}\n`),P.log(c.default.gray(`--- local: ${n}`)),P.log(c.default.gray(`+++ remote: StackOne Registry`)),P.log(``);let i=0,a=0;for(let e of r){let t=e.value.split(`
|
|
34
|
+
`).filter(e=>e!==``);if(e.added){i+=t.length;for(let e of t)P.log(c.default.green(`+ ${e}`))}else if(e.removed){a+=t.length;for(let e of t)P.log(c.default.red(`- ${e}`))}else if(t.length<=6)for(let e of t)P.log(c.default.gray(` ${e}`));else{for(let e=0;e<3;e++)P.log(c.default.gray(` ${t[e]}`));P.log(c.default.gray(` ... (${t.length-6} unchanged lines)`));for(let e=t.length-3;e<t.length;e++)P.log(c.default.gray(` ${t[e]}`))}}P.log(``),P.log(c.default.gray(`Summary: ${c.default.green(`+${i}`)} additions, ${c.default.red(`-${a}`)} deletions`))}#o(e,t){return(0,D.diffLines)(e,t).some(e=>e.added||e.removed)}async#s(e,t,n,r,i){P.log(``);let a=await(0,T.select)({message:`How would you like to resolve the differences?`,options:[{value:`override`,label:`Override local with remote`,hint:`Replace your local file with the StackOne version`},{value:`keep-local`,label:`Keep local version`,hint:`Cancel the pull and keep your current file`},{value:`interactive`,label:`Resolve conflicts interactively`,hint:`Choose which changes to accept one by one`},{value:`cancel`,label:`Cancel`,hint:`Abort the pull operation`}]});if((0,T.isCancel)(a))return{action:`cancel`};if(a===`override`)return{action:`override`};if(a===`keep-local`)return{action:`keep-local`};if(a===`interactive`){let a=await this.#c(e,t,n,r,i);return a===null?{action:`interactive-cancel`}:{action:`interactive`,resolvedContent:a}}return{action:`cancel`}}async#c(e,t,n,r,i){let a=(0,D.diffLines)(e,t),o=this.#u(a);if(o.length===0)return P.info(`No conflicts to resolve.`),t;let s=new Pe(o,n,r,i);for(;;){if((await s.resolve()).cancelled)return null;let e=s.getResolvedContent(),t=(0,E.validateYamlConnector)(e);if(t.success)return s.renderFinalSummary(),e;let n=await this.#l(t.errors);if(n===`cancel`)return V(),P.info(`Operation cancelled. No changes were made to the local connector.`),null;if(n===`save`)return V(),P.warn(`The connector was saved but it is invalid`),e;s.resetForReResolution()}}async#l(e){let{createInterface:t}=await import(`readline`);return new Promise(n=>{V();let r=(e||[{message:`Unknown validation error`}]).map(e=>` โข ${e.message}`).join(`
|
|
35
|
+
`);P.box({title:`โ ๏ธ Validation Failed`,message:`The resolved connector configuration is invalid:\n\n${r}`,style:{borderColor:`yellow`,padding:1}}),P.log(``),P.log(c.default.bold(` Choose an action:`)),P.log(``),P.log(c.default.cyan(` [B]`)+` โ Go back to conflict resolution`),P.log(c.default.dim(` Modify your choices to fix the validation errors`)),P.log(``),P.log(c.default.yellow(` [S]`)+` ๐พ Save anyway`),P.log(c.default.dim(` Save the invalid configuration (not recommended)`)),P.log(``),P.log(c.default.red(` [C]`)+` โ Cancel`),P.log(c.default.dim(` Discard all changes`)),P.log(``);let i=t({input:process.stdin,output:process.stdout});process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();let a=e=>{let t=e.toString().toLowerCase(),r=()=>{process.stdin.removeListener(`data`,a),process.stdin.isTTY&&process.stdin.setRawMode(!1),i.close()};if(t===``||t===`\x1B`){r(),n(`cancel`);return}switch(t){case`b`:r(),n(`back`);break;case`s`:r(),n(`save`);break;case`c`:case`q`:r(),n(`cancel`);break}};process.stdin.on(`data`,a)})}#u(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r.added&&!r.removed)t.push({type:`unchanged`,content:r.value}),n++;else if(r.removed){let i=e[n+1];i?.added?(t.push({type:`conflict`,local:r.value,remote:i.value}),n+=2):(t.push({type:`conflict`,local:r.value,remote:void 0}),n++)}else r.added&&t.push({type:`conflict`,local:void 0,remote:r.value}),n++}return t}async#d(e,t){let n=_.default.dirname(e);h.default.existsSync(n)||h.default.mkdirSync(n,{recursive:!0});try{h.default.writeFileSync(e,t,`utf-8`)}catch(t){P.error(`Failed to write connector to file ${R(e)}: ${t.message}`),process.exit(1)}}async#f(e,t,n,r){let i=(0,m.default)(`Pulling connector ${R(e)}@${R(r)} from registry...`).start();try{let a=Buffer.from(n).toString(`base64`),o=`${t}/registry/connectors/${e}@${r}`,s=await fetch(o,{method:`GET`,headers:{Authorization:`Basic ${a}`}});return i.stop(),s.ok||(await this.#p(s,e,r),process.exit(1)),await s.text()}catch(n){i.stop(),P.error(`Failed to pull connector ${R(e)}@${R(r)} from the registry: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid.`),process.exit(1)}}async#p(e,t,n){switch(e.status){case 401:case 403:P.error(`Access denied`),P.log(`Please ensure that your API key is valid and has the ${R(`connectors:read`)} scope required to pull connectors.`);break;case 404:P.error(`Connector ${R(t)}@${R(n)} was not found in the registry`),await this.#m(t);break;case 429:P.error(`Rate limit exceeded`),P.log(`Too many requests. Please wait a moment before trying again.`);break;default:await L(e,`Failed to pull connector ${R(t)}`)}}async#m(e){P.info(`To see available versions, check the connector documentation or contact support.`)}};const Re=`https://api.stackone.com`;var ze=class{async execute({profile:e,fileOrDir:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(P.error(`Profile or API key is required`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`To create a profile, run ${R(`stackone init`)}.`),process.exit(1)),e&&r&&(P.error(`Please provide either a profile or an API key, not both`),process.exit(1)),e&&n&&P.warn(`Specifying ${R(`--api-url`)} with a profile won't have any effect. Using API url from profile.`),e&&!J(e)){P.error(`Configuration profile ${R(e)} not found`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.\n`);let t=Y();t.length>0&&(P.info(`Available configuration profiles:`),t.forEach(e=>{P.log(` - ${c.default.blue(e)}`)})),process.exit(1)}let i=e?q(e):{apiUrl:n??Re,apiKey:r};i?.apiKey||(P.error(`API key is missing`),P.log(`Please provide a valid API key in the profile or via the ${R(`--api-key`)} option.`),process.exit(1)),t||(P.error(`File or directory is required.`),process.exit(1));try{(0,h.statSync)(t)}catch{P.error(`File or directory not found: ${c.default.red(t)}`),process.exit(1)}let a=(0,h.statSync)(t),o=i.apiUrl??Re;if(a.isDirectory()){let e=Ve(t),n=0;e.length===0?(P.error(`No .s1.yaml connector files found in the directory: ${t}.`),process.exit(1)):(P.start(`Found ${e.length} connector(s) file(s). Pushing to registry...`),P.log(``));for(let t of e)await this.uploadFile(t,o,i.apiKey)&&n++;n===0?P.error(`Error while pushing connectors: no files were uploaded`):(P.log(``),P.info(`Upload completed: ${c.default.green(n)} of ${c.default.blue(e.length)} file(s) uploaded successfully.`)),process.exit(n>0?0:1)}else t.endsWith(`.s1.yaml`)||(P.error(`Only ${R(`.s1.yaml`)} files are supported for upload`),process.exit(1));let s=await this.uploadFile(t,o,i.apiKey);process.exit(s?0:1)}async uploadFile(e,t,n){let r=(0,m.default)(`๐ค Pushing connector in ${(0,_.basename)(e)}...`).start();try{let i=Be(e);if(!i)return!1;let a=(0,_.basename)(e),o=new FormData,s=new Blob([i],{type:`application/x-yaml`});o.append(`file`,s,a);let c=Buffer.from(n).toString(`base64`),l=await fetch(`${t}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${c}`},body:o});if(r.stop(),!l.ok)return await L(l,`Failed to push connector in ${R(a)} to the registry`),!1;let u=await l.json();return P.success(`Successfully uploaded ${R(a)} with connector ${R(u.provider)}@${R(u.version)}`),!0}catch(n){return r.stop(),P.error(`Failed to upload file ${R(e)}: ${n}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),!1}}};const Be=e=>{let t=(0,E.loadConnector)(e),n=(0,E.validateYamlConnector)(t),r=n?.errors??[];if(n.success)return t;r.length>0?(P.error(`Connector in ${B(e)} is not valid`),I(r,!0)):P.error(`Connector in ${B(e)} is not valid. Please check the file for errors.`)},Ve=e=>{let t=[],n=(0,h.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,_.join)(e,r.name);r.isDirectory()?t.push(...Ve(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t},He=w.z.object({provider_key:w.z.string().optional(),provider_version:w.z.string().optional(),auth_config_key:w.z.string(),environment:w.z.string().default(`production`),organization_id:w.z.string().default(`cli-organization-id`),account_id:w.z.string().default(`cli-account-secure-id`),project_id:w.z.string().default(`cli-project-secure-id`),credentials:w.z.record(w.z.string(),w.z.any()).default({})}),Ue=w.z.record(w.z.string(),w.z.any()),We=w.z.object({path:w.z.record(w.z.string(),w.z.any()).default({}),queryParams:w.z.record(w.z.string(),w.z.any()).default({}),header:w.z.record(w.z.string(),w.z.any()).default({}),body:w.z.record(w.z.string(),w.z.any()).default({})}),Z=`https://api.stackone.com`;var Ge=class{async execute({connector:e,action:t,actionId:n,account:r,accountId:i,params:a,credentials:o,profile:s,outputFile:l,debug:u,apiUrl:d,apiKey:f}={}){if(!s&&!f&&i&&(P.error(`Profile or API key is required when providing an account ID`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`To create a profile, run ${R(`stackone init`)}.`),process.exit(1)),s&&f&&(P.error(`Please provide either a profile or an API key, not both`),process.exit(1)),s&&d&&P.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),s&&!J(s)){P.error(`Configuration profile ${R(s)} not found`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.\n`);let e=Y();e.length>0&&(P.info(`Available configuration profiles:`),e.forEach(e=>{P.log(` - ${c.default.blue(e)}`)})),process.exit(1)}let p=s?q(s):{apiUrl:d??Z,apiKey:f};(0,w.isMissing)(r)&&(0,w.isMissing)(i)&&(P.error(`A valid account or account ID is required to run an action`),process.exit(1));let m;if((0,w.notMissing)(e))if(this.#a(e)){!s&&!f&&(P.error(`Profile or API key is required when using a connector identifier`),P.log(`Please provide a profile using the ${R(`--profile`)} option or an API key using the ${R(`--api-key`)} option.`),P.log(`Run ${R(`stackone init`)} to create a new configuration profile.`),process.exit(1));let t=this.#o(e);m=await this.#s(t,p?.apiUrl??Z,p?.apiKey)}else m=this.#e(e);else (0,w.notMissing)(i)&&(m=await this.#c(i,p?.apiUrl??Z,p?.apiKey));let g=(0,w.notMissing)(t)?this.#r(t,e):m;(0,w.isMissing)(g)&&(P.error(`A valid connector is required to run an action.`),process.exit(1));let _=(0,w.notMissing)(g?.actions)?Object.keys(g?.actions).length:0,v=(0,w.notMissing)(g?.actions)?Object.keys(g.actions)[_-1]:void 0,y=(0,w.notMissing)(v)?g?.actions?.[v]?.id:void 0,b=((0,w.notMissing)(n)&&!n?.startsWith(`${g.key}_`)?`${g.key}_${n}`:n)??y;(0,w.isMissing)(b)&&(P.error(`A valid action ID is required to run an action`),process.exit(1));let x=(0,w.notMissing)(i)?await this.#l(i,p?.apiUrl??Z,p?.apiKey):{},S=(0,w.notMissing)(r)?this.#i(r,g.key??`unknown`,g.version??`unknown`):void 0,C=(0,w.notMissing)(o)?this.#u(o):{},T={...x,...S,credentials:{...x.credentials??{},...C}};(0,w.isMissing)(T)&&(P.error(`A valid account data is required to run an action.`),process.exit(1));let E=g.actions?.[b];(0,w.isMissing)(E)&&(P.error(`Action ID ${R(b)} not found in the connector ${R(g.key)}@${R(g.version)}.`),process.exit(1));let D=(0,w.notMissing)(a)?this.#d(a,b):{path:{},queryParams:{},header:{},body:{}},ee=Date.now(),O=await this.#f({connector:g,actionId:b,account:T,queryParams:{...D.queryParams,...u?{debug:`true`}:{}},pathParams:D.path,body:D.body,headers:D.header}),k=Date.now()-ee;if((0,w.notMissing)(l))try{h.default.writeFileSync(l,JSON.stringify(O.output,null,2),`utf-8`),P.info(`Output written to file: ${l}`)}catch(e){P.error(`Failed to write output to file ${l}: ${e.message}`),process.exit(1)}else P.log(`\n${c.default.blue.inverse(` ACTION OUTPUT `)}`),F(O.output);P.log(``),P.info(`Action ${R(b)} from connector ${R(g?.key)}@${R(g?.version)} finished in ${c.default.yellowBright((k/1e3).toFixed(2))} seconds.`),process.exit(0)}#e=e=>{let t=e;try{t=(0,E.loadConnector)(e)}catch{}return t?this.#n(t):void 0};#t=e=>{try{return(0,E.loadConnector)(e)}catch(t){P.error(`Failed to load connector file from ${R(e)}: ${t.message}`),process.exit(1)}};#n=e=>{let t=(0,E.validateYamlConnector)(e),n=t?.errors??[];if(t.success)return t.connector||(P.error(`Failed to load connector.`),process.exit(1)),t.connector;n.length>0?(P.error(`Connector is not valid`),I(n,!0),process.exit(1)):(P.error(`Connector is not valid. Please check the file for errors.`),process.exit(1))};#r=(e,t)=>{let n=e;try{n=h.default.readFileSync(e,`utf-8`)}catch{}(0,w.isMissing)(t)&&(P.error(`A valid connector is required to load an action.`),process.exit(1));let r=`${this.#t(t)} - ${n.split(`
|
|
36
|
+
`).map((e,t)=>t===0?e:` ${e}`).join(`
|
|
37
|
+
`)}`;return this.#n(r)};#i=(e,t,n)=>{let r=e;try{r=h.default.readFileSync(e,`utf-8`)}catch{}try{let e=He.parse(JSON.parse(r));return{providerKey:t,providerVersion:n,authConfigKey:e.auth_config_key,environment:e.environment,organizationId:e.organization_id,secureId:e.account_id,projectSecureId:e.project_id}}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}P.error(`Failed to parse account information`),I(t,!1),t.length===0&&P.log(e.message),process.exit(1)}};#a=e=>!e.includes(`/`)&&!e.includes(`\\`)&&!e.endsWith(`.yaml`)&&!e.endsWith(`.yml`)?e.includes(`@`)?e.split(`@`).length===2:!0:!1;#o=e=>e.includes(`@`)?e:`${e}@latest`;#s=async(e,t,n)=>{((0,w.isMissing)(e)||(0,w.isMissing)(t)||(0,w.isMissing)(n))&&(P.error(`Connector identifier, API URL, and API key are required to fetch connector from registry.`),process.exit(1));let r=(0,m.default)();try{r.text=`Fetching connector ${R(e)} from registry...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/registry/connectors/${e}`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await L(a,`Failed to fetch connector ${R(e)} from registry`),process.exit(1));let o=await a.text(),s=this.#n(o);return P.success(`Fetched connector ${R(s.key)}@${R(s.version)} from registry`),s}catch(n){r.stop(),P.error(`Failed to fetch connector ${R(e)} from registry: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),process.exit(1)}};#c=async(e,t,n)=>{((0,w.isMissing)(e)||(0,w.isMissing)(t)||(0,w.isMissing)(n))&&(P.error(`Account ID, API URL, and API key are required to fetch connector`),process.exit(1));let r=(0,m.default)();try{r.text=`Fetching connector for account ${R(e)} from API...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/accounts/${e}/connector`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await L(a,`Failed to fetch connector`),process.exit(1));let o=await a.text(),s=this.#n(o);return P.success(`Fetched connector ${R(s.key)}@${R(s.version)} for account ${R(e)}`),s}catch(e){r.stop(),P.error(`Failed to fetch connector: ${e.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),process.exit(1)}};#l=async(e,t,n)=>{((0,w.isMissing)(e)||(0,w.isMissing)(t)||(0,w.isMissing)(n))&&(P.error(`Account ID, API URL, and API key are required to fetch account information.`),process.exit(1));let r=(0,m.default)();try{r.text=`Fetching account ${R(e)} information from API...`,r.start();let i=Buffer.from(n).toString(`base64`),a=await fetch(`${t}/accounts/${e}/credentials`,{method:`GET`,headers:{Authorization:`Basic ${i}`}});r.stop(),a.ok||(await L(a,`Failed to fetch account ${R(e)} information`),process.exit(1));let o=await a.json();return P.success(`Fetched account ${R(e)} information from project ${R(o.project_id)}`),{providerKey:o.provider_key,providerVersion:o.provider_version,authConfigKey:o.auth_config_key,environment:o.environment,organizationId:o.organization_id,secureId:o.account_id,projectSecureId:o.project_id,credentials:o.credentials}}catch(n){r.stop(),P.error(`Failed to fetch account ${R(e)} information: ${n.message}`),P.log(`Please ensure that the API at ${z(t)} is reachable and the API key is valid`),process.exit(1)}};#u=e=>{let t=e;try{t=h.default.readFileSync(e,`utf-8`)}catch{}try{return Ue.parse(JSON.parse(t))}catch(e){let t=[];try{t=JSON.parse(e.message)}catch{}P.error(`Failed to parse credentials`),I(t,!1),t.length===0&&P.log(e.message),process.exit(1)}};#d=(e,t)=>{let n=e;try{n=h.default.readFileSync(e,`utf-8`)}catch{}try{return We.parse(JSON.parse(n))}catch(e){let n=[];try{n=JSON.parse(e.message)}catch{}P.error(`Invalid parameters for action ${R(t)}.`),I(n,!1),n.length===0&&P.log(e.message),process.exit(1)}};async#f({connector:e,actionId:t,account:n,pathParams:r={},queryParams:i={},body:a={},headers:o={}}){try{let s=await(0,E.runAction)({mode:`action_id`,actionId:t,account:n,connector:e,pathParams:r,queryParams:i,body:a,headers:o,getHttpClient:async()=>new O.HttpClient});if(s.response?.successful){let e={...this.#p(i,s.steps),...(0,w.isObject)(s.outputs)?s.outputs:{data:s.outputs}};return{statusCode:s.response?.statusCode,output:e}}else{let n=s.response?.message??`An error occurred while processing the request`;P.error(`Action ID ${R(t)} from connector ${R(e.key)}@${R(e.version)} failed with status ${s.response?.statusCode}: ${n}`);let r={...this.#p(i,s.steps)};Object.keys(r).length>0&&(P.log(`${c.default.yellow.inverse(` EXECUTION DETAILS `)}`),F(r)),process.exit(1)}}catch(e){this.#m(e)}}#p(e,t){return e?.debug===`true`?{debug:{steps:t}}:{}}#m(e){let t=e;switch((0,w.isMissing)(t.errorType)&&(P.error(`An unknown error occurred`),P.log(`${e instanceof Error?e.message:String(e)}`),process.exit(1)),t.errorType){case`MISSING_ACTION_ERROR`:P.error(`The specified action was not found: ${t.message}`);break;case`INVALID_ACTION_INPUTS_ERROR`:let e=t;P.error(`Invalid action inputs`),I(e.validationErrors,!1);break;case`INVALID_CURSOR_ERROR`:P.error(`Invalid cursor: ${t.message}`);break;default:P.error(`An error occurred: ${t.message}`)}process.exit(1)}};const Q=()=>{try{let e=(0,_.join)((0,_.dirname)((0,te.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),`..`,`package.json`);return JSON.parse((0,h.readFileSync)(e,`utf8`)).version}catch{return`unknown`}},Ke=(0,p.promisify)(u.exec);var qe=class{constructor(){this.packageName=`@stackone/cli`,this.spinner=(0,m.default)(),this.currentVersion=Q()}async execute(e={}){this.spinner.text=`Checking for updates...`,this.spinner.start();try{let t=await this.getLatestVersion();this.spinner.stop(),t||(P.error(`Failed to check for updates`),process.exit(1)),this.isNewerVersion(t,this.currentVersion)?(P.box(`New version available: ${c.default.yellow(this.currentVersion)} โ ${c.default.green(t)}`),await this.performUpdate(t)):e.force?(P.warn(`No updates available, but forcing reinstall...`),await this.performUpdate(t)):P.success(`You are already on the latest version (${this.currentVersion})`),process.exit(0)}catch(e){this.spinner.stop(),P.error(`Error while trying to update StackOne CLI: ${e?.message??`Unknown error`}`),process.exit(1)}}async getLatestVersion(){try{let{stdout:e}=await Ke(`npm view ${this.packageName} version`,{encoding:`utf-8`});return e.trim()}catch{return null}}isNewerVersion(e,t){return A.default.gt(e,t)}isUsingVolta(){if(typeof process.env.VOLTA_HOME!=`string`||process.env.VOLTA_HOME.length===0)return!1;let e=(0,f.join)(process.env.VOLTA_HOME,`bin`),t=(0,f.join)(e,`stackone`),n=(0,f.join)(e,`stackone.exe`);return(0,k.existsSync)(t)||(0,k.existsSync)(n)}async performUpdate(e){let t=this.isUsingVolta();this.spinner.text=`Updating to latest version (${R(e)})...`,this.spinner.start();try{await Ke(t?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`,{encoding:`utf-8`}),this.spinner.stop(),P.success(`StackOne CLI updated successfully to latest version (${R(e)})`)}catch{this.spinner.stop();let e=t?`volta install ${this.packageName}@latest`:`npm install -g ${this.packageName}@latest`;throw Error(`Failed to install update. Please try manually: ${e}`)}}};const $=()=>{P.log(`${c.default.gray.inverse(` CONNECTORS VALIDATION `)} ${c.default.yellow.inverse(` WATCH MODE `)}\n`)};var Je=class{async execute(e){let{watchMode:t,fileOrDir:n}=e,r=(0,m.default)(`Watching for file changes... ${c.default.gray(`(press "q" to quit)`)}`);if(!n)return;let i=(0,_.resolve)(n);try{await(0,j.stat)(i)}catch{P.error(`The specified path does not exist: ${i}\n`),process.exit(1)}if(t){V();let e={},{watch:t}=await import(`chokidar`),n=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let a=()=>{s.close(),r.stop(),n.close(),P.log(c.default.grey(`
|
|
38
|
+
Exiting watch mode...`)),process.exit(0)};$(),P.start(`Validating connectors...`);let o=await Qe(i);e=Ye(e,o||{}),Xe(e,i),r.start();let s=t(i,{persistent:!0,ignoreInitial:!0}),l=async t=>{if(!t.endsWith(`.s1.yaml`)&&!t.endsWith(`s1.partial.yaml`))return;let n=t.endsWith(`s1.partial.yaml`)?await et(t):[t];if(!(!n||n.length===0)){V(),r.stop(),$(),P.log(c.default.gray(`File change detected: ${t}`)),P.start(`Validating connectors...`);for(let t of n){let n=await Qe(t);e=Ye(e,n||{})}Xe(e,i),r.start()}};s.on(`change`,async e=>await l(e)),process.stdin.on(`data`,e=>{e.toString()===`q`&&a()}),process.on(`SIGINT`,()=>{a()})}else await Qe(i,P),process.exit(0)}};const Ye=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=r;return e},Xe=(e,t)=>{V(),$();let n=0,r=0;for(let[t,i]of Object.entries(e))i===null?n++:(P?.error(`Connector ${R(t)} is not valid`),I(i,!0),r++);P.log(``),P.log(c.default.blue.inverse(` Validation Summary `)),P.log(`Connectors path: ${R(t)}`),P.log(`${n===0?c.default.red(`0`):c.default.green(n)} valid, ${r===0?c.default.green(`0`):c.default.red(r)} invalid connectors\n`)},Ze=async e=>{let t=[],n=await(0,j.readdir)(e);for(let r of n){let n=(0,_.join)(e,r),i=await(0,j.stat)(n);i.isDirectory()?t.push(...await Ze(n)):i.isFile()&&r.endsWith(`.s1.yaml`)&&t.push(n)}return t},Qe=async(e,t)=>{let n=await(0,j.stat)(e),r={};if(n.isDirectory()){let n=await Ze(e);if(n.length===0)return t?.error(`No StackOne connector found in ${B(e)}`),t?.log(`Connector files need to have the extension ${R(`*.s1.yaml`)}`),null;let i=0,a=0;for(let e of n){let n=await $e(e,t);n===null?i++:(t?.log(``),a++),r[e]=n}return t?.log(``),t?.log(c.default.blue.inverse(` Validation Summary `)),t?.log(`${i===0?c.default.red(`0`):c.default.green(i)} valid, ${a===0?c.default.green(`0`):c.default.red(a)} invalid connectors`),r}else if(n.isFile()&&e.endsWith(`s1.yaml`))return r[e]=await $e(e,t),r;else if(n.isFile()&&e.endsWith(`partial.yaml`)){t?.error(`Partial connector files cannot be validated directly`),t?.log(`The file ${B(e)} is a partial connector file.`);let n=await et(e);return n&&n?.length>0&&t?.log(`Did you mean ${R(n[0])}?`),null}else return t?.error(`No StackOne connector found in ${B(e)}`),t?.log(`Connector files need to have the extension ${R(`*.s1.yaml`)}`),null},$e=async(e,t)=>{let n=(0,E.validateYamlConnector)((0,E.loadConnector)(e)),r=n?.errors??[];if(n.success){let n=e.split(`/`).pop()||e;return t?.success(`Connector ${R(n)} is valid!`),null}else if(r.length>0)return t?.error(`Connector ${R(e)} is not valid`),t&&I(r,!0),r;else return t?.error(`Connector ${R(e)} is not valid. Please check the file for errors`),[]},et=async e=>{let t=(0,_.dirname)(e);try{return(await(0,j.readdir)(t)).filter(e=>e.endsWith(`.s1.yaml`))?.map(e=>(0,_.join)(t,e))}catch{}},tt=`@stackone/cli`,nt=2880*60*1e3,rt=(0,f.join)((0,ne.homedir)(),`.stackone`),it=(0,f.join)(rt,`version-check.json`),at=(e=!1)=>{let t=lt(),n=Date.now();if(e||!t||n-t.lastCheckTime>1728e5){let e=ot();e&&st(e)&&ct(e),ut({lastCheckTime:n})}},ot=()=>{try{return(0,u.execSync)(`npm view @stackone/cli version`,{encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],timeout:15e3}).trim()}catch{return null}},st=e=>{try{let t=Q();return A.default.gt(e,t)}catch{return!1}},ct=e=>{let t=Q(),n=`Update available: ${c.default.dim(t)} โ ${c.default.green(e)}`,r=`\n\nRun ${c.default.cyan(`stackone update`)} to update`;P.box(n,r)},lt=()=>{try{if(!(0,k.existsSync)(it))return null;let e=(0,k.readFileSync)(it,`utf-8`);return JSON.parse(e)}catch{return null}},ut=e=>{try{(0,k.existsSync)(rt)||(0,k.mkdirSync)(rt,{recursive:!0}),(0,k.writeFileSync)(it,JSON.stringify(e,null,2),`utf-8`)}catch{}};var dt=class{constructor(e=new l.Command,t=Q()){this.program=e,this.version=t,this.setupProgram(),this.registerCommands()}setupProgram(){this.program.name(`stackone`).description(`StackOne CLI`).version(this.version,`-v, --version`)}registerCommands(){let e=new Me,t=new ze,n=new Le,r=new Ee,i=new Oe,a=new Je,o=new ve,s=new Se,u=new pe,d=new Ge,f=new qe;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,t)=>{t(c.default.red(e))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(t=>{e.execute({environment:t.env})}),this.program.command(`push`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new l.Argument(`<path>`,`Connector file or directory to push`)).description(`Push a connector to the StackOne registry`).action((e,n)=>{t.execute({profile:n.profile,fileOrDir:e,apiUrl:n.apiUrl,apiKey:n.apiKey})}),this.program.command(`drop`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).addArgument(new l.Argument(`<connector>`,`Connector identifier in format provider_key@version`)).description(`Drop a connector from the StackOne registry`).action((e,t)=>{r.execute({profile:t.profile,connector:e,apiUrl:t.apiUrl,apiKey:t.apiKey})}),this.program.command(`get`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key (defaults to latest)`).option(`--account-id <account-id>`,`Account ID to fetch connector from`).option(`-f, --format <format>`,`Output format: yaml or json (default: yaml)`,`yaml`).option(`-o, --output-file <output-file>`,`File to write the output to`).description(`Get a connector from the StackOne registry`).action(e=>{i.execute({profile:e.profile,connector:e.connector,accountId:e.accountId,format:e.format,outputFile:e.outputFile,apiUrl:e.apiUrl,apiKey:e.apiKey})}),this.program.command(`pull`).option(`-c, --connector <connector>`,`Connector identifier in format provider_key@version or provider_key`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output <path>`,`Output directory for the connectors files (default: ./connectors)`).description(`Pull a connector configuration from StackOne registry to local filesystem`).action(e=>{n.execute({profile:e.profile,connector:e.connector,outputPath:e.output,apiUrl:e.apiUrl,apiKey:e.apiKey})}),this.program.command(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new l.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{a.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`run`).option(`--connector <connector>`,`Connector file, inline YAML, or identifier (provider_key@version or provider_key for latest)`).option(`--action <action>`,`Action to execute on the connector (path to file or inline string action code)`).option(`--action-id <action-id>`,`Action ID to execute on the connector`).option(`--account <account>`,`Account details to use for running the connector (path to file or inline string account data)`).option(`--account-id <account-id>`,`Account ID to use for running the connector against (fetches connector from API if --connector not provided)`).option(`--params <params>`,`Action parameters (path to file or inline string with JSON parameters)`).option(`--credentials <credentials>`,`Credentials to use (path to file or inline string with JSON credentials)`).option(`-p, --profile <label>`,`Configuration profile to use`).option(`--api-url <api url>`,`API URL`).option(`--api-key <api key>`,`API Key`).option(`-o, --output-file <output-file>`,`File to write the output to`).option(`-d, --debug`,`Enables debug mode to include more details in the action execution output`).description(`Run a connector action`).action(e=>{d.execute({connector:e.connector,action:e.action,actionId:e.actionId,account:e.account,accountId:e.accountId,params:e.params,credentials:e.credentials,profile:e.profile,outputFile:e.outputFile,debug:e.debug,apiUrl:e.apiUrl,apiKey:e.apiKey})});let p=this.program.command(`agent`).description(`StackOne agent commands`);p.command(`setup`).option(`-g, --global`,`Setup global configuration`).option(`-l, --local`,`Setup local project configuration`).description(`Setup StackOne agent (global or local)`).action(e=>{e.global?o.execute():s.execute()}),p.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{u.execute()}),this.program.command(`update`).option(`-f, --force`,`Force reinstall even if already on latest version`).description(`Update the CLI to the latest version`).action(e=>{f.execute({force:e.force})}),this.program.command(`version`).description(`Show version information`).action(async()=>{P.log(`${c.default.inverse.greenBright(`StackOne`)} ${c.default.grey(`CLI`)} ${c.default.whiteBright(this.version)}`),at(!0),process.exit(0)})}run(){process.argv.includes(`version`)||at(),this.program.parse(process.argv)}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return dt}});
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./cliCore-
|
|
1
|
+
const e=require(`./cliCore-Emt0KqdF.cjs`);exports.CLI=e.t;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./cliCore-
|
|
1
|
+
import{t as e}from"./cliCore-DYoF7lqY.mjs";export{e as CLI};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackone/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"description": "StackOne Connect CLI tool",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -44,14 +44,15 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@clack/prompts": "0.11.0",
|
|
46
46
|
"@stackone/agent-config": "1.4.0",
|
|
47
|
-
"@stackone/connect-sdk": "2.
|
|
48
|
-
"@stackone/core": "2.
|
|
49
|
-
"@stackone/transport": "2.
|
|
47
|
+
"@stackone/connect-sdk": "2.18.0",
|
|
48
|
+
"@stackone/core": "2.10.0",
|
|
49
|
+
"@stackone/transport": "2.5.0",
|
|
50
|
+
"@stackone/utils": "0.16.0",
|
|
50
51
|
"chalk": "5.6.2",
|
|
51
52
|
"chokidar": "5.0.0",
|
|
52
53
|
"commander": "14.0.2",
|
|
53
54
|
"consola": "3.4.2",
|
|
54
|
-
"diff": "8.0.
|
|
55
|
+
"diff": "8.0.3",
|
|
55
56
|
"inquirer": "13.2.0",
|
|
56
57
|
"json-colorizer": "3.0.1",
|
|
57
58
|
"ora": "9.0.0",
|
|
@@ -64,8 +65,8 @@
|
|
|
64
65
|
"@swc/core": "1.15.8",
|
|
65
66
|
"@types/qs": "6.14.0",
|
|
66
67
|
"@types/semver": "^7.7.1",
|
|
67
|
-
"@vitest/coverage-istanbul": "4.0.
|
|
68
|
-
"@vitest/coverage-v8": "4.0.
|
|
68
|
+
"@vitest/coverage-istanbul": "4.0.17",
|
|
69
|
+
"@vitest/coverage-v8": "4.0.17",
|
|
69
70
|
"husky": "9.1.7",
|
|
70
71
|
"msw": "2.12.7",
|
|
71
72
|
"rimraf": "6.1.2",
|
|
@@ -76,7 +77,7 @@
|
|
|
76
77
|
"typescript": "5.9.3",
|
|
77
78
|
"unplugin-swc": "1.5.9",
|
|
78
79
|
"vite-tsconfig-paths": "6.0.4",
|
|
79
|
-
"vitest": "4.0.
|
|
80
|
+
"vitest": "4.0.17",
|
|
80
81
|
"vitest-mock-extended": "3.1.0"
|
|
81
82
|
},
|
|
82
83
|
"preferGlobal": true,
|
|
@@ -96,4 +97,4 @@
|
|
|
96
97
|
"node": "22.14.0",
|
|
97
98
|
"npm": "11.6.4"
|
|
98
99
|
}
|
|
99
|
-
}
|
|
100
|
+
}
|