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 ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
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
+
11
+ ## 1.0.0 — 2026-11-07
12
+
13
+ Rilis pertama.
14
+
15
+ - `npx tokocode`: installation token → verifikasi → pilih folder → download → SHA-256 → ekstraksi.
16
+ - Token divalidasi lokal (format dan checksum) sebelum menghubungi server.
17
+ - Download streaming dengan progress bar, lanjut otomatis (HTTP Range) saat koneksi putus, menunggu saat server sibuk, memperbarui sesi yang habis, dan mengikuti paket yang diperbarui admin.
18
+ - Instalasi tertunda bisa dilanjutkan pada run berikutnya tanpa token baru.
19
+ - Redeem idempoten: respons yang hilang di jaringan tidak menghanguskan token.
20
+ - Ekstraksi aman: ZIP Slip, path absolut, symlink, dan ZIP bomb ditolak; folder pembungkus tunggal dirapikan; staging lalu pemindahan atomik.
21
+ - `tokocode doctor`, `tokocode version`, dan bantuan berbahasa Indonesia.
22
+ - Node.js 18.17+; Windows, macOS, dan Linux.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TokoCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # TokoCode CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pasang source code yang sudah Anda beli di [TokoCode](https://tokocode.co-id.id) langsung ke folder project, cukup dengan satu perintah:
4
+
5
+ ```bash
6
+ npx tokocode
7
+ ```
8
+
9
+ Tempel **installation token** dari dashboard, pilih folder, selesai. CLI mengunduh paket dari server TokoCode lewat HTTPS, memeriksa checksum SHA-256, lalu mengekstraknya. Anda tidak perlu mengunduh ZIP, membukanya, atau memindahkan file satu per satu.
10
+
11
+ ```text
12
+ ╔══════════════════════════════════════════╗
13
+ ║ TOKOCODE CLI ║
14
+ ║ SOURCE CODE INSTALLER ║
15
+ ╚══════════════════════════════════════════╝
16
+
17
+ ? Masukkan installation token Anda:
18
+ › TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX
19
+
20
+ ✓ Token berhasil diverifikasi!
21
+ ✓ Pembelian berhasil ditemukan!
22
+ ✓ Hak akses produk tersedia!
23
+
24
+ Produk : Sistem Informasi Klinik
25
+ Versi : 1.0.0
26
+ Status : Siap diinstal
27
+
28
+ ✓ [1/5] Memvalidasi akses
29
+ ✓ [2/5] Menyiapkan sesi download
30
+ ✓ [3/5] Mengunduh source code 12.4 MB · 9 dtk
31
+ ✓ [4/5] Memverifikasi integritas file sha256 3f9a1c…
32
+ ✓ [5/5] Mengekstrak source code 842 file
33
+
34
+ INSTALASI BERHASIL!
35
+ ```
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
+
58
+ ## 1. Persyaratan
59
+
60
+ | Kebutuhan | Keterangan |
61
+ |---|---|
62
+ | **Node.js 18.17 atau lebih baru** | Cek dengan `node -v`. Unduh gratis di [nodejs.org](https://nodejs.org) (pilih **LTS**). npm dan `npx` ikut terpasang. |
63
+ | Koneksi internet | Hanya ke server TokoCode (HTTPS). |
64
+ | Ruang disk | Kira-kira 2–3× ukuran paket (file sementara dan hasil ekstraksi). |
65
+ | Sistem operasi | Windows 10/11 (PowerShell, CMD, terminal VS Code), macOS, dan Linux (Bash, Zsh). |
66
+
67
+ Anda tidak perlu memasang apa pun secara global. `npx` mengunduh CLI versi terbaru secara otomatis.
68
+
69
+ ## 2. Mendapatkan installation token
70
+
71
+ 1. Masuk ke website TokoCode, lalu buka **Akun → Instalasi CLI**.
72
+ 2. Pada produk yang sudah lunas, tekan **Buat token**.
73
+ 3. Salin token yang tampil (bentuknya `TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX`).
74
+
75
+ Hal penting tentang token:
76
+ - **Hanya ditampilkan sekali.** Kalau lupa menyalin, buat token baru; token lama otomatis dicabut.
77
+ - **Sekali pakai.** Satu token untuk satu instalasi. Untuk memasang di komputer lain, buat token baru.
78
+ - **Punya masa berlaku** (bawaan 7 hari) yang tampil di dashboard.
79
+ - **Rahasia.** Jangan dibagikan. Token terikat ke akun dan pesanan Anda.
80
+
81
+ ## 3. Menjalankan instalasi
82
+
83
+ Buka terminal di folder kerja Anda. Di VS Code: **Terminal → New Terminal**. Lalu jalankan:
84
+
85
+ ```bash
86
+ npx tokocode
87
+ ```
88
+
89
+ Tempel token saat diminta. Klik kanan atau `Ctrl+V` di terminal VS Code dan PowerShell, `Ctrl+Shift+V` di sebagian terminal Linux.
90
+
91
+ ### Memilih folder instalasi
92
+
93
+ CLI bertanya dua hal:
94
+
95
+ 1. **Lokasi folder induk.** Tekan Enter untuk memakai direktori terminal saat ini, atau ketik lokasi lain, misalnya `D:\Projects` atau `~/projects`.
96
+ 2. **Nama folder project.** Bawaannya nama produk. Nama boleh mengandung spasi.
97
+
98
+ Hasilnya, misalnya, `D:\Projects\sistem-informasi-klinik\` berisi struktur asli source code: `app/`, `public/`, `README.md`, dan seterusnya.
99
+
100
+ CLI **tidak pernah menimpa file yang sudah ada**. Jika folder tujuan sudah berisi file, Anda bisa memilih nama lain, lokasi lain, atau membatalkan.
101
+
102
+ ### Tanpa pertanyaan (otomatisasi)
103
+
104
+ ```bash
105
+ npx tokocode --token TK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX --dir D:\Projects --name "klinik saya" --yes
106
+ ```
107
+
108
+ | Opsi | Fungsi |
109
+ |---|---|
110
+ | `-t, --token <token>` | Installation token. Bisa juga lewat variabel `TOKOCODE_TOKEN`. |
111
+ | `-d, --dir <path>` | Folder induk (bawaan: direktori saat ini). |
112
+ | `-n, --name <folder>` | Nama folder project. |
113
+ | `-y, --yes` | Tanpa konfirmasi. |
114
+ | `--no-resume` | Abaikan instalasi tertunda dan mulai dengan token baru. |
115
+ | `--api <url>` | Alamat toko jika berbeda (wajib HTTPS). |
116
+ | `--debug` | Log diagnosis; token dan secret selalu disamarkan. |
117
+
118
+ Perintah lain: `npx tokocode doctor` untuk memeriksa Node.js, koneksi ke server, dan izin folder; `npx tokocode version`; `npx tokocode --help`.
119
+
120
+ ## 4. Jika download gagal atau terputus
121
+
122
+ **Jalankan ulang perintah yang sama di komputer yang sama:**
123
+
124
+ ```bash
125
+ npx tokocode
126
+ ```
127
+
128
+ CLI mendeteksi instalasi yang belum selesai, menanyakan *"Lanjutkan instalasi tersebut?"*, lalu melanjutkan download dari bagian yang sudah tersimpan. Anda **tidak memerlukan token baru** selama masih dalam batas waktu pemulihan (bawaan 24 jam sejak token dipakai).
129
+
130
+ Selama download berjalan, CLI juga otomatis:
131
+ - mencoba lagi saat koneksi putus, dan melanjutkan dari byte terakhir (HTTP Range);
132
+ - menunggu lalu mencoba lagi saat server sedang sibuk;
133
+ - memperbarui sesi download yang habis waktunya;
134
+ - mengunduh ulang dari awal bila checksum tidak cocok (file rusak di jalan).
135
+
136
+ Masih gagal? Jalankan `npx tokocode doctor`, periksa koneksi internet, atau coba jaringan lain. Jika batas pemulihan habis, buat token baru di dashboard.
137
+
138
+ ## 5. Jika token ditolak
139
+
140
+ | Pesan | Penyebab dan solusi |
141
+ |---|---|
142
+ | *Token tidak valid atau tidak ditemukan.* | Ada salah ketik atau salin. Salin ulang dari dashboard (tanda `-` dan huruf besar/kecil tidak masalah). |
143
+ | *Installation token sudah kedaluwarsa.* | Buat token baru di **Akun → Instalasi CLI**. |
144
+ | *Installation token sudah pernah digunakan.* | Token hanya untuk satu instalasi. Buat token baru. |
145
+ | *Installation token sudah dicabut.* | Token diganti token baru atau dicabut. Pakai token terbaru. |
146
+ | *Pembayaran pesanan ini belum berhasil…* | Selesaikan pembayaran di website, lalu buat token. |
147
+ | *Terlalu banyak token salah dari jaringan ini.* | Tunggu 15 menit, lalu salin ulang token dengan teliti. |
148
+ | *Versi TokoCode CLI Anda sudah tidak didukung.* | Jalankan `npx tokocode@latest`. |
149
+
150
+ Setiap error menampilkan **Kode** (misalnya `token_expired`). Sebutkan kode ini saat menghubungi dukungan.
151
+
152
+ ## 6. Membuka project di VS Code
153
+
154
+ Di akhir instalasi, CLI menawarkan untuk membuka project di VS Code. Bisa juga dengan:
155
+
156
+ ```bash
157
+ code "D:\Projects\sistem-informasi-klinik"
158
+ ```
159
+
160
+ Atau lewat VS Code: **File → Open Folder…**, lalu pilih folder project.
161
+
162
+ Jika perintah `code` tidak dikenal: buka VS Code, tekan `Ctrl+Shift+P` (macOS: `Cmd+Shift+P`), lalu jalankan **Shell Command: Install 'code' command in PATH**.
163
+
164
+ ## 7. Setelah instalasi: dependency dan konfigurasi
165
+
166
+ CLI **tidak menjalankan script apa pun** dari paket. Langkah lanjutan Anda yang menentukan, dan CLI menampilkan saran sesuai isi project:
167
+
168
+ 1. Baca `README.md` project.
169
+ 2. Salin `.env.example` menjadi `.env`, lalu isi konfigurasi (database, URL, dan lainnya).
170
+ 3. Instal dependency sesuai teknologi, di dalam folder project:
171
+
172
+ | Project | Perintah |
173
+ |---|---|
174
+ | PHP (Laravel, CodeIgniter, dan lain-lain) | `composer install` |
175
+ | JavaScript/TypeScript | `npm install` |
176
+ | Python | `pip install -r requirements.txt` |
177
+
178
+ ## Keamanan
179
+
180
+ - Komunikasi hanya lewat HTTPS ke server toko. Redirect ke alamat lain tidak diikuti.
181
+ - Token tidak pernah disimpan di komputer Anda. Server hanya menyimpan hash-nya.
182
+ - Download memakai sesi sementara. Secret-nya dikirim di header, tidak di URL, dan disamarkan di log.
183
+ - Integritas paket diverifikasi dengan SHA-256 sebelum diekstrak.
184
+ - Ekstraksi aman: path berbahaya (ZIP Slip, path absolut, `..`), symbolic link, dan ZIP bomb ditolak. File diekstrak ke folder sementara lalu dipindahkan setelah semuanya berhasil.
185
+ - Data pemulihan download disimpan di folder sementara sistem dengan izin khusus pemilik, dan dihapus setelah instalasi selesai.
186
+
187
+ ## Variabel lingkungan
188
+
189
+ | Variabel | Fungsi |
190
+ |---|---|
191
+ | `TOKOCODE_TOKEN` | Token (alternatif `--token`). |
192
+ | `TOKOCODE_API_URL` | Alamat toko (alternatif `--api`). |
193
+ | `TOKOCODE_DEBUG=1` | Log diagnosis. |
194
+ | `TOKOCODE_STATE_DIR` | Lokasi data pemulihan (bawaan: folder sementara sistem). |
195
+ | `NO_COLOR=1` | Matikan warna. |
196
+
197
+ ## Lisensi
198
+
199
+ MIT © TokoCode
@@ -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
+ }