filecafe 0.3.0 → 0.3.2

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
@@ -99,6 +99,8 @@ A saved token is only ever sent to the site it was issued for. To work against a
99
99
 
100
100
  Set `FILECAFE_DEBUG=1` to print stack traces for unexpected errors.
101
101
 
102
+ Output is only colored in a terminal, never when piped. Set `NO_COLOR=1` to turn colors off, or `FORCE_COLOR=1` to keep them when piping.
103
+
102
104
  ## Using file.cafe with AI agents
103
105
 
104
106
  Paste this into your project's `CLAUDE.md`, `AGENTS.md`, or Cursor rules:
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-D6lecimA.js";
2
+ import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-BDT0cPCo.js";
3
3
  import { Command } from "commander";
4
4
  import { homedir, hostname, tmpdir } from "node:os";
5
5
  import { realpath, stat } from "node:fs/promises";
@@ -8,6 +8,7 @@ import { execFile, spawn } from "node:child_process";
8
8
  import { createInterface } from "node:readline/promises";
9
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { fileURLToPath } from "node:url";
11
+ import { Chalk } from "chalk";
11
12
  import { openAsBlob } from "node:fs";
12
13
  // src/api.ts
13
14
  const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
@@ -290,6 +291,85 @@ async function requireSession(context, globals, onNotice) {
290
291
  }
291
292
  };
292
293
  }
294
+ // src/terminal.ts
295
+ /**
296
+ * Colors for text written to `stream`: on for a terminal, off when piped (scripts, CI logs,
297
+ * AI agents) or when NO_COLOR is set. FORCE_COLOR=1 or 0 overrides both.
298
+ */
299
+ function colorsFor(stream, env) {
300
+ return new Chalk({ level: useColor(stream, env) ? 1 : 0 });
301
+ }
302
+ function useColor(stream, env) {
303
+ if (env.FORCE_COLOR !== void 0) return env.FORCE_COLOR !== "0" && env.FORCE_COLOR !== "false";
304
+ return !env.NO_COLOR && Boolean(stream.isTTY) && env.TERM !== "dumb";
305
+ }
306
+ /**
307
+ * Whether `stream` is a terminal that understands OSC 8 hyperlinks (link text that opens a
308
+ * different URL when clicked). Terminals that don't would print the escape codes as garbage,
309
+ * so this only says yes for ones known to support them. FORCE_HYPERLINK=1 or 0 overrides it.
310
+ */
311
+ function supportsHyperlinks(stream, env) {
312
+ if (env.FORCE_HYPERLINK !== void 0) return env.FORCE_HYPERLINK !== "0";
313
+ if (!stream.isTTY || env.CI || env.TERM === "dumb") return false;
314
+ if (env.WT_SESSION || env.KITTY_WINDOW_ID || env.WEZTERM_PANE || env.KONSOLE_VERSION || env.DOMTERM) return true;
315
+ if (Number(env.VTE_VERSION) >= 5e3) return true;
316
+ return [
317
+ "iTerm.app",
318
+ "WezTerm",
319
+ "vscode",
320
+ "ghostty",
321
+ "Hyper",
322
+ "Tabby",
323
+ "rio"
324
+ ].includes(env.TERM_PROGRAM ?? "");
325
+ }
326
+ /** `text` that opens `url` when clicked, for terminals where supportsHyperlinks() is true. */
327
+ function hyperlink(text, url) {
328
+ return `\u001B]8;;${url}\u0007${text}\u001B]8;;\u0007`;
329
+ }
330
+ const FRAMES = [
331
+ "⠋",
332
+ "⠙",
333
+ "⠹",
334
+ "⠸",
335
+ "⠼",
336
+ "⠴",
337
+ "⠦",
338
+ "⠧",
339
+ "⠇",
340
+ "⠏"
341
+ ];
342
+ const ASCII_FRAMES = [
343
+ "-",
344
+ "\\",
345
+ "|",
346
+ "/"
347
+ ];
348
+ /**
349
+ * Show `text` with a spinner in front of it on a terminal, erased by stop(). Anywhere else
350
+ * (a log file, CI, an AI agent) the text is written once as a plain line instead.
351
+ */
352
+ function startSpinner(stream, text, env, platform) {
353
+ if (!stream.isTTY || env.CI || env.TERM === "dumb") {
354
+ stream.write(`${text}\n`);
355
+ return { stop: () => {} };
356
+ }
357
+ const frames = platform === "win32" && !env.WT_SESSION ? ASCII_FRAMES : FRAMES;
358
+ const color = colorsFor(stream, env);
359
+ let frame = 0;
360
+ const draw = () => stream.write(`\r${color.cyan(frames[frame++ % frames.length])} ${text}`);
361
+ draw();
362
+ const timer = setInterval(draw, 80);
363
+ timer.unref();
364
+ let stopped = false;
365
+ return { stop: () => {
366
+ if (!stopped) {
367
+ stopped = true;
368
+ clearInterval(timer);
369
+ stream.write("\r\x1B[2K");
370
+ }
371
+ } };
372
+ }
293
373
  // src/commands/login.ts
294
374
  async function readAll(input) {
295
375
  let text = "";
@@ -323,21 +403,27 @@ async function tokenFromBrowser(context, baseUrl) {
323
403
  const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
324
404
  const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
325
405
  if (!isStartedLogin(login)) throw new CliError(`Unexpected response from ${baseUrl} when starting the login. Check the --url option / FILECAFE_URL.`);
326
- context.stderr.write(`Your one-time code: ${login.user_code}\n\nOpening your browser to approve this login. Check that the code there matches.\nIf it does not open, visit ${login.verification_uri} and enter the code.\n\nWaiting for approval...
327
- `);
406
+ const color = colorsFor(context.stderr, context.env);
407
+ const link = color.cyan(supportsHyperlinks(context.stderr, context.env) ? hyperlink(login.verification_uri, login.verification_uri_complete) : login.verification_uri);
408
+ context.stderr.write(`Your one-time code: ${color.bold(login.user_code)}\n\nOpening your browser to approve this login. Check that the code there matches.\nIf it does not open, visit ${link} and enter the code.\n\n`);
328
409
  context.openBrowser(login.verification_uri_complete);
410
+ const spinner = startSpinner(context.stderr, "Waiting for approval...", context.env, context.platform);
329
411
  const intervalMs = Math.max(login.interval, 1) * 1e3;
330
412
  const deadline = context.now() + login.expires_in * 1e3;
331
- while (context.now() < deadline) {
332
- await context.sleep(Math.min(intervalMs, deadline - context.now()));
333
- const result = await pollLogin(client, login.device_code);
334
- switch (result.status) {
335
- case "approved": return result.token;
336
- case "denied": throw new CliError("Login was cancelled in the browser.");
337
- case "expired": throw new CliError(EXPIRED_MESSAGE);
413
+ try {
414
+ while (context.now() < deadline) {
415
+ await context.sleep(Math.min(intervalMs, deadline - context.now()));
416
+ const result = await pollLogin(client, login.device_code);
417
+ switch (result.status) {
418
+ case "approved": return result.token;
419
+ case "denied": throw new CliError("Login was cancelled in the browser.");
420
+ case "expired": throw new CliError(EXPIRED_MESSAGE);
421
+ }
338
422
  }
423
+ throw new CliError(EXPIRED_MESSAGE);
424
+ } finally {
425
+ spinner.stop();
339
426
  }
340
- throw new CliError(EXPIRED_MESSAGE);
341
427
  }
342
428
  async function loginCommand(options, globals, context) {
343
429
  if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
@@ -365,24 +451,30 @@ async function loginCommand(options, globals, context) {
365
451
  url: baseUrl,
366
452
  token
367
453
  });
368
- context.stdout.write(`Logged in as ${me.name} (${me.email})\n`);
369
- context.stderr.write(`Saved credentials for ${baseUrl} to ${configPath(context)}\n`);
370
- if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n");
454
+ const out = colorsFor(context.stdout, context.env);
455
+ const err = colorsFor(context.stderr, context.env);
456
+ context.stdout.write(`${out.green("Logged in")} as ${out.bold(me.name)} (${me.email})\n`);
457
+ context.stderr.write(`${err.gray(`Saved credentials for ${baseUrl} to ${configPath(context)}`)}\n`);
458
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n`);
459
+ const next = err.level > 0 ? err.cyan("filecafe upload <file>") : "\"filecafe upload <file>\"";
460
+ context.stderr.write(`\nRun ${next} to share a file.\n`);
371
461
  return 0;
372
462
  }
373
463
  // src/commands/logout.ts
374
464
  async function logoutCommand(context) {
375
465
  const saved = await readConfig(context).catch(() => null);
466
+ const out = colorsFor(context.stdout, context.env);
467
+ const err = colorsFor(context.stderr, context.env);
376
468
  if (saved) try {
377
469
  await clientFor(context, saved.url, saved.token).request("DELETE", "/api/v1/token", void 0, { idempotent: true });
378
470
  } catch (error) {
379
- if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`Could not revoke the token on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
471
+ if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`${err.yellow("Could not revoke the token")} on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
380
472
  }
381
473
  if (await deleteConfig(context)) {
382
- context.stdout.write(saved ? `Logged out of ${saved.url}.\n` : "Logged out.\n");
383
- context.stderr.write(`Removed ${configPath(context)}\n`);
474
+ context.stdout.write(saved ? `${out.green("Logged out")} of ${saved.url}.\n` : `${out.green("Logged out")}.\n`);
475
+ context.stderr.write(`${err.gray(`Removed ${configPath(context)}`)}\n`);
384
476
  } else context.stdout.write("Not logged in; nothing to do.\n");
385
- if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n");
477
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n`);
386
478
  return 0;
387
479
  }
388
480
  // src/mime.ts
@@ -755,7 +847,9 @@ function createProgress(context, enabled) {
755
847
  async function uploadCommand(files, options, globals, context) {
756
848
  if (options.collection !== void 0 && !UUID_PATTERN.test(options.collection)) throw new CliError(`Invalid --collection "${options.collection}". Expected a collection UUID.`);
757
849
  if (files.length === 0) throw new CliError("No files given. Usage: filecafe upload <files...>");
758
- const progress = createProgress(context, Boolean(context.stderr.isTTY) && !options.json && !options.quiet);
850
+ const showProgress = Boolean(context.stderr.isTTY) && !options.json && !options.quiet;
851
+ const err = colorsFor(context.stderr, context.env);
852
+ const progress = createProgress(context, showProgress);
759
853
  const notice = (message) => {
760
854
  if (!options.quiet) {
761
855
  progress.clear();
@@ -782,7 +876,7 @@ async function uploadCommand(files, options, globals, context) {
782
876
  };
783
877
  else {
784
878
  const filename = uploadFilename(file);
785
- progress.update(`Uploading ${filename} (${formatBytes(size)})...`);
879
+ progress.update(`Uploading ${err.bold(filename)} (${formatBytes(size)})...`);
786
880
  try {
787
881
  const completed = await uploadFile({
788
882
  client,
@@ -798,7 +892,7 @@ async function uploadCommand(files, options, globals, context) {
798
892
  onProgress: (uploaded, total) => {
799
893
  if (uploaded > 0 && total > 0) {
800
894
  const percent = Math.floor(uploaded / total * 100);
801
- progress.update(`Uploading ${filename} ${percent}% (${formatBytes(uploaded)} / ${formatBytes(total)})`);
895
+ progress.update(`Uploading ${err.bold(filename)} ${err.cyan(`${percent}%`)} (${formatBytes(uploaded)} / ${formatBytes(total)})`);
802
896
  }
803
897
  }
804
898
  });
@@ -825,15 +919,15 @@ async function uploadCommand(files, options, globals, context) {
825
919
  results.push(result);
826
920
  if (!options.json) {
827
921
  if (result.ok && result.url) context.stdout.write(`${result.url}\n`);
828
- else if (result.ok) context.stderr.write(`${file}: uploaded (id ${result.id}), but the server returned no share link.\n`);
829
- else context.stderr.write(`${file}: ${result.error}\n`);
922
+ else if (result.ok) context.stderr.write(`${err.yellow(`${file}:`)} uploaded (id ${result.id}), but the server returned no share link.\n`);
923
+ else context.stderr.write(`${err.red(`${file}:`)} ${result.error}\n`);
830
924
  }
831
925
  }
832
926
  }
833
927
  if (options.json) context.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
834
928
  else if (invalid.length > 0) {
835
- for (const entry of invalid) context.stderr.write(`${entry.file}: ${entry.error}\n`);
836
- context.stderr.write("Nothing was uploaded.\n");
929
+ for (const entry of invalid) context.stderr.write(`${err.red(`${entry.file}:`)} ${entry.error}\n`);
930
+ context.stderr.write(`${err.red("Nothing was uploaded.")}\n`);
837
931
  }
838
932
  return results.every((result) => result.ok) ? 0 : 1;
839
933
  }
@@ -853,8 +947,9 @@ async function whoamiCommand(options, globals, context) {
853
947
  token_source: settings.tokenSource
854
948
  })}\n`);
855
949
  else {
856
- context.stdout.write(`Logged in to ${settings.baseUrl} as ${me.name} (${me.email})\n`);
857
- if (settings.tokenSource === "env") context.stderr.write("(using FILECAFE_TOKEN)\n");
950
+ const out = colorsFor(context.stdout, context.env);
951
+ context.stdout.write(`Logged in to ${settings.baseUrl} as ${out.bold(me.name)} (${me.email})\n`);
952
+ if (settings.tokenSource === "env") context.stderr.write(`${colorsFor(context.stderr, context.env).gray("(using FILECAFE_TOKEN)")}\n`);
858
953
  }
859
954
  return 0;
860
955
  }
@@ -912,26 +1007,28 @@ function startUpdateCheck(context) {
912
1007
  }
913
1008
  /** Show the notice and, at a terminal, offer to install. `version` is null when npm could not confirm it. */
914
1009
  async function offerUpdate(context, version) {
915
- context.stderr.write(version ? `\nUpdate available for filecafe (${VERSION} → ${version}).\nChangelog: ${RELEASES_URL}/v${version}\n` : "\nA newer version of filecafe may be available.\n");
1010
+ const color = colorsFor(context.stderr, context.env);
1011
+ const run = (command) => color.cyan(command);
1012
+ context.stderr.write(version ? `\nUpdate available for filecafe (${color.gray(VERSION)} → ${color.green(version)}).\nChangelog: ${color.cyan(`${RELEASES_URL}/v${version}`)}\n` : "\nA newer version of filecafe may be available.\n");
916
1013
  if (context.env.npm_command === "exec" || context.scriptPath.replaceAll("\\", "/").includes("/_npx/")) {
917
- context.stderr.write("Run: npx filecafe@latest\n");
1014
+ context.stderr.write(`Run: ${run("npx filecafe@latest")}\n`);
918
1015
  return;
919
1016
  }
920
1017
  if (!context.stdin.isTTY || !context.stdout.isTTY) {
921
1018
  const installer = await detectInstaller(context);
922
- context.stderr.write(installer ? `Run: ${installer.join(" ")}\n` : UNKNOWN_INSTALL);
1019
+ context.stderr.write(installer ? `Run: ${run(installer.join(" "))}\n` : UNKNOWN_INSTALL);
923
1020
  return;
924
1021
  }
925
- if (!await context.confirm("Would you like to upgrade now? (Y/n) ")) return;
1022
+ if (!await context.confirm(`Would you like to upgrade now? ${color.gray("(Y/n)")} `)) return;
926
1023
  const installer = await detectInstaller(context);
927
1024
  if (!installer) {
928
1025
  context.stderr.write(UNKNOWN_INSTALL);
929
1026
  return;
930
1027
  }
931
1028
  const [command, ...args] = installer;
932
- context.stderr.write(`> ${installer.join(" ")}\n`);
1029
+ context.stderr.write(`${color.gray(`> ${installer.join(" ")}`)}\n`);
933
1030
  const exitCode = await context.run(command, args);
934
- context.stderr.write(exitCode === 0 ? "Updated filecafe.\n" : `The update failed. Run it yourself: ${installer.join(" ")}\n`);
1031
+ context.stderr.write(exitCode === 0 ? `${color.green("Updated filecafe.")}\n` : `${color.red("The update failed.")} Run it yourself: ${run(installer.join(" "))}\n`);
935
1032
  }
936
1033
  const PACKAGE_MANAGERS = [
937
1034
  {
@@ -1096,8 +1193,9 @@ async function execute(context, action, { quiet = false } = {}) {
1096
1193
  try {
1097
1194
  process.exitCode = await action();
1098
1195
  } catch (error) {
1099
- const message = error instanceof CliError || error instanceof ApiError ? error.message : `Unexpected error: ${error instanceof Error ? error.message : String(error)}`;
1100
- context.stderr.write(`${message}\n`);
1196
+ const label = error instanceof CliError || error instanceof ApiError ? "Error:" : "Unexpected error:";
1197
+ const message = error instanceof Error ? error.message : String(error);
1198
+ context.stderr.write(`${colorsFor(context.stderr, context.env).red(label)} ${message}\n`);
1101
1199
  if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
1102
1200
  process.exitCode = 1;
1103
1201
  }
@@ -108,7 +108,7 @@ async function resolveSettings(environment, urlOption) {
108
108
  };
109
109
  }
110
110
  // src/version.ts
111
- const VERSION = "0.3.0";
111
+ const VERSION = "0.3.2";
112
112
  // src/update-cache.ts
113
113
  const REGISTRY_URL = "https://registry.npmjs.org/filecafe/latest";
114
114
  /** Ask npm at most once a day. */
@@ -1,4 +1,4 @@
1
- import { i as refreshUpdateCache, s as VERSION } from "./update-cache-D6lecimA.js";
1
+ import { i as refreshUpdateCache, s as VERSION } from "./update-cache-BDT0cPCo.js";
2
2
  // src/update-worker.ts
3
3
  /**
4
4
  * Spawned detached by the CLI to refresh the update cache, so no command ever waits on npm.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "filecafe",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Upload files to file.cafe from the command line. Built for AI coding agents, humans, and CI.",
5
5
  "keywords": [
6
6
  "file.cafe",
@@ -28,6 +28,7 @@
28
28
  "prepublishOnly": "npm run build && npm test"
29
29
  },
30
30
  "dependencies": {
31
+ "chalk": "^5.6.2",
31
32
  "commander": "^14.0.3"
32
33
  },
33
34
  "devDependencies": {