@coffre/cli 0.1.13 → 0.1.15

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,71 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/init.ts
5
+ const KINDS = ["workers", "node"];
6
+ /** Where a template lives: in the package when published, else in the repository. */
7
+ function templateDir(kind) {
8
+ const packed = fileURLToPath(new URL(`./templates/${kind}/`, import.meta.url));
9
+ if (existsSync(packed)) return packed;
10
+ return fileURLToPath(new URL(`../../../examples/${kind}/`, import.meta.url));
11
+ }
12
+ /**
13
+ * A template's files, relative and sorted: everything but what its own
14
+ * `.gitignore` names, such as installed packages, local state and secrets.
15
+ * Patterns are file or directory names, `*` standing for any run of
16
+ * characters.
17
+ */
18
+ function templateFiles(dir) {
19
+ const ignoreFile = [join(dir, ".gitignore"), join(dir, "gitignore")].find((path) => existsSync(path));
20
+ const ignored = (ignoreFile === void 0 ? "" : readFileSync(ignoreFile, "utf8")).split("\n").map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("#")).map((glob) => new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`));
21
+ const files = [];
22
+ const walk = (relative) => {
23
+ for (const entry of readdirSync(join(dir, relative), { withFileTypes: true })) {
24
+ if (ignored.some((pattern) => pattern.test(entry.name))) continue;
25
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
26
+ if (entry.isDirectory()) walk(path);
27
+ else files.push(path);
28
+ }
29
+ };
30
+ walk("");
31
+ return files.sort();
32
+ }
33
+ /** The name a template file has in a project. */
34
+ function projectPath(templatePath) {
35
+ return templatePath === "gitignore" ? ".gitignore" : templatePath;
36
+ }
37
+ /** A package name from a directory's, e.g. `Acme Secrets` → `acme-secrets`. */
38
+ function packageName(dir) {
39
+ const name = basename(dir).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+|-+$/g, "");
40
+ return name === "" ? "coffre" : name;
41
+ }
42
+ /** The template's package.json, for this project and this version of coffre. */
43
+ function manifest(source, name, version) {
44
+ const pkg = JSON.parse(source);
45
+ pkg.name = name;
46
+ for (const field of ["dependencies", "devDependencies"]) {
47
+ const deps = pkg[field];
48
+ for (const dep of Object.keys(deps ?? {})) if (dep.startsWith("@coffre/")) deps[dep] = version;
49
+ }
50
+ return `${JSON.stringify(pkg, null, 2)}\n`;
51
+ }
52
+ /** Whether a directory holds nothing yet, or nothing but `.git`: a repository made first, then cloned. */
53
+ function isEmpty(dir) {
54
+ return !existsSync(dir) || readdirSync(dir).every((entry) => entry === ".git");
55
+ }
56
+ /** Write a new deployment into `target`, which must be empty (`isEmpty`) or absent. Returns the files written. */
57
+ function init(kind, target, version) {
58
+ if (!isEmpty(target)) throw new Error(`${target} is not empty; give \`coffre init\` a new directory`);
59
+ const source = templateDir(kind);
60
+ const written = [];
61
+ for (const file of templateFiles(source)) {
62
+ const path = projectPath(file);
63
+ const content = readFileSync(join(source, file), "utf8");
64
+ mkdirSync(dirname(join(target, path)), { recursive: true });
65
+ writeFileSync(join(target, path), path === "package.json" ? manifest(content, packageName(target), version) : content);
66
+ written.push(path);
67
+ }
68
+ return written;
69
+ }
70
+ //#endregion
71
+ export { templateDir as i, init as n, isEmpty as r, KINDS as t };
@@ -1,78 +1,7 @@
1
+ import { a as openTerminal, c as release, d as style, h as wrap, l as row, m as width, o as paragraph, p as truncate, s as readKeys } from "./tty-BDa14JX2.js";
1
2
  import { parseArgs } from "node:util";
2
3
  import { spawn } from "node:child_process";
3
- import { existsSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
- import { basename, dirname, join } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
4
  import { randomBytes } from "node:crypto";
7
- import { emitKeypressEvents } from "node:readline";
8
- import tty from "node:tty";
9
- //#region src/init.ts
10
- const KINDS = ["workers", "node"];
11
- /** Where a template lives: in the package when published, else in the repository. */
12
- function templateDir(kind) {
13
- const packed = fileURLToPath(new URL(`./templates/${kind}/`, import.meta.url));
14
- if (existsSync(packed)) return packed;
15
- return fileURLToPath(new URL(`../../../examples/${kind}/`, import.meta.url));
16
- }
17
- /**
18
- * A template's files, relative and sorted: everything but what its own
19
- * `.gitignore` names, such as installed packages, local state and secrets.
20
- * Patterns are file or directory names, `*` standing for any run of
21
- * characters.
22
- */
23
- function templateFiles(dir) {
24
- const ignoreFile = [join(dir, ".gitignore"), join(dir, "gitignore")].find((path) => existsSync(path));
25
- const ignored = (ignoreFile === void 0 ? "" : readFileSync(ignoreFile, "utf8")).split("\n").map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("#")).map((glob) => new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`));
26
- const files = [];
27
- const walk = (relative) => {
28
- for (const entry of readdirSync(join(dir, relative), { withFileTypes: true })) {
29
- if (ignored.some((pattern) => pattern.test(entry.name))) continue;
30
- const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
31
- if (entry.isDirectory()) walk(path);
32
- else files.push(path);
33
- }
34
- };
35
- walk("");
36
- return files.sort();
37
- }
38
- /** The name a template file has in a project. */
39
- function projectPath(templatePath) {
40
- return templatePath === "gitignore" ? ".gitignore" : templatePath;
41
- }
42
- /** A package name from a directory's, e.g. `Acme Secrets` → `acme-secrets`. */
43
- function packageName(dir) {
44
- const name = basename(dir).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-._]+|-+$/g, "");
45
- return name === "" ? "coffre" : name;
46
- }
47
- /** The template's package.json, for this project and this version of coffre. */
48
- function manifest(source, name, version) {
49
- const pkg = JSON.parse(source);
50
- pkg.name = name;
51
- for (const field of ["dependencies", "devDependencies"]) {
52
- const deps = pkg[field];
53
- for (const dep of Object.keys(deps ?? {})) if (dep.startsWith("@coffre/")) deps[dep] = version;
54
- }
55
- return `${JSON.stringify(pkg, null, 2)}\n`;
56
- }
57
- /** Whether a directory holds nothing yet, or nothing but `.git`: a repository made first, then cloned. */
58
- function isEmpty(dir) {
59
- return !existsSync(dir) || readdirSync(dir).every((entry) => entry === ".git");
60
- }
61
- /** Write a new deployment into `target`, which must be empty (`isEmpty`) or absent. Returns the files written. */
62
- function init(kind, target, version) {
63
- if (!isEmpty(target)) throw new Error(`${target} is not empty; give \`coffre init\` a new directory`);
64
- const source = templateDir(kind);
65
- const written = [];
66
- for (const file of templateFiles(source)) {
67
- const path = projectPath(file);
68
- const content = readFileSync(join(source, file), "utf8");
69
- mkdirSync(dirname(join(target, path)), { recursive: true });
70
- writeFileSync(join(target, path), path === "package.json" ? manifest(content, packageName(target), version) : content);
71
- written.push(path);
72
- }
73
- return written;
74
- }
75
- //#endregion
76
5
  //#region src/clipboard.ts
77
6
  const CLEAR_AFTER_MS = 3e4;
78
7
  /** The system's clipboard tool, by platform and display server; null for none known. */
@@ -200,285 +129,6 @@ function read([command, ...args]) {
200
129
  });
201
130
  }
202
131
  //#endregion
203
- //#region src/tty.ts
204
- const plain = (text) => text;
205
- /**
206
- * The web UI's accent, green and red, at the depth the terminal takes:
207
- * 24-bit, 256 colours or the 16 named ones. NO_COLOR (and FORCE_COLOR) are
208
- * the stream's own `hasColors`; bold and dim stay, being no colour.
209
- */
210
- function style(stream) {
211
- if (stream.isTTY !== true) return {
212
- ansi: false,
213
- bold: plain,
214
- dim: plain,
215
- accent: plain,
216
- green: plain,
217
- red: plain
218
- };
219
- const terminal = stream;
220
- const depth = typeof terminal.hasColors === "function" && terminal.hasColors() ? terminal.getColorDepth() : 1;
221
- const sgr = (open, close) => (text) => `\x1b[${open}m${text}\x1b[${close}m`;
222
- const colour = (rgb, index256, index16) => depth >= 24 ? sgr(`38;2;${rgb.join(";")}`, "39") : depth >= 8 ? sgr(`38;5;${index256}`, "39") : depth >= 4 ? sgr(String(index16), "39") : plain;
223
- return {
224
- ansi: true,
225
- bold: sgr("1", "22"),
226
- dim: sgr("2", "22"),
227
- accent: colour([
228
- 91,
229
- 141,
230
- 239
231
- ], 69, 94),
232
- green: colour([
233
- 63,
234
- 174,
235
- 111
236
- ], 71, 32),
237
- red: colour([
238
- 229,
239
- 83,
240
- 75
241
- ], 167, 31)
242
- };
243
- }
244
- const ESCAPE = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07/g;
245
- /** Columns `text` takes on screen: its characters, less its escape codes. */
246
- function width(text) {
247
- return [...text.replace(ESCAPE, "")].length;
248
- }
249
- /** `text` cut to `columns` on screen, escape codes kept, an ellipsis where it was cut. */
250
- function truncate(text, columns) {
251
- if (width(text) <= columns) return text;
252
- let out = "";
253
- let used = 0;
254
- for (let i = 0; i < text.length;) {
255
- ESCAPE.lastIndex = i;
256
- const code = text[i] === "\x1B" ? ESCAPE.exec(text) : null;
257
- if (code !== null && code.index === i) {
258
- out += code[0];
259
- i += code[0].length;
260
- continue;
261
- }
262
- const char = String.fromCodePoint(text.codePointAt(i));
263
- if (used === columns - 1) return `${out}…${text.includes("\x1B") ? "\x1B[0m" : ""}`;
264
- out += char;
265
- used += 1;
266
- i += char.length;
267
- }
268
- return out;
269
- }
270
- /** Plain `text` in lines of at most `columns`, broken at spaces, or anywhere in a word longer than a line. */
271
- function wrap(text, columns) {
272
- const lines = [];
273
- let line = "";
274
- for (const word of text.split(" ")) {
275
- let rest = word;
276
- while (width(rest) > columns) {
277
- if (line !== "") lines.push(line);
278
- line = "";
279
- lines.push([...rest].slice(0, columns).join(""));
280
- rest = [...rest].slice(columns).join("");
281
- }
282
- if (line === "") line = rest;
283
- else if (width(line) + 1 + width(rest) <= columns) line += ` ${rest}`;
284
- else {
285
- lines.push(line);
286
- line = rest;
287
- }
288
- }
289
- return [...lines, line];
290
- }
291
- /** `text` wrapped to the stream's width, each line indented by `indent` spaces. */
292
- function paragraph(out, text, indent = 2) {
293
- const pad = " ".repeat(indent);
294
- return wrap(text, Math.max(20, (out.columns || 80) - indent - 1)).map((line) => `${pad}${line}`).join("\n");
295
- }
296
- /** "a, b or c". */
297
- function listed(items, last) {
298
- return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} ${last} ${items.at(-1)}`;
299
- }
300
- /** A labelled row: `label` in a column of `column`, `text` wrapped beside it with a hanging indent. */
301
- function row(out, s, label, text, indent = 4, column = 10) {
302
- const lines = wrap(text, Math.max(20, (out.columns || 80) - indent - column - 1));
303
- const pad = " ".repeat(indent);
304
- return lines.map((line, i) => `${pad}${i === 0 ? s.dim(label.padEnd(column)) : " ".repeat(column)}${line}`).join("\n");
305
- }
306
- /**
307
- * The keyboard: stdin when it is a terminal, otherwise the terminal itself,
308
- * as `less` reads it when its input is piped. Null without one.
309
- */
310
- function keyboard() {
311
- if (process.stdin.isTTY) return process.stdin;
312
- try {
313
- return new tty.ReadStream(openSync("/dev/tty", "r"));
314
- } catch {
315
- return null;
316
- }
317
- }
318
- /** Where a screen is drawn and read from: stdout, and the keyboard. Null unless both are a terminal. */
319
- function openTerminal() {
320
- if (!process.stdout.isTTY) return null;
321
- const keys = keyboard();
322
- return keys === null ? null : {
323
- keys,
324
- out: process.stdout
325
- };
326
- }
327
- /** Release a keyboard `keyboard()` opened: stdin stays, /dev/tty closes. */
328
- function release(keys) {
329
- keys.setRawMode?.(false);
330
- keys.pause();
331
- if (keys !== process.stdin) keys.destroy?.();
332
- }
333
- /**
334
- * Every key pressed, in raw mode, until `until` returns true, or `signal`
335
- * aborts the reading. Raw mode is on when this returns: a prompt shown after
336
- * it gets every key, none echoed or edited by the terminal first.
337
- */
338
- function readKeys(keys, until, signal) {
339
- emitKeypressEvents(keys);
340
- keys.setRawMode?.(true);
341
- keys.resume();
342
- return new Promise((resolve, reject) => {
343
- let busy = Promise.resolve();
344
- const stop = () => {
345
- keys.off("keypress", onKey);
346
- signal?.removeEventListener("abort", stop);
347
- keys.setRawMode?.(false);
348
- keys.pause();
349
- resolve();
350
- };
351
- const onKey = (sequence, key) => {
352
- busy = busy.then(async () => {
353
- if (await until(key ?? { sequence }, sequence ?? key?.sequence ?? "")) stop();
354
- }).catch(reject);
355
- };
356
- keys.on("keypress", onKey);
357
- if (signal?.aborted) stop();
358
- else signal?.addEventListener("abort", stop);
359
- });
360
- }
361
- /** What a typed key does to a line: its new text, or `submit`, or `cancel`. */
362
- function edit(text, key, sequence) {
363
- if (key.ctrl && key.name === "c") return "cancel";
364
- if (key.name === "return" || key.name === "enter") return "submit";
365
- if (key.name === "backspace") return text.slice(0, -1);
366
- if (key.ctrl && key.name === "u") return "";
367
- if (!key.ctrl && !key.meta && sequence.length > 0 && !sequence.startsWith("\x1B") && sequence >= " ") return text + sequence;
368
- return text;
369
- }
370
- /**
371
- * A question answered by typing, shown as typed, `initial` to start from;
372
- * `note`, dim under it while it is asked; `check` says why an answer will
373
- * not do, under it. Once given, the question becomes one line: what was
374
- * asked, and the answer. Ctrl-C cancels.
375
- */
376
- async function textLine(keys, out, s, question, hint, options = {}) {
377
- const columns = Math.max(20, (out.columns || 80) - 1);
378
- let typed = options.initial ?? "";
379
- let error = null;
380
- const draw = () => {
381
- const below = [...error === null ? [] : [s.red(error)], ...options.note === void 0 ? [] : wrap(options.note, columns - 4).map(s.dim)].map((line) => `\n${truncate(` ${line}`, columns)}`);
382
- out.write(`\r\x1b[J${below.join("")}${below.length > 0 ? `\x1b[${below.length}A` : ""}\r${truncate(` ${s.accent("›")} ${typed}`, columns)}`);
383
- };
384
- let cancelled = false;
385
- const answered = readKeys(keys, async (key, sequence) => {
386
- const next = edit(typed, key, sequence);
387
- if (next === "cancel") cancelled = true;
388
- else if (next === "submit") {
389
- if (typed.trim() === "") return false;
390
- error = await options.check?.(typed.trim()) ?? null;
391
- if (error === null) return true;
392
- } else {
393
- typed = next;
394
- error = null;
395
- }
396
- if (cancelled) return true;
397
- draw();
398
- return false;
399
- });
400
- out.write(`${truncate(` ${s.accent("?")} ${s.bold(question)} ${s.dim(hint)}`, columns)}\n`);
401
- draw();
402
- await answered;
403
- out.write("\r\x1B[J\x1B[1A\x1B[2K");
404
- if (cancelled) throw new Cancelled();
405
- out.write(`${truncate(` ${s.green("✓")} ${s.dim(question)} ${typed.trim()}`, columns)}\n`);
406
- return typed.trim();
407
- }
408
- /** One of `options`, chosen with the arrows and Enter; then one line, as `textLine` leaves. Ctrl-C cancels. */
409
- async function select(keys, out, s, question, options) {
410
- const columns = Math.max(20, (out.columns || 80) - 1);
411
- let at = 0;
412
- let drawn = 0;
413
- const draw = () => {
414
- const lines = [` ${s.accent("?")} ${s.bold(question)} ${s.dim("↑↓ then Enter")}`, ...options.map((option, i) => i === at ? ` ${s.accent("›")} ${s.accent(option)}` : ` ${option}`)];
415
- out.write(`${drawn > 0 ? `\x1b[${drawn}F` : ""}${lines.map((line) => `${truncate(line, columns)}\x1b[K\n`).join("")}`);
416
- drawn = lines.length;
417
- };
418
- let cancelled = false;
419
- const chosen = readKeys(keys, (key) => {
420
- if (key.ctrl && key.name === "c") cancelled = true;
421
- else if (key.name === "return" || key.name === "enter") return true;
422
- else if (key.name === "up" || key.name === "k") at = (at - 1 + options.length) % options.length;
423
- else if (key.name === "down" || key.name === "j" || key.name === "tab") at = (at + 1) % options.length;
424
- if (cancelled) return true;
425
- draw();
426
- return false;
427
- });
428
- draw();
429
- await chosen;
430
- out.write(`\x1b[${drawn}F\x1b[J`);
431
- if (cancelled) throw new Cancelled();
432
- out.write(`${truncate(` ${s.green("✓")} ${s.dim(question)} ${options[at]}`, columns)}\n`);
433
- return at;
434
- }
435
- var Cancelled = class extends Error {
436
- constructor() {
437
- super("cancelled");
438
- }
439
- };
440
- /**
441
- * A line typed without echo: a bullet for each character, so that a paste
442
- * shows it arrived. The question, its hint and the bullets go once it is
443
- * given. Ctrl-C cancels.
444
- */
445
- async function hiddenLine(keys, out, s, question, hint) {
446
- const columns = Math.max(20, (out.columns || 80) - 1);
447
- let typed = "";
448
- const draw = () => {
449
- const count = typed.length > 0 ? s.dim(` ${typed.length} characters`) : "";
450
- out.write(`\r\x1b[2K${truncate(` ${s.accent("›")} ${"•".repeat(typed.length)}`, columns - width(count))}${count}`);
451
- };
452
- let cancelled = false;
453
- const typedIn = readKeys(keys, (key, sequence) => {
454
- const next = edit(typed, key, sequence);
455
- if (next === "cancel") cancelled = true;
456
- else if (next === "submit") return true;
457
- else typed = next;
458
- if (cancelled) return true;
459
- draw();
460
- return false;
461
- });
462
- out.write(`${truncate(` ${s.accent("?")} ${s.bold(question)}`, columns)}\n${truncate(` ${s.dim(hint)}`, columns)}\n`);
463
- draw();
464
- await typedIn;
465
- out.write("\r\x1B[2K\x1B[1A\x1B[2K\x1B[1A\x1B[2K");
466
- if (cancelled) throw new Cancelled();
467
- return typed.trim();
468
- }
469
- /** One key: y for yes, anything else for no. Ctrl-C cancels. */
470
- async function yes(keys) {
471
- let answer = false;
472
- let cancelled = false;
473
- await readKeys(keys, (key) => {
474
- if (key.ctrl && key.name === "c") cancelled = true;
475
- answer = key.name === "y";
476
- return true;
477
- });
478
- if (cancelled) throw new Cancelled();
479
- return answer;
480
- }
481
- //#endregion
482
132
  //#region src/secrets.ts
483
133
  function initialState() {
484
134
  return {
@@ -878,4 +528,4 @@ async function keys(args) {
878
528
  ].join("\n"));
879
529
  }
880
530
  //#endregion
881
- export { yes as C, isEmpty as E, wrap as S, init as T, select as _, keys as a, truncate as b, Cancelled as c, listed as d, openTerminal as f, row as g, release as h, keyValues as i, edit as l, readKeys as m, jsonWarning as n, needsTerminal as o, paragraph as p, keyGuide as r, showSecrets as s, generateKeys as t, hiddenLine as u, style as v, KINDS as w, width as x, textLine as y };
531
+ export { keys as a, keyValues as i, jsonWarning as n, needsTerminal as o, keyGuide as r, showSecrets as s, generateKeys as t };