filecafe 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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,13 +21,15 @@ 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
27
29
  filecafe login
28
30
  ```
29
31
 
30
- This opens your browser so you can approve the CLI on file.cafe. The token is saved to `~/.config/filecafe/config.json` (or `$XDG_CONFIG_HOME/filecafe/config.json`; `%APPDATA%\filecafe\config.json` on Windows) with owner-only permissions.
32
+ This shows a one-time code and opens your browser so you can approve the CLI on file.cafe; check that the code on the page matches the one in your terminal. It works over SSH too: if no browser opens, visit the printed URL on any device and enter the code. The token is saved to `~/.config/filecafe/config.json` (or `$XDG_CONFIG_HOME/filecafe/config.json`; `%APPDATA%\filecafe\config.json` on Windows) with owner-only permissions.
31
33
 
32
34
  Headless machines and CI can use an existing token instead:
33
35
 
package/dist/cli.js CHANGED
@@ -1,12 +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-D6lecimA.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";
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";
7
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
8
- import { randomBytes, timingSafeEqual } from "node:crypto";
9
- import { createServer } from "node:http";
10
+ import { fileURLToPath } from "node:url";
10
11
  import { openAsBlob } from "node:fs";
11
12
  // src/api.ts
12
13
  const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
@@ -77,7 +78,7 @@ function createApiClient(options) {
77
78
  for (;;) {
78
79
  const headers = {
79
80
  Accept: "application/json",
80
- Authorization: `Bearer ${token}`,
81
+ ...token && { Authorization: `Bearer ${token}` },
81
82
  "User-Agent": userAgent
82
83
  };
83
84
  if (body !== void 0) headers["Content-Type"] = "application/json";
@@ -138,111 +139,6 @@ async function fetchMe(client) {
138
139
  email: me.email
139
140
  };
140
141
  }
141
- /**
142
- * Location of the config file:
143
- * - Windows: %APPDATA%\filecafe\config.json
144
- * - Elsewhere: $XDG_CONFIG_HOME/filecafe/config.json, falling back to ~/.config/filecafe/config.json
145
- */
146
- function configPath({ env, platform, homedir }) {
147
- if (platform === "win32") {
148
- const appData = env.APPDATA || join(homedir, "AppData", "Roaming");
149
- return join(appData, "filecafe", "config.json");
150
- }
151
- const xdg = env.XDG_CONFIG_HOME;
152
- const base = xdg && xdg.startsWith("/") ? xdg : join(homedir, ".config");
153
- return join(base, "filecafe", "config.json");
154
- }
155
- /** Validate and normalize a base URL (http/https only, no trailing slash). */
156
- function normalizeBaseUrl(value) {
157
- let url;
158
- try {
159
- url = new URL(value.trim());
160
- } catch {
161
- throw new Error(`Invalid URL "${value}". Expected something like https://file.cafe`);
162
- }
163
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Invalid URL "${value}". Only http:// and https:// URLs are supported.`);
164
- 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`);
165
- return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
166
- }
167
- async function readConfig(environment) {
168
- let raw;
169
- try {
170
- raw = await readFile(configPath(environment), "utf8");
171
- } catch (error) {
172
- if (error.code === "ENOENT") return null;
173
- throw error;
174
- }
175
- try {
176
- const parsed = JSON.parse(raw);
177
- if (typeof parsed.url === "string" && typeof parsed.token === "string" && parsed.token) return {
178
- url: normalizeBaseUrl(parsed.url),
179
- token: parsed.token
180
- };
181
- } catch {}
182
- return null;
183
- }
184
- /** Write the config file atomically with owner-only permissions (dir 0700, file 0600). */
185
- async function writeConfig(environment, config) {
186
- const path = configPath(environment);
187
- const directory = dirname(path);
188
- await mkdir(directory, {
189
- recursive: true,
190
- mode: 448
191
- });
192
- if (environment.platform !== "win32") await chmod(directory, 448);
193
- const temporary = `${path}.${process.pid}.tmp`;
194
- const contents = `${JSON.stringify({
195
- url: config.url,
196
- token: config.token
197
- }, null, 2)}\n`;
198
- await writeFile(temporary, contents, { mode: 384 });
199
- await rename(temporary, path);
200
- if (environment.platform !== "win32") await chmod(path, 384);
201
- return path;
202
- }
203
- /** Delete the saved config. Returns true if a file was removed. */
204
- async function deleteConfig(environment) {
205
- const path = configPath(environment);
206
- try {
207
- await rm(path);
208
- return true;
209
- } catch (error) {
210
- if (error.code === "ENOENT") return false;
211
- throw error;
212
- }
213
- }
214
- /**
215
- * Resolve the base URL and token.
216
- *
217
- * Base URL: --url, then FILECAFE_URL, then the URL saved by `filecafe login`, then https://file.cafe.
218
- * Token: FILECAFE_TOKEN, then the saved token — but the saved token is only used when it was
219
- * issued for the resolved base URL, so a token is never sent to a different site.
220
- */
221
- async function resolveSettings(environment, urlOption) {
222
- const saved = await readConfig(environment);
223
- const baseUrl = normalizeBaseUrl(urlOption || environment.env.FILECAFE_URL || saved?.url || "https://file.cafe");
224
- const envToken = environment.env.FILECAFE_TOKEN?.trim();
225
- if (envToken) return {
226
- baseUrl,
227
- token: envToken,
228
- tokenSource: "env",
229
- saved
230
- };
231
- if (saved && saved.url === baseUrl) return {
232
- baseUrl,
233
- token: saved.token,
234
- tokenSource: "config",
235
- saved
236
- };
237
- return {
238
- baseUrl,
239
- token: null,
240
- tokenSource: null,
241
- saved
242
- };
243
- }
244
- // src/version.ts
245
- const VERSION = "0.1.1";
246
142
  // src/context.ts
247
143
  /** Open a URL in the default browser without ever throwing. */
248
144
  function openBrowser(url, platform = process.platform) {
@@ -274,6 +170,65 @@ function openBrowser(url, platform = process.platform) {
274
170
  child.unref();
275
171
  } catch {}
276
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
+ }
277
232
  function createDefaultContext() {
278
233
  return {
279
234
  env: process.env,
@@ -281,10 +236,17 @@ function createDefaultContext() {
281
236
  homedir: homedir(),
282
237
  fetch: (input, init) => fetch(input, init),
283
238
  sleep: (ms) => setTimeout$1(ms),
239
+ now: () => Date.now(),
284
240
  stdout: process.stdout,
285
241
  stderr: process.stderr,
286
242
  stdin: process.stdin,
287
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] ?? "",
288
250
  userAgent: `filecafe-cli/${VERSION} node/${process.versions.node} (${process.platform})`
289
251
  };
290
252
  }
@@ -295,116 +257,6 @@ var CliError = class extends Error {
295
257
  this.name = "CliError";
296
258
  }
297
259
  };
298
- // src/login-server.ts
299
- const LOGIN_TIMEOUT_MS = 3e5;
300
- function generateState() {
301
- return randomBytes(16).toString("hex");
302
- }
303
- function statesMatch(received, expected) {
304
- if (received === null) return false;
305
- const a = Buffer.from(received, "utf8");
306
- const b = Buffer.from(expected, "utf8");
307
- return a.length === b.length && timingSafeEqual(a, b);
308
- }
309
- function page(title, message) {
310
- return `<!doctype html>
311
- <html lang="en">
312
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title>
313
- <style>body{font-family:system-ui,-apple-system,sans-serif;display:flex;min-height:100vh;margin:0;align-items:center;justify-content:center;background:#faf9f7;color:#1c1917}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem}p{color:#57534e}</style>
314
- </head>
315
- <body><main><h1>${title}</h1><p>${message}</p></main></body>
316
- </html>
317
- `;
318
- }
319
- const SUCCESS_PAGE = page("You're logged in to file.cafe.", "You can close this tab and return to your terminal.");
320
- const DENIED_PAGE = page("Login cancelled.", "The file.cafe CLI was not authorized. You can close this tab.");
321
- const FAILED_PAGE = page("Login failed.", "Something went wrong. Return to your terminal and run \"filecafe login\" again.");
322
- const INVALID_PAGE = page("Invalid login request.", "This link does not match the login started in your terminal. Run \"filecafe login\" again.");
323
- /**
324
- * Decide how to answer a request to the local callback server. Only
325
- * `GET /callback` with the expected `state` concludes the login; anything
326
- * else is rejected and the server keeps waiting.
327
- */
328
- function handleCallbackRequest(method, rawUrl, expectedState) {
329
- const url = new URL(rawUrl ?? "/", "http://127.0.0.1");
330
- if (method !== "GET" || url.pathname !== "/callback") return {
331
- status: 404,
332
- body: page("Not found.", "Nothing to see here.")
333
- };
334
- if (!statesMatch(url.searchParams.get("state"), expectedState)) return {
335
- status: 400,
336
- body: INVALID_PAGE
337
- };
338
- const error = url.searchParams.get("error");
339
- if (error) return {
340
- status: 200,
341
- body: error === "access_denied" ? DENIED_PAGE : FAILED_PAGE,
342
- result: { error }
343
- };
344
- const token = url.searchParams.get("token");
345
- if (!token) return {
346
- status: 400,
347
- body: FAILED_PAGE
348
- };
349
- return {
350
- status: 200,
351
- body: SUCCESS_PAGE,
352
- result: { token }
353
- };
354
- }
355
- /** Listen on a random loopback port for the browser redirect. */
356
- function startCallbackServer(state, timeoutMs = LOGIN_TIMEOUT_MS) {
357
- let settle = () => {};
358
- let fail = () => {};
359
- let settled = false;
360
- const result = new Promise((resolve, reject) => {
361
- settle = resolve;
362
- fail = reject;
363
- });
364
- const server = createServer((request, response) => {
365
- const outcome = handleCallbackRequest(request.method, request.url, state);
366
- response.writeHead(outcome.status, {
367
- "Content-Type": "text/html; charset=utf-8",
368
- "Cache-Control": "no-store",
369
- "Referrer-Policy": "no-referrer",
370
- Connection: "close"
371
- });
372
- response.end(outcome.body);
373
- if (outcome.result && !settled) {
374
- const loginResult = outcome.result;
375
- response.on("finish", () => finish(() => settle(loginResult)));
376
- }
377
- });
378
- let timer;
379
- const close = () => {
380
- clearTimeout(timer);
381
- server.close();
382
- server.closeAllConnections();
383
- };
384
- const finish = (callback) => {
385
- if (settled) return;
386
- settled = true;
387
- close();
388
- callback();
389
- };
390
- return new Promise((resolve, reject) => {
391
- server.once("error", reject);
392
- server.listen(0, "127.0.0.1", () => {
393
- const address = server.address();
394
- if (!address || typeof address === "string") {
395
- close();
396
- reject(/* @__PURE__ */ new Error("Could not start the local login server."));
397
- return;
398
- }
399
- timer = setTimeout(() => finish(() => fail(/* @__PURE__ */ new Error("Timed out waiting for the browser login (5 minutes). Run \"filecafe login\" again, or use \"filecafe login --token <token>\"."))), timeoutMs);
400
- resolve({
401
- port: address.port,
402
- result,
403
- close: () => finish(() => fail(/* @__PURE__ */ new Error("Login cancelled.")))
404
- });
405
- });
406
- });
407
- }
408
260
  // src/session.ts
409
261
  const NOT_LOGGED_IN = "Not logged in. Run \"filecafe login\" or set FILECAFE_TOKEN.";
410
262
  function clientFor(context, baseUrl, token, onNotice) {
@@ -444,19 +296,48 @@ async function readAll(input) {
444
296
  for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
445
297
  return text;
446
298
  }
447
- function authorizeUrl(baseUrl, port, state, name) {
448
- return `${baseUrl}/cli/authorize?port=${port}&state=${state}&name=${encodeURIComponent(name)}`;
299
+ const EXPIRED_MESSAGE = "The login code expired before it was approved. Run \"filecafe login\" again.";
300
+ function isStartedLogin(value) {
301
+ if (!value || typeof value !== "object") return false;
302
+ const login = value;
303
+ return typeof login.device_code === "string" && typeof login.user_code === "string" && typeof login.verification_uri === "string" && typeof login.verification_uri_complete === "string" && typeof login.expires_in === "number" && typeof login.interval === "number";
449
304
  }
450
- async function tokenFromBrowser(context, baseUrl, timeoutMs) {
451
- const state = generateState();
452
- const server = await startCallbackServer(state, timeoutMs);
453
- const url = authorizeUrl(baseUrl, server.port, state, hostname());
454
- context.stderr.write(`Opening your browser to log in to ${baseUrl}.\n`);
455
- context.stderr.write(`If it does not open, visit this URL on this machine:\n\n ${url}\n\nWaiting for approval...\n`);
456
- context.openBrowser(url);
457
- const result = await server.result;
458
- if ("error" in result) throw new CliError(result.error === "access_denied" ? "Login was cancelled in the browser." : `Login failed in the browser (${result.error}).`);
459
- return result.token;
305
+ /**
306
+ * Ask where the login stands, treating a dropped connection or server hiccup
307
+ * as "still pending" so one bad poll does not end the login.
308
+ */
309
+ async function pollLogin(client, deviceCode) {
310
+ try {
311
+ return await client.request("POST", "/api/v1/cli/logins/token", { device_code: deviceCode });
312
+ } catch (error) {
313
+ if (error instanceof ApiError && (error.status === null || error.status >= 500)) return { status: "pending" };
314
+ throw error;
315
+ }
316
+ }
317
+ /**
318
+ * Start a login on file.cafe, show its code, and poll until it is approved in
319
+ * the browser. The token only exists once this collects it, and nothing
320
+ * listens on a local port, so it works over SSH too.
321
+ */
322
+ async function tokenFromBrowser(context, baseUrl) {
323
+ const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
324
+ const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
325
+ 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
+ `);
328
+ context.openBrowser(login.verification_uri_complete);
329
+ const intervalMs = Math.max(login.interval, 1) * 1e3;
330
+ 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);
338
+ }
339
+ }
340
+ throw new CliError(EXPIRED_MESSAGE);
460
341
  }
461
342
  async function loginCommand(options, globals, context) {
462
343
  if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
@@ -471,7 +352,7 @@ async function loginCommand(options, globals, context) {
471
352
  else if (options.withToken) {
472
353
  if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
473
354
  token = (await readAll(context.stdin)).trim();
474
- } else token = await tokenFromBrowser(context, baseUrl, options.timeoutMs ?? 3e5);
355
+ } else token = await tokenFromBrowser(context, baseUrl);
475
356
  if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
476
357
  let me;
477
358
  try {
@@ -977,6 +858,199 @@ async function whoamiCommand(options, globals, context) {
977
858
  }
978
859
  return 0;
979
860
  }
861
+ // src/update-check.ts
862
+ const RELEASES_URL = "https://github.com/filecafe/cli/releases/tag";
863
+ /** Mention an update at most every three days, like the Vercel CLI. */
864
+ const NOTIFY_INTERVAL_MS = 2592e5;
865
+ /** How long the command may wait at the end to confirm a cached version is still the latest. */
866
+ const CONFIRM_TIMEOUT_MS = 3e3;
867
+ /** How long to wait for the package managers to say where they keep global packages. */
868
+ const DETECT_TIMEOUT_MS = 3e3;
869
+ const UNKNOWN_INSTALL = "Could not tell whether npm, pnpm, Yarn, or Bun installed filecafe. Update it with the package manager that installed it.\n";
870
+ /**
871
+ * Check for a newer release without slowing the command down. The cache is refreshed by a
872
+ * detached worker; when it already knows of a newer version, npm is asked again while the
873
+ * command runs so the notice never names a stale version.
874
+ *
875
+ * The returned function reports the update on stderr once the command's own output is done,
876
+ * and offers to install it when the user is at a terminal. Nothing is shown in CI, when stderr
877
+ * is piped (scripts and AI agents), or when FILECAFE_NO_UPDATE_CHECK or NO_UPDATE_NOTIFIER is set.
878
+ */
879
+ function startUpdateCheck(context) {
880
+ const { env } = context;
881
+ if (!context.stderr.isTTY || env.CI || env.FILECAFE_NO_UPDATE_CHECK || env.NO_UPDATE_NOTIFIER) return async () => {};
882
+ const path = updateCachePath(context);
883
+ const pending = (async () => {
884
+ const cache = await readUpdateCache(path);
885
+ if (!cache || context.now() >= cache.expireAt) context.refreshInBackground(path);
886
+ if (!cache?.version || !isNewer(cache.version, VERSION) || context.now() < (cache.notifyAt ?? 0)) return null;
887
+ return {
888
+ cache,
889
+ fresh: await fetchLatestVersion(context.fetch, context.userAgent, CONFIRM_TIMEOUT_MS)
890
+ };
891
+ })().catch(() => null);
892
+ return async () => {
893
+ const result = await pending;
894
+ if (!result) return;
895
+ const { cache, fresh } = result;
896
+ const confirmed = fresh ? {
897
+ version: fresh,
898
+ expireAt: context.now() + CHECK_INTERVAL_MS
899
+ } : {};
900
+ const save = (change) => updateUpdateCache(path, (current) => ({
901
+ ...current ?? cache,
902
+ ...confirmed,
903
+ ...change
904
+ })).catch(() => {});
905
+ if (fresh && !isNewer(fresh, VERSION)) {
906
+ await save({});
907
+ return;
908
+ }
909
+ await save({ notifyAt: context.now() + NOTIFY_INTERVAL_MS });
910
+ await offerUpdate(context, fresh);
911
+ };
912
+ }
913
+ /** Show the notice and, at a terminal, offer to install. `version` is null when npm could not confirm it. */
914
+ 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");
916
+ if (context.env.npm_command === "exec" || context.scriptPath.replaceAll("\\", "/").includes("/_npx/")) {
917
+ context.stderr.write("Run: npx filecafe@latest\n");
918
+ return;
919
+ }
920
+ if (!context.stdin.isTTY || !context.stdout.isTTY) {
921
+ const installer = await detectInstaller(context);
922
+ context.stderr.write(installer ? `Run: ${installer.join(" ")}\n` : UNKNOWN_INSTALL);
923
+ return;
924
+ }
925
+ if (!await context.confirm("Would you like to upgrade now? (Y/n) ")) return;
926
+ const installer = await detectInstaller(context);
927
+ if (!installer) {
928
+ context.stderr.write(UNKNOWN_INSTALL);
929
+ return;
930
+ }
931
+ const [command, ...args] = installer;
932
+ context.stderr.write(`> ${installer.join(" ")}\n`);
933
+ 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`);
935
+ }
936
+ const PACKAGE_MANAGERS = [
937
+ {
938
+ install: [
939
+ "npm",
940
+ "i",
941
+ "-g",
942
+ "filecafe@latest"
943
+ ],
944
+ detect: [
945
+ "npm",
946
+ "root",
947
+ "-g"
948
+ ],
949
+ packageDir: (root) => join(root, "filecafe")
950
+ },
951
+ {
952
+ install: [
953
+ "pnpm",
954
+ "add",
955
+ "-g",
956
+ "filecafe@latest"
957
+ ],
958
+ detect: [
959
+ "pnpm",
960
+ "list",
961
+ "-g",
962
+ "filecafe",
963
+ "--depth=0",
964
+ "--json"
965
+ ],
966
+ packageDir: (output) => {
967
+ try {
968
+ const parsed = JSON.parse(output);
969
+ const path = (Array.isArray(parsed) ? parsed[0] : parsed)?.dependencies?.filecafe?.path;
970
+ return typeof path === "string" ? path : void 0;
971
+ } catch {
972
+ return;
973
+ }
974
+ }
975
+ },
976
+ {
977
+ install: [
978
+ "yarn",
979
+ "global",
980
+ "add",
981
+ "filecafe@latest"
982
+ ],
983
+ detect: [
984
+ "yarn",
985
+ "--silent",
986
+ "global",
987
+ "dir"
988
+ ],
989
+ packageDir: (root) => join(root, "node_modules", "filecafe")
990
+ },
991
+ {
992
+ install: [
993
+ "bun",
994
+ "add",
995
+ "-g",
996
+ "filecafe@latest"
997
+ ],
998
+ detect: [
999
+ "bun",
1000
+ "pm",
1001
+ "bin",
1002
+ "-g"
1003
+ ],
1004
+ binaryDir: (root) => root
1005
+ }
1006
+ ];
1007
+ /**
1008
+ * Find the package manager whose global install is the copy running now, by asking each one
1009
+ * (all at once) where it keeps global packages. Returns the command that upgrades it, or null
1010
+ * when none of them owns this copy (a project dependency, a source checkout, or an unusual
1011
+ * setup) or they take longer than `timeoutMs` to answer.
1012
+ */
1013
+ async function detectInstaller(context, timeoutMs = DETECT_TIMEOUT_MS) {
1014
+ const installPath = await context.realpath(context.scriptPath);
1015
+ if (!installPath) return null;
1016
+ const stop = new AbortController();
1017
+ const owns = async (manager) => {
1018
+ const [command, ...args] = manager.detect;
1019
+ const output = (await context.capture(command, args, stop.signal))?.trim();
1020
+ if (!output) return false;
1021
+ const packageDir = manager.packageDir?.(output);
1022
+ const resolvedDir = packageDir && await context.realpath(packageDir);
1023
+ if (resolvedDir && installPath.startsWith(resolvedDir + sep)) return true;
1024
+ return !!manager.binaryDir && await context.realpath(join(manager.binaryDir(output), "filecafe")) === installPath;
1025
+ };
1026
+ let timer;
1027
+ try {
1028
+ return await new Promise((resolve) => {
1029
+ timer = setTimeout(() => resolve(null), timeoutMs);
1030
+ const checks = PACKAGE_MANAGERS.map((manager) => owns(manager).then((owned) => owned && resolve(manager.install), () => {}));
1031
+ Promise.all(checks).then(() => resolve(null));
1032
+ });
1033
+ } finally {
1034
+ clearTimeout(timer);
1035
+ stop.abort();
1036
+ }
1037
+ }
1038
+ function parseVersion(version) {
1039
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
1040
+ return match ? [
1041
+ Number(match[1]),
1042
+ Number(match[2]),
1043
+ Number(match[3])
1044
+ ] : null;
1045
+ }
1046
+ /** Whether `candidate` is a later release than `current`. Pre-releases never count as newer. */
1047
+ function isNewer(candidate, current) {
1048
+ const a = parseVersion(candidate);
1049
+ const b = parseVersion(current);
1050
+ if (!a || !b) return false;
1051
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
1052
+ return false;
1053
+ }
980
1054
  // src/cli.ts
981
1055
  const MAIN_EXAMPLES = `
982
1056
  Examples:
@@ -989,6 +1063,7 @@ Examples:
989
1063
  Environment:
990
1064
  FILECAFE_TOKEN API token; takes precedence over the saved login
991
1065
  FILECAFE_URL Site URL (default: https://file.cafe)
1066
+ FILECAFE_NO_UPDATE_CHECK Set to turn off the new-version check (NO_UPDATE_NOTIFIER works too)
992
1067
 
993
1068
  Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
994
1069
  `;
@@ -1016,7 +1091,8 @@ Examples:
1016
1091
 
1017
1092
  In CI you can skip login entirely and set FILECAFE_TOKEN instead.
1018
1093
  `;
1019
- async function execute(context, action) {
1094
+ async function execute(context, action, { quiet = false } = {}) {
1095
+ const printUpdateNotice = quiet ? async () => {} : startUpdateCheck(context);
1020
1096
  try {
1021
1097
  process.exitCode = await action();
1022
1098
  } catch (error) {
@@ -1025,6 +1101,7 @@ async function execute(context, action) {
1025
1101
  if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
1026
1102
  process.exitCode = 1;
1027
1103
  }
1104
+ await printUpdateNotice();
1028
1105
  }
1029
1106
  function createProgram(context) {
1030
1107
  const program = new Command();
@@ -1033,7 +1110,7 @@ function createProgram(context) {
1033
1110
  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)));
1034
1111
  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)));
1035
1112
  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)));
1036
- 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)));
1113
+ 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 }));
1037
1114
  return program;
1038
1115
  }
1039
1116
  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.0";
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-D6lecimA.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.1.1",
3
+ "version": "0.3.0",
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",