filecafe 0.2.0 → 0.3.1

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  Upload files to [file.cafe](https://file.cafe) from the command line and get share links back.
4
4
 
5
- Built for AI coding agents (Claude Code, Codex, Cursor), humans, and CI: share URLs go to stdout, progress and errors go to stderr, `--json` gives machine-readable results, and nothing ever prompts (except the one-time browser login).
5
+ Built for AI coding agents (Claude Code, Codex, Cursor), humans, and CI: share URLs go to stdout, progress and errors go to stderr, `--json` gives machine-readable results, and nothing ever prompts (except the one-time browser login, and an upgrade offer when you run it yourself in a terminal).
6
6
 
7
7
  ## Install
8
8
 
@@ -21,6 +21,8 @@ filecafe --help
21
21
 
22
22
  Requires Node.js 20 or newer.
23
23
 
24
+ When you run filecafe in a terminal and a new version is out, it tells you and offers to upgrade it with the package manager you installed it with. It checks npm in the background once a day (retrying on the next run if npm can't be reached), mentions an update at most every three days, and never shows this in CI or when its output is piped (scripts and AI agents). Set `FILECAFE_NO_UPDATE_CHECK=1` or `NO_UPDATE_NOTIFIER=1` to turn it off.
25
+
24
26
  ## Log in
25
27
 
26
28
  ```sh
package/dist/cli.js CHANGED
@@ -1,10 +1,13 @@
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--jPxzzep.js";
2
3
  import { Command } from "commander";
3
- import { homedir, hostname } from "node:os";
4
- import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
- import { basename, dirname, extname, join } from "node:path";
6
- import { spawn } from "node:child_process";
7
- import { setTimeout } from "node:timers/promises";
4
+ import { homedir, hostname, tmpdir } from "node:os";
5
+ import { realpath, stat } from "node:fs/promises";
6
+ import { basename, extname, join, sep } from "node:path";
7
+ import { execFile, spawn } from "node:child_process";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
+ import { fileURLToPath } from "node:url";
8
11
  import { openAsBlob } from "node:fs";
9
12
  // src/api.ts
10
13
  const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
@@ -136,111 +139,6 @@ async function fetchMe(client) {
136
139
  email: me.email
137
140
  };
138
141
  }
139
- /**
140
- * Location of the config file:
141
- * - Windows: %APPDATA%\filecafe\config.json
142
- * - Elsewhere: $XDG_CONFIG_HOME/filecafe/config.json, falling back to ~/.config/filecafe/config.json
143
- */
144
- function configPath({ env, platform, homedir }) {
145
- if (platform === "win32") {
146
- const appData = env.APPDATA || join(homedir, "AppData", "Roaming");
147
- return join(appData, "filecafe", "config.json");
148
- }
149
- const xdg = env.XDG_CONFIG_HOME;
150
- const base = xdg && xdg.startsWith("/") ? xdg : join(homedir, ".config");
151
- return join(base, "filecafe", "config.json");
152
- }
153
- /** Validate and normalize a base URL (http/https only, no trailing slash). */
154
- function normalizeBaseUrl(value) {
155
- let url;
156
- try {
157
- url = new URL(value.trim());
158
- } catch {
159
- throw new Error(`Invalid URL "${value}". Expected something like https://file.cafe`);
160
- }
161
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Invalid URL "${value}". Only http:// and https:// URLs are supported.`);
162
- if (url.username || url.password || url.search || url.hash) throw new Error(`Invalid URL "${value}". Pass only the site address, e.g. https://file.cafe`);
163
- return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
164
- }
165
- async function readConfig(environment) {
166
- let raw;
167
- try {
168
- raw = await readFile(configPath(environment), "utf8");
169
- } catch (error) {
170
- if (error.code === "ENOENT") return null;
171
- throw error;
172
- }
173
- try {
174
- const parsed = JSON.parse(raw);
175
- if (typeof parsed.url === "string" && typeof parsed.token === "string" && parsed.token) return {
176
- url: normalizeBaseUrl(parsed.url),
177
- token: parsed.token
178
- };
179
- } catch {}
180
- return null;
181
- }
182
- /** Write the config file atomically with owner-only permissions (dir 0700, file 0600). */
183
- async function writeConfig(environment, config) {
184
- const path = configPath(environment);
185
- const directory = dirname(path);
186
- await mkdir(directory, {
187
- recursive: true,
188
- mode: 448
189
- });
190
- if (environment.platform !== "win32") await chmod(directory, 448);
191
- const temporary = `${path}.${process.pid}.tmp`;
192
- const contents = `${JSON.stringify({
193
- url: config.url,
194
- token: config.token
195
- }, null, 2)}\n`;
196
- await writeFile(temporary, contents, { mode: 384 });
197
- await rename(temporary, path);
198
- if (environment.platform !== "win32") await chmod(path, 384);
199
- return path;
200
- }
201
- /** Delete the saved config. Returns true if a file was removed. */
202
- async function deleteConfig(environment) {
203
- const path = configPath(environment);
204
- try {
205
- await rm(path);
206
- return true;
207
- } catch (error) {
208
- if (error.code === "ENOENT") return false;
209
- throw error;
210
- }
211
- }
212
- /**
213
- * Resolve the base URL and token.
214
- *
215
- * Base URL: --url, then FILECAFE_URL, then the URL saved by `filecafe login`, then https://file.cafe.
216
- * Token: FILECAFE_TOKEN, then the saved token — but the saved token is only used when it was
217
- * issued for the resolved base URL, so a token is never sent to a different site.
218
- */
219
- async function resolveSettings(environment, urlOption) {
220
- const saved = await readConfig(environment);
221
- const baseUrl = normalizeBaseUrl(urlOption || environment.env.FILECAFE_URL || saved?.url || "https://file.cafe");
222
- const envToken = environment.env.FILECAFE_TOKEN?.trim();
223
- if (envToken) return {
224
- baseUrl,
225
- token: envToken,
226
- tokenSource: "env",
227
- saved
228
- };
229
- if (saved && saved.url === baseUrl) return {
230
- baseUrl,
231
- token: saved.token,
232
- tokenSource: "config",
233
- saved
234
- };
235
- return {
236
- baseUrl,
237
- token: null,
238
- tokenSource: null,
239
- saved
240
- };
241
- }
242
- // src/version.ts
243
- const VERSION = "0.2.0";
244
142
  // src/context.ts
245
143
  /** Open a URL in the default browser without ever throwing. */
246
144
  function openBrowser(url, platform = process.platform) {
@@ -272,18 +170,83 @@ function openBrowser(url, platform = process.platform) {
272
170
  child.unref();
273
171
  } catch {}
274
172
  }
173
+ async function confirm(question) {
174
+ const prompt = createInterface({
175
+ input: process.stdin,
176
+ output: process.stderr
177
+ });
178
+ const cancel = new AbortController();
179
+ prompt.once("SIGINT", () => cancel.abort());
180
+ prompt.once("close", () => cancel.abort());
181
+ try {
182
+ const answer = await prompt.question(question, { signal: cancel.signal });
183
+ return /^(y|yes)?$/i.test(answer.trim());
184
+ } catch {
185
+ process.stderr.write("\n");
186
+ return false;
187
+ } finally {
188
+ prompt.close();
189
+ }
190
+ }
191
+ const packageManagerOptions = {
192
+ cwd: tmpdir(),
193
+ shell: process.platform === "win32",
194
+ windowsHide: true
195
+ };
196
+ function run(command, args) {
197
+ return new Promise((resolve) => {
198
+ const child = spawn(command, args, {
199
+ ...packageManagerOptions,
200
+ stdio: "inherit"
201
+ });
202
+ child.on("error", () => resolve(null));
203
+ child.on("close", (code) => resolve(code));
204
+ });
205
+ }
206
+ function capture(command, args, signal) {
207
+ return new Promise((resolve) => {
208
+ const options = {
209
+ ...packageManagerOptions,
210
+ encoding: "utf8",
211
+ timeout: 3e3,
212
+ killSignal: "SIGKILL",
213
+ signal
214
+ };
215
+ execFile(command, args, options, (error, stdout) => resolve(error ? null : stdout));
216
+ });
217
+ }
218
+ /** Spawn update-worker next to this file: dist/update-worker.js when built, src/update-worker.ts in development. */
219
+ function refreshInBackground(cachePath) {
220
+ try {
221
+ const here = fileURLToPath(import.meta.url);
222
+ const worker = fileURLToPath(new URL(`./update-worker${extname(here)}`, import.meta.url));
223
+ const child = spawn(process.execPath, [worker, cachePath], {
224
+ detached: true,
225
+ stdio: "ignore",
226
+ windowsHide: true
227
+ });
228
+ child.on("error", () => {});
229
+ child.unref();
230
+ } catch {}
231
+ }
275
232
  function createDefaultContext() {
276
233
  return {
277
234
  env: process.env,
278
235
  platform: process.platform,
279
236
  homedir: homedir(),
280
237
  fetch: (input, init) => fetch(input, init),
281
- sleep: (ms) => setTimeout(ms),
238
+ sleep: (ms) => setTimeout$1(ms),
282
239
  now: () => Date.now(),
283
240
  stdout: process.stdout,
284
241
  stderr: process.stderr,
285
242
  stdin: process.stdin,
286
243
  openBrowser: (url) => openBrowser(url),
244
+ confirm,
245
+ run,
246
+ capture,
247
+ realpath: (path) => realpath(path).catch(() => null),
248
+ refreshInBackground,
249
+ scriptPath: process.argv[1] ?? "",
287
250
  userAgent: `filecafe-cli/${VERSION} node/${process.versions.node} (${process.platform})`
288
251
  };
289
252
  }
@@ -327,6 +290,73 @@ async function requireSession(context, globals, onNotice) {
327
290
  }
328
291
  };
329
292
  }
293
+ // src/terminal.ts
294
+ /**
295
+ * Whether `stream` is a terminal that understands OSC 8 hyperlinks (link text that opens a
296
+ * different URL when clicked). Terminals that don't would print the escape codes as garbage,
297
+ * so this only says yes for ones known to support them. FORCE_HYPERLINK=1 or 0 overrides it.
298
+ */
299
+ function supportsHyperlinks(stream, env) {
300
+ if (env.FORCE_HYPERLINK !== void 0) return env.FORCE_HYPERLINK !== "0";
301
+ if (!stream.isTTY || env.CI || env.TERM === "dumb") return false;
302
+ if (env.WT_SESSION || env.KITTY_WINDOW_ID || env.WEZTERM_PANE || env.KONSOLE_VERSION || env.DOMTERM) return true;
303
+ if (Number(env.VTE_VERSION) >= 5e3) return true;
304
+ return [
305
+ "iTerm.app",
306
+ "WezTerm",
307
+ "vscode",
308
+ "ghostty",
309
+ "Hyper",
310
+ "Tabby",
311
+ "rio"
312
+ ].includes(env.TERM_PROGRAM ?? "");
313
+ }
314
+ /** `text` that opens `url` when clicked, for terminals where supportsHyperlinks() is true. */
315
+ function hyperlink(text, url) {
316
+ return `\u001B]8;;${url}\u0007${text}\u001B]8;;\u0007`;
317
+ }
318
+ const FRAMES = [
319
+ "⠋",
320
+ "⠙",
321
+ "⠹",
322
+ "⠸",
323
+ "⠼",
324
+ "⠴",
325
+ "⠦",
326
+ "⠧",
327
+ "⠇",
328
+ "⠏"
329
+ ];
330
+ const ASCII_FRAMES = [
331
+ "-",
332
+ "\\",
333
+ "|",
334
+ "/"
335
+ ];
336
+ /**
337
+ * Show `text` with a spinner in front of it on a terminal, erased by stop(). Anywhere else
338
+ * (a log file, CI, an AI agent) the text is written once as a plain line instead.
339
+ */
340
+ function startSpinner(stream, text, env, platform) {
341
+ if (!stream.isTTY || env.CI || env.TERM === "dumb") {
342
+ stream.write(`${text}\n`);
343
+ return { stop: () => {} };
344
+ }
345
+ const frames = platform === "win32" && !env.WT_SESSION ? ASCII_FRAMES : FRAMES;
346
+ let frame = 0;
347
+ const draw = () => stream.write(`\r${frames[frame++ % frames.length]} ${text}`);
348
+ draw();
349
+ const timer = setInterval(draw, 80);
350
+ timer.unref();
351
+ let stopped = false;
352
+ return { stop: () => {
353
+ if (!stopped) {
354
+ stopped = true;
355
+ clearInterval(timer);
356
+ stream.write("\r\x1B[2K");
357
+ }
358
+ } };
359
+ }
330
360
  // src/commands/login.ts
331
361
  async function readAll(input) {
332
362
  let text = "";
@@ -360,21 +390,26 @@ async function tokenFromBrowser(context, baseUrl) {
360
390
  const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
361
391
  const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
362
392
  if (!isStartedLogin(login)) throw new CliError(`Unexpected response from ${baseUrl} when starting the login. Check the --url option / FILECAFE_URL.`);
363
- 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...
364
- `);
393
+ const link = supportsHyperlinks(context.stderr, context.env) ? hyperlink(login.verification_uri, login.verification_uri_complete) : login.verification_uri;
394
+ 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 ${link} and enter the code.\n\n`);
365
395
  context.openBrowser(login.verification_uri_complete);
396
+ const spinner = startSpinner(context.stderr, "Waiting for approval...", context.env, context.platform);
366
397
  const intervalMs = Math.max(login.interval, 1) * 1e3;
367
398
  const deadline = context.now() + login.expires_in * 1e3;
368
- while (context.now() < deadline) {
369
- await context.sleep(Math.min(intervalMs, deadline - context.now()));
370
- const result = await pollLogin(client, login.device_code);
371
- switch (result.status) {
372
- case "approved": return result.token;
373
- case "denied": throw new CliError("Login was cancelled in the browser.");
374
- case "expired": throw new CliError(EXPIRED_MESSAGE);
399
+ try {
400
+ while (context.now() < deadline) {
401
+ await context.sleep(Math.min(intervalMs, deadline - context.now()));
402
+ const result = await pollLogin(client, login.device_code);
403
+ switch (result.status) {
404
+ case "approved": return result.token;
405
+ case "denied": throw new CliError("Login was cancelled in the browser.");
406
+ case "expired": throw new CliError(EXPIRED_MESSAGE);
407
+ }
375
408
  }
409
+ throw new CliError(EXPIRED_MESSAGE);
410
+ } finally {
411
+ spinner.stop();
376
412
  }
377
- throw new CliError(EXPIRED_MESSAGE);
378
413
  }
379
414
  async function loginCommand(options, globals, context) {
380
415
  if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
@@ -405,6 +440,7 @@ async function loginCommand(options, globals, context) {
405
440
  context.stdout.write(`Logged in as ${me.name} (${me.email})\n`);
406
441
  context.stderr.write(`Saved credentials for ${baseUrl} to ${configPath(context)}\n`);
407
442
  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");
443
+ context.stderr.write("\nRun \"filecafe upload <file>\" to share a file.\n");
408
444
  return 0;
409
445
  }
410
446
  // src/commands/logout.ts
@@ -895,6 +931,199 @@ async function whoamiCommand(options, globals, context) {
895
931
  }
896
932
  return 0;
897
933
  }
934
+ // src/update-check.ts
935
+ const RELEASES_URL = "https://github.com/filecafe/cli/releases/tag";
936
+ /** Mention an update at most every three days, like the Vercel CLI. */
937
+ const NOTIFY_INTERVAL_MS = 2592e5;
938
+ /** How long the command may wait at the end to confirm a cached version is still the latest. */
939
+ const CONFIRM_TIMEOUT_MS = 3e3;
940
+ /** How long to wait for the package managers to say where they keep global packages. */
941
+ const DETECT_TIMEOUT_MS = 3e3;
942
+ const UNKNOWN_INSTALL = "Could not tell whether npm, pnpm, Yarn, or Bun installed filecafe. Update it with the package manager that installed it.\n";
943
+ /**
944
+ * Check for a newer release without slowing the command down. The cache is refreshed by a
945
+ * detached worker; when it already knows of a newer version, npm is asked again while the
946
+ * command runs so the notice never names a stale version.
947
+ *
948
+ * The returned function reports the update on stderr once the command's own output is done,
949
+ * and offers to install it when the user is at a terminal. Nothing is shown in CI, when stderr
950
+ * is piped (scripts and AI agents), or when FILECAFE_NO_UPDATE_CHECK or NO_UPDATE_NOTIFIER is set.
951
+ */
952
+ function startUpdateCheck(context) {
953
+ const { env } = context;
954
+ if (!context.stderr.isTTY || env.CI || env.FILECAFE_NO_UPDATE_CHECK || env.NO_UPDATE_NOTIFIER) return async () => {};
955
+ const path = updateCachePath(context);
956
+ const pending = (async () => {
957
+ const cache = await readUpdateCache(path);
958
+ if (!cache || context.now() >= cache.expireAt) context.refreshInBackground(path);
959
+ if (!cache?.version || !isNewer(cache.version, VERSION) || context.now() < (cache.notifyAt ?? 0)) return null;
960
+ return {
961
+ cache,
962
+ fresh: await fetchLatestVersion(context.fetch, context.userAgent, CONFIRM_TIMEOUT_MS)
963
+ };
964
+ })().catch(() => null);
965
+ return async () => {
966
+ const result = await pending;
967
+ if (!result) return;
968
+ const { cache, fresh } = result;
969
+ const confirmed = fresh ? {
970
+ version: fresh,
971
+ expireAt: context.now() + CHECK_INTERVAL_MS
972
+ } : {};
973
+ const save = (change) => updateUpdateCache(path, (current) => ({
974
+ ...current ?? cache,
975
+ ...confirmed,
976
+ ...change
977
+ })).catch(() => {});
978
+ if (fresh && !isNewer(fresh, VERSION)) {
979
+ await save({});
980
+ return;
981
+ }
982
+ await save({ notifyAt: context.now() + NOTIFY_INTERVAL_MS });
983
+ await offerUpdate(context, fresh);
984
+ };
985
+ }
986
+ /** Show the notice and, at a terminal, offer to install. `version` is null when npm could not confirm it. */
987
+ async function offerUpdate(context, version) {
988
+ 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");
989
+ if (context.env.npm_command === "exec" || context.scriptPath.replaceAll("\\", "/").includes("/_npx/")) {
990
+ context.stderr.write("Run: npx filecafe@latest\n");
991
+ return;
992
+ }
993
+ if (!context.stdin.isTTY || !context.stdout.isTTY) {
994
+ const installer = await detectInstaller(context);
995
+ context.stderr.write(installer ? `Run: ${installer.join(" ")}\n` : UNKNOWN_INSTALL);
996
+ return;
997
+ }
998
+ if (!await context.confirm("Would you like to upgrade now? (Y/n) ")) return;
999
+ const installer = await detectInstaller(context);
1000
+ if (!installer) {
1001
+ context.stderr.write(UNKNOWN_INSTALL);
1002
+ return;
1003
+ }
1004
+ const [command, ...args] = installer;
1005
+ context.stderr.write(`> ${installer.join(" ")}\n`);
1006
+ const exitCode = await context.run(command, args);
1007
+ context.stderr.write(exitCode === 0 ? "Updated filecafe.\n" : `The update failed. Run it yourself: ${installer.join(" ")}\n`);
1008
+ }
1009
+ const PACKAGE_MANAGERS = [
1010
+ {
1011
+ install: [
1012
+ "npm",
1013
+ "i",
1014
+ "-g",
1015
+ "filecafe@latest"
1016
+ ],
1017
+ detect: [
1018
+ "npm",
1019
+ "root",
1020
+ "-g"
1021
+ ],
1022
+ packageDir: (root) => join(root, "filecafe")
1023
+ },
1024
+ {
1025
+ install: [
1026
+ "pnpm",
1027
+ "add",
1028
+ "-g",
1029
+ "filecafe@latest"
1030
+ ],
1031
+ detect: [
1032
+ "pnpm",
1033
+ "list",
1034
+ "-g",
1035
+ "filecafe",
1036
+ "--depth=0",
1037
+ "--json"
1038
+ ],
1039
+ packageDir: (output) => {
1040
+ try {
1041
+ const parsed = JSON.parse(output);
1042
+ const path = (Array.isArray(parsed) ? parsed[0] : parsed)?.dependencies?.filecafe?.path;
1043
+ return typeof path === "string" ? path : void 0;
1044
+ } catch {
1045
+ return;
1046
+ }
1047
+ }
1048
+ },
1049
+ {
1050
+ install: [
1051
+ "yarn",
1052
+ "global",
1053
+ "add",
1054
+ "filecafe@latest"
1055
+ ],
1056
+ detect: [
1057
+ "yarn",
1058
+ "--silent",
1059
+ "global",
1060
+ "dir"
1061
+ ],
1062
+ packageDir: (root) => join(root, "node_modules", "filecafe")
1063
+ },
1064
+ {
1065
+ install: [
1066
+ "bun",
1067
+ "add",
1068
+ "-g",
1069
+ "filecafe@latest"
1070
+ ],
1071
+ detect: [
1072
+ "bun",
1073
+ "pm",
1074
+ "bin",
1075
+ "-g"
1076
+ ],
1077
+ binaryDir: (root) => root
1078
+ }
1079
+ ];
1080
+ /**
1081
+ * Find the package manager whose global install is the copy running now, by asking each one
1082
+ * (all at once) where it keeps global packages. Returns the command that upgrades it, or null
1083
+ * when none of them owns this copy (a project dependency, a source checkout, or an unusual
1084
+ * setup) or they take longer than `timeoutMs` to answer.
1085
+ */
1086
+ async function detectInstaller(context, timeoutMs = DETECT_TIMEOUT_MS) {
1087
+ const installPath = await context.realpath(context.scriptPath);
1088
+ if (!installPath) return null;
1089
+ const stop = new AbortController();
1090
+ const owns = async (manager) => {
1091
+ const [command, ...args] = manager.detect;
1092
+ const output = (await context.capture(command, args, stop.signal))?.trim();
1093
+ if (!output) return false;
1094
+ const packageDir = manager.packageDir?.(output);
1095
+ const resolvedDir = packageDir && await context.realpath(packageDir);
1096
+ if (resolvedDir && installPath.startsWith(resolvedDir + sep)) return true;
1097
+ return !!manager.binaryDir && await context.realpath(join(manager.binaryDir(output), "filecafe")) === installPath;
1098
+ };
1099
+ let timer;
1100
+ try {
1101
+ return await new Promise((resolve) => {
1102
+ timer = setTimeout(() => resolve(null), timeoutMs);
1103
+ const checks = PACKAGE_MANAGERS.map((manager) => owns(manager).then((owned) => owned && resolve(manager.install), () => {}));
1104
+ Promise.all(checks).then(() => resolve(null));
1105
+ });
1106
+ } finally {
1107
+ clearTimeout(timer);
1108
+ stop.abort();
1109
+ }
1110
+ }
1111
+ function parseVersion(version) {
1112
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
1113
+ return match ? [
1114
+ Number(match[1]),
1115
+ Number(match[2]),
1116
+ Number(match[3])
1117
+ ] : null;
1118
+ }
1119
+ /** Whether `candidate` is a later release than `current`. Pre-releases never count as newer. */
1120
+ function isNewer(candidate, current) {
1121
+ const a = parseVersion(candidate);
1122
+ const b = parseVersion(current);
1123
+ if (!a || !b) return false;
1124
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
1125
+ return false;
1126
+ }
898
1127
  // src/cli.ts
899
1128
  const MAIN_EXAMPLES = `
900
1129
  Examples:
@@ -907,6 +1136,7 @@ Examples:
907
1136
  Environment:
908
1137
  FILECAFE_TOKEN API token; takes precedence over the saved login
909
1138
  FILECAFE_URL Site URL (default: https://file.cafe)
1139
+ FILECAFE_NO_UPDATE_CHECK Set to turn off the new-version check (NO_UPDATE_NOTIFIER works too)
910
1140
 
911
1141
  Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
912
1142
  `;
@@ -934,7 +1164,8 @@ Examples:
934
1164
 
935
1165
  In CI you can skip login entirely and set FILECAFE_TOKEN instead.
936
1166
  `;
937
- async function execute(context, action) {
1167
+ async function execute(context, action, { quiet = false } = {}) {
1168
+ const printUpdateNotice = quiet ? async () => {} : startUpdateCheck(context);
938
1169
  try {
939
1170
  process.exitCode = await action();
940
1171
  } catch (error) {
@@ -943,6 +1174,7 @@ async function execute(context, action) {
943
1174
  if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
944
1175
  process.exitCode = 1;
945
1176
  }
1177
+ await printUpdateNotice();
946
1178
  }
947
1179
  function createProgram(context) {
948
1180
  const program = new Command();
@@ -951,7 +1183,7 @@ function createProgram(context) {
951
1183
  program.command("login").description("Log in via your browser, or save an existing API token").option("--token <token>", "save this API token instead of opening a browser (visible in shell history; prefer --with-token)").option("--with-token", "read the API token from standard input").addHelpText("after", LOGIN_EXAMPLES).action((options, command) => execute(context, () => loginCommand(options, globals(command), context)));
952
1184
  program.command("logout").description("Revoke the saved login token on file.cafe and delete it from this machine (does not affect FILECAFE_TOKEN)").addHelpText("after", "\nThe token is revoked even if it was saved with \"filecafe login --token\", so don't log out\nwith a token that CI or another machine still uses.\n").action(() => execute(context, () => logoutCommand(context)));
953
1185
  program.command("whoami").description("Show the account you are logged in as").option("--json", "print {\"name\",\"email\",\"url\",\"token_source\"} as JSON").addHelpText("after", "\nExamples:\n $ filecafe whoami\n $ filecafe whoami --json\n").action((options, command) => execute(context, () => whoamiCommand(options, globals(command), context)));
954
- program.command("upload").description("Upload one or more files and print their share URLs").argument("<files...>", "files to upload (uploaded one after another)").option("--collection <uuid>", "add the files to this collection").option("--json", "print a JSON array of per-file results on stdout").option("-q, --quiet", "no progress or notices on stderr (errors are still printed)").addHelpText("after", UPLOAD_EXAMPLES).action((files, options, command) => execute(context, () => uploadCommand(files, options, globals(command), context)));
1186
+ program.command("upload").description("Upload one or more files and print their share URLs").argument("<files...>", "files to upload (uploaded one after another)").option("--collection <uuid>", "add the files to this collection").option("--json", "print a JSON array of per-file results on stdout").option("-q, --quiet", "no progress or notices on stderr (errors are still printed)").addHelpText("after", UPLOAD_EXAMPLES).action((files, options, command) => execute(context, () => uploadCommand(files, options, globals(command), context), { quiet: options.quiet }));
955
1187
  return program;
956
1188
  }
957
1189
  await createProgram(createDefaultContext()).parseAsync(process.argv);
@@ -0,0 +1,262 @@
1
+ import "node:os";
2
+ import { chmod, link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ // src/config.ts
6
+ const DEFAULT_BASE_URL = "https://file.cafe";
7
+ /**
8
+ * Location of the config file:
9
+ * - Windows: %APPDATA%\filecafe\config.json
10
+ * - Elsewhere: $XDG_CONFIG_HOME/filecafe/config.json, falling back to ~/.config/filecafe/config.json
11
+ */
12
+ function configPath({ env, platform, homedir }) {
13
+ if (platform === "win32") {
14
+ const appData = env.APPDATA || join(homedir, "AppData", "Roaming");
15
+ return join(appData, "filecafe", "config.json");
16
+ }
17
+ const xdg = env.XDG_CONFIG_HOME;
18
+ const base = xdg && xdg.startsWith("/") ? xdg : join(homedir, ".config");
19
+ return join(base, "filecafe", "config.json");
20
+ }
21
+ /** Validate and normalize a base URL (http/https only, no trailing slash). */
22
+ function normalizeBaseUrl(value) {
23
+ let url;
24
+ try {
25
+ url = new URL(value.trim());
26
+ } catch {
27
+ throw new Error(`Invalid URL "${value}". Expected something like https://file.cafe`);
28
+ }
29
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Invalid URL "${value}". Only http:// and https:// URLs are supported.`);
30
+ if (url.username || url.password || url.search || url.hash) throw new Error(`Invalid URL "${value}". Pass only the site address, e.g. https://file.cafe`);
31
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
32
+ }
33
+ async function readConfig(environment) {
34
+ let raw;
35
+ try {
36
+ raw = await readFile(configPath(environment), "utf8");
37
+ } catch (error) {
38
+ if (error.code === "ENOENT") return null;
39
+ throw error;
40
+ }
41
+ try {
42
+ const parsed = JSON.parse(raw);
43
+ if (typeof parsed.url === "string" && typeof parsed.token === "string" && parsed.token) return {
44
+ url: normalizeBaseUrl(parsed.url),
45
+ token: parsed.token
46
+ };
47
+ } catch {}
48
+ return null;
49
+ }
50
+ /** Write the config file atomically with owner-only permissions (dir 0700, file 0600). */
51
+ async function writeConfig(environment, config) {
52
+ const path = configPath(environment);
53
+ const directory = dirname(path);
54
+ await mkdir(directory, {
55
+ recursive: true,
56
+ mode: 448
57
+ });
58
+ if (environment.platform !== "win32") await chmod(directory, 448);
59
+ const temporary = `${path}.${process.pid}.tmp`;
60
+ const contents = `${JSON.stringify({
61
+ url: config.url,
62
+ token: config.token
63
+ }, null, 2)}\n`;
64
+ await writeFile(temporary, contents, { mode: 384 });
65
+ await rename(temporary, path);
66
+ if (environment.platform !== "win32") await chmod(path, 384);
67
+ return path;
68
+ }
69
+ /** Delete the saved config. Returns true if a file was removed. */
70
+ async function deleteConfig(environment) {
71
+ const path = configPath(environment);
72
+ try {
73
+ await rm(path);
74
+ return true;
75
+ } catch (error) {
76
+ if (error.code === "ENOENT") return false;
77
+ throw error;
78
+ }
79
+ }
80
+ /**
81
+ * Resolve the base URL and token.
82
+ *
83
+ * Base URL: --url, then FILECAFE_URL, then the URL saved by `filecafe login`, then https://file.cafe.
84
+ * Token: FILECAFE_TOKEN, then the saved token — but the saved token is only used when it was
85
+ * issued for the resolved base URL, so a token is never sent to a different site.
86
+ */
87
+ async function resolveSettings(environment, urlOption) {
88
+ const saved = await readConfig(environment);
89
+ const baseUrl = normalizeBaseUrl(urlOption || environment.env.FILECAFE_URL || saved?.url || "https://file.cafe");
90
+ const envToken = environment.env.FILECAFE_TOKEN?.trim();
91
+ if (envToken) return {
92
+ baseUrl,
93
+ token: envToken,
94
+ tokenSource: "env",
95
+ saved
96
+ };
97
+ if (saved && saved.url === baseUrl) return {
98
+ baseUrl,
99
+ token: saved.token,
100
+ tokenSource: "config",
101
+ saved
102
+ };
103
+ return {
104
+ baseUrl,
105
+ token: null,
106
+ tokenSource: null,
107
+ saved
108
+ };
109
+ }
110
+ // src/version.ts
111
+ const VERSION = "0.3.1";
112
+ // src/update-cache.ts
113
+ const REGISTRY_URL = "https://registry.npmjs.org/filecafe/latest";
114
+ /** Ask npm at most once a day. */
115
+ const CHECK_INTERVAL_MS = 864e5;
116
+ /** How long the background refresh may wait for npm. */
117
+ const BACKGROUND_TIMEOUT_MS = 8e3;
118
+ function updateCachePath(environment) {
119
+ return join(dirname(configPath(environment)), "update-check.json");
120
+ }
121
+ async function readUpdateCache(path) {
122
+ try {
123
+ const parsed = JSON.parse(await readFile(path, "utf8"));
124
+ if (typeof parsed.expireAt === "number" && typeof parsed.version === "string") return {
125
+ expireAt: parsed.expireAt,
126
+ version: parsed.version,
127
+ ...typeof parsed.notifyAt === "number" && { notifyAt: parsed.notifyAt }
128
+ };
129
+ } catch {}
130
+ return null;
131
+ }
132
+ /**
133
+ * Re-read the cache and save `change(current)`. The CLI and the background worker both write
134
+ * the cache, so each applies its change to what is on disk now rather than to what it read
135
+ * earlier; the write replaces the file atomically so a reader never sees half of it.
136
+ */
137
+ async function updateUpdateCache(path, change) {
138
+ const next = change(await readUpdateCache(path));
139
+ await mkdir(dirname(path), {
140
+ recursive: true,
141
+ mode: 448
142
+ });
143
+ await replaceFile(path, `${JSON.stringify(next)}\n`);
144
+ }
145
+ /** Write `contents` to a temporary file and move it over `path` in one step. */
146
+ async function replaceFile(path, contents) {
147
+ const temporary = `${path}.${randomUUID()}.tmp`;
148
+ try {
149
+ await writeFile(temporary, contents);
150
+ await rename(temporary, path);
151
+ } catch (error) {
152
+ await rm(temporary, { force: true });
153
+ throw error;
154
+ }
155
+ }
156
+ /** The version npm's `latest` tag points at, or null if npm cannot be reached in time. */
157
+ async function fetchLatestVersion(fetch, userAgent, timeoutMs) {
158
+ try {
159
+ const response = await fetch(REGISTRY_URL, {
160
+ headers: {
161
+ Accept: "application/json",
162
+ "User-Agent": userAgent
163
+ },
164
+ signal: AbortSignal.timeout(timeoutMs)
165
+ });
166
+ if (!response.ok) return null;
167
+ const { version } = await response.json();
168
+ return typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version) ? version : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+ /**
174
+ * Ask npm for the latest version and save it. Runs in the background worker, so only one runs
175
+ * at a time (guarded by a lock next to the cache) and errors are swallowed. If npm cannot
176
+ * be reached the cache is left as it was, so the next command tries again.
177
+ */
178
+ async function refreshUpdateCache(path, { fetch, userAgent, now }) {
179
+ await mkdir(dirname(path), {
180
+ recursive: true,
181
+ mode: 448
182
+ });
183
+ const lock = await acquireLock(path);
184
+ if (!lock) return;
185
+ try {
186
+ const current = await readUpdateCache(path);
187
+ if (current && now() < current.expireAt) return;
188
+ const version = await fetchLatestVersion(fetch, userAgent, BACKGROUND_TIMEOUT_MS);
189
+ if (!version) return;
190
+ await updateUpdateCache(path, (previous) => ({
191
+ expireAt: now() + CHECK_INTERVAL_MS,
192
+ version,
193
+ ...previous?.notifyAt !== void 0 && version === previous.version && { notifyAt: previous.notifyAt }
194
+ }));
195
+ } finally {
196
+ await replaceFile(lock, RELEASED).catch(() => {});
197
+ }
198
+ }
199
+ const RELEASED = "released";
200
+ /**
201
+ * Take the refresh lock and return its file, or null if another refresh holds it.
202
+ *
203
+ * Locks are numbered files (update-check.json.lock.1, .2, ...) and the highest number is the
204
+ * current one. To take the lock, a process creates the next number, which only one process can
205
+ * do, and keeps it only if that is still the highest number afterwards. That stays exclusive
206
+ * even when a holder dies without releasing it, which a single lock file taken over by
207
+ * deleting or renaming it cannot guarantee.
208
+ */
209
+ async function acquireLock(path) {
210
+ const numbers = await lockNumbers(path);
211
+ const newest = numbers.at(-1) ?? 0;
212
+ if (newest && await isHeld(lockFile(path, newest))) return null;
213
+ const mine = newest + 1;
214
+ const lock = lockFile(path, mine);
215
+ if (!await createExclusive(lock, `${process.pid}:${randomUUID()}`)) return null;
216
+ if ((await lockNumbers(path)).at(-1) !== mine) {
217
+ await replaceFile(lock, RELEASED).catch(() => {});
218
+ return null;
219
+ }
220
+ for (const old of numbers) await rm(lockFile(path, old), { force: true });
221
+ return lock;
222
+ }
223
+ function lockFile(path, number) {
224
+ return `${path}.lock.${number}`;
225
+ }
226
+ async function lockNumbers(path) {
227
+ const prefix = `${basename(path)}.lock.`;
228
+ return (await readdir(dirname(path)).catch(() => [])).filter((name) => name.startsWith(prefix) && /^\d+$/.test(name.slice(prefix.length))).map((name) => Number(name.slice(prefix.length))).sort((a, b) => a - b);
229
+ }
230
+ /** Whether a live process holds this lock: not released, and its owner is still running. */
231
+ async function isHeld(lock) {
232
+ const contents = await readFile(lock, "utf8").catch(() => RELEASED);
233
+ const pid = Number.parseInt(contents, 10);
234
+ return contents !== RELEASED && Number.isInteger(pid) && pid > 0 && isRunning(pid);
235
+ }
236
+ /**
237
+ * Create `path` holding `contents`, or return false if it exists. The contents are written to a
238
+ * temporary file first and hard-linked into place, so nobody ever sees a half-written lock.
239
+ * Without hard links (FAT and exFAT drives) this also returns false, so no refresh runs there:
240
+ * an exclusive create would expose the lock before its owner is written into it.
241
+ */
242
+ async function createExclusive(path, contents) {
243
+ const temporary = `${path}.${randomUUID()}.tmp`;
244
+ try {
245
+ await writeFile(temporary, contents);
246
+ await link(temporary, path);
247
+ return true;
248
+ } catch {
249
+ return false;
250
+ } finally {
251
+ await rm(temporary, { force: true });
252
+ }
253
+ }
254
+ function isRunning(pid) {
255
+ try {
256
+ process.kill(pid, 0);
257
+ return true;
258
+ } catch (error) {
259
+ return error.code === "EPERM";
260
+ }
261
+ }
262
+ export { updateCachePath as a, DEFAULT_BASE_URL as c, normalizeBaseUrl as d, readConfig as f, refreshUpdateCache as i, configPath as l, writeConfig as m, fetchLatestVersion as n, updateUpdateCache as o, resolveSettings as p, readUpdateCache as r, VERSION as s, CHECK_INTERVAL_MS as t, deleteConfig as u };
@@ -0,0 +1,14 @@
1
+ import { i as refreshUpdateCache, s as VERSION } from "./update-cache--jPxzzep.js";
2
+ // src/update-worker.ts
3
+ /**
4
+ * Spawned detached by the CLI to refresh the update cache, so no command ever waits on npm.
5
+ * Usage: node update-worker.js <cache path>
6
+ */
7
+ setTimeout(() => process.exit(1), 1e4).unref();
8
+ const path = process.argv[2];
9
+ if (path) await refreshUpdateCache(path, {
10
+ fetch: (input, init) => fetch(input, init),
11
+ userAgent: `filecafe-cli/${VERSION} node/${process.versions.node} (${process.platform})`,
12
+ now: () => Date.now()
13
+ }).catch(() => {});
14
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "filecafe",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
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",