filecafe 0.3.3 → 0.3.5

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
@@ -53,14 +53,25 @@ Settings → API tokens on file.cafe. `logout` revokes the token even if you sav
53
53
  ## Upload
54
54
 
55
55
  ```sh
56
- filecafe upload screenshot.png # prints the share URL
57
- filecafe upload a.png b.mp4 notes.txt # one URL per line, in order
58
- filecafe upload build.zip | pbcopy # copy the link to the clipboard
56
+ filecafe upload screenshot.png # shows the share URL, size and expiry date
57
+ filecafe upload a.png b.mp4 notes.txt # one summary per file, in order
58
+ filecafe upload build.zip | pbcopy # piped: just the link, copied to the clipboard
59
59
  filecafe upload video.mp4 --collection <uuid> # add to a collection
60
60
  filecafe upload report.pdf --json # machine-readable output
61
61
  filecafe upload big.mov --quiet # no progress output
62
62
  ```
63
63
 
64
+ In a terminal each upload ends with a summary:
65
+
66
+ ```
67
+ Successfully uploaded screenshot.png
68
+ URL: https://file.cafe/9e54VITGmPY.png
69
+ Size: 1.2 MB
70
+ Expires: November 7th 2026
71
+ ```
72
+
73
+ When the output is piped (scripts, CI, AI agents) or with `--quiet`, stdout is just the share URLs, one per line.
74
+
64
75
  Files are uploaded one after another; large files (over 64 MiB) are split into parts that upload in parallel. Every input is checked before anything is uploaded: if any path is missing or is not a regular file, nothing is uploaded.
65
76
 
66
77
  ### `--json` output
@@ -76,7 +87,8 @@ A single JSON array on stdout with one object per input file, in the order given
76
87
  "filename": "report.pdf",
77
88
  "size": 482113,
78
89
  "url": "https://file.cafe/...",
79
- "password_protected": false
90
+ "password_protected": false,
91
+ "expires_at": "2026-11-07T12:00:00+00:00"
80
92
  },
81
93
  {
82
94
  "file": "missing.png",
@@ -86,6 +98,8 @@ A single JSON array on stdout with one object per input file, in the order given
86
98
  ]
87
99
  ```
88
100
 
101
+ `expires_at` is `null` for files that never expire.
102
+
89
103
  The exit code is `0` if every file uploaded and `1` if any failed.
90
104
 
91
105
  ## Configuration
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-tQTolnAo.js";
2
+ import { a as updateCachePath, d as normalizeBaseUrl, f as readConfig, l as configPath, m as writeConfig, n as fetchLatestVersion, o as updateUpdateCache, p as resolveSettings, r as readUpdateCache, s as VERSION, t as CHECK_INTERVAL_MS, u as deleteConfig } from "./update-cache-DPfI7tdr.js";
3
3
  import { Command } from "commander";
4
4
  import { homedir, hostname, tmpdir } from "node:os";
5
5
  import { realpath, stat } from "node:fs/promises";
@@ -327,6 +327,14 @@ function supportsHyperlinks(stream, env) {
327
327
  function hyperlink(text, url) {
328
328
  return `\u001B]8;;${url}\u0007${text}\u001B]8;;\u0007`;
329
329
  }
330
+ /**
331
+ * A URL styled like the Vercel CLI's links: cyan and clickable where the terminal supports
332
+ * links (which usually underline it themselves), otherwise cyan and underlined.
333
+ */
334
+ function styledUrl(stream, env, url) {
335
+ const color = colorsFor(stream, env);
336
+ return supportsHyperlinks(stream, env) ? hyperlink(color.cyan(url), url) : color.cyan.underline(url);
337
+ }
330
338
  const FRAMES = [
331
339
  "⠋",
332
340
  "⠙",
@@ -607,18 +615,22 @@ function guessMimeType(filename) {
607
615
  /** An error while transferring bytes to the upload server. */
608
616
  var TransferError = class extends Error {
609
617
  status;
610
- /** The upload must be started again from scratch (e.g. the receipt for a written object was lost). */
611
- restartUpload;
612
- constructor(message, status, restartUpload = false) {
618
+ constructor(message, status) {
613
619
  super(message);
614
620
  this.name = "TransferError";
615
621
  this.status = status;
616
- this.restartUpload = restartUpload;
617
622
  }
618
623
  };
619
624
  const DEFAULT_CONCURRENCY = 4;
620
625
  const DEFAULT_PART_RETRIES = 3;
621
626
  const DEFAULT_PART_TIMEOUT_MS = 9e5;
627
+ /**
628
+ * Multipart uploads use the start response's URLs for the first batch of parts and fetch each
629
+ * later batch just before uploading it, so a long upload never sends a part to an expired URL.
630
+ */
631
+ const PART_URL_BATCH_SIZE = 50;
632
+ /** Fetch a batch's URLs again once they are this old. file.cafe signs them for two hours. */
633
+ const PART_URL_MAX_AGE_MS = 36e5;
622
634
  function isRecord(value) {
623
635
  return typeof value === "object" && value !== null && !Array.isArray(value);
624
636
  }
@@ -660,19 +672,31 @@ function describeFetchError(error) {
660
672
  }
661
673
  return String(error);
662
674
  }
663
- /** PUT one byte range, retrying network errors and 5xx responses. Returns the upload receipt. */
675
+ /** PUT one byte range, retrying network errors and 5xx responses. */
664
676
  async function putPart(target, body, options) {
665
677
  for (let attempt = 0;; attempt++) {
666
678
  options.signal.throwIfAborted();
679
+ let sent = 0;
680
+ const counted = body.stream().pipeThrough(new TransformStream({ transform(chunk, controller) {
681
+ sent += chunk.byteLength;
682
+ options.onBytes?.(chunk.byteLength);
683
+ controller.enqueue(chunk);
684
+ } }));
685
+ const failed = () => options.onBytes?.(-sent);
667
686
  let response;
668
687
  try {
669
688
  response = await options.fetch(target.url, {
670
689
  method: "PUT",
671
- headers: target.headers,
672
- body,
690
+ headers: {
691
+ ...target.headers,
692
+ "Content-Length": String(body.size)
693
+ },
694
+ body: counted,
695
+ duplex: "half",
673
696
  signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
674
697
  });
675
698
  } catch (error) {
699
+ failed();
676
700
  if (options.signal.aborted) throw options.signal.reason;
677
701
  if (attempt < options.maxRetries) {
678
702
  await options.sleep(1e3 * 2 ** attempt);
@@ -680,14 +704,12 @@ async function putPart(target, body, options) {
680
704
  }
681
705
  throw new TransferError(`Upload of ${options.label} failed: network error (${describeFetchError(error)}).`, null);
682
706
  }
683
- if (response.ok) {
707
+ if (response.ok || response.status === 412 && attempt > 0) {
684
708
  await response.body?.cancel();
685
- const receipt = response.headers.get("X-Upload-Receipt");
686
- if (!receipt && options.requireReceipt) throw new TransferError(`Upload of ${options.label} succeeded but the server did not return an upload receipt.`, response.status);
687
- return receipt;
709
+ return;
688
710
  }
711
+ failed();
689
712
  const detail = (await response.text().catch(() => "")).trim().slice(0, 500);
690
- if (response.status === 412) throw new TransferError(`Upload of ${options.label} failed: the file already exists and its receipt was lost.`, 412, true);
691
713
  if (response.status >= 500 && attempt < options.maxRetries) {
692
714
  await options.sleep(1e3 * 2 ** attempt);
693
715
  continue;
@@ -716,8 +738,14 @@ async function runPool(count, concurrency, controller, worker) {
716
738
  await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, count)) }, runner));
717
739
  if (firstError !== null) throw firstError;
718
740
  }
719
- async function transferOnce(options, blob) {
741
+ /**
742
+ * Upload one file: start the upload, PUT each part (in parallel for multipart), then complete
743
+ * it. file.cafe checks the stored file when completing, so nothing else needs to be sent back.
744
+ */
745
+ async function uploadFile(options) {
720
746
  const { client, size } = options;
747
+ const blob = await openAsBlob(options.path);
748
+ if (blob.size !== size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
721
749
  const started = await client.request("POST", "/api/v1/uploads", {
722
750
  filename: options.filename,
723
751
  size,
@@ -725,48 +753,73 @@ async function transferOnce(options, blob) {
725
753
  ...options.collectionId ? { collection_id: options.collectionId } : {}
726
754
  });
727
755
  const { targets, partSize } = planTransfer(started, size);
728
- const requireReceipt = started.requires_receipts !== false;
729
- const receipts = new Array(targets.length).fill(null);
756
+ const partUrls = createPartUrls(options, started, targets);
730
757
  const controller = new AbortController();
731
758
  let uploadedBytes = 0;
732
759
  options.onProgress?.(0, size);
733
760
  await runPool(targets.length, options.concurrency ?? DEFAULT_CONCURRENCY, controller, async (index) => {
734
761
  const start = index * partSize;
735
762
  const end = Math.min(start + partSize, size);
736
- const target = targets[index];
737
- receipts[index] = await putPart(target, blob.slice(start, end), {
763
+ await putPart(await partUrls.target(index), blob.slice(start, end), {
738
764
  fetch: options.fetch,
739
765
  sleep: options.sleep,
740
766
  maxRetries: options.maxPartRetries ?? DEFAULT_PART_RETRIES,
741
767
  timeoutMs: options.partTimeoutMs ?? DEFAULT_PART_TIMEOUT_MS,
742
768
  signal: controller.signal,
743
- requireReceipt,
744
- label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename
769
+ label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename,
770
+ onBytes: (bytes) => {
771
+ uploadedBytes += bytes;
772
+ options.onProgress?.(uploadedBytes, size);
773
+ }
745
774
  });
746
- uploadedBytes += end - start;
747
- options.onProgress?.(uploadedBytes, size);
748
775
  });
749
- return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, {
750
- token: started.token,
751
- receipts: receipts.filter((receipt) => receipt !== null)
752
- }, { idempotent: true });
776
+ return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, { token: partUrls.token() }, { idempotent: true });
753
777
  }
754
778
  /**
755
- * Upload one file: start the upload, PUT each part (in parallel for multipart),
756
- * then complete it with the receipts in part order.
779
+ * The URL for each part of an upload, in batches of PART_URL_BATCH_SIZE. The first batch comes
780
+ * from the start response; later ones, and any batch older than PART_URL_MAX_AGE_MS, are fetched
781
+ * when a part in them is about to be uploaded. Each fetch also renews the upload ticket, so the
782
+ * latest token is the one to complete with.
757
783
  */
758
- async function uploadFile(options) {
759
- const blob = await openAsBlob(options.path);
760
- if (blob.size !== options.size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
761
- try {
762
- return await transferOnce(options, blob);
763
- } catch (error) {
764
- if (error instanceof TransferError && error.restartUpload) {
765
- options.onNotice?.(`Restarting the upload of ${options.filename}...`);
766
- return transferOnce(options, blob);
767
- }
768
- throw error;
769
- }
784
+ function createPartUrls(options, started, targets) {
785
+ const now = options.now ?? Date.now;
786
+ const batches = /* @__PURE__ */ new Map([[0, {
787
+ fetchedAt: now(),
788
+ targets: Promise.resolve(targets.slice(0, PART_URL_BATCH_SIZE))
789
+ }]]);
790
+ let token = started.token;
791
+ const fetchBatch = async (batch) => {
792
+ const first = batch * PART_URL_BATCH_SIZE + 1;
793
+ const partNumbers = Array.from({ length: Math.min(PART_URL_BATCH_SIZE, targets.length - first + 1) }, (_, i) => first + i);
794
+ const response = await options.client.request("POST", `/api/v1/uploads/${encodeURIComponent(started.id)}/parts`, {
795
+ token,
796
+ part_numbers: partNumbers
797
+ }, { idempotent: true });
798
+ const parts = isRecord(response) && Array.isArray(response.parts) ? response.parts : [];
799
+ const fresh = partNumbers.map((partNumber) => parts.find((part) => isRecord(part) && part.part_number === partNumber));
800
+ if (!isRecord(response) || typeof response.token !== "string" || !fresh.every(isSignedTarget)) throw new ApiError("Unexpected response when fetching upload URLs.", null);
801
+ token = response.token;
802
+ return fresh.map((part) => ({
803
+ url: part.url,
804
+ headers: part.headers
805
+ }));
806
+ };
807
+ return {
808
+ async target(index) {
809
+ if (!("parts" in started)) return targets[index];
810
+ const batch = Math.floor(index / PART_URL_BATCH_SIZE);
811
+ let entry = batches.get(batch);
812
+ if (!entry || now() - entry.fetchedAt > PART_URL_MAX_AGE_MS) {
813
+ entry = {
814
+ fetchedAt: now(),
815
+ targets: fetchBatch(batch)
816
+ };
817
+ batches.set(batch, entry);
818
+ }
819
+ return (await entry.targets)[index % PART_URL_BATCH_SIZE];
820
+ },
821
+ token: () => token
822
+ };
770
823
  }
771
824
  // src/commands/upload.ts
772
825
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -781,6 +834,27 @@ function uploadFilename(path) {
781
834
  const keep = extension.length > 0 && extension.length <= 16 ? extension : [];
782
835
  return characters.slice(0, MAX_FILENAME_LENGTH - keep.length).join("") + keep.join("");
783
836
  }
837
+ /** "November 7th 2026", in the local time zone. */
838
+ function formatExpiry(iso) {
839
+ const date = new Date(iso);
840
+ if (Number.isNaN(date.getTime())) return iso;
841
+ const day = date.getDate();
842
+ const suffix = {
843
+ one: "st",
844
+ two: "nd",
845
+ few: "rd"
846
+ }[new Intl.PluralRules("en-US", { type: "ordinal" }).select(day)] ?? "th";
847
+ return `${date.toLocaleString("en-US", { month: "long" })} ${day}${suffix} ${date.getFullYear()}`;
848
+ }
849
+ function summary(result, url, color) {
850
+ const lines = [
851
+ `${color.green("Successfully uploaded")} ${color.bold(result.filename)}`,
852
+ `${color.gray("URL:")} ${url}`,
853
+ `${color.gray("Size:")} ${formatBytes(result.size)}`
854
+ ];
855
+ if (result.expires_at !== void 0) lines.push(`${color.gray("Expires:")} ${result.expires_at === null ? "Never" : formatExpiry(result.expires_at)}`);
856
+ return `${lines.join("\n")}\n`;
857
+ }
784
858
  function formatBytes(bytes) {
785
859
  const units = [
786
860
  "B",
@@ -849,6 +923,9 @@ async function uploadCommand(files, options, globals, context) {
849
923
  if (files.length === 0) throw new CliError("No files given. Usage: filecafe upload <files...>");
850
924
  const showProgress = Boolean(context.stderr.isTTY) && !options.json && !options.quiet;
851
925
  const err = colorsFor(context.stderr, context.env);
926
+ const showSummary = Boolean(context.stdout.isTTY) && !options.quiet;
927
+ const out = colorsFor(context.stdout, context.env);
928
+ let summaries = 0;
852
929
  const progress = createProgress(context, showProgress);
853
930
  const notice = (message) => {
854
931
  if (!options.quiet) {
@@ -877,6 +954,7 @@ async function uploadCommand(files, options, globals, context) {
877
954
  else {
878
955
  const filename = uploadFilename(file);
879
956
  progress.update(`Uploading ${err.bold(filename)} (${formatBytes(size)})...`);
957
+ let lastDrawn = -Infinity;
880
958
  try {
881
959
  const completed = await uploadFile({
882
960
  client,
@@ -888,8 +966,10 @@ async function uploadCommand(files, options, globals, context) {
888
966
  mimeType: guessMimeType(filename),
889
967
  collectionId: options.collection,
890
968
  concurrency: options.concurrency,
891
- onNotice: notice,
969
+ now: context.now,
892
970
  onProgress: (uploaded, total) => {
971
+ if (uploaded < total && context.now() - lastDrawn < 100) return;
972
+ lastDrawn = context.now();
893
973
  if (uploaded > 0 && total > 0) {
894
974
  const percent = Math.floor(uploaded / total * 100);
895
975
  progress.update(`Uploading ${err.bold(filename)} ${err.cyan(`${percent}%`)} (${formatBytes(uploaded)} / ${formatBytes(total)})`);
@@ -903,7 +983,8 @@ async function uploadCommand(files, options, globals, context) {
903
983
  filename: completed.filename,
904
984
  size: completed.size,
905
985
  url: completed.url ?? null,
906
- password_protected: Boolean(completed.password_protected)
986
+ password_protected: Boolean(completed.password_protected),
987
+ ...completed.expires_at !== void 0 && { expires_at: completed.expires_at }
907
988
  };
908
989
  } catch (error) {
909
990
  result = {
@@ -918,7 +999,8 @@ async function uploadCommand(files, options, globals, context) {
918
999
  }
919
1000
  results.push(result);
920
1001
  if (!options.json) {
921
- if (result.ok && result.url) context.stdout.write(`${result.url}\n`);
1002
+ if (result.ok && result.url && showSummary) context.stdout.write(`${summaries++ > 0 ? "\n" : ""}${summary(result, styledUrl(context.stdout, context.env, result.url), out)}`);
1003
+ else if (result.ok && result.url) context.stdout.write(`${result.url}\n`);
922
1004
  else if (result.ok) context.stderr.write(`${err.yellow(`${file}:`)} uploaded (id ${result.id}), but the server returned no share link.\n`);
923
1005
  else context.stderr.write(`${err.red(`${file}:`)} ${result.error}\n`);
924
1006
  }
@@ -1009,7 +1091,7 @@ function startUpdateCheck(context) {
1009
1091
  async function offerUpdate(context, version) {
1010
1092
  const color = colorsFor(context.stderr, context.env);
1011
1093
  const run = (command) => color.cyan(command);
1012
- context.stderr.write(version ? `\nUpdate available for filecafe (${color.gray(`v${VERSION}`)} → ${color.green(`v${version}`)})\nChangelog: ${color.cyan.underline(`${RELEASES_URL}/v${version}`)}\n` : "\nA newer version of filecafe may be available.\n");
1094
+ context.stderr.write(version ? `\nUpdate available for filecafe (${color.gray(`v${VERSION}`)} → ${color.green(`v${version}`)})\nChangelog: ${styledUrl(context.stderr, context.env, `${RELEASES_URL}/v${version}`)}\n` : "\nA newer version of filecafe may be available.\n");
1013
1095
  if (context.env.npm_command === "exec" || context.scriptPath.replaceAll("\\", "/").includes("/_npx/")) {
1014
1096
  context.stderr.write(`Run: ${run("npx filecafe@latest")}\n`);
1015
1097
  return;
@@ -1153,7 +1235,7 @@ function isNewer(candidate, current) {
1153
1235
  const MAIN_EXAMPLES = `
1154
1236
  Examples:
1155
1237
  $ filecafe login # log in via your browser (one time)
1156
- $ filecafe upload report.pdf # prints the share URL on stdout
1238
+ $ filecafe upload report.pdf # shows the share URL, size and expiry date
1157
1239
  $ filecafe upload a.png b.mp4 --json # machine-readable results (for scripts and AI agents)
1158
1240
  $ filecafe upload ./build.zip | pbcopy # copy the share URL to the clipboard
1159
1241
  $ FILECAFE_TOKEN=... npx filecafe upload notes.txt --json # CI / headless
@@ -1167,10 +1249,11 @@ Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
1167
1249
  `;
1168
1250
  const UPLOAD_EXAMPLES = `
1169
1251
  Output:
1170
- Default: one share URL per line on stdout, in the order the files were given.
1252
+ Terminal: a summary per file (share URL, size, expiry date).
1253
+ Piped or --quiet: one share URL per line on stdout, in the order the files were given.
1171
1254
  --json: a JSON array on stdout with one object per input file:
1172
- {"file": "a.png", "ok": true, "id": "...", "filename": "a.png",
1173
- "size": 1234, "url": "https://file.cafe/...", "password_protected": false}
1255
+ {"file": "a.png", "ok": true, "id": "...", "filename": "a.png", "size": 1234,
1256
+ "url": "https://file.cafe/...", "password_protected": false, "expires_at": "2026-11-07T12:00:00+00:00"}
1174
1257
  {"file": "b.png", "ok": false, "error": "No such file."}
1175
1258
  Exit code is 0 if every file uploaded, 1 if any failed.
1176
1259
 
@@ -108,7 +108,7 @@ async function resolveSettings(environment, urlOption) {
108
108
  };
109
109
  }
110
110
  // src/version.ts
111
- const VERSION = "0.3.3";
111
+ const VERSION = "0.3.5";
112
112
  // src/update-cache.ts
113
113
  const REGISTRY_URL = "https://registry.npmjs.org/filecafe/latest";
114
114
  /** Ask npm at most once a day. */
@@ -1,4 +1,4 @@
1
- import { i as refreshUpdateCache, s as VERSION } from "./update-cache-tQTolnAo.js";
1
+ import { i as refreshUpdateCache, s as VERSION } from "./update-cache-DPfI7tdr.js";
2
2
  // src/update-worker.ts
3
3
  /**
4
4
  * Spawned detached by the CLI to refresh the update cache, so no command ever waits on npm.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "filecafe",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
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",