tokocode 0.0.0-stage → 1.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/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +198 -2
- package/dist/commands/account.js +143 -0
- package/dist/commands/add.js +200 -0
- package/dist/commands/catalog.js +97 -0
- package/dist/commands/doctor.js +96 -0
- package/dist/commands/help.js +38 -0
- package/dist/commands/home.js +99 -0
- package/dist/commands/install.js +477 -0
- package/dist/commands/version.js +8 -0
- package/dist/config/constants.js +52 -0
- package/dist/index.js +143 -0
- package/dist/services/api.service.js +224 -0
- package/dist/services/auth.service.js +61 -0
- package/dist/services/checksum.service.js +23 -0
- package/dist/services/download.service.js +145 -0
- package/dist/services/extraction.service.js +222 -0
- package/dist/services/state.service.js +65 -0
- package/dist/services/token.service.js +39 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/cleanup.js +21 -0
- package/dist/utils/errors.js +77 -0
- package/dist/utils/filesystem.js +138 -0
- package/dist/utils/http.js +72 -0
- package/dist/utils/logger.js +47 -0
- package/dist/utils/progress.js +89 -0
- package/dist/utils/terminal.js +149 -0
- package/dist/utils/validation.js +121 -0
- package/package.json +47 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* TokoCode CLI — installs source code bought on TokoCode: `npx tokocode`.
|
|
4
|
+
*/
|
|
5
|
+
import { Command, Option } from 'commander';
|
|
6
|
+
import { CLI_VERSION, EXIT, PACKAGE_NAME } from './config/constants.js';
|
|
7
|
+
import { helpFooter } from './commands/help.js';
|
|
8
|
+
import { runDoctor } from './commands/doctor.js';
|
|
9
|
+
import { runHome } from './commands/home.js';
|
|
10
|
+
import { runInstall } from './commands/install.js';
|
|
11
|
+
import { runVersion } from './commands/version.js';
|
|
12
|
+
import { runLibrary, runLogin, runLogout, runWhoami } from './commands/account.js';
|
|
13
|
+
import { runAdd } from './commands/add.js';
|
|
14
|
+
import { runInfo, runSearch } from './commands/catalog.js';
|
|
15
|
+
import { runInterruptCleanup } from './utils/cleanup.js';
|
|
16
|
+
import { CliError, toCliError } from './utils/errors.js';
|
|
17
|
+
import { destroyAgents } from './utils/http.js';
|
|
18
|
+
import { debug, setDebug } from './utils/logger.js';
|
|
19
|
+
import { closePrompts, out, printError } from './utils/terminal.js';
|
|
20
|
+
let interrupted = false;
|
|
21
|
+
process.on('SIGINT', () => {
|
|
22
|
+
if (interrupted) {
|
|
23
|
+
process.exit(EXIT.cancelled);
|
|
24
|
+
}
|
|
25
|
+
interrupted = true;
|
|
26
|
+
closePrompts();
|
|
27
|
+
runInterruptCleanup();
|
|
28
|
+
process.stdout.write('\n');
|
|
29
|
+
out.warn('Dibatalkan. Progres download tersimpan; jalankan ulang npx tokocode untuk melanjutkan.');
|
|
30
|
+
process.exit(EXIT.cancelled);
|
|
31
|
+
});
|
|
32
|
+
async function main(argv) {
|
|
33
|
+
const program = new Command();
|
|
34
|
+
program
|
|
35
|
+
.name(PACKAGE_NAME)
|
|
36
|
+
.description('Pasang source code yang sudah Anda beli di TokoCode langsung ke folder project.')
|
|
37
|
+
.version(CLI_VERSION, '-v, --version', 'Tampilkan versi')
|
|
38
|
+
.helpOption('-h, --help', 'Tampilkan bantuan')
|
|
39
|
+
.addHelpCommand(false)
|
|
40
|
+
// Options after a subcommand belong to it (`tokocode doctor --api …`).
|
|
41
|
+
.enablePositionalOptions()
|
|
42
|
+
.showHelpAfterError('(jalankan --help untuk bantuan)')
|
|
43
|
+
.configureOutput({ outputError: (text, write) => write(text) });
|
|
44
|
+
const installOptions = (command) => command
|
|
45
|
+
.option('-t, --token <token>', 'Installation token (TK-XXXX-…); tanpa opsi ini token ditanyakan')
|
|
46
|
+
.option('-d, --dir <path>', 'Folder induk tempat project dibuat (bawaan: direktori saat ini)')
|
|
47
|
+
.option('-n, --name <folder>', 'Nama folder project (bawaan: nama produk)')
|
|
48
|
+
.option('-y, --yes', 'Jangan bertanya konfirmasi (untuk otomatisasi)')
|
|
49
|
+
.option('--no-resume', 'Abaikan instalasi tertunda dan mulai dengan token baru')
|
|
50
|
+
.addOption(new Option('--api <url>', 'Alamat toko (bawaan: https://tokocode.co-id.id)').env('TOKOCODE_API_URL'))
|
|
51
|
+
.option('--debug', 'Tampilkan log diagnosis (token dan secret disamarkan)');
|
|
52
|
+
let exitCode = EXIT.ok;
|
|
53
|
+
const install = async (options) => {
|
|
54
|
+
setDebug(Boolean(options.debug));
|
|
55
|
+
await runInstall(options);
|
|
56
|
+
};
|
|
57
|
+
// Without a command: a menu in a terminal, the installation-token flow with --token/scripts.
|
|
58
|
+
installOptions(program).action(async (options) => {
|
|
59
|
+
setDebug(Boolean(options.debug));
|
|
60
|
+
await runHome(options);
|
|
61
|
+
});
|
|
62
|
+
installOptions(program.command('install').description('Pasang produk dengan installation token (perintah bawaan)')).action(install);
|
|
63
|
+
program
|
|
64
|
+
.command('doctor')
|
|
65
|
+
.description('Periksa Node.js, koneksi ke server, dan izin folder')
|
|
66
|
+
.addOption(new Option('--api <url>', 'Alamat toko').env('TOKOCODE_API_URL'))
|
|
67
|
+
.option('--debug', 'Tampilkan log diagnosis')
|
|
68
|
+
.action(async (options) => {
|
|
69
|
+
setDebug(Boolean(options.debug));
|
|
70
|
+
exitCode = (await runDoctor(options.api)) ? EXIT.ok : EXIT.error;
|
|
71
|
+
});
|
|
72
|
+
program.command('version').description('Tampilkan versi CLI, Node.js, dan sistem').action(() => runVersion());
|
|
73
|
+
// Catalogue, free products and the customer's account (CLI 1.1).
|
|
74
|
+
const apiOption = () => new Option('--api <url>', 'Alamat toko').env('TOKOCODE_API_URL');
|
|
75
|
+
program
|
|
76
|
+
.command('add')
|
|
77
|
+
.alias('get')
|
|
78
|
+
.argument('<nama...>', 'Nama produk dari katalog (lihat npx tokocode search)')
|
|
79
|
+
.description('Pasang produk: yang gratis langsung, yang berbayar dari akun Anda (setelah login)')
|
|
80
|
+
.option('-d, --dir <path>', 'Folder induk (bawaan: direktori saat ini)')
|
|
81
|
+
.option('-n, --name <folder>', 'Nama folder (bawaan: nama produk)')
|
|
82
|
+
.option('-y, --yes', 'Jangan bertanya konfirmasi')
|
|
83
|
+
.addOption(apiOption())
|
|
84
|
+
.option('--debug', 'Tampilkan log diagnosis')
|
|
85
|
+
.action(async (names, options) => {
|
|
86
|
+
setDebug(Boolean(options.debug));
|
|
87
|
+
await runAdd(names, options);
|
|
88
|
+
});
|
|
89
|
+
program
|
|
90
|
+
.command('search')
|
|
91
|
+
.alias('cari')
|
|
92
|
+
.argument('[kata...]', 'Kata kunci (kosongkan untuk semua produk)')
|
|
93
|
+
.description('Cari komponen, template, dan source code di katalog')
|
|
94
|
+
.option('-g, --gratis', 'Hanya produk gratis')
|
|
95
|
+
.option('-j, --jenis <jenis>', 'komponen, template, atau jasa')
|
|
96
|
+
.option('--json', 'Keluaran JSON (untuk skrip)')
|
|
97
|
+
.addOption(apiOption())
|
|
98
|
+
.action(async (words, options) => runSearch(words, options));
|
|
99
|
+
program
|
|
100
|
+
.command('info')
|
|
101
|
+
.argument('<nama>', 'Nama produk')
|
|
102
|
+
.description('Detail produk: harga, versi, paket, dan cara memasang')
|
|
103
|
+
.option('--json', 'Keluaran JSON')
|
|
104
|
+
.addOption(apiOption())
|
|
105
|
+
.action(async (name, options) => runInfo(name, options));
|
|
106
|
+
program
|
|
107
|
+
.command('login')
|
|
108
|
+
.description('Hubungkan CLI ke akun TokoCode (setujui dengan satu klik di browser)')
|
|
109
|
+
.option('--no-browser', 'Jangan buka browser otomatis (salin tautannya sendiri)')
|
|
110
|
+
.addOption(apiOption())
|
|
111
|
+
.option('--debug', 'Tampilkan log diagnosis')
|
|
112
|
+
.action(async (options) => {
|
|
113
|
+
setDebug(Boolean(options.debug));
|
|
114
|
+
await runLogin(options);
|
|
115
|
+
});
|
|
116
|
+
program.command('logout').description('Putuskan CLI ini dari akun TokoCode').addOption(apiOption()).action(async (options) => runLogout(options));
|
|
117
|
+
program.command('whoami').description('Tampilkan akun yang terhubung').option('--json', 'Keluaran JSON').addOption(apiOption()).action(async (options) => runWhoami(options));
|
|
118
|
+
program
|
|
119
|
+
.command('library')
|
|
120
|
+
.alias('produk')
|
|
121
|
+
.description('Produk di akun Anda yang siap dipasang')
|
|
122
|
+
.option('--json', 'Keluaran JSON')
|
|
123
|
+
.addOption(apiOption())
|
|
124
|
+
.action(async (options) => runLibrary(options));
|
|
125
|
+
program.addHelpText('after', helpFooter());
|
|
126
|
+
try {
|
|
127
|
+
await program.parseAsync(argv);
|
|
128
|
+
return exitCode;
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
const cliError = toCliError(error);
|
|
132
|
+
debug('fatal', cliError.details.cause?.stack ?? cliError.stack);
|
|
133
|
+
printError(cliError);
|
|
134
|
+
return cliError instanceof CliError ? cliError.exitCode : EXIT.error;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
closePrompts();
|
|
138
|
+
destroyAgents();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
main(process.argv).then((code) => {
|
|
142
|
+
process.exitCode = code;
|
|
143
|
+
});
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import { API_PREFIX, CLI_VERSION, EXIT, RETRY, TIMEOUTS } from '../config/constants.js';
|
|
3
|
+
import { CliError, isNetworkError, toCliError } from '../utils/errors.js';
|
|
4
|
+
import { openRequest, parseRetryAfter, readBody } from '../utils/http.js';
|
|
5
|
+
import { debug } from '../utils/logger.js';
|
|
6
|
+
/**
|
|
7
|
+
* Client of the TokoCode CLI API (/api/v1/cli). Secrets are only ever sent in headers or JSON
|
|
8
|
+
* bodies over HTTPS, never in URLs; the download URL is always built from the configured store,
|
|
9
|
+
* so a session secret can never be sent to another host.
|
|
10
|
+
*/
|
|
11
|
+
export class ApiClient {
|
|
12
|
+
baseUrl;
|
|
13
|
+
constructor(baseUrl) {
|
|
14
|
+
this.baseUrl = baseUrl;
|
|
15
|
+
}
|
|
16
|
+
static clientInfo(requestId) {
|
|
17
|
+
return { version: CLI_VERSION, platform: `${process.platform}-${process.arch}`, ...(requestId ? { request_id: requestId } : {}) };
|
|
18
|
+
}
|
|
19
|
+
meta() {
|
|
20
|
+
return this.withRetry(() => this.call('GET', '/meta'));
|
|
21
|
+
}
|
|
22
|
+
verify(token) {
|
|
23
|
+
return this.withRetry(() => this.call('POST', '/tokens/verify', { token }));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Redeems once; a network failure is retried with the same request id, which the server
|
|
27
|
+
* recognises and answers with the same session (a lost response does not burn the token).
|
|
28
|
+
*/
|
|
29
|
+
redeem(token, client) {
|
|
30
|
+
return this.withRetry(() => this.call('POST', '/tokens/redeem', { token, client }), RETRY.redeemAttempts);
|
|
31
|
+
}
|
|
32
|
+
refresh(sessionId, secret) {
|
|
33
|
+
return this.withRetry(() => this.call('POST', `/downloads/${sessionId}/refresh`, {}, secret));
|
|
34
|
+
}
|
|
35
|
+
complete(sessionId, secret, sha256) {
|
|
36
|
+
return this.withRetry(() => this.call('POST', `/downloads/${sessionId}/complete`, { sha256, client: ApiClient.clientInfo() }, secret));
|
|
37
|
+
}
|
|
38
|
+
/** Best-effort failure report; never throws. */
|
|
39
|
+
async reportFailure(sessionId, secret, stage, reason) {
|
|
40
|
+
try {
|
|
41
|
+
await this.call('POST', `/downloads/${sessionId}/failed`, { stage, reason: reason.slice(0, 250) }, secret);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
debug('failure report not delivered', error.message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/* Catalogue and free products (no account). */
|
|
48
|
+
catalog(query = {}) {
|
|
49
|
+
const params = new URLSearchParams();
|
|
50
|
+
if (query.q) {
|
|
51
|
+
params.set('q', query.q);
|
|
52
|
+
}
|
|
53
|
+
if (query.kind) {
|
|
54
|
+
params.set('kind', query.kind);
|
|
55
|
+
}
|
|
56
|
+
if (query.free) {
|
|
57
|
+
params.set('free', '1');
|
|
58
|
+
}
|
|
59
|
+
const suffix = params.toString();
|
|
60
|
+
return this.withRetry(() => this.call('GET', `/catalog${suffix ? `?${suffix}` : ''}`));
|
|
61
|
+
}
|
|
62
|
+
product(name) {
|
|
63
|
+
return this.withRetry(() => this.call('GET', `/products/${encodeURIComponent(name)}`));
|
|
64
|
+
}
|
|
65
|
+
/** Opens the ZIP stream of a free product (200/206; 416 when the part file is complete). */
|
|
66
|
+
async openFreePackage(name, start, etag) {
|
|
67
|
+
const headers = this.headers({ Accept: 'application/zip, application/json' });
|
|
68
|
+
if (start > 0) {
|
|
69
|
+
headers.Range = `bytes=${start}-`;
|
|
70
|
+
headers['If-Range'] = `"${etag}"`;
|
|
71
|
+
}
|
|
72
|
+
const response = await openRequest({ method: 'GET', url: `${this.baseUrl}${API_PREFIX}/free/${encodeURIComponent(name)}/package`, headers, timeoutMs: TIMEOUTS.downloadIdleMs });
|
|
73
|
+
const status = response.statusCode ?? 0;
|
|
74
|
+
if (status === 200 || status === 206 || status === 416) {
|
|
75
|
+
return response;
|
|
76
|
+
}
|
|
77
|
+
throw await this.errorFrom(response);
|
|
78
|
+
}
|
|
79
|
+
/* `npx tokocode login` and the customer's library (access token in Authorization). */
|
|
80
|
+
deviceStart(client) {
|
|
81
|
+
return this.withRetry(() => this.call('POST', '/auth/device', { client }));
|
|
82
|
+
}
|
|
83
|
+
/** One poll; "authorization_pending" comes back as a CliError for the caller to wait on. */
|
|
84
|
+
deviceToken(deviceCode) {
|
|
85
|
+
return this.call('POST', '/auth/token', { device_code: deviceCode });
|
|
86
|
+
}
|
|
87
|
+
me(accessToken) {
|
|
88
|
+
return this.withRetry(() => this.call('GET', '/me', undefined, accessToken));
|
|
89
|
+
}
|
|
90
|
+
library(accessToken) {
|
|
91
|
+
return this.withRetry(() => this.call('GET', '/library', undefined, accessToken));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Prepares the install of an owned product: the server issues and redeems an installation token and
|
|
95
|
+
* answers like redeem (purchase details + download session).
|
|
96
|
+
*/
|
|
97
|
+
libraryInstall(name, accessToken, client) {
|
|
98
|
+
return this.withRetry(() => this.call('POST', `/library/${encodeURIComponent(name)}/install`, { client }, accessToken), 2);
|
|
99
|
+
}
|
|
100
|
+
async logout(accessToken) {
|
|
101
|
+
await this.call('POST', '/auth/logout', {}, accessToken);
|
|
102
|
+
}
|
|
103
|
+
downloadUrl(sessionId) {
|
|
104
|
+
return `${this.baseUrl}${API_PREFIX}/downloads/${sessionId}`;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Opens the package stream. Returns the raw response for 200/206/416; other statuses are
|
|
108
|
+
* converted into the server's CliError.
|
|
109
|
+
*/
|
|
110
|
+
async openDownload(sessionId, secret, start, etag) {
|
|
111
|
+
const headers = this.headers({ Accept: 'application/zip, application/json', Authorization: `Bearer ${secret}`, 'X-TokoCode-Session': secret });
|
|
112
|
+
if (start > 0) {
|
|
113
|
+
headers.Range = `bytes=${start}-`;
|
|
114
|
+
headers['If-Range'] = `"${etag}"`;
|
|
115
|
+
}
|
|
116
|
+
const response = await openRequest({ method: 'GET', url: this.downloadUrl(sessionId), headers, timeoutMs: TIMEOUTS.downloadIdleMs });
|
|
117
|
+
const status = response.statusCode ?? 0;
|
|
118
|
+
if (status === 200 || status === 206 || status === 416) {
|
|
119
|
+
return response;
|
|
120
|
+
}
|
|
121
|
+
throw await this.errorFrom(response);
|
|
122
|
+
}
|
|
123
|
+
async call(method, path, body, secret) {
|
|
124
|
+
const headers = this.headers(secret ? { Authorization: `Bearer ${secret}`, 'X-TokoCode-Session': secret } : {});
|
|
125
|
+
if (body !== undefined) {
|
|
126
|
+
headers['Content-Type'] = 'application/json';
|
|
127
|
+
}
|
|
128
|
+
const response = await openRequest({
|
|
129
|
+
method,
|
|
130
|
+
url: `${this.baseUrl}${API_PREFIX}${path}`,
|
|
131
|
+
headers,
|
|
132
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
133
|
+
timeoutMs: TIMEOUTS.requestMs,
|
|
134
|
+
});
|
|
135
|
+
const status = response.statusCode ?? 0;
|
|
136
|
+
const text = await readBody(response);
|
|
137
|
+
const envelope = parseEnvelope(text);
|
|
138
|
+
debug(`← ${status} ${path}`, envelope && !envelope.ok ? envelope.error : undefined);
|
|
139
|
+
if (envelope?.ok === true && status >= 200 && status < 300) {
|
|
140
|
+
return envelope.data;
|
|
141
|
+
}
|
|
142
|
+
if (envelope && envelope.ok === false) {
|
|
143
|
+
throw new CliError(envelope.error.code, envelope.error.message, envelope.error.hint, EXIT.error, { status, retryAfter: parseRetryAfter(response.headers['retry-after']) });
|
|
144
|
+
}
|
|
145
|
+
throw unavailable(status, response.headers.location);
|
|
146
|
+
}
|
|
147
|
+
async errorFrom(response) {
|
|
148
|
+
const status = response.statusCode ?? 0;
|
|
149
|
+
let text = '';
|
|
150
|
+
try {
|
|
151
|
+
text = await readBody(response, 64 * 1024);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// The status alone is enough to explain the failure.
|
|
155
|
+
}
|
|
156
|
+
const envelope = parseEnvelope(text);
|
|
157
|
+
if (envelope && envelope.ok === false) {
|
|
158
|
+
return new CliError(envelope.error.code, envelope.error.message, envelope.error.hint, EXIT.error, { status, retryAfter: parseRetryAfter(response.headers['retry-after']) });
|
|
159
|
+
}
|
|
160
|
+
return unavailable(status, response.headers.location);
|
|
161
|
+
}
|
|
162
|
+
headers(extra = {}) {
|
|
163
|
+
return {
|
|
164
|
+
'User-Agent': `tokocode-cli/${CLI_VERSION} (${process.platform} ${os.release()}; node ${process.version})`,
|
|
165
|
+
'X-TokoCode-CLI': CLI_VERSION,
|
|
166
|
+
Accept: 'application/json',
|
|
167
|
+
...extra,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Retries network failures and 5xx/429 answers with exponential backoff (Retry-After honoured).
|
|
172
|
+
*/
|
|
173
|
+
async withRetry(action, attempts = 3) {
|
|
174
|
+
let lastError;
|
|
175
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
176
|
+
try {
|
|
177
|
+
return await action();
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
lastError = error;
|
|
181
|
+
const retryable = isNetworkError(error)
|
|
182
|
+
|| (error instanceof CliError && (error.code === 'server_unavailable' || error.code === 'rate_limited' || error.code === 'server_busy' || error.code === 'internal_error'));
|
|
183
|
+
if (!retryable || attempt === attempts) {
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
const wait = error instanceof CliError && error.retryAfter !== undefined
|
|
187
|
+
? Math.min(error.retryAfter, RETRY.maxRetryAfterSeconds) * 1000
|
|
188
|
+
: 1000 * 2 ** (attempt - 1);
|
|
189
|
+
debug(`retry ${attempt}/${attempts - 1} in ${wait}ms`, error.message);
|
|
190
|
+
await sleep(wait);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
throw toCliError(lastError);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function parseEnvelope(text) {
|
|
197
|
+
try {
|
|
198
|
+
const value = JSON.parse(text);
|
|
199
|
+
return value && typeof value === 'object' && 'ok' in value ? value : null;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function unavailable(status, location) {
|
|
206
|
+
// Redirects are never followed: the session secret must only reach the configured store.
|
|
207
|
+
if (status >= 300 && status < 400 && location) {
|
|
208
|
+
let target = location;
|
|
209
|
+
try {
|
|
210
|
+
target = new URL(location).origin;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
// Relative Location: show it as is.
|
|
214
|
+
}
|
|
215
|
+
return new CliError('api_redirect', `Alamat toko dialihkan ke ${target}.`, `Jalankan ulang dengan alamat yang benar: --api ${target}`, EXIT.error, { status });
|
|
216
|
+
}
|
|
217
|
+
if (status === 404) {
|
|
218
|
+
return new CliError('api_not_found', 'Layanan instalasi tidak ditemukan di server ini.', 'Pastikan alamat toko benar (opsi --api atau TOKOCODE_API_URL) dan website sudah diperbarui.', EXIT.error, { status });
|
|
219
|
+
}
|
|
220
|
+
return new CliError('server_unavailable', `Server TokoCode sedang tidak tersedia${status ? ` (HTTP ${status})` : ''}.`, 'Coba lagi beberapa saat lagi. Jika berulang, hubungi dukungan TokoCode.', EXIT.error, { status });
|
|
221
|
+
}
|
|
222
|
+
export function sleep(ms) {
|
|
223
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
224
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { debug } from '../utils/logger.js';
|
|
5
|
+
/**
|
|
6
|
+
* Where `npx tokocode login` keeps its access token: one entry per store address, in a file only the current
|
|
7
|
+
* user can read (0600 in a 0700 folder). TOKOCODE_CONFIG_DIR overrides the location (tests, CI).
|
|
8
|
+
*/
|
|
9
|
+
export function configDir() {
|
|
10
|
+
if (process.env.TOKOCODE_CONFIG_DIR) {
|
|
11
|
+
return process.env.TOKOCODE_CONFIG_DIR;
|
|
12
|
+
}
|
|
13
|
+
if (process.platform === 'win32') {
|
|
14
|
+
return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'tokocode');
|
|
15
|
+
}
|
|
16
|
+
return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'tokocode');
|
|
17
|
+
}
|
|
18
|
+
export function authFile() {
|
|
19
|
+
return path.join(configDir(), 'auth.json');
|
|
20
|
+
}
|
|
21
|
+
async function readAll() {
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(await fs.readFile(authFile(), 'utf8'));
|
|
24
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function writeAll(all) {
|
|
31
|
+
await fs.mkdir(configDir(), { recursive: true, mode: 0o700 });
|
|
32
|
+
const target = authFile();
|
|
33
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
34
|
+
await fs.writeFile(temporary, JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
|
|
35
|
+
await fs.rename(temporary, target);
|
|
36
|
+
await fs.chmod(target, 0o600).catch(() => undefined);
|
|
37
|
+
}
|
|
38
|
+
/** The saved login for this store, or null (missing, malformed or expired). */
|
|
39
|
+
export async function loadLogin(apiUrl) {
|
|
40
|
+
const login = (await readAll())[apiUrl];
|
|
41
|
+
if (!login || typeof login.token !== 'string' || !login.token.startsWith('tca_')) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
if (Date.parse(login.expires_at) <= Date.now()) {
|
|
45
|
+
debug('saved login expired', { apiUrl });
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
return login;
|
|
49
|
+
}
|
|
50
|
+
export async function saveLogin(apiUrl, login) {
|
|
51
|
+
const all = await readAll();
|
|
52
|
+
all[apiUrl] = login;
|
|
53
|
+
await writeAll(all);
|
|
54
|
+
}
|
|
55
|
+
export async function forgetLogin(apiUrl) {
|
|
56
|
+
const all = await readAll();
|
|
57
|
+
if (all[apiUrl]) {
|
|
58
|
+
delete all[apiUrl];
|
|
59
|
+
await writeAll(all);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { createReadStream } from 'node:fs';
|
|
3
|
+
/**
|
|
4
|
+
* SHA-256 of a file, streamed (constant memory whatever the size).
|
|
5
|
+
*/
|
|
6
|
+
export function sha256File(file, onProgress) {
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const hash = createHash('sha256');
|
|
9
|
+
let bytes = 0;
|
|
10
|
+
const stream = createReadStream(file, { highWaterMark: 1024 * 1024 });
|
|
11
|
+
stream.on('data', (chunk) => {
|
|
12
|
+
hash.update(chunk);
|
|
13
|
+
bytes += chunk.length;
|
|
14
|
+
onProgress?.(bytes);
|
|
15
|
+
});
|
|
16
|
+
stream.on('error', reject);
|
|
17
|
+
stream.on('end', () => resolve(hash.digest('hex')));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/** Constant-time comparison is not needed (public checksums); case is normalised. */
|
|
21
|
+
export function sameChecksum(a, b) {
|
|
22
|
+
return a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
23
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { Transform } from 'node:stream';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { RETRY } from '../config/constants.js';
|
|
6
|
+
import { CliError, isNetworkError, toCliError } from '../utils/errors.js';
|
|
7
|
+
import { fileSize } from '../utils/filesystem.js';
|
|
8
|
+
import { debug } from '../utils/logger.js';
|
|
9
|
+
import { sleep } from './api.service.js';
|
|
10
|
+
/**
|
|
11
|
+
* Streams the package to `partPath`, resuming with HTTP Range after any interruption.
|
|
12
|
+
*
|
|
13
|
+
* - Network drops and stalls: retried with backoff from the bytes already on disk.
|
|
14
|
+
* - 503/429 (server busy, rate limit): waits for Retry-After, then continues.
|
|
15
|
+
* - session_expired: refreshes the session (new secret) and continues.
|
|
16
|
+
* - package_changed: refreshes, discards the partial file and starts the new build.
|
|
17
|
+
* - A server that ignores Range (200) restarts the file from zero.
|
|
18
|
+
*
|
|
19
|
+
* Resolves with the final session and package (both may have changed on the way).
|
|
20
|
+
*/
|
|
21
|
+
export async function downloadPackage(job, callbacks = {}) {
|
|
22
|
+
let { session, pkg } = job;
|
|
23
|
+
let failures = 0;
|
|
24
|
+
let refreshedForExpiry = false;
|
|
25
|
+
for (;;) {
|
|
26
|
+
if (job.signal?.aborted) {
|
|
27
|
+
throw new CliError('cancelled', 'Download dibatalkan.');
|
|
28
|
+
}
|
|
29
|
+
let existing = await fileSize(job.partPath);
|
|
30
|
+
if (existing > pkg.size) {
|
|
31
|
+
await fs.rm(job.partPath, { force: true });
|
|
32
|
+
existing = 0;
|
|
33
|
+
}
|
|
34
|
+
if (existing === pkg.size && pkg.size > 0) {
|
|
35
|
+
callbacks.onProgress?.(existing, pkg.size);
|
|
36
|
+
return { session, pkg };
|
|
37
|
+
}
|
|
38
|
+
if (existing > 0) {
|
|
39
|
+
callbacks.onNotice?.(`Melanjutkan download dari ${Math.floor((existing / pkg.size) * 100)}%`);
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const before = existing;
|
|
43
|
+
await fetchRange(job, session, pkg, existing, callbacks);
|
|
44
|
+
const after = await fileSize(job.partPath);
|
|
45
|
+
if (after > before) {
|
|
46
|
+
failures = 0;
|
|
47
|
+
}
|
|
48
|
+
refreshedForExpiry = false;
|
|
49
|
+
}
|
|
50
|
+
catch (rawError) {
|
|
51
|
+
const error = rawError instanceof CliError ? rawError : null;
|
|
52
|
+
if (error?.code === 'session_expired' && !refreshedForExpiry) {
|
|
53
|
+
callbacks.onNotice?.('Sesi download habis, memperbarui sesi…');
|
|
54
|
+
({ session, pkg } = await refreshSession(job, session, pkg, callbacks));
|
|
55
|
+
refreshedForExpiry = true;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (error?.code === 'package_changed') {
|
|
59
|
+
callbacks.onNotice?.('Paket diperbarui di server, mengunduh versi terbaru…');
|
|
60
|
+
({ session, pkg } = await refreshSession(job, session, pkg, callbacks));
|
|
61
|
+
await fs.rm(job.partPath, { force: true });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (error?.code === 'range_invalid') {
|
|
65
|
+
await fs.rm(job.partPath, { force: true });
|
|
66
|
+
failures++;
|
|
67
|
+
if (failures > RETRY.downloadAttempts) {
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const busy = error && (error.code === 'server_busy' || error.code === 'rate_limited' || error.code === 'server_unavailable' || error.code === 'internal_error');
|
|
73
|
+
if (!busy && !isNetworkError(rawError) && !(rawError instanceof StallError)) {
|
|
74
|
+
throw toCliError(rawError);
|
|
75
|
+
}
|
|
76
|
+
failures++;
|
|
77
|
+
if (failures > RETRY.downloadAttempts) {
|
|
78
|
+
throw new CliError('download_failed', 'Download gagal setelah beberapa kali percobaan.', 'Periksa koneksi internet Anda, lalu jalankan ulang npx tokocode: download dilanjutkan dari bagian yang sudah tersimpan.', 1, { cause: rawError });
|
|
79
|
+
}
|
|
80
|
+
const wait = error?.retryAfter !== undefined
|
|
81
|
+
? Math.min(error.retryAfter, RETRY.maxRetryAfterSeconds) * 1000
|
|
82
|
+
: Math.min(30_000, 1000 * 2 ** (failures - 1));
|
|
83
|
+
callbacks.onNotice?.(error?.code === 'server_busy'
|
|
84
|
+
? `Server sedang sibuk, mencoba lagi dalam ${Math.ceil(wait / 1000)} detik…`
|
|
85
|
+
: `Koneksi terputus, mencoba lagi dalam ${Math.ceil(wait / 1000)} detik (percobaan ${failures}/${RETRY.downloadAttempts})…`);
|
|
86
|
+
debug('download retry', rawError.message);
|
|
87
|
+
await sleep(wait);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
class StallError extends Error {
|
|
92
|
+
code = 'ETIMEDOUT';
|
|
93
|
+
}
|
|
94
|
+
async function fetchRange(job, session, pkg, start, callbacks) {
|
|
95
|
+
const response = await job.api.openDownload(session.id, session.secret, start, pkg.sha256);
|
|
96
|
+
const status = response.statusCode ?? 0;
|
|
97
|
+
if (status === 416) {
|
|
98
|
+
response.resume();
|
|
99
|
+
throw new CliError('range_invalid', 'Bagian file tidak tersedia.', '');
|
|
100
|
+
}
|
|
101
|
+
let offset = start;
|
|
102
|
+
let flags = 'a';
|
|
103
|
+
if (status === 200) {
|
|
104
|
+
// Full body: the server ignored the Range or the file changed (If-Range mismatch).
|
|
105
|
+
offset = 0;
|
|
106
|
+
flags = 'w';
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(String(response.headers['content-range'] ?? ''));
|
|
110
|
+
if (!match || Number(match[1]) !== start || Number(match[3]) !== pkg.size) {
|
|
111
|
+
response.resume();
|
|
112
|
+
await fs.rm(job.partPath, { force: true });
|
|
113
|
+
throw new CliError('range_invalid', 'Respons Range tidak sesuai.', '');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const declared = Number(response.headers['content-length'] ?? NaN);
|
|
117
|
+
if (Number.isFinite(declared) && offset + declared > pkg.size) {
|
|
118
|
+
response.resume();
|
|
119
|
+
throw new CliError('package_changed', 'Ukuran paket berbeda dengan informasi server.', '');
|
|
120
|
+
}
|
|
121
|
+
let received = offset;
|
|
122
|
+
const counter = new Transform({
|
|
123
|
+
transform(chunk, _encoding, done) {
|
|
124
|
+
received += chunk.length;
|
|
125
|
+
if (received > pkg.size) {
|
|
126
|
+
done(new CliError('package_changed', 'Ukuran paket melebihi informasi server.', ''));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
callbacks.onProgress?.(received, pkg.size);
|
|
130
|
+
done(null, chunk);
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
// A socket that stays silent is destroyed by the request timeout; surface it as a stall.
|
|
134
|
+
response.on('aborted', () => response.destroy(new StallError('Download terhenti.')));
|
|
135
|
+
await pipeline(response, counter, createWriteStream(job.partPath, { flags }), { signal: job.signal });
|
|
136
|
+
if (received < pkg.size) {
|
|
137
|
+
throw Object.assign(new Error('Koneksi terputus sebelum download selesai.'), { code: 'ECONNRESET' });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function refreshSession(job, session, pkg, callbacks) {
|
|
141
|
+
const refreshed = await job.api.refresh(session.id, session.secret);
|
|
142
|
+
const next = { session: refreshed.session, pkg: { ...pkg, ...refreshed.package } };
|
|
143
|
+
await callbacks.onSessionChange?.(next.session, next.pkg);
|
|
144
|
+
return next;
|
|
145
|
+
}
|