@deepdynamic/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +32 -2
- package/THIRD_PARTY_NOTICES.txt +102 -0
- package/dist/agents/content.js +12 -0
- package/dist/agents/edit.js +140 -0
- package/dist/agents/install.js +190 -0
- package/dist/agents/refresh.js +20 -0
- package/dist/agents/setup.js +29 -0
- package/dist/agents/targets.js +91 -0
- package/dist/auth/credentials.js +63 -0
- package/dist/auth/session.js +49 -0
- package/dist/cli.js +198 -0
- package/dist/commands/account.js +96 -0
- package/dist/commands/activity.js +80 -0
- package/dist/commands/blocked.js +89 -0
- package/dist/commands/deploy/agents.js +11 -0
- package/dist/commands/deploy/files.js +62 -0
- package/dist/commands/deploy/index.js +95 -0
- package/dist/commands/deploy/manifest.js +24 -0
- package/dist/commands/deploy/minify.js +27 -0
- package/dist/commands/deploy/progress.js +85 -0
- package/dist/commands/deploy/ship.js +117 -0
- package/dist/commands/deploy/upload.js +125 -0
- package/dist/commands/deployments.js +60 -0
- package/dist/commands/dns.js +777 -0
- package/dist/commands/domains.js +639 -0
- package/dist/commands/emails.js +74 -0
- package/dist/commands/env.js +194 -0
- package/dist/commands/help.js +148 -0
- package/dist/commands/keys.js +263 -0
- package/dist/commands/login/flow.js +155 -0
- package/dist/commands/login/index.js +26 -0
- package/dist/commands/logout.js +71 -0
- package/dist/commands/mail.js +241 -0
- package/dist/commands/notifications.js +133 -0
- package/dist/commands/plan.js +355 -0
- package/dist/commands/projects.js +838 -0
- package/dist/commands/reference.js +2187 -0
- package/dist/commands/search.js +86 -0
- package/dist/commands/server.js +301 -0
- package/dist/commands/sessions.js +114 -0
- package/dist/commands/sites.js +102 -0
- package/dist/commands/sms.js +65 -0
- package/dist/commands/status.js +87 -0
- package/dist/commands/support.js +115 -0
- package/dist/commands/update.js +100 -0
- package/dist/commands/usage.js +51 -0
- package/dist/commands/verify.js +149 -0
- package/dist/commands/version.js +6 -0
- package/dist/guide.js +37 -0
- package/dist/http/call.js +6 -0
- package/dist/http/request.js +54 -0
- package/dist/index.js +11 -0
- package/dist/metadata.js +4 -0
- package/dist/output.js +9 -0
- package/dist/pretty.js +70 -0
- package/dist/refresh-skills.js +5 -0
- package/dist/registry.js +688 -0
- package/dist/runtime/browser.js +15 -0
- package/dist/runtime/card-request.js +55 -0
- package/dist/runtime/confirm.js +21 -0
- package/dist/runtime/development.js +13 -0
- package/dist/runtime/domain-name.js +5 -0
- package/dist/runtime/dry-run.js +28 -0
- package/dist/runtime/env-file.js +55 -0
- package/dist/runtime/error-hints.js +26 -0
- package/dist/runtime/flags.js +48 -0
- package/dist/runtime/login-screen.js +78 -0
- package/dist/runtime/page.js +18 -0
- package/dist/runtime/project-name.js +1 -0
- package/dist/runtime/run-mode.js +7 -0
- package/dist/runtime/server-options.js +28 -0
- package/dist/runtime/spinner.js +17 -0
- package/dist/runtime/suggest.js +22 -0
- package/dist/runtime/support.js +13 -0
- package/dist/runtime/text-file.js +20 -0
- package/dist/runtime/timeout.js +22 -0
- package/dist/runtime/update-check.js +158 -0
- package/dist/runtime/update-install.js +80 -0
- package/dist/runtime/usage-error.js +9 -0
- package/dist/setup-agents.js +15 -0
- package/dist/site.js +1 -0
- package/dist/update-refresh.js +5 -0
- package/package.json +46 -3
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
export function browserCommand(url, platform, systemRoot = process.env.SystemRoot || 'C:\\Windows') {
|
|
4
|
+
if (platform === 'darwin')
|
|
5
|
+
return ['open', [url]];
|
|
6
|
+
if (platform === 'win32')
|
|
7
|
+
return [win32.join(systemRoot, 'System32', 'rundll32.exe'), ['url.dll,FileProtocolHandler', url]];
|
|
8
|
+
return ['xdg-open', [url]];
|
|
9
|
+
}
|
|
10
|
+
export function openBrowser(url) {
|
|
11
|
+
const [command, args] = browserCommand(url, process.platform);
|
|
12
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true });
|
|
13
|
+
child.on('error', () => { });
|
|
14
|
+
child.unref();
|
|
15
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { postJson, request } from "../http/request.js";
|
|
2
|
+
import { agentResult } from "../output.js";
|
|
3
|
+
import { prettyResult } from "../pretty.js";
|
|
4
|
+
import { openBrowser } from "./browser.js";
|
|
5
|
+
export const PUBLIC_IP_URL = 'https://ipc.artsnoa.com/api/v1/ip';
|
|
6
|
+
export const CARD_REQUESTS_PATH = '/api/v1/payments/card-requests';
|
|
7
|
+
export const REGISTER_PATH = '/payments/register';
|
|
8
|
+
const PUBLIC_IP_TIMEOUT_MS = 5_000;
|
|
9
|
+
const IP = /^[0-9A-Fa-f:.]{2,39}$/;
|
|
10
|
+
const AGENT_ENV = [['CLAUDECODE', 'CCD']];
|
|
11
|
+
export const detectAgent = (env = process.env) => AGENT_ENV.find(([name]) => env[name])?.[1] ?? 'OTH';
|
|
12
|
+
export const cardRequired = (result) => !('failure' in result) && result.status === 402 && result.body?.code === 'card_required';
|
|
13
|
+
async function publicIp(deps) {
|
|
14
|
+
const result = await request(PUBLIC_IP_URL, { method: 'GET' }, { ...deps, timeoutMs: Math.min(deps.timeoutMs, PUBLIC_IP_TIMEOUT_MS) }, null);
|
|
15
|
+
if ('failure' in result || result.status !== 200)
|
|
16
|
+
return null;
|
|
17
|
+
const ip = result.body?.ip;
|
|
18
|
+
return typeof ip === 'string' && IP.test(ip) ? ip : null;
|
|
19
|
+
}
|
|
20
|
+
async function registrationUrl(session, agent, ip, deps) {
|
|
21
|
+
const result = await postJson(new URL(CARD_REQUESTS_PATH, session.siteUrl).href, session.token, { agent, ip }, deps, null);
|
|
22
|
+
if ('failure' in result || result.status !== 200)
|
|
23
|
+
return null;
|
|
24
|
+
const body = result.body;
|
|
25
|
+
if (body?.ok !== true || typeof body.url !== 'string' || !URL.canParse(body.url))
|
|
26
|
+
return null;
|
|
27
|
+
const url = new URL(body.url);
|
|
28
|
+
return url.origin === new URL(session.siteUrl).origin && url.pathname === REGISTER_PATH ? url.href : null;
|
|
29
|
+
}
|
|
30
|
+
export async function requestCard(command, pretty, depth, session, deps, extra = {}) {
|
|
31
|
+
const agent = detectAgent();
|
|
32
|
+
const ip = await publicIp(deps);
|
|
33
|
+
const url = await registrationUrl(session, agent, ip, deps) ?? new URL(REGISTER_PATH, session.siteUrl).href;
|
|
34
|
+
(deps.openBrowser ?? openBrowser)(url);
|
|
35
|
+
if (pretty) {
|
|
36
|
+
return prettyResult(1, depth, command, 'A payment card is required.', [
|
|
37
|
+
['Server', session.siteUrl],
|
|
38
|
+
['Reason', 'This goes beyond the free tier, so a payment card is needed. Nothing was changed.'],
|
|
39
|
+
['Add card', url],
|
|
40
|
+
['Login', 'This link logs you in automatically once within one hour. Do not share it.'],
|
|
41
|
+
['Next', 'Add the card in the browser, then run the same command again.']
|
|
42
|
+
]);
|
|
43
|
+
}
|
|
44
|
+
return agentResult(1, {
|
|
45
|
+
command,
|
|
46
|
+
siteUrl: session.siteUrl,
|
|
47
|
+
...extra,
|
|
48
|
+
error: {
|
|
49
|
+
code: 'card_required',
|
|
50
|
+
message: 'This goes beyond the free tier and the account has no billing card, so nothing was changed. The card registration page was opened in the user\'s browser. Never send the link anywhere other than the user\'s browser. If no browser opened, show cardRegistration.url to the user. After the user adds a card, run the same command again.',
|
|
51
|
+
retryable: false
|
|
52
|
+
},
|
|
53
|
+
cardRegistration: { url, agent, ip }
|
|
54
|
+
});
|
|
55
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { agentResult } from "../output.js";
|
|
2
|
+
import { prettyResult } from "../pretty.js";
|
|
3
|
+
export const YES_OPTION = '--yes';
|
|
4
|
+
const SHELL_SAFE = /^[\w@%+=:,./-]+$/;
|
|
5
|
+
export function splitYes(args) {
|
|
6
|
+
return { args: args.filter((arg) => arg !== YES_OPTION), yes: args.includes(YES_OPTION) };
|
|
7
|
+
}
|
|
8
|
+
const LINE_BREAKS = /[\r\n]+/g;
|
|
9
|
+
const quote = (raw) => {
|
|
10
|
+
const arg = raw.replace(LINE_BREAKS, ' ');
|
|
11
|
+
return SHELL_SAFE.test(arg) ? arg : `'${arg.replace(/['‘’‚‛]/g, (mark) => `'"${mark}"'`)}'`;
|
|
12
|
+
};
|
|
13
|
+
export function confirmCommand(command, args) {
|
|
14
|
+
return ['deepdynamic', command, ...args.filter((arg) => arg !== YES_OPTION).map(quote), YES_OPTION].join(' ');
|
|
15
|
+
}
|
|
16
|
+
export function confirmationRequired(command, args, pretty, depth, reason, data = {}) {
|
|
17
|
+
const next = confirmCommand(command, args);
|
|
18
|
+
return pretty
|
|
19
|
+
? prettyResult(3, depth, command, reason.display, [['Run', next]])
|
|
20
|
+
: agentResult(3, { command, ...data, error: { code: 'confirmation_required', message: `${reason.message} Confirm with the user, then run: ${next}`, next, retryable: false } });
|
|
21
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { LOGIN_TIMEOUT_MS } from "../commands/login/flow.js";
|
|
2
|
+
import { commands } from "../registry.js";
|
|
3
|
+
import { SERVER_OPTION } from "./server-options.js";
|
|
4
|
+
import { LOGIN_TIMEOUT_OPTION, parseTimeout } from "./timeout.js";
|
|
5
|
+
export const LOCAL_SITE_URL = 'http://localhost:5173';
|
|
6
|
+
export const SERVER_COMMANDS = commands.filter(({ usage }) => usage.includes(SERVER_OPTION)).map(({ name }) => name);
|
|
7
|
+
export function developmentArgs(args) {
|
|
8
|
+
const timeout = parseTimeout(args.filter((arg) => arg !== '--pretty'), LOGIN_TIMEOUT_MS / 1000, LOGIN_TIMEOUT_OPTION, 1);
|
|
9
|
+
const [command, action] = 'error' in timeout ? [] : timeout.rest;
|
|
10
|
+
return SERVER_COMMANDS.includes(`${command} ${action}`) || SERVER_COMMANDS.includes(command ?? '')
|
|
11
|
+
? [...args, SERVER_OPTION, LOCAL_SITE_URL]
|
|
12
|
+
: args;
|
|
13
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const HOST = /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/;
|
|
2
|
+
export function cleanDomain(input) {
|
|
3
|
+
return input.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/[/?#].*$/, '').replace(/\.$/, '').replace(/^www\./, '');
|
|
4
|
+
}
|
|
5
|
+
export const isDomain = (name) => name.length <= 253 && HOST.test(name) && name.split('.').every((label) => label.length <= 63);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { agentResult } from "../output.js";
|
|
2
|
+
import { prettyResult } from "../pretty.js";
|
|
3
|
+
import { startSpinner } from "./spinner.js";
|
|
4
|
+
export const DRY_RUN_OPTION = '--dry-run';
|
|
5
|
+
export const DRY_RUN_STEP_MS = 400;
|
|
6
|
+
export const pauseFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
export function splitDryRun(args) {
|
|
8
|
+
return { args: args.filter((arg) => arg !== DRY_RUN_OPTION), dryRun: args.includes(DRY_RUN_OPTION) };
|
|
9
|
+
}
|
|
10
|
+
export function plannedRequest(command, pretty, depth, siteUrl, url) {
|
|
11
|
+
return pretty
|
|
12
|
+
? prettyResult(0, depth, command, 'Checked without sending the request.', [['Server', siteUrl], ['Request', `GET ${url}`]])
|
|
13
|
+
: agentResult(0, { command, siteUrl, dryRun: true, request: { method: 'GET', url } });
|
|
14
|
+
}
|
|
15
|
+
export async function rehearse(command, steps, pretty, stream, pause = pauseFor) {
|
|
16
|
+
for (const [index, { stage, message }] of steps.entries()) {
|
|
17
|
+
const stop = pretty ? startSpinner(message, stream) : () => { };
|
|
18
|
+
await pause(DRY_RUN_STEP_MS);
|
|
19
|
+
stop();
|
|
20
|
+
const percent = Math.round(((index + 1) * 100) / steps.length);
|
|
21
|
+
stream.write(pretty ? `[${percent}%] ${message}\n` : `${JSON.stringify({ event: 'dry_run_progress', command, percent, stage, message })}\n`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function plannedChange(command, pretty, depth, siteUrl, request, message, rows, plan) {
|
|
25
|
+
return pretty
|
|
26
|
+
? prettyResult(0, depth, command, message, [['Server', siteUrl], ...rows, ['Request', `POST ${request.url}`]])
|
|
27
|
+
: agentResult(0, { command, siteUrl, dryRun: true, applied: false, plan, request: { method: 'POST', ...request } });
|
|
28
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createCipheriv, createHash, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from 'node:crypto';
|
|
2
|
+
import { parseEnv } from 'node:util';
|
|
3
|
+
export const ENV_COUNT_MAX = 200;
|
|
4
|
+
export const ENV_FILE_MAX = 48 * 1024;
|
|
5
|
+
export const ENV_SEALED_MAX = 100_000;
|
|
6
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
7
|
+
const RESERVED = ['PATH', 'HOME', 'PORT', 'PWD', 'OLDPWD', 'SHELL', 'USER', 'LOGNAME', 'IFS', 'ENV', 'BASH_ENV', 'PS4'];
|
|
8
|
+
const PUBLIC_KEY = /^[0-9a-f]{64}$/;
|
|
9
|
+
const X25519_SPKI = Buffer.from('302a300506032b656e032100', 'hex');
|
|
10
|
+
const INFO = 'dd-env-v1';
|
|
11
|
+
const randomSource = { key: () => generateKeyPairSync('x25519').privateKey, nonce: () => randomBytes(12) };
|
|
12
|
+
export const validEnvName = (name) => NAME.test(name) && !RESERVED.includes(name) && !name.startsWith('LD_');
|
|
13
|
+
export const envKid = (publicKey) => createHash('sha256').update(Buffer.from(publicKey, 'hex')).digest('hex').slice(0, 16);
|
|
14
|
+
export const validSeal = (value) => {
|
|
15
|
+
const seal = value;
|
|
16
|
+
return typeof seal?.publicKey === 'string' && PUBLIC_KEY.test(seal.publicKey) && seal.kid === envKid(seal.publicKey)
|
|
17
|
+
&& typeof seal.context === 'string' && /^projects\/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(seal.context);
|
|
18
|
+
};
|
|
19
|
+
const shellSize = (vars) => Object.entries(vars)
|
|
20
|
+
.reduce((size, [name, value]) => size + Buffer.byteLength(`export ${name}='${value.replaceAll("'", `'\\''`)}'\n`), 0);
|
|
21
|
+
export function readEnv(text) {
|
|
22
|
+
let vars;
|
|
23
|
+
try {
|
|
24
|
+
vars = { ...parseEnv(text.replace(/^/, '')) };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { error: 'The env file could not be parsed. Use KEY=value lines.' };
|
|
28
|
+
}
|
|
29
|
+
const names = Object.keys(vars);
|
|
30
|
+
if (names.length === 0)
|
|
31
|
+
return { error: 'The env file has no variables. Use deepdynamic projects env clear to remove all variables.' };
|
|
32
|
+
if (names.length > ENV_COUNT_MAX)
|
|
33
|
+
return { error: `The env file has ${names.length} variables; at most ${ENV_COUNT_MAX} are allowed.` };
|
|
34
|
+
const invalid = names.find((name) => !validEnvName(name));
|
|
35
|
+
if (invalid !== undefined) {
|
|
36
|
+
return { error: `${JSON.stringify(invalid)} is not allowed. Names must match [A-Za-z_][A-Za-z0-9_]* (up to 128 characters) and must not be ${RESERVED.join(', ')} or start with LD_.` };
|
|
37
|
+
}
|
|
38
|
+
if (Object.values(vars).some((value) => value.includes('\0')))
|
|
39
|
+
return { error: 'Values must not contain NUL characters.' };
|
|
40
|
+
if (shellSize(vars) > ENV_FILE_MAX)
|
|
41
|
+
return { error: `The variables are larger than ${ENV_FILE_MAX} bytes.` };
|
|
42
|
+
return { vars };
|
|
43
|
+
}
|
|
44
|
+
export function sealEnv(vars, seal, source = randomSource) {
|
|
45
|
+
const recipient = Buffer.from(seal.publicKey, 'hex');
|
|
46
|
+
const privateKey = source.key();
|
|
47
|
+
const ephemeral = createPublicKey(privateKey).export({ format: 'der', type: 'spki' }).subarray(X25519_SPKI.length);
|
|
48
|
+
const shared = diffieHellman({ privateKey, publicKey: createPublicKey({ key: Buffer.concat([X25519_SPKI, recipient]), format: 'der', type: 'spki' }) });
|
|
49
|
+
const key = Buffer.from(hkdfSync('sha256', shared, Buffer.concat([ephemeral, recipient]), INFO, 32));
|
|
50
|
+
const nonce = source.nonce();
|
|
51
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce);
|
|
52
|
+
cipher.setAAD(Buffer.from(`${INFO}\n${seal.context}`));
|
|
53
|
+
const body = Buffer.concat([cipher.update(JSON.stringify(vars), 'utf8'), cipher.final(), cipher.getAuthTag()]);
|
|
54
|
+
return ['dde1', seal.kid, ephemeral.toString('base64url'), nonce.toString('base64url'), body.toString('base64url')].join('.');
|
|
55
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { optionSuggestion } from "./flags.js";
|
|
2
|
+
const RETRYABLE = [
|
|
3
|
+
'connection_failed', 'connection_timeout', 'rate_limited', 'backend_unavailable', 'server_updating', 'server_busy', 'publish_timeout', 'deploy_stopped',
|
|
4
|
+
'upload_failed', 'repository_failed', 'invalid_repository', 'unexpected_response', 'git_verification_failed',
|
|
5
|
+
'login_timeout', 'login_failed', 'token_exchange_failed', 'account_fetch_failed'
|
|
6
|
+
];
|
|
7
|
+
const NEXT = [
|
|
8
|
+
[['login_required', 'login_timeout', 'login_failed', 'token_exchange_failed', 'account_fetch_failed'], () => 'deepdynamic login'],
|
|
9
|
+
[['unknown_command', 'unknown_option'], () => 'deepdynamic --help'],
|
|
10
|
+
[['unknown_subcommand', 'invalid_arguments'], ({ command }) => command ? `deepdynamic ${command} --help` : 'deepdynamic --help'],
|
|
11
|
+
[['agent_required', 'invalid_manifest'], () => 'deepdynamic projects deploy --help'],
|
|
12
|
+
[['project_not_found'], () => 'deepdynamic projects'],
|
|
13
|
+
[['project_taken'], () => 'deepdynamic projects create --help'],
|
|
14
|
+
[['server_pending'], ({ project }) => `deepdynamic projects status ${project}`],
|
|
15
|
+
[['server_failed'], () => 'deepdynamic support contact --help'],
|
|
16
|
+
[['publish_pending', 'upload_unverified', 'progress_unavailable'], ({ id }) => id ? `deepdynamic deployments ${id}` : null],
|
|
17
|
+
[['commit_not_found', 'deployment_not_found'], ({ project }) => project ? `deepdynamic projects history ${project}` : null]
|
|
18
|
+
];
|
|
19
|
+
export function errorHints(data) {
|
|
20
|
+
const error = data.error;
|
|
21
|
+
const id = data.progress?.id;
|
|
22
|
+
const next = NEXT.find(([codes]) => codes.includes(error.code))?.[1]({ command: data.command, project: data.project, id }) ?? null;
|
|
23
|
+
const retryable = error.retryable ?? (error.code === 'progress_unavailable' ? !id : RETRYABLE.includes(error.code));
|
|
24
|
+
const suggestion = error.code === 'invalid_arguments' && typeof data.usage === 'string' ? optionSuggestion(error.message, data.usage) : null;
|
|
25
|
+
return { error: { ...error, ...(next ? { next } : {}), retryable }, ...(suggestion ? { suggestions: [suggestion] } : {}) };
|
|
26
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { closest } from "./suggest.js";
|
|
2
|
+
const UNKNOWN_OPTION = /^Unknown option: (-.*)$/;
|
|
3
|
+
const COMMAND_OPTIONS = ['--help', '--pretty', '--login-timeout'];
|
|
4
|
+
export function unknownArgument(arg) {
|
|
5
|
+
return `Unknown ${arg.startsWith('-') ? 'option' : 'argument'}: ${arg}`;
|
|
6
|
+
}
|
|
7
|
+
export function optionSuggestion(message, usage) {
|
|
8
|
+
const option = UNKNOWN_OPTION.exec(message)?.[1].split('=')[0];
|
|
9
|
+
return option ? closest(option, [...new Set([...(usage.match(/--[a-z][a-z-]*/g) ?? []), ...COMMAND_OPTIONS])]) : null;
|
|
10
|
+
}
|
|
11
|
+
export function parseFlags(args, flags) {
|
|
12
|
+
const entries = [];
|
|
13
|
+
for (let index = 0; index < args.length; index++) {
|
|
14
|
+
const arg = args[index];
|
|
15
|
+
const flag = flags.find((name) => arg === name || arg.startsWith(`${name}=`));
|
|
16
|
+
if (!flag) {
|
|
17
|
+
return { error: unknownArgument(arg) };
|
|
18
|
+
}
|
|
19
|
+
const value = arg === flag ? args[++index] : arg.slice(flag.length + 1);
|
|
20
|
+
if (value === undefined || !value.trim()) {
|
|
21
|
+
return { error: missingValue(flag) };
|
|
22
|
+
}
|
|
23
|
+
entries.push([flag, value]);
|
|
24
|
+
}
|
|
25
|
+
return { entries };
|
|
26
|
+
}
|
|
27
|
+
export function parseCommand(args, flags) {
|
|
28
|
+
const names = [];
|
|
29
|
+
const entries = [];
|
|
30
|
+
for (let index = 0; index < args.length; index++) {
|
|
31
|
+
const arg = args[index];
|
|
32
|
+
if (!arg.startsWith('-')) {
|
|
33
|
+
names.push(arg);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const flag = flags.find((name) => arg === name || arg.startsWith(`${name}=`));
|
|
37
|
+
if (!flag)
|
|
38
|
+
return { error: unknownArgument(arg) };
|
|
39
|
+
const value = arg !== flag ? arg.slice(flag.length + 1) : args[index + 1]?.startsWith('-') ? undefined : args[++index];
|
|
40
|
+
if (value === undefined || !value.trim())
|
|
41
|
+
return { error: missingValue(flag) };
|
|
42
|
+
entries.push([flag, value]);
|
|
43
|
+
}
|
|
44
|
+
return { names, entries };
|
|
45
|
+
}
|
|
46
|
+
function missingValue(flag) {
|
|
47
|
+
return `${flag} requires a value.`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { displayWidth } from "../pretty.js";
|
|
2
|
+
const wordmark = [
|
|
3
|
+
'// ____ ____ _ ____ _ _',
|
|
4
|
+
'// | _ \\ ___ ___ _ __ | _ \\ _ _ _ __ __ _ _ __ ___ (_) ___ / ___| | ___ _ _ __| |',
|
|
5
|
+
'// | | | |/ _ \\/ _ \\ \'_ \\| | | | | | | \'_ \\ / _` | \'_ ` _ \\| |/ __| | | | |/ _ \\| | | |/ _` |',
|
|
6
|
+
'// | |_| | __/ __/ |_) | |_| | |_| | | | | (_| | | | | | | | (__ | |___| | (_) | |_| | (_| |',
|
|
7
|
+
'// |____/ \\___|\\___| .__/|____/ \\__, |_| |_|\\__,_|_| |_| |_|_|\\___| \\____|_|\\___/ \\__,_|\\__,_|',
|
|
8
|
+
'// |_| |___/'
|
|
9
|
+
];
|
|
10
|
+
export function startLoginScreen(url, stream) {
|
|
11
|
+
if (!stream?.isTTY || process.env.TERM === 'dumb')
|
|
12
|
+
return;
|
|
13
|
+
const columns = stream.columns || 80;
|
|
14
|
+
const rows = stream.rows || 24;
|
|
15
|
+
const depth = stream.getColorDepth?.() ?? 1;
|
|
16
|
+
const style = (codes, text) => depth > 1 ? `\x1b[${codes}m${text}\x1b[0m` : text;
|
|
17
|
+
const blue = depth >= 24 ? '38;2;97;121;139' : depth >= 8 ? '38;5;67' : '34';
|
|
18
|
+
const warm = depth >= 24 ? '38;2;198;172;140' : depth >= 8 ? '38;5;180' : '33';
|
|
19
|
+
const wordmarkWidth = Math.max(...wordmark.map(displayWidth));
|
|
20
|
+
const logo = wordmark.map((line) => `${style(blue, line.slice(0, 2))}${style('1', line.slice(2))}`);
|
|
21
|
+
const rail = (shape, text = '') => ` ${style(blue, shape)}${text && ` ${text}`}`;
|
|
22
|
+
const wrap = (shape, text, tone = (line) => line) => {
|
|
23
|
+
const lines = [''];
|
|
24
|
+
for (const word of text.split(' ')) {
|
|
25
|
+
const last = lines.length - 1;
|
|
26
|
+
const next = lines[last] ? `${lines[last]} ${word}` : word;
|
|
27
|
+
if (!lines[last] || displayWidth(next) <= columns - 6)
|
|
28
|
+
lines[last] = next;
|
|
29
|
+
else
|
|
30
|
+
lines.push(word);
|
|
31
|
+
}
|
|
32
|
+
return lines.map((line, index) => rail(index ? '│' : shape, tone(line)));
|
|
33
|
+
};
|
|
34
|
+
const link = (text) => `\x1b]8;id=dd-login;${url}\x1b\\${text}\x1b]8;;\x1b\\`;
|
|
35
|
+
const urlLines = url.match(new RegExp(`.{1,${Math.max(1, columns - 6)}}`, 'g')).map((part) => rail('│', link(part)));
|
|
36
|
+
const status = `${style(warm, '●')} ${style('1', 'Logging in')}`;
|
|
37
|
+
const render = (compact) => [
|
|
38
|
+
...(compact ? [
|
|
39
|
+
` ${style(blue, '//')} ${style('1', 'DeepDynamic Cloud')}`,
|
|
40
|
+
rail('╭', status)
|
|
41
|
+
] : [
|
|
42
|
+
'',
|
|
43
|
+
...logo.map((line) => ` ${line}`),
|
|
44
|
+
'',
|
|
45
|
+
rail('╭', `${style('2', 'CLI / Account link')} ${status}`),
|
|
46
|
+
rail('│')
|
|
47
|
+
]),
|
|
48
|
+
...wrap('├', 'Finish logging in in your browser.'),
|
|
49
|
+
...wrap('│', 'If the browser does not open, open this URL yourself.', (line) => style('2', line)),
|
|
50
|
+
...urlLines,
|
|
51
|
+
...(compact ? [] : [rail('│')]),
|
|
52
|
+
rail('╰', style('2', 'Ctrl+C to cancel'))
|
|
53
|
+
];
|
|
54
|
+
const height = (lines) => lines.reduce((total, line) => total + Math.max(1, Math.ceil(displayWidth(line) / columns)), 0);
|
|
55
|
+
let lines = render(columns < wordmarkWidth + 4);
|
|
56
|
+
if (height(lines) >= rows)
|
|
57
|
+
lines = render(true);
|
|
58
|
+
if (height(lines) >= rows || columns < 24)
|
|
59
|
+
return;
|
|
60
|
+
const screen = lines.join('\r\n');
|
|
61
|
+
let stopped = false;
|
|
62
|
+
const stop = () => {
|
|
63
|
+
if (stopped)
|
|
64
|
+
return;
|
|
65
|
+
stopped = true;
|
|
66
|
+
process.removeListener('exit', stop);
|
|
67
|
+
process.removeListener('SIGTERM', terminate);
|
|
68
|
+
stream.write('\x1b[?1049l\x1b[?25h');
|
|
69
|
+
};
|
|
70
|
+
const terminate = () => {
|
|
71
|
+
stop();
|
|
72
|
+
process.exit(143);
|
|
73
|
+
};
|
|
74
|
+
process.once('exit', stop);
|
|
75
|
+
process.once('SIGTERM', terminate);
|
|
76
|
+
stream.write(`\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H${screen}`);
|
|
77
|
+
return stop;
|
|
78
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { parseFlags } from "./flags.js";
|
|
2
|
+
const PAGE = /^[1-9]\d{0,5}$/;
|
|
3
|
+
export function parsePage(args) {
|
|
4
|
+
const parsed = parseFlags(args, ['--page']);
|
|
5
|
+
if ('error' in parsed)
|
|
6
|
+
return parsed;
|
|
7
|
+
const values = parsed.entries.map(([, value]) => value);
|
|
8
|
+
const [page = '1'] = values;
|
|
9
|
+
if (values.length > 1 || !PAGE.test(page))
|
|
10
|
+
return { error: 'Give --page once, as a positive integer.' };
|
|
11
|
+
return Number(page);
|
|
12
|
+
}
|
|
13
|
+
export function pagination({ total, page, pageSize, totalPages }, command) {
|
|
14
|
+
return { total, page, pageSize, totalPages, next: Number.isSafeInteger(page) && Number.isSafeInteger(totalPages) && page < totalPages ? `deepdynamic ${command} --page ${page + 1}` : null };
|
|
15
|
+
}
|
|
16
|
+
export function pageRows({ total, page, totalPages, next }) {
|
|
17
|
+
return [['Page', `${page} / ${totalPages} (${total} total)`], ...(next ? [['Next', next]] : [])];
|
|
18
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const PROJECT = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { SITE_URL } from "../metadata.js";
|
|
2
|
+
let development = false;
|
|
3
|
+
export function setDevelopmentRun(enabled) {
|
|
4
|
+
development = enabled;
|
|
5
|
+
}
|
|
6
|
+
export const developmentRun = () => development;
|
|
7
|
+
export const allowedServer = (origin) => development || origin === SITE_URL;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { SITE_URL } from "../metadata.js";
|
|
2
|
+
import { unknownArgument } from "./flags.js";
|
|
3
|
+
import { allowedServer } from "./run-mode.js";
|
|
4
|
+
export const SERVER_OPTION = '--server';
|
|
5
|
+
export function parseServerArgs(args) {
|
|
6
|
+
let siteUrl = null;
|
|
7
|
+
for (let index = 0; index < args.length; index++) {
|
|
8
|
+
const arg = args[index];
|
|
9
|
+
const inline = arg.startsWith(`${SERVER_OPTION}=`);
|
|
10
|
+
if (arg !== SERVER_OPTION && !inline) {
|
|
11
|
+
return { error: unknownArgument(arg) };
|
|
12
|
+
}
|
|
13
|
+
const value = inline ? arg.slice(SERVER_OPTION.length + 1) : (args[++index] ?? '');
|
|
14
|
+
const url = URL.canParse(value) ? new URL(value) : null;
|
|
15
|
+
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
|
|
16
|
+
return {
|
|
17
|
+
error: `${SERVER_OPTION} requires a URL starting with http:// or https://${value ? `: ${value}` : ''}`
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
if (!allowedServer(url.origin)) {
|
|
21
|
+
return {
|
|
22
|
+
error: `The released CLI only accepts ${SERVER_OPTION} ${SITE_URL}. Other servers work only in development runs from the repository (pnpm cli): ${value}`
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
siteUrl = url.origin;
|
|
26
|
+
}
|
|
27
|
+
return { siteUrl };
|
|
28
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { paint } from "../pretty.js";
|
|
2
|
+
export function startSpinner(message, stream = process.stderr) {
|
|
3
|
+
if (!stream.isTTY)
|
|
4
|
+
return () => { };
|
|
5
|
+
const { accent } = paint(stream.getColorDepth?.() ?? 1);
|
|
6
|
+
const frames = ['┤', '┘', '┴', '└', '├', '┌', '┬', '┐'];
|
|
7
|
+
let frame = 0;
|
|
8
|
+
const text = typeof message === 'string' ? () => message : message;
|
|
9
|
+
const clear = typeof message === 'string' ? '' : '\x1b[2K';
|
|
10
|
+
const draw = () => stream.write(`\r${clear}${accent(frames[frame++ % frames.length])} ${text()}`);
|
|
11
|
+
draw();
|
|
12
|
+
const timer = setInterval(draw, 100);
|
|
13
|
+
return () => {
|
|
14
|
+
clearInterval(timer);
|
|
15
|
+
stream.write('\r\x1b[2K');
|
|
16
|
+
};
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const SUGGEST_DISTANCE = 2;
|
|
2
|
+
function distance(a, b) {
|
|
3
|
+
const rows = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
|
|
4
|
+
for (let i = 1; i <= a.length; i++) {
|
|
5
|
+
for (let j = 1; j <= b.length; j++) {
|
|
6
|
+
rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
7
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
|
|
8
|
+
rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return rows[a.length][b.length];
|
|
12
|
+
}
|
|
13
|
+
export function closest(input, candidates) {
|
|
14
|
+
let best = null;
|
|
15
|
+
let bestDistance = SUGGEST_DISTANCE + 1;
|
|
16
|
+
for (const candidate of candidates.filter((name) => name !== input)) {
|
|
17
|
+
const value = distance(input, candidate);
|
|
18
|
+
if (value < bestDistance)
|
|
19
|
+
[best, bestDistance] = [candidate, value];
|
|
20
|
+
}
|
|
21
|
+
return best;
|
|
22
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { SITE_URL } from "../metadata.js";
|
|
2
|
+
export const CONTACT_PAGE = `${SITE_URL}/contact`;
|
|
3
|
+
export const SUPPORT_EMAIL = 'mail@deepdynamic.net';
|
|
4
|
+
export const SUPPORT_HELP = `Contact support with the error code: deepdynamic support contact, ${CONTACT_PAGE} or ${SUPPORT_EMAIL}.`;
|
|
5
|
+
export const supportMessage = (code, note) => `Error ${code}.${note ? ` ${note}` : ''} Contact support with this code: deepdynamic support contact, ${CONTACT_PAGE} or ${SUPPORT_EMAIL}.`;
|
|
6
|
+
export function supportFailure(code, options = {}) {
|
|
7
|
+
return {
|
|
8
|
+
code,
|
|
9
|
+
message: supportMessage(code, options.note),
|
|
10
|
+
display: supportMessage(code, options.note),
|
|
11
|
+
...(options.retryable === undefined ? {} : { retryable: options.retryable })
|
|
12
|
+
};
|
|
13
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
export async function readText(flag, text, path) {
|
|
3
|
+
const fileFlag = `${flag}-file`;
|
|
4
|
+
if (text !== undefined && path !== undefined) {
|
|
5
|
+
return { error: `Give either ${flag} or ${fileFlag}, not both.` };
|
|
6
|
+
}
|
|
7
|
+
if (path === undefined) {
|
|
8
|
+
return text === undefined ? { error: `${flag} or ${fileFlag} is required.` } : { text };
|
|
9
|
+
}
|
|
10
|
+
let content;
|
|
11
|
+
try {
|
|
12
|
+
content = await readFile(path, 'utf8');
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
const reason = error.code ?? String(error);
|
|
16
|
+
return { error: `Cannot read the ${fileFlag} file (${reason}): ${path}` };
|
|
17
|
+
}
|
|
18
|
+
const stripped = content.replace(/^/, '').replace(/\r?\n$/, '');
|
|
19
|
+
return stripped.trim() ? { text: stripped } : { error: `The ${fileFlag} file is empty: ${path}` };
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const TIMEOUT_OPTION = '--timeout';
|
|
2
|
+
export const LOGIN_TIMEOUT_OPTION = '--login-timeout';
|
|
3
|
+
export function parseTimeout(args, maxSeconds, option = TIMEOUT_OPTION, minSeconds = 0) {
|
|
4
|
+
const rest = [];
|
|
5
|
+
const values = [];
|
|
6
|
+
for (let index = 0; index < args.length; index++) {
|
|
7
|
+
const arg = args[index];
|
|
8
|
+
if (arg === option)
|
|
9
|
+
values.push(args[++index] ?? '');
|
|
10
|
+
else if (arg.startsWith(`${option}=`))
|
|
11
|
+
values.push(arg.slice(option.length + 1));
|
|
12
|
+
else
|
|
13
|
+
rest.push(arg);
|
|
14
|
+
}
|
|
15
|
+
if (values.length === 0)
|
|
16
|
+
return { rest, waitMs: maxSeconds * 1000 };
|
|
17
|
+
const seconds = Number(values[0]);
|
|
18
|
+
if (values.length > 1 || !/^\d+$/.test(values[0]) || seconds < minSeconds || seconds > maxSeconds) {
|
|
19
|
+
return { error: `Give ${option} once, as whole seconds from ${minSeconds} to ${maxSeconds}.` };
|
|
20
|
+
}
|
|
21
|
+
return { rest, waitMs: seconds * 1000 };
|
|
22
|
+
}
|