runcloud 0.2.223 → 0.2.225
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 +5 -4
- package/dist/commands/run-cloud-credits.js +88 -0
- package/dist/commands/run-cloud.js +14 -1
- package/dist/index.js +0 -2
- package/dist/run-cloud-interactive.js +400 -0
- package/dist/run-cloud-menu.js +81 -0
- package/dist/run-cloud.js +10 -2
- package/dist/version.js +1 -1
- package/package.json +3 -2
- package/runcloud-0.2.225.tgz +0 -0
- package/skills/run-cloud-sandboxes/SKILL.md +15 -0
- package/dist/commands/environment.js +0 -290
- package/runcloud-0.2.223.tgz +0 -0
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ Everything the CLI creates also shows up at [run.cloud/dashboard](https://run.cl
|
|
|
15
15
|
npm i -g runcloud
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
Installs the `runcloud` binary. Requires **Node ≥ 20**.
|
|
18
|
+
Installs the `runcloud` binary. Requires **Node 20.x ≥ 20.18, or Node ≥ 22**.
|
|
19
19
|
|
|
20
20
|
Or take the standalone binary — no Node, no sudo. It installs to `~/.run-cloud/bin`
|
|
21
21
|
and hands the terminal to `runcloud login` when it finishes:
|
|
@@ -30,7 +30,8 @@ curl -fsSL https://run.cloud/install | sh
|
|
|
30
30
|
runcloud login # sign in with email, Google, or GitHub; stores a token in ~/.run-cloud/credentials
|
|
31
31
|
runcloud whoami # show the stored credential: account, API, expiry, file
|
|
32
32
|
runcloud logout # delete the stored credential
|
|
33
|
-
runcloud account # show your entitlement and
|
|
33
|
+
runcloud account # show your entitlement and organization access
|
|
34
|
+
runcloud credits # show available USD credits and estimated simulator/sandbox runtime
|
|
34
35
|
```
|
|
35
36
|
|
|
36
37
|
Email signs you in without leaving the terminal. Google and GitHub open a browser and
|
|
@@ -304,8 +305,8 @@ runcloud image refresh python:3.12-slim # re-pin the tag to its current u
|
|
|
304
305
|
runcloud sandbox create --image python:3.12-slim
|
|
305
306
|
```
|
|
306
307
|
|
|
307
|
-
Built in: `runcloud/agent-base` (the default, including with `--expose`)
|
|
308
|
-
`runcloud/desktop
|
|
308
|
+
Built in: `runcloud/agent-base` (the default, including with `--expose`) and
|
|
309
|
+
`runcloud/desktop`.
|
|
309
310
|
|
|
310
311
|
## Demos
|
|
311
312
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { ApiError } from '../api.js';
|
|
2
|
+
export class RunCloudCreditsError extends ApiError {
|
|
3
|
+
constructor(status, message, code = 'credits_unavailable') {
|
|
4
|
+
super(status, message, '/run-cloud/credits', { code, retryable: status >= 500 });
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
function record(value) {
|
|
8
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
9
|
+
}
|
|
10
|
+
function amount(value, nullable = false) {
|
|
11
|
+
return nullable && value === null || typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
12
|
+
}
|
|
13
|
+
function creditReport(value) {
|
|
14
|
+
const root = record(value);
|
|
15
|
+
const balance = record(root?.balance);
|
|
16
|
+
const rates = record(root?.rates);
|
|
17
|
+
const sandbox = record(root?.defaultSandbox);
|
|
18
|
+
const estimates = record(root?.estimates);
|
|
19
|
+
const account = record(root?.account);
|
|
20
|
+
const admission = record(root?.admission);
|
|
21
|
+
const available = root?.status === 'available';
|
|
22
|
+
if (root?.schemaVersion !== 1 || root.currency !== 'USD' || !['available', 'unavailable'].includes(String(root.status))
|
|
23
|
+
|| (root.reason !== undefined && typeof root.reason !== 'string')
|
|
24
|
+
|| (available ? !account || typeof account.orgId !== 'string' || typeof account.accountId !== 'string' : root.account !== null)
|
|
25
|
+
|| (available ? !admission || typeof admission.blocked !== 'boolean' || ![null, 'suspended', 'credit_limit'].includes(admission.reason) : root.admission !== null)
|
|
26
|
+
|| (available ? !balance || !['availableUsd', 'coveredUsd', 'spentUsd', 'ceilingUsd'].every(key => amount(balance[key])) : root.balance !== null)
|
|
27
|
+
|| !rates || !['iosUsdPerMinute', 'androidUsdPerMinute', 'cpuUsdPerVcpuSecond', 'memoryUsdPerGiBSecond', 'defaultSandboxUsdPerHour'].every(key => amount(rates[key]))
|
|
28
|
+
|| !sandbox || !amount(sandbox.cpuVcpus) || !amount(sandbox.memoryMiB) || !amount(sandbox.timeoutSeconds)
|
|
29
|
+
|| (available ? !estimates || !['iosSeconds', 'androidSeconds', 'defaultSandboxSeconds'].every(key => amount(estimates[key], true)) : root.estimates !== null)
|
|
30
|
+
|| !Array.isArray(root.assumptions) || !root.assumptions.every(value => typeof value === 'string')) {
|
|
31
|
+
throw new RunCloudCreditsError(502, 'The service returned incomplete credit information. No balance or runtime estimate is available.', 'credits_invalid_response');
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
export async function readRunCloudCredits(api, orgId) {
|
|
36
|
+
const query = orgId ? `?orgId=${encodeURIComponent(orgId)}` : '';
|
|
37
|
+
try {
|
|
38
|
+
return creditReport(await api.get(`/run-cloud/credits${query}`, { signal: AbortSignal.timeout(10_000) }));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error instanceof ApiError && !(error instanceof RunCloudCreditsError)) {
|
|
42
|
+
if (error.status === 401)
|
|
43
|
+
throw new RunCloudCreditsError(401, 'Cannot read credits with this credential (HTTP 401). Run `runcloud login` to refresh it; if other commands work, retry after the service update.');
|
|
44
|
+
if (error.status === 403)
|
|
45
|
+
throw new RunCloudCreditsError(403, 'This credential cannot read credits for the selected organization (HTTP 403).');
|
|
46
|
+
if (error.status === 404)
|
|
47
|
+
throw new RunCloudCreditsError(404, 'Credit information is not available from this API yet (HTTP 404). Retry after the service update.');
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function usd(value) {
|
|
53
|
+
return value === null ? 'unavailable' : new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value);
|
|
54
|
+
}
|
|
55
|
+
function runtime(seconds, unitRate) {
|
|
56
|
+
if (seconds === undefined)
|
|
57
|
+
return 'unavailable';
|
|
58
|
+
if (seconds === null)
|
|
59
|
+
return unitRate === 0 ? 'not metered at this rate' : 'unavailable';
|
|
60
|
+
const minutes = Math.floor(seconds / 60);
|
|
61
|
+
if (minutes < 1)
|
|
62
|
+
return `${Math.floor(seconds)}s`;
|
|
63
|
+
const hours = Math.floor(minutes / 60);
|
|
64
|
+
if (!hours)
|
|
65
|
+
return `${minutes}m`;
|
|
66
|
+
const days = Math.floor(hours / 24);
|
|
67
|
+
if (!days)
|
|
68
|
+
return `${hours}h ${minutes % 60}m`;
|
|
69
|
+
return `${days}d ${hours % 24}h ${minutes % 60}m`;
|
|
70
|
+
}
|
|
71
|
+
function rate(value) {
|
|
72
|
+
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 10 }).format(value);
|
|
73
|
+
}
|
|
74
|
+
export function formatRunCloudCredits(report) {
|
|
75
|
+
return [
|
|
76
|
+
`Available credits: ${usd(report.balance?.availableUsd ?? null)}`,
|
|
77
|
+
...(report.account ? [`Organization: ${report.account.orgId}`] : []),
|
|
78
|
+
...(report.reason ? [`Credit status: ${report.reason.replaceAll('_', ' ')}`] : []),
|
|
79
|
+
...(report.balance ? [`Current spend: ${usd(report.balance.spentUsd)} / ${usd(report.balance.ceilingUsd)} spending ceiling`] : []),
|
|
80
|
+
...(report.admission?.blocked ? [`New sessions blocked: ${report.admission.reason === 'suspended' ? 'account suspended' : 'spending limit reached'}`] : []),
|
|
81
|
+
'',
|
|
82
|
+
'Estimated equivalent runtime (one resource at a time):',
|
|
83
|
+
` iOS simulator: ${runtime(report.estimates?.iosSeconds, report.rates.iosUsdPerMinute)} at ${rate(report.rates.iosUsdPerMinute)}/minute`,
|
|
84
|
+
` Android emulator: ${runtime(report.estimates?.androidSeconds, report.rates.androidUsdPerMinute)} at ${rate(report.rates.androidUsdPerMinute)}/minute`,
|
|
85
|
+
` Default sandbox (${report.defaultSandbox.cpuVcpus} vCPU, ${report.defaultSandbox.memoryMiB} MiB): ${runtime(report.estimates?.defaultSandboxSeconds, report.rates.defaultSandboxUsdPerHour)} at ${rate(report.rates.defaultSandboxUsdPerHour)}/hour`,
|
|
86
|
+
...report.assumptions.map(assumption => ` ${assumption}`),
|
|
87
|
+
].join('\n');
|
|
88
|
+
}
|
|
@@ -8,6 +8,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
8
8
|
import { ApiClient, ApiError, ApiTransportError, friendlyApiError } from '../api.js';
|
|
9
9
|
import { requireCredentials } from '../config.js';
|
|
10
10
|
import { recordSimulatorAudio } from './run-cloud-audio.js';
|
|
11
|
+
import { formatRunCloudCredits, readRunCloudCredits, RunCloudCreditsError } from './run-cloud-credits.js';
|
|
11
12
|
export const IOS_SIMULATOR_CAPABILITIES = ['HealthKit', 'HomeKit', 'WidgetKit', 'SpeechSynthesis', 'Contacts', 'Calendars', 'AppleAccount'];
|
|
12
13
|
export const IOS_PLATFORM_VERSIONS = ['26.5'];
|
|
13
14
|
export const IOS_DEVICE_NAMES = ['iPhone 17e', 'iPad (A16)'];
|
|
@@ -1813,7 +1814,7 @@ async function action(fn, opts = {}) {
|
|
|
1813
1814
|
await fn();
|
|
1814
1815
|
}
|
|
1815
1816
|
catch (err) {
|
|
1816
|
-
console.error(opts.json ? JSON.stringify(jsonErrorEnvelope(err), null, 2) : friendlyApiError(err));
|
|
1817
|
+
console.error(opts.json ? JSON.stringify(jsonErrorEnvelope(err), null, 2) : err instanceof RunCloudCreditsError ? err.detail : friendlyApiError(err));
|
|
1817
1818
|
process.exitCode = err instanceof CliInteractionError && err.code.endsWith('_cancelled') ? 130 : 1;
|
|
1818
1819
|
}
|
|
1819
1820
|
}
|
|
@@ -1884,6 +1885,18 @@ export function registerRunCloud(program) {
|
|
|
1884
1885
|
.action((opts) => action(async () => {
|
|
1885
1886
|
print(await client().get('/run-cloud/account'), opts);
|
|
1886
1887
|
}));
|
|
1888
|
+
program
|
|
1889
|
+
.command('credits')
|
|
1890
|
+
.description('Show available credits and estimated simulator and sandbox runtime')
|
|
1891
|
+
.option('--org-id <id>', 'organization whose credits to show')
|
|
1892
|
+
.option('--json', 'output JSON', false)
|
|
1893
|
+
.action((opts) => action(async () => {
|
|
1894
|
+
const report = await readRunCloudCredits(client(), opts.orgId);
|
|
1895
|
+
if (opts.json)
|
|
1896
|
+
console.log(JSON.stringify(report, null, 2));
|
|
1897
|
+
else
|
|
1898
|
+
console.log(formatRunCloudCredits(report));
|
|
1899
|
+
}, opts));
|
|
1887
1900
|
program
|
|
1888
1901
|
.command('zones')
|
|
1889
1902
|
.alias('zone')
|
package/dist/index.js
CHANGED
|
@@ -21,7 +21,6 @@ import { registerDomains } from './commands/domains.js';
|
|
|
21
21
|
import { registerDns } from './commands/dns.js';
|
|
22
22
|
import { registerDiagnose } from './diagnose.js';
|
|
23
23
|
import { registerDesktop } from './commands/desktop.js';
|
|
24
|
-
import { registerEnvironment } from './commands/environment.js';
|
|
25
24
|
import { registerAppStore } from './commands/appStore.js';
|
|
26
25
|
import { registerUpdate } from './commands/update.js';
|
|
27
26
|
import { registerToken } from './commands/token.js';
|
|
@@ -52,7 +51,6 @@ registerDomains(program);
|
|
|
52
51
|
registerDns(program);
|
|
53
52
|
registerDiagnose(program);
|
|
54
53
|
registerDesktop(program);
|
|
55
|
-
registerEnvironment(program);
|
|
56
54
|
registerAppStore(program);
|
|
57
55
|
registerUpdate(program);
|
|
58
56
|
registerToken(program);
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import { PromptAbortedError } from './prompt.js';
|
|
2
|
+
import { terminalMenu } from './run-cloud-menu.js';
|
|
3
|
+
import { ApiClient } from './api.js';
|
|
4
|
+
import { loadCredentials } from './config.js';
|
|
5
|
+
import { shellCommand } from './sandboxExec.js';
|
|
6
|
+
function commandPath(command) {
|
|
7
|
+
return command.parent ? `${commandPath(command.parent)} ${command.name()}` : command.name();
|
|
8
|
+
}
|
|
9
|
+
function optionsFor(command) {
|
|
10
|
+
return [...command.options, ...(command.parent ? optionsFor(command.parent) : [])];
|
|
11
|
+
}
|
|
12
|
+
function isSandboxExec(command) {
|
|
13
|
+
return command.name() === 'exec' && command.parent?.name() === 'sandbox';
|
|
14
|
+
}
|
|
15
|
+
const groupActionRequiredArguments = new Map([['runcloud sandbox secrets', new Set(['id'])]]);
|
|
16
|
+
function inspect(program, argv) {
|
|
17
|
+
let command = program;
|
|
18
|
+
const result = { command, commandIndices: [], positionals: [], options: [], valid: true };
|
|
19
|
+
let positionalOnly = false;
|
|
20
|
+
for (let index = 0; index < argv.length; index++) {
|
|
21
|
+
const token = argv[index];
|
|
22
|
+
if (!positionalOnly && token === '--') {
|
|
23
|
+
positionalOnly = true;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (!positionalOnly && token.startsWith('-') && token !== '-' && !/^-\d/.test(token)) {
|
|
27
|
+
const flag = token.split('=')[0];
|
|
28
|
+
const options = optionsFor(command);
|
|
29
|
+
const exact = options.find(option => option.long === flag || option.short === flag);
|
|
30
|
+
const attached = !exact && /^-[^-].+/.test(token)
|
|
31
|
+
? options.find(option => option.short === token.slice(0, 2) && (option.required || option.optional)) : undefined;
|
|
32
|
+
const option = exact ?? attached;
|
|
33
|
+
if (!option) {
|
|
34
|
+
if (isSandboxExec(command)) {
|
|
35
|
+
result.positionals.push({ value: token, index });
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
result.valid = false;
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
const supplied = { option, start: index, end: index + 1, missing: false };
|
|
42
|
+
if ((option.required || option.optional) && !attached && !token.includes('=')) {
|
|
43
|
+
const next = argv[index + 1];
|
|
44
|
+
if (next !== undefined && (!next.startsWith('-') || /^-\d/.test(next) || next === '-')) {
|
|
45
|
+
index++;
|
|
46
|
+
if (option.variadic)
|
|
47
|
+
while (argv[index + 1] && !argv[index + 1].startsWith('-'))
|
|
48
|
+
index++;
|
|
49
|
+
supplied.end = index + 1;
|
|
50
|
+
}
|
|
51
|
+
else if (option.required)
|
|
52
|
+
supplied.missing = true;
|
|
53
|
+
}
|
|
54
|
+
result.options.push(supplied);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const child = !positionalOnly && result.positionals.length === 0
|
|
58
|
+
? command.commands.find(child => child.name() === token || child.aliases().includes(token)) : undefined;
|
|
59
|
+
if (child) {
|
|
60
|
+
command = child;
|
|
61
|
+
result.command = command;
|
|
62
|
+
result.commandIndices.push(index);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
result.positionals.push({ value: token, index });
|
|
66
|
+
if (command.commands.length && !command.registeredArguments.length)
|
|
67
|
+
result.valid = false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
function missingRequired(invocation) {
|
|
73
|
+
return invocation.command.registeredArguments.some((argument, index) => argument.required && !invocation.positionals[index])
|
|
74
|
+
|| invocation.options.some(option => option.missing)
|
|
75
|
+
|| invocation.command.options.some(option => option.mandatory && option.defaultValue === undefined
|
|
76
|
+
&& !(option.envVar && process.env[option.envVar]) && !invocation.options.some(supplied => supplied.option === option));
|
|
77
|
+
}
|
|
78
|
+
const controls = new Set(['--interactive', '--no-interactive']);
|
|
79
|
+
function menuControls(argv) {
|
|
80
|
+
let index = 0;
|
|
81
|
+
let mode;
|
|
82
|
+
while (controls.has(argv[index]))
|
|
83
|
+
mode = argv[index++];
|
|
84
|
+
return { args: argv.slice(index), mode };
|
|
85
|
+
}
|
|
86
|
+
function beforeDelimiter(argv) {
|
|
87
|
+
const delimiter = argv.indexOf('--');
|
|
88
|
+
return delimiter < 0 ? argv : argv.slice(0, delimiter);
|
|
89
|
+
}
|
|
90
|
+
function suppressInteractive(argv) {
|
|
91
|
+
return beforeDelimiter(argv).some(arg => ['--json', '--help', '-h', '--version', '-V'].includes(arg) || arg.startsWith('--json='))
|
|
92
|
+
|| argv[0] === 'help';
|
|
93
|
+
}
|
|
94
|
+
function quoted(value) {
|
|
95
|
+
return /^[A-Za-z0-9_./:@%+,=-]+$/.test(value) ? value : `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
96
|
+
}
|
|
97
|
+
export function repeatRunCloudCommand(argv) {
|
|
98
|
+
const safe = ['runcloud'];
|
|
99
|
+
let secretValue;
|
|
100
|
+
let environmentValue = false;
|
|
101
|
+
let positionalOnly = false;
|
|
102
|
+
const environmentReference = (pair) => {
|
|
103
|
+
const name = pair.slice(0, pair.indexOf('='));
|
|
104
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && pair.includes('=')
|
|
105
|
+
? `${name}="\${${name}}"` : '"$RUN_CLOUD_ENV"';
|
|
106
|
+
};
|
|
107
|
+
for (const arg of menuControls(argv).args) {
|
|
108
|
+
if (arg === '--')
|
|
109
|
+
positionalOnly = true;
|
|
110
|
+
if (environmentValue) {
|
|
111
|
+
safe.push(environmentReference(arg));
|
|
112
|
+
environmentValue = false;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (secretValue) {
|
|
116
|
+
safe.push(secretValue);
|
|
117
|
+
secretValue = undefined;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (!positionalOnly && /^--env(?:=|$)/.test(arg)) {
|
|
121
|
+
safe.push('--env');
|
|
122
|
+
if (arg.includes('='))
|
|
123
|
+
safe.push(environmentReference(arg.slice('--env='.length)));
|
|
124
|
+
else
|
|
125
|
+
environmentValue = true;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (!positionalOnly && /^--(?:[a-z0-9-]*-)?(?:token|api-key|password|credential)(?:=|$)/i.test(arg)) {
|
|
129
|
+
const [flag] = arg.split('=');
|
|
130
|
+
const reference = /^--(?:token|api-key)$/i.test(flag)
|
|
131
|
+
? '"$RUN_CLOUD_API_TOKEN"' : `"$${flag.slice(2).toUpperCase().replace(/-/g, '_')}"`;
|
|
132
|
+
safe.push(flag);
|
|
133
|
+
if (arg.includes('='))
|
|
134
|
+
safe.push(reference);
|
|
135
|
+
else
|
|
136
|
+
secretValue = reference;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const redacted = arg
|
|
140
|
+
.replace(/rc_(?:live|cap)_[A-Za-z0-9_-]+/g, '[REDACTED]')
|
|
141
|
+
.replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[REDACTED]')
|
|
142
|
+
.replace(/([?&](?:token|key|signature|credential|authorization)=)[^&#\s]+/gi, '$1[REDACTED]')
|
|
143
|
+
.replace(/(https?:\/\/)[^/@\s]+:[^/@\s]+@/g, '$1[REDACTED]@');
|
|
144
|
+
safe.push(quoted(redacted));
|
|
145
|
+
}
|
|
146
|
+
return safe.join(' ');
|
|
147
|
+
}
|
|
148
|
+
function appendOption(argv, tokens) {
|
|
149
|
+
const delimiter = argv.indexOf('--');
|
|
150
|
+
return delimiter < 0 ? [...argv, ...tokens] : [...argv.slice(0, delimiter), ...tokens, ...argv.slice(delimiter)];
|
|
151
|
+
}
|
|
152
|
+
function setPositional(program, argv, index, value, append = false, replaceRest = false) {
|
|
153
|
+
const invocation = inspect(program, argv);
|
|
154
|
+
const positionals = invocation.positionals.map(positional => positional.value);
|
|
155
|
+
if (replaceRest)
|
|
156
|
+
positionals.splice(index, positionals.length - index, value);
|
|
157
|
+
else if (append)
|
|
158
|
+
positionals.push(value);
|
|
159
|
+
else
|
|
160
|
+
positionals[index] = value;
|
|
161
|
+
const indices = new Set(invocation.positionals.map(positional => positional.index));
|
|
162
|
+
const prefix = argv.filter((token, index) => token !== '--' && !indices.has(index));
|
|
163
|
+
return [...prefix, ...(positionals.some(value => value.startsWith('-')) ? ['--'] : []), ...positionals];
|
|
164
|
+
}
|
|
165
|
+
async function simulatorSession(command, menu) {
|
|
166
|
+
let parent = command;
|
|
167
|
+
while (parent && !['ios', 'android'].includes(parent.name()))
|
|
168
|
+
parent = parent.parent;
|
|
169
|
+
if (!parent)
|
|
170
|
+
return undefined;
|
|
171
|
+
const credentials = loadCredentials();
|
|
172
|
+
if (!credentials)
|
|
173
|
+
return undefined;
|
|
174
|
+
const platform = parent.name();
|
|
175
|
+
let sessions;
|
|
176
|
+
try {
|
|
177
|
+
sessions = await new ApiClient(credentials.apiUrl, credentials.token)
|
|
178
|
+
.get(`/run-cloud/${platform}`, { signal: AbortSignal.timeout(5_000) });
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
menu.write(' Could not load active sessions. Enter a session ID directly.\n');
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
if (!Array.isArray(sessions))
|
|
185
|
+
return undefined;
|
|
186
|
+
const active = sessions.filter((session) => session && typeof session === 'object' && typeof session.id === 'string' && session.status === 'active');
|
|
187
|
+
if (!active.length) {
|
|
188
|
+
menu.write(` No active ${platform === 'ios' ? 'iOS' : 'Android'} sessions found. Enter a session ID directly.\n`);
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
const text = (value) => value.replace(/\p{C}/gu, '').slice(0, 120);
|
|
192
|
+
const selected = await menu.choose(`Choose an ${platform === 'ios' ? 'iOS' : 'Android'} session`, [
|
|
193
|
+
...active.map(session => ({ value: session.id, label: text(session.displayName || session.model || session.id), hint: text(session.id) })),
|
|
194
|
+
{ value: ':manual', label: 'Enter a session ID manually' },
|
|
195
|
+
{ value: ':cancel', label: 'Cancel' },
|
|
196
|
+
]);
|
|
197
|
+
if (selected === ':cancel')
|
|
198
|
+
throw new PromptAbortedError();
|
|
199
|
+
return selected === ':manual' ? undefined : selected;
|
|
200
|
+
}
|
|
201
|
+
async function argumentValue(command, argument, menu) {
|
|
202
|
+
if (isSandboxExec(command) && argument.name() === 'cmd')
|
|
203
|
+
return menu.read('Shell command — runs via /bin/sh -c');
|
|
204
|
+
if (argument.name() === 'id') {
|
|
205
|
+
const selected = await simulatorSession(command, menu);
|
|
206
|
+
if (selected !== undefined)
|
|
207
|
+
return selected;
|
|
208
|
+
}
|
|
209
|
+
const choices = argument.argChoices ?? (argument.name().includes('|') ? argument.name().split('|') : undefined);
|
|
210
|
+
if (choices?.length)
|
|
211
|
+
return menu.choose(argument.description || argument.name(), choices.map(value => ({ value, label: value })));
|
|
212
|
+
return menu.read(`${argument.name()}${argument.description ? ` — ${argument.description}` : ''}`, {
|
|
213
|
+
allowEmpty: /empty/.test(argument.description),
|
|
214
|
+
secret: /password|credential|token/.test(argument.name()),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
async function optionValue(command, option, menu) {
|
|
218
|
+
const flag = option.long ?? option.short;
|
|
219
|
+
if (option.isBoolean() || option.negate)
|
|
220
|
+
return [flag];
|
|
221
|
+
if (option.attributeName() === 'id') {
|
|
222
|
+
const selected = await simulatorSession(command, menu);
|
|
223
|
+
if (selected !== undefined)
|
|
224
|
+
return [`${flag}=${selected}`];
|
|
225
|
+
}
|
|
226
|
+
const choices = option.argChoices;
|
|
227
|
+
const value = choices?.length
|
|
228
|
+
? await menu.choose(option.description, choices.map(value => ({ value, label: value })))
|
|
229
|
+
: await menu.read(`${option.flags} — ${option.description}`, {
|
|
230
|
+
secret: option.attributeName() === 'env' || /token|password|credential/.test(option.attributeName()),
|
|
231
|
+
});
|
|
232
|
+
if (option.attributeName() === 'env' && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(value)) {
|
|
233
|
+
throw new Error('--env requires NAME=VALUE with a valid environment variable name.');
|
|
234
|
+
}
|
|
235
|
+
return [`${flag}=${value}`];
|
|
236
|
+
}
|
|
237
|
+
export async function interactiveRunCloudArgs(program, original, menu) {
|
|
238
|
+
const control = menuControls(original);
|
|
239
|
+
let argv = control.args;
|
|
240
|
+
let invocation = inspect(program, argv);
|
|
241
|
+
if (!invocation.valid)
|
|
242
|
+
return argv;
|
|
243
|
+
if (control.mode !== '--interactive' && (!invocation.command.commands.length || invocation.positionals.length) && !missingRequired(invocation))
|
|
244
|
+
return argv;
|
|
245
|
+
let configureSelf = invocation.command.commands.length > 0 && invocation.positionals.length > 0;
|
|
246
|
+
while (true) {
|
|
247
|
+
invocation = inspect(program, argv);
|
|
248
|
+
const command = invocation.command;
|
|
249
|
+
if (command.commands.length && !configureSelf) {
|
|
250
|
+
const children = command.createHelp().visibleCommands(command);
|
|
251
|
+
const selected = await menu.choose(commandPath(command), [
|
|
252
|
+
...children.map(child => ({
|
|
253
|
+
value: child.name(),
|
|
254
|
+
label: [child.name(), ...child.aliases()].join(' | '),
|
|
255
|
+
hint: child.description(),
|
|
256
|
+
})),
|
|
257
|
+
...(!children.some(child => child.name() === 'help') ? [{ value: 'help', label: 'help', hint: 'Show command usage and options' }] : []),
|
|
258
|
+
...(command.registeredArguments.length ? [{ value: ':self', label: `Run ${command.name()}`, hint: command.description() }] : []),
|
|
259
|
+
...(command.parent ? [{ value: ':back', label: '← Back', hint: commandPath(command.parent) }] : []),
|
|
260
|
+
{ value: ':cancel', label: 'Cancel' },
|
|
261
|
+
]);
|
|
262
|
+
if (selected === ':cancel')
|
|
263
|
+
throw new PromptAbortedError();
|
|
264
|
+
if (selected === 'help')
|
|
265
|
+
return appendOption(argv, ['--help']);
|
|
266
|
+
if (selected === ':self')
|
|
267
|
+
configureSelf = true;
|
|
268
|
+
else {
|
|
269
|
+
if (selected === ':back')
|
|
270
|
+
argv = argv.slice(0, invocation.commandIndices.at(-1));
|
|
271
|
+
else
|
|
272
|
+
argv = appendOption(argv, [selected]);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const [index, argument] of command.registeredArguments.entries()) {
|
|
277
|
+
const requiredForSelf = configureSelf && groupActionRequiredArguments.get(commandPath(command))?.has(argument.name());
|
|
278
|
+
if ((argument.required || requiredForSelf) && !inspect(program, argv).positionals[index]) {
|
|
279
|
+
const value = await argumentValue(command, argument, menu);
|
|
280
|
+
argv = setPositional(program, argv, index, value);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
invocation = inspect(program, argv);
|
|
284
|
+
for (const supplied of invocation.options.filter(option => option.missing).reverse()) {
|
|
285
|
+
const tokens = await optionValue(command, supplied.option, menu);
|
|
286
|
+
argv.splice(supplied.start, supplied.end - supplied.start, ...tokens);
|
|
287
|
+
}
|
|
288
|
+
invocation = inspect(program, argv);
|
|
289
|
+
for (const option of command.options.filter(option => option.mandatory)) {
|
|
290
|
+
if (option.defaultValue !== undefined || (option.envVar && process.env[option.envVar])
|
|
291
|
+
|| invocation.options.some(supplied => supplied.option === option))
|
|
292
|
+
continue;
|
|
293
|
+
argv = appendOption(argv, await optionValue(command, option, menu));
|
|
294
|
+
}
|
|
295
|
+
if (control.mode !== '--interactive')
|
|
296
|
+
return argv;
|
|
297
|
+
const settings = command.options.filter(option => !option.hidden && !['json', 'interactive'].includes(option.attributeName()));
|
|
298
|
+
const optionalArguments = command.registeredArguments.filter(argument => !argument.required || argument.variadic);
|
|
299
|
+
if (!settings.length && !optionalArguments.length)
|
|
300
|
+
return argv;
|
|
301
|
+
const setting = await menu.choose(commandPath(command), [
|
|
302
|
+
{ value: ':done', label: 'Done', hint: repeatRunCloudCommand(argv) },
|
|
303
|
+
...optionalArguments.map(argument => ({
|
|
304
|
+
value: `arg:${argument.name()}`,
|
|
305
|
+
label: isSandboxExec(command) && argument.name() === 'cmd' ? 'Edit shell command' : `${argument.variadic ? 'Add' : 'Set'} ${argument.name()}`,
|
|
306
|
+
hint: isSandboxExec(command) && argument.name() === 'cmd' ? 'Replace the complete /bin/sh -c command' : argument.description,
|
|
307
|
+
})),
|
|
308
|
+
...settings.map(option => ({ value: `opt:${option.attributeName()}`, label: option.flags, hint: option.description })),
|
|
309
|
+
{ value: ':back', label: '← Back', hint: command.parent ? commandPath(command.parent) : 'Menu' },
|
|
310
|
+
{ value: ':help', label: 'help', hint: 'Show command usage and options' },
|
|
311
|
+
{ value: ':cancel', label: 'Cancel' },
|
|
312
|
+
]);
|
|
313
|
+
if (setting === ':done')
|
|
314
|
+
return argv;
|
|
315
|
+
if (setting === ':cancel')
|
|
316
|
+
throw new PromptAbortedError();
|
|
317
|
+
if (setting === ':help')
|
|
318
|
+
return appendOption(argv, ['--help']);
|
|
319
|
+
if (setting === ':back') {
|
|
320
|
+
argv = argv.slice(0, invocation.commandIndices.at(-1));
|
|
321
|
+
configureSelf = false;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (setting.startsWith('arg:')) {
|
|
325
|
+
const argument = optionalArguments.find(argument => `arg:${argument.name()}` === setting);
|
|
326
|
+
const index = command.registeredArguments.indexOf(argument);
|
|
327
|
+
for (let preceding = 0; preceding < index; preceding++) {
|
|
328
|
+
if (inspect(program, argv).positionals[preceding])
|
|
329
|
+
continue;
|
|
330
|
+
const previous = command.registeredArguments[preceding];
|
|
331
|
+
argv = setPositional(program, argv, preceding, previous.defaultValue === undefined
|
|
332
|
+
? await argumentValue(command, previous, menu) : String(previous.defaultValue));
|
|
333
|
+
}
|
|
334
|
+
if (isSandboxExec(command) && argument.name() === 'cmd') {
|
|
335
|
+
const parts = inspect(program, argv).positionals.slice(index).map(positional => positional.value);
|
|
336
|
+
const value = await menu.read('Shell command — replaces the complete /bin/sh -c command', { initialValue: shellCommand(parts) });
|
|
337
|
+
argv = setPositional(program, argv, index, value, false, true);
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
const value = await argumentValue(command, argument, menu);
|
|
341
|
+
argv = setPositional(program, argv, index, value, argument.variadic);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else if (setting.startsWith('opt:')) {
|
|
345
|
+
const option = settings.find(option => `opt:${option.attributeName()}` === setting);
|
|
346
|
+
const supplied = inspect(program, argv).options.filter(supplied => supplied.option === option);
|
|
347
|
+
const repeatable = Array.isArray(option.defaultValue) || /repeatable|repeat to|repeat\)/i.test(option.description);
|
|
348
|
+
if ((option.isBoolean() || option.negate) && supplied.length) {
|
|
349
|
+
for (const item of supplied.reverse())
|
|
350
|
+
argv.splice(item.start, item.end - item.start);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
const tokens = await optionValue(command, option, menu);
|
|
354
|
+
if (!repeatable)
|
|
355
|
+
for (const item of supplied.reverse())
|
|
356
|
+
argv.splice(item.start, item.end - item.start);
|
|
357
|
+
argv = appendOption(argv, tokens);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
export async function runCloudCli(program, argv = process.argv.slice(2), options = {}) {
|
|
363
|
+
const terminal = options.terminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY && process.env.TERM !== 'dumb');
|
|
364
|
+
const menu = options.menu ?? terminalMenu();
|
|
365
|
+
const control = menuControls(argv);
|
|
366
|
+
const enabled = terminal && control.mode !== '--no-interactive' && !suppressInteractive(control.args);
|
|
367
|
+
let actionStarted = false;
|
|
368
|
+
let finished = false;
|
|
369
|
+
let args = control.args;
|
|
370
|
+
const complete = (success) => {
|
|
371
|
+
if (finished)
|
|
372
|
+
return;
|
|
373
|
+
finished = true;
|
|
374
|
+
const command = repeatRunCloudCommand(args);
|
|
375
|
+
if (menu.complete)
|
|
376
|
+
menu.complete(command, success);
|
|
377
|
+
else
|
|
378
|
+
menu.write(`\n Repeat this command:\n ${command}\n`);
|
|
379
|
+
};
|
|
380
|
+
try {
|
|
381
|
+
args = enabled ? await interactiveRunCloudArgs(program, argv, menu) : control.args;
|
|
382
|
+
if (enabled) {
|
|
383
|
+
program.hook('preAction', () => { actionStarted = true; });
|
|
384
|
+
program.hook('postAction', () => { complete(Number(process.exitCode ?? 0) === 0); });
|
|
385
|
+
}
|
|
386
|
+
await program.parseAsync(args, { from: 'user' });
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
if (!(error instanceof PromptAbortedError)) {
|
|
390
|
+
if (enabled && actionStarted)
|
|
391
|
+
complete(false);
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
394
|
+
if (menu.cancel)
|
|
395
|
+
menu.cancel();
|
|
396
|
+
else
|
|
397
|
+
menu.write('Cancelled.\n');
|
|
398
|
+
process.exitCode = 130;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { autocomplete, cancel, intro, isCancel, log, password, text, updateSettings } from '@clack/prompts';
|
|
2
|
+
import { styleText } from 'node:util';
|
|
3
|
+
import { PromptAbortedError } from './prompt.js';
|
|
4
|
+
function colorsDisabled() {
|
|
5
|
+
return process.env.NO_COLOR !== undefined || process.env.NODE_DISABLE_COLORS !== undefined || process.env.FORCE_COLOR === '0';
|
|
6
|
+
}
|
|
7
|
+
function styled(format, value) {
|
|
8
|
+
return colorsDisabled() ? value : styleText(format, value);
|
|
9
|
+
}
|
|
10
|
+
function promptOutput(output) {
|
|
11
|
+
if (!colorsDisabled())
|
|
12
|
+
return output;
|
|
13
|
+
const sgr = new RegExp(`${String.fromCharCode(27)}\\[[\\d;:]*m`, 'g');
|
|
14
|
+
const write = (chunk, ...args) => Reflect.apply(output.write, output, [
|
|
15
|
+
typeof chunk === 'string' ? chunk.replace(sgr, '') : chunk,
|
|
16
|
+
...args,
|
|
17
|
+
]);
|
|
18
|
+
return new Proxy(output, {
|
|
19
|
+
get(target, key) {
|
|
20
|
+
if (key === 'write')
|
|
21
|
+
return write;
|
|
22
|
+
const value = Reflect.get(target, key, target);
|
|
23
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export function terminalMenu(io = { input: process.stdin, output: process.stderr }) {
|
|
28
|
+
const common = { input: io.input, output: promptOutput(io.output) };
|
|
29
|
+
let started = false;
|
|
30
|
+
updateSettings({ aliases: { '\u0004': 'cancel' } });
|
|
31
|
+
const prompt = async (run) => {
|
|
32
|
+
if (!started) {
|
|
33
|
+
intro(styled(['bgCyan', 'black', 'bold'], ' run.cloud '), common);
|
|
34
|
+
started = true;
|
|
35
|
+
}
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const abort = () => controller.abort();
|
|
38
|
+
io.input.once('end', abort);
|
|
39
|
+
io.input.once('close', abort);
|
|
40
|
+
io.input.once('error', abort);
|
|
41
|
+
if (io.input.readableEnded || io.input.destroyed)
|
|
42
|
+
abort();
|
|
43
|
+
try {
|
|
44
|
+
const value = await run(controller.signal);
|
|
45
|
+
if (isCancel(value) || typeof value !== 'string')
|
|
46
|
+
throw new PromptAbortedError();
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
io.input.removeListener('end', abort);
|
|
51
|
+
io.input.removeListener('close', abort);
|
|
52
|
+
io.input.removeListener('error', abort);
|
|
53
|
+
io.input.pause();
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
write: message => { io.output.write(message); },
|
|
58
|
+
choose: (question, choices) => prompt(signal => autocomplete({
|
|
59
|
+
...common, signal,
|
|
60
|
+
message: question.startsWith('runcloud') ? question.replaceAll(' ', ' › ') : question,
|
|
61
|
+
options: choices,
|
|
62
|
+
maxItems: 8,
|
|
63
|
+
placeholder: `Type to filter all ${choices.length} options`,
|
|
64
|
+
filter: (query, choice) => `${choice.label} ${choice.hint ?? ''}`.toLowerCase().includes(query.toLowerCase()),
|
|
65
|
+
})),
|
|
66
|
+
read: (question, options = {}) => prompt(signal => {
|
|
67
|
+
const settings = {
|
|
68
|
+
...common, signal, message: question,
|
|
69
|
+
validate: (value) => value?.length || options.allowEmpty ? undefined : 'Enter a value.',
|
|
70
|
+
};
|
|
71
|
+
return options.secret ? password(settings) : text({ ...settings, initialValue: options.initialValue });
|
|
72
|
+
}),
|
|
73
|
+
complete: (command, success) => {
|
|
74
|
+
io.output.write('\n');
|
|
75
|
+
const label = styled([success ? 'green' : 'red', 'bold'], success ? 'COMMAND COMPLETE' : 'COMMAND FAILED');
|
|
76
|
+
(success ? log.success : log.error)(label, { output: common.output, withGuide: false });
|
|
77
|
+
io.output.write(`${styled('dim', 'Repeat this command:')}\n${command}\n\n`);
|
|
78
|
+
},
|
|
79
|
+
cancel: () => cancel('Cancelled.', { output: common.output, withGuide: false }),
|
|
80
|
+
};
|
|
81
|
+
}
|
package/dist/run-cloud.js
CHANGED
|
@@ -9,9 +9,17 @@ import { registerSecrets } from './commands/secrets.js';
|
|
|
9
9
|
import { registerToken } from './commands/token.js';
|
|
10
10
|
import { registerXcode } from './commands/xcode.js';
|
|
11
11
|
import { CLI_VERSION } from './version.js';
|
|
12
|
+
import { runCloudCli } from './run-cloud-interactive.js';
|
|
12
13
|
const program = new Command('runcloud')
|
|
13
14
|
.description('Create and control remote mobile simulators and microVM sandboxes')
|
|
14
|
-
.version(CLI_VERSION)
|
|
15
|
+
.version(CLI_VERSION)
|
|
16
|
+
.addHelpText('after', [
|
|
17
|
+
'\nRun `runcloud` or a command group, such as `runcloud ios`, to open its menu.',
|
|
18
|
+
'Global menu flags (place before the command):',
|
|
19
|
+
' --interactive configure a complete command using menus',
|
|
20
|
+
' --no-interactive disable menus and the repeat-command hint',
|
|
21
|
+
'Example: runcloud --interactive ios create',
|
|
22
|
+
].join('\n'));
|
|
15
23
|
registerLogin(program);
|
|
16
24
|
registerRunCloud(program);
|
|
17
25
|
registerRunCloudFleet(program);
|
|
@@ -20,4 +28,4 @@ registerSecrets(program);
|
|
|
20
28
|
registerToken(program);
|
|
21
29
|
registerXcode(program);
|
|
22
30
|
registerImage(program);
|
|
23
|
-
await program
|
|
31
|
+
await runCloudCli(program);
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = '0.2.
|
|
1
|
+
export const CLI_VERSION = '0.2.225';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "runcloud",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.225",
|
|
4
4
|
"description": "Create and control run.cloud remote mobile simulators and cloud sandboxes",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"keywords": [
|
|
@@ -41,9 +41,10 @@
|
|
|
41
41
|
"runcloud": "dist/run-cloud.js"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
|
-
"node": ">=
|
|
44
|
+
"node": "^20.18.0 || >=22.0.0"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
+
"@clack/prompts": "1.9.0",
|
|
47
48
|
"@run-cloud/sdk": "0.48.0",
|
|
48
49
|
"commander": "^12.1.0",
|
|
49
50
|
"ignore": "^7.0.5",
|
|
Binary file
|
|
@@ -405,6 +405,21 @@ An agent older than this gave a `vsock: … i/o timeout` error (HTTP 502) for
|
|
|
405
405
|
both cases and left the processes running. A sandbox keeps the agent it was
|
|
406
406
|
created with.
|
|
407
407
|
|
|
408
|
+
### A command with large output
|
|
409
|
+
|
|
410
|
+
A command run without streaming returns at most 4 MiB of stdout and 1 MiB of
|
|
411
|
+
stderr, cut again if needed so the result fits the host's 8 MiB reader. When
|
|
412
|
+
anything was cut, a `guestagent: output cut: …` line follows the command's
|
|
413
|
+
stderr and gives the number of bytes dropped from each stream. A timeout or
|
|
414
|
+
out-of-memory line can come after it. The command still runs to its end and
|
|
415
|
+
keeps its exit code. For large output, use streaming exec (SDK `exec` with
|
|
416
|
+
`onStdout`/`onStderr`), or write to a file and read the file.
|
|
417
|
+
|
|
418
|
+
An agent older than this held all of the output in memory. In a small sandbox
|
|
419
|
+
the kernel killed the agent: HTTP 502 `vsock: connection to vm_… closed before
|
|
420
|
+
response`, and then `vsock: handshake ack …: EOF` for the next exec while the
|
|
421
|
+
agent restarted. Output over 8 MiB failed in every sandbox.
|
|
422
|
+
|
|
408
423
|
### Lifecycle markers
|
|
409
424
|
|
|
410
425
|
The host writes a marker into the console on every transition:
|
|
@@ -1,290 +0,0 @@
|
|
|
1
|
-
import { createInterface } from 'node:readline/promises';
|
|
2
|
-
import { ApiClient, friendlyApiError } from '../api.js';
|
|
3
|
-
import { runEnvironmentDatabaseShell } from '../shellSession.js';
|
|
4
|
-
import { clearEnvironmentSelection, readEnvironmentSelection, requireCredentials, requireEnvironmentSelection, resolveProject, writeEnvironmentSelection, } from '../config.js';
|
|
5
|
-
const POLL_INTERVAL_MS = 2_000;
|
|
6
|
-
const POLL_TIMEOUT_MS = 10 * 60 * 1_000;
|
|
7
|
-
function client() {
|
|
8
|
-
const credentials = requireCredentials();
|
|
9
|
-
return new ApiClient(credentials.apiUrl, credentials.token);
|
|
10
|
-
}
|
|
11
|
-
async function projectEnvironments(api, projectId) {
|
|
12
|
-
const response = await api.get(`/projects/${encodeURIComponent(projectId)}/environments`);
|
|
13
|
-
return response.environments;
|
|
14
|
-
}
|
|
15
|
-
function resolveEnvironment(rows, value) {
|
|
16
|
-
const matches = rows.filter((row) => row.id === value || row.name === value);
|
|
17
|
-
if (matches.length === 0)
|
|
18
|
-
throw new Error(`Environment not found: ${value}`);
|
|
19
|
-
if (matches.length > 1)
|
|
20
|
-
throw new Error(`Environment name is ambiguous; use its ID: ${value}`);
|
|
21
|
-
return matches[0];
|
|
22
|
-
}
|
|
23
|
-
export function resolveNamedResource(rows, value, kind) {
|
|
24
|
-
if (!value) {
|
|
25
|
-
if (rows.length === 1)
|
|
26
|
-
return rows[0];
|
|
27
|
-
if (rows.length === 0)
|
|
28
|
-
throw new Error(`This environment has no ${kind}s.`);
|
|
29
|
-
throw new Error(`This environment has multiple ${kind}s; specify a name or ID.`);
|
|
30
|
-
}
|
|
31
|
-
const matches = rows.filter((row) => row.id === value || row.name === value);
|
|
32
|
-
if (matches.length === 0)
|
|
33
|
-
throw new Error(`${kind} not found: ${value}`);
|
|
34
|
-
if (matches.length > 1)
|
|
35
|
-
throw new Error(`${kind} name is ambiguous; use its ID: ${value}`);
|
|
36
|
-
return matches[0];
|
|
37
|
-
}
|
|
38
|
-
export function formatEnvironmentLog(entry) {
|
|
39
|
-
return `${entry.timestamp || '-'} ${entry.level.padEnd(5)} ${entry.message}`;
|
|
40
|
-
}
|
|
41
|
-
export function resolveSourceEnvironment(rows, value) {
|
|
42
|
-
const source = value
|
|
43
|
-
? resolveEnvironment(rows, value)
|
|
44
|
-
: (() => {
|
|
45
|
-
const production = rows.filter((row) => row.class === 'production');
|
|
46
|
-
if (production.length === 0)
|
|
47
|
-
throw new Error('Production environment is not ready yet.');
|
|
48
|
-
if (production.length > 1)
|
|
49
|
-
throw new Error('Production environment is ambiguous; use --from <id>.');
|
|
50
|
-
return production[0];
|
|
51
|
-
})();
|
|
52
|
-
if (source.class !== 'production') {
|
|
53
|
-
throw new Error('--from must identify the production environment');
|
|
54
|
-
}
|
|
55
|
-
if (source.status !== 'ready') {
|
|
56
|
-
throw new Error(`Production environment is not ready yet (${source.stage}).`);
|
|
57
|
-
}
|
|
58
|
-
return source;
|
|
59
|
-
}
|
|
60
|
-
async function waitForEnvironment(api, environmentId, terminal) {
|
|
61
|
-
const deadline = Date.now() + POLL_TIMEOUT_MS;
|
|
62
|
-
for (;;) {
|
|
63
|
-
const environment = await api.get(`/environments/${encodeURIComponent(environmentId)}`);
|
|
64
|
-
if (terminal.has(environment.status))
|
|
65
|
-
return environment;
|
|
66
|
-
if (Date.now() >= deadline) {
|
|
67
|
-
throw new Error(`Timed out waiting for environment ${environment.name} (${environment.stage}).`);
|
|
68
|
-
}
|
|
69
|
-
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
function printEnvironment(environment) {
|
|
73
|
-
console.log(`${environment.name} ${environment.id} ${environment.status} ${environment.region}`);
|
|
74
|
-
for (const database of environment.databases) {
|
|
75
|
-
console.log(`database ${database.name} ${database.status}`);
|
|
76
|
-
}
|
|
77
|
-
for (const service of environment.services) {
|
|
78
|
-
console.log(`service ${service.name} ${service.status}`);
|
|
79
|
-
}
|
|
80
|
-
for (const route of environment.routes) {
|
|
81
|
-
console.log(`route ${route.status} https://${route.hostname}`);
|
|
82
|
-
}
|
|
83
|
-
if (environment.lastError)
|
|
84
|
-
console.log(`error ${environment.lastError}`);
|
|
85
|
-
}
|
|
86
|
-
async function confirmDelete(name) {
|
|
87
|
-
if (!process.stdin.isTTY)
|
|
88
|
-
return false;
|
|
89
|
-
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
90
|
-
try {
|
|
91
|
-
const answer = await rl.question(`Delete environment ${name}? Type its name to confirm: `);
|
|
92
|
-
return answer === name;
|
|
93
|
-
}
|
|
94
|
-
finally {
|
|
95
|
-
rl.close();
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
export function registerEnvironment(program) {
|
|
99
|
-
const env = program.command('env').description('Create, select, and operate environments');
|
|
100
|
-
env.command('list')
|
|
101
|
-
.description('List environments for the linked project')
|
|
102
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
103
|
-
.action(async (opts) => {
|
|
104
|
-
try {
|
|
105
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
106
|
-
const selected = readEnvironmentSelection(process.cwd())?.id;
|
|
107
|
-
for (const row of await projectEnvironments(client(), projectId)) {
|
|
108
|
-
console.log(`${row.id === selected ? '*' : ' '} ${row.name}\t${row.id}\t${row.status}\t${row.region}`);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
catch (error) {
|
|
112
|
-
console.error(friendlyApiError(error));
|
|
113
|
-
process.exitCode = 1;
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
env.command('use')
|
|
117
|
-
.description('Select an environment for this workspace')
|
|
118
|
-
.argument('<environment>', 'environment name or id')
|
|
119
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
120
|
-
.action(async (value, opts) => {
|
|
121
|
-
try {
|
|
122
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
123
|
-
const selected = resolveEnvironment(await projectEnvironments(client(), projectId), value);
|
|
124
|
-
writeEnvironmentSelection(process.cwd(), {
|
|
125
|
-
id: selected.id,
|
|
126
|
-
name: selected.name,
|
|
127
|
-
projectId,
|
|
128
|
-
});
|
|
129
|
-
console.log(`Using ${selected.name} (${selected.id}) in this workspace.`);
|
|
130
|
-
}
|
|
131
|
-
catch (error) {
|
|
132
|
-
console.error(friendlyApiError(error));
|
|
133
|
-
process.exitCode = 1;
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
env.command('current')
|
|
137
|
-
.description('Show the selected environment')
|
|
138
|
-
.action(() => {
|
|
139
|
-
const selected = readEnvironmentSelection(process.cwd());
|
|
140
|
-
if (!selected) {
|
|
141
|
-
console.log('No environment selected.');
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
console.log(`${selected.name} (${selected.id})`);
|
|
145
|
-
});
|
|
146
|
-
env.command('clear')
|
|
147
|
-
.description('Clear the selected environment')
|
|
148
|
-
.action(() => {
|
|
149
|
-
clearEnvironmentSelection(process.cwd());
|
|
150
|
-
console.log('Environment selection cleared.');
|
|
151
|
-
});
|
|
152
|
-
env.command('create')
|
|
153
|
-
.description('Fork production and select the new environment')
|
|
154
|
-
.argument('<name>', 'new environment name')
|
|
155
|
-
.option('--from <environment>', 'source production environment name or id')
|
|
156
|
-
.option('--region <region>', 'region (defaults to the source region)')
|
|
157
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
158
|
-
.action(async (name, opts) => {
|
|
159
|
-
try {
|
|
160
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
161
|
-
const api = client();
|
|
162
|
-
const source = resolveSourceEnvironment(await projectEnvironments(api, projectId), opts.from);
|
|
163
|
-
console.log(`Creating environment ${name} from ${source.name}…`);
|
|
164
|
-
const created = await api.post(`/projects/${encodeURIComponent(projectId)}/environments`, {
|
|
165
|
-
name,
|
|
166
|
-
sourceEnvironmentId: source.id,
|
|
167
|
-
region: opts.region ?? source.region,
|
|
168
|
-
});
|
|
169
|
-
const ready = await waitForEnvironment(api, created.id, new Set(['ready', 'failed']));
|
|
170
|
-
if (ready.status === 'failed') {
|
|
171
|
-
throw new Error(`Environment provisioning failed at ${ready.stage}: ${ready.lastError ?? 'unknown error'}`);
|
|
172
|
-
}
|
|
173
|
-
writeEnvironmentSelection(process.cwd(), { id: ready.id, name: ready.name, projectId });
|
|
174
|
-
printEnvironment(ready);
|
|
175
|
-
console.log(`\nUsing ${ready.name} (${ready.id}) in this workspace.`);
|
|
176
|
-
console.log('Deploy with: newly deploy');
|
|
177
|
-
}
|
|
178
|
-
catch (error) {
|
|
179
|
-
console.error(friendlyApiError(error));
|
|
180
|
-
process.exitCode = 1;
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
env.command('status')
|
|
184
|
-
.description('Show the selected environment and its resources')
|
|
185
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
186
|
-
.action(async (opts) => {
|
|
187
|
-
try {
|
|
188
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
189
|
-
const selected = requireEnvironmentSelection(process.cwd(), projectId);
|
|
190
|
-
printEnvironment(await client().get(`/environments/${encodeURIComponent(selected.id)}`));
|
|
191
|
-
}
|
|
192
|
-
catch (error) {
|
|
193
|
-
console.error(friendlyApiError(error));
|
|
194
|
-
process.exitCode = 1;
|
|
195
|
-
}
|
|
196
|
-
});
|
|
197
|
-
env.command('logs')
|
|
198
|
-
.description('Show logs for a service in the selected environment')
|
|
199
|
-
.argument('[service]', 'service name or id (optional when there is only one)')
|
|
200
|
-
.option('-n, --lines <count>', 'maximum log entries', '100')
|
|
201
|
-
.option('--since <timestamp>', 'ISO timestamp (defaults to one hour ago)')
|
|
202
|
-
.option('-f, --follow', 'keep polling for new logs', false)
|
|
203
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
204
|
-
.action(async (value, opts) => {
|
|
205
|
-
try {
|
|
206
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
207
|
-
const selected = requireEnvironmentSelection(process.cwd(), projectId);
|
|
208
|
-
const api = client();
|
|
209
|
-
const environment = await api.get(`/environments/${encodeURIComponent(selected.id)}`);
|
|
210
|
-
const service = resolveNamedResource(environment.services, value, 'service');
|
|
211
|
-
const lines = Number(opts.lines);
|
|
212
|
-
if (!Number.isInteger(lines) || lines < 1 || lines > 2_000) {
|
|
213
|
-
throw new Error('--lines must be an integer from 1 to 2000');
|
|
214
|
-
}
|
|
215
|
-
let since = opts.since ?? new Date(Date.now() - 3_600_000).toISOString();
|
|
216
|
-
if (Number.isNaN(new Date(since).getTime()))
|
|
217
|
-
throw new Error('--since must be an ISO timestamp');
|
|
218
|
-
const seen = new Set();
|
|
219
|
-
for (;;) {
|
|
220
|
-
const result = await api.get(`/environment-services/${encodeURIComponent(service.id)}/logs` +
|
|
221
|
-
`?limit=${lines}&since=${encodeURIComponent(since)}`);
|
|
222
|
-
for (const entry of result.entries) {
|
|
223
|
-
if (seen.has(entry.id))
|
|
224
|
-
continue;
|
|
225
|
-
seen.add(entry.id);
|
|
226
|
-
console.log(formatEnvironmentLog(entry));
|
|
227
|
-
if (entry.timestamp && new Date(entry.timestamp).getTime() >= new Date(since).getTime()) {
|
|
228
|
-
since = entry.timestamp;
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
if (!opts.follow)
|
|
232
|
-
break;
|
|
233
|
-
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
catch (error) {
|
|
237
|
-
console.error(friendlyApiError(error));
|
|
238
|
-
process.exitCode = 1;
|
|
239
|
-
}
|
|
240
|
-
});
|
|
241
|
-
const database = env.command('db').description('Operate databases in the selected environment');
|
|
242
|
-
database.command('shell')
|
|
243
|
-
.description('Open a Postgres shell for an environment database')
|
|
244
|
-
.argument('[database]', 'database name or id (optional when there is only one)')
|
|
245
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
246
|
-
.action(async (value, opts) => {
|
|
247
|
-
try {
|
|
248
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
249
|
-
const selected = requireEnvironmentSelection(process.cwd(), projectId);
|
|
250
|
-
const credentials = requireCredentials();
|
|
251
|
-
const environment = await new ApiClient(credentials.apiUrl, credentials.token).get(`/environments/${encodeURIComponent(selected.id)}`);
|
|
252
|
-
const resource = resolveNamedResource(environment.databases, value, 'database');
|
|
253
|
-
if (resource.status !== 'ready')
|
|
254
|
-
throw new Error(`Database is not ready (${resource.status}).`);
|
|
255
|
-
process.exitCode = await runEnvironmentDatabaseShell({
|
|
256
|
-
apiUrl: credentials.apiUrl,
|
|
257
|
-
token: credentials.token,
|
|
258
|
-
databaseId: resource.id,
|
|
259
|
-
});
|
|
260
|
-
}
|
|
261
|
-
catch (error) {
|
|
262
|
-
console.error(friendlyApiError(error));
|
|
263
|
-
process.exitCode = 1;
|
|
264
|
-
}
|
|
265
|
-
});
|
|
266
|
-
env.command('delete')
|
|
267
|
-
.description('Delete the selected environment')
|
|
268
|
-
.option('--yes', 'skip interactive confirmation', false)
|
|
269
|
-
.option('--project <id>', 'project id (defaults to the linked directory)')
|
|
270
|
-
.action(async (opts) => {
|
|
271
|
-
try {
|
|
272
|
-
const projectId = resolveProject(process.cwd(), opts.project);
|
|
273
|
-
const selected = requireEnvironmentSelection(process.cwd(), projectId);
|
|
274
|
-
if (!opts.yes && !await confirmDelete(selected.name))
|
|
275
|
-
throw new Error('Deletion cancelled.');
|
|
276
|
-
const api = client();
|
|
277
|
-
await api.delete(`/environments/${encodeURIComponent(selected.id)}`);
|
|
278
|
-
const deleted = await waitForEnvironment(api, selected.id, new Set(['deleted', 'failed']));
|
|
279
|
-
if (deleted.status === 'failed') {
|
|
280
|
-
throw new Error(`Environment deletion failed: ${deleted.lastError ?? 'unknown error'}`);
|
|
281
|
-
}
|
|
282
|
-
clearEnvironmentSelection(process.cwd());
|
|
283
|
-
console.log(`Deleted ${selected.name} (${selected.id}).`);
|
|
284
|
-
}
|
|
285
|
-
catch (error) {
|
|
286
|
-
console.error(friendlyApiError(error));
|
|
287
|
-
process.exitCode = 1;
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
}
|
package/runcloud-0.2.223.tgz
DELETED
|
Binary file
|