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,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
+ }
@@ -0,0 +1,96 @@
1
+ import os from 'node:os';
2
+ import chalk from 'chalk';
3
+ import { CLI_VERSION, DEFAULT_API_URL, MIN_NODE_VERSION, PACKAGE_NAME } from '../config/constants.js';
4
+ import { ApiClient } from '../services/api.service.js';
5
+ import { pendingStates, stateDir } from '../services/state.service.js';
6
+ import { toCliError } from '../utils/errors.js';
7
+ import { ensureWritableDirectory, freeSpace, humanBytes } from '../utils/filesystem.js';
8
+ import { out, symbols } from '../utils/terminal.js';
9
+ import { compareVersions, normalizeApiUrl } from '../utils/validation.js';
10
+ /**
11
+ * `tokocode doctor`: checks everything an installation needs and explains what to fix.
12
+ *
13
+ * @returns true when no blocking problem was found
14
+ */
15
+ export async function runDoctor(apiOption) {
16
+ let ok = true;
17
+ const pass = (label, detail = '') => out.line(`${chalk.green(symbols.ok)} ${label}${detail ? chalk.dim(' · ' + detail) : ''}`);
18
+ const fail = (label, hint) => {
19
+ ok = false;
20
+ out.line(`${chalk.red(symbols.fail)} ${label}`);
21
+ out.line(chalk.yellow(` ${hint}`));
22
+ };
23
+ const warn = (label, hint) => {
24
+ out.line(`${chalk.yellow(symbols.warn)} ${label}`);
25
+ out.line(chalk.dim(` ${hint}`));
26
+ };
27
+ out.line(chalk.bold(`TokoCode CLI ${CLI_VERSION} — pemeriksaan sistem`));
28
+ out.line();
29
+ if (compareVersions(process.versions.node, MIN_NODE_VERSION) >= 0) {
30
+ pass(`Node.js ${process.versions.node}`, `${process.platform}-${process.arch}`);
31
+ }
32
+ else {
33
+ fail(`Node.js ${process.versions.node} terlalu lama`, `Pasang Node.js ${MIN_NODE_VERSION} atau lebih baru dari nodejs.org (pilih LTS).`);
34
+ }
35
+ let api = null;
36
+ try {
37
+ api = new ApiClient(normalizeApiUrl(apiOption ?? process.env.TOKOCODE_API_URL ?? DEFAULT_API_URL));
38
+ }
39
+ catch (error) {
40
+ fail('Alamat server tidak valid', toCliError(error).message);
41
+ }
42
+ if (api) {
43
+ const started = Date.now();
44
+ try {
45
+ const meta = await api.meta();
46
+ pass(`Server ${meta.store_name} terhubung`, `${api.baseUrl} · ${Date.now() - started} ms`);
47
+ if (!meta.enabled) {
48
+ fail('Instalasi lewat CLI sedang dinonaktifkan oleh toko', meta.maintenance_message || 'Coba lagi nanti.');
49
+ }
50
+ if (compareVersions(CLI_VERSION, meta.min_cli_version) < 0) {
51
+ fail(`Versi CLI ${CLI_VERSION} sudah tidak didukung (minimum ${meta.min_cli_version})`, `Jalankan: npx ${PACKAGE_NAME}@latest`);
52
+ }
53
+ else {
54
+ pass('Versi CLI didukung server', `minimum ${meta.min_cli_version}`);
55
+ }
56
+ const skew = Math.abs(Date.parse(meta.server_time) - Date.now()) / 1000;
57
+ if (Number.isFinite(skew) && skew > 300) {
58
+ warn(`Jam komputer berbeda ${Math.round(skew / 60)} menit dengan server`, 'Atur tanggal & jam otomatis agar masa berlaku token terbaca benar.');
59
+ }
60
+ }
61
+ catch (error) {
62
+ const cliError = toCliError(error);
63
+ fail(`Tidak dapat terhubung ke ${api.baseUrl}`, `${cliError.message} ${cliError.hint}`.trim());
64
+ }
65
+ }
66
+ try {
67
+ await ensureWritableDirectory(stateDir());
68
+ const free = await freeSpace(stateDir());
69
+ pass('Folder sementara dapat ditulis', `${stateDir()}${free !== null ? ` · ${humanBytes(free)} kosong` : ''}`);
70
+ }
71
+ catch (error) {
72
+ fail('Folder sementara tidak dapat ditulis', toCliError(error).message);
73
+ }
74
+ try {
75
+ await ensureWritableDirectory(process.cwd());
76
+ const free = await freeSpace(process.cwd());
77
+ pass('Direktori saat ini dapat ditulis', `${process.cwd()}${free !== null ? ` · ${humanBytes(free)} kosong` : ''}`);
78
+ }
79
+ catch {
80
+ warn('Direktori saat ini tidak dapat ditulis', 'Pindah ke folder lain (misalnya Documents) sebelum menjalankan instalasi.');
81
+ }
82
+ const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy;
83
+ if (proxy && process.env.NODE_USE_ENV_PROXY !== '1') {
84
+ warn('Proxy terdeteksi di variabel lingkungan', 'Node.js tidak memakai proxy otomatis. Di Node 22.14+/24, set NODE_USE_ENV_PROXY=1.');
85
+ }
86
+ if (api) {
87
+ const pending = await pendingStates(api.baseUrl);
88
+ if (pending.length > 0) {
89
+ warn(`${pending.length} instalasi belum selesai`, `Jalankan npx ${PACKAGE_NAME} untuk melanjutkan.`);
90
+ }
91
+ }
92
+ out.line();
93
+ out.line(ok ? chalk.green('Semua siap. Jalankan: ') + chalk.cyan(`npx ${PACKAGE_NAME}`) : chalk.red('Perbaiki masalah di atas, lalu jalankan ulang pemeriksaan.'));
94
+ out.muted(`${os.type()} ${os.release()}`);
95
+ return ok;
96
+ }
@@ -0,0 +1,38 @@
1
+ import chalk from 'chalk';
2
+ import { PACKAGE_NAME } from '../config/constants.js';
3
+ /** Extra help text shown after Commander's option list. */
4
+ export function helpFooter() {
5
+ const cmd = `npx ${PACKAGE_NAME}`;
6
+ return `
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
20
+ ${chalk.cyan(`${cmd} --token TK-XXXX-… --name klinik`)} Langsung dengan token dan nama folder
21
+ ${chalk.cyan(`${cmd} --dir D:\\Projects --name "toko saya"`)} Pilih lokasi lain (nama dengan spasi diberi tanda kutip)
22
+ ${chalk.cyan(`${cmd} doctor`)} Periksa koneksi dan kesiapan komputer
23
+
24
+ ${chalk.bold('Installation token')}
25
+ Buat di website TokoCode: Akun > Instalasi CLI > Buat token.
26
+ Token sekali pakai, hanya ditampilkan sekali, dan bisa dibuat ulang bila hilang.
27
+
28
+ ${chalk.bold('Download terputus?')}
29
+ Jalankan ulang ${chalk.cyan(cmd)} di komputer yang sama: download dilanjutkan otomatis
30
+ tanpa token baru selama masih dalam batas waktu pemulihan.
31
+
32
+ ${chalk.bold('Variabel lingkungan')}
33
+ TOKOCODE_TOKEN Token (alternatif --token; tidak disimpan)
34
+ TOKOCODE_API_URL Alamat toko bila berbeda dari bawaan
35
+ TOKOCODE_DEBUG=1 Log diagnosis (token dan secret selalu disamarkan)
36
+ NO_COLOR=1 Matikan warna
37
+ `;
38
+ }
@@ -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
+ }