aakarui 0.0.0-stage → 1.0.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/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # aakarui 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
+ Node.js ES Module CLI for downloading and managing components from Aakar UI.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # From within the aakar-cli folder:
9
+ npm install
10
+ npm link
11
+ ```
12
+
13
+ ## Commands
14
+
15
+ ### 1. `aakar-ui login`
16
+ Prompts for email and password in the terminal, calls `POST /auth/login`, and stores credentials in `~/.aakar-ui/config.json`.
17
+ ```bash
18
+ aakar-ui login
19
+ ```
20
+ Flags `--email <email>` and `--password <password>` are also supported for scripting/CI environments.
21
+
22
+ ### 2. `aakar-ui whoami`
23
+ Reads the stored token, calls `GET /auth/me`, and prints your name, email, and current token balance.
24
+ ```bash
25
+ aakar-ui whoami
26
+ ```
27
+
28
+ ### 3. `aakar-ui add <commandName>`
29
+ Reads the saved token, sends a request to `POST /installations` with `{ commandName }` and a random UUID `idempotencyKey`, and writes the TSX source code to `./src/components/aakar/<commandName>.tsx`.
30
+ ```bash
31
+ aakar-ui add ai-citation-sidebar
32
+ ```
33
+
34
+ Handles 401 (not logged in), 402/400 (insufficient tokens), and 404 (component not found) cleanly.
35
+
36
+ ## Environment Variables
37
+
38
+ - `AAKAR_API_URL`: Override the default API URL (`http://localhost:8000/api/v1`).
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import { registerLoginCommand } from "../src/commands/login.js";
5
+ import { registerWhoamiCommand } from "../src/commands/whoami.js";
6
+ import { registerAddCommand } from "../src/commands/add.js";
7
+
8
+ const program = new Command();
9
+
10
+ program
11
+ .name("aakarui")
12
+ .description("Official CLI for adding Aakar UI components to your project")
13
+ .version("1.0.0");
14
+
15
+ registerLoginCommand(program);
16
+ registerWhoamiCommand(program);
17
+ registerAddCommand(program);
18
+
19
+ program.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "aakarui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Command-line interface to add accessible, production-ready React & Tailwind CSS components directly into your project.",
5
+ "type": "module",
6
+ "main": "./src/api.js",
7
+ "bin": {
8
+ "aakarui": "./bin/aakar-ui.js",
9
+ "aakar-ui": "./bin/aakar-ui.js"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "start": "node ./bin/aakar-ui.js"
18
+ },
19
+ "keywords": [
20
+ "aakarui",
21
+ "aakar-ui",
22
+ "ui",
23
+ "react",
24
+ "tailwind",
25
+ "components",
26
+ "cli"
27
+ ],
28
+ "author": "Aakar UI",
29
+ "license": "MIT",
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "dependencies": {
37
+ "commander": "^15.1.0"
38
+ }
39
+ }
package/src/api.js ADDED
@@ -0,0 +1,73 @@
1
+ import crypto from "node:crypto";
2
+
3
+ export function getBaseUrl() {
4
+ const url = process.env.AAKAR_API_URL || "https://aakar-backend-c3gk.onrender.com/api/v1";
5
+ return url.replace(/\/+$/, "");
6
+ }
7
+
8
+ async function safeFetch(url, options) {
9
+ try {
10
+ const response = await fetch(url, options);
11
+ const payload = await response.json().catch(() => ({}));
12
+ return { status: response.status, ok: response.ok, data: payload };
13
+ } catch (err) {
14
+ if (err.cause?.code === "ECONNREFUSED" || err.message?.includes("fetch failed")) {
15
+ throw new Error(`Unable to connect to backend at ${url}. Please verify the server is running.`);
16
+ }
17
+ throw err;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Call POST /auth/login
23
+ */
24
+ export async function loginRequest(email, password) {
25
+ const baseUrl = getBaseUrl();
26
+ const url = `${baseUrl}/auth/login`;
27
+
28
+ return safeFetch(url, {
29
+ method: "POST",
30
+ headers: {
31
+ "Content-Type": "application/json",
32
+ "Accept": "application/json",
33
+ },
34
+ body: JSON.stringify({ email, password }),
35
+ });
36
+ }
37
+
38
+ /**
39
+ * Call GET /auth/me
40
+ */
41
+ export async function getMeRequest(token) {
42
+ const baseUrl = getBaseUrl();
43
+ const url = `${baseUrl}/auth/me`;
44
+
45
+ return safeFetch(url, {
46
+ method: "GET",
47
+ headers: {
48
+ "Authorization": `Bearer ${token}`,
49
+ "Accept": "application/json",
50
+ },
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Call POST /installations
56
+ */
57
+ export async function installComponentRequest(token, commandName, idempotencyKey = crypto.randomUUID()) {
58
+ const baseUrl = getBaseUrl();
59
+ const url = `${baseUrl}/installations`;
60
+
61
+ return safeFetch(url, {
62
+ method: "POST",
63
+ headers: {
64
+ "Authorization": `Bearer ${token}`,
65
+ "Content-Type": "application/json",
66
+ "Accept": "application/json",
67
+ },
68
+ body: JSON.stringify({
69
+ commandName,
70
+ idempotencyKey,
71
+ }),
72
+ });
73
+ }
@@ -0,0 +1,277 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import crypto from "node:crypto";
5
+ import { getToken } from "../config.js";
6
+ import { installComponentRequest } from "../api.js";
7
+
8
+ function stripJsonComments(str) {
9
+ return str.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => (g ? "" : m));
10
+ }
11
+
12
+ export function registerAddCommand(program) {
13
+ program
14
+ .command("add <commandName>")
15
+ .description("Install an Aakar UI component into ./src/components/aakar/<commandName>.tsx")
16
+ .option("-y, --yes", "Automatically install missing dependencies and scaffolding")
17
+ .action(async (commandName, options) => {
18
+ try {
19
+ // ==========================================
20
+ // 1. Auth Check (~/.aakar-ui/config.json)
21
+ // ==========================================
22
+ const token = await getToken();
23
+ if (!token) {
24
+ console.error("✗ Not logged in. Please run \"aakarui login\" first.");
25
+ process.exit(1);
26
+ }
27
+
28
+ const projectRoot = process.cwd();
29
+
30
+ // ==========================================
31
+ // 2. Dependency Check (package.json)
32
+ // ==========================================
33
+ const pkgJsonPath = path.join(projectRoot, "package.json");
34
+ if (!existsSync(pkgJsonPath)) {
35
+ console.error("✗ No package.json found in the current directory.");
36
+ console.error(" Please run this command from the root of your React / Vite project.");
37
+ process.exit(1);
38
+ }
39
+
40
+ let pkgJson;
41
+ try {
42
+ const pkgContent = await fs.readFile(pkgJsonPath, "utf-8");
43
+ pkgJson = JSON.parse(pkgContent);
44
+ } catch (err) {
45
+ console.error(`✗ Failed to parse package.json: ${err.message}`);
46
+ process.exit(1);
47
+ }
48
+
49
+ const allDeps = {
50
+ ...(pkgJson.dependencies || {}),
51
+ ...(pkgJson.devDependencies || {}),
52
+ };
53
+
54
+ const requiredDeps = ["tailwindcss", "clsx", "tailwind-merge"];
55
+ const missingDeps = requiredDeps.filter((dep) => !allDeps[dep]);
56
+
57
+ if (missingDeps.length > 0) {
58
+ if (options.yes) {
59
+ console.log(`ℹ Installing missing dependencies: ${missingDeps.join(" ")}...`);
60
+ try {
61
+ const { execSync } = await import("node:child_process");
62
+ execSync(`npm install ${missingDeps.join(" ")}`, { stdio: "inherit", cwd: projectRoot });
63
+ } catch (err) {
64
+ console.error(`✗ Failed to install dependencies: ${err.message}`);
65
+ process.exit(1);
66
+ }
67
+ } else {
68
+ console.error(`✗ Missing required dependencies: ${missingDeps.join(", ")}`);
69
+ console.error(" Please install them before installing components:");
70
+ console.error(` npm install ${missingDeps.join(" ")}`);
71
+ console.error(" (Or re-run with --yes to install automatically)");
72
+ process.exit(1);
73
+ }
74
+ }
75
+
76
+ // ==========================================
77
+ // 3. Utility Helper Check (src/lib/utils)
78
+ // ==========================================
79
+ const candidateUtils = [
80
+ path.join(projectRoot, "src", "lib", "utils.ts"),
81
+ path.join(projectRoot, "src", "lib", "utils.js"),
82
+ path.join(projectRoot, "src", "lib", "utils.tsx"),
83
+ path.join(projectRoot, "src", "lib", "utils.jsx"),
84
+ ];
85
+
86
+ let utilsPath = candidateUtils.find((p) => existsSync(p));
87
+
88
+ if (!utilsPath) {
89
+ if (options.yes) {
90
+ const isTs = existsSync(path.join(projectRoot, "tsconfig.json")) || existsSync(path.join(projectRoot, "tsconfig.app.json"));
91
+ const defaultUtilsPath = path.join(projectRoot, "src", "lib", isTs ? "utils.ts" : "utils.js");
92
+ await fs.mkdir(path.dirname(defaultUtilsPath), { recursive: true });
93
+ const utilsContent = `import { clsx } from "clsx";\nimport { twMerge } from "tailwind-merge";\n\nexport function cn(...inputs) {\n return twMerge(clsx(inputs));\n}\n`;
94
+ await fs.writeFile(defaultUtilsPath, utilsContent, "utf-8");
95
+ console.log(`✓ Created ${path.relative(projectRoot, defaultUtilsPath)} with cn(...) helper`);
96
+ utilsPath = defaultUtilsPath;
97
+ } else {
98
+ console.error("✗ Missing utility helper: 'src/lib/utils.ts' or 'src/lib/utils.js' with the 'cn' helper was not found.");
99
+ console.error(" Please create 'src/lib/utils.ts' (or utils.js) with the following content:");
100
+ console.error("");
101
+ console.error(' import { clsx } from "clsx";');
102
+ console.error(' import { twMerge } from "tailwind-merge";');
103
+ console.error("");
104
+ console.error(" export function cn(...inputs) {");
105
+ console.error(" return twMerge(clsx(inputs));");
106
+ console.error(" }");
107
+ console.error("");
108
+ console.error(" (Or re-run with --yes to create it automatically)");
109
+ process.exit(1);
110
+ }
111
+ }
112
+
113
+ // Verify cn helper is present in utils file
114
+ try {
115
+ const utilsContent = await fs.readFile(utilsPath, "utf-8");
116
+ if (!utilsContent.includes("cn(")) {
117
+ console.error(`✗ Utility file '${path.relative(projectRoot, utilsPath)}' does not define a 'cn' helper function.`);
118
+ console.error(" Please ensure cn(...) is exported using clsx and tailwind-merge.");
119
+ process.exit(1);
120
+ }
121
+ } catch (err) {
122
+ console.error(`✗ Error reading utility file: ${err.message}`);
123
+ process.exit(1);
124
+ }
125
+
126
+ // ==========================================
127
+ // 4. Path Alias Check (@/* in tsconfig/jsconfig)
128
+ // ==========================================
129
+ const configFiles = ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"];
130
+ let hasPathsAlias = false;
131
+
132
+ for (const file of configFiles) {
133
+ const fullPath = path.join(projectRoot, file);
134
+ if (existsSync(fullPath)) {
135
+ try {
136
+ const raw = await fs.readFile(fullPath, "utf-8");
137
+ const parsed = JSON.parse(stripJsonComments(raw));
138
+ const paths = parsed.compilerOptions?.paths;
139
+ if (paths && (paths["@/*"] || paths["@"])) {
140
+ const aliasValues = paths["@/*"] || paths["@"];
141
+ const aliasArr = Array.isArray(aliasValues) ? aliasValues : [aliasValues];
142
+ if (aliasArr.some((v) => typeof v === "string" && (v.includes("src") || v.includes("./src")))) {
143
+ hasPathsAlias = true;
144
+ break;
145
+ }
146
+ }
147
+ } catch {
148
+ // Regex fallback if JSON has non-standard trailing commas/comments
149
+ const raw = await fs.readFile(fullPath, "utf-8");
150
+ if (/["']@\/\*["']\s*:\s*\[\s*["'](\.\/)?src\/\*["']\s*\]/.test(raw) || /["']@["']\s*:\s*\[\s*["'](\.\/)?src["']\s*\]/.test(raw)) {
151
+ hasPathsAlias = true;
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ if (!hasPathsAlias) {
159
+ console.error("✗ Missing TypeScript/JavaScript path alias configuration.");
160
+ console.error(" None of tsconfig.json, tsconfig.app.json, or jsconfig.json define \"@/*\": [\"./src/*\"].");
161
+ console.error("");
162
+ console.error(" Please add the following under 'compilerOptions' in your tsconfig.json (or jsconfig.json):");
163
+ console.error("");
164
+ console.error(" {");
165
+ console.error(' "compilerOptions": {');
166
+ console.error(' "paths": {');
167
+ console.error(' "@/*": ["./src/*"]');
168
+ console.error(" }");
169
+ console.error(" }");
170
+ console.error(" }");
171
+ console.error("");
172
+ process.exit(1);
173
+ }
174
+
175
+ // ==========================================
176
+ // 5. Path Alias Check (vite.config.js / .ts)
177
+ // ==========================================
178
+ const viteConfigFiles = [
179
+ "vite.config.js",
180
+ "vite.config.ts",
181
+ "vite.config.mjs",
182
+ "vite.config.cjs",
183
+ ];
184
+ const foundViteFile = viteConfigFiles.find((f) => existsSync(path.join(projectRoot, f)));
185
+
186
+ if (!foundViteFile) {
187
+ console.error("✗ No Vite configuration file found (vite.config.js or vite.config.ts).");
188
+ console.error(" Please ensure your Vite project has a configuration file.");
189
+ process.exit(1);
190
+ }
191
+
192
+ const viteRaw = await fs.readFile(path.join(projectRoot, foundViteFile), "utf-8");
193
+ const hasViteAlias =
194
+ (/alias\s*:\s*\{[^}]*['"]@['"]\s*:\s*[^}]+src/i.test(viteRaw)) ||
195
+ (/alias\s*:\s*\[[\s\S]*?find\s*:\s*['"]@['"][\s\S]*?replacement\s*:\s*[^\]]+src/i.test(viteRaw)) ||
196
+ (/['"]@['"]\s*:\s*path\.resolve\(__dirname,\s*['"]\.\/src['"]\)/i.test(viteRaw)) ||
197
+ (/['"]@['"]\s*:\s*['"]\.\/src['"]/i.test(viteRaw)) ||
198
+ (/['"]@['"]\s*:\s*path\.resolve\(__dirname,\s*['"]src['"]\)/i.test(viteRaw));
199
+
200
+ if (!hasViteAlias) {
201
+ console.error(`✗ Vite path alias '@' is not configured in ${foundViteFile}.`);
202
+ console.error(" Please configure the '@' alias to resolve to './src':");
203
+ console.error("");
204
+ console.error(` // In ${foundViteFile}:`);
205
+ console.error(' import path from "path";');
206
+ console.error(' import { defineConfig } from "vite";');
207
+ console.error("");
208
+ console.error(" export default defineConfig({");
209
+ console.error(" resolve: {");
210
+ console.error(" alias: {");
211
+ console.error(' "@": path.resolve(__dirname, "./src"),');
212
+ console.error(" },");
213
+ console.error(" },");
214
+ console.error(" });");
215
+ console.error("");
216
+ process.exit(1);
217
+ }
218
+
219
+ // ==========================================
220
+ // 6. Execute Installation Request
221
+ // ==========================================
222
+ const idempotencyKey = crypto.randomUUID();
223
+ const { status, ok, data } = await installComponentRequest(token, commandName, idempotencyKey);
224
+
225
+ if (status === 401) {
226
+ console.error("✗ Unauthorized: You must be logged in to install components. Please run \"aakarui login\".");
227
+ process.exit(1);
228
+ }
229
+
230
+ if (status === 403) {
231
+ console.error(`✗ Forbidden: ${data?.message || "Account is not active or verified."}`);
232
+ process.exit(1);
233
+ }
234
+
235
+ if (status === 402 || (status === 400 && data?.message?.toLowerCase().includes("balance"))) {
236
+ const message = data?.message || "Insufficient tokens to install this component.";
237
+ console.error(`✗ Insufficient tokens: ${message}`);
238
+ process.exit(1);
239
+ }
240
+
241
+ if (status === 404) {
242
+ console.error(`✗ Component not found: ${data?.message || `Component '${commandName}' not found.`}`);
243
+ process.exit(1);
244
+ }
245
+
246
+ if (!ok || !data.success) {
247
+ const errorMessage = data?.message || `Installation failed with HTTP status ${status}`;
248
+ console.error(`✗ Installation failed: ${errorMessage}`);
249
+ process.exit(1);
250
+ }
251
+
252
+ const { installation, component, sourceCode, wallet } = data.data;
253
+
254
+ if (!sourceCode) {
255
+ console.error("✗ Error: No source code received for this component.");
256
+ process.exit(1);
257
+ }
258
+
259
+ const relativePath = path.join("src", "components", "aakar", `${commandName}.tsx`);
260
+ const targetPath = path.resolve(process.cwd(), relativePath);
261
+
262
+ // Ensure target directory exists
263
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
264
+
265
+ // Write TSX source code
266
+ await fs.writeFile(targetPath, sourceCode, "utf-8");
267
+
268
+ console.log(`✓ Installed ${component?.name || commandName} successfully!`);
269
+ console.log(` File created: ./${relativePath.replace(/\\/g, "/")}`);
270
+ console.log(` Tokens deducted: ${installation?.creditsCharged ?? 0}`);
271
+ console.log(` Balance: ${wallet?.balance ?? 0}`);
272
+ } catch (err) {
273
+ console.error(`✗ An unexpected error occurred: ${err.message}`);
274
+ process.exit(1);
275
+ }
276
+ });
277
+ }
@@ -0,0 +1,57 @@
1
+ import { askQuestion, askPassword, closePrompt } from "../utils/prompt.js";
2
+ import { loginRequest } from "../api.js";
3
+ import { saveConfig, CONFIG_FILE } from "../config.js";
4
+
5
+ export function registerLoginCommand(program) {
6
+ program
7
+ .command("login")
8
+ .description("Authenticate with Aakar UI and save access credentials")
9
+ .option("-e, --email <email>", "User email address")
10
+ .option("-p, --password <password>", "User password")
11
+ .action(async (options) => {
12
+ try {
13
+ let email = options.email;
14
+ let password = options.password;
15
+
16
+ if (!email) {
17
+ email = await askQuestion("Enter your email: ");
18
+ }
19
+
20
+ if (!email) {
21
+ closePrompt();
22
+ console.error("✗ Error: Email is required.");
23
+ process.exit(1);
24
+ }
25
+
26
+ if (!password) {
27
+ password = await askPassword("Enter your password: ");
28
+ }
29
+
30
+ closePrompt();
31
+
32
+ if (!password) {
33
+ console.error("✗ Error: Password is required.");
34
+ process.exit(1);
35
+ }
36
+
37
+ const { status, ok, data } = await loginRequest(email, password);
38
+
39
+ if (!ok || !data.success) {
40
+ const errorMessage = data?.message || `Login failed with HTTP status ${status}`;
41
+ console.error(`✗ Login failed: ${errorMessage}`);
42
+ process.exit(1);
43
+ }
44
+
45
+ const { token, user } = data.data;
46
+
47
+ await saveConfig({ token, user });
48
+
49
+ console.log(`✓ Logged in successfully as ${user.name} (${user.email})`);
50
+ console.log(`✓ Configuration saved to ${CONFIG_FILE}`);
51
+ } catch (err) {
52
+ closePrompt();
53
+ console.error(`✗ An unexpected error occurred: ${err.message}`);
54
+ process.exit(1);
55
+ }
56
+ });
57
+ }
@@ -0,0 +1,41 @@
1
+ import { getToken } from "../config.js";
2
+ import { getMeRequest } from "../api.js";
3
+
4
+ export function registerWhoamiCommand(program) {
5
+ program
6
+ .command("whoami")
7
+ .description("Display details and token balance of currently logged-in user")
8
+ .action(async () => {
9
+ try {
10
+ const token = await getToken();
11
+
12
+ if (!token) {
13
+ console.error("✗ Not logged in. Please run \"aakarui login\" first.");
14
+ process.exit(1);
15
+ }
16
+
17
+ const { status, ok, data } = await getMeRequest(token);
18
+
19
+ if (status === 401) {
20
+ console.error("✗ Authentication failed: Session expired or invalid token. Please run \"aakarui login\" to log in again.");
21
+ process.exit(1);
22
+ }
23
+
24
+ if (!ok || !data.success) {
25
+ const errorMessage = data?.message || `Failed to fetch profile (HTTP ${status})`;
26
+ console.error(`✗ Error: ${errorMessage}`);
27
+ process.exit(1);
28
+ }
29
+
30
+ const { user, wallet } = data.data;
31
+
32
+ console.log("Logged in user:");
33
+ console.log(` Name: ${user.name}`);
34
+ console.log(` Email: ${user.email}`);
35
+ console.log(` Token balance: ${wallet?.balance ?? 0}`);
36
+ } catch (err) {
37
+ console.error(`✗ An unexpected error occurred: ${err.message}`);
38
+ process.exit(1);
39
+ }
40
+ });
41
+ }
package/src/config.js ADDED
@@ -0,0 +1,41 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import fs from "node:fs/promises";
4
+ import { existsSync } from "node:fs";
5
+
6
+ export const CONFIG_DIR = path.join(os.homedir(), ".aakar-ui");
7
+ export const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
8
+
9
+ /**
10
+ * Read stored config from ~/.aakar-ui/config.json
11
+ * @returns {Promise<{token?: string, user?: object} | null>}
12
+ */
13
+ export async function readConfig() {
14
+ try {
15
+ if (!existsSync(CONFIG_FILE)) {
16
+ return null;
17
+ }
18
+ const content = await fs.readFile(CONFIG_FILE, "utf-8");
19
+ return JSON.parse(content);
20
+ } catch (err) {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Save config object { token, user } to ~/.aakar-ui/config.json
27
+ * @param {{token: string, user: object}} config
28
+ */
29
+ export async function saveConfig(config) {
30
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
31
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
32
+ }
33
+
34
+ /**
35
+ * Retrieve the saved auth token
36
+ * @returns {Promise<string | null>}
37
+ */
38
+ export async function getToken() {
39
+ const config = await readConfig();
40
+ return config?.token || null;
41
+ }
@@ -0,0 +1,100 @@
1
+ import readline from "node:readline";
2
+
3
+ let nonTtyIterator = null;
4
+ let nonTtyInterface = null;
5
+
6
+ function getNonTtyIterator() {
7
+ if (!nonTtyIterator) {
8
+ nonTtyInterface = readline.createInterface({
9
+ input: process.stdin,
10
+ output: process.stdout,
11
+ });
12
+ nonTtyIterator = nonTtyInterface[Symbol.asyncIterator]();
13
+ }
14
+ return nonTtyIterator;
15
+ }
16
+
17
+ export function closePrompt() {
18
+ if (nonTtyInterface && !nonTtyInterface.closed) {
19
+ nonTtyInterface.close();
20
+ nonTtyInterface = null;
21
+ nonTtyIterator = null;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Prompt user with a text query
27
+ */
28
+ export async function askQuestion(query) {
29
+ if (!process.stdin.isTTY) {
30
+ process.stdout.write(query);
31
+ const it = getNonTtyIterator();
32
+ const next = await it.next();
33
+ return next.done ? "" : next.value.trim();
34
+ }
35
+
36
+ return new Promise((resolve) => {
37
+ const rl = readline.createInterface({
38
+ input: process.stdin,
39
+ output: process.stdout,
40
+ });
41
+ rl.question(query, (answer) => {
42
+ rl.close();
43
+ resolve(answer.trim());
44
+ });
45
+ });
46
+ }
47
+
48
+ /**
49
+ * Prompt user for password with masking in TTY mode,
50
+ * and line read in non-TTY mode.
51
+ */
52
+ export async function askPassword(query) {
53
+ if (!process.stdin.isTTY) {
54
+ process.stdout.write(query);
55
+ const it = getNonTtyIterator();
56
+ const next = await it.next();
57
+ return next.done ? "" : next.value.trim();
58
+ }
59
+
60
+ return new Promise((resolve) => {
61
+ const stdin = process.stdin;
62
+ const stdout = process.stdout;
63
+
64
+ stdout.write(query);
65
+ let password = "";
66
+
67
+ stdin.setRawMode(true);
68
+ stdin.resume();
69
+ stdin.setEncoding("utf8");
70
+
71
+ const onData = (chunk) => {
72
+ for (const char of chunk) {
73
+ if (char === "\r" || char === "\n" || char === "\u0004") {
74
+ stdin.setRawMode(false);
75
+ stdin.pause();
76
+ stdin.removeListener("data", onData);
77
+ stdout.write("\n");
78
+ resolve(password.trim());
79
+ return;
80
+ } else if (char === "\u0003") {
81
+ // Ctrl+C
82
+ stdin.setRawMode(false);
83
+ stdin.pause();
84
+ process.exit(1);
85
+ } else if (char === "\b" || char === "\x7f") {
86
+ // Backspace
87
+ if (password.length > 0) {
88
+ password = password.slice(0, -1);
89
+ stdout.write("\b \b");
90
+ }
91
+ } else {
92
+ password += char;
93
+ stdout.write("*");
94
+ }
95
+ }
96
+ };
97
+
98
+ stdin.on("data", onData);
99
+ });
100
+ }