@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.
- 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 +180 -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 +59 -0
- package/dist/commands/dns.js +791 -0
- package/dist/commands/domains.js +711 -0
- package/dist/commands/emails.js +74 -0
- package/dist/commands/env.js +194 -0
- package/dist/commands/help.js +149 -0
- package/dist/commands/keys.js +269 -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 +132 -0
- package/dist/commands/plan.js +371 -0
- package/dist/commands/projects.js +836 -0
- package/dist/commands/reference.js +2180 -0
- package/dist/commands/search.js +75 -0
- package/dist/commands/server.js +314 -0
- package/dist/commands/sessions.js +120 -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 +98 -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 +76 -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/registry.js +760 -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 +58 -0
- package/dist/runtime/error-hints.js +26 -0
- package/dist/runtime/flags.js +50 -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 +32 -0
- package/dist/runtime/spinner.js +15 -0
- package/dist/runtime/suggest.js +22 -0
- package/dist/runtime/support.js +14 -0
- package/dist/runtime/text-file.js +20 -0
- package/dist/runtime/timeout.js +22 -0
- package/dist/runtime/update-check.js +124 -0
- package/dist/runtime/update-install.js +50 -0
- package/dist/runtime/usage-error.js +9 -0
- package/dist/setup-agents.js +8 -0
- package/dist/site.js +1 -0
- package/dist/update-refresh.js +5 -0
- package/package.json +46 -3
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { defaultAuthDeps } from "../auth/session.js";
|
|
2
|
+
import { httpFailure } from "../http/request.js";
|
|
3
|
+
import { agentResult } from "../output.js";
|
|
4
|
+
import { CONTROL, prettyResult } from "../pretty.js";
|
|
5
|
+
import { plannedRequest } from "../runtime/dry-run.js";
|
|
6
|
+
import { parseFlags } from "../runtime/flags.js";
|
|
7
|
+
import { rehearsed } from "./dns.js";
|
|
8
|
+
export const BLOCKED_PATH = '/api/v1/blocked-requests';
|
|
9
|
+
const command = 'sites blocked';
|
|
10
|
+
const FLAGS = ['--page', '--ray', '--host', '--date'];
|
|
11
|
+
const PAGE_RE = /^[1-9]\d{0,5}$/;
|
|
12
|
+
const RAY_RE = /^[0-9a-f]{16}$/;
|
|
13
|
+
const HOST_RE = /^(?=.{1,253}$)[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?)*$/;
|
|
14
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
15
|
+
const STEPS = [
|
|
16
|
+
{ stage: 'validate_filters', message: '조회 조건을 확인하고 있습니다.' },
|
|
17
|
+
{ stage: 'prepare_request', message: '차단 기록 요청을 준비하고 있습니다.' }
|
|
18
|
+
];
|
|
19
|
+
function isCalendarDate(value) {
|
|
20
|
+
const time = DATE_RE.test(value) ? Date.parse(`${value}T00:00:00Z`) : NaN;
|
|
21
|
+
return !Number.isNaN(time) && new Date(time).toISOString().startsWith(value);
|
|
22
|
+
}
|
|
23
|
+
function parseBlockedArgs(args, pretty) {
|
|
24
|
+
const parsed = parseFlags(args, FLAGS, pretty);
|
|
25
|
+
if ('error' in parsed)
|
|
26
|
+
return parsed;
|
|
27
|
+
const repeated = FLAGS.find((flag) => parsed.entries.filter(([name]) => name === flag).length > 1);
|
|
28
|
+
if (repeated)
|
|
29
|
+
return { error: pretty ? `${repeated} 는 한 번만 지정하세요.` : `${repeated} can be given only once.` };
|
|
30
|
+
const { '--page': page = '1', '--ray': ray, '--host': host, '--date': date } = Object.fromEntries(parsed.entries);
|
|
31
|
+
if (!PAGE_RE.test(page))
|
|
32
|
+
return { error: pretty ? `--page 에는 1 이상의 정수를 지정하세요: ${page}` : `--page requires a positive integer: ${page}` };
|
|
33
|
+
if (ray !== undefined && !RAY_RE.test(ray))
|
|
34
|
+
return { error: pretty ? `--ray 에는 차단 페이지에 보인 16자리 소문자 hex ID 를 지정하세요: ${ray}` : `--ray requires the 16 lowercase hex character ID shown on the block page: ${ray}` };
|
|
35
|
+
if (host !== undefined && !HOST_RE.test(host))
|
|
36
|
+
return { error: pretty ? `--host 에는 소문자 호스트 이름을 지정하세요: ${host}` : `--host requires a lowercase host name: ${host}` };
|
|
37
|
+
if (date !== undefined && !isCalendarDate(date))
|
|
38
|
+
return { error: pretty ? `--date 에는 실제 날짜를 YYYY-MM-DD 형식(UTC)으로 지정하세요: ${date}` : `--date requires a real calendar date as YYYY-MM-DD (UTC): ${date}` };
|
|
39
|
+
return { page: Number(page), ray: ray ?? null, host: host ?? null, date: date ?? null };
|
|
40
|
+
}
|
|
41
|
+
const plain = (text) => text.replace(CONTROL, ' ');
|
|
42
|
+
function recordLine(record) {
|
|
43
|
+
const parts = [
|
|
44
|
+
record.ray,
|
|
45
|
+
record.site ?? '(직접 접속)',
|
|
46
|
+
...(record.method || record.path ? [plain(`${record.method ?? ''} ${record.path ?? ''}`.trim())] : []),
|
|
47
|
+
...(record.ip ? [`IP ${record.ip}`] : [])
|
|
48
|
+
];
|
|
49
|
+
return [`${record.at.slice(0, 19).replace('T', ' ')} UTC`, parts.join(' · ')];
|
|
50
|
+
}
|
|
51
|
+
export async function runBlocked(args, pretty, depth, deps = defaultAuthDeps(pretty, depth)) {
|
|
52
|
+
return rehearsed(command, args, pretty, depth, deps, (rest) => {
|
|
53
|
+
const options = parseBlockedArgs(rest, pretty);
|
|
54
|
+
if ('error' in options)
|
|
55
|
+
return options;
|
|
56
|
+
const url = (siteUrl) => {
|
|
57
|
+
const endpoint = new URL(BLOCKED_PATH, siteUrl);
|
|
58
|
+
endpoint.searchParams.set('page', String(options.page));
|
|
59
|
+
if (options.ray)
|
|
60
|
+
endpoint.searchParams.set('ray', options.ray);
|
|
61
|
+
if (options.host)
|
|
62
|
+
endpoint.searchParams.set('host', options.host);
|
|
63
|
+
if (options.date)
|
|
64
|
+
endpoint.searchParams.set('date', options.date);
|
|
65
|
+
return endpoint.href;
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
steps: STEPS,
|
|
69
|
+
result: (siteUrl) => plannedRequest(command, pretty, depth, siteUrl, url(siteUrl)),
|
|
70
|
+
send: {
|
|
71
|
+
method: 'GET',
|
|
72
|
+
url,
|
|
73
|
+
spinner: '차단 기록을 불러오고 있습니다.',
|
|
74
|
+
failed: '차단 기록을 불러오지 못했습니다.',
|
|
75
|
+
notFound: httpFailure(404),
|
|
76
|
+
done: (body, siteUrl) => {
|
|
77
|
+
const { scope, page, pageSize, total, ray, host, date, records } = body;
|
|
78
|
+
if (!pretty)
|
|
79
|
+
return agentResult(0, { command, siteUrl, scope, page, pageSize, total, ray, host, date, records });
|
|
80
|
+
return prettyResult(0, depth, command, `차단 기록 ${total}건 중 ${page}페이지를 불러왔습니다.`, [
|
|
81
|
+
['서버', siteUrl],
|
|
82
|
+
['범위', scope === 'all' ? '전체' : '내 사이트'],
|
|
83
|
+
...records.map(recordLine)
|
|
84
|
+
]);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
});
|
|
89
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const AGENTS = [
|
|
2
|
+
['CLD', 'Claude'],
|
|
3
|
+
['CCD', 'Claude Code'],
|
|
4
|
+
['CDX', 'Codex'],
|
|
5
|
+
['GPT', 'ChatGPT'],
|
|
6
|
+
['OPC', 'OpenCode'],
|
|
7
|
+
['CRS', 'Crush'],
|
|
8
|
+
['CUR', 'Cursor'],
|
|
9
|
+
['OTH', 'any other agent or a person']
|
|
10
|
+
];
|
|
11
|
+
export const AGENT_CODES = AGENTS.map(([code]) => code);
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { credentialsPath } from "../../auth/credentials.js";
|
|
4
|
+
const EXCLUDED_NAMES = [
|
|
5
|
+
'node_modules', '.git', '.cache', '.ds_store', 'thumbs.db', '.env', '.envrc', '.dev.vars', '.wrangler', '.cloudflare', '.npmrc', '.netrc', '_netrc',
|
|
6
|
+
'.yarnrc', '.yarnrc.yml', '.git-credentials', '.pypirc', '.ssh', '.aws', '.docker', '.kube', '.gnupg', '.svn', '.hg'
|
|
7
|
+
];
|
|
8
|
+
const sameFile = (first, second) => first.dev === second.dev && first.ino === second.ino;
|
|
9
|
+
function isExcluded(name) {
|
|
10
|
+
const normalized = name.toLowerCase();
|
|
11
|
+
return EXCLUDED_NAMES.includes(normalized) || normalized.startsWith('.env.') || normalized.startsWith('.dev.vars.') || /^git~\d+$/.test(normalized) || /^\.git[. ]+$/.test(normalized);
|
|
12
|
+
}
|
|
13
|
+
export async function collectDeployFiles(root) {
|
|
14
|
+
const files = [];
|
|
15
|
+
const paths = ['', '1'].map((development) => credentialsPath({ ...process.env, DEEPDYNAMIC_DEVELOPMENT: development }));
|
|
16
|
+
const credentials = paths.map((path) => path.toLowerCase());
|
|
17
|
+
const names = paths.map((path) => basename(path).toLowerCase());
|
|
18
|
+
const saved = (await Promise.all(paths.map((path) => stat(path, { bigint: true }).catch(() => null)))).filter((info) => info !== null && info.ino !== 0n);
|
|
19
|
+
const isCredentials = async (path, name) => {
|
|
20
|
+
if (credentials.includes(path.toLowerCase()))
|
|
21
|
+
return true;
|
|
22
|
+
if (!saved.length || !names.includes(name.toLowerCase()))
|
|
23
|
+
return false;
|
|
24
|
+
const info = await stat(path, { bigint: true }).catch(() => null);
|
|
25
|
+
return info !== null && saved.some((credential) => sameFile(credential, info));
|
|
26
|
+
};
|
|
27
|
+
const walk = async (directory, prefix) => {
|
|
28
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
29
|
+
if (isExcluded(entry.name))
|
|
30
|
+
continue;
|
|
31
|
+
const path = join(directory, entry.name);
|
|
32
|
+
if (await isCredentials(path, entry.name))
|
|
33
|
+
continue;
|
|
34
|
+
if (entry.isDirectory())
|
|
35
|
+
await walk(path, `${prefix}${entry.name}/`);
|
|
36
|
+
else if (entry.isFile())
|
|
37
|
+
files.push(`${prefix}${entry.name}`);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
await walk(root, '');
|
|
41
|
+
return files.sort();
|
|
42
|
+
}
|
|
43
|
+
const comparable = (path) => process.platform === 'linux' ? path : path.normalize('NFC').toLowerCase();
|
|
44
|
+
export async function deployFileReader(root) {
|
|
45
|
+
const base = await realpath(root);
|
|
46
|
+
return async (file) => {
|
|
47
|
+
const path = join(root, file);
|
|
48
|
+
const handle = await open(path, 'r');
|
|
49
|
+
try {
|
|
50
|
+
const opened = await handle.stat({ bigint: true });
|
|
51
|
+
const real = await realpath(path);
|
|
52
|
+
const current = await lstat(real, { bigint: true });
|
|
53
|
+
if (comparable(real) !== comparable(join(base, file)) || !current.isFile() || !sameFile(current, opened)) {
|
|
54
|
+
throw new Error('A deploy file changed or points outside the deployed directory.');
|
|
55
|
+
}
|
|
56
|
+
return await handle.readFile();
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
await handle.close();
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { agentResult } from "../../output.js";
|
|
4
|
+
import { displayWidth, pad, prettyResult } from "../../pretty.js";
|
|
5
|
+
import { spec } from "../../registry.js";
|
|
6
|
+
import { collectDeployFiles, deployFileReader } from "./files.js";
|
|
7
|
+
import { minifyFile } from "./minify.js";
|
|
8
|
+
import { defaultAuthDeps } from "../../auth/session.js";
|
|
9
|
+
import { uploadDeployment } from "./upload.js";
|
|
10
|
+
import { MANIFEST_FILE, readManifest } from "./manifest.js";
|
|
11
|
+
import { PUBLISH_WAIT_SECONDS, shipDeployment } from "./ship.js";
|
|
12
|
+
import { AGENT_CODES } from "./agents.js";
|
|
13
|
+
import { parseCommand } from "../../runtime/flags.js";
|
|
14
|
+
import { PROJECT } from "../../runtime/project-name.js";
|
|
15
|
+
import { parseTimeout } from "../../runtime/timeout.js";
|
|
16
|
+
const { name: command, usage, prettyUsage } = spec('projects deploy');
|
|
17
|
+
function formatSize(bytes) {
|
|
18
|
+
if (bytes < 1024)
|
|
19
|
+
return `${bytes} B`;
|
|
20
|
+
if (bytes < 1024 * 1024)
|
|
21
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
22
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
23
|
+
}
|
|
24
|
+
export async function runDeploy(input, pretty, depth, deps = { ...defaultAuthDeps(pretty, depth), upload: uploadDeployment }) {
|
|
25
|
+
const invalid = (message) => pretty
|
|
26
|
+
? prettyResult(2, depth, command, message, [['사용법', prettyUsage]])
|
|
27
|
+
: agentResult(2, { command, error: { code: 'invalid_arguments', message }, usage });
|
|
28
|
+
const timeout = parseTimeout(input, PUBLISH_WAIT_SECONDS, pretty);
|
|
29
|
+
if ('error' in timeout)
|
|
30
|
+
return invalid(timeout.error);
|
|
31
|
+
const dryRun = timeout.rest.includes('--dry-run');
|
|
32
|
+
const parsed = parseCommand(timeout.rest.filter((arg) => arg !== '--dry-run'), ['--agent'], pretty);
|
|
33
|
+
if ('error' in parsed)
|
|
34
|
+
return invalid(parsed.error);
|
|
35
|
+
const [project, target] = parsed.names;
|
|
36
|
+
const agent = parsed.entries.find(([flag]) => flag === '--agent')?.[1];
|
|
37
|
+
const problem = parsed.names.length !== 2
|
|
38
|
+
? pretty ? '프로젝트 이름과 배포할 폴더를 하나씩 지정하세요.' : 'Specify the project name and exactly one directory to deploy.'
|
|
39
|
+
: !PROJECT.test(project)
|
|
40
|
+
? pretty ? '프로젝트 이름은 영문 소문자·숫자로 시작하고 끝나는 1~63자의 소문자·숫자·하이픈입니다.' : 'The project name must be 1-63 lowercase letters, digits or hyphens that start and end with a letter or digit.'
|
|
41
|
+
: agent !== undefined && !AGENT_CODES.includes(agent)
|
|
42
|
+
? pretty ? `--agent 에는 ${AGENT_CODES.join(', ')} 중 하나를 지정하세요.` : `--agent must be one of ${AGENT_CODES.join(', ')}.`
|
|
43
|
+
: null;
|
|
44
|
+
if (problem)
|
|
45
|
+
return invalid(problem);
|
|
46
|
+
if (!dryRun && !agent) {
|
|
47
|
+
return pretty
|
|
48
|
+
? prettyResult(2, depth, command, '--agent 로 배포하는 에이전트 코드를 지정하세요. 업로드하지 않았습니다.', [['사용법', prettyUsage], ['코드', AGENT_CODES.join(' ')]])
|
|
49
|
+
: agentResult(2, { command, project, uploaded: false, deployed: false, error: { code: 'agent_required', message: `Specify --agent <code> for the agent running this deploy, one of ${AGENT_CODES.join(', ')}. No files were uploaded.` }, usage });
|
|
50
|
+
}
|
|
51
|
+
const directory = resolve(target);
|
|
52
|
+
if (!(await stat(directory).catch(() => null))?.isDirectory()) {
|
|
53
|
+
return pretty
|
|
54
|
+
? prettyResult(1, depth, command, '배포할 폴더를 찾을 수 없습니다.', [['폴더', directory]])
|
|
55
|
+
: agentResult(1, { command, project, directory, error: { code: 'directory_not_found', message: 'The directory does not exist.' } });
|
|
56
|
+
}
|
|
57
|
+
const reader = await deployFileReader(directory);
|
|
58
|
+
const files = await collectDeployFiles(directory);
|
|
59
|
+
if (files.length === 0) {
|
|
60
|
+
return pretty
|
|
61
|
+
? prettyResult(1, depth, command, '전송할 파일이 없습니다.', [['폴더', directory]])
|
|
62
|
+
: agentResult(1, { command, project, directory, error: { code: 'no_files', message: 'No files to upload after exclusions.' } });
|
|
63
|
+
}
|
|
64
|
+
const read = await readManifest(directory);
|
|
65
|
+
if ('error' in read) {
|
|
66
|
+
return pretty
|
|
67
|
+
? prettyResult(1, depth, command, `${MANIFEST_FILE} 파일을 확인하세요.`, [['폴더', directory], ['원인', read.error]])
|
|
68
|
+
: agentResult(1, { command, project, directory, error: { code: 'invalid_manifest', message: read.error } });
|
|
69
|
+
}
|
|
70
|
+
const { manifest } = read;
|
|
71
|
+
const app = manifest?.start !== undefined;
|
|
72
|
+
const minify = typeof manifest?.build !== 'string' && !app;
|
|
73
|
+
if (!dryRun) {
|
|
74
|
+
return shipDeployment({
|
|
75
|
+
command, project, agent, manifest, context: { project, directory }, success: { files }, rows: [['폴더', directory]], waitMs: timeout.waitMs,
|
|
76
|
+
send: (remote, branch, token, onUploading) => deps.upload(directory, files, remote, branch, token, { onUploading, minify, read: reader })
|
|
77
|
+
}, pretty, depth, deps);
|
|
78
|
+
}
|
|
79
|
+
if (!pretty) {
|
|
80
|
+
return agentResult(0, { command, project, directory, dryRun: true, files, uploaded: false, ...(manifest ? { manifest } : {}) });
|
|
81
|
+
}
|
|
82
|
+
const nameWidth = Math.max(...files.map(displayWidth));
|
|
83
|
+
const rows = [];
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
const content = await readFile(join(directory, file));
|
|
86
|
+
const minified = minify ? await minifyFile(file, content) : content;
|
|
87
|
+
const size = minified.length < content.length ? `${formatSize(content.length)} → ${formatSize(minified.length)}` : formatSize(content.length);
|
|
88
|
+
rows.push([rows.length === 0 ? '파일' : '', `${pad(file, nameWidth)} ${size}`]);
|
|
89
|
+
}
|
|
90
|
+
return prettyResult(0, depth, command, `전송할 파일 ${files.length}개를 확인했습니다. 업로드하지 않았습니다.`, [
|
|
91
|
+
['폴더', directory],
|
|
92
|
+
...(manifest ? [['빌드', `${typeof manifest.build === 'string' ? manifest.build : '빌드 없음'} → ${app ? `${String(manifest.start)} (포트 ${String(manifest.port)})` : String(manifest.output)}`]] : []),
|
|
93
|
+
...rows
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export const MANIFEST_FILE = 'deepdynamic.json';
|
|
4
|
+
const MANIFEST_MAX = 1024;
|
|
5
|
+
export async function readManifest(directory) {
|
|
6
|
+
let text;
|
|
7
|
+
try {
|
|
8
|
+
text = await readFile(join(directory, MANIFEST_FILE), 'utf8');
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
return error.code === 'ENOENT' ? { manifest: null } : { error: `Could not read ${MANIFEST_FILE}.` };
|
|
12
|
+
}
|
|
13
|
+
if (Buffer.byteLength(text) > MANIFEST_MAX)
|
|
14
|
+
return { error: `${MANIFEST_FILE} must be at most ${MANIFEST_MAX} bytes.` };
|
|
15
|
+
try {
|
|
16
|
+
const value = JSON.parse(text);
|
|
17
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
18
|
+
? { manifest: value }
|
|
19
|
+
: { error: `${MANIFEST_FILE} must contain a JSON object.` };
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return { error: `${MANIFEST_FILE} is not valid JSON.` };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { extname } from 'node:path';
|
|
2
|
+
const TARGET = ['chrome107', 'edge107', 'firefox104', 'safari16'];
|
|
3
|
+
const CUSTOM_FRAGMENT = /<%[\s\S]*?%>|<\?[\s\S]*?\?>/;
|
|
4
|
+
const minifyHtml = async (text) => CUSTOM_FRAGMENT.test(text)
|
|
5
|
+
? text
|
|
6
|
+
: (await import('html-minifier-terser')).minify(text, { collapseWhitespace: true, conservativeCollapse: true, removeComments: true, minifyCSS: { inline: false }, minifyJS: true });
|
|
7
|
+
const minifyScript = async (text) => (await (await import('esbuild')).transform(text, { loader: 'js', minify: true, target: TARGET })).code;
|
|
8
|
+
const MINIFIERS = {
|
|
9
|
+
'.html': minifyHtml,
|
|
10
|
+
'.htm': minifyHtml,
|
|
11
|
+
'.css': async (text) => (await (await import('esbuild')).transform(text, { loader: 'css', minify: true, target: TARGET })).code,
|
|
12
|
+
'.js': minifyScript,
|
|
13
|
+
'.mjs': minifyScript
|
|
14
|
+
};
|
|
15
|
+
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
|
16
|
+
export async function minifyFile(path, content) {
|
|
17
|
+
const minifier = MINIFIERS[extname(path).toLowerCase()];
|
|
18
|
+
if (!minifier)
|
|
19
|
+
return content;
|
|
20
|
+
try {
|
|
21
|
+
const minified = Buffer.from(await minifier(utf8.decode(content)));
|
|
22
|
+
return minified.length < content.length ? minified : content;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return content;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { LoginExpiredError, postJson, request } from "../../http/request.js";
|
|
2
|
+
import { jsonLine } from "../../output.js";
|
|
3
|
+
import { plain } from "../../pretty.js";
|
|
4
|
+
import { PROJECT } from "../../runtime/project-name.js";
|
|
5
|
+
const STAGES = ['preparing', 'packing', 'uploading', 'verifying', 'awaiting_publish', 'publishing', 'published', 'failed'];
|
|
6
|
+
const STATUSES = ['running', 'blocked', 'succeeded', 'failed', 'interrupted'];
|
|
7
|
+
const ERROR_CODES = ['publishing_not_configured', 'upload_failed', 'git_verification_failed', 'progress_interrupted', 'publish_failed', 'publish_timeout', 'server_failed', 'project_not_found', 'deploy_stopped'];
|
|
8
|
+
const NEXT_ACTIONS = ['wait_for_publishing_integration', 'inspect_and_retry', 'poll', 'continue_upload', 'done'];
|
|
9
|
+
const LOG_MAX = 4000;
|
|
10
|
+
export const PUBLIC_URL = /^https?:\/\/[a-z0-9.-]{1,250}$/;
|
|
11
|
+
export class ProgressRejected extends Error {
|
|
12
|
+
status;
|
|
13
|
+
constructor(status) {
|
|
14
|
+
super('The server rejected the deployment.');
|
|
15
|
+
this.status = status;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export const DEPLOYMENT_ID = /^[a-f0-9-]{36}$/;
|
|
19
|
+
export function parseProgress(body, token, expected) {
|
|
20
|
+
const value = body;
|
|
21
|
+
const agent = value?.forAgent;
|
|
22
|
+
const human = value?.forHuman;
|
|
23
|
+
const safeText = (text) => typeof text === 'string' && text.length <= 2000 && !/[\x00-\x1f\x7f]/.test(text) && !text.includes(token);
|
|
24
|
+
const safeLog = (text) => text === null
|
|
25
|
+
|| (typeof text === 'string' && text.length <= LOG_MAX && !/[\x00-\x08\x0b-\x1f\x7f]/.test(text) && !text.includes(token));
|
|
26
|
+
const site = value?.publicUrl ?? null;
|
|
27
|
+
if (!value || value.ok !== true || typeof value.id !== 'string' || !DEPLOYMENT_ID.test(value.id) || (expected.id && expected.id !== value.id)
|
|
28
|
+
|| (expected.project ? value.project !== expected.project : typeof value.project !== 'string' || !PROJECT.test(value.project))
|
|
29
|
+
|| (site !== null && (typeof site !== 'string' || !PUBLIC_URL.test(site) || agent?.stage !== 'published'))
|
|
30
|
+
|| !Number.isInteger(value.percent) || value.percent < 0 || value.percent > 100 || typeof value.updatedAt !== 'string' || !Number.isFinite(Date.parse(value.updatedAt))
|
|
31
|
+
|| !human || !safeText(human.message) || !safeText(human.detail) || !agent
|
|
32
|
+
|| !STAGES.includes(agent.stage) || !STATUSES.includes(agent.status)
|
|
33
|
+
|| typeof agent.gitUploaded !== 'boolean' || agent.deployed !== (agent.stage === 'published') || agent.progressBasis !== 'milestones'
|
|
34
|
+
|| (agent.commit !== null && (typeof agent.commit !== 'string' || !/^[a-f0-9]{40}$/.test(agent.commit)))
|
|
35
|
+
|| (agent.errorCode !== null && !ERROR_CODES.includes(agent.errorCode))
|
|
36
|
+
|| !safeLog(agent.publishLog ?? null)
|
|
37
|
+
|| !NEXT_ACTIONS.includes(agent.nextAction)
|
|
38
|
+
|| (agent.pollAfterMs !== null && agent.pollAfterMs !== 2000))
|
|
39
|
+
return null;
|
|
40
|
+
return {
|
|
41
|
+
ok: true, id: value.id, project: value.project, percent: value.percent, updatedAt: new Date(value.updatedAt).toISOString(), publicUrl: site,
|
|
42
|
+
forHuman: { message: human.message, detail: human.detail },
|
|
43
|
+
forAgent: {
|
|
44
|
+
stage: agent.stage, status: agent.status, gitUploaded: agent.gitUploaded, deployed: agent.deployed,
|
|
45
|
+
commit: agent.commit, errorCode: agent.errorCode, publishLog: agent.publishLog ?? null, progressBasis: 'milestones',
|
|
46
|
+
nextAction: agent.nextAction, pollAfterMs: agent.pollAfterMs,
|
|
47
|
+
userMessageFields: ['forHuman.message', 'forHuman.detail']
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function progressTracker(siteUrl, token, project, deps, pretty) {
|
|
52
|
+
let id;
|
|
53
|
+
let latest;
|
|
54
|
+
let lastOutput = '';
|
|
55
|
+
const read = async (body) => {
|
|
56
|
+
const url = new URL(`/api/v1/deployments${id ? `/${id}` : ''}`, siteUrl).href;
|
|
57
|
+
const result = body
|
|
58
|
+
? await postJson(url, token, body, deps, null)
|
|
59
|
+
: await request(url, { method: 'GET', headers: { authorization: `Bearer ${token}` } }, deps, null);
|
|
60
|
+
if (!('failure' in result) && result.status === 401)
|
|
61
|
+
throw new LoginExpiredError('The access token was rejected.');
|
|
62
|
+
if (!id && !('failure' in result) && (result.status === 400 || result.status === 404))
|
|
63
|
+
throw new ProgressRejected(result.status);
|
|
64
|
+
if ('failure' in result || result.status !== 200)
|
|
65
|
+
throw new Error('Progress tracking is unavailable.');
|
|
66
|
+
const parsed = parseProgress(result.body, token, { id, project });
|
|
67
|
+
if (!parsed)
|
|
68
|
+
throw new Error('Invalid progress response.');
|
|
69
|
+
id = parsed.id;
|
|
70
|
+
latest = parsed;
|
|
71
|
+
const output = pretty ? `[${latest.percent}%] ${plain(latest.forHuman.message)}\n${plain(latest.forHuman.detail)}\n`
|
|
72
|
+
: jsonLine({ event: 'deployment_progress', ...latest });
|
|
73
|
+
if (output !== lastOutput)
|
|
74
|
+
deps.stream.write(output);
|
|
75
|
+
lastOutput = output;
|
|
76
|
+
return latest;
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
start: (manifest, agent) => read({ project, ...(manifest ? { manifest } : {}), ...(agent ? { agent } : {}) }),
|
|
80
|
+
update: (stage, commit) => read({ stage, ...(commit ? { commit } : {}) }),
|
|
81
|
+
read: () => read(),
|
|
82
|
+
get latest() { return latest; },
|
|
83
|
+
get url() { return id ? new URL(`/api/v1/deployments/${id}`, siteUrl).href : null; }
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { agentResult } from "../../output.js";
|
|
2
|
+
import { prettyResult } from "../../pretty.js";
|
|
3
|
+
import { signedIn } from "../../auth/session.js";
|
|
4
|
+
import { LoginExpiredError, postJson } from "../../http/request.js";
|
|
5
|
+
import { TransferRejected, validGitRemote } from "./upload.js";
|
|
6
|
+
import { ProgressRejected, progressTracker } from "./progress.js";
|
|
7
|
+
import { MANIFEST_FILE } from "./manifest.js";
|
|
8
|
+
import { supportDisplay, supportMessage } from "../../runtime/support.js";
|
|
9
|
+
export const PUBLISH_WAIT_SECONDS = 15 * 60;
|
|
10
|
+
const PROJECT_BRANCH = /^projects\/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
11
|
+
const READ_RETRIES = 3;
|
|
12
|
+
const PUBLISH_FAILURES = {
|
|
13
|
+
publish_failed: 'The project server could not build or publish this commit. Read progress.forAgent.publishLog, fix the project and deploy again.',
|
|
14
|
+
project_not_found: 'The project no longer exists. Create it with deepdynamic projects create <name>.',
|
|
15
|
+
deploy_stopped: 'The deploy was stopped with deepdynamic projects stop and the project server was turned off. Deploy again to turn it back on.'
|
|
16
|
+
};
|
|
17
|
+
export function publishFailure(code) {
|
|
18
|
+
const message = PUBLISH_FAILURES[code];
|
|
19
|
+
return message ? { message, display: message } : { message: supportMessage(code), display: supportDisplay(code) };
|
|
20
|
+
}
|
|
21
|
+
export async function shipDeployment(shipment, pretty, depth, deps) {
|
|
22
|
+
const { command, project, agent, manifest, context, rows } = shipment;
|
|
23
|
+
let uploaded = false;
|
|
24
|
+
let tracker;
|
|
25
|
+
const failure = (code, message, display = message) => pretty
|
|
26
|
+
? prettyResult(1, depth, command, display, [...rows, ...(tracker?.url ? [['진행 조회', tracker.url]] : [])])
|
|
27
|
+
: agentResult(1, { command, ...context, uploaded, deployed: false, statusUrl: tracker?.url ?? null, progress: tracker?.latest ?? null, error: { code, message } });
|
|
28
|
+
let session = await signedIn(deps);
|
|
29
|
+
for (let renewed = false;; renewed = true) {
|
|
30
|
+
if ('login' in session)
|
|
31
|
+
return session.login;
|
|
32
|
+
tracker = progressTracker(session.siteUrl, session.token, project, deps, pretty);
|
|
33
|
+
try {
|
|
34
|
+
await tracker.start(manifest, agent);
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error instanceof ProgressRejected) {
|
|
39
|
+
return error.status === 404
|
|
40
|
+
? failure('project_not_found', 'You have no project with that name. Check it with deepdynamic projects. No files were uploaded.')
|
|
41
|
+
: failure('invalid_manifest', `The server rejected ${MANIFEST_FILE}. Check it against deepdynamic projects deploy --help. No files were uploaded.`);
|
|
42
|
+
}
|
|
43
|
+
if (renewed || !(error instanceof LoginExpiredError))
|
|
44
|
+
return failure('progress_unavailable', 'Could not start deployment tracking. No files were uploaded.');
|
|
45
|
+
session = await signedIn(deps, true);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const { token, siteUrl } = session;
|
|
49
|
+
const recheck = `deepdynamic deployments ${tracker.latest.id}`;
|
|
50
|
+
const abort = async (code, message, display = message) => {
|
|
51
|
+
try {
|
|
52
|
+
await tracker.update('failed');
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return failure('progress_unavailable', `${message} Could not record the failure; check it with ${recheck}.`, `${display} 실패를 기록하지 못했습니다. ${recheck} 로 확인하세요.`);
|
|
56
|
+
}
|
|
57
|
+
return failure(code, message, display);
|
|
58
|
+
};
|
|
59
|
+
const supportAbort = (code) => abort(code, supportMessage(code), supportDisplay(code));
|
|
60
|
+
const result = await postJson(new URL('/api/v1/git/repository', siteUrl).href, token, { project }, deps, pretty ? '배포 저장소를 준비하고 있습니다.' : null);
|
|
61
|
+
if ('failure' in result)
|
|
62
|
+
return abort(result.failure.code, result.failure.message, result.failure.display);
|
|
63
|
+
if (result.status !== 200)
|
|
64
|
+
return supportAbort('repository_failed');
|
|
65
|
+
const body = result.body;
|
|
66
|
+
if (!body?.ok || typeof body.remote !== 'string' || !validGitRemote(body.remote) || typeof body.branch !== 'string' || !PROJECT_BRANCH.test(body.branch)) {
|
|
67
|
+
return supportAbort('invalid_repository');
|
|
68
|
+
}
|
|
69
|
+
let upload;
|
|
70
|
+
try {
|
|
71
|
+
await tracker.update('packing');
|
|
72
|
+
upload = await shipment.send(body.remote, body.branch, token, async () => { await tracker.update('uploading'); });
|
|
73
|
+
uploaded = true;
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
return error instanceof TransferRejected
|
|
77
|
+
? abort(error.code, error.message)
|
|
78
|
+
: supportAbort('upload_failed');
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
await tracker.update('verifying', upload.commit);
|
|
82
|
+
let progress = await tracker.read();
|
|
83
|
+
const pause = deps.pause ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
84
|
+
for (let misses = 0, deadline = Date.now() + shipment.waitMs; progress.forAgent.status === 'running' && Date.now() < deadline;) {
|
|
85
|
+
await pause(progress.forAgent.pollAfterMs ?? 2000);
|
|
86
|
+
try {
|
|
87
|
+
progress = await tracker.read();
|
|
88
|
+
misses = 0;
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
if (++misses >= READ_RETRIES)
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const verifying = progress.forAgent.status === 'running' && progress.forAgent.stage === 'verifying';
|
|
96
|
+
if (progress.forAgent.commit !== upload.commit || (!progress.forAgent.gitUploaded && !verifying)) {
|
|
97
|
+
return failure('upload_unverified', `Git finished, but the server has not confirmed this commit. Check it with ${recheck}; the site is not published.`);
|
|
98
|
+
}
|
|
99
|
+
if (progress.forAgent.stage === 'failed') {
|
|
100
|
+
const code = progress.forAgent.errorCode ?? 'publish_failed';
|
|
101
|
+
const { message, display } = publishFailure(code);
|
|
102
|
+
return failure(code, message, display);
|
|
103
|
+
}
|
|
104
|
+
if (progress.forAgent.stage !== 'published') {
|
|
105
|
+
return failure('publish_pending', `The site is still being published. Keep running ${recheck} until forAgent.status is succeeded or failed, and do not deploy again before that.`);
|
|
106
|
+
}
|
|
107
|
+
return pretty
|
|
108
|
+
? prettyResult(0, depth, command, `[${progress.percent}%] ${progress.forHuman.message} ${progress.forHuman.detail}`, [
|
|
109
|
+
...(progress.publicUrl ? [['주소', progress.publicUrl]] : []),
|
|
110
|
+
['저장소', body.remote], ['브랜치', body.branch], ['진행 조회', tracker.url]
|
|
111
|
+
])
|
|
112
|
+
: agentResult(0, { command, ...context, ...shipment.success, uploaded: true, changed: upload.changed, deployed: true, remote: body.remote, branch: body.branch, statusUrl: tracker.url, ...progress });
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return failure('progress_unavailable', `Git finished, but progress verification is unavailable. Check ${recheck} before retrying. The site is not published.`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, mkdir, readdir, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { developmentRun } from "../../runtime/run-mode.js";
|
|
6
|
+
import { deployFileReader } from "./files.js";
|
|
7
|
+
import { minifyFile } from "./minify.js";
|
|
8
|
+
export class TransferRejected extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const runGit = (args, cwd, env) => new Promise((resolve, reject) => {
|
|
16
|
+
execFile('git', args, { cwd, env, windowsHide: true, timeout: 180_000, maxBuffer: 1024 * 1024 }, (error, stdout) => {
|
|
17
|
+
if (error && 'code' in error && error.code === 'ENOENT')
|
|
18
|
+
return reject(new Error('Git is required. Install Git and retry.'));
|
|
19
|
+
resolve({ code: error ? typeof error.code === 'number' ? error.code : -1 : 0, stdout });
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
const LOCAL_GIT_ORIGIN = /^http:\/\/(localhost|127\.0\.0\.1):[0-9]{2,5}$/;
|
|
23
|
+
const COMMIT = /^[a-f0-9]{40}$/;
|
|
24
|
+
const IDENTITY = ['-c', 'user.name=DeepDynamic', '-c', 'user.email=uploads@deepdynamic.net', '-c', 'commit.gpgsign=false'];
|
|
25
|
+
export function validGitRemote(remote) {
|
|
26
|
+
try {
|
|
27
|
+
const url = new URL(remote);
|
|
28
|
+
const origin = url.origin === 'https://git.deepdynamic.net' || (developmentRun() && LOCAL_GIT_ORIGIN.test(url.origin));
|
|
29
|
+
return origin && !url.username && !url.password && !url.search && !url.hash
|
|
30
|
+
&& /^\/project-[a-f0-9]{64}\.git$/.test(url.pathname);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function inRepository(remote, branch, token, git, use) {
|
|
37
|
+
if (!validGitRemote(remote) || !/^projects\/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(branch))
|
|
38
|
+
throw new Error('Invalid repository destination.');
|
|
39
|
+
const work = await mkdtemp(join(tmpdir(), 'dd-upload-'));
|
|
40
|
+
try {
|
|
41
|
+
const repository = join(work, 'repository');
|
|
42
|
+
const gitDir = join(work, 'git');
|
|
43
|
+
const hooks = join(work, 'hooks');
|
|
44
|
+
const config = join(work, 'config');
|
|
45
|
+
const askpass = join(work, 'askpass.cjs');
|
|
46
|
+
const wrapper = join(work, 'askpass.sh');
|
|
47
|
+
const slash = (path) => path.replaceAll('\\', '/');
|
|
48
|
+
const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
49
|
+
await mkdir(repository);
|
|
50
|
+
await mkdir(hooks);
|
|
51
|
+
await writeFile(config, '');
|
|
52
|
+
await writeFile(askpass, `const prompt = process.argv[2] ?? '';\nlet origin = '';\ntry { origin = new URL(/'(https?:\\/\\/[^']+)'/.exec(prompt)?.[1] ?? '').origin; } catch {}\nif (origin !== ${JSON.stringify(new URL(remote).origin)}) process.exit(1);\nprocess.stdout.write(prompt.toLowerCase().includes('username') ? 'dd\\n' : (process.env.DEEPDYNAMIC_GIT_TOKEN ?? '') + '\\n');\n`);
|
|
53
|
+
await writeFile(wrapper, `#!/bin/sh\nexec ${quote(slash(process.execPath))} ${quote(slash(askpass))} "$@"\n`, { mode: 0o700 });
|
|
54
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(GIT_|GCM_|CURL_|DEEPDYNAMIC_GIT_TOKEN$|NODE_OPTIONS$)/i.test(key)));
|
|
55
|
+
Object.assign(env, {
|
|
56
|
+
GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: config, GIT_CONFIG_SYSTEM: config,
|
|
57
|
+
GIT_ATTR_NOSYSTEM: '1', GIT_TEMPLATE_DIR: hooks, GIT_TERMINAL_PROMPT: '0', GIT_ALLOW_PROTOCOL: new URL(remote).protocol.slice(0, -1),
|
|
58
|
+
GIT_ASKPASS: slash(wrapper),
|
|
59
|
+
DEEPDYNAMIC_GIT_TOKEN: token
|
|
60
|
+
});
|
|
61
|
+
const run = async (args, allowed = [0]) => {
|
|
62
|
+
const result = await (git ?? runGit)([`--git-dir=${gitDir}`, `--work-tree=${repository}`, '-c', 'credential.helper=', '-c', 'http.followRedirects=false', '-c', `core.hooksPath=${hooks}`, ...args], work, env);
|
|
63
|
+
if (!allowed.includes(result.code))
|
|
64
|
+
throw new Error('Git upload failed. Check your login and retry; concurrent updates are not overwritten.');
|
|
65
|
+
return result;
|
|
66
|
+
};
|
|
67
|
+
await run(['init', '--initial-branch', branch]);
|
|
68
|
+
await run(['remote', 'add', 'origin', remote]);
|
|
69
|
+
return await use(run, repository);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await rm(work, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
export function uploadDeployment(directory, files, remote, branch, token, options = {}) {
|
|
76
|
+
return inRepository(remote, branch, token, options.git, async (run, repository) => {
|
|
77
|
+
if ((await run(['ls-remote', '--exit-code', '--heads', 'origin', `refs/heads/${branch}`], [0, 2])).code === 0) {
|
|
78
|
+
await run(['fetch', '--depth=1', 'origin', `refs/heads/${branch}`]);
|
|
79
|
+
await run(['reset', '--hard', 'FETCH_HEAD']);
|
|
80
|
+
}
|
|
81
|
+
for (const entry of await readdir(repository))
|
|
82
|
+
await rm(join(repository, entry), { recursive: true, force: true });
|
|
83
|
+
const read = options.read ?? await deployFileReader(directory);
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
const original = await read(file);
|
|
86
|
+
const content = options.minify === false ? original : await minifyFile(file, original);
|
|
87
|
+
await mkdir(dirname(join(repository, file)), { recursive: true });
|
|
88
|
+
await writeFile(join(repository, file), content);
|
|
89
|
+
}
|
|
90
|
+
await run(['read-tree', '--empty']);
|
|
91
|
+
await run(['add', '--all', '--force']);
|
|
92
|
+
const changed = (await run(['diff', '--cached', '--quiet'], [0, 1])).code !== 0;
|
|
93
|
+
if (changed)
|
|
94
|
+
await run([...IDENTITY, 'commit', '--quiet', '-m', 'Upload site']);
|
|
95
|
+
const commit = (await run(['rev-parse', 'HEAD'])).stdout.trim();
|
|
96
|
+
if (!COMMIT.test(commit))
|
|
97
|
+
throw new Error('Could not identify the uploaded commit.');
|
|
98
|
+
if (changed) {
|
|
99
|
+
await options.onUploading?.();
|
|
100
|
+
await run(['push', 'origin', `HEAD:refs/heads/${branch}`]);
|
|
101
|
+
}
|
|
102
|
+
return { changed, commit };
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
export function restoreDeployment(remote, branch, token, target, options = {}) {
|
|
106
|
+
if (!COMMIT.test(target))
|
|
107
|
+
return Promise.reject(new Error('Invalid commit.'));
|
|
108
|
+
return inRepository(remote, branch, token, options.git, async (run) => {
|
|
109
|
+
await run(['fetch', 'origin', `refs/heads/${branch}`]);
|
|
110
|
+
if ((await run(['merge-base', '--is-ancestor', target, 'FETCH_HEAD'], [0, 1, 128])).code !== 0) {
|
|
111
|
+
throw new TransferRejected('commit_not_found', 'That commit is not in the project history, so nothing was uploaded. Pick another deployment from deepdynamic projects history <name>.');
|
|
112
|
+
}
|
|
113
|
+
const [head, headTree, tree] = (await run(['rev-parse', 'FETCH_HEAD', 'FETCH_HEAD^{tree}', `${target}^{tree}`])).stdout.trim().split(/\r?\n/);
|
|
114
|
+
if (![head, headTree, tree].every((value) => COMMIT.test(value ?? '')))
|
|
115
|
+
throw new Error('Could not identify the commits to restore.');
|
|
116
|
+
if (tree === headTree)
|
|
117
|
+
return { changed: false, commit: head };
|
|
118
|
+
const commit = (await run([...IDENTITY, 'commit-tree', tree, '-p', head, '-m', `Rollback to ${target}`])).stdout.trim();
|
|
119
|
+
if (!COMMIT.test(commit))
|
|
120
|
+
throw new Error('Could not identify the rollback commit.');
|
|
121
|
+
await options.onUploading?.();
|
|
122
|
+
await run(['push', 'origin', `${commit}:refs/heads/${branch}`]);
|
|
123
|
+
return { changed: true, commit };
|
|
124
|
+
});
|
|
125
|
+
}
|