filecafe 0.2.0 → 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,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-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";
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
  }
@@ -895,6 +858,199 @@ async function whoamiCommand(options, globals, context) {
895
858
  }
896
859
  return 0;
897
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
+ }
898
1054
  // src/cli.ts
899
1055
  const MAIN_EXAMPLES = `
900
1056
  Examples:
@@ -907,6 +1063,7 @@ Examples:
907
1063
  Environment:
908
1064
  FILECAFE_TOKEN API token; takes precedence over the saved login
909
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)
910
1067
 
911
1068
  Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
912
1069
  `;
@@ -934,7 +1091,8 @@ Examples:
934
1091
 
935
1092
  In CI you can skip login entirely and set FILECAFE_TOKEN instead.
936
1093
  `;
937
- async function execute(context, action) {
1094
+ async function execute(context, action, { quiet = false } = {}) {
1095
+ const printUpdateNotice = quiet ? async () => {} : startUpdateCheck(context);
938
1096
  try {
939
1097
  process.exitCode = await action();
940
1098
  } catch (error) {
@@ -943,6 +1101,7 @@ async function execute(context, action) {
943
1101
  if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
944
1102
  process.exitCode = 1;
945
1103
  }
1104
+ await printUpdateNotice();
946
1105
  }
947
1106
  function createProgram(context) {
948
1107
  const program = new Command();
@@ -951,7 +1110,7 @@ function createProgram(context) {
951
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)));
952
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)));
953
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)));
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)));
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 }));
955
1114
  return program;
956
1115
  }
957
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.2.0",
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",