@stackone/cli 1.8.1 โ 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE_TEMPLATE.md +634 -0
- package/README.md +52 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.js +1 -1
- package/dist/cliCore-57MzGvkG.js +139 -0
- package/dist/cliCore-BRPqDxQ9.cjs +139 -0
- package/dist/{esm-BrK-ICga.cjs โ esm-BSZWAx0q.cjs} +1 -1
- package/dist/esm-Wey0v-fi.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -1
- package/dist/cliCore-Bba3TFak.cjs +0 -7
- package/dist/cliCore-CGA-wigN.js +0 -7
- package/dist/esm-D_hUWJ1V.js +0 -1
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import e from"chalk";import{Argument as t,Command as n}from"commander";import{exec as r}from"node:child_process";import{access as i,chmod as a,mkdir as o,readFile as s,rm as c,writeFile as l}from"node:fs/promises";import{dirname as u,join as d}from"node:path";import{promisify as f}from"node:util";import p from"ora";import{existsSync as ee}from"node:fs";import{homedir as m}from"node:os";import{stdin as h,stdout as g}from"node:process";import{createInterface as _}from"node:readline";import v from"inquirer";import{fileURLToPath as y}from"node:url";import{existsSync as b,mkdirSync as te,readFileSync as x,readdirSync as S,statSync as C,writeFileSync as ne}from"fs";import{homedir as w}from"os";import{basename as T,dirname as re,join as E}from"path";import{loadConnector as D,validateYamlConnector as O}from"@stackone/connect-sdk";import{fileURLToPath as ie}from"url";const k=d(m(),`.stackone`),A=d(k,`agent-config.json`),ae=`stackone-agent-global`,oe=`stackone-agent-local`,se=process.env.STACKONE_AGENT_SERVER_URL||`https://mcp-internal-falcon.stackonehq.workers.dev/mcp`;async function j(){let e=ee(k);e||await o(k,{recursive:!0,mode:448})}async function M(e){await j(),await l(A,JSON.stringify(e,null,2)),await a(A,384)}async function N(){try{let e=await s(A,`utf-8`);return JSON.parse(e)}catch{return null}}async function ce(){try{await c(A,{force:!0})}catch{}}function P(){return se}function F(){return ae}function I(){return oe}function le(e){return new Date(e)<=new Date}function ue(e){return!!e?.apiKey&&!le(e.expiresAt)}const L=f(r);async function R(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 l(e,JSON.stringify(n,null,2)),r}catch{return!1}}var z=class{async execute(){console.log(e.blue.bold(`๐งน StackOne Agent Cleanup
|
|
2
|
+
`));let t={configsCleaned:0};try{let n=p(`Removing stored configuration...`).start();await ce(),n.succeed(`Removed ~/.stackone/agent-config.json`);let r=p(`Removing MCP servers from Claude...`).start(),i=0;try{let e=F();await L(`claude mcp remove ${e} 2>/dev/null`),i++}catch{}try{let e=I();await L(`claude mcp remove ${e} 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=p(`Checking for .mcp.json file...`).start(),o=process.cwd(),s=d(o,`.mcp.json`);try{let e=await R(s);e?(t.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)`)}console.log(e.green(`
|
|
3
|
+
โ Cleanup complete!`)),console.log(e.white(`
|
|
4
|
+
What was removed:`)),console.log(e.cyan(` โข ~/.stackone/agent-config.json`)),console.log(e.cyan(` โข MCP server from Claude configuration`)),t.configsCleaned>0&&console.log(e.cyan(` โข Hardcoded credentials from .mcp.json`)),console.log(e.dim(`
|
|
5
|
+
To authenticate again:`)),console.log(e.cyan(` stackone agent setup --global`),e.dim(`(for global setup)`)),console.log(e.cyan(` stackone agent setup --local`),e.dim(`(for local project setup)`)),console.log(``),process.exit(0)}catch(t){t instanceof Error?console.error(e.red(`\nโ ${t.message}\n`)):console.error(e.red(`
|
|
6
|
+
โ Unknown error occurred
|
|
7
|
+
`)),process.exit(1)}}},B=class{baseUrl;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 V=new B,H=f(r);function U(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}),o=t.toDateString()===n.toDateString()?`Today`:t.toDateString()===new Date(n.getTime()+864e5).toDateString()?`Tomorrow`:t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`});return`${o} at ${a} (${i} hours from now)`}var de=class{async execute(){console.log(e.blue.bold(`๐ค StackOne Agent Setup - Global Configuration
|
|
8
|
+
`));try{let t=process.cwd(),n=await i(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await i(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){console.log(e.yellow(`โ Existing local setup detected:`)),n&&console.log(e.dim(` โข CLAUDE.md found in current directory`)),r&&console.log(e.dim(` โข .mcp.json found in current directory`)),console.log();let{proceed:t}=await v.prompt([{type:`confirm`,name:`proceed`,message:`Re-authenticate globally despite existing local setup?`,default:!0}]);t||(console.log(e.dim(`
|
|
9
|
+
Setup cancelled.`)),process.exit(0)),console.log()}let a=await N(),o;if(a?.email){console.log(e.dim(`Last used email: ${a.email}\n`));let{useExisting:t}=await v.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);if(t)o=a.email;else{let t=_({input:h,output:g});o=await new Promise(n=>{t.question(e.white(`Email: `),e=>{n(e.trim())})}),t.close(),o||(console.error(e.red(`
|
|
10
|
+
โ Email is required
|
|
11
|
+
`)),process.exit(1))}}else{let t=_({input:h,output:g});o=await new Promise(n=>{t.question(e.white(`Email: `),e=>{n(e.trim())})}),t.close(),o||(console.error(e.red(`
|
|
12
|
+
โ Email is required
|
|
13
|
+
`)),process.exit(1))}let s=await v.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);s.password||(console.error(e.red(`
|
|
14
|
+
โ Password is required
|
|
15
|
+
`)),process.exit(1)),console.log();let c=p(`Authenticating...`).start(),l=await V.login(o,s.password);(!l.success||!l.apiKey)&&(c.fail(`Authentication failed`),console.error(e.red(`\nโ ${l.error||`Invalid credentials`}\n`)),console.log(e.dim(`Please check your email and password and try again.
|
|
16
|
+
`)),process.exit(1)),c.succeed(`Login successful!`);let u=new Date(Date.now()+1440*60*1e3).toISOString();await M({apiKey:l.apiKey,userId:o,email:o,expiresAt:u,serverUrl:P()}),console.log(e.green.bold(`
|
|
17
|
+
โ API key saved to ~/.stackone/agent-config.json`)),console.log(e.white(`โ Key expires at`),e.cyan(U(u)));let d=p(`Setting up global MCP configuration...`).start();try{let t=F(),n=P();try{await H(`claude mcp remove ${t} 2>/dev/null`)}catch{}let r=`claude mcp add ${t} ${n} --scope user --transport http --header "Authorization: Bearer ${l.apiKey}"`;await H(r),d.succeed(`Installed to Claude (global)`),console.log(e.green(`
|
|
18
|
+
โ Global setup complete!`)),console.log(e.white(`Config location:`),e.cyan(`~/.claude.json`)),console.log(e.blue(`
|
|
19
|
+
Verify:`),e.cyan(`claude mcp list`)),console.log(e.dim(`
|
|
20
|
+
๐ก Tip: Run Claude without permission prompts:`),e.cyan(`claude --dangerously-skip-permissions`)),console.log(e.dim(`
|
|
21
|
+
To setup for a specific project, run:`),e.cyan(`stackone agent setup --local`)),console.log(``)}catch(t){d.fail(`Installation to Claude failed`),t instanceof Error&&(console.error(e.red(`\nโ ${t.message}\n`)),console.error(e.dim(`You can manually add the server later with:`)),console.error(e.cyan(` claude mcp add ${F()} ${P()} --scope user --transport http --header "Authorization: Bearer ${l.apiKey}"`)))}process.exit(0)}catch(t){t instanceof Error?console.error(e.red(`\nโ ${t.message}\n`)):console.error(e.red(`
|
|
22
|
+
โ Unknown error occurred
|
|
23
|
+
`)),process.exit(1)}}};const W=f(r),fe=y(import.meta.url),pe=u(fe);async function me(){let e=d(pe,`..`,`..`,`..`,`CLAUDE_TEMPLATE.md`);try{return await s(e,`utf-8`)}catch{return`# ๐ STACKONE API CONFIG BUILDER
|
|
24
|
+
|
|
25
|
+
This document provides the complete methodology for building StackOne API configurations with Claude. Follow this strict workflow to ensure comprehensive, tested, and customer-valuable integrations.
|
|
26
|
+
|
|
27
|
+
## ๐ด CRITICAL WORKFLOW (STRICT ORDER)
|
|
28
|
+
|
|
29
|
+
When asked to build StackOne API configurations, you MUST follow this exact sequence:
|
|
30
|
+
|
|
31
|
+
1. **Research Phase (PARALLEL EXECUTION)** โ Launch \`discover_actions\` subagent for action discovery + main agent for auth/docs/external repos
|
|
32
|
+
2. **Synchronization** โ Collect and integrate subagent results
|
|
33
|
+
3. **Version Validation** โ \`analyze_versioning()\` โ Detect and resolve API version conflicts for discovered endpoints
|
|
34
|
+
4. **Config Building** โ Create comprehensive configuration with all discovered actions
|
|
35
|
+
5. **YAML Validation** โ \`stackone validate src/configs/<provider>.yaml\` โ Ensure valid YAML syntax
|
|
36
|
+
6. **Coverage Validation** โ \`check_all_endpoints()\` โ Confirm endpoint coverage โฅ80%
|
|
37
|
+
7. **Testing Phase** โ \`run_connector_action()\` โ Test EVERY action with real API calls
|
|
38
|
+
8. **Test Completion** โ \`check_test_completion()\` โ Verify 100% actions tested
|
|
39
|
+
9. **Security** โ \`scramble_credentials()\` โ Secure all sensitive data before storage
|
|
40
|
+
10. **Meta Feedback** โ \`meta_feedback()\` โ **MANDATORY** - Send feedback to third-party system for tracking
|
|
41
|
+
|
|
42
|
+
**โ Skip/Disorder = Incomplete Task / Professional Failure**
|
|
43
|
+
|
|
44
|
+
## ๐ฏ CORE PRINCIPLES
|
|
45
|
+
|
|
46
|
+
- **MAXIMUM COVERAGE**: Discover and include ALL useful actions that provide customer value
|
|
47
|
+
- **ACTION-FOCUSED**: Think: "what actions would developers commonly perform with this provider?"
|
|
48
|
+
- **CUSTOMER VALUE**: Prioritize actions that solve real business problems
|
|
49
|
+
- **MORE IS BETTER**: Default to comprehensiveness over minimalism
|
|
50
|
+
- **PRACTICAL UTILITY**: Focus on actions developers actually use in production
|
|
51
|
+
|
|
52
|
+
## ๐ AVAILABLE TOOLS
|
|
53
|
+
|
|
54
|
+
### Core Research
|
|
55
|
+
- \`get_stackone_categories()\`, \`get_stackone_actions(category)\`
|
|
56
|
+
- \`get_providers()\`, \`get_provider_coverage(provider)\`
|
|
57
|
+
- \`vector_search(query, provider, k)\`
|
|
58
|
+
|
|
59
|
+
### Action Discovery
|
|
60
|
+
- \`discover_actions(provider)\` - Autonomous AI agent (5-15 min)
|
|
61
|
+
- \`get_provider_actions(provider)\` - Check S3 for indexed actions
|
|
62
|
+
|
|
63
|
+
### API Versioning
|
|
64
|
+
- \`analyze_versioning(provider, endpoints)\` - Version validation (2-5 min)
|
|
65
|
+
|
|
66
|
+
### External Analysis
|
|
67
|
+
- \`get_external_integrations(provider)\`
|
|
68
|
+
- \`analyze_external_integration(integration, provider)\`
|
|
69
|
+
- \`scan_external_repo(repo_url, search_terms)\`
|
|
70
|
+
|
|
71
|
+
### Testing
|
|
72
|
+
- \`run_connector_action()\` - Test with real API calls
|
|
73
|
+
- \`check_all_endpoints()\` - Validate โฅ80% coverage
|
|
74
|
+
- \`check_test_completion()\` - Verify 100% tested
|
|
75
|
+
|
|
76
|
+
### Security
|
|
77
|
+
- \`scramble_credentials()\` - **REQUIRED** before storage
|
|
78
|
+
- \`meta_feedback()\` - **MANDATORY** after completion
|
|
79
|
+
|
|
80
|
+
## ๐ DOCUMENTATION
|
|
81
|
+
|
|
82
|
+
See \`src/configs/README.md\` for complete YAML structure, authentication patterns, actions, and field configs.
|
|
83
|
+
|
|
84
|
+
## ๐ AUTHENTICATION
|
|
85
|
+
|
|
86
|
+
Your CLI is authenticated via OAuth with StackOne.
|
|
87
|
+
|
|
88
|
+
**Security:** Your access token is stored as \`STACKONE_FALCON_MCP_TOKEN\` environment variable. The \`.mcp.json\` file uses this variable reference - safe to commit!
|
|
89
|
+
|
|
90
|
+
## โก QUICK START
|
|
91
|
+
|
|
92
|
+
\`\`\`bash
|
|
93
|
+
# Setup authentication (global)
|
|
94
|
+
stackone agent setup --global
|
|
95
|
+
|
|
96
|
+
# Setup local project
|
|
97
|
+
stackone agent setup --local
|
|
98
|
+
|
|
99
|
+
# Cleanup all credentials
|
|
100
|
+
stackone agent cleanup
|
|
101
|
+
\`\`\`
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
*Authenticated with StackOne โข Agent MCP Server*
|
|
106
|
+
*For full workflow details, see the complete CLAUDE.md in repository*
|
|
107
|
+
`}}const he=()=>`{
|
|
108
|
+
"mcpServers": {
|
|
109
|
+
"${I()}": {
|
|
110
|
+
"url": "${P()}",
|
|
111
|
+
"transport": {
|
|
112
|
+
"type": "http",
|
|
113
|
+
"headers": {
|
|
114
|
+
"Authorization": "Bearer \${STACKONE_AGENT_MCP_TOKEN}"
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}`;var ge=class{async execute(){console.log(e.blue.bold(`๐ค StackOne Agent Setup - Local Project
|
|
120
|
+
`));try{let t=process.cwd(),n=await i(`${t}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await i(`${t}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){console.log(e.yellow(`โ Existing local setup detected:`)),n&&console.log(e.dim(` โข CLAUDE.md found`)),r&&console.log(e.dim(` โข .mcp.json found`)),console.log();let{proceed:t}=await v.prompt([{type:`confirm`,name:`proceed`,message:`Overwrite existing local configuration?`,default:!1}]);t||(console.log(e.dim(`
|
|
121
|
+
Setup cancelled.`)),process.exit(0)),console.log()}let a=await N();if(!a||!ue(a)){console.log(e.yellow(`โ Not authenticated globally.`)),console.log(e.white(`Let's authenticate now...
|
|
122
|
+
`));let t=_({input:h,output:g}),n=await new Promise(n=>{t.question(e.white(`Email: `),e=>{n(e.trim())})});t.close(),n||(console.error(e.red(`
|
|
123
|
+
โ Email is required
|
|
124
|
+
`)),process.exit(1));let r=await v.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);r.password||(console.error(e.red(`
|
|
125
|
+
โ Password is required
|
|
126
|
+
`)),process.exit(1)),console.log();let i=p(`Authenticating...`).start(),o=await V.login(n,r.password);(!o.success||!o.apiKey)&&(i.fail(`Authentication failed`),console.error(e.red(`\nโ ${o.error||`Invalid credentials`}\n`)),console.log(e.dim(`Please check your email and password and try again.
|
|
127
|
+
`)),process.exit(1)),i.succeed(`Login successful!`);let s=new Date(Date.now()+1440*60*1e3).toISOString();await M({apiKey:o.apiKey,userId:n,email:n,expiresAt:s,serverUrl:P()}),a={apiKey:o.apiKey,userId:n,email:n,expiresAt:s,serverUrl:P()},console.log()}let o=p(`Setting up local project configuration...`).start();o.text=`Creating CLAUDE.md...`;let s=await me();await l(`CLAUDE.md`,s),o.succeed(`Created CLAUDE.md`);let c=p(`Creating .mcp.json...`).start();await l(`.mcp.json`,he()),c.succeed(`Created .mcp.json (using STACKONE_AGENT_MCP_TOKEN env var)`);let u=p(`Installing to Claude (local)...`).start();try{let t=I();try{await W(`claude mcp remove ${t} 2>/dev/null`)}catch{}let n=`claude mcp add ${t} ${P()} --scope local --transport http --header "Authorization: Bearer ${a.apiKey}"`;await W(n),u.succeed(`Installed to Claude (local)`),console.log(e.green(`
|
|
128
|
+
โ Local setup complete!`)),console.log(e.white(`Files created:`)),console.log(e.cyan(` - CLAUDE.md`)),console.log(e.cyan(` - .mcp.json`)),console.log(e.dim(`
|
|
129
|
+
๐ก The stackone-agent-local MCP server is now available in this project`)),console.log(e.dim(`
|
|
130
|
+
๐ก Tip: Run Claude without permission prompts:`),e.cyan(`claude --dangerously-skip-permissions`)),console.log(e.blue(`
|
|
131
|
+
Verify:`),e.cyan(`claude mcp list`)),console.log(``)}catch(t){u.fail(`Installation to Claude failed`),t instanceof Error&&(console.error(e.red(`\nโ ${t.message}\n`)),console.error(e.dim(`Configuration files created, but Claude setup failed.`)),console.error(e.dim(`You can manually add the server later with:`)),console.error(e.cyan(` claude mcp add ${I()} ${P()} --scope local --transport http --header "Authorization: Bearer ${a.apiKey}"`))),console.log(``)}process.exit(0)}catch(t){t instanceof Error?console.error(e.red(`\nโ ${t.message}\n`)):console.error(e.red(`
|
|
132
|
+
โ Unknown error occurred
|
|
133
|
+
`)),process.exit(1)}}};const G=E(w(),`.stackone`),K={profiles:{}},q=()=>{if(!b(G))return K;try{let e=x(G,`utf-8`);return JSON.parse(e)}catch{return K}},_e=e=>{let t=q();return t.profiles[e]},J=e=>{let t=q();return!!t.profiles[e]},ve=(e,t)=>{let n=q();n.profiles[e]=t;let r=E(w());b(r)||te(r,{recursive:!0}),ne(G,JSON.stringify(n,null,2),`utf-8`)},ye=()=>{let e=q();return Object.keys(e.profiles)};var Y=class{static info(t){console.info(e.blue(`โน`),t)}static warn(t){console.info(e.yellow(`โ `),t)}static error(t){console.info(e.red(`โ`),t)}static success(t){console.info(e.green(`โ`),t)}};const be=`https://api.stackone.com`,xe=`https://api.stackone-dev.com`,Se=`http://localhost:4000`;var Ce=class{async execute({environment:t}={}){let n=t?.toLowerCase()??`production`;try{let{label:t}=await v.prompt([{type:`input`,name:`label`,message:`Profile label:`,validate:e=>!e||e.trim().length===0?`The profile label is required`:e.includes(` `)?`The profile label cannot contain spaces`:!0}]);if(J(t)){let{overwrite:e}=await v.prompt([{type:`confirm`,name:`overwrite`,message:`Configuration profile with name "${t}" already exists. Do you want to overwrite it?`,default:!1}]);e||(Y.info(`Configuration profile initialization cancelled`),process.exit(0))}let r;if(n===`production`)r=be;else if(n===`staging`)r=xe;else{let{customUrl:e}=await v.prompt([{type:`input`,name:`customUrl`,message:`API URL:`,default:Se,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{return new URL(e),!0}catch{return`Please enter a valid URL`}}}]);r=e}let{apiKey:i}=await v.prompt([{type:`password`,name:`apiKey`,message:`API Key:`,validate:e=>!e||e.trim().length===0?`API Key is required`:!0}]),a={label:t,environment:n,apiUrl:r,apiKey:i};ve(t,a),console.info(e.green(`\nโ Configuration profile "${t}" saved successfully`)),process.exit(0)}catch(e){e.isTtyError?Y.error(`Prompt couldn't be rendered in the current environment`):Y.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const X=`https://api.stackone.com`;var we=class{async execute({profile:e,fileOrDir:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(Y.error(`Please provide a profile or API key to use for pushing the connector.`),Y.info(`You can provide these using the --profile and --api-key options.`),Y.info(`Run "stackone init" to create a new configuration profile.`),process.exit(1)),e&&r&&(Y.error(`Please provide either a profile or an API key, not both.`),process.exit(1)),e&&n&&Y.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),e&&!J(e)){Y.error(`Configuration profile "${e}" not found.`),Y.info(`Run "stackone init" to create a new configuration profile.`);let t=ye();Y.info(`Available profiles: ${t.join(`, `)||`none`}`),process.exit(1)}let i=e?_e(e):{apiUrl:n??X,apiKey:r};i||(Y.error(`Failed to load configuration profile "${e}".`),process.exit(1)),i.apiKey||(Y.error(`API key is missing. Please provide a valid API key in the profile or via the --api-key option.`),process.exit(1)),t||(Y.error(`File or directory path is required.`),process.exit(1));try{C(t)}catch{Y.error(`File or directory not found: ${t}`),process.exit(1)}let a=C(t),o=i.apiUrl??X;if(a.isDirectory()){let e=Z(t),n=0;e.length===0?(Y.error(`No .s1.yaml connector files found in the directory: ${t}.`),process.exit(1)):Y.info(`Found ${e.length} connector(s) file(s). Processing...`);for(let t of e){console.info(`
|
|
134
|
+
`);let e=await this.uploadFile(t,o,i.apiKey);e&&n++}console.info(`
|
|
135
|
+
`),Y.info(`Upload completed: ${n} of ${e.length} file(s) uploaded successfully.`),process.exit(n>0?0:1)}else t.endsWith(`.s1.yaml`)||(Y.error(`Only .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(t,n,r){try{console.info(e.blue(`๐ค Uploading ${T(t)}...`));let i=Te(t);if(!i)return!1;let a=T(t),o=new FormData,s=new Blob([i],{type:`application/x-yaml`});o.append(`file`,s,a);let c=Buffer.from(r).toString(`base64`),l=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${c}`},body:o});if(!l.ok){let t=await l.text();return Y.error(`Upload failed: ${l.status} - ${l.statusText}`),t&&console.error(e.red(t)),!1}let u=await l.json();return console.info(e.green(`โ Successfully uploaded ${a} with connector "${u.provider}@${u.version}"`)),!0}catch(e){return Y.error(`Failed to upload file: ${e}`),!1}}};const Te=t=>{let n=D(t),r=O(n),i=r?.errors??[];if(r.success){let e=t.split(`/`).pop()||t;return Y.success(`Connector ${e} is valid!`),n}else i.length>0?(Y.error(`Connector ${t} is not valid. Please fix the following errors:\n`),i.forEach(t=>{console.info(e.red(`- L${t.line}: ${t.message}`))})):Y.error(`Connector ${t} is not valid. Please check the file for errors.`)},Z=e=>{let t=[],n=S(e,{withFileTypes:!0});for(let r of n){let n=E(e,r.name);r.isDirectory()?t.push(...Z(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t};var Ee=class{async execute(t){let{watchMode:n,fileOrDir:r}=t,i=p(`Watching for changes...`),a=()=>{console.clear(),console.info(e.yellow(`Watch mode enabled. Press "q" to quit.
|
|
136
|
+
`))};if(r){try{C(r)}catch{Y.error(`File or directory not found: ${r}`),process.exit(1)}if(n){let{watch:t}=await import(`./esm-Wey0v-fi.js`),n=await import(`readline`),o=n.createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{console.info(e.grey(`
|
|
137
|
+
|
|
138
|
+
Exiting watch mode...`)),c.close(),i.stop(),o.close(),process.exit(0)};a(),console.info(e.blue(`Running connector(s) validations...`)),await Q(r),i.start();let c=t(r||`.`,{ignored:/(^|[/\\])\../,persistent:!0});c.on(`change`,async t=>{a(),i.stop(),console.info(e.blue(`File change detected. Running connector(s) validations...`)),await Q(r),i.start()}),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else await Q(r),process.exit(0)}}};const Q=async e=>{let t=C(e);if(t.isDirectory()){let t=S(e),n=t.filter(e=>e.endsWith(`.s1.yaml`));if(n.length===0){Y.error(`No StackOne connectors found in directory: ${e}. Connector files need to have the extension .s1.yaml.\n`);return}let r=0,i=0;for(let t of n){let n=`${e}/${t}`,a=C(n);if(a.isFile()){let e=await $(n);e?r++:i++}}Y.info(`Validation completed: ${r} valid, ${i} invalid connectors.\n`)}else t.isFile()&&e.endsWith(`s1.yaml`)?await $(e):Y.error(`No StackOne connector found: ${e}. Connector files need to have the extension .s1.yaml.\n`)},$=async t=>{let n=D(t),r=O(n),i=r?.errors??[];if(r.success){let e=t.split(`/`).pop()||t;return Y.success(`Connector ${e} is valid!\n`),!0}else if(i.length>0)return Y.error(`Connector ${t} is not valid. Please fix the following errors:\n`),i.forEach(t=>{console.info(e.red(`- L${t.line}: ${t.message}`))}),console.info(`
|
|
139
|
+
`),!1;else return Y.error(`Connector ${t} is not valid. Please check the file for errors.`),!1},De=()=>{try{let e=ie(import.meta.url),t=re(e),n=E(t,`..`,`package.json`),r=JSON.parse(x(n,`utf8`));return r.version}catch{return`unknown`}};var Oe=class{constructor(e=new n,t=De()){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 n=new Ce,r=new we,i=new Ee,a=new de,o=new ge,s=new z;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(t,n)=>{n(e.red(t))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(e=>{n.execute({environment:e.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 t(`<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(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new t(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{i.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`version`).description(`Show version information`).action(()=>{console.info(`${e.greenBright(`StackOne`)} ${e.grey(`CLI`)} ${e.whiteBright(this.version)}`),process.exit(0)});let c=this.program.command(`agent`).description(`StackOne agent commands`);c.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?a.execute():o.execute()}),c.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{s.execute()})}run(){this.program.parse(process.argv)}};export{Oe as CLI};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
const e=require(`./chunk-CUT6urMc.cjs`),t=e.__toESM(require(`chalk`)),n=e.__toESM(require(`commander`)),r=e.__toESM(require(`node:child_process`)),i=e.__toESM(require(`node:fs/promises`)),a=e.__toESM(require(`node:path`)),o=e.__toESM(require(`node:util`)),s=e.__toESM(require(`ora`)),c=e.__toESM(require(`node:fs`)),l=e.__toESM(require(`node:os`)),u=e.__toESM(require(`node:process`)),d=e.__toESM(require(`node:readline`)),f=e.__toESM(require(`inquirer`)),p=e.__toESM(require(`node:url`)),m=e.__toESM(require(`fs`)),h=e.__toESM(require(`os`)),g=e.__toESM(require(`path`)),_=e.__toESM(require(`@stackone/connect-sdk`)),ee=e.__toESM(require(`url`)),v=(0,a.join)((0,l.homedir)(),`.stackone`),y=(0,a.join)(v,`agent-config.json`),te=`stackone-agent-global`,b=`stackone-agent-local`,x=process.env.STACKONE_AGENT_SERVER_URL||`https://mcp-internal-falcon.stackonehq.workers.dev/mcp`;async function S(){let e=(0,c.existsSync)(v);e||await(0,i.mkdir)(v,{recursive:!0,mode:448})}async function C(e){await S(),await(0,i.writeFile)(y,JSON.stringify(e,null,2)),await(0,i.chmod)(y,384)}async function w(){try{let e=await(0,i.readFile)(y,`utf-8`);return JSON.parse(e)}catch{return null}}async function ne(){try{await(0,i.rm)(y,{force:!0})}catch{}}function T(){return x}function E(){return te}function D(){return b}function O(e){return new Date(e)<=new Date}function k(e){return!!e?.apiKey&&!O(e.expiresAt)}const A=(0,o.promisify)(r.exec);async function re(e){try{let t=await(0,i.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,i.writeFile)(e,JSON.stringify(n,null,2)),r}catch{return!1}}var ie=class{async execute(){console.log(t.default.blue.bold(`๐งน StackOne Agent Cleanup
|
|
2
|
+
`));let e={configsCleaned:0};try{let n=(0,s.default)(`Removing stored configuration...`).start();await ne(),n.succeed(`Removed ~/.stackone/agent-config.json`);let r=(0,s.default)(`Removing MCP servers from Claude...`).start(),i=0;try{let e=E();await A(`claude mcp remove ${e} 2>/dev/null`),i++}catch{}try{let e=D();await A(`claude mcp remove ${e} 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 o=(0,s.default)(`Checking for .mcp.json file...`).start(),c=process.cwd(),l=(0,a.join)(c,`.mcp.json`);try{let t=await re(l);t?(e.configsCleaned=1,o.succeed(`Cleaned .mcp.json (replaced tokens with environment variables)`)):o.info(`.mcp.json already uses environment variables or not found`)}catch{o.info(`.mcp.json not found (already cleaned or not created)`)}console.log(t.default.green(`
|
|
3
|
+
โ Cleanup complete!`)),console.log(t.default.white(`
|
|
4
|
+
What was removed:`)),console.log(t.default.cyan(` โข ~/.stackone/agent-config.json`)),console.log(t.default.cyan(` โข MCP server from Claude configuration`)),e.configsCleaned>0&&console.log(t.default.cyan(` โข Hardcoded credentials from .mcp.json`)),console.log(t.default.dim(`
|
|
5
|
+
To authenticate again:`)),console.log(t.default.cyan(` stackone agent setup --global`),t.default.dim(`(for global setup)`)),console.log(t.default.cyan(` stackone agent setup --local`),t.default.dim(`(for local project setup)`)),console.log(``),process.exit(0)}catch(e){e instanceof Error?console.error(t.default.red(`\nโ ${e.message}\n`)):console.error(t.default.red(`
|
|
6
|
+
โ Unknown error occurred
|
|
7
|
+
`)),process.exit(1)}}},ae=class{baseUrl;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 j=new ae,M=(0,o.promisify)(r.exec);function N(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}),o=t.toDateString()===n.toDateString()?`Today`:t.toDateString()===new Date(n.getTime()+864e5).toDateString()?`Tomorrow`:t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`});return`${o} at ${a} (${i} hours from now)`}var P=class{async execute(){console.log(t.default.blue.bold(`๐ค StackOne Agent Setup - Global Configuration
|
|
8
|
+
`));try{let e=process.cwd(),n=await(0,i.access)(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await(0,i.access)(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){console.log(t.default.yellow(`โ Existing local setup detected:`)),n&&console.log(t.default.dim(` โข CLAUDE.md found in current directory`)),r&&console.log(t.default.dim(` โข .mcp.json found in current directory`)),console.log();let{proceed:e}=await f.default.prompt([{type:`confirm`,name:`proceed`,message:`Re-authenticate globally despite existing local setup?`,default:!0}]);e||(console.log(t.default.dim(`
|
|
9
|
+
Setup cancelled.`)),process.exit(0)),console.log()}let a=await w(),o;if(a?.email){console.log(t.default.dim(`Last used email: ${a.email}\n`));let{useExisting:e}=await f.default.prompt([{type:`confirm`,name:`useExisting`,message:`Sign in with this email?`,default:!0}]);if(e)o=a.email;else{let e=(0,d.createInterface)({input:u.stdin,output:u.stdout});o=await new Promise(n=>{e.question(t.default.white(`Email: `),e=>{n(e.trim())})}),e.close(),o||(console.error(t.default.red(`
|
|
10
|
+
โ Email is required
|
|
11
|
+
`)),process.exit(1))}}else{let e=(0,d.createInterface)({input:u.stdin,output:u.stdout});o=await new Promise(n=>{e.question(t.default.white(`Email: `),e=>{n(e.trim())})}),e.close(),o||(console.error(t.default.red(`
|
|
12
|
+
โ Email is required
|
|
13
|
+
`)),process.exit(1))}let c=await f.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);c.password||(console.error(t.default.red(`
|
|
14
|
+
โ Password is required
|
|
15
|
+
`)),process.exit(1)),console.log();let l=(0,s.default)(`Authenticating...`).start(),p=await j.login(o,c.password);(!p.success||!p.apiKey)&&(l.fail(`Authentication failed`),console.error(t.default.red(`\nโ ${p.error||`Invalid credentials`}\n`)),console.log(t.default.dim(`Please check your email and password and try again.
|
|
16
|
+
`)),process.exit(1)),l.succeed(`Login successful!`);let m=new Date(Date.now()+1440*60*1e3).toISOString();await C({apiKey:p.apiKey,userId:o,email:o,expiresAt:m,serverUrl:T()}),console.log(t.default.green.bold(`
|
|
17
|
+
โ API key saved to ~/.stackone/agent-config.json`)),console.log(t.default.white(`โ Key expires at`),t.default.cyan(N(m)));let h=(0,s.default)(`Setting up global MCP configuration...`).start();try{let e=E(),n=T();try{await M(`claude mcp remove ${e} 2>/dev/null`)}catch{}let r=`claude mcp add ${e} ${n} --scope user --transport http --header "Authorization: Bearer ${p.apiKey}"`;await M(r),h.succeed(`Installed to Claude (global)`),console.log(t.default.green(`
|
|
18
|
+
โ Global setup complete!`)),console.log(t.default.white(`Config location:`),t.default.cyan(`~/.claude.json`)),console.log(t.default.blue(`
|
|
19
|
+
Verify:`),t.default.cyan(`claude mcp list`)),console.log(t.default.dim(`
|
|
20
|
+
๐ก Tip: Run Claude without permission prompts:`),t.default.cyan(`claude --dangerously-skip-permissions`)),console.log(t.default.dim(`
|
|
21
|
+
To setup for a specific project, run:`),t.default.cyan(`stackone agent setup --local`)),console.log(``)}catch(e){h.fail(`Installation to Claude failed`),e instanceof Error&&(console.error(t.default.red(`\nโ ${e.message}\n`)),console.error(t.default.dim(`You can manually add the server later with:`)),console.error(t.default.cyan(` claude mcp add ${E()} ${T()} --scope user --transport http --header "Authorization: Bearer ${p.apiKey}"`)))}process.exit(0)}catch(e){e instanceof Error?console.error(t.default.red(`\nโ ${e.message}\n`)):console.error(t.default.red(`
|
|
22
|
+
โ Unknown error occurred
|
|
23
|
+
`)),process.exit(1)}}};const F=(0,o.promisify)(r.exec),I=(0,p.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),L=(0,a.dirname)(I);async function R(){let e=(0,a.join)(L,`..`,`..`,`..`,`CLAUDE_TEMPLATE.md`);try{return await(0,i.readFile)(e,`utf-8`)}catch{return`# ๐ STACKONE API CONFIG BUILDER
|
|
24
|
+
|
|
25
|
+
This document provides the complete methodology for building StackOne API configurations with Claude. Follow this strict workflow to ensure comprehensive, tested, and customer-valuable integrations.
|
|
26
|
+
|
|
27
|
+
## ๐ด CRITICAL WORKFLOW (STRICT ORDER)
|
|
28
|
+
|
|
29
|
+
When asked to build StackOne API configurations, you MUST follow this exact sequence:
|
|
30
|
+
|
|
31
|
+
1. **Research Phase (PARALLEL EXECUTION)** โ Launch \`discover_actions\` subagent for action discovery + main agent for auth/docs/external repos
|
|
32
|
+
2. **Synchronization** โ Collect and integrate subagent results
|
|
33
|
+
3. **Version Validation** โ \`analyze_versioning()\` โ Detect and resolve API version conflicts for discovered endpoints
|
|
34
|
+
4. **Config Building** โ Create comprehensive configuration with all discovered actions
|
|
35
|
+
5. **YAML Validation** โ \`stackone validate src/configs/<provider>.yaml\` โ Ensure valid YAML syntax
|
|
36
|
+
6. **Coverage Validation** โ \`check_all_endpoints()\` โ Confirm endpoint coverage โฅ80%
|
|
37
|
+
7. **Testing Phase** โ \`run_connector_action()\` โ Test EVERY action with real API calls
|
|
38
|
+
8. **Test Completion** โ \`check_test_completion()\` โ Verify 100% actions tested
|
|
39
|
+
9. **Security** โ \`scramble_credentials()\` โ Secure all sensitive data before storage
|
|
40
|
+
10. **Meta Feedback** โ \`meta_feedback()\` โ **MANDATORY** - Send feedback to third-party system for tracking
|
|
41
|
+
|
|
42
|
+
**โ Skip/Disorder = Incomplete Task / Professional Failure**
|
|
43
|
+
|
|
44
|
+
## ๐ฏ CORE PRINCIPLES
|
|
45
|
+
|
|
46
|
+
- **MAXIMUM COVERAGE**: Discover and include ALL useful actions that provide customer value
|
|
47
|
+
- **ACTION-FOCUSED**: Think: "what actions would developers commonly perform with this provider?"
|
|
48
|
+
- **CUSTOMER VALUE**: Prioritize actions that solve real business problems
|
|
49
|
+
- **MORE IS BETTER**: Default to comprehensiveness over minimalism
|
|
50
|
+
- **PRACTICAL UTILITY**: Focus on actions developers actually use in production
|
|
51
|
+
|
|
52
|
+
## ๐ AVAILABLE TOOLS
|
|
53
|
+
|
|
54
|
+
### Core Research
|
|
55
|
+
- \`get_stackone_categories()\`, \`get_stackone_actions(category)\`
|
|
56
|
+
- \`get_providers()\`, \`get_provider_coverage(provider)\`
|
|
57
|
+
- \`vector_search(query, provider, k)\`
|
|
58
|
+
|
|
59
|
+
### Action Discovery
|
|
60
|
+
- \`discover_actions(provider)\` - Autonomous AI agent (5-15 min)
|
|
61
|
+
- \`get_provider_actions(provider)\` - Check S3 for indexed actions
|
|
62
|
+
|
|
63
|
+
### API Versioning
|
|
64
|
+
- \`analyze_versioning(provider, endpoints)\` - Version validation (2-5 min)
|
|
65
|
+
|
|
66
|
+
### External Analysis
|
|
67
|
+
- \`get_external_integrations(provider)\`
|
|
68
|
+
- \`analyze_external_integration(integration, provider)\`
|
|
69
|
+
- \`scan_external_repo(repo_url, search_terms)\`
|
|
70
|
+
|
|
71
|
+
### Testing
|
|
72
|
+
- \`run_connector_action()\` - Test with real API calls
|
|
73
|
+
- \`check_all_endpoints()\` - Validate โฅ80% coverage
|
|
74
|
+
- \`check_test_completion()\` - Verify 100% tested
|
|
75
|
+
|
|
76
|
+
### Security
|
|
77
|
+
- \`scramble_credentials()\` - **REQUIRED** before storage
|
|
78
|
+
- \`meta_feedback()\` - **MANDATORY** after completion
|
|
79
|
+
|
|
80
|
+
## ๐ DOCUMENTATION
|
|
81
|
+
|
|
82
|
+
See \`src/configs/README.md\` for complete YAML structure, authentication patterns, actions, and field configs.
|
|
83
|
+
|
|
84
|
+
## ๐ AUTHENTICATION
|
|
85
|
+
|
|
86
|
+
Your CLI is authenticated via OAuth with StackOne.
|
|
87
|
+
|
|
88
|
+
**Security:** Your access token is stored as \`STACKONE_FALCON_MCP_TOKEN\` environment variable. The \`.mcp.json\` file uses this variable reference - safe to commit!
|
|
89
|
+
|
|
90
|
+
## โก QUICK START
|
|
91
|
+
|
|
92
|
+
\`\`\`bash
|
|
93
|
+
# Setup authentication (global)
|
|
94
|
+
stackone agent setup --global
|
|
95
|
+
|
|
96
|
+
# Setup local project
|
|
97
|
+
stackone agent setup --local
|
|
98
|
+
|
|
99
|
+
# Cleanup all credentials
|
|
100
|
+
stackone agent cleanup
|
|
101
|
+
\`\`\`
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
*Authenticated with StackOne โข Agent MCP Server*
|
|
106
|
+
*For full workflow details, see the complete CLAUDE.md in repository*
|
|
107
|
+
`}}const z=()=>`{
|
|
108
|
+
"mcpServers": {
|
|
109
|
+
"${D()}": {
|
|
110
|
+
"url": "${T()}",
|
|
111
|
+
"transport": {
|
|
112
|
+
"type": "http",
|
|
113
|
+
"headers": {
|
|
114
|
+
"Authorization": "Bearer \${STACKONE_AGENT_MCP_TOKEN}"
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}`;var B=class{async execute(){console.log(t.default.blue.bold(`๐ค StackOne Agent Setup - Local Project
|
|
120
|
+
`));try{let e=process.cwd(),n=await(0,i.access)(`${e}/CLAUDE.md`).then(()=>!0).catch(()=>!1),r=await(0,i.access)(`${e}/.mcp.json`).then(()=>!0).catch(()=>!1);if(n||r){console.log(t.default.yellow(`โ Existing local setup detected:`)),n&&console.log(t.default.dim(` โข CLAUDE.md found`)),r&&console.log(t.default.dim(` โข .mcp.json found`)),console.log();let{proceed:e}=await f.default.prompt([{type:`confirm`,name:`proceed`,message:`Overwrite existing local configuration?`,default:!1}]);e||(console.log(t.default.dim(`
|
|
121
|
+
Setup cancelled.`)),process.exit(0)),console.log()}let a=await w();if(!a||!k(a)){console.log(t.default.yellow(`โ Not authenticated globally.`)),console.log(t.default.white(`Let's authenticate now...
|
|
122
|
+
`));let e=(0,d.createInterface)({input:u.stdin,output:u.stdout}),n=await new Promise(n=>{e.question(t.default.white(`Email: `),e=>{n(e.trim())})});e.close(),n||(console.error(t.default.red(`
|
|
123
|
+
โ Email is required
|
|
124
|
+
`)),process.exit(1));let r=await f.default.prompt([{type:`password`,name:`password`,message:`Password:`,mask:`*`}]);r.password||(console.error(t.default.red(`
|
|
125
|
+
โ Password is required
|
|
126
|
+
`)),process.exit(1)),console.log();let i=(0,s.default)(`Authenticating...`).start(),o=await j.login(n,r.password);(!o.success||!o.apiKey)&&(i.fail(`Authentication failed`),console.error(t.default.red(`\nโ ${o.error||`Invalid credentials`}\n`)),console.log(t.default.dim(`Please check your email and password and try again.
|
|
127
|
+
`)),process.exit(1)),i.succeed(`Login successful!`);let c=new Date(Date.now()+1440*60*1e3).toISOString();await C({apiKey:o.apiKey,userId:n,email:n,expiresAt:c,serverUrl:T()}),a={apiKey:o.apiKey,userId:n,email:n,expiresAt:c,serverUrl:T()},console.log()}let o=(0,s.default)(`Setting up local project configuration...`).start();o.text=`Creating CLAUDE.md...`;let c=await R();await(0,i.writeFile)(`CLAUDE.md`,c),o.succeed(`Created CLAUDE.md`);let l=(0,s.default)(`Creating .mcp.json...`).start();await(0,i.writeFile)(`.mcp.json`,z()),l.succeed(`Created .mcp.json (using STACKONE_AGENT_MCP_TOKEN env var)`);let p=(0,s.default)(`Installing to Claude (local)...`).start();try{let e=D();try{await F(`claude mcp remove ${e} 2>/dev/null`)}catch{}let n=`claude mcp add ${e} ${T()} --scope local --transport http --header "Authorization: Bearer ${a.apiKey}"`;await F(n),p.succeed(`Installed to Claude (local)`),console.log(t.default.green(`
|
|
128
|
+
โ Local setup complete!`)),console.log(t.default.white(`Files created:`)),console.log(t.default.cyan(` - CLAUDE.md`)),console.log(t.default.cyan(` - .mcp.json`)),console.log(t.default.dim(`
|
|
129
|
+
๐ก The stackone-agent-local MCP server is now available in this project`)),console.log(t.default.dim(`
|
|
130
|
+
๐ก Tip: Run Claude without permission prompts:`),t.default.cyan(`claude --dangerously-skip-permissions`)),console.log(t.default.blue(`
|
|
131
|
+
Verify:`),t.default.cyan(`claude mcp list`)),console.log(``)}catch(e){p.fail(`Installation to Claude failed`),e instanceof Error&&(console.error(t.default.red(`\nโ ${e.message}\n`)),console.error(t.default.dim(`Configuration files created, but Claude setup failed.`)),console.error(t.default.dim(`You can manually add the server later with:`)),console.error(t.default.cyan(` claude mcp add ${D()} ${T()} --scope local --transport http --header "Authorization: Bearer ${a.apiKey}"`))),console.log(``)}process.exit(0)}catch(e){e instanceof Error?console.error(t.default.red(`\nโ ${e.message}\n`)):console.error(t.default.red(`
|
|
132
|
+
โ Unknown error occurred
|
|
133
|
+
`)),process.exit(1)}}};const V=(0,g.join)((0,h.homedir)(),`.stackone`),H={profiles:{}},U=()=>{if(!(0,m.existsSync)(V))return H;try{let e=(0,m.readFileSync)(V,`utf-8`);return JSON.parse(e)}catch{return H}},W=e=>{let t=U();return t.profiles[e]},G=e=>{let t=U();return!!t.profiles[e]},K=(e,t)=>{let n=U();n.profiles[e]=t;let r=(0,g.join)((0,h.homedir)());(0,m.existsSync)(r)||(0,m.mkdirSync)(r,{recursive:!0}),(0,m.writeFileSync)(V,JSON.stringify(n,null,2),`utf-8`)},q=()=>{let e=U();return Object.keys(e.profiles)};var J=class{static info(e){console.info(t.default.blue(`โน`),e)}static warn(e){console.info(t.default.yellow(`โ `),e)}static error(e){console.info(t.default.red(`โ`),e)}static success(e){console.info(t.default.green(`โ`),e)}};const oe=`https://api.stackone.com`,se=`https://api.stackone-dev.com`,ce=`http://localhost:4000`;var le=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{let{label:e}=await f.default.prompt([{type:`input`,name:`label`,message:`Profile label:`,validate:e=>!e||e.trim().length===0?`The profile label is required`:e.includes(` `)?`The profile label cannot contain spaces`:!0}]);if(G(e)){let{overwrite:t}=await f.default.prompt([{type:`confirm`,name:`overwrite`,message:`Configuration profile with name "${e}" already exists. Do you want to overwrite it?`,default:!1}]);t||(J.info(`Configuration profile initialization cancelled`),process.exit(0))}let r;if(n===`production`)r=oe;else if(n===`staging`)r=se;else{let{customUrl:e}=await f.default.prompt([{type:`input`,name:`customUrl`,message:`API URL:`,default:ce,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{return new URL(e),!0}catch{return`Please enter a valid URL`}}}]);r=e}let{apiKey:i}=await f.default.prompt([{type:`password`,name:`apiKey`,message:`API Key:`,validate:e=>!e||e.trim().length===0?`API Key is required`:!0}]),a={label:e,environment:n,apiUrl:r,apiKey:i};K(e,a),console.info(t.default.green(`\nโ Configuration profile "${e}" saved successfully`)),process.exit(0)}catch(e){e.isTtyError?J.error(`Prompt couldn't be rendered in the current environment`):J.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const Y=`https://api.stackone.com`;var X=class{async execute({profile:e,fileOrDir:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(J.error(`Please provide a profile or API key to use for pushing the connector.`),J.info(`You can provide these using the --profile and --api-key options.`),J.info(`Run "stackone init" to create a new configuration profile.`),process.exit(1)),e&&r&&(J.error(`Please provide either a profile or an API key, not both.`),process.exit(1)),e&&n&&J.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),e&&!G(e)){J.error(`Configuration profile "${e}" not found.`),J.info(`Run "stackone init" to create a new configuration profile.`);let t=q();J.info(`Available profiles: ${t.join(`, `)||`none`}`),process.exit(1)}let i=e?W(e):{apiUrl:n??Y,apiKey:r};i||(J.error(`Failed to load configuration profile "${e}".`),process.exit(1)),i.apiKey||(J.error(`API key is missing. Please provide a valid API key in the profile or via the --api-key option.`),process.exit(1)),t||(J.error(`File or directory path is required.`),process.exit(1));try{(0,m.statSync)(t)}catch{J.error(`File or directory not found: ${t}`),process.exit(1)}let a=(0,m.statSync)(t),o=i.apiUrl??Y;if(a.isDirectory()){let e=Z(t),n=0;e.length===0?(J.error(`No .s1.yaml connector files found in the directory: ${t}.`),process.exit(1)):J.info(`Found ${e.length} connector(s) file(s). Processing...`);for(let t of e){console.info(`
|
|
134
|
+
`);let e=await this.uploadFile(t,o,i.apiKey);e&&n++}console.info(`
|
|
135
|
+
`),J.info(`Upload completed: ${n} of ${e.length} file(s) uploaded successfully.`),process.exit(n>0?0:1)}else t.endsWith(`.s1.yaml`)||(J.error(`Only .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,n,r){try{console.info(t.default.blue(`๐ค Uploading ${(0,g.basename)(e)}...`));let i=ue(e);if(!i)return!1;let a=(0,g.basename)(e),o=new FormData,s=new Blob([i],{type:`application/x-yaml`});o.append(`file`,s,a);let c=Buffer.from(r).toString(`base64`),l=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${c}`},body:o});if(!l.ok){let e=await l.text();return J.error(`Upload failed: ${l.status} - ${l.statusText}`),e&&console.error(t.default.red(e)),!1}let u=await l.json();return console.info(t.default.green(`โ Successfully uploaded ${a} with connector "${u.provider}@${u.version}"`)),!0}catch(e){return J.error(`Failed to upload file: ${e}`),!1}}};const ue=e=>{let n=(0,_.loadConnector)(e),r=(0,_.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let t=e.split(`/`).pop()||e;return J.success(`Connector ${t} is valid!`),n}else i.length>0?(J.error(`Connector ${e} is not valid. Please fix the following errors:\n`),i.forEach(e=>{console.info(t.default.red(`- L${e.line}: ${e.message}`))})):J.error(`Connector ${e} is not valid. Please check the file for errors.`)},Z=e=>{let t=[],n=(0,m.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,g.join)(e,r.name);r.isDirectory()?t.push(...Z(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t};var de=class{async execute(e){let{watchMode:n,fileOrDir:r}=e,i=(0,s.default)(`Watching for changes...`),a=()=>{console.clear(),console.info(t.default.yellow(`Watch mode enabled. Press "q" to quit.
|
|
136
|
+
`))};if(r){try{(0,m.statSync)(r)}catch{J.error(`File or directory not found: ${r}`),process.exit(1)}if(n){let{watch:e}=await Promise.resolve().then(()=>require(`./esm-BSZWAx0q.cjs`)),n=await import(`readline`),o=n.createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{console.info(t.default.grey(`
|
|
137
|
+
|
|
138
|
+
Exiting watch mode...`)),c.close(),i.stop(),o.close(),process.exit(0)};a(),console.info(t.default.blue(`Running connector(s) validations...`)),await Q(r),i.start();let c=e(r||`.`,{ignored:/(^|[/\\])\../,persistent:!0});c.on(`change`,async e=>{a(),i.stop(),console.info(t.default.blue(`File change detected. Running connector(s) validations...`)),await Q(r),i.start()}),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else await Q(r),process.exit(0)}}};const Q=async e=>{let t=(0,m.statSync)(e);if(t.isDirectory()){let t=(0,m.readdirSync)(e),n=t.filter(e=>e.endsWith(`.s1.yaml`));if(n.length===0){J.error(`No StackOne connectors found in directory: ${e}. Connector files need to have the extension .s1.yaml.\n`);return}let r=0,i=0;for(let t of n){let n=`${e}/${t}`,a=(0,m.statSync)(n);if(a.isFile()){let e=await $(n);e?r++:i++}}J.info(`Validation completed: ${r} valid, ${i} invalid connectors.\n`)}else t.isFile()&&e.endsWith(`s1.yaml`)?await $(e):J.error(`No StackOne connector found: ${e}. Connector files need to have the extension .s1.yaml.\n`)},$=async e=>{let n=(0,_.loadConnector)(e),r=(0,_.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let t=e.split(`/`).pop()||e;return J.success(`Connector ${t} is valid!\n`),!0}else if(i.length>0)return J.error(`Connector ${e} is not valid. Please fix the following errors:\n`),i.forEach(e=>{console.info(t.default.red(`- L${e.line}: ${e.message}`))}),console.info(`
|
|
139
|
+
`),!1;else return J.error(`Connector ${e} is not valid. Please check the file for errors.`),!1},fe=()=>{try{let e=(0,ee.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),t=(0,g.dirname)(e),n=(0,g.join)(t,`..`,`package.json`),r=JSON.parse((0,m.readFileSync)(n,`utf8`));return r.version}catch{return`unknown`}};var pe=class{constructor(e=new n.Command,t=fe()){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 le,r=new X,i=new de,a=new P,o=new B,s=new ie;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,n)=>{n(t.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 n.Argument(`<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(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new n.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{i.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`version`).description(`Show version information`).action(()=>{console.info(`${t.default.greenBright(`StackOne`)} ${t.default.grey(`CLI`)} ${t.default.whiteBright(this.version)}`),process.exit(0)});let c=this.program.command(`agent`).description(`StackOne agent commands`);c.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?a.execute():o.execute()}),c.command(`cleanup`).description(`Remove all API keys and credentials from configurations`).action(()=>{s.execute()})}run(){this.program.parse(process.argv)}};Object.defineProperty(exports,`CLI`,{enumerable:!0,get:function(){return pe}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./chunk-CUT6urMc.cjs`),t=e.__toESM(require(`fs`)),n=e.__toESM(require(`os`)),r=e.__toESM(require(`path`)),i=e.__toESM(require(`fs/promises`)),a=e.__toESM(require(`events`)),o=e.__toESM(require(`node:fs/promises`)),s=e.__toESM(require(`node:stream`)),c=e.__toESM(require(`node:path`)),l={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},u={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:l.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(u);const d=`READDIRP_RECURSIVE_ERROR`,f=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,d]),p=[l.DIR_TYPE,l.EVERYTHING_TYPE,l.FILE_DIR_TYPE,l.FILE_TYPE],ee=new Set([l.DIR_TYPE,l.EVERYTHING_TYPE,l.FILE_DIR_TYPE]),m=new Set([l.EVERYTHING_TYPE,l.FILE_DIR_TYPE,l.FILE_TYPE]),te=e=>f.has(e.code),ne=process.platform===`win32`,h=e=>!0,g=e=>{if(e===void 0)return h;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return h};var _=class extends s.Readable{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...u,...e},{root:n,type:r}=t;this._fileFilter=g(t.fileFilter),this._directoryFilter=g(t.directoryFilter);let i=t.lstat?o.lstat:o.stat;ne?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??u.depth,this._wantsDir=r?ee.has(r):!1,this._wantsFile=r?m.has(r):!1,this._wantsEverything=r===l.EVERYTHING_TYPE,this._root=(0,c.resolve)(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await(0,o.readdir)(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=(0,c.resolve)((0,c.join)(t,r));n={path:(0,c.relative)(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){te(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await(0,o.realpath)(t),n=await(0,o.lstat)(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===c.sep){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=d,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function v(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=l.FILE_DIR_TYPE),n&&(t.type=n),e){if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!p.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${p.join(`, `)}`)}else throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);return t.root=e,new _(t)}const re=`data`,y=`end`,ie=`close`,b=()=>{},x=process.platform,S=x===`win32`,C=x===`darwin`,w=x===`linux`,T=x===`freebsd`,E=(0,n.type)()===`OS400`,D={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},O=D,ae=`watch`,oe={lstat:i.lstat,stat:i.stat},k=`listeners`,A=`errHandlers`,j=`rawEmitters`,se=[k,A,j],ce=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),le=e=>ce.has(r.extname(e).slice(1).toLowerCase()),M=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},N=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},ue=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},P=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},F=e=>e instanceof Set?e.size===0:!e,I=new Map;function L(e,n,i,a,o){let s=(t,n)=>{i(e),o(t,n,{watchedPath:e}),n&&e!==n&&R(r.resolve(e,n),k,r.join(e,n))};try{return(0,t.watch)(e,{persistent:n.persistent},s)}catch(e){a(e);return}}const R=(e,t,n,r,i)=>{let a=I.get(e);a&&M(a[t],e=>{e(n,r,i)})},z=(e,t,n,r)=>{let{listener:a,errHandler:o,rawEmitter:s}=r,c=I.get(t),l;if(!n.persistent)return l=L(e,n,a,o,s),l?l.close.bind(l):void 0;if(c)N(c,k,a),N(c,A,o),N(c,j,s);else{if(l=L(e,n,R.bind(null,t,k),o,R.bind(null,t,j)),!l)return;l.on(O.ERROR,async n=>{let r=R.bind(null,t,A);if(c&&(c.watcherUnusable=!0),S&&n.code===`EPERM`)try{let t=await(0,i.open)(e,`r`);await t.close(),r(n)}catch{}else r(n)}),c={listeners:a,errHandlers:o,rawEmitters:s,watcher:l},I.set(t,c)}return()=>{P(c,k,a),P(c,A,o),P(c,j,s),F(c.listeners)&&(c.watcher.close(),I.delete(t),se.forEach(ue(c)),c.watcher=void 0,Object.freeze(c))}},B=new Map,V=(e,n,r,i)=>{let{listener:a,rawEmitter:o}=i,s=B.get(n),c=s&&s.options;return c&&(c.persistent<r.persistent||c.interval>r.interval)&&((0,t.unwatchFile)(n),s=void 0),s?(N(s,k,a),N(s,j,o)):(s={listeners:a,rawEmitters:o,options:r,watcher:(0,t.watchFile)(n,r,(t,r)=>{M(s.rawEmitters,e=>{e(O.CHANGE,n,{curr:t,prev:r})});let i=t.mtimeMs;(t.size!==r.size||i>r.mtimeMs||i===0)&&M(s.listeners,n=>n(e,t))})},B.set(n,s)),()=>{P(s,k,a),P(s,j,o),F(s.listeners)&&(B.delete(n),(0,t.unwatchFile)(n),s.options=s.watcher=void 0,Object.freeze(s))}};var H=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=r.dirname(e),a=r.basename(e),o=this.fsw._getWatchedDir(i);o.add(a);let s=r.resolve(e),c={persistent:n.persistent};t||=b;let l;if(n.usePolling){let r=n.interval!==n.binaryInterval;c.interval=r&&le(a)?n.binaryInterval:n.interval,l=V(e,s,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=z(e,s,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let a=r.dirname(e),o=r.basename(e),s=this.fsw._getWatchedDir(a),c=t;if(s.has(o))return;let l=async(t,n)=>{if(this.fsw._throttle(ae,e,5)){if(!n||n.mtimeMs===0)try{let n=await(0,i.stat)(e);if(this.fsw.closed)return;let r=n.atimeMs,a=n.mtimeMs;if((!r||r<=a||a!==c.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),(C||w||T)&&c.ino!==n.ino){this.fsw._closeFile(t),c=n;let r=this._watchWithNodeFs(e,l);r&&this.fsw._addPathCloser(t,r)}else c=n}catch{this.fsw._remove(a,o)}else if(s.has(o)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==c.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),c=n}}},u=this._watchWithNodeFs(e,l);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(O.ADD,e,0))return;this.fsw._emit(O.ADD,e,t)}return u}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let a=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await(0,i.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(a)!==t&&(this.fsw._symlinkPaths.set(a,t),this.fsw._emit(O.CHANGE,n,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(a,t),this.fsw._emit(O.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(a))return!0;this.fsw._symlinkPaths.set(a,!0)}_handleRead(e,t,n,i,a,o,s){if(e=r.join(e,``),s=this.fsw._throttle(`readdir`,e,1e3),!s)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(re,async s=>{if(this.fsw.closed){u=void 0;return}let d=s.path,f=r.join(e,d);if(l.add(d),!(s.stats.isSymbolicLink()&&await this._handleSymlink(s,e,f,d))){if(this.fsw.closed){u=void 0;return}(d===i||!i&&!c.has(d))&&(this.fsw._incrReadyCount(),f=r.join(a,r.relative(a,f)),this._addToNodeFs(f,t,n,o+1))}}).on(O.ERROR,this._boundHandleError),new Promise((t,r)=>{if(!u)return r();u.once(y,()=>{if(this.fsw.closed){u=void 0;return}let r=s?s.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,r&&this._handleRead(e,!1,n,i,a,o,s)})})}async _handleDir(e,t,n,i,a,o,s){let c=this.fsw._getWatchedDir(r.dirname(e)),l=c.has(r.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!a&&!l&&this.fsw._emit(O.ADD_DIR,e,t),c.add(r.basename(e)),this.fsw._getWatchedDir(e);let u,d,f=this.fsw.options.depth;if((f==null||i<=f)&&!this.fsw._symlinkPaths.has(s)){if(!a&&(await this._handleRead(e,n,o,a,e,i,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,o,a,e,i,u)})}return d}async _addToNodeFs(e,t,n,a,o){let s=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return s(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=e=>n.filterPath(e),c.filterDir=e=>n.filterDir(e));try{let n=await oe[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,n))return s(),!1;let l=this.fsw.options.followSymlinks,u;if(n.isDirectory()){let s=r.resolve(e),d=l?await(0,i.realpath)(e):e;if(this.fsw.closed||(u=await this._handleDir(c.watchPath,n,t,a,o,c,d),this.fsw.closed))return;s!==d&&d!==void 0&&this.fsw._symlinkPaths.set(s,d)}else if(n.isSymbolicLink()){let o=l?await(0,i.realpath)(e):e;if(this.fsw.closed)return;let s=r.dirname(c.watchPath);if(this.fsw._getWatchedDir(s).add(c.watchPath),this.fsw._emit(O.ADD,c.watchPath,n),u=await this._handleDir(s,n,t,a,e,c,o),this.fsw.closed)return;o!==void 0&&this.fsw._symlinkPaths.set(r.resolve(e),o)}else u=this._handleFile(c.watchPath,n,t);return s(),u&&this.fsw._addPathCloser(e,u),!1}catch(t){if(this.fsw._handleError(t))return s(),e}}};const U=`/`,de=`//`,W=`.`,fe=`..`,pe=`string`,me=/\\/g,G=/\/\//,he=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ge=/^\.[/\\]/;function K(e){return Array.isArray(e)?e:[e]}const q=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function _e(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=r.relative(e.path,t);return n?!n.startsWith(`..`)&&!r.isAbsolute(n):!1}return!1}:()=>!1}function ve(e){if(typeof e!=`string`)throw Error(`string expected`);e=r.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function J(e,t,n){let r=ve(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function ye(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=K(e),r=n.map(e=>_e(e));return t==null?(e,t)=>J(r,e,t):J(r,t)}const Y=e=>{let t=K(e).flat();if(!t.every(e=>typeof e===pe))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Z)},X=e=>{let t=e.replace(me,U),n=!1;for(t.startsWith(de)&&(n=!0);t.match(G);)t=t.replace(G,U);return n&&(t=U+t),t},Z=e=>X(r.normalize(X(e))),Q=(e=``)=>t=>typeof t==`string`?Z(r.isAbsolute(t)?t:r.join(e,t)):t,be=(e,t)=>r.isAbsolute(e)?e:r.join(t,e),xe=Object.freeze(new Set);var Se=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==W&&e!==fe&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,i.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(r.dirname(n),r.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=b,this.items=xe,Object.freeze(this)}};const Ce=`stat`,$=`lstat`;var we=class{constructor(e,t,n){this.fsw=n;let i=e;this.path=e=e.replace(ge,``),this.watchPath=i,this.fullWatchPath=r.resolve(i),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?Ce:$}entryPath(e){return r.join(this.watchPath,r.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Te=class extends a.EventEmitter{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?K(e.ignored):K([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};E&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=b,this._readyEmitted=!0,process.nextTick(()=>this.emit(D.READY)))},this._emitRaw=(...e)=>this.emit(D.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new H(this),Object.freeze(r)}_addIgnoredPath(e){if(q(e)){for(let t of this._ignoredPaths)if(q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:i}=this.options;this.closed=!1,this._closePromise=void 0;let a=Y(e);return i&&(a=a.map(e=>{let t=be(e,i);return t})),a.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=a.length,Promise.all(a.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(r.dirname(e),r.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Y(e),{cwd:n}=this.options;return t.forEach(e=>{!r.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=r.join(n,e)),e=r.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=this.options.cwd?r.relative(this.options.cwd,n):n,a=i||W;e[a]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==D.ERROR&&this.emit(D.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let a=this.options;S&&(t=r.normalize(t)),a.cwd&&(t=r.relative(a.cwd,t));let o=[t];n!=null&&o.push(n);let s=a.awaitWriteFinish,c;if(s&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(a.atomic){if(e===D.UNLINK)return this._pendingUnlinks.set(t,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(D.ALL,...e),this._pendingUnlinks.delete(t)})},typeof a.atomic==`number`?a.atomic:100),this;e===D.ADD&&this._pendingUnlinks.has(t)&&(e=D.CHANGE,this._pendingUnlinks.delete(t))}if(s&&(e===D.ADD||e===D.CHANGE)&&this._readyEmitted){let n=(t,n)=>{t?(e=D.ERROR,o[0]=t,this.emitWithAll(e,o)):n&&(o.length>1?o[1]=n:o.push(n),this.emitWithAll(e,o))};return this._awaitWriteFinish(t,s.stabilityThreshold,e,n),this}if(e===D.CHANGE){let e=!this._throttle(D.CHANGE,t,50);if(e)return this}if(a.alwaysStat&&n===void 0&&(e===D.ADD||e===D.ADD_DIR||e===D.CHANGE)){let e=a.cwd?r.join(a.cwd,t):t,n;try{n=await(0,i.stat)(e)}catch{}if(!n||this.closed)return;o.push(n)}return this.emitWithAll(e,o),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(D.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,i,a){let o=this.options.awaitWriteFinish;if(typeof o!=`object`)return;let s=o.pollInterval,c,l=e;this.options.cwd&&!r.isAbsolute(e)&&(l=r.join(this.options.cwd,e));let u=new Date,d=this._pendingWrites;function f(r){(0,t.stat)(l,(t,i)=>{if(t||!d.has(e)){t&&t.code!==`ENOENT`&&a(t);return}let o=Number(new Date);r&&i.size!==r.size&&(d.get(e).lastChange=o);let l=d.get(e),u=o-l.lastChange;u>=n?(d.delete(e),a(void 0,i)):c=setTimeout(f,s,i)})}d.has(e)||(d.set(e,{lastChange:u,cancelWait:()=>(d.delete(e),clearTimeout(c),i)}),c=setTimeout(f,s))}_isIgnored(e,t){if(this.options.atomic&&he.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=this.options.ignored,n=(t||[]).map(Q(e)),r=[...this._ignoredPaths],i=[...r.map(Q(e)),...n];this._userIgnored=ye(i,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new we(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=r.resolve(e);return this._watched.has(t)||this._watched.set(t,new Se(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let i=r.join(e,t),a=r.resolve(i);if(n??=this._watched.has(i)||this._watched.has(a),!this._throttle(`remove`,i,100))return;!n&&this._watched.size===1&&this.add(e,t,!0);let o=this._getWatchedDir(i),s=o.getChildren();s.forEach(e=>this._remove(i,e));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(a)&&this._symlinkPaths.delete(a);let u=i;if(this.options.cwd&&(u=r.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)){let e=this._pendingWrites.get(u).cancelWait();if(e===D.ADD)return}this._watched.delete(i),this._watched.delete(a);let d=n?D.UNLINK_DIR:D.UNLINK;l&&!this._isIgnored(i)&&this._emit(d,i),this._closePath(i)}_closePath(e){this._closeFile(e);let t=r.dirname(e);this._getWatchedDir(t).remove(r.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:D.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=v(e,n);return this._streams.add(r),r.once(ie,()=>{r=void 0}),r.once(y,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ee(e,t={}){let n=new Te(t);return n.add(e),n}exports.watch=Ee;
|
|
1
|
+
const e=require(`./chunk-CUT6urMc.cjs`),t=e.__toESM(require(`node:fs/promises`)),n=e.__toESM(require(`node:path`)),r=e.__toESM(require(`fs`)),i=e.__toESM(require(`os`)),a=e.__toESM(require(`path`)),o=e.__toESM(require(`fs/promises`)),s=e.__toESM(require(`events`)),c=e.__toESM(require(`node:stream`)),l={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},u={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:l.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(u);const d=`READDIRP_RECURSIVE_ERROR`,f=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,d]),p=[l.DIR_TYPE,l.EVERYTHING_TYPE,l.FILE_DIR_TYPE,l.FILE_TYPE],ee=new Set([l.DIR_TYPE,l.EVERYTHING_TYPE,l.FILE_DIR_TYPE]),m=new Set([l.EVERYTHING_TYPE,l.FILE_DIR_TYPE,l.FILE_TYPE]),te=e=>f.has(e.code),ne=process.platform===`win32`,h=e=>!0,g=e=>{if(e===void 0)return h;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return h};var _=class extends c.Readable{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let r={...u,...e},{root:i,type:a}=r;this._fileFilter=g(r.fileFilter),this._directoryFilter=g(r.directoryFilter);let o=r.lstat?t.lstat:t.stat;ne?this._stat=e=>o(e,{bigint:!0}):this._stat=o,this._maxDepth=r.depth??u.depth,this._wantsDir=a?ee.has(a):!1,this._wantsFile=a?m.has(a):!1,this._wantsEverything=a===l.EVERYTHING_TYPE,this._root=(0,n.resolve)(i),this._isDirent=!r.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await(0,t.readdir)(e,this._rdOptions)}catch(e){this._onError(e)}return{files:r,depth:n,path:e}}async _formatEntry(e,t){let r,i=this._isDirent?e.name:e;try{let a=(0,n.resolve)((0,n.join)(t,i));r={path:(0,n.relative)(this._root,a),fullPath:a,basename:i},r[this._statsProp]=this._isDirent?e:await this._stat(a)}catch(e){this._onError(e);return}return r}_onError(e){te(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let r=e[this._statsProp];if(r.isFile())return`file`;if(r.isDirectory())return`directory`;if(r&&r.isSymbolicLink()){let r=e.fullPath;try{let e=await(0,t.realpath)(r),i=await(0,t.lstat)(e);if(i.isFile())return`file`;if(i.isDirectory()){let t=e.length;if(r.startsWith(e)&&r.substr(t,1)===n.sep){let t=Error(`Circular symlink detected: "${r}" points to "${e}"`);return t.code=d,this._onError(t)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function v(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=l.FILE_DIR_TYPE),n&&(t.type=n),e){if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!p.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${p.join(`, `)}`)}else throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);return t.root=e,new _(t)}const re=`data`,y=`end`,ie=`close`,b=()=>{},x=process.platform,S=x===`win32`,C=x===`darwin`,w=x===`linux`,T=x===`freebsd`,E=(0,i.type)()===`OS400`,D={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},O=D,ae=`watch`,oe={lstat:o.lstat,stat:o.stat},k=`listeners`,A=`errHandlers`,j=`rawEmitters`,se=[k,A,j],ce=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),le=e=>ce.has(a.extname(e).slice(1).toLowerCase()),M=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},N=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},ue=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},P=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},F=e=>e instanceof Set?e.size===0:!e,I=new Map;function L(e,t,n,i,o){let s=(t,r)=>{n(e),o(t,r,{watchedPath:e}),r&&e!==r&&R(a.resolve(e,r),k,a.join(e,r))};try{return(0,r.watch)(e,{persistent:t.persistent},s)}catch(e){i(e);return}}const R=(e,t,n,r,i)=>{let a=I.get(e);a&&M(a[t],e=>{e(n,r,i)})},z=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:s}=r,c=I.get(t),l;if(!n.persistent)return l=L(e,n,i,a,s),l?l.close.bind(l):void 0;if(c)N(c,k,i),N(c,A,a),N(c,j,s);else{if(l=L(e,n,R.bind(null,t,k),a,R.bind(null,t,j)),!l)return;l.on(O.ERROR,async n=>{let r=R.bind(null,t,A);if(c&&(c.watcherUnusable=!0),S&&n.code===`EPERM`)try{let t=await(0,o.open)(e,`r`);await t.close(),r(n)}catch{}else r(n)}),c={listeners:i,errHandlers:a,rawEmitters:s,watcher:l},I.set(t,c)}return()=>{P(c,k,i),P(c,A,a),P(c,j,s),F(c.listeners)&&(c.watcher.close(),I.delete(t),se.forEach(ue(c)),c.watcher=void 0,Object.freeze(c))}},B=new Map,V=(e,t,n,i)=>{let{listener:a,rawEmitter:o}=i,s=B.get(t),c=s&&s.options;return c&&(c.persistent<n.persistent||c.interval>n.interval)&&((0,r.unwatchFile)(t),s=void 0),s?(N(s,k,a),N(s,j,o)):(s={listeners:a,rawEmitters:o,options:n,watcher:(0,r.watchFile)(t,n,(n,r)=>{M(s.rawEmitters,e=>{e(O.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&M(s.listeners,t=>t(e,n))})},B.set(t,s)),()=>{P(s,k,a),P(s,j,o),F(s.listeners)&&(B.delete(t),(0,r.unwatchFile)(t),s.options=s.watcher=void 0,Object.freeze(s))}};var H=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=a.dirname(e),i=a.basename(e),o=this.fsw._getWatchedDir(r);o.add(i);let s=a.resolve(e),c={persistent:n.persistent};t||=b;let l;if(n.usePolling){let r=n.interval!==n.binaryInterval;c.interval=r&&le(i)?n.binaryInterval:n.interval,l=V(e,s,c,{listener:t,rawEmitter:this.fsw._emitRaw})}else l=z(e,s,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(e,t,n){if(this.fsw.closed)return;let r=a.dirname(e),i=a.basename(e),s=this.fsw._getWatchedDir(r),c=t;if(s.has(i))return;let l=async(t,n)=>{if(this.fsw._throttle(ae,e,5)){if(!n||n.mtimeMs===0)try{let n=await(0,o.stat)(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==c.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),(C||w||T)&&c.ino!==n.ino){this.fsw._closeFile(t),c=n;let r=this._watchWithNodeFs(e,l);r&&this.fsw._addPathCloser(t,r)}else c=n}catch{this.fsw._remove(r,i)}else if(s.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==c.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),c=n}}},u=this._watchWithNodeFs(e,l);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(O.ADD,e,0))return;this.fsw._emit(O.ADD,e,t)}return u}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await(0,o.realpath)(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(O.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(O.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,o,s){if(e=a.join(e,``),s=this.fsw._throttle(`readdir`,e,1e3),!s)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(re,async s=>{if(this.fsw.closed){u=void 0;return}let d=s.path,f=a.join(e,d);if(l.add(d),!(s.stats.isSymbolicLink()&&await this._handleSymlink(s,e,f,d))){if(this.fsw.closed){u=void 0;return}(d===r||!r&&!c.has(d))&&(this.fsw._incrReadyCount(),f=a.join(i,a.relative(i,f)),this._addToNodeFs(f,t,n,o+1))}}).on(O.ERROR,this._boundHandleError),new Promise((t,a)=>{if(!u)return a();u.once(y,()=>{if(this.fsw.closed){u=void 0;return}let a=s?s.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,a&&this._handleRead(e,!1,n,r,i,o,s)})})}async _handleDir(e,t,n,r,i,o,s){let c=this.fsw._getWatchedDir(a.dirname(e)),l=c.has(a.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(O.ADD_DIR,e,t),c.add(a.basename(e)),this.fsw._getWatchedDir(e);let u,d,f=this.fsw.options.depth;if((f==null||r<=f)&&!this.fsw._symlinkPaths.has(s)){if(!i&&(await this._handleRead(e,n,o,i,e,r,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,o,i,e,r,u)})}return d}async _addToNodeFs(e,t,n,r,i){let s=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return s(),!1;let c=this.fsw._getWatchHelpers(e);n&&(c.filterPath=e=>n.filterPath(e),c.filterDir=e=>n.filterDir(e));try{let n=await oe[c.statMethod](c.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(c.watchPath,n))return s(),!1;let l=this.fsw.options.followSymlinks,u;if(n.isDirectory()){let s=a.resolve(e),d=l?await(0,o.realpath)(e):e;if(this.fsw.closed||(u=await this._handleDir(c.watchPath,n,t,r,i,c,d),this.fsw.closed))return;s!==d&&d!==void 0&&this.fsw._symlinkPaths.set(s,d)}else if(n.isSymbolicLink()){let i=l?await(0,o.realpath)(e):e;if(this.fsw.closed)return;let s=a.dirname(c.watchPath);if(this.fsw._getWatchedDir(s).add(c.watchPath),this.fsw._emit(O.ADD,c.watchPath,n),u=await this._handleDir(s,n,t,r,e,c,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(a.resolve(e),i)}else u=this._handleFile(c.watchPath,n,t);return s(),u&&this.fsw._addPathCloser(e,u),!1}catch(t){if(this.fsw._handleError(t))return s(),e}}};const U=`/`,de=`//`,W=`.`,fe=`..`,pe=`string`,me=/\\/g,G=/\/\//,he=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,ge=/^\.[/\\]/;function K(e){return Array.isArray(e)?e:[e]}const q=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function _e(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=a.relative(e.path,t);return n?!n.startsWith(`..`)&&!a.isAbsolute(n):!1}return!1}:()=>!1}function ve(e){if(typeof e!=`string`)throw Error(`string expected`);e=a.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function J(e,t,n){let r=ve(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function ye(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=K(e),r=n.map(e=>_e(e));return t==null?(e,t)=>J(r,e,t):J(r,t)}const Y=e=>{let t=K(e).flat();if(!t.every(e=>typeof e===pe))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Z)},X=e=>{let t=e.replace(me,U),n=!1;for(t.startsWith(de)&&(n=!0);t.match(G);)t=t.replace(G,U);return n&&(t=U+t),t},Z=e=>X(a.normalize(X(e))),Q=(e=``)=>t=>typeof t==`string`?Z(a.isAbsolute(t)?t:a.join(e,t)):t,be=(e,t)=>a.isAbsolute(e)?e:a.join(t,e),xe=Object.freeze(new Set);var Se=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==W&&e!==fe&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await(0,o.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(a.dirname(n),a.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=b,this.items=xe,Object.freeze(this)}};const Ce=`stat`,$=`lstat`;var we=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(ge,``),this.watchPath=r,this.fullWatchPath=a.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?Ce:$}entryPath(e){return a.join(this.watchPath,a.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Te=class extends s.EventEmitter{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?K(e.ignored):K([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};E&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=b,this._readyEmitted=!0,process.nextTick(()=>this.emit(D.READY)))},this._emitRaw=(...e)=>this.emit(D.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new H(this),Object.freeze(r)}_addIgnoredPath(e){if(q(e)){for(let t of this._ignoredPaths)if(q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Y(e);return r&&(i=i.map(e=>{let t=be(e,r);return t})),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(a.dirname(e),a.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Y(e),{cwd:n}=this.options;return t.forEach(e=>{!a.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=a.join(n,e)),e=a.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=this.options.cwd?a.relative(this.options.cwd,n):n,i=r||W;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==D.ERROR&&this.emit(D.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;S&&(t=a.normalize(t)),r.cwd&&(t=a.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let s=r.awaitWriteFinish,c;if(s&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(r.atomic){if(e===D.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(D.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===D.ADD&&this._pendingUnlinks.has(t)&&(e=D.CHANGE,this._pendingUnlinks.delete(t))}if(s&&(e===D.ADD||e===D.CHANGE)&&this._readyEmitted){let n=(t,n)=>{t?(e=D.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,s.stabilityThreshold,e,n),this}if(e===D.CHANGE){let e=!this._throttle(D.CHANGE,t,50);if(e)return this}if(r.alwaysStat&&n===void 0&&(e===D.ADD||e===D.ADD_DIR||e===D.CHANGE)){let e=r.cwd?a.join(r.cwd,t):t,n;try{n=await(0,o.stat)(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(D.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){let o=this.options.awaitWriteFinish;if(typeof o!=`object`)return;let s=o.pollInterval,c,l=e;this.options.cwd&&!a.isAbsolute(e)&&(l=a.join(this.options.cwd,e));let u=new Date,d=this._pendingWrites;function f(n){(0,r.stat)(l,(r,a)=>{if(r||!d.has(e)){r&&r.code!==`ENOENT`&&i(r);return}let o=Number(new Date);n&&a.size!==n.size&&(d.get(e).lastChange=o);let l=d.get(e),u=o-l.lastChange;u>=t?(d.delete(e),i(void 0,a)):c=setTimeout(f,s,a)})}d.has(e)||(d.set(e,{lastChange:u,cancelWait:()=>(d.delete(e),clearTimeout(c),n)}),c=setTimeout(f,s))}_isIgnored(e,t){if(this.options.atomic&&he.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=this.options.ignored,n=(t||[]).map(Q(e)),r=[...this._ignoredPaths],i=[...r.map(Q(e)),...n];this._userIgnored=ye(i,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new we(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=a.resolve(e);return this._watched.has(t)||this._watched.set(t,new Se(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=a.join(e,t),i=a.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0);let o=this._getWatchedDir(r),s=o.getChildren();s.forEach(e=>this._remove(r,e));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let u=r;if(this.options.cwd&&(u=a.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)){let e=this._pendingWrites.get(u).cancelWait();if(e===D.ADD)return}this._watched.delete(r),this._watched.delete(i);let d=n?D.UNLINK_DIR:D.UNLINK;l&&!this._isIgnored(r)&&this._emit(d,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=a.dirname(e);this._getWatchedDir(t).remove(a.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:D.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=v(e,n);return this._streams.add(r),r.once(ie,()=>{r=void 0}),r.once(y,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Ee(e,t={}){let n=new Te(t);return n.add(e),n}exports.watch=Ee;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lstat as e,readdir as t,realpath as n,stat as r}from"node:fs/promises";import{join as i,relative as a,resolve as o,sep as s}from"node:path";import{stat as c,unwatchFile as l,watch as u,watchFile as d}from"fs";import{type as f}from"os";import*as p from"path";import{lstat as ee,open as te,readdir as ne,realpath as m,stat as h}from"fs/promises";import{EventEmitter as re}from"events";import{Readable as g}from"node:stream";const _={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},v={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:_.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(v);const y=`READDIRP_RECURSIVE_ERROR`,ie=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,y]),b=[_.DIR_TYPE,_.EVERYTHING_TYPE,_.FILE_DIR_TYPE,_.FILE_TYPE],ae=new Set([_.DIR_TYPE,_.EVERYTHING_TYPE,_.FILE_DIR_TYPE]),oe=new Set([_.EVERYTHING_TYPE,_.FILE_DIR_TYPE,_.FILE_TYPE]),se=e=>ie.has(e.code),ce=process.platform===`win32`,x=e=>!0,S=e=>{if(e===void 0)return x;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return x};var le=class extends g{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let n={...v,...t},{root:i,type:a}=n;this._fileFilter=S(n.fileFilter),this._directoryFilter=S(n.directoryFilter);let s=n.lstat?e:r;ce?this._stat=e=>s(e,{bigint:!0}):this._stat=s,this._maxDepth=n.depth??v.depth,this._wantsDir=a?ae.has(a):!1,this._wantsFile=a?oe.has(a):!1,this._wantsEverything=a===_.EVERYTHING_TYPE,this._root=o(i),this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await t(e,this._rdOptions)}catch(e){this._onError(e)}return{files:r,depth:n,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let s=o(i(t,r));n={path:a(this._root,s),fullPath:s,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(e){this._onError(e);return}return n}_onError(e){se(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(t){if(!t&&this._statsProp in t)return``;let r=t[this._statsProp];if(r.isFile())return`file`;if(r.isDirectory())return`directory`;if(r&&r.isSymbolicLink()){let r=t.fullPath;try{let t=await n(r),i=await e(t);if(i.isFile())return`file`;if(i.isDirectory()){let e=t.length;if(r.startsWith(t)&&r.substr(e,1)===s){let e=Error(`Circular symlink detected: "${r}" points to "${t}"`);return e.code=y,this._onError(e)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function ue(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=_.FILE_DIR_TYPE),n&&(t.type=n),e){if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!b.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${b.join(`, `)}`)}else throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);return t.root=e,new le(t)}const de=`data`,C=`end`,fe=`close`,w=()=>{},T=process.platform,E=T===`win32`,pe=T===`darwin`,me=T===`linux`,he=T===`freebsd`,ge=f()===`OS400`,D={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},O=D,_e=`watch`,ve={lstat:ee,stat:h},k=`listeners`,A=`errHandlers`,j=`rawEmitters`,M=[k,A,j],N=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),P=e=>N.has(p.extname(e).slice(1).toLowerCase()),F=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},I=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},ye=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},L=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},R=e=>e instanceof Set?e.size===0:!e,z=new Map;function B(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&V(p.resolve(e,r),k,p.join(e,r))};try{return u(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const V=(e,t,n,r,i)=>{let a=z.get(e);a&&F(a[t],e=>{e(n,r,i)})},H=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=z.get(t),c;if(!n.persistent)return c=B(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)I(s,k,i),I(s,A,a),I(s,j,o);else{if(c=B(e,n,V.bind(null,t,k),a,V.bind(null,t,j)),!c)return;c.on(O.ERROR,async n=>{let r=V.bind(null,t,A);if(s&&(s.watcherUnusable=!0),E&&n.code===`EPERM`)try{let t=await te(e,`r`);await t.close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},z.set(t,s)}return()=>{L(s,k,i),L(s,A,a),L(s,j,o),R(s.listeners)&&(s.watcher.close(),z.delete(t),M.forEach(ye(s)),s.watcher=void 0,Object.freeze(s))}},U=new Map,be=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=U.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(l(t),o=void 0),o?(I(o,k,i),I(o,j,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:d(t,n,(n,r)=>{F(o.rawEmitters,e=>{e(O.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&F(o.listeners,t=>t(e,n))})},U.set(t,o)),()=>{L(o,k,i),L(o,j,a),R(o.listeners)&&(U.delete(t),l(t),o.options=o.watcher=void 0,Object.freeze(o))}};var xe=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=p.dirname(e),i=p.basename(e),a=this.fsw._getWatchedDir(r);a.add(i);let o=p.resolve(e),s={persistent:n.persistent};t||=w;let c;if(n.usePolling){let r=n.interval!==n.binaryInterval;s.interval=r&&P(i)?n.binaryInterval:n.interval,c=be(e,o,s,{listener:t,rawEmitter:this.fsw._emitRaw})}else c=H(e,o,s,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return c}_handleFile(e,t,n){if(this.fsw.closed)return;let r=p.dirname(e),i=p.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(_e,e,5)){if(!n||n.mtimeMs===0)try{let n=await h(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),(pe||me||he)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(O.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(O.ADD,e,0))return;this.fsw._emit(O.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await m(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(O.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(O.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=p.join(e,``),o=this.fsw._throttle(`readdir`,e,1e3),!o)return;let s=this.fsw._getWatchedDir(n.path),c=new Set,l=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(l)return l.on(de,async o=>{if(this.fsw.closed){l=void 0;return}let u=o.path,d=p.join(e,u);if(c.add(u),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,u))){if(this.fsw.closed){l=void 0;return}(u===r||!r&&!s.has(u))&&(this.fsw._incrReadyCount(),d=p.join(i,p.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(O.ERROR,this._boundHandleError),new Promise((t,u)=>{if(!l)return u();l.once(C,()=>{if(this.fsw.closed){l=void 0;return}let u=o?o.clear():!1;t(void 0),s.getChildren().filter(t=>t!==e&&!c.has(t)).forEach(t=>{this.fsw._remove(e,t)}),l=void 0,u&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(p.dirname(e)),c=s.has(p.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(O.ADD_DIR,e,t),s.add(p.basename(e)),this.fsw._getWatchedDir(e);let l,u,d=this.fsw.options.depth;if((d==null||r<=d)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,l),this.fsw.closed))return;u=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,l)})}return u}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await ve[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=p.resolve(e),l=s?await m(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await m(e):e;if(this.fsw.closed)return;let a=p.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(O.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(p.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};const W=`/`,Se=`//`,G=`.`,Ce=`..`,we=`string`,Te=/\\/g,K=/\/\//,Ee=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,De=/^\.[/\\]/;function q(e){return Array.isArray(e)?e:[e]}const J=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Oe(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=p.relative(e.path,t);return n?!n.startsWith(`..`)&&!p.isAbsolute(n):!1}return!1}:()=>!1}function ke(e){if(typeof e!=`string`)throw Error(`string expected`);e=p.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function Y(e,t,n){let r=ke(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Ae(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=q(e),r=n.map(e=>Oe(e));return t==null?(e,t)=>Y(r,e,t):Y(r,t)}const X=e=>{let t=q(e).flat();if(!t.every(e=>typeof e===we))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Q)},Z=e=>{let t=e.replace(Te,W),n=!1;for(t.startsWith(Se)&&(n=!0);t.match(K);)t=t.replace(K,W);return n&&(t=W+t),t},Q=e=>Z(p.normalize(Z(e))),$=(e=``)=>t=>typeof t==`string`?Q(p.isAbsolute(t)?t:p.join(e,t)):t,je=(e,t)=>p.isAbsolute(e)?e:p.join(t,e),Me=Object.freeze(new Set);var Ne=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==G&&e!==Ce&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await ne(n)}catch{this._removeWatcher&&this._removeWatcher(p.dirname(n),p.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=w,this.items=Me,Object.freeze(this)}};const Pe=`stat`,Fe=`lstat`;var Ie=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(De,``),this.watchPath=r,this.fullWatchPath=p.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?Pe:Fe}entryPath(e){return p.join(this.watchPath,p.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Le=class extends re{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?q(e.ignored):q([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};ge&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=w,this._readyEmitted=!0,process.nextTick(()=>this.emit(D.READY)))},this._emitRaw=(...e)=>this.emit(D.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new xe(this),Object.freeze(r)}_addIgnoredPath(e){if(J(e)){for(let t of this._ignoredPaths)if(J(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)J(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=X(e);return r&&(i=i.map(e=>{let t=je(e,r);return t})),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(p.dirname(e),p.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=X(e),{cwd:n}=this.options;return t.forEach(e=>{!p.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=p.join(n,e)),e=p.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=this.options.cwd?p.relative(this.options.cwd,n):n,i=r||G;e[i]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==D.ERROR&&this.emit(D.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;E&&(t=p.normalize(t)),r.cwd&&(t=p.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===D.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(D.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===D.ADD&&this._pendingUnlinks.has(t)&&(e=D.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===D.ADD||e===D.CHANGE)&&this._readyEmitted){let n=(t,n)=>{t?(e=D.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))};return this._awaitWriteFinish(t,a.stabilityThreshold,e,n),this}if(e===D.CHANGE){let e=!this._throttle(D.CHANGE,t,50);if(e)return this}if(r.alwaysStat&&n===void 0&&(e===D.ADD||e===D.ADD_DIR||e===D.CHANGE)){let e=r.cwd?p.join(r.cwd,t):t,n;try{n=await h(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(D.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!p.isAbsolute(e)&&(s=p.join(this.options.cwd,e));let l=new Date,u=this._pendingWrites;function d(n){c(s,(i,s)=>{if(i||!u.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(u.get(e).lastChange=c);let l=u.get(e),f=c-l.lastChange;f>=t?(u.delete(e),r(void 0,s)):o=setTimeout(d,a,s)})}u.has(e)||(u.set(e,{lastChange:l,cancelWait:()=>(u.delete(e),clearTimeout(o),n)}),o=setTimeout(d,a))}_isIgnored(e,t){if(this.options.atomic&&Ee.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=this.options.ignored,n=(t||[]).map($(e)),r=[...this._ignoredPaths],i=[...r.map($(e)),...n];this._userIgnored=Ae(i,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Ie(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=p.resolve(e);return this._watched.has(t)||this._watched.set(t,new Ne(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=p.join(e,t),i=p.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0);let a=this._getWatchedDir(r),o=a.getChildren();o.forEach(e=>this._remove(r,e));let s=this._getWatchedDir(e),c=s.has(t);s.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let l=r;if(this.options.cwd&&(l=p.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(l)){let e=this._pendingWrites.get(l).cancelWait();if(e===D.ADD)return}this._watched.delete(r),this._watched.delete(i);let u=n?D.UNLINK_DIR:D.UNLINK;c&&!this._isIgnored(r)&&this._emit(u,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=p.dirname(e);this._getWatchedDir(t).remove(p.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:D.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},r=ue(e,n);return this._streams.add(r),r.once(fe,()=>{r=void 0}),r.once(C,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};function Re(e,t={}){let n=new Le(t);return n.add(e),n}export{Re as watch};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`./cliCore-
|
|
1
|
+
const e=require(`./cliCore-BRPqDxQ9.cjs`);exports.CLI=e.CLI;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CLI as e}from"./cliCore-
|
|
1
|
+
import{CLI as e}from"./cliCore-57MzGvkG.js";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.9.1",
|
|
4
4
|
"description": "StackOne Connect CLI tool",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
},
|
|
12
12
|
"files": [
|
|
13
13
|
"dist",
|
|
14
|
+
"CLAUDE_TEMPLATE.md",
|
|
14
15
|
"package.json",
|
|
15
16
|
"README.md"
|
|
16
17
|
],
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
const e=require(`./chunk-CUT6urMc.cjs`),t=e.__toESM(require(`chalk`)),n=e.__toESM(require(`commander`)),r=e.__toESM(require(`inquirer`)),i=e.__toESM(require(`fs`)),a=e.__toESM(require(`os`)),o=e.__toESM(require(`path`)),s=e.__toESM(require(`@stackone/connect-sdk`)),c=e.__toESM(require(`ora`)),l=e.__toESM(require(`url`)),u=(0,o.join)((0,a.homedir)(),`.stackone`),d={profiles:{}},f=()=>{if(!(0,i.existsSync)(u))return d;try{let e=(0,i.readFileSync)(u,`utf-8`);return JSON.parse(e)}catch{return d}},p=e=>{let t=f();return t.profiles[e]},m=e=>{let t=f();return!!t.profiles[e]},h=(e,t)=>{let n=f();n.profiles[e]=t;let r=(0,o.join)((0,a.homedir)());(0,i.existsSync)(r)||(0,i.mkdirSync)(r,{recursive:!0}),(0,i.writeFileSync)(u,JSON.stringify(n,null,2),`utf-8`)},g=()=>{let e=f();return Object.keys(e.profiles)};var _=class{static info(e){console.info(t.default.blue(`โน`),e)}static warn(e){console.info(t.default.yellow(`โ `),e)}static error(e){console.info(t.default.red(`โ`),e)}static success(e){console.info(t.default.green(`โ`),e)}};const v=`https://api.stackone.com`,y=`https://api.stackone-dev.com`,b=`http://localhost:4000`;var x=class{async execute({environment:e}={}){let n=e?.toLowerCase()??`production`;try{let{label:e}=await r.default.prompt([{type:`input`,name:`label`,message:`Profile label:`,validate:e=>!e||e.trim().length===0?`The profile label is required`:e.includes(` `)?`The profile label cannot contain spaces`:!0}]);if(m(e)){let{overwrite:t}=await r.default.prompt([{type:`confirm`,name:`overwrite`,message:`Configuration profile with name "${e}" already exists. Do you want to overwrite it?`,default:!1}]);t||(_.info(`Configuration profile initialization cancelled`),process.exit(0))}let i;if(n===`production`)i=v;else if(n===`staging`)i=y;else{let{customUrl:e}=await r.default.prompt([{type:`input`,name:`customUrl`,message:`API URL:`,default:b,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{return new URL(e),!0}catch{return`Please enter a valid URL`}}}]);i=e}let{apiKey:a}=await r.default.prompt([{type:`password`,name:`apiKey`,message:`API Key:`,validate:e=>!e||e.trim().length===0?`API Key is required`:!0}]),o={label:e,environment:n,apiUrl:i,apiKey:a};h(e,o),console.info(t.default.green(`\nโ Configuration profile "${e}" saved successfully`)),process.exit(0)}catch(e){e.isTtyError?_.error(`Prompt couldn't be rendered in the current environment`):_.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const S=`https://api.stackone.com`;var C=class{async execute({profile:e,fileOrDir:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(_.error(`Please provide a profile or API key to use for pushing the connector.`),_.info(`You can provide these using the --profile and --api-key options.`),_.info(`Run "stackone init" to create a new configuration profile.`),process.exit(1)),e&&r&&(_.error(`Please provide either a profile or an API key, not both.`),process.exit(1)),e&&n&&_.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),e&&!m(e)){_.error(`Configuration profile "${e}" not found.`),_.info(`Run "stackone init" to create a new configuration profile.`);let t=g();_.info(`Available profiles: ${t.join(`, `)||`none`}`),process.exit(1)}let a=e?p(e):{apiUrl:n??S,apiKey:r};a||(_.error(`Failed to load configuration profile "${e}".`),process.exit(1)),a.apiKey||(_.error(`API key is missing. Please provide a valid API key in the profile or via the --api-key option.`),process.exit(1)),t||(_.error(`File or directory path is required.`),process.exit(1));try{(0,i.statSync)(t)}catch{_.error(`File or directory not found: ${t}`),process.exit(1)}let o=(0,i.statSync)(t),s=a.apiUrl??S;if(o.isDirectory()){let e=T(t),n=0;e.length===0?(_.error(`No .s1.yaml connector files found in the directory: ${t}.`),process.exit(1)):_.info(`Found ${e.length} connector(s) file(s). Processing...`);for(let t of e){console.info(`
|
|
2
|
-
`);let e=await this.uploadFile(t,s,a.apiKey);e&&n++}console.info(`
|
|
3
|
-
`),_.info(`Upload completed: ${n} of ${e.length} file(s) uploaded successfully.`),process.exit(n>0?0:1)}else t.endsWith(`.s1.yaml`)||(_.error(`Only .s1.yaml files are supported for upload.`),process.exit(1));let c=await this.uploadFile(t,s,a.apiKey);process.exit(c?0:1)}async uploadFile(e,n,r){try{console.info(t.default.blue(`๐ค Uploading ${(0,o.basename)(e)}...`));let i=w(e);if(!i)return!1;let a=(0,o.basename)(e),s=new FormData,c=new Blob([i],{type:`application/x-yaml`});s.append(`file`,c,a);let l=Buffer.from(r).toString(`base64`),u=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${l}`},body:s});if(!u.ok){let e=await u.text();return _.error(`Upload failed: ${u.status} - ${u.statusText}`),e&&console.error(t.default.red(e)),!1}let d=await u.json();return console.info(t.default.green(`โ Successfully uploaded ${a} with connector "${d.provider}@${d.version}"`)),!0}catch(e){return _.error(`Failed to upload file: ${e}`),!1}}};const w=e=>{let n=(0,s.loadConnector)(e),r=(0,s.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let t=e.split(`/`).pop()||e;return _.success(`Connector ${t} is valid!`),n}else i.length>0?(_.error(`Connector ${e} is not valid. Please fix the following errors:\n`),i.forEach(e=>{console.info(t.default.red(`- L${e.line}: ${e.message}`))})):_.error(`Connector ${e} is not valid. Please check the file for errors.`)},T=e=>{let t=[],n=(0,i.readdirSync)(e,{withFileTypes:!0});for(let r of n){let n=(0,o.join)(e,r.name);r.isDirectory()?t.push(...T(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t};var E=class{async execute(e){let{watchMode:n,fileOrDir:r}=e,a=(0,c.default)(`Watching for changes...`),o=()=>{console.clear(),console.info(t.default.yellow(`Watch mode enabled. Press "q" to quit.
|
|
4
|
-
`))};if(r){try{(0,i.statSync)(r)}catch{_.error(`File or directory not found: ${r}`),process.exit(1)}if(n){let{watch:e}=await Promise.resolve().then(()=>require(`./esm-BrK-ICga.cjs`)),n=await import(`readline`),i=n.createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{console.info(t.default.grey(`
|
|
5
|
-
|
|
6
|
-
Exiting watch mode...`)),c.close(),a.stop(),i.close(),process.exit(0)};o(),console.info(t.default.blue(`Running connector(s) validations...`)),await D(r),a.start();let c=e(r||`.`,{ignored:/(^|[/\\])\../,persistent:!0});c.on(`change`,async e=>{o(),a.stop(),console.info(t.default.blue(`File change detected. Running connector(s) validations...`)),await D(r),a.start()}),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else await D(r),process.exit(0)}}};const D=async e=>{let t=(0,i.statSync)(e);if(t.isDirectory()){let t=(0,i.readdirSync)(e),n=t.filter(e=>e.endsWith(`.s1.yaml`));if(n.length===0){_.error(`No StackOne connectors found in directory: ${e}. Connector files need to have the extension .s1.yaml.\n`);return}let r=0,a=0;for(let t of n){let n=`${e}/${t}`,o=(0,i.statSync)(n);if(o.isFile()){let e=await O(n);e?r++:a++}}_.info(`Validation completed: ${r} valid, ${a} invalid connectors.\n`)}else t.isFile()&&e.endsWith(`s1.yaml`)?await O(e):_.error(`No StackOne connector found: ${e}. Connector files need to have the extension .s1.yaml.\n`)},O=async e=>{let n=(0,s.loadConnector)(e),r=(0,s.validateYamlConnector)(n),i=r?.errors??[];if(r.success){let t=e.split(`/`).pop()||e;return _.success(`Connector ${t} is valid!\n`),!0}else if(i.length>0)return _.error(`Connector ${e} is not valid. Please fix the following errors:\n`),i.forEach(e=>{console.info(t.default.red(`- L${e.line}: ${e.message}`))}),console.info(`
|
|
7
|
-
`),!1;else return _.error(`Connector ${e} is not valid. Please check the file for errors.`),!1},k=()=>{try{let e=(0,l.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),t=(0,o.dirname)(e),n=(0,o.join)(t,`..`,`package.json`),r=JSON.parse((0,i.readFileSync)(n,`utf8`));return r.version}catch{return`unknown`}};var A=class{constructor(e=new n.Command,t=k()){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 x,r=new C,i=new E;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(e,n)=>{n(t.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 n.Argument(`<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(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new n.Argument(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{i.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`version`).description(`Show version information`).action(()=>{console.info(`${t.default.greenBright(`StackOne`)} ${t.default.grey(`CLI`)} ${t.default.whiteBright(this.version)}`),process.exit(0)})}run(){this.program.parse(process.argv)}};Object.defineProperty(exports,`CLI`,{enumerable:!0,get:function(){return A}});
|
package/dist/cliCore-CGA-wigN.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import e from"chalk";import{Argument as t,Command as n}from"commander";import r from"inquirer";import{existsSync as i,mkdirSync as a,readFileSync as o,readdirSync as s,statSync as c,writeFileSync as l}from"fs";import{homedir as u}from"os";import{basename as d,dirname as f,join as p}from"path";import{loadConnector as m,validateYamlConnector as h}from"@stackone/connect-sdk";import g from"ora";import{fileURLToPath as _}from"url";const v=p(u(),`.stackone`),y={profiles:{}},b=()=>{if(!i(v))return y;try{let e=o(v,`utf-8`);return JSON.parse(e)}catch{return y}},x=e=>{let t=b();return t.profiles[e]},S=e=>{let t=b();return!!t.profiles[e]},C=(e,t)=>{let n=b();n.profiles[e]=t;let r=p(u());i(r)||a(r,{recursive:!0}),l(v,JSON.stringify(n,null,2),`utf-8`)},w=()=>{let e=b();return Object.keys(e.profiles)};var T=class{static info(t){console.info(e.blue(`โน`),t)}static warn(t){console.info(e.yellow(`โ `),t)}static error(t){console.info(e.red(`โ`),t)}static success(t){console.info(e.green(`โ`),t)}};const E=`https://api.stackone.com`,D=`https://api.stackone-dev.com`,O=`http://localhost:4000`;var k=class{async execute({environment:t}={}){let n=t?.toLowerCase()??`production`;try{let{label:t}=await r.prompt([{type:`input`,name:`label`,message:`Profile label:`,validate:e=>!e||e.trim().length===0?`The profile label is required`:e.includes(` `)?`The profile label cannot contain spaces`:!0}]);if(S(t)){let{overwrite:e}=await r.prompt([{type:`confirm`,name:`overwrite`,message:`Configuration profile with name "${t}" already exists. Do you want to overwrite it?`,default:!1}]);e||(T.info(`Configuration profile initialization cancelled`),process.exit(0))}let i;if(n===`production`)i=E;else if(n===`staging`)i=D;else{let{customUrl:e}=await r.prompt([{type:`input`,name:`customUrl`,message:`API URL:`,default:O,validate:e=>{if(!e||e.trim().length===0)return`API URL is required`;try{return new URL(e),!0}catch{return`Please enter a valid URL`}}}]);i=e}let{apiKey:a}=await r.prompt([{type:`password`,name:`apiKey`,message:`API Key:`,validate:e=>!e||e.trim().length===0?`API Key is required`:!0}]),o={label:t,environment:n,apiUrl:i,apiKey:a};C(t,o),console.info(e.green(`\nโ Configuration profile "${t}" saved successfully`)),process.exit(0)}catch(e){e.isTtyError?T.error(`Prompt couldn't be rendered in the current environment`):T.error(`Failed to initialize configuration profile: ${e}`),process.exit(1)}}};const A=`https://api.stackone.com`;var j=class{async execute({profile:e,fileOrDir:t,apiUrl:n,apiKey:r}={}){if(!e&&!r&&(T.error(`Please provide a profile or API key to use for pushing the connector.`),T.info(`You can provide these using the --profile and --api-key options.`),T.info(`Run "stackone init" to create a new configuration profile.`),process.exit(1)),e&&r&&(T.error(`Please provide either a profile or an API key, not both.`),process.exit(1)),e&&n&&T.warn(`Specifying --api-url with a profile won't have any effect. Using API url from profile.`),e&&!S(e)){T.error(`Configuration profile "${e}" not found.`),T.info(`Run "stackone init" to create a new configuration profile.`);let t=w();T.info(`Available profiles: ${t.join(`, `)||`none`}`),process.exit(1)}let i=e?x(e):{apiUrl:n??A,apiKey:r};i||(T.error(`Failed to load configuration profile "${e}".`),process.exit(1)),i.apiKey||(T.error(`API key is missing. Please provide a valid API key in the profile or via the --api-key option.`),process.exit(1)),t||(T.error(`File or directory path is required.`),process.exit(1));try{c(t)}catch{T.error(`File or directory not found: ${t}`),process.exit(1)}let a=c(t),o=i.apiUrl??A;if(a.isDirectory()){let e=N(t),n=0;e.length===0?(T.error(`No .s1.yaml connector files found in the directory: ${t}.`),process.exit(1)):T.info(`Found ${e.length} connector(s) file(s). Processing...`);for(let t of e){console.info(`
|
|
2
|
-
`);let e=await this.uploadFile(t,o,i.apiKey);e&&n++}console.info(`
|
|
3
|
-
`),T.info(`Upload completed: ${n} of ${e.length} file(s) uploaded successfully.`),process.exit(n>0?0:1)}else t.endsWith(`.s1.yaml`)||(T.error(`Only .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(t,n,r){try{console.info(e.blue(`๐ค Uploading ${d(t)}...`));let i=M(t);if(!i)return!1;let a=d(t),o=new FormData,s=new Blob([i],{type:`application/x-yaml`});o.append(`file`,s,a);let c=Buffer.from(r).toString(`base64`),l=await fetch(`${n}/registry/connectors`,{method:`POST`,headers:{Authorization:`Basic ${c}`},body:o});if(!l.ok){let t=await l.text();return T.error(`Upload failed: ${l.status} - ${l.statusText}`),t&&console.error(e.red(t)),!1}let u=await l.json();return console.info(e.green(`โ Successfully uploaded ${a} with connector "${u.provider}@${u.version}"`)),!0}catch(e){return T.error(`Failed to upload file: ${e}`),!1}}};const M=t=>{let n=m(t),r=h(n),i=r?.errors??[];if(r.success){let e=t.split(`/`).pop()||t;return T.success(`Connector ${e} is valid!`),n}else i.length>0?(T.error(`Connector ${t} is not valid. Please fix the following errors:\n`),i.forEach(t=>{console.info(e.red(`- L${t.line}: ${t.message}`))})):T.error(`Connector ${t} is not valid. Please check the file for errors.`)},N=e=>{let t=[],n=s(e,{withFileTypes:!0});for(let r of n){let n=p(e,r.name);r.isDirectory()?t.push(...N(n)):r.name.endsWith(`.s1.yaml`)&&t.push(n)}return t};var P=class{async execute(t){let{watchMode:n,fileOrDir:r}=t,i=g(`Watching for changes...`),a=()=>{console.clear(),console.info(e.yellow(`Watch mode enabled. Press "q" to quit.
|
|
4
|
-
`))};if(r){try{c(r)}catch{T.error(`File or directory not found: ${r}`),process.exit(1)}if(n){let{watch:t}=await import(`./esm-D_hUWJ1V.js`),n=await import(`readline`),o=n.createInterface({input:process.stdin,output:process.stdout});process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding(`utf8`);let s=()=>{console.info(e.grey(`
|
|
5
|
-
|
|
6
|
-
Exiting watch mode...`)),c.close(),i.stop(),o.close(),process.exit(0)};a(),console.info(e.blue(`Running connector(s) validations...`)),await F(r),i.start();let c=t(r||`.`,{ignored:/(^|[/\\])\../,persistent:!0});c.on(`change`,async t=>{a(),i.stop(),console.info(e.blue(`File change detected. Running connector(s) validations...`)),await F(r),i.start()}),process.stdin.on(`data`,e=>{e.toString()===`q`&&s()}),process.on(`SIGINT`,()=>{s()})}else await F(r),process.exit(0)}}};const F=async e=>{let t=c(e);if(t.isDirectory()){let t=s(e),n=t.filter(e=>e.endsWith(`.s1.yaml`));if(n.length===0){T.error(`No StackOne connectors found in directory: ${e}. Connector files need to have the extension .s1.yaml.\n`);return}let r=0,i=0;for(let t of n){let n=`${e}/${t}`,a=c(n);if(a.isFile()){let e=await I(n);e?r++:i++}}T.info(`Validation completed: ${r} valid, ${i} invalid connectors.\n`)}else t.isFile()&&e.endsWith(`s1.yaml`)?await I(e):T.error(`No StackOne connector found: ${e}. Connector files need to have the extension .s1.yaml.\n`)},I=async t=>{let n=m(t),r=h(n),i=r?.errors??[];if(r.success){let e=t.split(`/`).pop()||t;return T.success(`Connector ${e} is valid!\n`),!0}else if(i.length>0)return T.error(`Connector ${t} is not valid. Please fix the following errors:\n`),i.forEach(t=>{console.info(e.red(`- L${t.line}: ${t.message}`))}),console.info(`
|
|
7
|
-
`),!1;else return T.error(`Connector ${t} is not valid. Please check the file for errors.`),!1},L=()=>{try{let e=_(import.meta.url),t=f(e),n=p(t,`..`,`package.json`),r=JSON.parse(o(n,`utf8`));return r.version}catch{return`unknown`}};var R=class{constructor(e=new n,t=L()){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 n=new k,r=new j,i=new P;this.program.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),outputError:(t,n)=>{n(e.red(t))}}),this.program.command(`init`).option(`-e, --env <environment>`,`Specify the environment for the configuration profile`).description(`Initialize & create a StackOne CLI configuration profile`).action(e=>{n.execute({environment:e.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 t(`<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(`validate`).option(`-w, --watch`,`Run in watch mode`).addArgument(new t(`<path>`,`Connector file or directory with connectors to validate`)).description(`Validate a StackOne connector`).action((e,t)=>{i.execute({watchMode:t.watch,fileOrDir:e})}),this.program.command(`version`).description(`Show version information`).action(()=>{console.info(`${e.greenBright(`StackOne`)} ${e.grey(`CLI`)} ${e.whiteBright(this.version)}`),process.exit(0)})}run(){this.program.parse(process.argv)}};export{R as CLI};
|