stably 2.0.4 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,92 +1,78 @@
1
- <p align="center">
2
- <a href="https://stably.ai">
3
- <img src="./logo/logo-white-with-bg.png" height="96">
4
- <h3 align="center">Stably</h3>
5
- </a>
6
- </p>
7
-
8
- <p align="center">
9
- Code. Ship. <s>Test.</s>
10
- </p>
11
-
12
- <p align="center">
13
- <a href="https://vercel.com/docs"><strong>Documentation</strong></a> ·
14
- <a href="https://stably.ai/"><strong>Homepage</strong></a>
15
- </p>
16
- <br/>
17
-
18
1
  # Stably CLI
19
2
 
20
- A command-line interface tool for interacting with [Stably](https://stably.ai/) services.
3
+ ## Local Development
21
4
 
22
- ## Installation
5
+ ### Prerequisites
23
6
 
24
- ```bash
25
- # Install globally
26
- npm install -g stably
7
+ - Node.js v20+
8
+ - pnpm v10+
27
9
 
28
- # Or use npx
29
- npx stably
30
- ```
10
+ ### Build
31
11
 
32
- ## Authentication
12
+ From the monorepo root:
33
13
 
34
- Before using the CLI, you need to authenticate with your Stably API key.
14
+ ```bash
15
+ pnpm --filter stably build
16
+ ```
35
17
 
36
- ### Getting Your API Key
18
+ Or from this directory:
37
19
 
38
- 1. Visit the Stably API Keys page: https://auth.stably.ai/api_keys/personal
39
- 2. Create a new Personal API Key
40
- 3. Copy the generated API Key
20
+ ```bash
21
+ pnpm build
22
+ ```
41
23
 
42
- ### Authentication Methods
24
+ ### Run Locally (without global link)
43
25
 
44
- #### Using the auth command
45
26
  ```bash
46
- # Authenticate with API key
47
- stably auth --api-key YOUR_API_KEY
27
+ # Using tsx (dev mode, no build required)
28
+ pnpm dev
48
29
 
49
- # Or let the CLI prompt you for the API key
50
- stably auth
30
+ # Using built dist
31
+ pnpm start
32
+ # or
33
+ node dist/index.js
51
34
  ```
52
35
 
53
- The CLI will store your API key securely for future use.
36
+ ### Global Link for Testing
54
37
 
55
- ## Development Server
38
+ To test the CLI as if it were installed globally:
56
39
 
57
- Start a development server with a secure tunnel to expose your local environment.
40
+ **1. Build the CLI:**
58
41
 
59
42
  ```bash
60
- # Start development server on default port (3000)
61
- stably dev
43
+ cd /path/to/noqa
44
+ pnpm --filter stably build
45
+ ```
46
+
47
+ **2. Link globally:**
62
48
 
63
- # Specify a custom port
64
- stably dev --port 8080
49
+ ```bash
50
+ cd packages/cli
51
+ PNPM_HOME="$HOME/Library/pnpm" PATH="$PNPM_HOME:$PATH" pnpm link --global
65
52
  ```
66
53
 
67
- The CLI will:
68
- 1. Start a development server on the specified port
69
- 2. Create a secure tunnel to expose your local environment
70
- 3. Provide you with a public URL where your local environment is accessible
54
+ **3. Run from anywhere:**
55
+
56
+ ```bash
57
+ PNPM_HOME="$HOME/Library/pnpm" PATH="$PNPM_HOME:$PATH" stably --help
58
+ ```
71
59
 
72
- ## Troubleshooting
60
+ **Tip:** Add this to your shell profile (`.zshrc` / `.bashrc`) to avoid typing the env vars:
73
61
 
74
- ### Authentication Issues
75
- - If you receive an "Invalid Personal API Key" error, verify that:
76
- 1. The API key is correct and hasn't been revoked
77
- 2. You're using a Personal API Key, not an Organization API Key
78
- 3. The API key has the necessary permissions
62
+ ```bash
63
+ export PNPM_HOME="$HOME/Library/pnpm"
64
+ export PATH="$PNPM_HOME:$PATH"
65
+ ```
79
66
 
80
- ### Development Server Issues
81
- - If the development server fails to start:
82
- 1. Ensure the specified port is available
83
- 2. Check if you're authenticated (run `stably auth` if needed)
84
- 3. Verify your API key has the necessary permissions
67
+ ### Unlink
85
68
 
86
- ## Contributing
69
+ To remove the global link:
87
70
 
88
- For information on how to contribute to this project, including development setup and available scripts, please see [CONTRIBUTING.md](CONTRIBUTING.md).
71
+ ```bash
72
+ rm -f "$HOME/Library/pnpm/stably"
73
+ ```
89
74
 
90
- ## Support
75
+ ### Notes
91
76
 
92
- For additional help or to report issues, please contact the Stably support team.
77
+ - Workspace dependencies (`@stablyai/internal-api-client`, `@stablyai/agent-hooks`, etc.) are bundled into the dist via `noExternal` in `tsup.config.ts`
78
+ - If you add new workspace dependencies, add them to the `noExternal` array in `tsup.config.ts`
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/index.js CHANGED
@@ -1,169 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
25
-
26
- // src/index.ts
27
- var import_commander = require("commander");
28
-
29
- // package.json
30
- var version = "2.0.4";
31
-
32
- // src/config/config.ts
33
- var import_path = __toESM(require("path"));
34
- var import_promises = require("fs/promises");
35
- var import_os = __toESM(require("os"));
36
- var import_v4 = __toESM(require("zod/v4"));
37
- var CONFIG_DIR = import_path.default.join(import_os.default.homedir(), ".stably");
38
- var CONFIG_FILE = import_path.default.join(CONFIG_DIR, "config");
39
- var zStablyUser = import_v4.default.object({
40
- lastName: import_v4.default.string(),
41
- organization: import_v4.default.string()
42
- });
43
- var zStablyConfig = import_v4.default.object({
44
- apiKey: import_v4.default.string(),
45
- user: zStablyUser.optional()
46
- });
47
- async function getConfig() {
48
- try {
49
- const configStr = await (0, import_promises.readFile)(CONFIG_FILE, "utf-8");
50
- return zStablyConfig.parse(JSON.parse(configStr));
51
- } catch {
52
- return void 0;
53
- }
54
- }
55
- async function saveConfig(config) {
56
- await (0, import_promises.mkdir)(import_path.default.dirname(CONFIG_FILE), { recursive: true });
57
- await (0, import_promises.writeFile)(CONFIG_FILE, JSON.stringify(config, null, 2));
58
- }
59
-
60
- // src/auth/auth.ts
61
- var import_prompts = require("@clack/prompts");
62
- var import_picocolors = __toESM(require("picocolors"));
63
-
64
- // src/api/stably/constants.ts
65
- var STABLY_API_URL = process.env.STABLY_API_URL || "https://api.stably.ai";
66
-
67
- // src/api/stably/user.ts
68
- async function getUser(apiKey) {
69
- const result = await fetch(`${STABLY_API_URL}/v1/user/info`, {
70
- method: "POST",
71
- headers: {
72
- "Content-Type": "application/json"
73
- },
74
- body: JSON.stringify({ apiKey })
75
- });
76
- if (result.status === 401) {
77
- throw new Error("Invalid API Key");
78
- }
79
- if (!result.ok) {
80
- throw new Error("Validating API Key failed");
81
- }
82
- return zStablyUser.parse(await result.json());
83
- }
84
-
85
- // src/auth/auth.ts
86
- var import_v42 = __toESM(require("zod/v4"));
87
- var zAuthOptions = import_v42.default.object({
88
- apiKey: import_v42.default.string().optional()
89
- });
90
- async function auth(options) {
91
- const config = await getAuthenticationConfig(options);
92
- const validConfig = await validateConfig(config);
93
- await saveConfig(validConfig);
94
- (0, import_prompts.outro)(import_picocolors.default.green("Login successful"));
95
- }
96
- async function getAuthenticationConfig(options) {
97
- if (options.apiKey) {
98
- return { apiKey: options.apiKey };
99
- }
100
- const config = await getConfig();
101
- if (!config?.apiKey) {
102
- return await askForApiKey();
103
- }
104
- return config;
105
- }
106
- async function askForApiKey() {
107
- import_prompts.log.info("Please visit the following URL to create a Personal API Key:");
108
- import_prompts.log.info(import_picocolors.default.underline(import_picocolors.default.cyan("https://auth.stably.ai/api_keys/personal")));
109
- const apiKey = await (0, import_prompts.password)({
110
- message: "Enter your Personal API Key",
111
- mask: "*"
112
- });
113
- if ((0, import_prompts.isCancel)(apiKey) || !apiKey) {
114
- (0, import_prompts.outro)(import_picocolors.default.red("Login cancelled"));
115
- process.exit(0);
116
- }
117
- return { apiKey: apiKey.toString().trim() };
118
- }
119
- async function validateConfig(config) {
120
- const s = (0, import_prompts.spinner)();
121
- s.start("Validating Personal API Key");
122
- if (!config?.apiKey) {
123
- s.stop(import_picocolors.default.red("\u2717 No Personal API Key provided"));
124
- process.exit(1);
125
- }
126
- try {
127
- const newConfig = await getUser(config.apiKey);
128
- s.stop("\u2713 Personal API Key validated");
129
- return { ...config, user: newConfig };
130
- } catch (error) {
131
- s.stop(import_picocolors.default.red("\u2717 Invalid Personal API Key"));
132
- (0, import_prompts.outro)(import_picocolors.default.red(`Error: ${error}`));
133
- process.exit(1);
134
- }
135
- }
136
-
137
- // src/dev/dev.ts
138
- var import_runner_sdk = require("@stablyhq/runner-sdk");
139
- var import_prompts2 = require("@clack/prompts");
140
- var import_picocolors2 = __toESM(require("picocolors"));
141
- async function dev(options) {
142
- (0, import_prompts2.intro)(`Starting development server for port ${options.port}...`);
143
- const config = await getConfig();
144
- if (!config?.apiKey || !config.user) {
145
- (0, import_prompts2.outro)(import_picocolors2.default.red("You are not authenticated. Run `stably auth`"));
146
- process.exit(1);
147
- }
148
- const s = (0, import_prompts2.spinner)();
149
- s.start("Starting development server...");
150
- const tunnel = await (0, import_runner_sdk.startTunnel)(`http://localhost:${options.port}`, {
151
- subdomain: `${config.user?.organization}-${config.user?.lastName}`.toLowerCase().replace(/[^a-z0-9-]/g, "")
152
- });
153
- s.stop(
154
- `Your local environment is available at: ${import_picocolors2.default.underline(
155
- import_picocolors2.default.cyan(tunnel.url)
156
- )}`
157
- );
158
- }
159
-
160
- // src/index.ts
161
- var program = new import_commander.Command();
162
- program.name("stably").description("Stably CLI").version(version);
163
- program.command("auth").description("Authenticate with Stably").option("-k, --api-key <string>", "API key for authentication").action(auth);
164
- program.command("dev").description("Start the development server").option(
165
- "-p, --port <number>",
166
- "Port number for the development server",
167
- "3000"
168
- ).option("-k, --api-key <string>", "API key for authentication").action(dev);
169
- program.parse();
2
+ "use strict";var e=require("commander"),t=require("buffer"),r=require("path"),n=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("@clack/prompts"),p=require("picocolors"),h=require("readline/promises"),f=require("zod"),m=require("fs/promises"),_=require("open"),g=require("http"),E=require("crypto"),y=require("react"),I=require("react/jsx-runtime"),b=require("simple-git"),T=require("zod/v3"),v=require("@stablyhq/runner-sdk");function R(e){return e&&e.__esModule?e:{default:e}}var S=R(r),w=R(n),C=R(o),A=R(i),U=R(a),x=R(p),L=R(f),O=R(_),P=R(g),B=R(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,r)=>(r=null!=e?N(M(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of k(t))$.call(e,r)||void 0===r||D(e,r,{get:()=>t[r],enumerable:!(n=j(t,r))||n.enumerable});return e})(D(r,"default",{value:e,enumerable:!0}),e)),K=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return n(r.statSync(e),e,t)};var r=H("fs");function n(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,r)}function o(e,t,o){r.stat(e,function(r,s){o(r,!r&&n(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=n,n.sync=function(e,t){return o(r.statSync(e),t)};var r=H("fs");function n(e,t,n){r.stat(e,function(e,r){n(e,!e&&o(r,t))})}function o(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&o===i||r&a&&n===s||r&(a|c)&&0===s}(e,t)}}}),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var r;function n(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(r,o){n(e,t||{},function(e,t){e?o(e):r(t)})})}r(e,t||{},function(e,r){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,r=!1),o(e,r)})}H("fs"),r="win32"===process.platform||global.TESTING_WINDOWS?K():z(),t.exports=n,n.sync=function(e,t){try{return r.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),V=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var r="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,n=H("path"),o=r?";":":",s=Y(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const n=t.colon||o,s=e.match(/\//)||r&&e.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],i=r?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=r?i.split(n):[""];return r&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=r=>new Promise((s,a)=>{if(r===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[r],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=n.join(l,e),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(h,r,0))}),p=(e,r,n)=>new Promise((o,i)=>{if(n===c.length)return o(u(r+1));const a=c[n];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,r,n+1))})});return r?u(0).then(e=>r(null,e),r):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<r.length;i++){const a=r[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=n.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const r=p+o[e];try{if(s.sync(r,{pathExt:c})){if(!t.all)return r;l.push(r)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),W=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var r=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=r,t.exports.default=r}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var r=H("path"),n=V(),o=W();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=n.sync(e.command,{path:s[o({env:s})],pathExt:t?r.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=r.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var r=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(r,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(r,"^$1"),t&&(e=e.replace(r,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var r=X();t.exports=(e="")=>{const t=e.match(r);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var r=H("fs"),n=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=r.openSync(e,"r"),r.readSync(o,t,0,150,0),r.closeSync(o)}catch(e){}return n(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var r=H("path"),n=q(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=n(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,n(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const n=c.test(t);e.command=r.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,n));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var r="win32"===process.platform;function n(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,t){return r&&1===e&&!t.file?n(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!r)return;const n=e.emit;e.emit=function(r,s){if("exit"===r){const r=o(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return r&&1===e&&!t.file?n(t.original,"spawnSync"):null},notFoundError:n}}}),re=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var r=H("child_process"),n=ee(),o=te();function s(e,t,s){const i=n(e,t,s),a=r.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=n(e,t,s),a=r.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=n,t.exports._enoent=o}}),ne=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:r}=H("stream");t.exports=function(){var e=[],t=new r({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",o.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(r){!(e=e.filter(function(e){return e!==r})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,r=(t=H("fs"))&&t.__esModule?t:{default:t},n=class{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),r=Math.min(...t),n=e.substring(0,r).trim(),o=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(o);else{let e=this.objs[n];this.objs[n]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let t=r.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<t.length;e++){let r=t[e];for(;"\\"===r.substring(r.length-1);)r=r.slice(0,-1),r+=t[e+1].trim(),e++;n.makeKeys(r)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var r=this.objs[e].length;return this.interpolate(this.objs[e][r-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}};e.PropertiesFile=n,e.of=function(...e){let t=new n;return t.of.apply(t,e),t}}}),se={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ae(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ae(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},de={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},ue={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},he=F(re());function fe(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var me=(e,t)=>({name:`SIGRT${t+1}`,number:_e+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_e=34,ge=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],Ee=()=>{const e=(()=>{const e=64-_e+1;return Array.from({length:e},me)})();return[...ge,...e].map(ye)},ye=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:r,supported:c,action:n,forced:o,standard:s}},Ie=({name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i}],be=(()=>{const e=Ee();return Object.fromEntries(e.map(Ie))})();(()=>{const e=Ee(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>i.constants.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:o,supported:s,action:a,forced:c,standard:l}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(r,e));Object.assign({},...t)})();var Te=({stdout:e,stderr:t,all:r,error:n,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=C.default.cwd()}}})=>{s=null===s?void 0:s;const h=void 0===(o=null===o?void 0:o)?void 0:be[o].description,f=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:n&&n.code,signal:o,signalDescription:h,exitCode:s,isCanceled:l}),m=`Command ${f}: ${i}`,_="[object Error]"===Object.prototype.toString.call(n),g=_?`${m}\n${n.message}`:m,E=[g,t,e].filter(Boolean).join("\n");return _?(n.originalMessage=n.message,n.message=E):n=new Error(E),n.shortMessage=g,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,n.signalDescription=h,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=l,n.killed=d&&!c,n},ve=["stdin","stdout","stderr"],Re=[];Re.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Se=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,we=Symbol.for("signal-exit emitter"),Ce=globalThis,Ae=Object.defineProperty.bind(Object),Ue=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[we])return Ce[we];Ae(Ce,we,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const o of this.listeners[e])n=!0===o(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},xe=class{},Le=globalThis.process;Se(Le)?new class extends xe{#e="win32"===Le.platform?"SIGINT":"SIGHUP";#t=new Ue;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of Re)this.#s[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(n+=o.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#o=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Se(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Re)try{const t=this.#s[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#a(e,...t),this.#r.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Re.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#o,this.#t.count-=1)}#c(e){return Se(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Se(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(Le):new class extends xe{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(ne());var Oe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Oe,e)]);var Pe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,r={})=>{const n=he.default._parse(e,t,r);return e=n.command,t=n.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=n.options).cwd||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return r?(({env:e=C.default.env,...t}={})=>{const r=fe({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=C.default.cwd(),path:t=C.default.env[fe()],preferLocal:r=!0,execPath:n=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=S.default.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(S.default.join(t,"node_modules/.bin")),r=t,t=S.default.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const n=t instanceof URL?s.fileURLToPath(t):t;e.push(S.default.resolve(r,n,".."))})(c,n,a),[...c,t].join(S.default.delimiter)})(t),e})({env:i,cwd:n,execPath:o}):i})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const r=Math.max(t.length,ve.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===C.default.platform&&"cmd"===S.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},ke=(e,r,n)=>"string"==typeof r||t.Buffer.isBuffer(r)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(r):r:void 0===n?void 0:"";function Me(e,t,r){const n=je(e,t,r),o=((e,t)=>Pe(e,t).join(" "))(e,t),s=((e,t)=>Pe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.readFileSync(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let c;try{c=w.default.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw Te({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(n.options,c.stdout,c.error),d=ke(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=Te({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,parsed:n,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!n.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function $e(e){try{return Me("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=Me("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Me("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function Ke(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var ze={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Ke(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ye={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Ve="https://cirrus-ci.com",We={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Ve}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ve}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},qe={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:$e({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},Je={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},Xe={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?Qe({env:e}):void 0}}},et={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},tt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||$e({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},rt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},nt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},st={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},it={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},at={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||$e({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},ct={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?ut(n):n;return Object.fromEntries(Object.keys(dt).map(n=>[n,(r?r.get(dt[n]):void 0)||(o?o.get(dt[n]):void 0)||("branch"===n?He({env:e,cwd:t}):void 0)]))},ht={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ye,cirrus:We,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:qe,codefresh:Je,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:rt,puppet:nt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,shippable:ct,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...pt({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,r=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:r,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",r="vercel";return e.VERCEL?{name:t,service:r,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:r,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,r=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},ft={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},mt=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):_t({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},_t=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},gt=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${r}=${o.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(o).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const s=t.join(",");switch(n){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(o).map(([t,o])=>_t({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Et=/\{[^{}]+\}/g;function yt(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var It,bt=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},Tt=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const o in r){const s=r[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=gt({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=_t({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},vt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Rt=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let r=t;const n=t.match(Et);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,mt({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,gt({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${_t({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:s}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Tt(e.querySerializer),url:e.url}),St=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Ct(e.headers,t.headers),r},wt=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Ct=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?wt(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},At=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Ut=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xt={"Content-Type":"application/json"},Lt=(e={})=>({...ft,headers:xt,parseAs:"auto",querySerializer:Ut,...e}),Ot=(e={})=>{let t=St(Lt(),e);const r=()=>({...t}),n={error:new At,request:new At,response:new At},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Ct(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(vt(t,r.name))continue;const e=await bt(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:Rt(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:yt(t)};let i=new Request(r,s);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const o of n.error.fns)o&&(r=await o(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let h=p;for(const e of n.error.fns)e&&(h=await e(p,c,i,t));if(h=h||{},t.throwOnError)throw h;return"data"===t.responseStyle?void 0:{error:h,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:r,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),h=async function*(){let c=s??3e3,h=0;const f=d.signal??(new AbortController).signal;for(;!f.aborted;){h++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:f};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const h=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const _=()=>{try{h.cancel()}catch{}};f.addEventListener("abort",_);try{for(;;){const{done:e,value:t}=await h.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),n&&(a=await n(a))),r?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{f.removeEventListener("abort",_),h.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&h>=i)break;const r=Math.min(c*2**(h-1),a??3e4);await p(r)}}}();return{stream:h}})({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of n.request.fns)e&&(o=await e(o,r));return o},url:s})};return{buildUrl:Rt,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=St(t,e),r()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Pt=Ot(Lt({baseUrl:"https://api.stably.ai"})),Bt="x-stably-org-id",Nt="4.0.2",Dt=process.env.STABLY_API_URL||"https://api.stably.ai",jt=process.env.AUTH_URL||"https://auth.stably.ai",kt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Mt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",$t="http://localhost:9876/auth/callback",Ht=()=>It||(It=Ot(Lt({baseUrl:Dt,headers:{"X-STABLY-CLI-VERSION":Nt,"X-STABLY-SOURCE":"cli"}}))),Gt=f.z.object({org_id:f.z.string(),org_name:f.z.string()}),Ft=f.z.object({email:f.z.string(),org_id_to_org_member_info:f.z.record(f.z.string(),Gt).optional(),org_member_info:Gt.optional(),user_id:f.z.string()});f.z.object({email:f.z.string(),firstName:f.z.string().optional(),lastName:f.z.string().optional(),organizations:f.z.array(f.z.object({id:f.z.string(),name:f.z.string()})),userId:f.z.string()});var Kt=f.z.object({projects:f.z.array(f.z.object({id:f.z.string(),name:f.z.string()}))}),zt=f.z.object({accessToken:f.z.string(),expiresInSeconds:f.z.number()}),Yt=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Ht()},(n.client??Pt).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return zt.parse(r.data)},Vt=S.default.join(A.default.homedir(),".stably"),Wt=S.default.join(Vt,"auth.json"),qt=".stably",Jt="project.json",Xt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),Qt=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),Zt=async()=>{try{const e=await m.readFile(Wt,"utf-8");return Xt.parse(JSON.parse(e))}catch{return}},er=async e=>{await m.mkdir(Vt,{recursive:!0}),await m.writeFile(Wt,JSON.stringify(e,null,2),{mode:384})},tr=async()=>{try{await m.unlink(Wt)}catch{}},rr=async e=>{let t=e;const{root:r}=S.default.parse(t);for(;t!==r;){const e=S.default.join(t,qt);try{return await m.access(e),e}catch{t=S.default.dirname(t)}}},nr=async()=>{try{const e=await rr(process.cwd());if(!e)return;const t=S.default.join(e,Jt),r=await m.readFile(t,"utf-8");return Qt.parse(JSON.parse(r))}catch{return}},or=async()=>{try{const e=await rr(process.cwd());e&&await m.unlink(S.default.join(e,Jt))}catch{}},sr=e=>Date.now()>=e.expiresAt-3e5,ir=async e=>{const t=new URLSearchParams({client_id:kt,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${jt}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}},ar=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,cr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},lr=(e,t)=>{const r=new URLSearchParams({client_id:kt,code_challenge:e,code_challenge_method:"S256",redirect_uri:$t,response_type:"code",state:t});return`${jt}/propelauth/oauth/authorize?${r.toString()}`},dr=async e=>{const t=u.spinner();let r;t.start("Loading user info...");try{r=(e=>{try{const t=Ft.parse((e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)})(e));let r;return r=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[],{email:t.email,organizations:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}})(e.accessToken),t.stop(x.default.green(`✓ Logged in as ${x.default.cyan(r.email)}`))}catch(e){t.stop(x.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void u.log.error("You don't belong to any organizations.");if(1===e.length)return u.log.info(`Using organization: ${x.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting organization: ${x.default.cyan(e[0].name)}`),e[0];const t=await u.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return u.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return u.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const r=await Yt(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(x.default.green("✓ Credentials obtained"))}catch(e){t.stop(x.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const s=await(async(e,t)=>{const r=u.spinner();let n;r.start("Loading projects...");try{n=await(async(e,t)=>{const r=await(n={auth:`Bearer ${e}`,client:Ht(),path:{orgId:t}},(n.client??Pt).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return Kt.parse(r.data).projects})(e,t),r.stop(x.default.green("✓ Projects loaded"))}catch(e){r.stop(x.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void u.log.error(t)}if(0===n.length)return u.log.error("No projects found in this organization."),void u.log.info(`Create a project at ${x.default.underline(x.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return u.log.info(`Using project: ${x.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting project: ${x.default.cyan(n[0].name)}`),n[0];const o=await u.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return u.isCancel(o)?void 0:n.find(e=>e.id===o)})(o.accessToken,n.id);return s?(await(async e=>{const t=S.default.join(process.cwd(),qt),r=S.default.join(t,Jt);await m.mkdir(t,{recursive:!0}),await m.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=S.default.join(e,".gitignore");try{if((await m.readFile(t,"utf-8")).split("\n").some(e=>".stably"===e.trim()))return;await m.appendFile(t,"\n# Stably CLI\n.stably\n")}catch{await m.writeFile(t,"# Stably CLI\n.stably\n")}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:s.id,projectName:s.name}),u.log.info(x.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(u.log.warn("Project selection cancelled."),{success:!1})},ur=async()=>{const e=await Zt();if(e){if(!sr(e)){if(await nr())return void u.outro(x.default.yellow("You are already logged in. Run `stably logout` first to log out."));u.log.info("You are logged in but haven't selected a project yet.");const t=await dr(e);return void(t.success?(await er(t.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=u.spinner();t.start("Refreshing session...");try{const r=await ir(e.refreshToken);t.stop(x.default.green("✓ Session refreshed"));const n=await nr();if(n){t.start("Getting org credentials...");try{const e=await Yt(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await er(o),t.stop(x.default.green("✓ Credentials obtained")),u.outro(x.default.green("Login successful"))}catch{await er(r),t.stop(x.default.yellow("Using full credentials")),u.outro(x.default.green("Login successful"))}}else{const e=await dr(r);e.success?(await er(e.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(x.default.yellow("Session expired, proceeding with fresh login...")),await tr(),await or()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=B.default.randomBytes(32).toString("base64url"),t=(r=e,B.default.createHash("sha256").update(r).digest("base64url"));var r;const n=B.default.randomBytes(16).toString("base64url");return{authorizeUrl:lr(t,n),codeVerifier:e,state:n}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const r=await(n=e,new Promise((e,t)=>{const r=setTimeout(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(r)},i=P.default.createServer((t,r)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return r.writeHead(404),void r.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(cr(r,400,ar(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==n?(cr(r,400,ar("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(cr(r,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),o(),i.close(),void e({code:c,state:l,success:!0})):(cr(r,400,ar("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),i.listen(9876)}));var n;if(!r.success)throw new Error(r.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:kt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:$t}),n=await fetch(`${jt}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const o=await n.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(r.code,t)})(r,t)}})();u.log.info("Opening browser for authentication..."),u.log.info(x.default.dim("If browser doesn't open, visit:")),u.log.info(x.default.underline(x.default.cyan(t)));try{await O.default(t)}catch{u.log.warn("Could not open browser automatically. Please open the URL above manually.")}const n=u.spinner();let o;n.start("Waiting for authentication...");try{o=await r(),n.stop(x.default.green("✓ Authentication successful"))}catch(e){n.stop(x.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";u.outro(x.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await dr(o);i.success?(await er(i.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):(u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},pr=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},hr=async()=>{const e=await Zt();if(e){if(!sr(e))return e;try{const t=await ir(e.refreshToken),r=await nr();if(r)try{const e=await Yt(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await er(n),n}catch{return await er(t),t}return await er(t),t}catch{return}}},fr=async(e={})=>{const t=pr();if(t)return{auth:t,type:"env"};let r=await hr(),n=r?await nr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!r||!n)&&e.autoLogin&&o){r?u.log.info("You are logged in but need to select an organization and project."):u.log.info("You are not logged in."),u.log.info("Press Enter to log in."),process.stdout.write(`${x.default.dim("Alternatively, set environment variables for an org API key:")}\n${x.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=h.createInterface({input:process.stdin,output:process.stdout});try{await e.question(x.default.dim("Press Enter to continue... "))}finally{e.close()}await ur(),r=await hr(),n=r?await nr():void 0}return r||(u.outro(x.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(u.outro(x.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},mr=e=>e?{[Bt]:e}:void 0,_r=f.z.object({context:f.z.string().min(1)});function gr(e){return/^\.env(\..*)?$/.test(e)}function Er(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function yr({input:e,pathKey:t}){if(!Er(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}function Ir({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async o=>{const s=yr({input:o,pathKey:n});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}function br({action:e,pathKey:t}){return Ir({action:e,fileCheck:gr,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}function Tr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".gitignore"===e,getBlockMessage:()=>"Modifying .gitignore is not allowed. The .gitignore file is managed by the system and cannot be changed.",pathKey:t})}function vr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".gitattributes"===e,getBlockMessage:()=>"Modifying .gitattributes is not allowed. The .gitattributes file is managed by the system and cannot be changed.",pathKey:t})}function Rr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".lfsconfig"===e,getBlockMessage:()=>"Modifying .lfsconfig is not allowed. The .lfsconfig file is managed by the system and cannot be changed.",pathKey:t})}var Sr=/\.(spec|test)\.(c|m)?(ts|tsx|js|jsx)$/;function wr({pathKey:e}){return async t=>{const r=yr({input:t,pathKey:e});if(!r.success)return r;const n=r.path.replace(/\\/g,"/").split("/").pop()||r.path;return Sr.test(n)?n.endsWith(".spec.ts")?{decision:"approve"}:{decision:"block",reason:`Test files must use the .spec.ts extension. The file "${n}" is not supported by Stably. Please use ".spec.ts" as the extension instead.`,systemMessage:"Tool call blocked due to unsupported test file extension"}:{decision:"approve"}}}function Cr({action:e,pathKey:t,workDir:n}){return async o=>{const s=yr({input:o,pathKey:t});if(!s.success)return s;const i=s.path;try{return function({targetPath:e,workDir:t}){const n=function(e){if(a.existsSync(e))return a.realpathSync.native(e);let t=e;const n=[];for(;!a.existsSync(t);){const o=r.dirname(t);if(o===t)return r.resolve(e);n.unshift(t.slice(o.length+1)),t=o}const o=a.realpathSync.native(t);return n.length>0?r.resolve(o,...n):o}(e),o=a.realpathSync.native(t),s=n.endsWith(r.sep)?n:n+r.sep,i=o.endsWith(r.sep)?o:o+r.sep;return s.startsWith(i)||n===o}({targetPath:r.resolve(n,i),workDir:n})?{decision:"approve"}:{decision:"block",reason:`${"reading"===e?"Accessing":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"} files outside the workspace is not allowed. The path "${i}" resolves to a location outside your workspace directory. Please only access files within your workspace.`,systemMessage:"Tool call blocked due to path traversal attempt"}}catch(e){return{decision:"block",reason:`Unable to validate file path "${i}". Please ensure the path is valid and try again. Error: ${e instanceof Error?e.message:"Unknown error"}`,systemMessage:"Tool call blocked due to path validation error"}}}}var Ar=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Ur=e=>null!=e&&"object"==typeof e&&"tool_response"in e,xr=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Lr=e=>{const t=xr(e);if(t)return t.filter(Ar).map(e=>e.text).join("\n")||void 0},Or=/\u001b\[[0-9;]*m/g,Pr=e=>e.replace(Or,""),Br=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Nr({envVars:e}){return async t=>{if(!Er(t))return{decision:"approve"};const r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const o=n.replace(Br,(t,r)=>{const n=e[r];return null!=n?n:t});return o===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:o}}}}}function Dr({onResult:e}){return async t=>{if(!Ur(t))return{decision:"approve"};const r=Lr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Pr(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===o)return;const s=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=r.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function jr({onResult:e}){return async t=>{if(!Ur(t))return{decision:"approve"};const r=Lr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Pr(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var kr=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}},Mr=10240,$r=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await m.stat(r)).size,n=await m.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Mr)return n;const s=(e=>{const t=e.split("\n"),r=[];let n=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(r.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(s,"utf-8");return i<=Mr?s:s.slice(0,Mr)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},Hr=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await m.readdir(r);return e.length>0?e.join("\n"):"(empty)"}catch(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},Gr=e=>{const t=["mcp__playwright-test__","mcp__auto-heal-report__"];for(const r of t)if(e.startsWith(r))return e.slice(r.length).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return e},Fr=T.z.object({bucket:T.z.string(),key:T.z.string()}),Kr=T.z.object({diffBucketPath:Fr,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),zr=["test","bug","other"],Yr={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},Vr=e=>Yr[e],{zSuiteAutoHealReport:Wr}=function(e){const t=e.enum(zr),r=["Classification of the root cause:","",`- test: ${Vr("test")}`,`- bug: ${Vr("bug")}`,`- other: ${Vr("other")}`].join("\n"),n=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),o=e.discriminatedUnion("result",[n.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),n.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")})}}(T.z),qr=({authHeader:e,orgId:t,runId:r})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:Wr},async({report:n})=>{const o=b.simpleGit({baseDir:process.cwd(),maxConcurrentProcesses:1}),s=await o.diff(),i=Wr.parse(n);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:Ht(),headers:mr(t),path:{runId:n}},(s.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:t,report:i,runId:r});const{uploadUrl:n}=await(async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:Ht(),headers:mr(r),path:{runId:n}},(s.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=Kr.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:t,runId:r});await(async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)})({contentType:"text/plain",diff:s,uploadUrl:n})}catch(e){return{content:[{text:"Error: Failed to upload auto-heal report or diff. Please surface this to the user, and terminate the session.",type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),Jr=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),Xr=(e,t)=>({message:Jr(e),status:t?.status,statusText:t?.statusText}),Qr=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),Zr=["mcp__playwright-test","Read","Write","Edit","Glob","Grep"],en=async e=>{const t=await fr({autoLogin:"chat"===e.mode}),r=(e=>"env"===e.type?e.auth.apiKey:`Bearer ${e.auth.accessToken}`)(t),n="oauth"===t.type?t.auth.context.orgId:void 0,o=S.default.resolve(process.cwd()),s=S.default.join(o,".env"),i=U.default.existsSync(s)&&U.default.statSync(s).isFile()?d.parse(U.default.readFileSync(s,"utf8")):{},a="chat"!==e.mode,c="chat"===e.mode?new kr:void 0,u="chat"===e.mode?e.getHelpText:void 0,p={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let h,f=a,m=!1;const _={current:e=>{}},{addTool:g,addToolResult:E,appendText:b,appendUserMessage:T,cleanup:v,setStatus:R}=await(async(e,t)=>{const{Box:r,Text:n,render:o,useInput:s}=await import("ink"),i=({label:e})=>{const[t,r]=y.useState(0);return y.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(n,{color:"yellow",children:[c[t]," ",e]})},a=()=>{const[e,t]=y.useState(!0);return y.useEffect(()=>{const e=setInterval(()=>t(e=>!e),500);return()=>clearInterval(e)},[]),e?I.jsx(n,{inverse:!0,children:" "}):I.jsx(n,{children:" "})},c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=({onSend:e,state:t})=>{const[o,c]=y.useState("");s((t,r)=>{if(e&&(!r.ctrl||"c"!==t)){if(r.return){const t=o.trim();return t&&e(t),void c("")}r.backspace||r.delete?c(e=>e.slice(0,-1)):c(e=>`${e}${t}`)}});const l=y.useMemo(()=>"running"===t.status?I.jsx(i,{label:"Working"}):"success"!==t.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[t.status]),d=!!e&&"running"===t.status&&0===t.log.length&&!t.resultText&&!t.errorText,u="running"===t.status&&!d||t.log.length>0||t.resultText||t.errorText||"running"!==t.status;return I.jsxs(r,{flexDirection:"column",children:[I.jsxs(r,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),t.promptDisplay&&I.jsx(r,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:t.promptDisplay})})]}),I.jsxs(r,{flexDirection:"column",flexGrow:1,justifyContent:t.log.length>0?"flex-end":"flex-start",minHeight:0,children:[t.log.length>0&&I.jsx(r,{flexDirection:"column",marginTop:1,children:t.log.map(e=>"tool"===e.kind?I.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(n,{children:e.content},e.id))}),"error"===t.status&&t.errorText&&I.jsx(r,{marginTop:1,children:I.jsx(n,{color:"red",children:t.errorText})})]}),u&&I.jsx(r,{flexDirection:"column",flexShrink:0,marginTop:1,children:l}),e&&I.jsxs(r,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(n,{children:[I.jsx(n,{color:"yellow",children:">"})," ",o,I.jsx(a,{})]})]})]})};let d=e;const u=o(I.jsx(l,{onSend:t?.onSend,state:d})),p=()=>{d={...d},u.rerender(I.jsx(l,{onSend:t?.onSend,state:d}))};return{addTool:({rawName:e})=>{d.log=[...d.log,{content:Gr(e),id:d.log.length,kind:"tool"}],p()},addToolResult:({message:e})=>{d.log=[...d.log,{content:e,id:d.log.length,kind:"tool_result"}],p()},appendText:({text:e})=>{if(!e)return;const t=d.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?d.log=[...d.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:d.log=[...d.log,{content:r,id:d.log.length,kind:"text"}],p()},appendUserMessage:({text:e})=>{e&&(d.log=[...d.log,{content:e,id:d.log.length,kind:"user"}],p())},cleanup:async()=>{u.unmount(),await u.waitUntilExit()},setStatus:({error:e,result:t,status:r})=>{d.errorText=e,d.resultText=t,d.status=r,p()}}})(p,"chat"===e.mode?{onSend:e=>_.current(e)}:void 0);let w=p.status;const C=({error:e,result:t,status:r})=>{w=r,R({error:e,result:t,status:r})};_.current=e=>{if("/help"===e.trim()){f&&c&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),"running"===w&&C({status:"success"}),T({text:e});const t=u?.();return void b({text:t??"Help is not available in this session."})}c&&(f&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),C({status:"running"}),T({text:e}),c.pushText(e),f=!0)};const A=await(async()=>{if("single"===e.mode)return Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;if("fix"===e.mode)try{return await(async({authHeader:e,orgId:t,runId:r})=>{const n=await(o={auth:e,client:Ht(),headers:mr(t),path:{runId:r}},(o.client??Pt).get({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===n.response.status)throw new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=_r.safeParse(n.data);if(e.success)return e.data.context;throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:r,orgId:n,runId:e.runId})}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";C({error:t,status:"error"}),await v(),process.exit(1)}return""})(),x=await async function(e){const t=S.default.resolve(e),r=S.default.join(t,"tests"),n=S.default.join(r,"helpers"),o=S.default.join(r,"assets"),s=S.default.join(t,"playwright.config.ts"),i=S.default.join(r,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([Hr({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Hr({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Hr({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Hr({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),$r({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),$r({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:i})]);return{absolutePath:t,directories:{assets:d,helpers:l,root:a,tests:c},files:{playwrightConfig:u,seedSpec:p}}}(o),L=await(async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n})=>{const o=Ht(),s=await(i={client:o,body:{mode:t,workspaceInfo:r,allowedEnvVars:e},headers:{authorization:n}},(i.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],url:"/internal/v1/cli/prompts/system",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(s.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(s.error)}`);return s.data.systemPrompt})({allowedEnvVars:Object.keys(i),mode:e.mode,workspaceInfo:x,authHeader:r}),O=await async function({auth:e,client:t,source:r,metadata:n}){try{const s=await(o={auth:e,client:t,body:{source:r,metadata:n??{}}},(o.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),i=s.response;if(s.error){const e="object"==typeof s.error&&"error"in s.error?s.error.error:"Unknown error";return{error:Xr(e,i)}}return s.data?{key:s.data.key}:{error:Xr("No data in response",i)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Xr(t)}}var o}({auth:r,client:Ht(),source:"cli"}),P=O.key;if(!P){const e=O.error?.message;C({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await v(),process.exit(1)}const B=Object.fromEntries(Object.entries(process.env).filter(([e])=>!Qr.has(e)));h=l.query({options:{allowedTools:[...Zr,..."fix"===e.mode?["mcp__auto-heal-report"]:[]],cwd:o,env:{...B,ANTHROPIC_API_KEY:P,ANTHROPIC_BASE_URL:Mt},hooks:{PostToolUse:[{hooks:[async e=>{const t=xr(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>Ar(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Dr({onResult:e=>E({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[jr({onResult:e=>E({message:e})})]}],PreToolUse:[{hooks:[Cr({action:"writing",pathKey:"file_path",workDir:o}),Tr({action:"writing",pathKey:"file_path"}),vr({action:"writing",pathKey:"file_path"}),Rr({action:"writing",pathKey:"file_path"}),br({action:"writing",pathKey:"file_path"}),wr({pathKey:"file_path"})],matcher:"Write"},{hooks:[Cr({action:"editing",pathKey:"file_path",workDir:o}),Tr({action:"editing",pathKey:"file_path"}),vr({action:"editing",pathKey:"file_path"}),Rr({action:"editing",pathKey:"file_path"}),br({action:"editing",pathKey:"file_path"}),wr({pathKey:"file_path"})],matcher:"Edit"},{hooks:[wr({pathKey:"fileName"})],matcher:"mcp__playwright-test__generator_write_test"},{hooks:[Cr({action:"reading",pathKey:"file_path",workDir:o}),br({action:"reading",pathKey:"file_path"})],matcher:"Read"},{hooks:[Cr({action:"searching",pathKey:"path",workDir:o}),br({action:"searching",pathKey:"path"})],matcher:"Grep"},{matcher:"mcp__playwright-test__browser_type",hooks:[Nr({envVars:i})]}]},includePartialMessages:!0,mcpServers:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx"},..."fix"===e.mode?{"auto-heal-report":qr({authHeader:r,orgId:n,runId:e.runId})}:{}},model:"claude-sonnet-4-5",systemPrompt:L},prompt:c??A});const N=async()=>{try{await(h?.interrupt?.())}catch{}c?.finish(),await v(),process.exit(1)};process.on("SIGINT",N);try{for await(const e of h){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&b({text:e.text})}"message_stop"===t?.type&&c&&c.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)"tool_use"===e?.type&&g({rawName:e.name});continue}if("result"!==e.type);else{if(a){"success"===e.subtype?C({status:"success"}):m||(C({error:"Run failed.",status:"error"}),process.exitCode=1),m=!1;break}"success"!==e.subtype?m||(C({error:"Run failed.",status:"error"}),process.exitCode=1):C({status:"success"}),f=!1,m=!1,c?.allowNextTurn()}}}catch(e){m||(C({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{f=!1,m=!1,process.off("SIGINT",N),c?.finish(),await v()}},tn=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],rn=new e.Command;rn.name("stably").description("Stably CLI").version(Nt),rn.enablePositionalOptions(),rn.showHelpAfterError(),rn.exitOverride();var nn=[];rn.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{nn.push(e)}});var on=()=>{const e=rn.helpInformation().trimEnd();return e?`${e}\n`:""},sn=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},an=()=>{process.stdout.write(on())};rn.command("help").description("Show help for a command").argument("[command...]","Command to show help for").action(e=>{if(!e||0===e.length)return void an();const t=sn(rn,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),an(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),rn.action(()=>en({mode:"chat",getHelpText:on})),rn.command("login").description("Login to Stably via browser authentication").action(ur),rn.command("logout").description("Logout from Stably and clear stored credentials").action(async()=>{const e=await Zt();if(!e)return void u.outro(x.default.yellow("You are not logged in."));const t=u.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${jt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await tr(),await or(),t.stop(x.default.green("✓ Logged out")),u.outro(x.default.green("You have been logged out successfully."))}),rn.command("whoami").description("Show current authentication status").action(async()=>{const e=pr();if(e)return u.log.info(x.default.dim("Authentication: Environment variables")),u.log.info(` ${x.default.bold("API Key:")} ${x.default.cyan(e.apiKey.slice(0,8))}...`),u.log.info(` ${x.default.bold("Project ID:")} ${x.default.cyan(e.projectId)}`),void u.outro(x.default.green("Authenticated via environment variables"));if(!await Zt())return void u.outro(x.default.yellow("Not logged in. Run `stably login` to authenticate."));const t=await nr();if(!t)return u.log.info(x.default.dim("Authentication: OAuth (not linked to a project)")),void u.outro(x.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const r=await(async()=>rr(process.cwd()))(),n=r?S.default.dirname(r):process.cwd(),o=S.default.relative(process.cwd(),n)||".";u.log.info(x.default.dim("Authentication: OAuth")),u.log.info(` ${x.default.bold("Organization:")} ${x.default.cyan(t.orgName)}`),u.log.info(` ${x.default.bold("Project:")} ${x.default.cyan(t.projectName)}`),u.log.info(` ${x.default.bold("Linked at:")} ${x.default.dim(o)}`),u.outro(x.default.green("Authenticated"))}),rn.command("tunnel").description("Start a tunnel to expose your local server").option("-p, --port <number>","Port number for the tunnel","3000").action(async e=>{u.intro(`Starting development server for port ${e.port}...`);const t=await fr(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=u.spinner();n.start("Starting development server...");const o=await v.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ${x.default.underline(x.default.cyan(o.url))}`)}),rn.command("create").description("Create resources").command("test").description("Create a test from a prompt").argument("<prompt...>","Prompt describing the test to create").action(e=>en({mode:"single",prompt:e})),rn.command("fix").description("Fix failing Playwright tests with debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=e??function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const r of Object.keys(ht))if(ht[r].detect({env:e,cwd:t}))return{isCi:!0,...ht[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:$e(r),branch:He(r)})};var r})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),r=[e.service,"slug"in e?e.slug:void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),en({mode:"fix",runId:t})}),tn.forEach(({args:e,description:t,name:o})=>{rn.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,r)=>r>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0]?i.slice(1):i,l=e??[],d=new Set(l.map(e=>{const[t]=e.split("=");return t})),u=c.filter(e=>{const[t]=e.split("=");return!d.has(t)});!function(e){const t=function(e=process.cwd()){const t=r.resolve(e),n=function(e){const t=r.join(e,"package.json");let n;try{n=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}(t);if(!n)return{inNodeModules:!1,installed:!1,packageManager:void 0};const o={...n.dependencies,...n.devDependencies},s="@playwright/test"in o?"@playwright/test":"playwright"in o?"playwright":void 0,i=function(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];for(const[n,o]of t)if(a.existsSync(r.join(e,o)))return n}(t),c=r.join(t,"node_modules"),l=s?r.join(c,s):void 0;return{inNodeModules:!!l&&a.existsSync(l),installed:!!s,packageManager:i,packageName:s}}();t.installed||process.exit(1),t.inNodeModules||process.exit(1);const{packageManager:o}=t;o||process.exit(1);const[s,...i]=function(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}(o),c=[s,...i.slice(0,-1)].join(" "),l=n.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"]}),d=(e,t)=>{let r=e.toString();for(const e of tn)r=r.replaceAll(`${c} playwright ${e.name}`,`${c} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===o){const e=r.split("\n");e.length>0&&e[0].includes("/.bin/playwright")&&e.shift();const n=e.join("\n");return void t.write(n)}t.write(r)};l.stdout?.on("data",e=>{d(e,process.stdout)}),l.stderr?.on("data",e=>{d(e,process.stderr)}),l.on("close",e=>{process.exit(e??0)})}([t,...l,...u])}({overrideArgs:e,subcommand:o}))});var cn=()=>{0!==nn.length&&(process.stderr.write(nn.join("")),nn=[])};(async()=>{try{await rn.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw cn(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!sn(rn,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return nn=[],process.stderr.write(`command '${r}' not found\n`),an(),void(process.exitCode=t);cn(),process.exitCode=t}})();
package/package.json CHANGED
@@ -1,56 +1,62 @@
1
1
  {
2
2
  "name": "stably",
3
- "version": "2.0.4",
3
+ "version": "4.0.2",
4
+ "packageManager": "pnpm@10.24.0",
4
5
  "description": "Stably CLI",
5
6
  "main": "dist/index.js",
6
7
  "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
7
11
  "bin": {
8
12
  "stably": "dist/index.js"
9
13
  },
10
14
  "scripts": {
11
- "build": "tsup",
15
+ "typecheck": "tsgo --noEmit",
16
+ "build": "pnpm run typecheck && tsup",
12
17
  "start": "node dist/index.js",
13
- "dev": "ts-node src/index.ts",
14
- "test": "jest",
15
- "lint": "eslint . --ext .ts --ignore-pattern 'dist/'",
16
- "format": "prettier --write \"src/**/*.ts\"",
17
- "prepare": "husky"
18
- },
19
- "lint-staged": {
20
- "*.{js,ts}": [
21
- "eslint --fix",
22
- "prettier --write"
23
- ]
18
+ "start:staging": "dotenv -e .env.staging -- node dist/index.js",
19
+ "dev": "tsx src/index.ts",
20
+ "dev:staging": "dotenv -e .env.staging -- tsx src/index.ts",
21
+ "lint": "PATH=../../node_modules/.bin:$PATH oxlint . --type-aware --tsconfig ./tsconfig.json",
22
+ "lintf": "PATH=../../node_modules/.bin:$PATH oxlint . --fix --quiet --type-aware --tsconfig ./tsconfig.json",
23
+ "lintf-specific": "PATH=../../node_modules/.bin:$PATH oxlint --fix --quiet --type-aware --tsconfig ./tsconfig.json",
24
+ "format": "prettier --write \"src/**/*.ts\""
24
25
  },
25
26
  "keywords": [
26
27
  "cli"
27
28
  ],
28
29
  "author": "",
29
- "license": "ISC",
30
30
  "dependencies": {
31
+ "@anthropic-ai/claude-agent-sdk": "^0.1.62",
31
32
  "@clack/prompts": "^0.11.0",
32
33
  "@stablyhq/runner-sdk": "^1.0.8",
33
- "commander": "^14.0.0",
34
+ "commander": "^14.0.1",
35
+ "dotenv": "^17.2.3",
36
+ "ink": "^6.5.1",
37
+ "open": "^11.0.0",
34
38
  "picocolors": "^1.1.1",
35
- "zod": "^4.0.5"
39
+ "react": "^19.2.1",
40
+ "simple-git": "^3.30.0",
41
+ "zod": "^4.1.12"
36
42
  },
37
43
  "devDependencies": {
38
- "@tsconfig/node20": "^20.1.6",
39
- "@types/node": "^24.0.14",
40
- "@typescript-eslint/eslint-plugin": "^8.37.0",
41
- "@typescript-eslint/parser": "^8.37.0",
42
- "eslint": "8.57.0",
43
- "eslint-config-prettier": "^9.1.0",
44
- "eslint-plugin-import": "^2.32.0",
45
- "eslint-plugin-unicorn": "^56.0.1",
46
- "eslint-plugin-unused-imports": "^4.1.4",
47
- "husky": "^9.1.7",
48
- "jest": "^29.7.0",
49
- "lint-staged": "^15.5.2",
50
- "prettier": "3.6.2",
51
- "ts-jest": "^29.4.0",
52
- "ts-node": "^10.9.2",
44
+ "@stablyai/agent-hooks": "workspace:*",
45
+ "@stablyai/agent-schemas": "workspace:*",
46
+ "@stablyai/agent-security-hooks": "workspace:*",
47
+ "@stablyai/agent-workspace-info": "workspace:*",
48
+ "@stablyai/ci-run-id": "0.1.0",
49
+ "@stablyai/internal-api-client": "workspace:*",
50
+ "@stablyai/proxy": "workspace:*",
51
+ "@tsconfig/node20": "^20.1.4",
52
+ "@types/node": "^22.18.11",
53
+ "@types/react": "^19.2.1",
54
+ "@types/react-dom": "^19.2.1",
55
+ "@typescript/native-preview": "7.0.0-dev.20251216.1",
56
+ "dotenv-cli": "^11.0.0",
57
+ "terser": "^5.44.1",
53
58
  "tsup": "^8.5.0",
54
- "typescript": "^5.8.3"
59
+ "tsx": "^4.20.5",
60
+ "typescript": "^5.9.3"
55
61
  }
56
62
  }
package/.eslintrc.cjs DELETED
@@ -1,75 +0,0 @@
1
- /** @type {import("eslint").ESLint.ConfigData} */
2
- const config = {
3
- extends: ["plugin:@typescript-eslint/recommended", "prettier"],
4
- plugins: ["unused-imports", "unicorn", "import"],
5
- parser: "@typescript-eslint/parser",
6
- parserOptions: { project: ["tsconfig.json"] },
7
- root: true,
8
- ignorePatterns: ["*", "!src/"],
9
- rules: {
10
- "@typescript-eslint/array-type": "error",
11
- "@typescript-eslint/ban-ts-comment": "off",
12
- "@typescript-eslint/consistent-indexed-object-style": "error",
13
- "@typescript-eslint/consistent-type-assertions": ["error"],
14
- "@typescript-eslint/consistent-type-imports": "error",
15
- "@typescript-eslint/no-floating-promises": ["error"],
16
- "@typescript-eslint/no-unnecessary-boolean-literal-compare": ["error"],
17
- "@typescript-eslint/no-explicit-any": ["error", { ignoreRestArgs: true }],
18
- "@typescript-eslint/no-unused-vars": "off",
19
- "@typescript-eslint/no-unnecessary-boolean-literal-compare": "error",
20
- "@typescript-eslint/no-unnecessary-template-expression": "error",
21
- "@typescript-eslint/switch-exhaustiveness-check": ["error"],
22
- "@typescript-eslint/prefer-includes": "error",
23
- "@typescript-eslint/prefer-optional-chain": "error",
24
- // temporary disable this causing issues with next upgrade
25
- // '@typescript-eslint/prefer-readonly': 'error',
26
- // TODO: consider enabling this
27
- // 'no-unused-vars': 'off',
28
- // '@typescript-eslint/no-use-before-define': ['error', { functions: false, typedefs: false }],
29
- curly: "error",
30
- "brace-style": ["error", "1tbs", { allowSingleLine: false }],
31
- "import/newline-after-import": "error",
32
- "import/no-anonymous-default-export": "off",
33
- // We use a smarter no-used plugin: https://www.npmjs.com/package/eslint-plugin-unused-imports
34
- "no-restricted-imports": [
35
- "error",
36
- {
37
- paths: [
38
- {
39
- name: "inspector",
40
- importNames: ["console"],
41
- message:
42
- "Likely an error. Please use the global console object instead",
43
- },
44
- {
45
- name: "zod",
46
- importNames: ["undefined"],
47
- message: "Likely an error. Please use the global undefined instead",
48
- },
49
- ],
50
- },
51
- ],
52
- "no-unneeded-ternary": "error",
53
- "no-unsafe-finally": "error",
54
- "no-use-before-define": "off",
55
- "object-shorthand": ["error", "always"],
56
- "prefer-template": "error",
57
- "unicorn/prefer-negative-index": "error",
58
- "unicorn/prefer-ternary": "error",
59
- "unused-imports/no-unused-imports": "error",
60
- "unused-imports/no-unused-vars": [
61
- "error",
62
- {
63
- caughtErrors: "none",
64
- vars: "all",
65
- varsIgnorePattern: "^_|z[A-Z]", // z[A-Z] is for zod objects
66
- args: "after-used",
67
- argsIgnorePattern: "^_",
68
- ignoreRestSiblings: true,
69
- destructuredArrayIgnorePattern: "^_",
70
- },
71
- ],
72
- },
73
- };
74
-
75
- module.exports = config;
package/.eslintrc.json DELETED
@@ -1,20 +0,0 @@
1
- {
2
- "parser": "@typescript-eslint/parser",
3
- "plugins": ["@typescript-eslint"],
4
- "extends": [
5
- "eslint:recommended",
6
- "plugin:@typescript-eslint/recommended"
7
- ],
8
- "env": {
9
- "node": true,
10
- "es6": true
11
- },
12
- "parserOptions": {
13
- "ecmaVersion": 2020,
14
- "sourceType": "module"
15
- },
16
- "rules": {
17
- "@typescript-eslint/explicit-function-return-type": "warn",
18
- "@typescript-eslint/no-explicit-any": "warn"
19
- }
20
- }
@@ -1,4 +0,0 @@
1
- template: |
2
- ## What’s Changed
3
-
4
- $CHANGES
@@ -1,70 +0,0 @@
1
- name: Release
2
-
3
- on:
4
- # Trigger the workflow selectively
5
- workflow_dispatch:
6
-
7
- permissions:
8
- contents: write
9
- pull-requests: write
10
-
11
- env:
12
- NODE_VERSION: 22.17.1
13
- PNPM_VERSION: 9.14.2
14
-
15
- jobs:
16
- release:
17
- # prevent this action from running on forks
18
- if: github.repository == 'stablyai/stably'
19
- permissions:
20
- contents: write
21
- pull-requests: read
22
- runs-on: ubuntu-latest
23
- steps:
24
- - uses: actions/checkout@v4
25
- with:
26
- fetch-depth: 0 # required to get tags
27
- - uses: actions/setup-node@v4
28
- with:
29
- node-version: ${{ env.NODE_VERSION }}
30
- # Required for npm publish
31
- registry-url: 'https://registry.npmjs.org'
32
- - name: Extract version from package.json
33
- run: echo "VERSION=$(jq -r .version package.json)" >> $GITHUB_ENV
34
- - name: Get latest semver tag
35
- run: |
36
- # Get all tags that match semver pattern (v1.2.3 or 1.2.3)
37
- latest_tag=$(git tag -l | grep -E '^v?[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)
38
-
39
- # Fallback: if no semver tags found, get the latest tag by date
40
- if [ -z "$latest_tag" ]; then
41
- latest_tag=$(git describe --tags --abbrev=0 2>/dev/null || echo "no-tags")
42
- fi
43
-
44
- echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV
45
-
46
- echo "Will release version $VERSION, latest tag is $LATEST_TAG"
47
- - name: Exit if version already released
48
- if: ${{ contains(env.LATEST_TAG, env.VERSION) }}
49
- run: |
50
- echo "Version $VERSION already released. Exiting workflow early."
51
- exit 0
52
- # TODO: we could cache these deps (but not many today)
53
- - uses: pnpm/action-setup@v4.0.0
54
- with:
55
- version: ${{ env.PNPM_VERSION }}
56
- run_install: true
57
- - name: Build
58
- run: pnpm run build
59
- - name: Publish GitHub Release
60
- uses: release-drafter/release-drafter@v6
61
- with:
62
- version: ${{ env.VERSION }}
63
- tag: v${{ env.VERSION }}
64
- publish: true
65
- env:
66
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
67
- - name: Publish to NPM
68
- run: npm publish --access public
69
- env:
70
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/.husky/pre-commit DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env sh
2
- npx lint-staged
package/CONTRIBUTING.md DELETED
@@ -1,47 +0,0 @@
1
- # Development Guide
2
-
3
- This guide is for contributors who want to develop and contribute to the Stably CLI.
4
-
5
- ## Development Setup
6
-
7
- 1. Clone the repository
8
- 2. Install dependencies:
9
- ```bash
10
- npm install
11
- ```
12
- 3. Build the project:
13
- ```bash
14
- npm run build
15
- ```
16
- 4. Run in development mode:
17
- ```bash
18
- npm run dev
19
- ```
20
-
21
- ## Available Scripts
22
-
23
- - `pnpm run build` - Compile TypeScript to JavaScript
24
- - `pnpm run start` - Run the compiled JavaScript
25
- - `pnpm run dev` - Run TypeScript directly (for development)
26
- - `pnpm run test` - Run tests
27
- - `pnpm run lint` - Run ESLint
28
- - `pnpm run format` - Format code with Prettier
29
-
30
- ## Contributing
31
-
32
- When contributing to this project, please:
33
-
34
- 1. Follow the existing code style
35
- 2. Run tests before submitting pull requests
36
- 3. Update documentation as needed
37
-
38
- For questions about development, please refer to the main [README.md](README.md) for general project information.
39
-
40
- ## Relevant ENV varialbes
41
- | Variable | Description |
42
- |------------------|---------------------------------------------|
43
- | STABLY_API_URL | Base URL for the Stably API (override default endpoint) |
44
-
45
- ## Release
46
- 1. Increment version in package.json according to SemVer
47
- 2. Build and publish (easiest via GH release action)
Binary file
@@ -1,2 +0,0 @@
1
- export const STABLY_API_URL =
2
- process.env.STABLY_API_URL || "https://api.stably.ai";
@@ -1,22 +0,0 @@
1
- import { zStablyUser, type StablyUser } from "~/config/config";
2
- import { STABLY_API_URL } from "./constants";
3
-
4
- export async function getUser(apiKey: string): Promise<StablyUser> {
5
- const result = await fetch(`${STABLY_API_URL}/v1/user/info`, {
6
- method: "POST",
7
- headers: {
8
- "Content-Type": "application/json",
9
- },
10
- body: JSON.stringify({ apiKey }),
11
- });
12
-
13
- if (result.status === 401) {
14
- throw new Error("Invalid API Key");
15
- }
16
-
17
- if (!result.ok) {
18
- throw new Error("Validating API Key failed");
19
- }
20
-
21
- return zStablyUser.parse(await result.json());
22
- }
package/src/auth/auth.ts DELETED
@@ -1,70 +0,0 @@
1
- import type { StablyConfig } from "~/config/config";
2
- import { getConfig, saveConfig } from "~/config/config";
3
- import { outro, password, spinner, log, isCancel } from "@clack/prompts";
4
- import pc from "picocolors";
5
- import { getUser } from "~/api/stably/user";
6
- import z from "zod/v4";
7
-
8
- const zAuthOptions = z.object({
9
- apiKey: z.string().optional(),
10
- });
11
-
12
- export type AuthOptions = z.infer<typeof zAuthOptions>;
13
-
14
- export async function auth(options: AuthOptions) {
15
- const config = await getAuthenticationConfig(options);
16
- const validConfig = await validateConfig(config);
17
- await saveConfig(validConfig);
18
- outro(pc.green("Login successful"));
19
- }
20
-
21
- export async function getAuthenticationConfig(options: AuthOptions) {
22
- // apiKey is optional, so if not provided, we ask for it
23
- // in an interactive way
24
- if (options.apiKey) {
25
- return { apiKey: options.apiKey };
26
- }
27
-
28
- const config = await getConfig();
29
- if (!config?.apiKey) {
30
- return await askForApiKey();
31
- }
32
-
33
- return config;
34
- }
35
-
36
- async function askForApiKey(): Promise<StablyConfig> {
37
- log.info("Please visit the following URL to create a Personal API Key:");
38
- log.info(pc.underline(pc.cyan("https://auth.stably.ai/api_keys/personal")));
39
-
40
- const apiKey = await password({
41
- message: "Enter your Personal API Key",
42
- mask: "*",
43
- });
44
-
45
- if (isCancel(apiKey) || !apiKey) {
46
- outro(pc.red("Login cancelled"));
47
- process.exit(0);
48
- }
49
-
50
- return { apiKey: apiKey.toString().trim() };
51
- }
52
-
53
- async function validateConfig(config?: StablyConfig): Promise<StablyConfig> {
54
- const s = spinner();
55
- s.start("Validating Personal API Key");
56
- if (!config?.apiKey) {
57
- s.stop(pc.red("✗ No Personal API Key provided"));
58
- process.exit(1);
59
- }
60
-
61
- try {
62
- const newConfig = await getUser(config.apiKey);
63
- s.stop("✓ Personal API Key validated");
64
- return { ...config, user: newConfig };
65
- } catch (error) {
66
- s.stop(pc.red("✗ Invalid Personal API Key"));
67
- outro(pc.red(`Error: ${error}`));
68
- process.exit(1);
69
- }
70
- }
@@ -1,34 +0,0 @@
1
- import path from "path";
2
- import { readFile, mkdir, writeFile } from "fs/promises";
3
- import os from "os";
4
- import z from "zod/v4";
5
-
6
- const CONFIG_DIR = path.join(os.homedir(), ".stably");
7
- const CONFIG_FILE = path.join(CONFIG_DIR, "config");
8
-
9
- export const zStablyUser = z.object({
10
- lastName: z.string(),
11
- organization: z.string(),
12
- });
13
-
14
- const zStablyConfig = z.object({
15
- apiKey: z.string(),
16
- user: zStablyUser.optional(),
17
- });
18
-
19
- export type StablyUser = z.infer<typeof zStablyUser>;
20
- export type StablyConfig = z.infer<typeof zStablyConfig>;
21
-
22
- export async function getConfig(): Promise<StablyConfig | undefined> {
23
- try {
24
- const configStr = await readFile(CONFIG_FILE, "utf-8");
25
- return zStablyConfig.parse(JSON.parse(configStr));
26
- } catch {
27
- return undefined;
28
- }
29
- }
30
-
31
- export async function saveConfig(config: StablyConfig) {
32
- await mkdir(path.dirname(CONFIG_FILE), { recursive: true });
33
- await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
34
- }
package/src/dev/dev.ts DELETED
@@ -1,27 +0,0 @@
1
- import { startTunnel } from "@stablyhq/runner-sdk";
2
- import { getConfig } from "../config/config";
3
- import { spinner, intro, outro } from "@clack/prompts";
4
- import pc from "picocolors";
5
-
6
- export async function dev(options: { port: number; apiKey: string }) {
7
- intro(`Starting development server for port ${options.port}...`);
8
-
9
- const config = await getConfig();
10
- if (!config?.apiKey || !config.user) {
11
- outro(pc.red("You are not authenticated. Run `stably auth`"));
12
- process.exit(1);
13
- }
14
-
15
- const s = spinner();
16
- s.start("Starting development server...");
17
- const tunnel = await startTunnel(`http://localhost:${options.port}`, {
18
- subdomain: `${config.user?.organization}-${config.user?.lastName}`
19
- .toLowerCase()
20
- .replace(/[^a-z0-9-]/g, ""),
21
- });
22
- s.stop(
23
- `Your local environment is available at: ${pc.underline(
24
- pc.cyan(tunnel.url),
25
- )}`,
26
- );
27
- }
package/src/index.ts DELETED
@@ -1,28 +0,0 @@
1
- import { Command } from "commander";
2
- import { version } from "../package.json";
3
-
4
- import { auth } from "./auth/auth";
5
- import { dev } from "./dev/dev";
6
-
7
- const program = new Command();
8
-
9
- program.name("stably").description("Stably CLI").version(version);
10
-
11
- program
12
- .command("auth")
13
- .description("Authenticate with Stably")
14
- .option("-k, --api-key <string>", "API key for authentication")
15
- .action(auth);
16
-
17
- program
18
- .command("dev")
19
- .description("Start the development server")
20
- .option(
21
- "-p, --port <number>",
22
- "Port number for the development server",
23
- "3000",
24
- )
25
- .option("-k, --api-key <string>", "API key for authentication")
26
- .action(dev);
27
-
28
- program.parse();
package/tsconfig.json DELETED
@@ -1,20 +0,0 @@
1
- {
2
- "extends": "@tsconfig/node20/tsconfig.json",
3
- "compilerOptions": {
4
- "declaration": true,
5
- "outDir": "./dist",
6
- "rootDir": "./src",
7
- "forceConsistentCasingInFileNames": true,
8
- "resolveJsonModule": true,
9
- "allowImportingTsExtensions": true,
10
- "noEmit": true,
11
- "moduleResolution": "bundler",
12
- "module": "ESNext",
13
- "baseUrl": ".",
14
- "paths": {
15
- "~/*": ["./src/*"]
16
- }
17
- },
18
- "include": ["src/**/*"],
19
- "exclude": ["node_modules", "dist"]
20
- }
package/tsup.config.ts DELETED
@@ -1,14 +0,0 @@
1
- import { defineConfig } from "tsup";
2
-
3
- export default defineConfig({
4
- entry: ["src/index.ts"],
5
- format: ["cjs"],
6
- target: "node18",
7
- outDir: "dist",
8
- clean: true,
9
- minify: false,
10
- sourcemap: false,
11
- banner: {
12
- js: "#!/usr/bin/env node",
13
- },
14
- });