@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.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +32 -2
  3. package/THIRD_PARTY_NOTICES.txt +102 -0
  4. package/dist/agents/content.js +12 -0
  5. package/dist/agents/edit.js +140 -0
  6. package/dist/agents/install.js +190 -0
  7. package/dist/agents/refresh.js +20 -0
  8. package/dist/agents/setup.js +29 -0
  9. package/dist/agents/targets.js +91 -0
  10. package/dist/auth/credentials.js +63 -0
  11. package/dist/auth/session.js +49 -0
  12. package/dist/cli.js +198 -0
  13. package/dist/commands/account.js +96 -0
  14. package/dist/commands/activity.js +80 -0
  15. package/dist/commands/blocked.js +89 -0
  16. package/dist/commands/deploy/agents.js +11 -0
  17. package/dist/commands/deploy/files.js +62 -0
  18. package/dist/commands/deploy/index.js +95 -0
  19. package/dist/commands/deploy/manifest.js +24 -0
  20. package/dist/commands/deploy/minify.js +27 -0
  21. package/dist/commands/deploy/progress.js +85 -0
  22. package/dist/commands/deploy/ship.js +117 -0
  23. package/dist/commands/deploy/upload.js +125 -0
  24. package/dist/commands/deployments.js +60 -0
  25. package/dist/commands/dns.js +777 -0
  26. package/dist/commands/domains.js +639 -0
  27. package/dist/commands/emails.js +74 -0
  28. package/dist/commands/env.js +194 -0
  29. package/dist/commands/help.js +148 -0
  30. package/dist/commands/keys.js +263 -0
  31. package/dist/commands/login/flow.js +155 -0
  32. package/dist/commands/login/index.js +26 -0
  33. package/dist/commands/logout.js +71 -0
  34. package/dist/commands/mail.js +241 -0
  35. package/dist/commands/notifications.js +133 -0
  36. package/dist/commands/plan.js +355 -0
  37. package/dist/commands/projects.js +838 -0
  38. package/dist/commands/reference.js +2187 -0
  39. package/dist/commands/search.js +86 -0
  40. package/dist/commands/server.js +301 -0
  41. package/dist/commands/sessions.js +114 -0
  42. package/dist/commands/sites.js +102 -0
  43. package/dist/commands/sms.js +65 -0
  44. package/dist/commands/status.js +87 -0
  45. package/dist/commands/support.js +115 -0
  46. package/dist/commands/update.js +100 -0
  47. package/dist/commands/usage.js +51 -0
  48. package/dist/commands/verify.js +149 -0
  49. package/dist/commands/version.js +6 -0
  50. package/dist/guide.js +37 -0
  51. package/dist/http/call.js +6 -0
  52. package/dist/http/request.js +54 -0
  53. package/dist/index.js +11 -0
  54. package/dist/metadata.js +4 -0
  55. package/dist/output.js +9 -0
  56. package/dist/pretty.js +70 -0
  57. package/dist/refresh-skills.js +5 -0
  58. package/dist/registry.js +688 -0
  59. package/dist/runtime/browser.js +15 -0
  60. package/dist/runtime/card-request.js +55 -0
  61. package/dist/runtime/confirm.js +21 -0
  62. package/dist/runtime/development.js +13 -0
  63. package/dist/runtime/domain-name.js +5 -0
  64. package/dist/runtime/dry-run.js +28 -0
  65. package/dist/runtime/env-file.js +55 -0
  66. package/dist/runtime/error-hints.js +26 -0
  67. package/dist/runtime/flags.js +48 -0
  68. package/dist/runtime/login-screen.js +78 -0
  69. package/dist/runtime/page.js +18 -0
  70. package/dist/runtime/project-name.js +1 -0
  71. package/dist/runtime/run-mode.js +7 -0
  72. package/dist/runtime/server-options.js +28 -0
  73. package/dist/runtime/spinner.js +17 -0
  74. package/dist/runtime/suggest.js +22 -0
  75. package/dist/runtime/support.js +13 -0
  76. package/dist/runtime/text-file.js +20 -0
  77. package/dist/runtime/timeout.js +22 -0
  78. package/dist/runtime/update-check.js +158 -0
  79. package/dist/runtime/update-install.js +80 -0
  80. package/dist/runtime/usage-error.js +9 -0
  81. package/dist/setup-agents.js +15 -0
  82. package/dist/site.js +1 -0
  83. package/dist/update-refresh.js +5 -0
  84. package/package.json +46 -3
@@ -0,0 +1,86 @@
1
+ import { readLoginSiteUrl } from "../auth/credentials.js";
2
+ import { UNEXPECTED, defaultDeps, failureError, httpFailure, request } from "../http/request.js";
3
+ import { SITE_URL } from "../metadata.js";
4
+ import { agentResult } from "../output.js";
5
+ import { CONTROL, prettyResult } from "../pretty.js";
6
+ import { spec } from "../registry.js";
7
+ import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
8
+ import { parseServerArgs } from "../runtime/server-options.js";
9
+ export const SEARCH_PATH = '/api/v1/search';
10
+ const { name: command, usage } = spec('search');
11
+ function isPageInfo(body) {
12
+ const info = body;
13
+ return info?.ok === true
14
+ && typeof info.page === 'string'
15
+ && typeof info.url === 'string'
16
+ && typeof info.markdown === 'string';
17
+ }
18
+ function searchablePages(body) {
19
+ const pages = body?.pages;
20
+ return Array.isArray(pages) && pages.every((page) => typeof page === 'string') ? pages : null;
21
+ }
22
+ function normalizePage(raw) {
23
+ const segments = [];
24
+ for (const segment of raw.split('/')) {
25
+ if (segment === '..')
26
+ segments.pop();
27
+ else if (segment && segment !== '.')
28
+ segments.push(segment);
29
+ }
30
+ return `/${segments.join('/')}`;
31
+ }
32
+ const searchUrl = (page, siteUrl) => new URL(`${SEARCH_PATH}${page.split('/').filter(Boolean).map((segment) => `/${encodeURIComponent(segment)}`).join('')}`, siteUrl);
33
+ function parseSearchArgs(args) {
34
+ const first = args[0];
35
+ if (first === undefined || first.startsWith('-') || !first.trim()) {
36
+ return { error: 'A page path is required, for example: deepdynamic search /pricing' };
37
+ }
38
+ const server = parseServerArgs(args.slice(1));
39
+ return 'error' in server ? server : { page: normalizePage(first), siteUrl: server.siteUrl };
40
+ }
41
+ export async function runSearch(args, pretty, depth, deps = defaultDeps()) {
42
+ const { args: rest, dryRun } = splitDryRun(args);
43
+ const options = parseSearchArgs(rest);
44
+ if ('error' in options) {
45
+ return pretty
46
+ ? prettyResult(2, depth, command, options.error, [['Usage', usage]])
47
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: options.error }, usage });
48
+ }
49
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
50
+ const endpoint = searchUrl(options.page, siteUrl);
51
+ if (dryRun)
52
+ return plannedRequest(command, pretty, depth, siteUrl, endpoint.href);
53
+ const result = await request(endpoint.href, { method: 'GET' }, deps, pretty ? 'Loading page info.' : null);
54
+ if ('failure' in result || result.status !== 200 || !isPageInfo(result.body)) {
55
+ const pages = 'failure' in result || result.status !== 404 ? null : searchablePages(result.body);
56
+ const failure = 'failure' in result
57
+ ? result.failure
58
+ : result.status === 404
59
+ ? { code: 'page_not_found', message: `No searchable page at ${options.page}.`, display: `No searchable page at ${options.page}.` }
60
+ : result.status !== 200
61
+ ? httpFailure(result.status)
62
+ : UNEXPECTED;
63
+ return pretty
64
+ ? prettyResult(1, depth, command, 'Could not load page info.', [
65
+ ['Server', siteUrl],
66
+ ['Page', options.page],
67
+ ['Reason', failure.display],
68
+ ...(pages ? [['Searchable', pages.join(', ')]] : [])
69
+ ])
70
+ : agentResult(1, {
71
+ command,
72
+ siteUrl,
73
+ page: options.page,
74
+ error: { ...failureError(failure), ...(pages ? { pages } : {}) }
75
+ });
76
+ }
77
+ const { page, url, markdown } = result.body;
78
+ if (!pretty) {
79
+ return agentResult(0, { command, siteUrl, page, url, markdown });
80
+ }
81
+ return prettyResult(0, depth, command, `Loaded page info for ${page.replace(CONTROL, ' ')}.`, [
82
+ ['Server', siteUrl],
83
+ ['URL', url.replace(CONTROL, ' ')],
84
+ ...markdown.trimEnd().split('\n').map((line) => ['', line.replace(CONTROL, ' ')])
85
+ ]);
86
+ }
@@ -0,0 +1,301 @@
1
+ import { defaultAuthDeps } from "../auth/session.js";
2
+ import { httpFailure } from "../http/request.js";
3
+ import { agentResult } from "../output.js";
4
+ import { prettyResult } from "../pretty.js";
5
+ import { confirmationRequired } from "../runtime/confirm.js";
6
+ import { plannedChange, plannedRequest } from "../runtime/dry-run.js";
7
+ import { parseFlags, unknownArgument } from "../runtime/flags.js";
8
+ import { spec } from "../registry.js";
9
+ import { PROJECT } from "../runtime/project-name.js";
10
+ import { supportFailure } from "../runtime/support.js";
11
+ import { rehearsed } from "./dns.js";
12
+ export const SERVER_PATH = '/api/v1/aircraft';
13
+ const CORES = ['1', '2', '4', '8'];
14
+ const MEMORIES = ['1', '2', '4', '8'];
15
+ const CORE_PRICE = 5000;
16
+ const MEMORY_PRICE = 3000;
17
+ const AUTOPILOT_LIMITS = [50000, 100000, 200000, 300000];
18
+ const STARTING_LIMIT = AUTOPILOT_LIMITS[1];
19
+ const LIST = spec('server');
20
+ const SET = spec('server set');
21
+ const AUTOPILOT = spec('server autopilot');
22
+ const RESTART = 'Applying restarts the server, so the site stops for about a minute. A stopped server picks up the change the next time it starts.';
23
+ const SERVER_STATES = { running: 'Running', stopped: 'Stopped', preparing: 'Preparing', failed: 'Setup failed' };
24
+ const failure = (code, message) => ({ code, message, display: message });
25
+ const PROJECT_NOT_FOUND = failure('project_not_found', 'You have no active project with that name. Check it with deepdynamic server.');
26
+ const SERVER_UNAVAILABLE = supportFailure('server_unavailable', { note: 'Nothing was changed.' });
27
+ const UNREACHABLE = supportFailure('server_unreachable', { note: 'Nothing was read or changed.' });
28
+ const LIST_FAILURES = {
29
+ server_unreachable: UNREACHABLE,
30
+ list_failed: supportFailure('list_failed')
31
+ };
32
+ const AUTOPILOT_UNPAID = failure('unpaid_charges', 'The account has unpaid charges, so autopilot was not turned on. Pay them with deepdynamic plan pay, then run the same command again.');
33
+ const SET_FAILURES = {
34
+ server_unreachable: UNREACHABLE,
35
+ autopilot_on: failure('autopilot_on', 'Autopilot is on, so the spec cannot be changed by hand. Turn it off first with deepdynamic server autopilot off.'),
36
+ server_not_ready: failure('server_not_ready', 'The project server is not ready yet. Check it with deepdynamic server and retry once it is running or stopped.'),
37
+ server_busy: failure('server_busy', 'The server is busy with a restart, update or deploy, or cannot take more CPU or RAM right now. Retry later.'),
38
+ cpu_too_small: failure('cpu_too_small', 'With that few cores the current CPU use would go over 100%. Keep more cores.'),
39
+ memory_too_small: failure('memory_too_small', 'The server uses more RAM than that. Keep more RAM.'),
40
+ unpaid_charges: failure('unpaid_charges', 'The account has unpaid charges, so the spec was not raised and nothing was charged. Pay them with deepdynamic plan pay, then run the same command again.'),
41
+ charge_pending: failure('charge_pending', 'A server options payment or another spec change is still in progress, so nothing was charged or changed. Retry a little later.'),
42
+ payment_declined: failure('payment_declined', 'The card company declined the payment for the difference, so nothing was charged or changed. Ask the user to check the card or register another one, then run the same command again.'),
43
+ payment_unavailable: supportFailure('payment_unavailable', { note: 'Nothing was charged or changed.' })
44
+ };
45
+ const LIST_STEPS = [
46
+ { stage: 'check_options', message: 'Checking the options.' },
47
+ { stage: 'prepare_request', message: 'Preparing the server list request.' }
48
+ ];
49
+ const SET_STEPS = [
50
+ { stage: 'check_options', message: 'Checking the CPU and RAM options.' },
51
+ { stage: 'calculate_charge', message: 'Calculating the monthly extra charge after the change.' },
52
+ { stage: 'check_consent', message: 'Checking consent to the extra charge.' },
53
+ { stage: 'prepare_request', message: 'Preparing the server spec change request.' }
54
+ ];
55
+ const autopilotSteps = (enabled) => [
56
+ { stage: 'check_options', message: 'Checking the autopilot setting.' },
57
+ enabled
58
+ ? { stage: 'check_limit', message: 'Checking the monthly limit.' }
59
+ : { stage: 'check_manual_control', message: 'Checking the switch to manual spec changes.' },
60
+ { stage: 'prepare_request', message: 'Preparing the autopilot request.' }
61
+ ];
62
+ const won = (amount) => `${amount.toLocaleString('en-US')} KRW`;
63
+ const monthly = (amount) => `${won(amount)}/month`;
64
+ const price = (amount) => amount ? `+${monthly(amount)}` : 'No extra charge';
65
+ const extraOf = (cores, memory) => (cores - 1) * CORE_PRICE + (memory - 1) * MEMORY_PRICE;
66
+ const coreCount = (cores) => `${cores} ${cores === 1 ? 'core' : 'cores'}`;
67
+ const specText = (cores, memory) => `CPU ${coreCount(cores)} · RAM ${memory}GB`;
68
+ const count = (amount, noun) => `${amount} ${noun}${amount === 1 ? '' : 's'}`;
69
+ function pickFlags(args, flags) {
70
+ const parsed = parseFlags(args, flags);
71
+ if ('error' in parsed)
72
+ return parsed;
73
+ const repeated = parsed.entries.find(([flag], index) => parsed.entries.findIndex(([other]) => other === flag) !== index);
74
+ if (repeated)
75
+ return { error: `Give ${repeated[0]} only once.` };
76
+ return { values: Object.fromEntries(parsed.entries) };
77
+ }
78
+ function oneOf(flag, value, choices) {
79
+ if (value === undefined)
80
+ return {};
81
+ if (choices.includes(value))
82
+ return { value: Number(value) };
83
+ return { error: `${flag} must be one of ${choices.join(', ')}: ${value}` };
84
+ }
85
+ function parseSet(args) {
86
+ const [project, ...rest] = args.filter((arg) => arg !== '--yes');
87
+ if (project === undefined || project.startsWith('-'))
88
+ return { error: 'Specify the project name first.' };
89
+ if (!PROJECT.test(project)) {
90
+ return { error: 'Project names are 1-63 lowercase letters, digits or hyphens and start and end with a letter or digit.' };
91
+ }
92
+ const flags = pickFlags(rest, ['--cores', '--memory']);
93
+ if ('error' in flags)
94
+ return flags;
95
+ const cores = oneOf('--cores', flags.values['--cores'], CORES);
96
+ if ('error' in cores)
97
+ return cores;
98
+ const memory = oneOf('--memory', flags.values['--memory'], MEMORIES);
99
+ if ('error' in memory)
100
+ return memory;
101
+ if (cores.value === undefined && memory.value === undefined) {
102
+ return { error: 'Give --cores, --memory or both.' };
103
+ }
104
+ return { project, cores: cores.value, memory: memory.value, consented: args.includes('--yes') };
105
+ }
106
+ function setPlan(project, cores, memory, consented) {
107
+ const cpu = cores === undefined ? null : { cores, monthlyExtra: (cores - 1) * CORE_PRICE };
108
+ const ram = memory === undefined ? null : { memoryGb: memory, monthlyExtra: (memory - 1) * MEMORY_PRICE };
109
+ const known = (cpu?.monthlyExtra ?? 0) + (ram?.monthlyExtra ?? 0);
110
+ return {
111
+ project, cpu, ram,
112
+ monthlyExtra: cpu && ram ? known : null,
113
+ currency: 'KRW',
114
+ restartRequired: true,
115
+ consentRequired: known > 0,
116
+ consented
117
+ };
118
+ }
119
+ function setRows({ project, cpu, ram, monthlyExtra, consentRequired, consented }) {
120
+ const known = (cpu?.monthlyExtra ?? 0) + (ram?.monthlyExtra ?? 0);
121
+ const kept = cpu ? 'RAM' : 'CPU';
122
+ const total = monthlyExtra !== null
123
+ ? monthlyExtra ? monthly(monthlyExtra) : 'None'
124
+ : known ? `${monthly(known)} + the current ${kept} charge` : `The current ${kept} charge only`;
125
+ const charge = 'Any increase over the current spec is billed to the account as an extra charge from the next billing date.';
126
+ return [
127
+ ['Project', project],
128
+ ['CPU', cpu ? `${coreCount(cpu.cores)} · ${price(cpu.monthlyExtra)}` : 'Unchanged (keeps the current setting)'],
129
+ ['RAM', ram ? `${ram.memoryGb}GB · ${price(ram.monthlyExtra)}` : 'Unchanged (keeps the current setting)'],
130
+ ['New extra charge', total],
131
+ ['Restart', RESTART],
132
+ ['Billing consent', !consentRequired
133
+ ? 'Not needed. This change does not raise the charge.'
134
+ : consented ? `Given (--yes). ${charge}` : `Required. ${charge} Add --yes once the user agrees to the amount.`],
135
+ ['Autopilot', 'While it is on, the spec cannot be changed by hand. Turn it off first with deepdynamic server autopilot off.']
136
+ ];
137
+ }
138
+ function parseAutopilot(args) {
139
+ const [mode, ...rest] = args;
140
+ if (mode !== 'on' && mode !== 'off')
141
+ return { error: 'Specify on or off.' };
142
+ const flags = pickFlags(rest, ['--limit']);
143
+ if ('error' in flags)
144
+ return flags;
145
+ const value = flags.values['--limit'];
146
+ if (value === undefined)
147
+ return mode === 'on' ? { enabled: true, limit: STARTING_LIMIT, defaulted: true } : { enabled: false, limit: null, defaulted: false };
148
+ if (mode === 'off')
149
+ return { error: '--limit is only accepted with on.' };
150
+ const limit = AUTOPILOT_LIMITS.find((amount) => String(amount) === value);
151
+ const choices = AUTOPILOT_LIMITS.join(', ');
152
+ if (limit === undefined)
153
+ return { error: `--limit must be one of ${choices}: ${value}` };
154
+ return { enabled: true, limit, defaulted: false };
155
+ }
156
+ function autopilotRows(enabled, limit, defaulted) {
157
+ if (!enabled || limit === null) {
158
+ return [
159
+ ['Autopilot', 'Turn off'],
160
+ ['Auto scaling', 'Turning it off stops scaling the spec up or down automatically.'],
161
+ ['Manual changes', 'Turning it off lets you change CPU and RAM with deepdynamic server set.']
162
+ ];
163
+ }
164
+ return [
165
+ ['Autopilot', 'Turn on'],
166
+ ['Monthly limit', defaulted ? `${won(limit)} (starting limit, change it with --limit)` : won(limit)],
167
+ ['Auto scaling', 'Scales CPU and RAM up when the spec runs short and back down when there is room. The server restarts briefly on each change.'],
168
+ ['Limit reached', 'Extra charges are billed only within the monthly limit. At the limit, autopilot stops scaling up and sends a notification first.'],
169
+ ['Manual changes', 'While it is on, the spec cannot be changed with deepdynamic server set.']
170
+ ];
171
+ }
172
+ function serverRow({ project, name, server, cores, memory, cpu, memoryUsed, restarting }) {
173
+ const state = restarting ? 'Restarting' : SERVER_STATES[server] ?? server;
174
+ if (server !== 'running' && server !== 'stopped')
175
+ return [project, `${name} · ${state}`];
176
+ const usage = server === 'running' ? ` · Usage: CPU ${cpu === null ? 'not measured' : `${cpu}%`}, RAM ${memoryUsed === null ? 'not measured' : `${memoryUsed}/${memory}GB`}` : '';
177
+ return [project, `${name} · ${state} · ${specText(cores, memory)} · ${price(extraOf(cores, memory))}${usage}`];
178
+ }
179
+ function listed(command, pretty, depth, body, siteUrl) {
180
+ const { aircraft, monthlyExtra, autopilot } = body;
181
+ const servers = aircraft.map(({ project, name, deploy, server, cores, memory, cpu, memoryUsed, restarting }) => ({ project, name, deploy, server, cores, memory, cpu, memoryUsed, restarting }));
182
+ if (!pretty)
183
+ return agentResult(0, { command, siteUrl, servers, monthlyExtra, currency: 'KRW', autopilot });
184
+ return prettyResult(0, depth, command, servers.length ? `Loaded ${count(servers.length, 'server')}.` : 'No servers found.', [
185
+ ['Server', siteUrl],
186
+ ...servers.map(serverRow),
187
+ ['Total extra charge', monthly(monthlyExtra)],
188
+ ['Autopilot', autopilot.enabled ? `On · Monthly limit ${won(autopilot.limit)}${autopilot.limitBlocked ? ' · Limit reached, not scaling up further' : ''}` : 'Off']
189
+ ]);
190
+ }
191
+ function specApplied(command, pretty, depth, body, siteUrl) {
192
+ const { project, cores, memory, monthlyExtra, previousMonthlyExtra, changed, restarting } = body;
193
+ const charged = typeof body.charged === 'number' ? body.charged : 0;
194
+ if (!pretty)
195
+ return agentResult(0, { command, siteUrl, applied: changed, project, cores, memory, monthlyExtra, previousMonthlyExtra, charged, currency: 'KRW', restarting });
196
+ const message = !changed
197
+ ? 'The server already has that spec. Nothing was changed.'
198
+ : `Changed the ${project} server to ${specText(cores, memory)}. ${restarting ? 'The server is restarting.' : 'The change applies the next time the server starts.'}`;
199
+ return prettyResult(0, depth, command, message, [
200
+ ['Server', siteUrl],
201
+ ['Project', project],
202
+ ['Spec', specText(cores, memory)],
203
+ ['Monthly extra charge', `${won(monthlyExtra)} (previously ${won(previousMonthlyExtra)})`],
204
+ ...(charged > 0 ? [['Charged now', won(charged)]] : [])
205
+ ]);
206
+ }
207
+ function consentNeeded(command, args, pretty, depth) {
208
+ return ({ status, body }) => {
209
+ const answer = body;
210
+ if (status !== 400 || answer?.consentRequired !== true || typeof answer.monthlyExtra !== 'number' || typeof answer.previousMonthlyExtra !== 'number')
211
+ return null;
212
+ const { monthlyExtra, previousMonthlyExtra } = answer;
213
+ return confirmationRequired(command, args, pretty, depth, {
214
+ message: `The change raises the monthly extra charge from ${previousMonthlyExtra} to ${monthlyExtra} KRW and needs the user's consent.`,
215
+ display: `The monthly extra charge rises from ${won(previousMonthlyExtra)} to ${won(monthlyExtra)}. Confirm with the user, then run it with --yes.`
216
+ }, { monthlyExtra, previousMonthlyExtra, currency: 'KRW' });
217
+ };
218
+ }
219
+ export async function runServerList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
220
+ const command = LIST.name;
221
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
222
+ if (rest.length)
223
+ return { error: unknownArgument(rest[0]) };
224
+ const url = (siteUrl) => new URL(SERVER_PATH, siteUrl).href;
225
+ return {
226
+ steps: LIST_STEPS,
227
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
228
+ send: {
229
+ method: 'GET',
230
+ url,
231
+ spinner: 'Loading the server list.',
232
+ failed: 'Could not load the server list.',
233
+ notFound: httpFailure(404),
234
+ failures: LIST_FAILURES,
235
+ done: (body, siteUrl) => listed(command, pretty, depth, body, siteUrl)
236
+ }
237
+ };
238
+ });
239
+ }
240
+ export async function runServerSet(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
241
+ const command = SET.name;
242
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
243
+ const parsed = parseSet(rest);
244
+ if ('error' in parsed)
245
+ return parsed;
246
+ const { project, cores, memory, consented } = parsed;
247
+ const plan = setPlan(project, cores, memory, consented);
248
+ const body = { ...(cores === undefined ? {} : { cores }), ...(memory === undefined ? {} : { memory }), ...(consented ? { consented: true } : {}) };
249
+ const url = (siteUrl) => new URL(`${SERVER_PATH}/${encodeURIComponent(project)}/spec`, siteUrl).href;
250
+ return {
251
+ steps: SET_STEPS,
252
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: url(siteUrl), body }, 'Checked the server spec change. Nothing was changed.', setRows(plan), plan),
253
+ send: {
254
+ method: 'POST',
255
+ url,
256
+ body,
257
+ spinner: 'Changing the server spec.',
258
+ failed: 'Could not change the server spec.',
259
+ notFound: PROJECT_NOT_FOUND,
260
+ conflict: SERVER_UNAVAILABLE,
261
+ failures: SET_FAILURES,
262
+ intercept: consentNeeded(command, rest, pretty, depth),
263
+ done: (result, siteUrl) => specApplied(command, pretty, depth, result, siteUrl)
264
+ }
265
+ };
266
+ });
267
+ }
268
+ export async function runServerAutopilot(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
269
+ const command = AUTOPILOT.name;
270
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
271
+ const parsed = parseAutopilot(rest);
272
+ if ('error' in parsed)
273
+ return parsed;
274
+ const { enabled, limit, defaulted } = parsed;
275
+ const plan = { enabled, monthlyLimit: limit, currency: 'KRW', manualChangesAllowed: !enabled };
276
+ const body = enabled ? { enabled, limit } : { enabled };
277
+ const url = (siteUrl) => new URL(`${SERVER_PATH}/autopilot`, siteUrl).href;
278
+ return {
279
+ steps: autopilotSteps(enabled),
280
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: url(siteUrl), body }, `Checked the autopilot change. Autopilot was not turned ${enabled ? 'on' : 'off'}.`, autopilotRows(enabled, limit, defaulted), plan),
281
+ send: {
282
+ method: 'POST',
283
+ url,
284
+ body,
285
+ spinner: enabled ? 'Turning autopilot on.' : 'Turning autopilot off.',
286
+ failed: enabled ? 'Could not turn autopilot on.' : 'Could not turn autopilot off.',
287
+ notFound: httpFailure(404),
288
+ failures: { server_unreachable: UNREACHABLE, unpaid_charges: AUTOPILOT_UNPAID },
289
+ done: (result, siteUrl) => {
290
+ const saved = result;
291
+ const monthlyLimit = saved.enabled ? saved.limit : null;
292
+ if (!pretty)
293
+ return agentResult(0, { command, siteUrl, applied: true, enabled: saved.enabled, monthlyLimit, currency: 'KRW', manualChangesAllowed: !saved.enabled });
294
+ return saved.enabled
295
+ ? prettyResult(0, depth, command, `Turned autopilot on. The monthly limit is ${won(saved.limit)}.`, [['Server', siteUrl], ...autopilotRows(true, saved.limit, false).slice(1)])
296
+ : prettyResult(0, depth, command, 'Turned autopilot off.', [['Server', siteUrl], ...autopilotRows(false, null, false).slice(1)]);
297
+ }
298
+ }
299
+ };
300
+ });
301
+ }
@@ -0,0 +1,114 @@
1
+ import { defaultAuthDeps } from "../auth/session.js";
2
+ import { httpFailure } from "../http/request.js";
3
+ import { agentResult } from "../output.js";
4
+ import { prettyResult } from "../pretty.js";
5
+ import { plannedChange, plannedRequest } from "../runtime/dry-run.js";
6
+ import { unknownArgument } from "../runtime/flags.js";
7
+ import { rehearsed } from "./dns.js";
8
+ export const SESSIONS_PATH = '/api/v1/security/sessions';
9
+ const SESSION_ID = /^(?:[0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
10
+ const TOKEN_VALUE = /^dd(?:c_|_)/i;
11
+ const KIND_LABELS = { web: 'Browser', cli: 'CLI' };
12
+ const failure = (code, message) => ({ code, message, display: message });
13
+ const SESSION_NOT_FOUND = failure('session_not_found', 'No session with that ID is among your sessions. Check them with deepdynamic sessions.');
14
+ const CURRENT_SESSION = failure('current_session', 'That is the session this CLI is using. It cannot be revoked here; run deepdynamic logout to end it.');
15
+ const LIST_STEPS = [{ stage: 'prepare_request', message: 'Preparing the session list request.' }];
16
+ const REVOKE_STEPS = [
17
+ { stage: 'validate_id', message: 'Checking the session ID format.' },
18
+ { stage: 'summarize_impact', message: 'Summarizing the access that revoking cuts off.' },
19
+ { stage: 'prepare_request', message: 'Preparing the revoke request.' }
20
+ ];
21
+ const sessionsUrl = (siteUrl, suffix = '') => new URL(`${SESSIONS_PATH}${suffix}`, siteUrl).href;
22
+ const when = (iso) => (iso === null ? 'never' : iso.replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC'));
23
+ const describe = (session) => session.kind === 'web' ? `${session.device?.browser ?? 'Unknown'} · ${session.device?.os ?? 'Unknown'}` : (session.name ?? 'CLI token');
24
+ const count = (amount, noun) => `${amount} ${noun}${amount === 1 ? '' : 's'}`;
25
+ function sessionLine(session) {
26
+ const parts = [
27
+ ...(session.current ? ['Current'] : []),
28
+ KIND_LABELS[session.kind],
29
+ describe(session),
30
+ `IP ${session.ip ?? 'unknown'}`,
31
+ ...(session.lastIp && session.lastIp !== session.ip ? [`Last IP ${session.lastIp}`] : []),
32
+ `Last active ${when(session.lastSeen)}`
33
+ ];
34
+ return [session.id, parts.join(' · ')];
35
+ }
36
+ function sessionRows(session) {
37
+ return [
38
+ ['Session ID', session.id],
39
+ ['Type', `${KIND_LABELS[session.kind]} · ${describe(session)}`],
40
+ ['IP', session.ip ?? 'unknown'],
41
+ ...(session.lastIp ? [['Last IP', session.lastIp]] : []),
42
+ ['Last active', when(session.lastSeen)],
43
+ ['Signed in', when(session.createdAt)],
44
+ ['Expires', when(session.expiresAt)]
45
+ ];
46
+ }
47
+ function parseRevoke(args) {
48
+ const option = args.find((arg) => arg.startsWith('-'));
49
+ if (option)
50
+ return { error: unknownArgument(option) };
51
+ if (args.length !== 1)
52
+ return { error: 'Specify exactly one session ID.' };
53
+ if (TOKEN_VALUE.test(args[0]))
54
+ return { error: 'Pass the session ID listed by deepdynamic sessions, not a token value.' };
55
+ const id = args[0].toLowerCase();
56
+ if (!SESSION_ID.test(id))
57
+ return { error: 'Session IDs are the id values listed by deepdynamic sessions.' };
58
+ return id;
59
+ }
60
+ export async function runSessionsList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
61
+ const command = 'sessions';
62
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
63
+ if (rest.length)
64
+ return { error: unknownArgument(rest[0]) };
65
+ return {
66
+ steps: LIST_STEPS,
67
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, sessionsUrl(siteUrl)),
68
+ send: {
69
+ method: 'GET',
70
+ url: (siteUrl) => sessionsUrl(siteUrl),
71
+ spinner: 'Loading login sessions.',
72
+ failed: 'Could not load login sessions.',
73
+ notFound: httpFailure(404),
74
+ done: (body, siteUrl) => {
75
+ const { sessions } = body;
76
+ if (!pretty)
77
+ return agentResult(0, { command, siteUrl, sessions });
78
+ return prettyResult(0, depth, command, `Loaded ${count(sessions.length, 'active session')}.`, [['Server', siteUrl], ...sessions.map(sessionLine)]);
79
+ }
80
+ }
81
+ };
82
+ });
83
+ }
84
+ export async function runSessionsRevoke(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
85
+ const command = 'sessions revoke';
86
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
87
+ const id = parseRevoke(rest);
88
+ if (typeof id !== 'string')
89
+ return id;
90
+ const path = `/${encodeURIComponent(id)}/revoke`;
91
+ return {
92
+ steps: REVOKE_STEPS,
93
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: sessionsUrl(siteUrl, path), body: {} }, 'Checked the session revoke request. The session was not revoked.', [['Session ID', id], ['Impact', 'Revoking signs out the browser or terminal that uses this session at once.']], { sessionId: id }),
94
+ send: {
95
+ method: 'POST',
96
+ url: (siteUrl) => sessionsUrl(siteUrl, path),
97
+ body: {},
98
+ spinner: 'Revoking the session.',
99
+ failed: 'Could not revoke the session.',
100
+ notFound: SESSION_NOT_FOUND,
101
+ failures: { current_session: CURRENT_SESSION },
102
+ done: (body, siteUrl) => {
103
+ const { session } = body;
104
+ return pretty
105
+ ? prettyResult(0, depth, command, `Revoked the ${session.kind === 'web' ? 'browser' : 'CLI'} session.`, [['Server', siteUrl], ...sessionRows(session), ['Impact', 'The browser or terminal that used this session is now signed out.']])
106
+ : agentResult(0, { command, siteUrl, applied: true, sessionId: session.id, session });
107
+ }
108
+ }
109
+ };
110
+ }, {
111
+ message: 'Revoking signs out the browser or terminal that uses the session at once.',
112
+ display: 'Revoking signs out the browser or terminal that uses the session at once. Confirm with the user, then run it with --yes.'
113
+ });
114
+ }
@@ -0,0 +1,102 @@
1
+ import { readLoginSiteUrl } from "../auth/credentials.js";
2
+ import { UNEXPECTED, defaultDeps, failureError, httpFailure, request } from "../http/request.js";
3
+ import { SITE_URL } from "../metadata.js";
4
+ import { agentResult } from "../output.js";
5
+ import { CONTROL, prettyResult } from "../pretty.js";
6
+ import { parseFlags } from "../runtime/flags.js";
7
+ import { spec } from "../registry.js";
8
+ import { plannedRequest, splitDryRun } from "../runtime/dry-run.js";
9
+ import { SERVER_OPTION, parseServerArgs } from "../runtime/server-options.js";
10
+ export const SITES_PATH = '/api/v1/sites';
11
+ const { name: command, usage } = spec('sites');
12
+ const FLAGS = ['--page', SERVER_OPTION];
13
+ const PAGE_RE = /^[1-9]\d{0,5}$/;
14
+ function isSite(value) {
15
+ const site = value;
16
+ return typeof site === 'object' && site !== null
17
+ && typeof site.name === 'string'
18
+ && (site.tagline === null || typeof site.tagline === 'string')
19
+ && typeof site.domain === 'string'
20
+ && typeof site.url === 'string'
21
+ && typeof site.regions === 'string'
22
+ && typeof site.monthlyVisits === 'number'
23
+ && typeof site.createdAt === 'string';
24
+ }
25
+ function isListing(body) {
26
+ const listing = body;
27
+ return listing?.ok === true
28
+ && typeof listing.total === 'number'
29
+ && typeof listing.page === 'number'
30
+ && typeof listing.pageSize === 'number'
31
+ && typeof listing.totalPages === 'number'
32
+ && Array.isArray(listing.sites)
33
+ && listing.sites.every(isSite);
34
+ }
35
+ function parseSitesArgs(args) {
36
+ const parsed = parseFlags(args, FLAGS);
37
+ if ('error' in parsed)
38
+ return parsed;
39
+ let page = 1;
40
+ const serverArgs = [];
41
+ for (const [flag, value] of parsed.entries) {
42
+ if (flag === SERVER_OPTION) {
43
+ serverArgs.push(flag, value);
44
+ }
45
+ else if (PAGE_RE.test(value)) {
46
+ page = Number(value);
47
+ }
48
+ else {
49
+ return { error: `--page requires a positive integer: ${value}` };
50
+ }
51
+ }
52
+ const server = parseServerArgs(serverArgs);
53
+ return 'error' in server ? server : { page, siteUrl: server.siteUrl };
54
+ }
55
+ const plain = (text) => text.replace(CONTROL, ' ');
56
+ function rows({ name, tagline, url, regions, monthlyVisits, createdAt }) {
57
+ return [
58
+ [plain(name), plain(url)],
59
+ ...(tagline ? [['', plain(tagline)]] : []),
60
+ ['', plain(`${regions} · ${monthlyVisits.toLocaleString('en-US')} visits/month · published ${createdAt.slice(0, 10)}`)]
61
+ ];
62
+ }
63
+ export async function runSites(args, pretty, depth, deps = defaultDeps()) {
64
+ const { args: rest, dryRun } = splitDryRun(args);
65
+ const options = parseSitesArgs(rest);
66
+ if ('error' in options) {
67
+ return pretty
68
+ ? prettyResult(2, depth, command, options.error, [['Usage', usage]])
69
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: options.error }, usage });
70
+ }
71
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
72
+ const endpoint = new URL(SITES_PATH, siteUrl);
73
+ endpoint.searchParams.set('page', String(options.page));
74
+ if (dryRun)
75
+ return plannedRequest(command, pretty, depth, siteUrl, endpoint.href);
76
+ const result = await request(endpoint.href, { method: 'GET' }, deps, pretty ? 'Loading public sites.' : null);
77
+ if ('failure' in result || result.status !== 200 || !isListing(result.body)) {
78
+ const failure = 'failure' in result
79
+ ? result.failure
80
+ : result.status !== 200
81
+ ? httpFailure(result.status)
82
+ : UNEXPECTED;
83
+ return pretty
84
+ ? prettyResult(1, depth, command, 'Could not load public sites.', [['Server', siteUrl], ['Reason', failure.display]])
85
+ : agentResult(1, { command, siteUrl, error: failureError(failure) });
86
+ }
87
+ const { total, page, pageSize, totalPages, sites } = result.body;
88
+ const next = page < totalPages ? `deepdynamic sites --page ${page + 1}` : null;
89
+ if (!pretty) {
90
+ return agentResult(0, { command, siteUrl, total, page, pageSize, totalPages, next, sites });
91
+ }
92
+ return prettyResult(0, depth, command, total === 0
93
+ ? 'No sites have been published yet.'
94
+ : sites.length
95
+ ? `Loaded ${sites.length} of ${total} public site${total === 1 ? '' : 's'}.`
96
+ : `Page ${page} has no sites.`, [
97
+ ['Server', siteUrl],
98
+ ...sites.flatMap(rows),
99
+ ['Page', `${page} / ${totalPages}`],
100
+ ...(next ? [['Next', next]] : [])
101
+ ]);
102
+ }