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,47 @@
1
+ /**
2
+ * Debug logging (--debug or TOKOCODE_DEBUG=1) to stderr. Every line passes through redact(),
3
+ * so installation tokens, session secrets and Authorization headers are never printed.
4
+ */
5
+ let enabled = process.env.TOKOCODE_DEBUG === '1';
6
+ export function setDebug(value) {
7
+ enabled = value || process.env.TOKOCODE_DEBUG === '1';
8
+ }
9
+ export function isDebug() {
10
+ return enabled;
11
+ }
12
+ const PATTERNS = [
13
+ // Installation tokens: TK-XXXX-… in any spacing/case.
14
+ [/\bTK[-\s]?(?:[0-9A-Za-z]{4}[-\s]?){5}[0-9A-Za-z]{4}\b/gi, 'TK-****'],
15
+ [/\b[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{24}\b/g, '****'],
16
+ // Download session secrets and bearer headers.
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_****'],
21
+ [/(authorization|x-tokocode-session)(["']?\s*[:=]\s*["']?)(bearer\s+)?[^\s"',}]+/gi, '$1$2$3****'],
22
+ [/("(?:token|secret|request_id)"\s*:\s*")[^"]*(")/gi, '$1****$2'],
23
+ ];
24
+ export function redact(text) {
25
+ let out = text;
26
+ for (const [pattern, replacement] of PATTERNS) {
27
+ out = out.replace(pattern, replacement);
28
+ }
29
+ return out;
30
+ }
31
+ export function debug(message, data) {
32
+ if (!enabled) {
33
+ return;
34
+ }
35
+ let line = `[debug ${new Date().toISOString()}] ${message}`;
36
+ if (data !== undefined) {
37
+ let serialized;
38
+ try {
39
+ serialized = typeof data === 'string' ? data : JSON.stringify(data);
40
+ }
41
+ catch {
42
+ serialized = String(data);
43
+ }
44
+ line += ' ' + serialized;
45
+ }
46
+ process.stderr.write(redact(line) + '\n');
47
+ }
@@ -0,0 +1,89 @@
1
+ import chalk from 'chalk';
2
+ import { humanBytes } from './filesystem.js';
3
+ /**
4
+ * Download/extract progress bar. On a TTY it redraws one line; when output is piped it prints
5
+ * a line every 10% so logs stay readable.
6
+ */
7
+ export class ProgressBar {
8
+ label;
9
+ total;
10
+ unit;
11
+ started = Date.now();
12
+ lastDraw = 0;
13
+ lastPercentLogged = -10;
14
+ samples = [];
15
+ tty = Boolean(process.stdout.isTTY);
16
+ constructor(label, total, unit = 'bytes') {
17
+ this.label = label;
18
+ this.total = total;
19
+ this.unit = unit;
20
+ }
21
+ update(current, force = false) {
22
+ const now = Date.now();
23
+ this.samples.push([now, current]);
24
+ while (this.samples.length > 2 && now - this.samples[0][0] > 5000) {
25
+ this.samples.shift();
26
+ }
27
+ if (!force && now - this.lastDraw < 100) {
28
+ return;
29
+ }
30
+ this.lastDraw = now;
31
+ const percent = this.total > 0 ? Math.min(100, Math.floor((current / this.total) * 100)) : 0;
32
+ if (!this.tty) {
33
+ if (percent >= this.lastPercentLogged + 10 || force) {
34
+ this.lastPercentLogged = percent - (percent % 10);
35
+ process.stdout.write(` ${this.label} ${percent}% (${this.amount(current)})\n`);
36
+ }
37
+ return;
38
+ }
39
+ const columns = process.stdout.columns ?? 80;
40
+ const width = Math.max(10, Math.min(30, columns - 60));
41
+ const filled = Math.round((percent / 100) * width);
42
+ const bar = chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(width - filled));
43
+ const rate = this.rate();
44
+ const extra = this.unit === 'bytes' && rate > 0
45
+ ? ` ${humanBytes(rate)}/s` + (this.total > current ? ` · sisa ${formatDuration((this.total - current) / rate)}` : '')
46
+ : '';
47
+ const line = ` ${bar} ${String(percent).padStart(3)}% ${chalk.dim(this.amount(current) + extra)}`;
48
+ process.stdout.write('\r\u001b[2K' + line);
49
+ }
50
+ done(current = this.total) {
51
+ this.update(current, true);
52
+ if (this.tty) {
53
+ process.stdout.write('\r\u001b[2K');
54
+ }
55
+ }
56
+ /** Clears the bar line so a message can be printed (e.g. a retry notice). */
57
+ clear() {
58
+ if (this.tty) {
59
+ process.stdout.write('\r\u001b[2K');
60
+ }
61
+ }
62
+ elapsedSeconds() {
63
+ return (Date.now() - this.started) / 1000;
64
+ }
65
+ amount(current) {
66
+ return this.unit === 'bytes' ? `${humanBytes(current)} / ${humanBytes(this.total)}` : `${current} / ${this.total} file`;
67
+ }
68
+ rate() {
69
+ if (this.samples.length < 2) {
70
+ return 0;
71
+ }
72
+ const [t0, b0] = this.samples[0];
73
+ const [t1, b1] = this.samples[this.samples.length - 1];
74
+ return t1 > t0 ? ((b1 - b0) / (t1 - t0)) * 1000 : 0;
75
+ }
76
+ }
77
+ export function formatDuration(seconds) {
78
+ if (!Number.isFinite(seconds) || seconds < 0) {
79
+ return '-';
80
+ }
81
+ if (seconds < 60) {
82
+ return `${Math.ceil(seconds)} dtk`;
83
+ }
84
+ const minutes = Math.floor(seconds / 60);
85
+ if (minutes < 60) {
86
+ return `${minutes} mnt ${Math.ceil(seconds % 60)} dtk`;
87
+ }
88
+ return `${Math.floor(minutes / 60)} jam ${minutes % 60} mnt`;
89
+ }
@@ -0,0 +1,149 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import chalk from 'chalk';
3
+ import { CancelledError, CliError } from './errors.js';
4
+ import { EXIT } from '../config/constants.js';
5
+ /**
6
+ * Terminal output and prompts. Plain ASCII fallbacks are used where the console cannot show
7
+ * box-drawing characters; colours follow chalk's detection (NO_COLOR / FORCE_COLOR respected).
8
+ */
9
+ const unicode = process.platform !== 'win32' || Boolean(process.env.WT_SESSION) || process.env.TERM_PROGRAM === 'vscode' || process.env.TERM === 'xterm-256color';
10
+ export const symbols = {
11
+ ok: unicode ? '✓' : '√',
12
+ fail: unicode ? '✖' : '×',
13
+ warn: unicode ? '⚠' : '!',
14
+ info: unicode ? 'ℹ' : 'i',
15
+ arrow: unicode ? '›' : '>',
16
+ bullet: unicode ? '•' : '-',
17
+ };
18
+ export const out = {
19
+ line(text = '') {
20
+ process.stdout.write(text + '\n');
21
+ },
22
+ ok(text) {
23
+ out.line(chalk.green(symbols.ok) + ' ' + text);
24
+ },
25
+ warn(text) {
26
+ out.line(chalk.yellow(symbols.warn) + ' ' + text);
27
+ },
28
+ info(text) {
29
+ out.line(chalk.cyan(symbols.info) + ' ' + text);
30
+ },
31
+ fail(text) {
32
+ process.stderr.write(chalk.red(symbols.fail) + ' ' + chalk.bold(text) + '\n');
33
+ },
34
+ muted(text) {
35
+ out.line(chalk.dim(text));
36
+ },
37
+ };
38
+ /** Draws a centred box around lines (the welcome and success banners). */
39
+ export function box(lines, color = chalk.cyan) {
40
+ const width = Math.max(42, ...lines.map((line) => visibleLength(line) + 6));
41
+ const [tl, tr, bl, br, h, v] = unicode ? ['╔', '╗', '╚', '╝', '═', '║'] : ['+', '+', '+', '+', '-', '|'];
42
+ const pad = (text) => {
43
+ const free = width - visibleLength(text);
44
+ const left = Math.floor(free / 2);
45
+ return color(v) + ' '.repeat(left) + text + ' '.repeat(free - left) + color(v);
46
+ };
47
+ const rows = [color(tl + h.repeat(width) + tr), pad(''), ...lines.map(pad), pad(''), color(bl + h.repeat(width) + br)];
48
+ return rows.join('\n');
49
+ }
50
+ export function banner() {
51
+ out.line();
52
+ out.line(box([chalk.bold.white('TOKOCODE CLI'), chalk.cyan('SOURCE CODE INSTALLER')]));
53
+ out.line();
54
+ }
55
+ /** Two-column details ("Produk : …"). */
56
+ export function details(rows) {
57
+ const width = Math.max(...rows.map(([label]) => label.length));
58
+ for (const [label, value] of rows) {
59
+ out.line(`${chalk.dim(label.padEnd(width))} : ${value}`);
60
+ }
61
+ }
62
+ export function step(index, total, label) {
63
+ return `${chalk.dim(`[${index}/${total}]`)} ${label}`;
64
+ }
65
+ function visibleLength(text) {
66
+ // eslint-disable-next-line no-control-regex
67
+ return text.replace(/\u001b\[[0-9;]*m/g, '').length;
68
+ }
69
+ export function isInteractive() {
70
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.env.CI !== 'true';
71
+ }
72
+ let rl = null;
73
+ function readline() {
74
+ if (!rl) {
75
+ rl = createInterface({ input: process.stdin, output: process.stdout, terminal: Boolean(process.stdin.isTTY) });
76
+ rl.on('SIGINT', () => {
77
+ closePrompts();
78
+ process.emit('SIGINT');
79
+ });
80
+ }
81
+ return rl;
82
+ }
83
+ export function closePrompts() {
84
+ rl?.close();
85
+ rl = null;
86
+ }
87
+ function requireInteractive(question) {
88
+ if (!isInteractive()) {
89
+ throw new CliError('needs_input', `Butuh jawaban interaktif: ${question}`, 'Jalankan di terminal biasa, atau berikan opsi --token, --dir, --name, dan --yes.', EXIT.usage);
90
+ }
91
+ }
92
+ /** Asks a question; an empty answer returns `fallback`. */
93
+ export async function ask(question, fallback = '') {
94
+ requireInteractive(question);
95
+ const suffix = fallback !== '' ? chalk.dim(` (${fallback})`) : '';
96
+ try {
97
+ const answer = await readline().question(`${chalk.cyan('?')} ${chalk.bold(question)}${suffix}\n${chalk.cyan(symbols.arrow)} `);
98
+ return answer.trim() === '' ? fallback : answer.trim();
99
+ }
100
+ catch (error) {
101
+ if (error.name === 'AbortError') {
102
+ throw new CancelledError();
103
+ }
104
+ throw error;
105
+ }
106
+ }
107
+ /** Yes/no question; Enter picks the default. */
108
+ export async function confirm(question, defaultYes = true) {
109
+ requireInteractive(question);
110
+ const hint = defaultYes ? 'Y/n' : 'y/N';
111
+ for (;;) {
112
+ const answer = (await readline().question(`${chalk.cyan('?')} ${chalk.bold(question)} ${chalk.dim(`(${hint})`)} `)).trim().toLowerCase();
113
+ if (answer === '') {
114
+ return defaultYes;
115
+ }
116
+ if (['y', 'ya', 'yes'].includes(answer)) {
117
+ return true;
118
+ }
119
+ if (['n', 'no', 't', 'tidak'].includes(answer)) {
120
+ return false;
121
+ }
122
+ out.muted('Jawab y (ya) atau n (tidak).');
123
+ }
124
+ }
125
+ /** Numbered menu; returns the chosen value. */
126
+ export async function choose(question, options) {
127
+ requireInteractive(question);
128
+ out.line(`${chalk.cyan('?')} ${chalk.bold(question)}`);
129
+ options.forEach((option, index) => out.line(` ${chalk.cyan(String(index + 1))}. ${option.label}`));
130
+ for (;;) {
131
+ const answer = (await readline().question(`${chalk.cyan(symbols.arrow)} Pilih 1-${options.length}: `)).trim();
132
+ const picked = options[Number.parseInt(answer, 10) - 1];
133
+ if (picked) {
134
+ return picked.value;
135
+ }
136
+ out.muted(`Ketik angka 1 sampai ${options.length}.`);
137
+ }
138
+ }
139
+ /** Prints a CliError the way customers see it: message, then what to do. */
140
+ export function printError(error) {
141
+ out.line();
142
+ out.fail(error.message);
143
+ if (error.hint) {
144
+ process.stderr.write(chalk.yellow(' ' + error.hint.split('\n').join('\n ')) + '\n');
145
+ }
146
+ if (error.code !== 'cancelled' && error.code !== 'unexpected') {
147
+ process.stderr.write(chalk.dim(` Kode: ${error.code}`) + '\n');
148
+ }
149
+ }
@@ -0,0 +1,121 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { CliError } from './errors.js';
3
+ import { EXIT } from '../config/constants.js';
4
+ /** Crockford Base32, the alphabet of installation tokens (no I, L, O, U). */
5
+ export const TOKEN_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
6
+ const BODY_LENGTH = 20;
7
+ const CHECK_LENGTH = 4;
8
+ /**
9
+ * Four-character checksum of a token body; identical to CliTokenCodec::checksum() on the server.
10
+ */
11
+ export function tokenChecksum(body) {
12
+ const hash = createHash('sha256').update('tokocode-cli-token|' + body).digest();
13
+ const bits = (hash[0] << 12) | (hash[1] << 4) | (hash[2] >> 4);
14
+ let out = '';
15
+ for (let shift = 15; shift >= 0; shift -= 5) {
16
+ out += TOKEN_ALPHABET[(bits >> shift) & 31];
17
+ }
18
+ return out;
19
+ }
20
+ /**
21
+ * Canonical 24-character token, or null when the input cannot be a valid token.
22
+ * Accepts lower case, spaces, dashes and the look-alikes O→0, I/L→1.
23
+ */
24
+ export function normalizeToken(input) {
25
+ let value = input.trim().toUpperCase().replace(/[\s\-_.]+/g, '');
26
+ const full = BODY_LENGTH + CHECK_LENGTH;
27
+ if (value.length === full + 2 && value.startsWith('TK')) {
28
+ value = value.slice(2);
29
+ }
30
+ value = value.replace(/O/g, '0').replace(/[IL]/g, '1');
31
+ if (value.length !== full || [...value].some((char) => !TOKEN_ALPHABET.includes(char))) {
32
+ return null;
33
+ }
34
+ const body = value.slice(0, BODY_LENGTH);
35
+ return tokenChecksum(body) === value.slice(BODY_LENGTH) ? value : null;
36
+ }
37
+ export function formatToken(normalized) {
38
+ return 'TK-' + (normalized.match(/.{1,4}/g) ?? []).join('-');
39
+ }
40
+ /** "TK-••••-…-AB12" for display; never prints the full token. */
41
+ export function maskToken(normalized) {
42
+ return 'TK-••••-••••-••••-••••-••••-' + normalized.slice(-4);
43
+ }
44
+ const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i;
45
+ // eslint-disable-next-line no-control-regex
46
+ const INVALID_CHARS = /[<>:"/\\|?*\u0000-\u001F]/;
47
+ /**
48
+ * Why a folder name cannot be used on Windows, macOS and Linux alike (null = valid).
49
+ * Spaces are allowed; names must be portable so the project can move between systems.
50
+ */
51
+ export function folderNameProblem(name) {
52
+ if (name.trim() === '') {
53
+ return 'Nama folder tidak boleh kosong.';
54
+ }
55
+ if (name.length > 100) {
56
+ return 'Nama folder maksimal 100 karakter.';
57
+ }
58
+ if (INVALID_CHARS.test(name)) {
59
+ return 'Nama folder tidak boleh berisi karakter < > : " / \\ | ? *';
60
+ }
61
+ if (name === '.' || name === '..') {
62
+ return 'Nama folder tidak valid.';
63
+ }
64
+ if (/[. ]$/.test(name)) {
65
+ return 'Nama folder tidak boleh diakhiri titik atau spasi.';
66
+ }
67
+ if (WINDOWS_RESERVED.test(name)) {
68
+ return `"${name}" adalah nama yang dicadangkan Windows.`;
69
+ }
70
+ return null;
71
+ }
72
+ /** Turns a product slug or name into a safe default folder name. */
73
+ export function suggestFolderName(input) {
74
+ const name = input
75
+ .normalize('NFKD')
76
+ .replace(/[̀-ͯ]/g, '')
77
+ .toLowerCase()
78
+ .replace(/[^a-z0-9._ -]+/g, '-')
79
+ .replace(/\s+/g, '-')
80
+ .replace(/-+/g, '-')
81
+ .replace(/^[-.]+|[-. ]+$/g, '')
82
+ .slice(0, 80);
83
+ return name !== '' && folderNameProblem(name) === null ? name : 'tokocode-project';
84
+ }
85
+ /** Compares dotted versions numerically: -1, 0 or 1. */
86
+ export function compareVersions(a, b) {
87
+ const pa = a.split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0);
88
+ const pb = b.split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0);
89
+ for (let i = 0; i < 3; i++) {
90
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
91
+ if (diff !== 0) {
92
+ return diff > 0 ? 1 : -1;
93
+ }
94
+ }
95
+ return 0;
96
+ }
97
+ /**
98
+ * Validates the API base URL: HTTPS, except plain HTTP for localhost during development.
99
+ */
100
+ export function normalizeApiUrl(input) {
101
+ let url;
102
+ try {
103
+ url = new URL(input.trim());
104
+ }
105
+ catch {
106
+ throw new CliError('invalid_api_url', `Alamat API tidak valid: ${input}`, 'Contoh yang benar: https://tokocode.co-id.id', EXIT.usage);
107
+ }
108
+ const local = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(url.hostname);
109
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
110
+ throw new CliError('insecure_api_url', 'Alamat API wajib memakai HTTPS.', 'Gunakan alamat yang diawali https://', EXIT.usage);
111
+ }
112
+ if (url.username || url.password) {
113
+ throw new CliError('invalid_api_url', 'Alamat API tidak boleh berisi nama pengguna atau password.', '', EXIT.usage);
114
+ }
115
+ url.hash = '';
116
+ url.search = '';
117
+ return url.toString().replace(/\/+$/, '');
118
+ }
119
+ export function isSha256(value) {
120
+ return /^[a-f0-9]{64}$/i.test(value);
121
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "tokocode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Pasang source code yang sudah Anda beli di TokoCode langsung dari terminal: npx tokocode",
5
+ "keywords": [
6
+ "tokocode",
7
+ "installer",
8
+ "cli",
9
+ "source-code",
10
+ "template"
11
+ ],
12
+ "homepage": "https://tokocode.co-id.id",
13
+ "license": "MIT",
14
+ "author": "TokoCode",
15
+ "type": "module",
16
+ "bin": {
17
+ "tokocode": "dist/index.js"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE",
23
+ "CHANGELOG.md"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18.17"
27
+ },
28
+ "scripts": {
29
+ "build": "node scripts/clean.mjs && tsc -p tsconfig.build.json",
30
+ "typecheck": "tsc -p tsconfig.json --noEmit",
31
+ "test": "npm run build && vitest run",
32
+ "test:watch": "vitest",
33
+ "start": "node dist/index.js",
34
+ "pack:check": "npm pack --dry-run",
35
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
36
+ },
37
+ "dependencies": {
38
+ "chalk": "5.6.2",
39
+ "commander": "12.1.0",
40
+ "ora": "8.2.0",
41
+ "yauzl": "3.4.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "18.19.130",
45
+ "@types/yauzl": "3.4.0",
46
+ "typescript": "5.9.3",
47
+ "vitest": "3.2.7"
48
+ }
49
+ }