@deepdynamic/cli 0.0.0-stage → 0.1.0

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 (82) 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 +180 -0
  7. package/dist/agents/setup.js +29 -0
  8. package/dist/agents/targets.js +91 -0
  9. package/dist/auth/credentials.js +63 -0
  10. package/dist/auth/session.js +49 -0
  11. package/dist/cli.js +198 -0
  12. package/dist/commands/account.js +96 -0
  13. package/dist/commands/activity.js +80 -0
  14. package/dist/commands/blocked.js +89 -0
  15. package/dist/commands/deploy/agents.js +11 -0
  16. package/dist/commands/deploy/files.js +62 -0
  17. package/dist/commands/deploy/index.js +95 -0
  18. package/dist/commands/deploy/manifest.js +24 -0
  19. package/dist/commands/deploy/minify.js +27 -0
  20. package/dist/commands/deploy/progress.js +85 -0
  21. package/dist/commands/deploy/ship.js +117 -0
  22. package/dist/commands/deploy/upload.js +125 -0
  23. package/dist/commands/deployments.js +59 -0
  24. package/dist/commands/dns.js +791 -0
  25. package/dist/commands/domains.js +711 -0
  26. package/dist/commands/emails.js +74 -0
  27. package/dist/commands/env.js +194 -0
  28. package/dist/commands/help.js +149 -0
  29. package/dist/commands/keys.js +269 -0
  30. package/dist/commands/login/flow.js +155 -0
  31. package/dist/commands/login/index.js +26 -0
  32. package/dist/commands/logout.js +71 -0
  33. package/dist/commands/mail.js +241 -0
  34. package/dist/commands/notifications.js +132 -0
  35. package/dist/commands/plan.js +371 -0
  36. package/dist/commands/projects.js +836 -0
  37. package/dist/commands/reference.js +2180 -0
  38. package/dist/commands/search.js +75 -0
  39. package/dist/commands/server.js +314 -0
  40. package/dist/commands/sessions.js +120 -0
  41. package/dist/commands/sites.js +102 -0
  42. package/dist/commands/sms.js +65 -0
  43. package/dist/commands/status.js +87 -0
  44. package/dist/commands/support.js +115 -0
  45. package/dist/commands/update.js +98 -0
  46. package/dist/commands/usage.js +51 -0
  47. package/dist/commands/verify.js +149 -0
  48. package/dist/commands/version.js +6 -0
  49. package/dist/guide.js +76 -0
  50. package/dist/http/call.js +6 -0
  51. package/dist/http/request.js +54 -0
  52. package/dist/index.js +11 -0
  53. package/dist/metadata.js +4 -0
  54. package/dist/output.js +9 -0
  55. package/dist/pretty.js +70 -0
  56. package/dist/registry.js +760 -0
  57. package/dist/runtime/browser.js +15 -0
  58. package/dist/runtime/card-request.js +55 -0
  59. package/dist/runtime/confirm.js +21 -0
  60. package/dist/runtime/development.js +13 -0
  61. package/dist/runtime/domain-name.js +5 -0
  62. package/dist/runtime/dry-run.js +28 -0
  63. package/dist/runtime/env-file.js +58 -0
  64. package/dist/runtime/error-hints.js +26 -0
  65. package/dist/runtime/flags.js +50 -0
  66. package/dist/runtime/login-screen.js +78 -0
  67. package/dist/runtime/page.js +18 -0
  68. package/dist/runtime/project-name.js +1 -0
  69. package/dist/runtime/run-mode.js +7 -0
  70. package/dist/runtime/server-options.js +32 -0
  71. package/dist/runtime/spinner.js +15 -0
  72. package/dist/runtime/suggest.js +22 -0
  73. package/dist/runtime/support.js +14 -0
  74. package/dist/runtime/text-file.js +20 -0
  75. package/dist/runtime/timeout.js +22 -0
  76. package/dist/runtime/update-check.js +124 -0
  77. package/dist/runtime/update-install.js +50 -0
  78. package/dist/runtime/usage-error.js +9 -0
  79. package/dist/setup-agents.js +8 -0
  80. package/dist/site.js +1 -0
  81. package/dist/update-refresh.js +5 -0
  82. package/package.json +46 -3
@@ -0,0 +1,75 @@
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, prettyUsage } = 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 parseSearchArgs(args, pretty) {
23
+ const first = args[0];
24
+ if (first === undefined || first.startsWith('-') || !first.trim()) {
25
+ return { error: pretty ? '조회할 페이지 경로를 지정하세요. 예: deepdynamic search /pricing' : 'A page path is required, for example: deepdynamic search /pricing' };
26
+ }
27
+ const server = parseServerArgs(args.slice(1), pretty);
28
+ return 'error' in server ? server : { page: first.startsWith('/') ? first : `/${first}`, siteUrl: server.siteUrl };
29
+ }
30
+ export async function runSearch(args, pretty, depth, deps = defaultDeps()) {
31
+ const { args: rest, dryRun } = splitDryRun(args);
32
+ const options = parseSearchArgs(rest, pretty);
33
+ if ('error' in options) {
34
+ return pretty
35
+ ? prettyResult(2, depth, command, options.error, [['사용법', prettyUsage]])
36
+ : agentResult(2, { command, error: { code: 'invalid_arguments', message: options.error }, usage });
37
+ }
38
+ const siteUrl = options.siteUrl ?? await readLoginSiteUrl() ?? SITE_URL;
39
+ const endpoint = new URL(`${SEARCH_PATH}/${encodeURIComponent(options.page)}`, siteUrl);
40
+ if (dryRun)
41
+ return plannedRequest(command, pretty, depth, siteUrl, endpoint.href);
42
+ const result = await request(endpoint.href, { method: 'GET' }, deps, pretty ? '페이지 정보를 불러오고 있습니다.' : null);
43
+ if ('failure' in result || result.status !== 200 || !isPageInfo(result.body)) {
44
+ const pages = 'failure' in result || result.status !== 404 ? null : searchablePages(result.body);
45
+ const failure = 'failure' in result
46
+ ? result.failure
47
+ : result.status === 404
48
+ ? { code: 'page_not_found', message: `No searchable page at ${options.page}.`, display: '검색할 수 없는 페이지입니다.' }
49
+ : result.status !== 200
50
+ ? httpFailure(result.status)
51
+ : UNEXPECTED;
52
+ return pretty
53
+ ? prettyResult(1, depth, command, '페이지 정보를 불러오지 못했습니다.', [
54
+ ['서버', siteUrl],
55
+ ['페이지', options.page],
56
+ ['원인', failure.display],
57
+ ...(pages ? [['검색 가능', pages.join(', ')]] : [])
58
+ ])
59
+ : agentResult(1, {
60
+ command,
61
+ siteUrl,
62
+ page: options.page,
63
+ error: { ...failureError(failure), ...(pages ? { pages } : {}) }
64
+ });
65
+ }
66
+ const { page, url, markdown } = result.body;
67
+ if (!pretty) {
68
+ return agentResult(0, { command, siteUrl, page, url, markdown });
69
+ }
70
+ return prettyResult(0, depth, command, `${page.replace(CONTROL, ' ')} 페이지 정보를 불러왔습니다.`, [
71
+ ['서버', siteUrl],
72
+ ['주소', url.replace(CONTROL, ' ')],
73
+ ...markdown.trimEnd().split('\n').map((line) => ['', line.replace(CONTROL, ' ')])
74
+ ]);
75
+ }
@@ -0,0 +1,314 @@
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 = '적용하면 서버가 재시작되어 1분 안팎으로 사이트가 멈춥니다. 꺼져 있는 서버는 다음에 켤 때 반영됩니다.';
23
+ const SERVER_STATES = { running: '실행 중', stopped: '꺼짐', preparing: '서버 준비 중', failed: '서버 준비 실패' };
24
+ const PROJECT_NOT_FOUND = {
25
+ code: 'project_not_found',
26
+ message: 'You have no active project with that name. Check it with deepdynamic server.',
27
+ display: '그 이름의 내 프로젝트를 찾을 수 없습니다.'
28
+ };
29
+ const SERVER_UNAVAILABLE = supportFailure('server_unavailable', { note: { en: 'Nothing was changed.', ko: '바뀐 것은 없습니다.' } });
30
+ const UNREACHABLE = supportFailure('server_unreachable', { note: { en: 'Nothing was read or changed.', ko: '읽거나 바꾼 것은 없습니다.' } });
31
+ const LIST_FAILURES = {
32
+ server_unreachable: UNREACHABLE,
33
+ list_failed: supportFailure('list_failed')
34
+ };
35
+ const SET_FAILURES = {
36
+ server_unreachable: UNREACHABLE,
37
+ autopilot_on: {
38
+ code: 'autopilot_on',
39
+ message: 'Autopilot is on, so the spec cannot be changed by hand. Turn it off first with deepdynamic server autopilot off.',
40
+ display: '오토파일럿이 켜져 있는 동안에는 사양을 직접 바꿀 수 없습니다. 먼저 deepdynamic server autopilot off 로 끄세요.'
41
+ },
42
+ server_not_ready: {
43
+ code: 'server_not_ready',
44
+ message: 'The project server is not ready yet. Check it with deepdynamic server and retry once it is running or stopped.',
45
+ display: '서버가 준비된 뒤에 사양을 바꿀 수 있습니다. deepdynamic server 로 상태를 확인하세요.'
46
+ },
47
+ server_busy: {
48
+ code: 'server_busy',
49
+ message: 'The server is busy with a restart, update or deploy, or cannot take more CPU or RAM right now. Retry later.',
50
+ display: '서버가 다른 작업을 하고 있거나 지금은 CPU·RAM 을 늘릴 수 없습니다. 잠시 후 다시 시도하세요.'
51
+ },
52
+ cpu_too_small: {
53
+ code: 'cpu_too_small',
54
+ message: 'With that few cores the current CPU use would go over 100%. Keep more cores.',
55
+ display: '지금 CPU 사용량으로는 코어를 이만큼 줄일 수 없습니다.'
56
+ },
57
+ memory_too_small: {
58
+ code: 'memory_too_small',
59
+ message: 'The server uses more RAM than that. Keep more RAM.',
60
+ display: '지금 쓰는 RAM보다 작게 줄일 수 없습니다.'
61
+ }
62
+ };
63
+ const LIST_STEPS = [
64
+ { stage: 'check_options', message: '조회 옵션을 확인하고 있습니다.' },
65
+ { stage: 'prepare_request', message: '서버 목록 요청을 준비하고 있습니다.' }
66
+ ];
67
+ const SET_STEPS = [
68
+ { stage: 'check_options', message: 'CPU와 RAM 옵션을 확인하고 있습니다.' },
69
+ { stage: 'calculate_charge', message: '바꾼 뒤 월 추가 요금을 계산하고 있습니다.' },
70
+ { stage: 'check_consent', message: '추가 요금 청구 동의를 확인하고 있습니다.' },
71
+ { stage: 'prepare_request', message: '서버 사양 변경 요청을 준비하고 있습니다.' }
72
+ ];
73
+ const autopilotSteps = (enabled) => [
74
+ { stage: 'check_options', message: '오토파일럿 설정을 확인하고 있습니다.' },
75
+ enabled
76
+ ? { stage: 'check_limit', message: '월 한도를 확인하고 있습니다.' }
77
+ : { stage: 'check_manual_control', message: '사양 직접 변경 전환을 확인하고 있습니다.' },
78
+ { stage: 'prepare_request', message: '오토파일럿 요청을 준비하고 있습니다.' }
79
+ ];
80
+ const won = (amount) => `${amount.toLocaleString('ko-KR')}원`;
81
+ const price = (amount) => amount ? `월 +${won(amount)}` : '기본 포함';
82
+ const extraOf = (cores, memory) => (cores - 1) * CORE_PRICE + (memory - 1) * MEMORY_PRICE;
83
+ const specText = (cores, memory) => `CPU ${cores}코어 · RAM ${memory}GB`;
84
+ function pickFlags(args, flags, pretty) {
85
+ const parsed = parseFlags(args, flags, pretty);
86
+ if ('error' in parsed)
87
+ return parsed;
88
+ const repeated = parsed.entries.find(([flag], index) => parsed.entries.findIndex(([other]) => other === flag) !== index);
89
+ if (repeated)
90
+ return { error: pretty ? `${repeated[0]} 는 한 번만 지정하세요.` : `Give ${repeated[0]} only once.` };
91
+ return { values: Object.fromEntries(parsed.entries) };
92
+ }
93
+ function oneOf(flag, value, choices, pretty) {
94
+ if (value === undefined)
95
+ return {};
96
+ if (choices.includes(value))
97
+ return { value: Number(value) };
98
+ return { error: pretty ? `${flag} 에는 ${choices.join(', ')} 중 하나를 지정하세요: ${value}` : `${flag} must be one of ${choices.join(', ')}: ${value}` };
99
+ }
100
+ function parseSet(args, pretty) {
101
+ const [project, ...rest] = args.filter((arg) => arg !== '--yes');
102
+ if (project === undefined || project.startsWith('-'))
103
+ return { error: pretty ? '프로젝트 이름을 먼저 지정하세요.' : 'Specify the project name first.' };
104
+ if (!PROJECT.test(project)) {
105
+ return { error: pretty ? '프로젝트 이름은 영문 소문자·숫자로 시작하고 끝나는 1~63자의 소문자·숫자·하이픈입니다.' : 'Project names are 1-63 lowercase letters, digits or hyphens and start and end with a letter or digit.' };
106
+ }
107
+ const flags = pickFlags(rest, ['--cores', '--memory'], pretty);
108
+ if ('error' in flags)
109
+ return flags;
110
+ const cores = oneOf('--cores', flags.values['--cores'], CORES, pretty);
111
+ if ('error' in cores)
112
+ return cores;
113
+ const memory = oneOf('--memory', flags.values['--memory'], MEMORIES, pretty);
114
+ if ('error' in memory)
115
+ return memory;
116
+ if (cores.value === undefined && memory.value === undefined) {
117
+ return { error: pretty ? '--cores 나 --memory 중 하나 이상을 지정하세요.' : 'Give --cores, --memory or both.' };
118
+ }
119
+ return { project, cores: cores.value, memory: memory.value, consented: args.includes('--yes') };
120
+ }
121
+ function setPlan(project, cores, memory, consented) {
122
+ const cpu = cores === undefined ? null : { cores, monthlyExtra: (cores - 1) * CORE_PRICE };
123
+ const ram = memory === undefined ? null : { memoryGb: memory, monthlyExtra: (memory - 1) * MEMORY_PRICE };
124
+ const known = (cpu?.monthlyExtra ?? 0) + (ram?.monthlyExtra ?? 0);
125
+ return {
126
+ project, cpu, ram,
127
+ monthlyExtra: cpu && ram ? known : null,
128
+ currency: 'KRW',
129
+ restartRequired: true,
130
+ consentRequired: known > 0,
131
+ consented
132
+ };
133
+ }
134
+ function setRows({ project, cpu, ram, monthlyExtra, consentRequired, consented }) {
135
+ const known = (cpu?.monthlyExtra ?? 0) + (ram?.monthlyExtra ?? 0);
136
+ const kept = cpu ? 'RAM' : 'CPU';
137
+ const total = monthlyExtra !== null
138
+ ? monthlyExtra ? `월 ${won(monthlyExtra)}` : '없음'
139
+ : known ? `월 ${won(known)} + 지금 ${kept} 요금` : `지금 ${kept} 요금 그대로`;
140
+ const charge = '지금 사양보다 늘어나면 그 금액이 다음 결제일부터 계정에 추가 요금으로 청구됩니다.';
141
+ return [
142
+ ['프로젝트', project],
143
+ ['CPU', cpu ? `${cpu.cores}코어 · ${price(cpu.monthlyExtra)}` : '바꾸지 않음 (지금 그대로)'],
144
+ ['RAM', ram ? `${ram.memoryGb}GB · ${price(ram.monthlyExtra)}` : '바꾸지 않음 (지금 그대로)'],
145
+ ['바꾼 뒤 추가 요금', total],
146
+ ['적용', RESTART],
147
+ ['청구 동의', !consentRequired
148
+ ? '필요 없습니다. 요금이 늘지 않는 변경입니다.'
149
+ : consented ? `동의함 (--yes). ${charge}` : `필요합니다. ${charge} 금액에 동의하면 --yes 를 붙이세요.`],
150
+ ['오토파일럿', '켜져 있으면 사양을 직접 바꿀 수 없습니다. 먼저 deepdynamic server autopilot off 로 끄세요.']
151
+ ];
152
+ }
153
+ function parseAutopilot(args, pretty) {
154
+ const [mode, ...rest] = args;
155
+ if (mode !== 'on' && mode !== 'off')
156
+ return { error: pretty ? 'on 또는 off 를 지정하세요.' : 'Specify on or off.' };
157
+ const flags = pickFlags(rest, ['--limit'], pretty);
158
+ if ('error' in flags)
159
+ return flags;
160
+ const value = flags.values['--limit'];
161
+ if (value === undefined)
162
+ return mode === 'on' ? { enabled: true, limit: STARTING_LIMIT, defaulted: true } : { enabled: false, limit: null, defaulted: false };
163
+ if (mode === 'off')
164
+ return { error: pretty ? '--limit 은 on 과 함께만 지정할 수 있습니다.' : '--limit is only accepted with on.' };
165
+ const limit = AUTOPILOT_LIMITS.find((amount) => String(amount) === value);
166
+ const choices = AUTOPILOT_LIMITS.join(', ');
167
+ if (limit === undefined)
168
+ return { error: pretty ? `--limit 에는 ${choices} 중 하나를 지정하세요: ${value}` : `--limit must be one of ${choices}: ${value}` };
169
+ return { enabled: true, limit, defaulted: false };
170
+ }
171
+ function autopilotRows(enabled, limit, defaulted) {
172
+ if (!enabled || limit === null) {
173
+ return [
174
+ ['오토파일럿', '끄기'],
175
+ ['자동 조정', '끄면 사양을 자동으로 올리거나 낮추지 않습니다.'],
176
+ ['직접 변경', '끄면 deepdynamic server set 으로 CPU와 RAM을 직접 바꿀 수 있습니다.']
177
+ ];
178
+ }
179
+ return [
180
+ ['오토파일럿', '켜기'],
181
+ ['월 한도', defaulted ? `${won(limit)} (처음 한도, --limit 로 바꿀 수 있습니다)` : won(limit)],
182
+ ['자동 조정', '사양이 부족하면 CPU와 RAM을 자동으로 올리고, 여유로워지면 다시 낮춥니다. 바꿀 때마다 서버가 잠시 재시작됩니다.'],
183
+ ['한도 도달', '추가 요금은 월 한도 안에서만 청구되고, 한도에 이르면 더 올리지 않고 알림으로 먼저 알립니다.'],
184
+ ['직접 변경', '켜져 있는 동안에는 deepdynamic server set 으로 사양을 직접 바꿀 수 없습니다.']
185
+ ];
186
+ }
187
+ function serverRow({ project, name, server, cores, memory, cpu, memoryUsed, restarting }) {
188
+ const state = restarting ? '재시작 중' : SERVER_STATES[server] ?? server;
189
+ if (server !== 'running' && server !== 'stopped')
190
+ return [project, `${name} · ${state}`];
191
+ const usage = server === 'running' ? ` · 사용량 CPU ${cpu === null ? '측정 안 됨' : `${cpu}%`} · RAM ${memoryUsed === null ? '측정 안 됨' : `${memoryUsed}/${memory}GB`}` : '';
192
+ return [project, `${name} · ${state} · ${specText(cores, memory)} · ${price(extraOf(cores, memory))}${usage}`];
193
+ }
194
+ function listed(command, pretty, depth, body, siteUrl) {
195
+ const { aircraft, monthlyExtra, autopilot } = body;
196
+ const servers = aircraft.map(({ project, name, deploy, server, cores, memory, cpu, memoryUsed, restarting }) => ({ project, name, deploy, server, cores, memory, cpu, memoryUsed, restarting }));
197
+ if (!pretty)
198
+ return agentResult(0, { command, siteUrl, servers, monthlyExtra, currency: 'KRW', autopilot });
199
+ return prettyResult(0, depth, command, servers.length ? `서버 ${servers.length}대를 불러왔습니다.` : '서버가 없습니다.', [
200
+ ['서버', siteUrl],
201
+ ...servers.map(serverRow),
202
+ ['추가 요금 합계', `월 ${won(monthlyExtra)}`],
203
+ ['오토파일럿', autopilot.enabled ? `켜짐 · 월 한도 ${won(autopilot.limit)}${autopilot.limitBlocked ? ' · 한도에 걸려 더 올리지 못함' : ''}` : '꺼짐']
204
+ ]);
205
+ }
206
+ function specApplied(command, pretty, depth, body, siteUrl) {
207
+ const { project, cores, memory, monthlyExtra, previousMonthlyExtra, changed, restarting } = body;
208
+ if (!pretty)
209
+ return agentResult(0, { command, siteUrl, applied: changed, project, cores, memory, monthlyExtra, previousMonthlyExtra, currency: 'KRW', restarting });
210
+ const message = !changed
211
+ ? '지금 사양 그대로라 바꾸지 않았습니다.'
212
+ : `${project} 서버를 ${specText(cores, memory)}로 바꿨습니다. ${restarting ? '서버가 재시작되고 있습니다.' : '다음에 켤 때 반영됩니다.'}`;
213
+ return prettyResult(0, depth, command, message, [
214
+ ['서버', siteUrl],
215
+ ['프로젝트', project],
216
+ ['사양', specText(cores, memory)],
217
+ ['월 추가 요금', `${won(monthlyExtra)} (이전 ${won(previousMonthlyExtra)})`]
218
+ ]);
219
+ }
220
+ function consentNeeded(command, args, pretty, depth) {
221
+ return ({ status, body }) => {
222
+ const answer = body;
223
+ if (status !== 400 || answer?.consentRequired !== true || typeof answer.monthlyExtra !== 'number' || typeof answer.previousMonthlyExtra !== 'number')
224
+ return null;
225
+ const { monthlyExtra, previousMonthlyExtra } = answer;
226
+ return confirmationRequired(command, args, pretty, depth, {
227
+ message: `The change raises the monthly extra charge from ${previousMonthlyExtra} to ${monthlyExtra} KRW and needs the user's consent.`,
228
+ display: `월 추가 요금이 ${won(previousMonthlyExtra)}에서 ${won(monthlyExtra)}으로 늘어납니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.`
229
+ }, { monthlyExtra, previousMonthlyExtra, currency: 'KRW' });
230
+ };
231
+ }
232
+ export async function runServerList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
233
+ const command = LIST.name;
234
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
235
+ if (rest.length)
236
+ return { error: unknownArgument(rest[0], pretty) };
237
+ const url = (siteUrl) => new URL(SERVER_PATH, siteUrl).href;
238
+ return {
239
+ steps: LIST_STEPS,
240
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
241
+ send: {
242
+ method: 'GET',
243
+ url,
244
+ spinner: '서버 목록을 불러오고 있습니다.',
245
+ failed: '서버 목록을 불러오지 못했습니다.',
246
+ notFound: httpFailure(404),
247
+ failures: LIST_FAILURES,
248
+ done: (body, siteUrl) => listed(command, pretty, depth, body, siteUrl)
249
+ }
250
+ };
251
+ });
252
+ }
253
+ export async function runServerSet(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
254
+ const command = SET.name;
255
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
256
+ const parsed = parseSet(rest, pretty);
257
+ if ('error' in parsed)
258
+ return parsed;
259
+ const { project, cores, memory, consented } = parsed;
260
+ const plan = setPlan(project, cores, memory, consented);
261
+ const body = { ...(cores === undefined ? {} : { cores }), ...(memory === undefined ? {} : { memory }), ...(consented ? { consented: true } : {}) };
262
+ const url = (siteUrl) => new URL(`${SERVER_PATH}/${encodeURIComponent(project)}/spec`, siteUrl).href;
263
+ return {
264
+ steps: SET_STEPS,
265
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: url(siteUrl), body }, '서버 사양 변경을 확인했습니다. 바꾸지 않았습니다.', setRows(plan), plan),
266
+ send: {
267
+ method: 'POST',
268
+ url,
269
+ body,
270
+ spinner: '서버 사양을 바꾸고 있습니다.',
271
+ failed: '서버 사양을 바꾸지 못했습니다.',
272
+ notFound: PROJECT_NOT_FOUND,
273
+ conflict: SERVER_UNAVAILABLE,
274
+ failures: SET_FAILURES,
275
+ intercept: consentNeeded(command, rest, pretty, depth),
276
+ done: (result, siteUrl) => specApplied(command, pretty, depth, result, siteUrl)
277
+ }
278
+ };
279
+ });
280
+ }
281
+ export async function runServerAutopilot(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
282
+ const command = AUTOPILOT.name;
283
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
284
+ const parsed = parseAutopilot(rest, pretty);
285
+ if ('error' in parsed)
286
+ return parsed;
287
+ const { enabled, limit, defaulted } = parsed;
288
+ const plan = { enabled, monthlyLimit: limit, currency: 'KRW', manualChangesAllowed: !enabled };
289
+ const body = enabled ? { enabled, limit } : { enabled };
290
+ const url = (siteUrl) => new URL(`${SERVER_PATH}/autopilot`, siteUrl).href;
291
+ return {
292
+ steps: autopilotSteps(enabled),
293
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: url(siteUrl), body }, `오토파일럿 설정을 확인했습니다. ${enabled ? '켜지' : '끄지'} 않았습니다.`, autopilotRows(enabled, limit, defaulted), plan),
294
+ send: {
295
+ method: 'POST',
296
+ url,
297
+ body,
298
+ spinner: enabled ? '오토파일럿을 켜고 있습니다.' : '오토파일럿을 끄고 있습니다.',
299
+ failed: enabled ? '오토파일럿을 켜지 못했습니다.' : '오토파일럿을 끄지 못했습니다.',
300
+ notFound: httpFailure(404),
301
+ failures: { server_unreachable: UNREACHABLE },
302
+ done: (result, siteUrl) => {
303
+ const saved = result;
304
+ const monthlyLimit = saved.enabled ? saved.limit : null;
305
+ if (!pretty)
306
+ return agentResult(0, { command, siteUrl, applied: true, enabled: saved.enabled, monthlyLimit, currency: 'KRW', manualChangesAllowed: !saved.enabled });
307
+ return saved.enabled
308
+ ? prettyResult(0, depth, command, `오토파일럿을 켰습니다. 월 한도는 ${won(saved.limit)}입니다.`, [['서버', siteUrl], ...autopilotRows(true, saved.limit, false).slice(1)])
309
+ : prettyResult(0, depth, command, '오토파일럿을 껐습니다.', [['서버', siteUrl], ...autopilotRows(false, null, false).slice(1)]);
310
+ }
311
+ }
312
+ };
313
+ });
314
+ }
@@ -0,0 +1,120 @@
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 { fail, 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: '웹', cli: 'CLI' };
12
+ const SESSION_NOT_FOUND = {
13
+ code: 'session_not_found',
14
+ message: 'No session with that ID is among your sessions. Check them with deepdynamic sessions.',
15
+ display: '내 세션 목록에 없는 세션 ID 입니다.'
16
+ };
17
+ const CURRENT_SESSION = {
18
+ code: 'current_session',
19
+ message: 'That is the session this CLI is using. It cannot be revoked here; run deepdynamic logout to end it.',
20
+ display: '지금 이 CLI 가 쓰는 세션입니다. 여기서는 회수할 수 없고 deepdynamic logout 으로 끝낼 수 있습니다.'
21
+ };
22
+ const LIST_STEPS = [{ stage: 'prepare_request', message: '세션 목록 요청을 준비하고 있습니다.' }];
23
+ const REVOKE_STEPS = [
24
+ { stage: 'validate_id', message: '세션 ID 형식을 확인하고 있습니다.' },
25
+ { stage: 'summarize_impact', message: '회수하면 끊기는 접근을 정리하고 있습니다.' },
26
+ { stage: 'prepare_request', message: '회수 요청을 준비하고 있습니다.' }
27
+ ];
28
+ const sessionsUrl = (siteUrl, suffix = '') => new URL(`${SESSIONS_PATH}${suffix}`, siteUrl).href;
29
+ const when = (iso) => (iso === null ? '없음' : iso.replace('T', ' ').replace(/\.\d{3}Z$/, ' UTC'));
30
+ const describe = (session) => session.kind === 'web' ? `${session.device?.browser ?? 'Unknown'} · ${session.device?.os ?? 'Unknown'}` : (session.name ?? 'CLI 토큰');
31
+ function sessionLine(session) {
32
+ const parts = [
33
+ ...(session.current ? ['현재'] : []),
34
+ KIND_LABELS[session.kind],
35
+ describe(session),
36
+ `IP ${session.ip ?? '알 수 없음'}`,
37
+ ...(session.lastIp && session.lastIp !== session.ip ? [`마지막 IP ${session.lastIp}`] : []),
38
+ `마지막 활동 ${when(session.lastSeen)}`
39
+ ];
40
+ return [session.id, parts.join(' · ')];
41
+ }
42
+ function sessionRows(session) {
43
+ return [
44
+ ['세션 ID', session.id],
45
+ ['종류', `${KIND_LABELS[session.kind]} · ${describe(session)}`],
46
+ ['IP', session.ip ?? '알 수 없음'],
47
+ ...(session.lastIp ? [['마지막 IP', session.lastIp]] : []),
48
+ ['마지막 활동', when(session.lastSeen)],
49
+ ['로그인', when(session.createdAt)],
50
+ ['만료', when(session.expiresAt)]
51
+ ];
52
+ }
53
+ function parseRevoke(args, pretty) {
54
+ const option = args.find((arg) => arg.startsWith('-'));
55
+ if (option)
56
+ return { error: unknownArgument(option, pretty) };
57
+ if (args.length !== 1)
58
+ return fail(pretty, 'Specify exactly one session ID.', '회수할 세션 ID 를 하나만 지정하세요.');
59
+ if (TOKEN_VALUE.test(args[0]))
60
+ return fail(pretty, 'Pass the session ID listed by deepdynamic sessions, not a token value.', '토큰 값이 아니라 deepdynamic sessions 에 나오는 세션 ID 를 지정하세요.');
61
+ const id = args[0].toLowerCase();
62
+ if (!SESSION_ID.test(id))
63
+ return fail(pretty, 'Session IDs are the id values listed by deepdynamic sessions.', '세션 ID 는 deepdynamic sessions 에 나오는 id 값입니다.');
64
+ return id;
65
+ }
66
+ export async function runSessionsList(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
67
+ const command = 'sessions';
68
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
69
+ if (rest.length)
70
+ return { error: unknownArgument(rest[0], pretty) };
71
+ return {
72
+ steps: LIST_STEPS,
73
+ result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, sessionsUrl(siteUrl)),
74
+ send: {
75
+ method: 'GET',
76
+ url: (siteUrl) => sessionsUrl(siteUrl),
77
+ spinner: '로그인 세션을 불러오고 있습니다.',
78
+ failed: '로그인 세션을 불러오지 못했습니다.',
79
+ notFound: httpFailure(404),
80
+ done: (body, siteUrl) => {
81
+ const { sessions } = body;
82
+ if (!pretty)
83
+ return agentResult(0, { command, siteUrl, sessions });
84
+ return prettyResult(0, depth, command, `활성 세션 ${sessions.length}개를 불러왔습니다.`, [['서버', siteUrl], ...sessions.map(sessionLine)]);
85
+ }
86
+ }
87
+ };
88
+ });
89
+ }
90
+ export async function runSessionsRevoke(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
91
+ const command = 'sessions revoke';
92
+ return rehearsed(command, args, pretty, depth, deps, (rest) => {
93
+ const id = parseRevoke(rest, pretty);
94
+ if (typeof id !== 'string')
95
+ return id;
96
+ const path = `/${encodeURIComponent(id)}/revoke`;
97
+ return {
98
+ steps: REVOKE_STEPS,
99
+ result: (siteUrl) => plannedChange(command, pretty, depth, siteUrl, { url: sessionsUrl(siteUrl, path), body: {} }, '세션 회수 요청을 확인했습니다. 회수하지 않았습니다.', [['세션 ID', id], ['영향', '회수하면 그 세션으로 로그인한 브라우저나 터미널은 바로 로그아웃됩니다.']], { sessionId: id }),
100
+ send: {
101
+ method: 'POST',
102
+ url: (siteUrl) => sessionsUrl(siteUrl, path),
103
+ body: {},
104
+ spinner: '세션을 회수하고 있습니다.',
105
+ failed: '세션을 회수하지 못했습니다.',
106
+ notFound: SESSION_NOT_FOUND,
107
+ failures: { current_session: CURRENT_SESSION },
108
+ done: (body, siteUrl) => {
109
+ const { session } = body;
110
+ return pretty
111
+ ? prettyResult(0, depth, command, `${KIND_LABELS[session.kind]} 세션을 회수했습니다.`, [['서버', siteUrl], ...sessionRows(session), ['영향', '그 세션으로 로그인한 브라우저나 터미널은 바로 로그아웃됩니다.']])
112
+ : agentResult(0, { command, siteUrl, applied: true, sessionId: session.id, session });
113
+ }
114
+ }
115
+ };
116
+ }, {
117
+ message: 'Revoking signs out the browser or terminal that uses the session at once.',
118
+ display: '회수하면 그 세션으로 로그인한 브라우저나 터미널이 바로 로그아웃됩니다. 사용자에게 확인한 뒤 --yes 를 붙여 실행하세요.'
119
+ });
120
+ }
@@ -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, prettyUsage } = 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, pretty) {
36
+ const parsed = parseFlags(args, FLAGS, pretty);
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: pretty ? `--page 에는 1 이상의 정수를 지정하세요: ${value}` : `--page requires a positive integer: ${value}` };
50
+ }
51
+ }
52
+ const server = parseServerArgs(serverArgs, pretty);
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('ko-KR')}명 · ${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, pretty);
66
+ if ('error' in options) {
67
+ return pretty
68
+ ? prettyResult(2, depth, command, options.error, [['사용법', prettyUsage]])
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 ? '공개 사이트를 불러오고 있습니다.' : 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, '공개 사이트를 불러오지 못했습니다.', [['서버', siteUrl], ['원인', 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
+ ? '아직 공개된 사이트가 없습니다.'
94
+ : sites.length
95
+ ? `공개 사이트 ${total}개 중 ${sites.length}개를 불러왔습니다.`
96
+ : `${page}페이지에는 사이트가 없습니다.`, [
97
+ ['서버', siteUrl],
98
+ ...sites.flatMap(rows),
99
+ ['페이지', `${page} / ${totalPages}`],
100
+ ...(next ? [['다음', next]] : [])
101
+ ]);
102
+ }