tokocode 1.0.0 → 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 +8 -0
- package/README.md +21 -0
- package/dist/commands/account.js +143 -0
- package/dist/commands/add.js +200 -0
- package/dist/commands/catalog.js +97 -0
- package/dist/commands/help.js +13 -2
- package/dist/commands/home.js +99 -0
- package/dist/commands/install.js +39 -9
- package/dist/index.js +61 -1
- package/dist/services/api.service.js +56 -0
- package/dist/services/auth.service.js +61 -0
- package/dist/utils/logger.js +3 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0 — 2026-11-17
|
|
4
|
+
|
|
5
|
+
- `search` / `info`: katalog TokoCode dari terminal (harga, label gratis, jenis, `--json`).
|
|
6
|
+
- `add <nama...>`: produk gratis terpasang tanpa akun (unduh, SHA-256, ekstraksi aman ke `./<nama>`); produk berbayar dipasang dari akun setelah `login`, tanpa menyalin token.
|
|
7
|
+
- `npx tokocode` tanpa perintah membuka menu: pasang komponen gratis, cari di katalog, pasang produk yang sudah dibeli, pasang dengan installation token, atau lihat semua perintah. Dengan `--token`, `TOKOCODE_TOKEN`, `--yes`, unduhan tertunda, atau tanpa terminal (skrip/CI), alur installation token tetap berjalan langsung.
|
|
8
|
+
- Perbaikan Windows: pertanyaan yang muncul setelah spinner (misalnya lokasi folder setelah verifikasi token) tidak lagi menunggu tanpa bisa diketik.
|
|
9
|
+
- `login` (device login: kode di terminal, satu klik "Izinkan" di browser), `whoami`, `library`, `logout`. Kunci akses disimpan dengan izin 0600 dan disamarkan di log.
|
|
10
|
+
|
|
3
11
|
## 1.0.0 — 2026-11-07
|
|
4
12
|
|
|
5
13
|
Rilis pertama.
|
package/README.md
CHANGED
|
@@ -34,6 +34,27 @@ Status : Siap diinstal
|
|
|
34
34
|
INSTALASI BERHASIL!
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
+
## Perintah utama (versi 1.1)
|
|
38
|
+
|
|
39
|
+
| Perintah | Fungsi |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `npx tokocode search [kata] [--gratis] [--jenis komponen|template|jasa]` | Cari produk di katalog, lengkap dengan harga dan label gratis |
|
|
42
|
+
| `npx tokocode info <nama>` | Detail produk: harga, versi, ukuran paket, cara memasang |
|
|
43
|
+
| `npx tokocode add <nama...>` | Pasang produk **gratis** tanpa akun, atau produk yang sudah Anda beli (setelah `login`) ke `./<nama>` |
|
|
44
|
+
| `npx tokocode login` | Hubungkan CLI ke akun: buka tautan, klik **Izinkan**, selesai (tanpa mengetik password) |
|
|
45
|
+
| `npx tokocode library` | Produk di akun Anda yang siap dipasang |
|
|
46
|
+
| `npx tokocode whoami` · `logout` | Akun yang terhubung · putuskan CLI dari akun |
|
|
47
|
+
| `npx tokocode` / `--token TK-…` | Pasang dengan installation token (cara di bawah, tetap didukung) |
|
|
48
|
+
| `npx tokocode doctor` | Periksa Node.js, koneksi, dan izin folder |
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
npx tokocode add liquid-toggle # komponen gratis, langsung terpasang
|
|
52
|
+
npx tokocode login # sekali saja, untuk produk berbayar
|
|
53
|
+
npx tokocode add template-kopi-senja # produk yang sudah dibeli, tanpa menyalin token
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Login disimpan di `%APPDATA%\tokocode\auth.json` (Windows) atau `~/.config/tokocode/auth.json` (izin 0600); server hanya menyimpan hash-nya, berlaku 90 hari, dan bisa diputus kapan saja di **Akun > Instalasi CLI**. Opsi `--json` pada `search`, `info`, `whoami`, dan `library` memberi keluaran untuk skrip.
|
|
57
|
+
|
|
37
58
|
## 1. Persyaratan
|
|
38
59
|
|
|
39
60
|
| Kebutuhan | Keterangan |
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import ora from 'ora';
|
|
5
|
+
import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
|
|
6
|
+
import { ApiClient } from '../services/api.service.js';
|
|
7
|
+
import { forgetLogin, loadLogin, saveLogin } from '../services/auth.service.js';
|
|
8
|
+
import { CliError, toCliError } from '../utils/errors.js';
|
|
9
|
+
import { debug } from '../utils/logger.js';
|
|
10
|
+
import { box, details, out } from '../utils/terminal.js';
|
|
11
|
+
import { normalizeApiUrl } from '../utils/validation.js';
|
|
12
|
+
import { printTable } from './catalog.js';
|
|
13
|
+
import { withSpinner } from './install.js';
|
|
14
|
+
function client(api) {
|
|
15
|
+
return new ApiClient(normalizeApiUrl(api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
|
|
16
|
+
}
|
|
17
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
18
|
+
/** Opens the approval page in the default browser; failure is fine (the link is printed). */
|
|
19
|
+
function openBrowser(url) {
|
|
20
|
+
try {
|
|
21
|
+
const child = process.platform === 'win32'
|
|
22
|
+
? spawn('cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true })
|
|
23
|
+
: spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [url], { detached: true, stdio: 'ignore' });
|
|
24
|
+
child.on('error', (error) => debug('browser not opened', error.message));
|
|
25
|
+
child.unref();
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
debug('browser not opened', error.message);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* `npx tokocode login`: shows a code, opens the browser, and waits for one click on "Izinkan".
|
|
33
|
+
*/
|
|
34
|
+
export async function runLogin(options) {
|
|
35
|
+
const api = client(options.api);
|
|
36
|
+
const start = await withSpinner('Menyiapkan login…', () => api.deviceStart({ ...ApiClient.clientInfo(), host: os.hostname().slice(0, 60) }), { silentSuccess: true });
|
|
37
|
+
out.line();
|
|
38
|
+
out.line(box([chalk.bold.white('MASUK KE TOKOCODE'), '', `Kode: ${chalk.bold.cyan(start.user_code)}`], chalk.cyan));
|
|
39
|
+
out.line();
|
|
40
|
+
out.line(`Buka tautan ini lalu klik ${chalk.bold('Izinkan')}:`);
|
|
41
|
+
out.line(chalk.cyan.underline(start.verification_url_complete));
|
|
42
|
+
out.line();
|
|
43
|
+
if (options.browser !== false && process.stdout.isTTY) {
|
|
44
|
+
openBrowser(start.verification_url_complete);
|
|
45
|
+
out.muted('Browser dibuka otomatis. Pastikan kodenya sama dengan di atas.');
|
|
46
|
+
}
|
|
47
|
+
const spinner = ora({ text: 'Menunggu persetujuan di browser…', stream: process.stdout, discardStdin: false }).start();
|
|
48
|
+
const deadline = Date.now() + start.expires_in * 1000;
|
|
49
|
+
let interval = Math.max(2, start.interval) * 1000;
|
|
50
|
+
for (;;) {
|
|
51
|
+
await sleep(interval);
|
|
52
|
+
try {
|
|
53
|
+
const granted = await api.deviceToken(start.device_code);
|
|
54
|
+
await saveLogin(api.baseUrl, { token: granted.access_token, user: granted.user, expires_at: granted.expires_at, saved_at: new Date().toISOString() });
|
|
55
|
+
spinner.succeed(`Terhubung sebagai ${chalk.bold(granted.user.name)} ${chalk.dim(`(${granted.user.email})`)}`);
|
|
56
|
+
out.line();
|
|
57
|
+
out.line(`Lihat produk Anda: ${chalk.cyan(`npx ${PACKAGE_NAME} library`)}`);
|
|
58
|
+
out.line(`Pasang produk: ${chalk.cyan(`npx ${PACKAGE_NAME} add <nama>`)}`);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
const cliError = toCliError(error);
|
|
63
|
+
if (cliError.code === 'authorization_pending' && Date.now() < deadline) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (cliError.code === 'rate_limited') {
|
|
67
|
+
interval = Math.min(interval * 2, 15000);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
spinner.fail(cliError.code === 'authorization_pending' ? 'Waktu persetujuan habis' : cliError.message);
|
|
71
|
+
if (cliError.code === 'authorization_pending') {
|
|
72
|
+
throw new CliError('login_expired', 'Kode masuk sudah kedaluwarsa (10 menit).', `Jalankan ulang: npx ${PACKAGE_NAME} login`);
|
|
73
|
+
}
|
|
74
|
+
throw cliError;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export async function runLogout(options) {
|
|
79
|
+
const api = client(options.api);
|
|
80
|
+
const login = await loadLogin(api.baseUrl);
|
|
81
|
+
if (!login) {
|
|
82
|
+
out.info('CLI ini belum terhubung ke akun TokoCode.');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
await api.logout(login.token);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
debug('logout not confirmed by the server', error.message);
|
|
90
|
+
}
|
|
91
|
+
await forgetLogin(api.baseUrl);
|
|
92
|
+
out.ok(`Keluar dari akun ${chalk.bold(login.user.name)}. Kunci akses di perangkat ini sudah dihapus.`);
|
|
93
|
+
}
|
|
94
|
+
async function requireLogin(api) {
|
|
95
|
+
const login = await loadLogin(api.baseUrl);
|
|
96
|
+
if (!login) {
|
|
97
|
+
throw new CliError('auth_required', 'Anda belum masuk ke TokoCode CLI.', `Jalankan: npx ${PACKAGE_NAME} login`);
|
|
98
|
+
}
|
|
99
|
+
return login.token;
|
|
100
|
+
}
|
|
101
|
+
async function forgetIfRejected(api, error) {
|
|
102
|
+
const cliError = toCliError(error);
|
|
103
|
+
if (cliError.code === 'auth_invalid') {
|
|
104
|
+
await forgetLogin(api.baseUrl);
|
|
105
|
+
}
|
|
106
|
+
throw cliError;
|
|
107
|
+
}
|
|
108
|
+
export async function runWhoami(options) {
|
|
109
|
+
const api = client(options.api);
|
|
110
|
+
const token = await requireLogin(api);
|
|
111
|
+
const me = await withSpinner('Memeriksa akun…', () => api.me(token), { silentSuccess: true }).catch((error) => forgetIfRejected(api, error));
|
|
112
|
+
if (options.json) {
|
|
113
|
+
out.line(JSON.stringify(me, null, 2));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
details([
|
|
117
|
+
['Akun', `${chalk.bold(me.user.name)} ${chalk.dim(me.user.email)}`],
|
|
118
|
+
['Produk', `${me.library} siap dipasang`],
|
|
119
|
+
['Login berlaku', new Date(me.token.expires_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })],
|
|
120
|
+
['Toko', api.baseUrl],
|
|
121
|
+
]);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* `npx tokocode library`: paid and free products of the signed-in customer.
|
|
125
|
+
*/
|
|
126
|
+
export async function runLibrary(options) {
|
|
127
|
+
const api = client(options.api);
|
|
128
|
+
const token = await requireLogin(api);
|
|
129
|
+
const { items } = await withSpinner('Mengambil produk di akun Anda…', () => api.library(token), { silentSuccess: true }).catch((error) => forgetIfRejected(api, error));
|
|
130
|
+
if (options.json) {
|
|
131
|
+
out.line(JSON.stringify(items, null, 2));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (items.length === 0) {
|
|
135
|
+
out.info('Belum ada produk di akun Anda.');
|
|
136
|
+
out.muted(` Lihat yang gratis: npx ${PACKAGE_NAME} search --gratis`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
out.line();
|
|
140
|
+
printTable(items.map((item) => ({ ...item, extra: item.source === 'paid' && item.invoice_no ? item.invoice_no : undefined })));
|
|
141
|
+
out.line();
|
|
142
|
+
out.muted(`${items.length} produk. Pasang: npx ${PACKAGE_NAME} add <nama>`);
|
|
143
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { Transform } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import chalk from 'chalk';
|
|
8
|
+
import ora from 'ora';
|
|
9
|
+
import { CLI_VERSION, DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
|
|
10
|
+
import { ApiClient } from '../services/api.service.js';
|
|
11
|
+
import { loadLogin } from '../services/auth.service.js';
|
|
12
|
+
import { sameChecksum, sha256File } from '../services/checksum.service.js';
|
|
13
|
+
import { extractArchive } from '../services/extraction.service.js';
|
|
14
|
+
import { stateDir } from '../services/state.service.js';
|
|
15
|
+
import { removeOnInterrupt } from '../utils/cleanup.js';
|
|
16
|
+
import { CliError, toCliError } from '../utils/errors.js';
|
|
17
|
+
import { directoryState, fileSize, humanBytes, moveDirectory, removeQuietly } from '../utils/filesystem.js';
|
|
18
|
+
import { formatDuration, ProgressBar } from '../utils/progress.js';
|
|
19
|
+
import { box, details, out } from '../utils/terminal.js';
|
|
20
|
+
import { compareVersions, normalizeApiUrl } from '../utils/validation.js';
|
|
21
|
+
import { chooseTarget, runLibraryInstall, withSpinner } from './install.js';
|
|
22
|
+
const KIND_LABEL = { komponen: 'Komponen UI', template: 'Template / source code', jasa: 'Layanan' };
|
|
23
|
+
/**
|
|
24
|
+
* `npx tokocode add <name...>`: free products install right away (no account); paid products install from the
|
|
25
|
+
* signed-in account (`npx tokocode login`), otherwise the CLI explains how to get them.
|
|
26
|
+
*/
|
|
27
|
+
export async function runAdd(names, options) {
|
|
28
|
+
const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
|
|
29
|
+
await assertAvailable(api);
|
|
30
|
+
const many = names.length > 1;
|
|
31
|
+
for (const [index, raw] of names.entries()) {
|
|
32
|
+
const name = raw.trim().toLowerCase();
|
|
33
|
+
if (many) {
|
|
34
|
+
out.line();
|
|
35
|
+
out.line(chalk.bold(`[${index + 1}/${names.length}] ${name}`));
|
|
36
|
+
}
|
|
37
|
+
const { product } = await withSpinner(`Mencari ${chalk.bold(name)} di katalog…`, () => api.product(name), { silentSuccess: true });
|
|
38
|
+
const perItem = many ? { ...options, name: undefined } : options;
|
|
39
|
+
if (product.install === 'service') {
|
|
40
|
+
throw new CliError('product_unavailable', `${product.title} adalah layanan yang dikerjakan tim, bukan paket untuk dipasang.`, `Pesan di website: ${product.url}`);
|
|
41
|
+
}
|
|
42
|
+
if (product.free) {
|
|
43
|
+
await installFree(api, product, perItem);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const login = await loadLogin(api.baseUrl);
|
|
47
|
+
if (!login) {
|
|
48
|
+
throw new CliError('auth_required', `${product.title} berbayar (${product.price_label}).`, [
|
|
49
|
+
`1. Beli di website: ${product.url}`,
|
|
50
|
+
`2. Hubungkan CLI sekali saja: npx ${PACKAGE_NAME} login`,
|
|
51
|
+
`3. Jalankan lagi: npx ${PACKAGE_NAME} add ${product.name}`,
|
|
52
|
+
].join('\n'));
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
await runLibraryInstall(api, product.name, login.token, { ...perItem, dir: perItem.dir ?? process.cwd(), name: perItem.name ?? product.name });
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
const cliError = toCliError(error);
|
|
59
|
+
if (cliError.code === 'not_owned') {
|
|
60
|
+
throw new CliError('not_owned', `${product.title} belum ada di akun ${login.user.name}.`, `Beli di ${product.url} (${product.price_label}), lalu jalankan perintah ini lagi.`);
|
|
61
|
+
}
|
|
62
|
+
if (cliError.code === 'auth_invalid') {
|
|
63
|
+
throw new CliError('auth_invalid', cliError.message, `Masuk lagi: npx ${PACKAGE_NAME} login`);
|
|
64
|
+
}
|
|
65
|
+
throw cliError;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function assertAvailable(api) {
|
|
70
|
+
const meta = await withSpinner('Menghubungi server TokoCode…', () => api.meta(), { silentSuccess: true });
|
|
71
|
+
if (!meta.enabled) {
|
|
72
|
+
throw new CliError('cli_disabled', 'TokoCode CLI sedang dinonaktifkan.', meta.maintenance_message || 'Silakan coba lagi nanti.');
|
|
73
|
+
}
|
|
74
|
+
if (compareVersions(CLI_VERSION, meta.min_cli_version) < 0) {
|
|
75
|
+
throw new CliError('cli_outdated', `Versi TokoCode CLI Anda (${CLI_VERSION}) sudah tidak didukung.`, `Jalankan versi terbaru: npx ${PACKAGE_NAME}@latest`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Free product: download (resumable) → SHA-256 check → extraction into a new folder. Nothing is executed.
|
|
80
|
+
*/
|
|
81
|
+
async function installFree(api, product, options) {
|
|
82
|
+
const pkg = product.package;
|
|
83
|
+
if (!pkg) {
|
|
84
|
+
throw new CliError('package_unavailable', `Paket ${product.title} sedang disiapkan.`, `Coba lagi nanti, atau unduh dari ${product.url}`);
|
|
85
|
+
}
|
|
86
|
+
out.ok(`${chalk.bold(product.title)} ${chalk.green('· Gratis')}`);
|
|
87
|
+
details([
|
|
88
|
+
['Jenis', [KIND_LABEL[product.kind] ?? product.kind, product.group].filter(Boolean).join(' · ')],
|
|
89
|
+
['Versi', pkg.version || product.version],
|
|
90
|
+
['Ukuran', humanBytes(pkg.size)],
|
|
91
|
+
]);
|
|
92
|
+
out.line();
|
|
93
|
+
// One command, no questions: ./<name> in the current folder (asked again only when that folder has files).
|
|
94
|
+
const target = await chooseTarget({ suggested_folder: product.name, package: pkg }, { ...options, dir: options.dir ?? process.cwd(), name: options.name ?? product.name });
|
|
95
|
+
out.line();
|
|
96
|
+
await fs.mkdir(stateDir(), { recursive: true });
|
|
97
|
+
const part = path.join(stateDir(), `free-${product.name}-${pkg.sha256.slice(0, 16)}.zip.part`);
|
|
98
|
+
const started = Date.now();
|
|
99
|
+
await downloadFree(api, product.name, pkg, part);
|
|
100
|
+
const spinner = ora({ text: 'Memverifikasi integritas file (SHA-256)', stream: process.stdout, discardStdin: false }).start();
|
|
101
|
+
const checksum = await sha256File(part);
|
|
102
|
+
if (!sameChecksum(checksum, pkg.sha256)) {
|
|
103
|
+
spinner.fail('Checksum file tidak cocok');
|
|
104
|
+
await removeQuietly(part);
|
|
105
|
+
throw new CliError('checksum_mismatch', 'Checksum file tidak cocok dengan server.', `File rusak saat diunduh dan sudah dihapus. Jalankan ulang: npx ${PACKAGE_NAME} add ${product.name}`);
|
|
106
|
+
}
|
|
107
|
+
spinner.succeed(`Integritas file cocok ${chalk.dim('sha256 ' + checksum.slice(0, 12) + '…')}`);
|
|
108
|
+
const files = await extractInto(part, target);
|
|
109
|
+
await removeQuietly(part);
|
|
110
|
+
out.line();
|
|
111
|
+
out.line(box([chalk.bold.green('TERPASANG!'), chalk.dim(`${product.title} · Gratis`)], chalk.green));
|
|
112
|
+
out.line();
|
|
113
|
+
details([
|
|
114
|
+
['Lokasi', chalk.cyan(target)],
|
|
115
|
+
['Isi', `${files} file · ${humanBytes(pkg.size)} · ${formatDuration((Date.now() - started) / 1000)}`],
|
|
116
|
+
]);
|
|
117
|
+
out.line();
|
|
118
|
+
out.line(chalk.bold('Langkah selanjutnya:'));
|
|
119
|
+
const relative = path.relative(process.cwd(), target) || '.';
|
|
120
|
+
out.line(`1. Buka ${chalk.cyan(path.join(relative, 'index.html'))} di browser untuk melihat contohnya.`);
|
|
121
|
+
out.line(`2. Baca ${chalk.cyan(path.join(relative, 'README.md'))}: cara menempel komponen ke halaman Anda.`);
|
|
122
|
+
if (await exists(path.join(target, 'i18n.js'))) {
|
|
123
|
+
out.line(`3. Bahasa Indonesia: tambahkan ${chalk.cyan('<html lang="id">')} atau ${chalk.cyan('#lang=id')}; lihat bagian "Bahasa" di README.`);
|
|
124
|
+
}
|
|
125
|
+
out.line();
|
|
126
|
+
out.muted('Tidak ada script dari paket yang dijalankan otomatis.');
|
|
127
|
+
}
|
|
128
|
+
async function downloadFree(api, name, pkg, part) {
|
|
129
|
+
let start = await fileSize(part).catch(() => 0);
|
|
130
|
+
if (start > pkg.size) {
|
|
131
|
+
await removeQuietly(part);
|
|
132
|
+
start = 0;
|
|
133
|
+
}
|
|
134
|
+
const bar = new ProgressBar('Mengunduh', pkg.size);
|
|
135
|
+
const forget = removeOnInterrupt(part);
|
|
136
|
+
try {
|
|
137
|
+
if (start < pkg.size) {
|
|
138
|
+
const response = await api.openFreePackage(name, start, pkg.sha256);
|
|
139
|
+
if (response.statusCode === 200) {
|
|
140
|
+
start = 0; // the server sent the whole file (new build or no range support)
|
|
141
|
+
}
|
|
142
|
+
if (response.statusCode !== 416) {
|
|
143
|
+
let received = start;
|
|
144
|
+
const counter = new Transform({
|
|
145
|
+
transform(chunk, _encoding, callback) {
|
|
146
|
+
received += chunk.length;
|
|
147
|
+
bar.update(received);
|
|
148
|
+
callback(null, chunk);
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
await pipeline(response, counter, createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }));
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
response.resume();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
bar.done(pkg.size);
|
|
158
|
+
forget();
|
|
159
|
+
out.ok(`Diunduh ${chalk.dim(`${humanBytes(pkg.size)} · ${formatDuration(bar.elapsedSeconds())}`)}`);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
bar.clear();
|
|
163
|
+
forget();
|
|
164
|
+
throw toCliError(error);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function extractInto(zip, target) {
|
|
168
|
+
const parent = path.dirname(target);
|
|
169
|
+
await fs.mkdir(parent, { recursive: true });
|
|
170
|
+
const status = await directoryState(target);
|
|
171
|
+
if (status === 'not-empty' || status === 'file') {
|
|
172
|
+
throw new CliError('target_not_empty', `Folder ${target} sudah berisi file.`, 'Pilih nama folder lain dengan --name. File Anda tidak diubah.');
|
|
173
|
+
}
|
|
174
|
+
const staging = path.join(parent, `.tokocode-${path.basename(target)}-${randomBytes(4).toString('hex')}`);
|
|
175
|
+
const forget = removeOnInterrupt(staging);
|
|
176
|
+
const spinner = ora({ text: 'Mengekstrak file', stream: process.stdout, discardStdin: false }).start();
|
|
177
|
+
try {
|
|
178
|
+
const result = await extractArchive(zip, staging, {
|
|
179
|
+
onProgress: (written, total) => {
|
|
180
|
+
spinner.text = `Mengekstrak file ${chalk.dim(`${total > 0 ? Math.floor((written / total) * 100) : 100}%`)}`;
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
if (status === 'empty') {
|
|
184
|
+
await fs.rm(target, { recursive: true, force: true });
|
|
185
|
+
}
|
|
186
|
+
await moveDirectory(staging, target);
|
|
187
|
+
forget();
|
|
188
|
+
spinner.succeed(`Diekstrak ${chalk.dim(`${result.files} file`)}`);
|
|
189
|
+
return result.files;
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
spinner.fail('Ekstraksi gagal');
|
|
193
|
+
await removeQuietly(staging);
|
|
194
|
+
forget();
|
|
195
|
+
throw toCliError(error);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async function exists(file) {
|
|
199
|
+
return fs.stat(file).then(() => true, () => false);
|
|
200
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
|
|
3
|
+
import { ApiClient } from '../services/api.service.js';
|
|
4
|
+
import { CliError } from '../utils/errors.js';
|
|
5
|
+
import { humanBytes } from '../utils/filesystem.js';
|
|
6
|
+
import { details, out } from '../utils/terminal.js';
|
|
7
|
+
import { normalizeApiUrl } from '../utils/validation.js';
|
|
8
|
+
import { withSpinner } from './install.js';
|
|
9
|
+
const KINDS = ['komponen', 'template', 'jasa'];
|
|
10
|
+
const KIND_LABEL = { komponen: 'Komponen', template: 'Template', jasa: 'Layanan' };
|
|
11
|
+
function client(api) {
|
|
12
|
+
return new ApiClient(normalizeApiUrl(api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
|
|
13
|
+
}
|
|
14
|
+
/** Pads with the visible width (colours do not count). */
|
|
15
|
+
function cell(text, width) {
|
|
16
|
+
const plain = text.length > width ? text.slice(0, Math.max(1, width - 1)) + '…' : text;
|
|
17
|
+
return plain + ' '.repeat(Math.max(0, width - plain.length));
|
|
18
|
+
}
|
|
19
|
+
export function printTable(items) {
|
|
20
|
+
const columns = process.stdout.columns && process.stdout.columns > 60 ? process.stdout.columns : 100;
|
|
21
|
+
const nameWidth = Math.min(30, Math.max(8, ...items.map((item) => item.name.length)));
|
|
22
|
+
const priceWidth = 11;
|
|
23
|
+
const kindWidth = 18;
|
|
24
|
+
const titleWidth = Math.max(16, columns - nameWidth - priceWidth - kindWidth - 8);
|
|
25
|
+
out.line(chalk.dim(`${cell('NAMA', nameWidth)} ${cell('PRODUK', titleWidth)} ${cell('JENIS', kindWidth)} HARGA`));
|
|
26
|
+
for (const item of items) {
|
|
27
|
+
const kind = [KIND_LABEL[item.kind] ?? item.kind, item.group].filter(Boolean).join(' · ');
|
|
28
|
+
const price = item.free ? chalk.green(cell('Gratis', priceWidth)) : cell(item.price_label, priceWidth);
|
|
29
|
+
out.line(`${chalk.cyan(cell(item.name, nameWidth))} ${cell(item.title, titleWidth)} ${chalk.dim(cell(kind, kindWidth))} ${price}${item.extra ? ' ' + chalk.dim(item.extra) : ''}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* `npx tokocode search [kata...] [--gratis] [--jenis komponen|template|jasa] [--json]`
|
|
34
|
+
*/
|
|
35
|
+
export async function runSearch(words, options) {
|
|
36
|
+
const kind = options.jenis?.toLowerCase();
|
|
37
|
+
if (kind && !KINDS.includes(kind)) {
|
|
38
|
+
throw new CliError('invalid_option', `Jenis "${options.jenis}" tidak dikenal.`, `Pilih salah satu: ${KINDS.join(', ')}`, 2);
|
|
39
|
+
}
|
|
40
|
+
const query = words.join(' ').trim();
|
|
41
|
+
const api = client(options.api);
|
|
42
|
+
const { items } = await withSpinner('Mencari di katalog TokoCode…', () => api.catalog({ q: query, kind, free: options.gratis }), { silentSuccess: true });
|
|
43
|
+
if (options.json) {
|
|
44
|
+
out.line(JSON.stringify(items, null, 2));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (items.length === 0) {
|
|
48
|
+
out.warn(`Tidak ada produk yang cocok${query ? ` dengan "${query}"` : ''}.`);
|
|
49
|
+
out.muted(` Coba kata lain, atau lihat semuanya: npx ${PACKAGE_NAME} search`);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
out.line();
|
|
53
|
+
printTable(items);
|
|
54
|
+
out.line();
|
|
55
|
+
const free = items.filter((item) => item.free).length;
|
|
56
|
+
out.muted(`${items.length} produk${free > 0 ? ` · ${free} gratis` : ''}. Detail: npx ${PACKAGE_NAME} info <nama> · Pasang: npx ${PACKAGE_NAME} add <nama>`);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `npx tokocode info <nama>`
|
|
60
|
+
*/
|
|
61
|
+
export async function runInfo(name, options) {
|
|
62
|
+
const api = client(options.api);
|
|
63
|
+
const { product } = await withSpinner(`Mengambil detail ${chalk.bold(name)}…`, () => api.product(name.trim().toLowerCase()), { silentSuccess: true });
|
|
64
|
+
if (options.json) {
|
|
65
|
+
out.line(JSON.stringify(product, null, 2));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
out.line();
|
|
69
|
+
out.line(chalk.bold(product.title) + (product.free ? chalk.green(' Gratis') : ''));
|
|
70
|
+
if (product.summary) {
|
|
71
|
+
out.line(chalk.dim(product.summary));
|
|
72
|
+
}
|
|
73
|
+
out.line();
|
|
74
|
+
const rows = [
|
|
75
|
+
['Nama CLI', chalk.cyan(product.name)],
|
|
76
|
+
['Jenis', [KIND_LABEL[product.kind] ?? product.kind, product.group ?? product.category].filter(Boolean).join(' · ')],
|
|
77
|
+
['Harga', product.free ? chalk.green('Gratis') : product.price_label],
|
|
78
|
+
];
|
|
79
|
+
if (product.version) {
|
|
80
|
+
rows.push(['Versi', product.version]);
|
|
81
|
+
}
|
|
82
|
+
if (product.package) {
|
|
83
|
+
rows.push(['Paket', `${product.package.file_name} · ${humanBytes(product.package.size)}`]);
|
|
84
|
+
}
|
|
85
|
+
rows.push(['Halaman', product.url]);
|
|
86
|
+
details(rows);
|
|
87
|
+
out.line();
|
|
88
|
+
if (product.install === 'free') {
|
|
89
|
+
out.line(`Pasang sekarang: ${chalk.cyan(`npx ${PACKAGE_NAME} add ${product.name}`)}`);
|
|
90
|
+
}
|
|
91
|
+
else if (product.install === 'purchase') {
|
|
92
|
+
out.line(`Setelah membeli: ${chalk.cyan(`npx ${PACKAGE_NAME} login`)} lalu ${chalk.cyan(`npx ${PACKAGE_NAME} add ${product.name}`)}`);
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
out.line(`Layanan dikerjakan tim TokoCode. Pesan di: ${product.url}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
package/dist/commands/help.js
CHANGED
|
@@ -4,8 +4,19 @@ import { PACKAGE_NAME } from '../config/constants.js';
|
|
|
4
4
|
export function helpFooter() {
|
|
5
5
|
const cmd = `npx ${PACKAGE_NAME}`;
|
|
6
6
|
return `
|
|
7
|
-
${chalk.bold('
|
|
8
|
-
${chalk.cyan(cmd)}
|
|
7
|
+
${chalk.bold('Katalog & produk gratis (tanpa akun):')}
|
|
8
|
+
${chalk.cyan(`${cmd} search tombol --gratis`)} Cari produk (--jenis komponen|template|jasa)
|
|
9
|
+
${chalk.cyan(`${cmd} info otp-verify`)} Detail, harga, dan cara memasang
|
|
10
|
+
${chalk.cyan(`${cmd} add liquid-toggle`)} Pasang produk gratis ke ./liquid-toggle
|
|
11
|
+
|
|
12
|
+
${chalk.bold('Produk yang sudah dibeli (sekali login):')}
|
|
13
|
+
${chalk.cyan(`${cmd} login`)} Setujui dengan satu klik di browser
|
|
14
|
+
${chalk.cyan(`${cmd} library`)} Produk di akun Anda
|
|
15
|
+
${chalk.cyan(`${cmd} add template-kopi-senja`)} Pasang tanpa menyalin token
|
|
16
|
+
${chalk.cyan(`${cmd} whoami`)} · ${chalk.cyan(`${cmd} logout`)}
|
|
17
|
+
|
|
18
|
+
${chalk.bold('Dengan installation token:')}
|
|
19
|
+
${chalk.cyan(cmd)} Menu: gratis, cari, akun, atau token
|
|
9
20
|
${chalk.cyan(`${cmd} --token TK-XXXX-… --name klinik`)} Langsung dengan token dan nama folder
|
|
10
21
|
${chalk.cyan(`${cmd} --dir D:\\Projects --name "toko saya"`)} Pilih lokasi lain (nama dengan spasi diberi tanda kutip)
|
|
11
22
|
${chalk.cyan(`${cmd} doctor`)} Periksa koneksi dan kesiapan komputer
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { DEFAULT_API_URL, PACKAGE_NAME } from '../config/constants.js';
|
|
3
|
+
import { ApiClient } from '../services/api.service.js';
|
|
4
|
+
import { loadLogin } from '../services/auth.service.js';
|
|
5
|
+
import { pendingStates } from '../services/state.service.js';
|
|
6
|
+
import { ask, banner, choose, isInteractive, out } from '../utils/terminal.js';
|
|
7
|
+
import { normalizeApiUrl } from '../utils/validation.js';
|
|
8
|
+
import { runLibrary, runLogin } from './account.js';
|
|
9
|
+
import { runAdd } from './add.js';
|
|
10
|
+
import { printTable, runSearch } from './catalog.js';
|
|
11
|
+
import { runInstall, withSpinner } from './install.js';
|
|
12
|
+
/**
|
|
13
|
+
* `npx tokocode` without a command. In a terminal it opens a menu (free components, search, the customer's
|
|
14
|
+
* products, installation token, help); with --token, TOKOCODE_TOKEN, an unfinished download, or without a
|
|
15
|
+
* terminal (scripts, CI) it keeps the original installation-token flow.
|
|
16
|
+
*/
|
|
17
|
+
export async function runHome(options) {
|
|
18
|
+
const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
|
|
19
|
+
const direct = Boolean(options.token || process.env.TOKOCODE_TOKEN || options.yes || !isInteractive());
|
|
20
|
+
if (direct || (options.resume !== false && (await pendingStates(api.baseUrl)).length > 0)) {
|
|
21
|
+
await runInstall(options);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
banner();
|
|
25
|
+
const login = await loadLogin(api.baseUrl);
|
|
26
|
+
out.line(chalk.bold('Selamat datang di TokoCode!') + (login ? chalk.dim(` Masuk sebagai ${login.user.name || login.user.email}`) : ''));
|
|
27
|
+
out.line(chalk.dim('Komponen UI, template, dan source code siap pakai, langsung ke folder project Anda.'));
|
|
28
|
+
out.line();
|
|
29
|
+
const choice = await choose('Apa yang ingin Anda lakukan?', [
|
|
30
|
+
{ value: 'free', label: `Pasang komponen gratis ${chalk.dim('(tanpa akun)')}` },
|
|
31
|
+
{ value: 'search', label: `Cari di katalog ${chalk.dim('(komponen, template, source code)')}` },
|
|
32
|
+
{ value: 'library', label: `Pasang produk yang sudah saya beli ${chalk.dim(login ? '(dari akun Anda)' : '(login sekali, tanpa token)')}` },
|
|
33
|
+
{ value: 'token', label: `Pasang dengan installation token ${chalk.dim('(TK-XXXX-…)')}` },
|
|
34
|
+
{ value: 'help', label: 'Lihat semua perintah' },
|
|
35
|
+
]);
|
|
36
|
+
out.line();
|
|
37
|
+
const add = { dir: options.dir, name: options.name, api: options.api, debug: options.debug };
|
|
38
|
+
switch (choice) {
|
|
39
|
+
case 'free': {
|
|
40
|
+
const { items } = await withSpinner('Mengambil komponen gratis…', () => api.catalog({ free: true }), { silentSuccess: true });
|
|
41
|
+
if (items.length === 0) {
|
|
42
|
+
out.info('Belum ada produk gratis saat ini.');
|
|
43
|
+
out.muted(` Lihat semua produk: npx ${PACKAGE_NAME} search`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
printTable(items);
|
|
47
|
+
out.line();
|
|
48
|
+
await offerAdd(add);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
case 'search': {
|
|
52
|
+
const words = await ask('Cari apa? (contoh: tombol, navbar, template klinik; Enter = semua)');
|
|
53
|
+
await runSearch(words ? [words] : [], { api: options.api });
|
|
54
|
+
out.line();
|
|
55
|
+
await offerAdd(add);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
case 'library':
|
|
59
|
+
if (!login) {
|
|
60
|
+
await runLogin({ api: options.api });
|
|
61
|
+
out.line();
|
|
62
|
+
}
|
|
63
|
+
await runLibrary({ api: options.api });
|
|
64
|
+
out.line();
|
|
65
|
+
await offerAdd(add);
|
|
66
|
+
return;
|
|
67
|
+
case 'token':
|
|
68
|
+
await runInstall(options, { banner: false });
|
|
69
|
+
return;
|
|
70
|
+
default:
|
|
71
|
+
showCommands();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Asks which product to install (Enter skips) and installs it with `add`. */
|
|
75
|
+
async function offerAdd(options) {
|
|
76
|
+
const name = (await ask('Nama produk yang ingin dipasang (Enter = selesai)')).trim().toLowerCase();
|
|
77
|
+
if (name === '') {
|
|
78
|
+
out.muted(`Kapan saja: npx ${PACKAGE_NAME} add <nama>`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
await runAdd([name], options);
|
|
82
|
+
}
|
|
83
|
+
function showCommands() {
|
|
84
|
+
const cmd = `npx ${PACKAGE_NAME}`;
|
|
85
|
+
const rows = [
|
|
86
|
+
[`${cmd} search tombol --gratis`, 'Cari produk (--jenis komponen|template|jasa)'],
|
|
87
|
+
[`${cmd} info otp-verify`, 'Detail, harga, dan cara memasang'],
|
|
88
|
+
[`${cmd} add liquid-toggle`, 'Pasang produk (gratis langsung, berbayar dari akun)'],
|
|
89
|
+
[`${cmd} login`, 'Hubungkan akun dengan satu klik di browser'],
|
|
90
|
+
[`${cmd} library`, 'Produk di akun Anda'],
|
|
91
|
+
[`${cmd} --token TK-XXXX-…`, 'Pasang dengan installation token'],
|
|
92
|
+
[`${cmd} doctor`, 'Periksa koneksi dan kesiapan komputer'],
|
|
93
|
+
[`${cmd} --help`, 'Semua opsi'],
|
|
94
|
+
];
|
|
95
|
+
const width = Math.max(...rows.map(([command]) => command.length));
|
|
96
|
+
out.line(chalk.bold('Perintah TokoCode CLI'));
|
|
97
|
+
out.line();
|
|
98
|
+
rows.forEach(([command, label]) => out.line(` ${chalk.cyan(command.padEnd(width))} ${chalk.dim(label)}`));
|
|
99
|
+
}
|
package/dist/commands/install.js
CHANGED
|
@@ -23,11 +23,13 @@ const STEPS = 5;
|
|
|
23
23
|
* `tokocode` / `tokocode install`: token → verify → choose folder → redeem → download (resumable)
|
|
24
24
|
* → SHA-256 check → safe extraction → report. Nothing from the package is ever executed.
|
|
25
25
|
*/
|
|
26
|
-
export async function runInstall(options) {
|
|
26
|
+
export async function runInstall(options, view = {}) {
|
|
27
27
|
const api = new ApiClient(normalizeApiUrl(options.api ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
|
|
28
|
-
banner
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
if (view.banner !== false) {
|
|
29
|
+
banner();
|
|
30
|
+
out.line(chalk.bold('Selamat datang di TokoCode!'));
|
|
31
|
+
out.line();
|
|
32
|
+
}
|
|
31
33
|
warnOldNode();
|
|
32
34
|
await withSpinner('Menghubungi server TokoCode…', async () => {
|
|
33
35
|
const meta = await api.meta();
|
|
@@ -78,6 +80,34 @@ export async function runInstall(options) {
|
|
|
78
80
|
debug('state saved', { dir: stateDir() });
|
|
79
81
|
await performInstall(api, state, options);
|
|
80
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
|
+
}
|
|
81
111
|
/**
|
|
82
112
|
* Offers to continue an unfinished installation (download interrupted, terminal closed…).
|
|
83
113
|
*
|
|
@@ -132,7 +162,7 @@ async function performInstall(api, state, options) {
|
|
|
132
162
|
let checksum = '';
|
|
133
163
|
for (let attempt = 1;; attempt++) {
|
|
134
164
|
await downloadStep(api, state);
|
|
135
|
-
const spinner = ora({ text: step(4, STEPS, 'Memverifikasi integritas file (SHA-256)'), stream: process.stdout }).start();
|
|
165
|
+
const spinner = ora({ text: step(4, STEPS, 'Memverifikasi integritas file (SHA-256)'), stream: process.stdout, discardStdin: false }).start();
|
|
136
166
|
checksum = await sha256File(state.partPath);
|
|
137
167
|
if (sameChecksum(checksum, state.package.sha256)) {
|
|
138
168
|
spinner.succeed(step(4, STEPS, `Memverifikasi integritas file ${chalk.dim('sha256 ' + checksum.slice(0, 12) + '…')}`));
|
|
@@ -203,7 +233,7 @@ async function extractStep(api, state) {
|
|
|
203
233
|
}
|
|
204
234
|
const staging = path.join(parent, `.tokocode-${path.basename(state.target)}-${randomBytes(4).toString('hex')}`);
|
|
205
235
|
const forget = removeOnInterrupt(staging);
|
|
206
|
-
const spinner = ora({ text: step(5, STEPS, 'Mengekstrak source code'), stream: process.stdout }).start();
|
|
236
|
+
const spinner = ora({ text: step(5, STEPS, 'Mengekstrak source code'), stream: process.stdout, discardStdin: false }).start();
|
|
207
237
|
try {
|
|
208
238
|
const result = await extractArchive(state.partPath, staging, {
|
|
209
239
|
onProgress: (written, total) => {
|
|
@@ -334,7 +364,7 @@ function describePurchase(info) {
|
|
|
334
364
|
* Asks for (or takes from options) the parent folder and project folder name, and makes sure
|
|
335
365
|
* the destination is new or empty and writable. An existing folder with files is never touched.
|
|
336
366
|
*/
|
|
337
|
-
async function chooseTarget(info, options) {
|
|
367
|
+
export async function chooseTarget(info, options) {
|
|
338
368
|
const interactive = isInteractive() && !options.yes;
|
|
339
369
|
const suggested = suggestFolderName(options.name ?? info.suggested_folder ?? 'tokocode-project');
|
|
340
370
|
let base = options.dir ? resolveUserPath(options.dir) : process.cwd();
|
|
@@ -428,8 +458,8 @@ function warnOldNode() {
|
|
|
428
458
|
out.warn(`Node.js ${process.versions.node} terdeteksi; disarankan versi ${MIN_NODE_VERSION} atau lebih baru (unduh di nodejs.org).`);
|
|
429
459
|
}
|
|
430
460
|
}
|
|
431
|
-
async function withSpinner(text, action, options = {}) {
|
|
432
|
-
const spinner = ora({ text, stream: process.stdout }).start();
|
|
461
|
+
export async function withSpinner(text, action, options = {}) {
|
|
462
|
+
const spinner = ora({ text, stream: process.stdout, discardStdin: false }).start();
|
|
433
463
|
try {
|
|
434
464
|
const result = await action();
|
|
435
465
|
if (options.silentSuccess) {
|
package/dist/index.js
CHANGED
|
@@ -6,8 +6,12 @@ import { Command, Option } from 'commander';
|
|
|
6
6
|
import { CLI_VERSION, EXIT, PACKAGE_NAME } from './config/constants.js';
|
|
7
7
|
import { helpFooter } from './commands/help.js';
|
|
8
8
|
import { runDoctor } from './commands/doctor.js';
|
|
9
|
+
import { runHome } from './commands/home.js';
|
|
9
10
|
import { runInstall } from './commands/install.js';
|
|
10
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';
|
|
11
15
|
import { runInterruptCleanup } from './utils/cleanup.js';
|
|
12
16
|
import { CliError, toCliError } from './utils/errors.js';
|
|
13
17
|
import { destroyAgents } from './utils/http.js';
|
|
@@ -50,7 +54,11 @@ async function main(argv) {
|
|
|
50
54
|
setDebug(Boolean(options.debug));
|
|
51
55
|
await runInstall(options);
|
|
52
56
|
};
|
|
53
|
-
|
|
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
|
+
});
|
|
54
62
|
installOptions(program.command('install').description('Pasang produk dengan installation token (perintah bawaan)')).action(install);
|
|
55
63
|
program
|
|
56
64
|
.command('doctor')
|
|
@@ -62,6 +70,58 @@ async function main(argv) {
|
|
|
62
70
|
exitCode = (await runDoctor(options.api)) ? EXIT.ok : EXIT.error;
|
|
63
71
|
});
|
|
64
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));
|
|
65
125
|
program.addHelpText('after', helpFooter());
|
|
66
126
|
try {
|
|
67
127
|
await program.parseAsync(argv);
|
|
@@ -44,6 +44,62 @@ export class ApiClient {
|
|
|
44
44
|
debug('failure report not delivered', error.message);
|
|
45
45
|
}
|
|
46
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
|
+
}
|
|
47
103
|
downloadUrl(sessionId) {
|
|
48
104
|
return `${this.baseUrl}${API_PREFIX}/downloads/${sessionId}`;
|
|
49
105
|
}
|
|
@@ -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
|
+
}
|
package/dist/utils/logger.js
CHANGED
|
@@ -15,6 +15,9 @@ const PATTERNS = [
|
|
|
15
15
|
[/\b[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{24}\b/g, '****'],
|
|
16
16
|
// Download session secrets and bearer headers.
|
|
17
17
|
[/tcs_[A-Za-z0-9_-]{10,}/g, 'tcs_****'],
|
|
18
|
+
// `npx tokocode login`: access tokens and device codes.
|
|
19
|
+
[/tca_[A-Za-z0-9_-]{10,}/g, 'tca_****'],
|
|
20
|
+
[/tcd_[A-Za-z0-9_-]{10,}/g, 'tcd_****'],
|
|
18
21
|
[/(authorization|x-tokocode-session)(["']?\s*[:=]\s*["']?)(bearer\s+)?[^\s"',}]+/gi, '$1$2$3****'],
|
|
19
22
|
[/("(?:token|secret|request_id)"\s*:\s*")[^"]*(")/gi, '$1****$2'],
|
|
20
23
|
];
|