juas.dev 1.0.0 → 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,351 @@
1
+ // ============================================================
2
+ // commands/login.js — `juas login`
3
+ // ============================================================
4
+ import { spawn } from "child_process";
5
+ import crypto from "crypto";
6
+ import http from "http";
7
+ import readline from "readline/promises";
8
+ import ora from "ora";
9
+ import pc from "picocolors";
10
+ import { fetchWhoami } from "../lib/authApi.js";
11
+ import {
12
+ getCliBaseUrl,
13
+ getCredentialsPath,
14
+ maskToken,
15
+ writeCredentials,
16
+ } from "../lib/credentials.js";
17
+ import { logger } from "../lib/logger.js";
18
+
19
+ const LOGIN_TIMEOUT_MS = 180_000;
20
+ const MAX_BODY_BYTES = 8192;
21
+
22
+ function timingSafeStateEqual(a, b) {
23
+ if (typeof a !== "string" || typeof b !== "string") return false;
24
+ const bufA = Buffer.from(a);
25
+ const bufB = Buffer.from(b);
26
+ if (bufA.length !== bufB.length || bufA.length === 0) return false;
27
+ return crypto.timingSafeEqual(bufA, bufB);
28
+ }
29
+
30
+ function openExternalUrl(targetUrl) {
31
+ try {
32
+ if (process.platform === "win32") {
33
+ const child = spawn("cmd", ["/c", "start", "", targetUrl], {
34
+ detached: true,
35
+ stdio: "ignore",
36
+ });
37
+ child.unref();
38
+ return true;
39
+ }
40
+ if (process.platform === "darwin") {
41
+ const child = spawn("open", [targetUrl], {
42
+ detached: true,
43
+ stdio: "ignore",
44
+ });
45
+ child.unref();
46
+ return true;
47
+ }
48
+ const child = spawn("xdg-open", [targetUrl], {
49
+ detached: true,
50
+ stdio: "ignore",
51
+ });
52
+ child.unref();
53
+ return true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ function isAllowedLoopbackOrigin(originHeader, expectedOrigin) {
60
+ if (!originHeader) return false;
61
+ if (originHeader === expectedOrigin || originHeader === "https://juas.dev") {
62
+ return true;
63
+ }
64
+ return /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(originHeader);
65
+ }
66
+
67
+ function buildCallbackSuccessHtml() {
68
+ return `<!doctype html>
69
+ <html lang="en">
70
+ <head>
71
+ <meta charset="utf-8" />
72
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
73
+ <title>Juas CLI Authorized</title>
74
+ <style>
75
+ body{font-family:system-ui,-apple-system,sans-serif;background:#09090b;color:#fafafa;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:24px;}
76
+ .card{max-width:420px;border:1px solid #27272a;background:#111114;border-radius:14px;padding:28px;text-align:center;}
77
+ h1{font-size:18px;margin:0 0 8px;}
78
+ p{font-size:14px;color:#a1a1aa;margin:0;line-height:1.5;}
79
+ </style>
80
+ </head>
81
+ <body>
82
+ <div class="card">
83
+ <h1>Juas CLI Connected</h1>
84
+ <p>Authentication succeeded and credentials are saved locally. You can close this browser tab and return to your terminal.</p>
85
+ </div>
86
+ </body>
87
+ </html>`;
88
+ }
89
+
90
+ function startLoopbackCallbackServer(expectedState, expectedOrigin) {
91
+ let resolveCallback;
92
+ let rejectCallback;
93
+ const resultPromise = new Promise((resolve, reject) => {
94
+ resolveCallback = resolve;
95
+ rejectCallback = reject;
96
+ });
97
+
98
+ let settled = false;
99
+
100
+ const server = http.createServer((req, res) => {
101
+ const originHeader = req.headers.origin;
102
+ const allowOrigin = isAllowedLoopbackOrigin(originHeader, expectedOrigin)
103
+ ? originHeader
104
+ : expectedOrigin;
105
+
106
+ const corsHeaders = {
107
+ "Access-Control-Allow-Origin": allowOrigin,
108
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
109
+ "Access-Control-Allow-Headers": "Content-Type, Accept",
110
+ "Access-Control-Allow-Private-Network": "true",
111
+ "Cache-Control": "no-store",
112
+ };
113
+
114
+ if (req.method === "OPTIONS") {
115
+ res.writeHead(204, corsHeaders);
116
+ res.end();
117
+ return;
118
+ }
119
+
120
+ const reqUrl = new URL(req.url || "/", "http://127.0.0.1");
121
+ if (reqUrl.pathname !== "/callback") {
122
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
123
+ res.end("Not Found");
124
+ return;
125
+ }
126
+
127
+ const handlePayload = (token, state, isJsonClient) => {
128
+ if (settled) {
129
+ res.writeHead(409, { ...corsHeaders, "Content-Type": "application/json" });
130
+ res.end(JSON.stringify({ ok: false, error: "Authorization already completed." }));
131
+ return;
132
+ }
133
+
134
+ if (!timingSafeStateEqual(state || "", expectedState)) {
135
+ res.writeHead(403, { ...corsHeaders, "Content-Type": "application/json" });
136
+ res.end(JSON.stringify({ ok: false, error: "Invalid CSRF state." }));
137
+ return;
138
+ }
139
+
140
+ if (!token || typeof token !== "string" || !token.trim()) {
141
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" });
142
+ res.end(JSON.stringify({ ok: false, error: "Missing authorization token." }));
143
+ return;
144
+ }
145
+
146
+ settled = true;
147
+ if (isJsonClient) {
148
+ res.writeHead(200, { ...corsHeaders, "Content-Type": "application/json" });
149
+ res.end(JSON.stringify({ ok: true }));
150
+ } else {
151
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
152
+ res.end(buildCallbackSuccessHtml());
153
+ }
154
+ resolveCallback(token.trim());
155
+ };
156
+
157
+ if (req.method === "GET") {
158
+ handlePayload(
159
+ reqUrl.searchParams.get("token"),
160
+ reqUrl.searchParams.get("state"),
161
+ false
162
+ );
163
+ return;
164
+ }
165
+
166
+ if (req.method === "POST") {
167
+ let body = "";
168
+ let oversized = false;
169
+ req.on("data", (chunk) => {
170
+ body += chunk.toString("utf-8");
171
+ if (body.length > MAX_BODY_BYTES) {
172
+ oversized = true;
173
+ res.writeHead(413, { ...corsHeaders, "Content-Type": "application/json" });
174
+ res.end(JSON.stringify({ ok: false, error: "Payload too large." }));
175
+ req.destroy();
176
+ }
177
+ });
178
+ req.on("end", () => {
179
+ if (oversized) return;
180
+ try {
181
+ const parsed = JSON.parse(body || "{}");
182
+ handlePayload(parsed.token, parsed.state, true);
183
+ } catch {
184
+ res.writeHead(400, { ...corsHeaders, "Content-Type": "application/json" });
185
+ res.end(JSON.stringify({ ok: false, error: "Invalid JSON callback body." }));
186
+ }
187
+ });
188
+ return;
189
+ }
190
+
191
+ res.writeHead(405, corsHeaders);
192
+ res.end();
193
+ });
194
+
195
+ const timeoutId = setTimeout(() => {
196
+ if (!settled) {
197
+ settled = true;
198
+ server.close();
199
+ rejectCallback(new Error("CLI login timed out after 3 minutes."));
200
+ }
201
+ }, LOGIN_TIMEOUT_MS);
202
+ timeoutId.unref();
203
+
204
+ return new Promise((resolve, reject) => {
205
+ server.on("error", reject);
206
+ server.listen(0, "127.0.0.1", () => {
207
+ const address = server.address();
208
+ if (!address || typeof address === "string") {
209
+ clearTimeout(timeoutId);
210
+ server.close();
211
+ reject(new Error("Could not bind loopback callback listener on 127.0.0.1."));
212
+ return;
213
+ }
214
+ resolve({
215
+ port: address.port,
216
+ waitForToken: async () => {
217
+ try {
218
+ return await resultPromise;
219
+ } finally {
220
+ clearTimeout(timeoutId);
221
+ server.close();
222
+ }
223
+ },
224
+ close: () => {
225
+ clearTimeout(timeoutId);
226
+ server.close();
227
+ },
228
+ });
229
+ });
230
+ });
231
+ }
232
+
233
+ async function verifyAndPersistToken(token, baseUrl) {
234
+ const spinner = ora("Verifying credentials with juas.dev…").start();
235
+ let verifyRes;
236
+ try {
237
+ verifyRes = await fetchWhoami(token, { baseUrl });
238
+ } catch (err) {
239
+ spinner.fail("Failed to reach juas.dev.");
240
+ logger.error(err.message);
241
+ process.exit(1);
242
+ }
243
+
244
+ if (!verifyRes.ok || !verifyRes.data?.authenticated) {
245
+ spinner.fail("Authentication failed.");
246
+ logger.error(verifyRes.data?.error || `HTTP ${verifyRes.status}: Invalid or revoked token.`);
247
+ process.exit(1);
248
+ }
249
+
250
+ const savedPath = await writeCredentials({
251
+ token,
252
+ baseUrl,
253
+ user: verifyRes.data.user,
254
+ subscription: verifyRes.data.subscription,
255
+ });
256
+
257
+ spinner.succeed("Logged in to juas.dev.");
258
+ logger.blank();
259
+ logger.divider();
260
+ const handle = verifyRes.data.user?.username
261
+ ? `@${verifyRes.data.user.username}`
262
+ : verifyRes.data.user?.name || verifyRes.data.user?.id;
263
+ logger.label("Account", handle);
264
+ logger.label(
265
+ "Plan",
266
+ `${verifyRes.data.subscription?.tier || "free"} (${verifyRes.data.subscription?.status || "active"})`
267
+ );
268
+ logger.label(
269
+ "Pro CLI Access",
270
+ verifyRes.data.subscription?.hasUnlimitedProAccess
271
+ ? pc.green("Unlocked")
272
+ : `Credits (${verifyRes.data.creditsAvailable ?? 0})`
273
+ );
274
+ logger.label("Token", maskToken(token));
275
+ logger.label("Saved", savedPath);
276
+ logger.divider();
277
+ logger.blank();
278
+ logger.info(`Run ${pc.bold("npx juas.dev whoami")} anytime to inspect access status.`);
279
+ logger.blank();
280
+ }
281
+
282
+ export async function cmdLogin(options = {}) {
283
+ logger.banner();
284
+
285
+ let baseUrl;
286
+ try {
287
+ baseUrl = getCliBaseUrl(options.webUrl);
288
+ } catch (err) {
289
+ logger.error(err.message);
290
+ process.exit(1);
291
+ }
292
+
293
+ // 1. Direct token login (`npx juas.dev login --token juas_user_...`)
294
+ if (typeof options.token === "string" && options.token.trim()) {
295
+ await verifyAndPersistToken(options.token.trim(), baseUrl);
296
+ return;
297
+ }
298
+
299
+ // 2. Headless / no-browser manual paste workflow
300
+ if (options.browser === false) {
301
+ const manualUrl = `${baseUrl}/cli/auth`;
302
+ logger.info("Manual CLI login (--no-browser):");
303
+ logger.label("1. Open URL", pc.underline(manualUrl));
304
+ logger.info("2. Sign in and copy your CLI token.");
305
+ logger.blank();
306
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
307
+ const pasted = await rl.question(" Paste your Juas API key (juas_user_...): ");
308
+ rl.close();
309
+ if (!pasted.trim()) {
310
+ logger.error("No token entered.");
311
+ process.exit(1);
312
+ }
313
+ await verifyAndPersistToken(pasted.trim(), baseUrl);
314
+ return;
315
+ }
316
+
317
+ // 3. Interactive Browser OAuth Loopback Flow
318
+ const state = crypto.randomBytes(24).toString("hex");
319
+ let listener;
320
+ try {
321
+ listener = await startLoopbackCallbackServer(state, baseUrl);
322
+ } catch (err) {
323
+ logger.error(`Could not start local login server: ${err.message}`);
324
+ logger.info(`Fallback: run ${pc.bold("npx juas.dev login --token <your-api-key>")}`);
325
+ process.exit(1);
326
+ }
327
+
328
+ const authUrl = `${baseUrl}/cli/auth?port=${listener.port}&state=${state}`;
329
+ logger.info("Opening browser to authorize your Juas CLI session…");
330
+ logger.label("URL", pc.underline(authUrl));
331
+ logger.info(pc.dim(`Waiting for approval on 127.0.0.1:${listener.port} (timeout: 3m)`));
332
+ logger.blank();
333
+
334
+ const opened = openExternalUrl(authUrl);
335
+ if (!opened) {
336
+ logger.warn("Could not open browser automatically. Open the URL above manually.");
337
+ }
338
+
339
+ let receivedToken;
340
+ try {
341
+ receivedToken = await listener.waitForToken();
342
+ } catch (err) {
343
+ listener.close();
344
+ logger.error(err.message);
345
+ logger.info(`Tip: get a token from ${pc.underline(baseUrl + "/cli/auth")} and run:`);
346
+ logger.info(` ${pc.bold("npx juas.dev login --token <key>")}`);
347
+ process.exit(1);
348
+ }
349
+
350
+ await verifyAndPersistToken(receivedToken, baseUrl);
351
+ }
@@ -0,0 +1,25 @@
1
+ // ============================================================
2
+ // commands/logout.js — `juas logout`
3
+ // ============================================================
4
+ import pc from "picocolors";
5
+ import { clearCredentials, getCredentialsPath } from "../lib/credentials.js";
6
+ import { logger } from "../lib/logger.js";
7
+
8
+ export async function cmdLogout() {
9
+ logger.banner();
10
+
11
+ const removed = await clearCredentials();
12
+ if (removed) {
13
+ logger.success(`Cleared CLI credentials from ${pc.dim(getCredentialsPath())}`);
14
+ } else {
15
+ logger.info("No saved CLI credentials found.");
16
+ }
17
+
18
+ if (process.env.JUAS_API_TOKEN) {
19
+ logger.warn(
20
+ `Note: ${pc.bold("JUAS_API_TOKEN")} is still set in your shell environment. Unset it to fully deauthorize this shell.`
21
+ );
22
+ }
23
+
24
+ logger.blank();
25
+ }
@@ -0,0 +1,52 @@
1
+ // ============================================================
2
+ // commands/search.js
3
+ // npx juas.dev search "glass button"
4
+ // ============================================================
5
+ import ora from "ora";
6
+ import pc from "picocolors";
7
+
8
+ import { logger } from "../lib/logger.js";
9
+ import { searchComponents } from "../lib/supabase.js";
10
+
11
+ export async function cmdSearch(query, options) {
12
+ logger.banner();
13
+ logger.info(`Searching for: ${pc.bold(query)}`);
14
+ logger.blank();
15
+
16
+ const spinner = ora("Searching juas.dev…").start();
17
+
18
+ let results;
19
+ try {
20
+ results = await searchComponents(query);
21
+ spinner.succeed(`${results.length} result${results.length !== 1 ? "s" : ""}`);
22
+ } catch (err) {
23
+ spinner.fail("Search failed.");
24
+ logger.error(err.message);
25
+ process.exit(1);
26
+ }
27
+
28
+ if (!results.length) {
29
+ logger.warn(`No components matched "${query}".`);
30
+ logger.info(`Try browsing all: ${pc.bold("npx juas.dev list")}`);
31
+ return;
32
+ }
33
+
34
+ if (options.json) {
35
+ console.log(JSON.stringify(results, null, 2));
36
+ return;
37
+ }
38
+
39
+ logger.blank();
40
+ for (const item of results) {
41
+ const tags = item.tags?.slice(0, 4).map((t) => pc.dim(`#${t}`)).join(" ") ?? "";
42
+ console.log(` ${pc.green(pc.bold(item.slug.padEnd(36)))} ${pc.dim(item.category ?? "")}`);
43
+ if (item.description) {
44
+ console.log(` ${pc.dim(item.description.slice(0, 72))}`);
45
+ }
46
+ if (tags) console.log(` ${tags}`);
47
+ console.log();
48
+ }
49
+
50
+ logger.info(`Install: ${pc.bold("npx juas.dev add <slug>")}`);
51
+ logger.blank();
52
+ }
@@ -0,0 +1,119 @@
1
+ // ============================================================
2
+ // commands/whoami.js — `juas whoami [--check <slug>]`
3
+ // ============================================================
4
+ import ora from "ora";
5
+ import pc from "picocolors";
6
+ import { fetchWhoami } from "../lib/authApi.js";
7
+ import { getActiveToken, getCliBaseUrl } from "../lib/credentials.js";
8
+ import { logger } from "../lib/logger.js";
9
+
10
+ export async function cmdWhoami(options = {}) {
11
+ const isJson = Boolean(options.json);
12
+ const { token, source, baseUrl: savedBaseUrl } = getActiveToken(options.token);
13
+ const baseUrl = getCliBaseUrl(options.webUrl || savedBaseUrl);
14
+
15
+ if (!token) {
16
+ if (isJson) {
17
+ console.log(JSON.stringify({ authenticated: false, error: "Not logged in" }, null, 2));
18
+ } else {
19
+ logger.banner();
20
+ logger.warn("Not logged in to juas.dev.");
21
+ logger.info(`Authenticate now: ${pc.bold("npx juas.dev login")}`);
22
+ logger.blank();
23
+ }
24
+ process.exit(1);
25
+ }
26
+
27
+ const spinner = isJson ? null : ora("Checking access status with juas.dev…").start();
28
+
29
+ let res;
30
+ try {
31
+ res = await fetchWhoami(token, { slug: options.check, baseUrl });
32
+ } catch (err) {
33
+ if (spinner) spinner.fail("Network error.");
34
+ if (isJson) {
35
+ console.log(JSON.stringify({ authenticated: false, error: err.message }, null, 2));
36
+ } else {
37
+ logger.error(err.message);
38
+ }
39
+ process.exit(1);
40
+ }
41
+
42
+ if (!res.ok || !res.data?.authenticated) {
43
+ if (spinner) spinner.fail("Session is invalid or revoked.");
44
+ const errorMsg = res.data?.error || `HTTP ${res.status}: Unauthorized`;
45
+ if (isJson) {
46
+ console.log(JSON.stringify({ authenticated: false, error: errorMsg }, null, 2));
47
+ } else {
48
+ logger.error(errorMsg);
49
+ logger.info(`Run ${pc.bold("npx juas.dev login")} to re-authenticate.`);
50
+ logger.blank();
51
+ }
52
+ process.exit(1);
53
+ }
54
+
55
+ const data = res.data;
56
+
57
+ if (isJson) {
58
+ console.log(JSON.stringify(data, null, 2));
59
+ if (options.check && !data.componentAccess?.canViewFullCode) {
60
+ process.exit(1);
61
+ }
62
+ return;
63
+ }
64
+
65
+ spinner.stop();
66
+ logger.banner();
67
+ logger.success(pc.bold("Authenticated with juas.dev"));
68
+ logger.divider();
69
+
70
+ const handle = data.user?.username
71
+ ? `@${data.user.username}`
72
+ : data.user?.name || data.user?.id;
73
+ logger.label("Account", handle);
74
+ logger.label(
75
+ "Auth Source",
76
+ `${data.auth?.type === "api_key" ? `API Key (${data.auth.scope})` : "Session JWT"} via ${source}`
77
+ );
78
+ logger.label(
79
+ "Plan",
80
+ `${data.subscription?.tier || "free"} (${data.subscription?.status || "active"})`
81
+ );
82
+ logger.label(
83
+ "Pro CLI Access",
84
+ data.subscription?.hasUnlimitedProAccess
85
+ ? pc.green("Unlocked (Pro / Lifetime)")
86
+ : data.subscription?.hasYearlyAccess
87
+ ? pc.green("Yearly Window Active")
88
+ : pc.yellow("Free / Credit-Gated")
89
+ );
90
+ logger.label(
91
+ "Credits",
92
+ data.subscription?.hasUnlimitedProAccess
93
+ ? "Unlimited"
94
+ : String(data.creditsAvailable ?? 0)
95
+ );
96
+
97
+ if (data.componentAccess) {
98
+ logger.divider();
99
+ const access = data.componentAccess;
100
+ if (!access.found) {
101
+ logger.error(`Component "${access.slug}" not found.`);
102
+ logger.blank();
103
+ process.exit(1);
104
+ }
105
+ const badge = access.canViewFullCode
106
+ ? pc.green(`UNLOCKED (${access.accessType})`)
107
+ : pc.red("LOCKED");
108
+ logger.label(`Component (${access.slug})`, badge);
109
+ if (!access.canViewFullCode) {
110
+ logger.info(access.reason || "Requires Pro plan or 1 credit.");
111
+ logger.info(`Unlock on web: ${pc.underline("https://juas.dev/component/" + access.slug)}`);
112
+ logger.blank();
113
+ process.exit(1);
114
+ }
115
+ }
116
+
117
+ logger.divider();
118
+ logger.blank();
119
+ }
@@ -0,0 +1,67 @@
1
+ // ============================================================
2
+ // authApi.js — CLI HTTP client for /api/cli/whoami & /component
3
+ // ============================================================
4
+ import { getCliBaseUrl } from "./credentials.js";
5
+
6
+ /**
7
+ * Queries `/api/cli/whoami` to verify token validity, plan tier, credits,
8
+ * and optional component entitlement (`slug`).
9
+ */
10
+ export async function fetchWhoami(token, options = {}) {
11
+ const baseUrl = getCliBaseUrl(options.baseUrl);
12
+ const url = new URL("/api/cli/whoami", baseUrl);
13
+ if (options.slug) {
14
+ url.searchParams.set("slug", String(options.slug).trim());
15
+ }
16
+
17
+ const headers = {
18
+ Accept: "application/json",
19
+ };
20
+ if (token) {
21
+ headers.Authorization = `Bearer ${token}`;
22
+ }
23
+
24
+ const res = await fetch(url.toString(), { method: "GET", headers });
25
+ let data = null;
26
+ try {
27
+ data = await res.json();
28
+ } catch {
29
+ data = null;
30
+ }
31
+
32
+ return {
33
+ ok: res.ok,
34
+ status: res.status,
35
+ data,
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Fetches component source files or lock metadata from `/api/cli/component`.
41
+ */
42
+ export async function fetchCliComponent(slug, options = {}) {
43
+ const baseUrl = getCliBaseUrl(options.baseUrl);
44
+ const url = new URL("/api/cli/component", baseUrl);
45
+ url.searchParams.set("slug", String(slug).trim());
46
+
47
+ const headers = {
48
+ Accept: "application/json",
49
+ };
50
+ if (options.token) {
51
+ headers.Authorization = `Bearer ${options.token}`;
52
+ }
53
+
54
+ const res = await fetch(url.toString(), { method: "GET", headers });
55
+ let data = null;
56
+ try {
57
+ data = await res.json();
58
+ } catch {
59
+ data = null;
60
+ }
61
+
62
+ return {
63
+ ok: res.ok,
64
+ status: res.status,
65
+ data,
66
+ };
67
+ }
@@ -0,0 +1,48 @@
1
+ // ============================================================
2
+ // config.js — read/write juas.config.json in the user's project
3
+ // ============================================================
4
+ import fs from "fs-extra";
5
+ import path from "path";
6
+
7
+ const CONFIG_FILE = "juas.config.json";
8
+
9
+ /** Default config shape */
10
+ const DEFAULT_CONFIG = {
11
+ outputDir: "src/components/juas",
12
+ typescript: true,
13
+ framework: "react",
14
+ };
15
+
16
+ /**
17
+ * Find the nearest juas.config.json walking up from cwd.
18
+ * Returns the absolute path or null if not found.
19
+ */
20
+ export function findConfig(cwd = process.cwd()) {
21
+ let dir = cwd;
22
+ while (true) {
23
+ const candidate = path.join(dir, CONFIG_FILE);
24
+ if (fs.existsSync(candidate)) return candidate;
25
+ const parent = path.dirname(dir);
26
+ if (parent === dir) return null; // reached filesystem root
27
+ dir = parent;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Load config. Falls back to defaults if no file found.
33
+ */
34
+ export function loadConfig(cwd = process.cwd()) {
35
+ const cfgPath = findConfig(cwd);
36
+ if (!cfgPath) return { ...DEFAULT_CONFIG, _path: null };
37
+ const raw = fs.readJsonSync(cfgPath);
38
+ return { ...DEFAULT_CONFIG, ...raw, _path: cfgPath };
39
+ }
40
+
41
+ /**
42
+ * Write a new config file.
43
+ */
44
+ export async function writeConfig(dir, data) {
45
+ const cfgPath = path.join(dir, CONFIG_FILE);
46
+ await fs.outputJson(cfgPath, { ...DEFAULT_CONFIG, ...data }, { spaces: 2 });
47
+ return cfgPath;
48
+ }