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.
@@ -0,0 +1,477 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import chalk from 'chalk';
6
+ import ora, {} from 'ora';
7
+ import { CLI_VERSION, DEFAULT_API_URL, EXIT, MIN_NODE_VERSION, PACKAGE_NAME } from '../config/constants.js';
8
+ import { ApiClient } from '../services/api.service.js';
9
+ import { sameChecksum, sha256File } from '../services/checksum.service.js';
10
+ import { downloadPackage } from '../services/download.service.js';
11
+ import { extractArchive } from '../services/extraction.service.js';
12
+ import { discardState, partPath, pendingStates, saveState, stateDir } from '../services/state.service.js';
13
+ import { readInstallationToken } from '../services/token.service.js';
14
+ import { removeOnInterrupt } from '../utils/cleanup.js';
15
+ import { CancelledError, CliError, toCliError } from '../utils/errors.js';
16
+ import { directoryState, ensureWritableDirectory, freeSpace, humanBytes, moveDirectory, removeQuietly, resolveUserPath } from '../utils/filesystem.js';
17
+ import { debug } from '../utils/logger.js';
18
+ import { formatDuration, ProgressBar } from '../utils/progress.js';
19
+ import { ask, banner, box, choose, confirm, details, isInteractive, out, step } from '../utils/terminal.js';
20
+ import { compareVersions, folderNameProblem, normalizeApiUrl, suggestFolderName } from '../utils/validation.js';
21
+ const STEPS = 5;
22
+ /**
23
+ * `tokocode` / `tokocode install`: token → verify → choose folder → redeem → download (resumable)
24
+ * → SHA-256 check → safe extraction → report. Nothing from the package is ever executed.
25
+ */
26
+ export async function runInstall(options, view = {}) {
27
+ const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
28
+ if (view.banner !== false) {
29
+ banner();
30
+ out.line(chalk.bold('Selamat datang di TokoCode!'));
31
+ out.line();
32
+ }
33
+ warnOldNode();
34
+ await withSpinner('Menghubungi server TokoCode…', async () => {
35
+ const meta = await api.meta();
36
+ if (!meta.enabled) {
37
+ throw new CliError('cli_disabled', 'Instalasi lewat CLI sedang dinonaktifkan.', meta.maintenance_message || 'Silakan coba lagi nanti.');
38
+ }
39
+ if (compareVersions(CLI_VERSION, meta.min_cli_version) < 0) {
40
+ throw new CliError('cli_outdated', `Versi TokoCode CLI Anda (${CLI_VERSION}) sudah tidak didukung.`, `Jalankan versi terbaru: npx ${PACKAGE_NAME}@latest`);
41
+ }
42
+ }, { silentSuccess: true });
43
+ if (!options.token && !process.env.TOKOCODE_TOKEN && options.resume !== false) {
44
+ const resumed = await offerResume(api, options);
45
+ if (resumed) {
46
+ return;
47
+ }
48
+ }
49
+ const token = await readInstallationToken(options.token);
50
+ out.line();
51
+ const info = await withSpinner('Memverifikasi installation token…', () => api.verify(token), { silentSuccess: true });
52
+ out.ok('Token berhasil diverifikasi!');
53
+ out.ok('Pembelian berhasil ditemukan!');
54
+ out.ok('Hak akses produk tersedia!');
55
+ out.line();
56
+ describePurchase(info);
57
+ const target = await chooseTarget(info, options);
58
+ out.line();
59
+ if (!options.yes && !(await confirm('Lanjutkan instalasi?', true))) {
60
+ throw new CancelledError();
61
+ }
62
+ out.line();
63
+ out.line(chalk.bold('Memulai proses instalasi...'));
64
+ out.line();
65
+ out.ok(step(1, STEPS, 'Memvalidasi akses'));
66
+ const requestId = randomBytes(18).toString('base64url');
67
+ const redeemed = await withSpinner(step(2, STEPS, 'Menyiapkan sesi download'), () => api.redeem(token, ApiClient.clientInfo(requestId)));
68
+ const state = {
69
+ schema: 1,
70
+ apiUrl: api.baseUrl,
71
+ session: redeemed.session,
72
+ product: redeemed.product,
73
+ package: redeemed.package,
74
+ invoice: redeemed.order.invoice_no,
75
+ target,
76
+ partPath: await choosePartPath(redeemed.session.id, target, redeemed.package.size),
77
+ createdAt: new Date().toISOString(),
78
+ };
79
+ await saveState(state);
80
+ debug('state saved', { dir: stateDir() });
81
+ await performInstall(api, state, options);
82
+ }
83
+ /**
84
+ * `npx tokocode add <name>` for a product the signed-in customer bought: the server issues and redeems an
85
+ * installation token for it, then the usual resumable download, SHA-256 check and safe extraction run.
86
+ */
87
+ export async function runLibraryInstall(api, name, accessToken, options) {
88
+ const requestId = randomBytes(18).toString('base64url');
89
+ const redeemed = await withSpinner(`Menyiapkan ${chalk.bold(name)} dari akun Anda…`, () => api.libraryInstall(name, accessToken, ApiClient.clientInfo(requestId)), { silentSuccess: true });
90
+ out.ok('Pembelian ditemukan di akun Anda!');
91
+ out.line();
92
+ describePurchase(redeemed);
93
+ const target = await chooseTarget(redeemed, options);
94
+ out.line();
95
+ out.ok(step(1, STEPS, 'Memvalidasi akses'));
96
+ out.ok(step(2, STEPS, 'Menyiapkan sesi download'));
97
+ const state = {
98
+ schema: 1,
99
+ apiUrl: api.baseUrl,
100
+ session: redeemed.session,
101
+ product: redeemed.product,
102
+ package: redeemed.package,
103
+ invoice: redeemed.order.invoice_no,
104
+ target,
105
+ partPath: await choosePartPath(redeemed.session.id, target, redeemed.package.size),
106
+ createdAt: new Date().toISOString(),
107
+ };
108
+ await saveState(state);
109
+ await performInstall(api, state, options);
110
+ }
111
+ /**
112
+ * Offers to continue an unfinished installation (download interrupted, terminal closed…).
113
+ *
114
+ * @returns true when an installation was resumed (successfully)
115
+ */
116
+ async function offerResume(api, options) {
117
+ const [state] = await pendingStates(api.baseUrl);
118
+ if (!state) {
119
+ return false;
120
+ }
121
+ out.info(`Ada instalasi yang belum selesai: ${chalk.bold(state.product.name)} v${state.package.version}`);
122
+ out.muted(` Lokasi: ${state.target}`);
123
+ const resume = isInteractive() ? await confirm('Lanjutkan instalasi tersebut?', true) : Boolean(options.yes);
124
+ if (!resume) {
125
+ if (isInteractive() && (await confirm('Hapus data instalasi yang tertunda itu?', false))) {
126
+ await discardState(state.session.id);
127
+ out.muted(' Data instalasi tertunda dihapus.');
128
+ }
129
+ out.line();
130
+ return false;
131
+ }
132
+ out.line();
133
+ out.ok(step(1, STEPS, 'Memvalidasi akses'));
134
+ await withSpinner(step(2, STEPS, 'Memulihkan sesi download'), async () => {
135
+ try {
136
+ const refreshed = await api.refresh(state.session.id, state.session.secret);
137
+ state.session = refreshed.session;
138
+ if (refreshed.package_changed) {
139
+ await removeQuietly(state.partPath);
140
+ }
141
+ state.package = { ...state.package, ...refreshed.package };
142
+ await saveState(state);
143
+ }
144
+ catch (error) {
145
+ const cliError = toCliError(error);
146
+ if (['session_invalid', 'session_closed', 'refresh_exhausted'].includes(cliError.code)) {
147
+ await discardState(state.session.id);
148
+ }
149
+ throw cliError;
150
+ }
151
+ });
152
+ const status = await directoryState(state.target);
153
+ if (status === 'not-empty' || status === 'file') {
154
+ out.warn(`Folder tujuan ${state.target} sekarang sudah berisi file.`);
155
+ state.target = await chooseTarget({ suggested_folder: path.basename(state.target), package: state.package }, { ...options, dir: path.dirname(state.target), name: undefined });
156
+ await saveState(state);
157
+ }
158
+ await performInstall(api, state, options);
159
+ return true;
160
+ }
161
+ async function performInstall(api, state, options) {
162
+ let checksum = '';
163
+ for (let attempt = 1;; attempt++) {
164
+ await downloadStep(api, state);
165
+ const spinner = ora({ text: step(4, STEPS, 'Memverifikasi integritas file (SHA-256)'), stream: process.stdout, discardStdin: false }).start();
166
+ checksum = await sha256File(state.partPath);
167
+ if (sameChecksum(checksum, state.package.sha256)) {
168
+ spinner.succeed(step(4, STEPS, `Memverifikasi integritas file ${chalk.dim('sha256 ' + checksum.slice(0, 12) + '…')}`));
169
+ break;
170
+ }
171
+ spinner.fail(step(4, STEPS, 'Checksum file tidak cocok'));
172
+ await removeQuietly(state.partPath);
173
+ await api.reportFailure(state.session.id, state.session.secret, 'checksum', `expected ${state.package.sha256.slice(0, 12)} got ${checksum.slice(0, 12)}`);
174
+ if (attempt >= 2) {
175
+ throw new CliError('checksum_mismatch', 'Checksum file tidak cocok dengan server.', 'File rusak saat diunduh. Jalankan ulang npx tokocode untuk mengunduh ulang; jika berulang, coba jaringan lain atau hubungi dukungan TokoCode.');
176
+ }
177
+ out.warn('File rusak saat diunduh, mengunduh ulang dari awal…');
178
+ }
179
+ const result = await extractStep(api, state);
180
+ try {
181
+ await api.complete(state.session.id, state.session.secret, checksum);
182
+ }
183
+ catch (error) {
184
+ debug('completion report failed', error.message);
185
+ out.warn('Instalasi berhasil, tetapi laporan ke server belum terkirim (tidak memengaruhi project Anda).');
186
+ }
187
+ await discardState(state.session.id);
188
+ await removeQuietly(state.partPath);
189
+ await showSuccess(state, result.files, result.strippedRoot, result.skippedLinks, options);
190
+ }
191
+ async function downloadStep(api, state) {
192
+ out.line(`${chalk.cyan('…')} ${step(3, STEPS, 'Mengunduh source code')} ${chalk.dim(`(${humanBytes(state.package.size)})`)}`);
193
+ let bar = new ProgressBar('Mengunduh', state.package.size);
194
+ try {
195
+ const result = await downloadPackage({ api, session: state.session, pkg: state.package, partPath: state.partPath }, {
196
+ onProgress: (received) => bar.update(received),
197
+ onNotice: (message) => {
198
+ bar.clear();
199
+ out.warn(message);
200
+ },
201
+ onSessionChange: async (session, pkg) => {
202
+ const sizeChanged = pkg.size !== state.package.size;
203
+ state.session = session;
204
+ state.package = pkg;
205
+ await saveState(state);
206
+ if (sizeChanged) {
207
+ bar = new ProgressBar('Mengunduh', pkg.size);
208
+ }
209
+ },
210
+ });
211
+ state.session = result.session;
212
+ state.package = result.pkg;
213
+ bar.done(state.package.size);
214
+ out.ok(step(3, STEPS, `Mengunduh source code ${chalk.dim(`${humanBytes(state.package.size)} · ${formatDuration(bar.elapsedSeconds())}`)}`));
215
+ }
216
+ catch (error) {
217
+ bar.clear();
218
+ const cliError = toCliError(error);
219
+ await api.reportFailure(state.session.id, state.session.secret, cliError.code === 'enospc' ? 'disk' : 'download', cliError.message);
220
+ if (!['session_invalid', 'session_closed', 'refresh_exhausted', 'payment_incomplete', 'access_denied'].includes(cliError.code)) {
221
+ throw new CliError(cliError.code, cliError.message, `${cliError.hint}\nProgres download tersimpan. Jalankan ulang npx tokocode untuk melanjutkan tanpa token baru.`.trim(), cliError.exitCode, cliError.details);
222
+ }
223
+ await discardState(state.session.id);
224
+ throw cliError;
225
+ }
226
+ }
227
+ async function extractStep(api, state) {
228
+ const parent = path.dirname(state.target);
229
+ await fs.mkdir(parent, { recursive: true });
230
+ const status = await directoryState(state.target);
231
+ if (status === 'not-empty' || status === 'file') {
232
+ throw new CliError('target_not_empty', `Folder ${state.target} sudah berisi file.`, 'Jalankan ulang npx tokocode lalu pilih nama folder lain. File Anda tidak diubah.');
233
+ }
234
+ const staging = path.join(parent, `.tokocode-${path.basename(state.target)}-${randomBytes(4).toString('hex')}`);
235
+ const forget = removeOnInterrupt(staging);
236
+ const spinner = ora({ text: step(5, STEPS, 'Mengekstrak source code'), stream: process.stdout, discardStdin: false }).start();
237
+ try {
238
+ const result = await extractArchive(state.partPath, staging, {
239
+ onProgress: (written, total) => {
240
+ spinner.text = step(5, STEPS, `Mengekstrak source code ${chalk.dim(`${total > 0 ? Math.floor((written / total) * 100) : 100}%`)}`);
241
+ },
242
+ });
243
+ if (status === 'empty') {
244
+ await fs.rm(state.target, { recursive: true, force: true });
245
+ }
246
+ await moveDirectory(staging, state.target);
247
+ forget();
248
+ spinner.succeed(step(5, STEPS, `Mengekstrak source code ${chalk.dim(`${result.files} file`)}`));
249
+ return result;
250
+ }
251
+ catch (error) {
252
+ spinner.fail(step(5, STEPS, 'Ekstraksi gagal'));
253
+ await removeQuietly(staging);
254
+ forget();
255
+ const cliError = toCliError(error);
256
+ await api.reportFailure(state.session.id, state.session.secret, cliError.code === 'enospc' ? 'disk' : 'extract', cliError.message);
257
+ if (cliError.code === 'zip_corrupt') {
258
+ await removeQuietly(state.partPath);
259
+ }
260
+ throw cliError;
261
+ }
262
+ }
263
+ async function showSuccess(state, files, strippedRoot, skippedLinks, options) {
264
+ if (strippedRoot) {
265
+ out.muted(` Folder pembungkus "${strippedRoot}/" dirapikan agar project tidak bersarang.`);
266
+ }
267
+ if (skippedLinks.length > 0) {
268
+ out.warn(`${skippedLinks.length} symbolic link dilewati demi keamanan.`);
269
+ }
270
+ out.line();
271
+ out.line(box([chalk.bold.green('INSTALASI BERHASIL!')], chalk.green));
272
+ out.line();
273
+ out.line(chalk.dim('Produk:'));
274
+ out.line(chalk.bold(state.product.name));
275
+ out.line();
276
+ out.line(chalk.dim('Versi:'));
277
+ out.line(state.package.version);
278
+ out.line();
279
+ out.line(chalk.dim('Lokasi:'));
280
+ out.line(chalk.cyan(state.target));
281
+ out.line();
282
+ out.line(`Source code berhasil diunduh dan diekstrak ${chalk.dim(`(${files} file)`)}.`);
283
+ out.line();
284
+ out.line(chalk.bold('Langkah selanjutnya:'));
285
+ out.line();
286
+ const steps = await nextSteps(state.target);
287
+ steps.forEach((text, index) => out.line(`${index + 1}. ${text}`));
288
+ out.line();
289
+ out.line(chalk.dim('Tidak ada script dari paket yang dijalankan otomatis.'));
290
+ out.line(`Terima kasih telah menggunakan ${chalk.bold('TokoCode')}!`);
291
+ out.line();
292
+ if (isInteractive() && !options.yes && (await confirm('Buka project di VS Code sekarang?', false))) {
293
+ openInVsCode(state.target);
294
+ }
295
+ }
296
+ /**
297
+ * Suggestions based on files in the project (read only; nothing is executed).
298
+ */
299
+ async function nextSteps(target) {
300
+ const has = async (name) => (await fs.stat(path.join(target, name)).then(() => true, () => false));
301
+ const relative = path.relative(process.cwd(), target) || '.';
302
+ const cdPath = relative.startsWith('..') || path.isAbsolute(relative) ? target : relative;
303
+ const steps = [`Buka folder project di VS Code: ${chalk.cyan(`code "${cdPath}"`)}`];
304
+ if (await has('README.md')) {
305
+ steps.push(`Baca dokumentasi ${chalk.cyan('README.md')}.`);
306
+ }
307
+ if (await has('.env.example')) {
308
+ steps.push(`Sesuaikan konfigurasi environment: salin ${chalk.cyan('.env.example')} menjadi ${chalk.cyan('.env')} lalu isi nilainya.`);
309
+ }
310
+ else if (await has('env')) {
311
+ steps.push(`Sesuaikan konfigurasi environment: salin ${chalk.cyan('env')} menjadi ${chalk.cyan('.env')} lalu isi nilainya.`);
312
+ }
313
+ else {
314
+ steps.push('Sesuaikan konfigurasi environment sesuai dokumentasi.');
315
+ }
316
+ const installers = [];
317
+ if (await has('composer.json')) {
318
+ installers.push(chalk.cyan('composer install'));
319
+ }
320
+ if (await has('package.json')) {
321
+ installers.push(chalk.cyan('npm install'));
322
+ }
323
+ if (await has('requirements.txt')) {
324
+ installers.push(chalk.cyan('pip install -r requirements.txt'));
325
+ }
326
+ steps.push(installers.length > 0 ? `Instal dependency: ${installers.join(' dan ')} (di dalam folder project).` : 'Instal dependency sesuai teknologi project.');
327
+ return steps;
328
+ }
329
+ function openInVsCode(target) {
330
+ try {
331
+ const child = process.platform === 'win32'
332
+ // code.cmd needs a shell on Windows; the path is quoted (Windows paths cannot contain ").
333
+ ? spawn(`code "${target}"`, { shell: true, detached: true, stdio: 'ignore' })
334
+ : spawn('code', [target], { detached: true, stdio: 'ignore' });
335
+ child.on('error', () => out.warn('Perintah "code" tidak ditemukan. Buka folder lewat VS Code: File > Open Folder.'));
336
+ child.unref();
337
+ }
338
+ catch {
339
+ out.warn('VS Code tidak dapat dibuka otomatis. Buka folder lewat File > Open Folder.');
340
+ }
341
+ }
342
+ function describePurchase(info) {
343
+ details([
344
+ ['Produk', chalk.bold(info.product.name)],
345
+ ['Kode', info.product.sku],
346
+ ['Versi', info.package.version],
347
+ ['Ukuran', humanBytes(info.package.size)],
348
+ ['Invoice', info.order.invoice_no],
349
+ ['Status', chalk.green('Siap diinstal')],
350
+ ]);
351
+ const changelog = (info.package.changelog ?? '').trim();
352
+ if (changelog !== '') {
353
+ out.line();
354
+ out.line(chalk.dim('Catatan rilis:'));
355
+ const lines = changelog.split('\n').slice(0, 6);
356
+ lines.forEach((line) => out.line(chalk.dim(' ' + line.slice(0, 100))));
357
+ if (changelog.split('\n').length > lines.length) {
358
+ out.line(chalk.dim(' …'));
359
+ }
360
+ }
361
+ out.line();
362
+ }
363
+ /**
364
+ * Asks for (or takes from options) the parent folder and project folder name, and makes sure
365
+ * the destination is new or empty and writable. An existing folder with files is never touched.
366
+ */
367
+ export async function chooseTarget(info, options) {
368
+ const interactive = isInteractive() && !options.yes;
369
+ const suggested = suggestFolderName(options.name ?? info.suggested_folder ?? 'tokocode-project');
370
+ let base = options.dir ? resolveUserPath(options.dir) : process.cwd();
371
+ let name = options.name ?? suggested;
372
+ if (interactive) {
373
+ out.line(chalk.bold('Di mana Anda ingin menginstal project?'));
374
+ out.line();
375
+ out.line(chalk.dim('Direktori saat ini:'));
376
+ out.line(base);
377
+ out.line();
378
+ if (!options.dir) {
379
+ base = resolveUserPath(await ask('Lokasi folder induk (Enter = direktori saat ini):', base));
380
+ }
381
+ if (!options.name) {
382
+ name = await ask('Nama folder project:', suggested);
383
+ }
384
+ }
385
+ for (;;) {
386
+ const problem = folderNameProblem(name);
387
+ if (problem) {
388
+ if (!interactive) {
389
+ throw new CliError('invalid_folder_name', problem, 'Gunakan nama folder lain dengan opsi --name.', EXIT.usage);
390
+ }
391
+ out.fail(problem);
392
+ name = await ask('Nama folder project:', suggested);
393
+ continue;
394
+ }
395
+ const target = path.join(base, name);
396
+ const status = await directoryState(target);
397
+ if (status === 'not-empty' || status === 'file') {
398
+ const what = status === 'file' ? 'Sudah ada file dengan nama tersebut' : 'Folder tersebut sudah berisi file';
399
+ if (!interactive) {
400
+ throw new CliError('target_not_empty', `${what}: ${target}`, 'Gunakan --name atau --dir lain. CLI tidak pernah menimpa file yang sudah ada.', EXIT.usage);
401
+ }
402
+ out.warn(`${what}: ${target}`);
403
+ const action = await choose('Apa yang ingin Anda lakukan?', [
404
+ { value: 'rename', label: 'Gunakan nama folder lain' },
405
+ { value: 'location', label: 'Pilih lokasi lain' },
406
+ { value: 'cancel', label: 'Batalkan instalasi' },
407
+ ]);
408
+ if (action === 'cancel') {
409
+ throw new CancelledError('Instalasi dibatalkan. Tidak ada file yang diubah.');
410
+ }
411
+ if (action === 'location') {
412
+ base = resolveUserPath(await ask('Lokasi folder induk:', base));
413
+ }
414
+ name = await ask('Nama folder project:', status === 'not-empty' ? `${name}-baru` : name);
415
+ continue;
416
+ }
417
+ try {
418
+ await ensureWritableDirectory(base);
419
+ }
420
+ catch (error) {
421
+ const cliError = toCliError(error);
422
+ if (!interactive) {
423
+ throw cliError;
424
+ }
425
+ out.fail(`${cliError.message}`);
426
+ base = resolveUserPath(await ask('Pilih lokasi folder induk lain:', base));
427
+ continue;
428
+ }
429
+ const free = await freeSpace(base);
430
+ if (free !== null && free < info.package.size * 3) {
431
+ out.warn(`Ruang disk tersisa ${humanBytes(free)}; paket ${humanBytes(info.package.size)} (setelah diekstrak bisa lebih besar).`);
432
+ }
433
+ out.line();
434
+ out.line(chalk.dim('Lokasi instalasi:'));
435
+ out.line(chalk.cyan(target));
436
+ return target;
437
+ }
438
+ }
439
+ /**
440
+ * Where the resumable download is kept: the CLI temp folder, or next to the project when the
441
+ * system drive has too little space.
442
+ */
443
+ async function choosePartPath(sessionId, target, size) {
444
+ const preferred = partPath(sessionId);
445
+ const tempFree = await freeSpace(stateDir());
446
+ if (tempFree === null || tempFree > size + 64 * 1024 * 1024) {
447
+ return preferred;
448
+ }
449
+ const nearTarget = path.join(path.dirname(target), `.tokocode-${sessionId}.zip.part`);
450
+ const targetFree = await freeSpace(path.dirname(target));
451
+ if (targetFree !== null && targetFree > size + 64 * 1024 * 1024) {
452
+ return nearTarget;
453
+ }
454
+ throw new CliError('enospc', `Ruang penyimpanan tidak cukup untuk mengunduh ${humanBytes(size)}.`, 'Kosongkan ruang disk, lalu jalankan ulang npx tokocode untuk melanjutkan.');
455
+ }
456
+ function warnOldNode() {
457
+ if (compareVersions(process.versions.node, MIN_NODE_VERSION) < 0) {
458
+ out.warn(`Node.js ${process.versions.node} terdeteksi; disarankan versi ${MIN_NODE_VERSION} atau lebih baru (unduh di nodejs.org).`);
459
+ }
460
+ }
461
+ export async function withSpinner(text, action, options = {}) {
462
+ const spinner = ora({ text, stream: process.stdout, discardStdin: false }).start();
463
+ try {
464
+ const result = await action();
465
+ if (options.silentSuccess) {
466
+ spinner.stop();
467
+ }
468
+ else {
469
+ spinner.succeed();
470
+ }
471
+ return result;
472
+ }
473
+ catch (error) {
474
+ spinner.stop();
475
+ throw error;
476
+ }
477
+ }
@@ -0,0 +1,8 @@
1
+ import { CLI_VERSION, DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
2
+ import { out } from '../utils/terminal.js';
3
+ /** `tokocode version`: CLI, Node.js and platform, useful in support requests. */
4
+ export function runVersion() {
5
+ out.line(`${PACKAGE_NAME} ${CLI_VERSION}`);
6
+ out.muted(`Node.js ${process.versions.node} · ${process.platform}-${process.arch}`);
7
+ out.muted(`Server: ${process.env.TOKOCODE_API_URL || DEFAULT_API_URL}`);
8
+ }
@@ -0,0 +1,52 @@
1
+ import { createRequire } from 'node:module';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ const require = createRequire(import.meta.url);
5
+ const pkg = require('../../package.json');
6
+ /** Package name as published on npm (used in update hints). */
7
+ export const PACKAGE_NAME = pkg.name;
8
+ /** Version of this CLI, sent to the server in the X-TokoCode-CLI header. */
9
+ export const CLI_VERSION = pkg.version;
10
+ /** Store the CLI talks to. Override with --api or TOKOCODE_API_URL (non-secret configuration). */
11
+ export const DEFAULT_API_URL = 'https://tokocode.co-id.id';
12
+ export const API_PREFIX = '/api/v1/cli';
13
+ /** Minimum Node.js version (package.json engines). */
14
+ export const MIN_NODE_VERSION = '18.17.0';
15
+ export const TIMEOUTS = {
16
+ /** JSON API calls. */
17
+ requestMs: 30_000,
18
+ /** A download that receives no byte for this long is retried (with Range). */
19
+ downloadIdleMs: 60_000,
20
+ };
21
+ const positiveInt = (value, fallback) => {
22
+ const parsed = Number.parseInt(value ?? '', 10);
23
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
24
+ };
25
+ export const RETRY = {
26
+ /** Consecutive failed download attempts without progress before giving up (TOKOCODE_DOWNLOAD_RETRIES). */
27
+ downloadAttempts: positiveInt(process.env.TOKOCODE_DOWNLOAD_RETRIES, 8),
28
+ /** Redeem retries after a network error (same request id, so it is safe). */
29
+ redeemAttempts: 3,
30
+ /** Longest wait the CLI accepts from a Retry-After header. */
31
+ maxRetryAfterSeconds: 60,
32
+ };
33
+ export const EXTRACTION_LIMITS = {
34
+ /** More entries than this is treated as a broken or hostile archive. */
35
+ maxEntries: 200_000,
36
+ /** Total uncompressed size limit (zip bomb guard). */
37
+ maxTotalBytes: 20 * 1024 ** 3,
38
+ /** Compression ratio above which a large entry is rejected (zip bomb guard). */
39
+ maxRatio: 1_000,
40
+ /** Entries smaller than this are not ratio-checked (tiny text files compress extremely well). */
41
+ ratioCheckFromBytes: 10 * 1024 ** 2,
42
+ };
43
+ /** Folder (in the OS temp dir) that holds resumable downloads and their state files. */
44
+ export const STATE_DIR = path.join(os.tmpdir(), 'tokocode-cli');
45
+ /** Folder names that are a project's own source folders, never a wrapper to strip. */
46
+ export const SOURCE_DIR_NAMES = new Set(['app', 'src', 'public', 'lib', 'resources', 'config', 'database', 'tests', 'test', 'vendor', 'node_modules', 'system', 'writable', 'assets', 'views', 'routes', 'storage']);
47
+ export const EXIT = {
48
+ ok: 0,
49
+ error: 1,
50
+ usage: 2,
51
+ cancelled: 130,
52
+ };