catylst 1.0.5 → 1.0.8

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/postinstall.js +151 -136
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "catylst",
3
- "version": "1.0.5",
3
+ "version": "1.0.8",
4
4
  "description": "Generate customized Kotlin Multiplatform projects with an interactive wizard",
5
5
  "keywords": [
6
6
  "kotlin",
package/postinstall.js CHANGED
@@ -4,18 +4,20 @@
4
4
  // 2. Clones (or updates) the Catylst template to ~/.catylst/template
5
5
  // 3. Downloads the CLI JAR to ~/.catylst/catylst-cli.jar
6
6
 
7
- const { spawnSync } = require("child_process");
8
- const https = require("https");
7
+ // NOTE: all progress output goes to stderr.
8
+ // npm buffers stdout during install and only shows it on error.
9
+ // stderr is streamed to the terminal in real-time.
10
+
11
+ const { spawnSync, spawn } = require("child_process");
12
+ const https = require("https");
9
13
  const crypto = require("crypto");
10
- const fs = require("fs");
11
- const path = require("path");
12
- const os = require("os");
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+ const os = require("os");
13
17
 
14
18
  const REPO_URL = "https://github.com/rohit-554/Catylst.git";
15
- const JAR_URL =
16
- "https://github.com/rohit-554/Catylst/releases/latest/download/catylst-cli.jar";
19
+ const JAR_URL = "https://github.com/rohit-554/Catylst/releases/latest/download/catylst-cli.jar";
17
20
 
18
- // Trusted hosts for redirect following — no other host is allowed
19
21
  const TRUSTED_HOSTS = [
20
22
  "github.com",
21
23
  "objects.githubusercontent.com",
@@ -24,164 +26,173 @@ const TRUSTED_HOSTS = [
24
26
  "codeload.github.com",
25
27
  ];
26
28
 
27
- const CATYLST_DIR = path.join(os.homedir(), ".catylst");
29
+ const CATYLST_DIR = path.join(os.homedir(), ".catylst");
28
30
  const TEMPLATE_DIR = path.join(CATYLST_DIR, "template");
29
- const JAR_PATH = path.join(CATYLST_DIR, "catylst-cli.jar");
31
+ const JAR_PATH = path.join(CATYLST_DIR, "catylst-cli.jar");
32
+
33
+ // ── colours ───────────────────────────────────────────────────────────────────
30
34
 
31
- const green = (s) => `\x1b[32m${s}\x1b[0m`;
35
+ const green = (s) => `\x1b[32m${s}\x1b[0m`;
32
36
  const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
33
- const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
34
- const bold = (s) => `\x1b[1m${s}\x1b[0m`;
35
- const dim = (s) => `\x1b[2m${s}\x1b[0m`;
37
+ const cyan = (s) => `\x1b[36m${s}\x1b[0m`;
38
+ const bold = (s) => `\x1b[1m${s}\x1b[0m`;
39
+ const dim = (s) => `\x1b[2m${s}\x1b[0m`;
40
+ const purple = (s) => `\x1b[35m${s}\x1b[0m`;
41
+
42
+ const print = (s) => process.stderr.write(s + "\n");
43
+ const printRaw = (s) => process.stderr.write(s);
44
+
45
+ // ── tips & jokes ──────────────────────────────────────────────────────────────
46
+
47
+ const MESSAGES = [
48
+ ["tip", "Room 3.1 auto-generates all your DAO queries at compile time."],
49
+ ["tip", "Navigation3 uses type-safe routes — no more string typos in nav graphs."],
50
+ ["tip", "Swap AI providers by changing one line in AppModule.kt."],
51
+ ["tip", "bloom-build scaffolds a full screen — Entity, DAO, ViewModel, UI — in seconds."],
52
+ ["tip", "Material 3 Expressive ships spring-based motion out of the box."],
53
+ ["tip", "Run ./gradlew :composeApp:kspAndroidMain after every Room Entity change."],
54
+ ["tip", "Koin multiplatform means one DI graph for Android, iOS, and Desktop."],
55
+ ["tip", "bloom-navigate cleanly removes any feature you do not need."],
56
+ ["tip", "AGP 9 brings predictive back gesture support by default."],
57
+ ["tip", "commonMain code compiles to all targets — write once, ship everywhere."],
58
+ ["joke", "Why do Kotlin developers stay calm? They know how to handle exceptions."],
59
+ ["joke", "A null pointer walks into a bar. Bartender: we don't serve your type here."],
60
+ ["joke", "Why did the Android dev quit? Too many fragments."],
61
+ ["joke", "Kotlin: where semicolons go to retire."],
62
+ ["joke", "iOS dev asks what Gradle is. Android dev weeps softly."],
63
+ ["joke", "There are 10 types of developers: those who get binary and those who don't."],
64
+ ["joke", "A git push a day keeps the merge conflicts away. Usually."],
65
+ ["joke", "My code works. I have no idea why. Shipping it anyway."],
66
+ ];
67
+
68
+ let tipTimer = null;
69
+
70
+ function startTips() {
71
+ const msgs = [...MESSAGES].sort(() => Math.random() - 0.5);
72
+ let i = 0;
73
+ function next() {
74
+ const [kind, text] = msgs[i++ % msgs.length];
75
+ const label = kind === "joke" ? purple("joke") : cyan("tip ");
76
+ printRaw(`\r ${label} ${dim(text)}${" ".repeat(6)}`);
77
+ tipTimer = setTimeout(next, 3200);
78
+ }
79
+ next();
80
+ }
81
+
82
+ function stopTips(line) {
83
+ if (tipTimer) { clearTimeout(tipTimer); tipTimer = null; }
84
+ printRaw(`\r${line}${" ".repeat(40)}\n`);
85
+ }
86
+
87
+ // ── helpers ───────────────────────────────────────────────────────────────────
88
+
89
+ // Async wrapper for spawn — keeps event loop alive so timers fire during git ops
90
+ function runAsync(cmd, args, opts = {}) {
91
+ return new Promise((resolve, reject) => {
92
+ const child = spawn(cmd, args, { stdio: "pipe", ...opts });
93
+ const stderr = [];
94
+ child.stderr && child.stderr.on("data", (d) => stderr.push(d));
95
+ child.on("close", (code) => resolve({ status: code, stderr: Buffer.concat(stderr) }));
96
+ child.on("error", reject);
97
+ });
98
+ }
36
99
 
37
- console.log("");
38
- console.log(bold(" Catylst KMP Project Generator"));
39
- console.log(dim(" ────────────────────────────────────────"));
40
- console.log("");
100
+ function isTrustedHost(urlString) {
101
+ try {
102
+ const { hostname } = new URL(urlString);
103
+ return TRUSTED_HOSTS.some((h) => hostname === h || hostname.endsWith("." + h));
104
+ } catch { return false; }
105
+ }
41
106
 
42
- // ── 1. Check Java ────────────────────────────────────────────────────────────
107
+ // ── 1. Check Java ─────────────────────────────────────────────────────────────
43
108
 
44
109
  function checkJava() {
45
110
  const result = spawnSync("java", ["-version"], { encoding: "utf8" });
46
111
  const output = result.stderr || result.stdout || "";
47
- const match = output.match(/version "(\d+)/);
112
+ const match = output.match(/version "(\d+)/);
48
113
  if (!match) {
49
- console.error(yellow(" Java not found. Install JDK 17+ from https://adoptium.net"));
114
+ print(yellow(" x Java not found. Install JDK 17+ from https://adoptium.net"));
50
115
  process.exit(1);
51
116
  }
52
117
  const major = parseInt(match[1], 10);
53
118
  if (major < 17) {
54
- console.error(
55
- yellow(` ✗ JDK 17+ required (found ${major}). Install from https://adoptium.net`)
56
- );
119
+ print(yellow(` x JDK 17+ required (found ${major}). https://adoptium.net`));
57
120
  process.exit(1);
58
121
  }
59
- console.log(green(` Java ${major}`));
122
+ print(green(` ok Java ${major}`));
60
123
  }
61
124
 
62
- // ── 2. Clone / update template ───────────────────────────────────────────────
125
+ // ── 2. Clone / update template ────────────────────────────────────────────────
63
126
 
64
- function setupTemplate() {
127
+ async function setupTemplate() {
65
128
  fs.mkdirSync(CATYLST_DIR, { recursive: true });
66
129
 
67
- const isGitRepo = fs.existsSync(path.join(TEMPLATE_DIR, ".git"));
68
-
69
- if (isGitRepo) {
70
- process.stdout.write(cyan(" ↻ Updating template..."));
71
- // Use spawn array form — no shell interpolation, no injection risk
72
- const result = spawnSync("git", ["pull", "--quiet", "--rebase"], {
73
- cwd: TEMPLATE_DIR,
74
- stdio: "pipe",
75
- });
76
- if (result.status === 0) {
77
- console.log("\r" + green(" ✓ Template updated "));
78
- } else {
79
- console.log("\r" + yellow(" ⚠ Could not update template (offline?). Using existing."));
80
- }
130
+ if (fs.existsSync(path.join(TEMPLATE_DIR, ".git"))) {
131
+ startTips();
132
+ const r = await runAsync("git", ["pull", "--quiet", "--rebase"], { cwd: TEMPLATE_DIR });
133
+ stopTips(r.status === 0
134
+ ? green(" ok Template updated")
135
+ : yellow(" !! Could not update template (offline?). Using existing."));
81
136
  } else {
82
- console.log(cyan(" Cloning template to ~/.catylst/template ..."));
137
+ print(dim(" .. Cloning template\n"));
138
+ startTips();
83
139
  fs.rmSync(TEMPLATE_DIR, { recursive: true, force: true });
84
- // Use spawn array form REPO_URL and TEMPLATE_DIR are never shell-interpolated
85
- const result = spawnSync(
86
- "git",
87
- ["clone", "--depth", "1", "--quiet", REPO_URL, TEMPLATE_DIR],
88
- { stdio: "pipe" }
89
- );
90
- if (result.status !== 0) {
91
- const msg = result.stderr ? result.stderr.toString().trim() : "unknown error";
92
- console.error(yellow(" ✗ Failed to clone template. Is git installed?"));
93
- console.error(dim(` ${msg}`));
140
+ const r = await runAsync("git", ["clone", "--depth", "1", "--quiet", REPO_URL, TEMPLATE_DIR]);
141
+ if (r.status !== 0) {
142
+ stopTips("");
143
+ print(yellow(" x Failed to clone. Is git installed?"));
144
+ print(dim(" " + r.stderr.toString().trim()));
94
145
  process.exit(1);
95
146
  }
96
- console.log(green(" Template ready"));
147
+ stopTips(green(" ok Template ready"));
97
148
  }
98
149
  }
99
150
 
100
- // ── 3. Download JAR ──────────────────────────────────────────────────────────
101
-
102
- function isTrustedHost(urlString) {
103
- try {
104
- const { hostname } = new URL(urlString);
105
- return TRUSTED_HOSTS.some((h) => hostname === h || hostname.endsWith("." + h));
106
- } catch {
107
- return false;
108
- }
109
- }
151
+ // ── 3. Download JAR ───────────────────────────────────────────────────────────
110
152
 
111
153
  function downloadJar() {
112
- // Dev mode use local build if available
113
- const localJar = path.join(
114
- TEMPLATE_DIR,
115
- "cli-generator",
116
- "build",
117
- "libs",
118
- "cli-generator-1.0.0.jar"
119
- );
154
+ const localJar = path.join(TEMPLATE_DIR, "cli-generator", "build", "libs", "cli-generator-1.0.0.jar");
120
155
  if (fs.existsSync(localJar)) {
121
156
  fs.copyFileSync(localJar, JAR_PATH);
122
- console.log(green(" Using local build"));
157
+ print(green(" ok Using local build"));
123
158
  return Promise.resolve();
124
159
  }
125
160
 
126
161
  return new Promise((resolve, reject) => {
127
- process.stdout.write(cyan(" Downloading catylst-cli.jar ..."));
128
-
129
- // Write to a temp file first — atomic rename prevents race conditions
162
+ print(dim(" .. Downloading CLI\n"));
163
+ startTips();
130
164
  const tmpPath = JAR_PATH + ".tmp." + process.pid;
131
165
 
132
- function get(url, redirectCount = 0) {
133
- if (redirectCount > 5) return reject(new Error("Too many redirects"));
134
-
135
- // Validate redirect destination stays on trusted hosts
136
- if (!isTrustedHost(url)) {
137
- return reject(new Error(`Redirect to untrusted host blocked: ${url}`));
138
- }
139
-
140
- https
141
- .get(url, { headers: { "User-Agent": "catylst-npm-installer" } }, (res) => {
142
- if (res.statusCode === 301 || res.statusCode === 302) {
143
- const location = res.headers.location;
144
- if (!location) return reject(new Error("Redirect with no Location header"));
145
- return get(location, redirectCount + 1);
146
- }
147
- if (res.statusCode !== 200) {
148
- return reject(new Error(`HTTP ${res.statusCode}`));
149
- }
150
-
151
- // Stream to temp file with restricted permissions (owner read/write only)
152
- const file = fs.createWriteStream(tmpPath, { mode: 0o600 });
153
- const hash = crypto.createHash("sha256");
154
-
155
- res.on("data", (chunk) => hash.update(chunk));
156
- res.pipe(file);
157
-
158
- file.on("finish", () => {
159
- file.close(() => {
160
- // Atomic rename — prevents TOCTOU race where another process
161
- // could read a partially-written file
162
- try {
163
- fs.renameSync(tmpPath, JAR_PATH);
164
- } catch (e) {
165
- fs.unlinkSync(tmpPath);
166
- return reject(e);
167
- }
168
-
169
- const digest = hash.digest("hex");
170
- console.log("\r" + green(" ✓ CLI ready "));
171
- console.log(dim(` SHA-256: ${digest}`));
172
- resolve();
173
- });
166
+ function get(url, hops = 0) {
167
+ if (hops > 5) return reject(new Error("Too many redirects"));
168
+ if (!isTrustedHost(url)) return reject(new Error(`Blocked redirect to: ${url}`));
169
+
170
+ https.get(url, { headers: { "User-Agent": "catylst-npm-installer" } }, (res) => {
171
+ if (res.statusCode === 301 || res.statusCode === 302) {
172
+ const loc = res.headers.location;
173
+ if (!loc) return reject(new Error("Redirect missing Location header"));
174
+ return get(loc, hops + 1);
175
+ }
176
+ if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`));
177
+
178
+ const file = fs.createWriteStream(tmpPath, { mode: 0o600 });
179
+ const hash = crypto.createHash("sha256");
180
+
181
+ res.on("data", (chunk) => hash.update(chunk));
182
+ res.pipe(file);
183
+
184
+ file.on("finish", () => {
185
+ file.close(() => {
186
+ try { fs.renameSync(tmpPath, JAR_PATH); }
187
+ catch (e) { fs.unlink(tmpPath, () => {}); return reject(e); }
188
+ stopTips(green(" ok CLI ready"));
189
+ print(dim(` sha256: ${hash.digest("hex")}`));
190
+ resolve();
174
191
  });
175
-
176
- file.on("error", (err) => {
177
- fs.unlink(tmpPath, () => {});
178
- reject(err);
179
- });
180
- })
181
- .on("error", (err) => {
182
- fs.unlink(tmpPath, () => {});
183
- reject(err);
184
192
  });
193
+
194
+ file.on("error", (e) => { stopTips(""); fs.unlink(tmpPath, () => {}); reject(e); });
195
+ }).on("error", (e) => { stopTips(""); fs.unlink(tmpPath, () => {}); reject(e); });
185
196
  }
186
197
 
187
198
  get(JAR_URL);
@@ -191,17 +202,21 @@ function downloadJar() {
191
202
  // ── run ───────────────────────────────────────────────────────────────────────
192
203
 
193
204
  (async () => {
205
+ print("");
206
+ print(bold(" Catylst KMP Project Generator"));
207
+ print(dim(" ──────────────────────────────────────"));
208
+ print("");
209
+
194
210
  checkJava();
195
- setupTemplate();
211
+ await setupTemplate();
196
212
  await downloadJar();
197
213
 
198
- console.log("");
199
- console.log(dim(" ────────────────────────────────────────"));
200
- console.log(" " + green(bold("All done!")) + " Start your project:");
201
- console.log("");
202
- console.log(" " + cyan("catylst --interactive"));
203
- console.log("");
204
- console.log(" " + dim("Or non-interactive:"));
205
- console.log(" " + dim("catylst --package com.example.app --name MyApp"));
206
- console.log("");
214
+ print("");
215
+ print(dim(" ──────────────────────────────────────"));
216
+ print(" " + green(bold("Done.")) + " Start your project:");
217
+ print("");
218
+ print(" " + cyan("catylst --interactive"));
219
+ print("");
220
+ print(" " + dim("catylst --package com.example.app --name MyApp"));
221
+ print("");
207
222
  })();