filecafe 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # filecafe
2
2
 
3
- Upload files to [file.cafe](https://file.cafe) from the command line and get share links back.
3
+ Upload files to [file.cafe](https://file.cafe) from the command line and get share links back, or group them into a collection that shares them all on one page.
4
4
 
5
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
 
@@ -56,7 +56,8 @@ Settings → API tokens on file.cafe. `logout` revokes the token even if you sav
56
56
  filecafe upload screenshot.png # shows the share URL, size and expiry date
57
57
  filecafe upload a.png b.mp4 notes.txt # one summary per file, in order
58
58
  filecafe upload build.zip | pbcopy # piped: just the link, copied to the clipboard
59
- filecafe upload video.mp4 --collection <uuid> # add to a collection
59
+ filecafe upload video.mp4 --collection <uuid> # add to an existing collection
60
+ filecafe upload *.png --new-collection "Shots" # share them all on one collection page
60
61
  filecafe upload report.pdf --json # machine-readable output
61
62
  filecafe upload big.mov --quiet # no progress output
62
63
  ```
@@ -98,10 +99,134 @@ A single JSON array on stdout with one object per input file, in the order given
98
99
  ]
99
100
  ```
100
101
 
101
- `expires_at` is `null` for files that never expire.
102
+ `expires_at` is `null` for files that never expire. With `--new-collection` the output is an object instead; see [Collections](#collections).
102
103
 
103
104
  The exit code is `0` if every file uploaded and `1` if any failed.
104
105
 
106
+ ## Collections
107
+
108
+ A collection shares several files on one page, with one link (`https://file.cafe/c/...`). Each
109
+ file in it keeps its own share link too.
110
+
111
+ ```sh
112
+ filecafe upload shots/*.png --new-collection "Launch screenshots" # upload files into a new collection
113
+ filecafe collections create "Inbox" # make an empty collection
114
+ filecafe upload extra.png --collection <id> # add files to an existing one
115
+ filecafe collections # list your collections and their IDs
116
+ ```
117
+
118
+ Collection names can be up to 120 characters. Collections made from the CLI never expire, have no
119
+ password, and don't accept files from visitors. You can add a password or let visitors send files
120
+ (paid plans) from the collection's page on your file.cafe dashboard. A collection holds up to
121
+ 10,000 files.
122
+
123
+ ### Upload files into a new collection
124
+
125
+ ```sh
126
+ filecafe upload shots/*.png --new-collection "Launch screenshots"
127
+ ```
128
+
129
+ The files upload first, then one collection is created holding the ones that uploaded, in the order
130
+ you passed them. Any number of files works: the CLI adds them to the collection 100 at a time. In a
131
+ terminal you get the usual summary per file, followed by:
132
+
133
+ ```
134
+ Created collection Launch screenshots
135
+ URL: https://file.cafe/c/b7kfVweVXQM
136
+ Files: 12 files
137
+ ID: 01a1a9ea-a04d-70da-8786-d74d331a9720
138
+ ```
139
+
140
+ When piped or with `--quiet`, stdout is just the collection's URL, so
141
+ `filecafe upload *.png --new-collection "Shots" | pbcopy` copies the one link to share.
142
+
143
+ If some files fail to upload, the collection is still created from the rest and the command exits
144
+ with `1`. If no file uploads, no collection is created. `--new-collection` can't be combined with
145
+ `--collection`.
146
+
147
+ With `--json` the output is an object instead of an array:
148
+
149
+ ```json
150
+ {
151
+ "collection": {
152
+ "id": "01a1a9ea-a04d-70da-8786-d74d331a9720",
153
+ "name": "Launch screenshots",
154
+ "url": "https://file.cafe/c/b7kfVweVXQM",
155
+ "files_count": 12,
156
+ "password_protected": false,
157
+ "accepts_uploads": false,
158
+ "created_at": "2026-11-05T04:14:48+00:00",
159
+ "expires_at": null
160
+ },
161
+ "files": [ /* one object per input file, as in the upload --json output */ ]
162
+ }
163
+ ```
164
+
165
+ `collection` is `null` when no file uploaded or the collection couldn't be created, and a
166
+ `collection_error` field then says why. Files that uploaded keep their share links either way.
167
+
168
+ ### Create an empty collection
169
+
170
+ ```sh
171
+ filecafe collections create "Inbox"
172
+ ```
173
+
174
+ In a terminal this prints the new collection's URL and ID, and the command to upload into it.
175
+ When piped it prints one `id<TAB>name<TAB>url` line, so a script can create a collection and upload
176
+ into it straight away:
177
+
178
+ ```sh
179
+ id=$(filecafe collections create "Nightly builds" | cut -f1)
180
+ filecafe upload build.zip --collection "$id"
181
+ ```
182
+
183
+ Add `--json` to print the collection object (the same fields as above) instead.
184
+
185
+ ### Add files to an existing collection
186
+
187
+ ```sh
188
+ filecafe upload video.mp4 notes.txt --collection 01a1a9ea-a04d-70da-8786-d74d331a9720
189
+ ```
190
+
191
+ Pass the ID of one of your own collections. Files are added to the end of it. Get the ID from
192
+ `filecafe collections`, from `collections create`, or from the collection's address on your
193
+ dashboard.
194
+
195
+ ### List your collections
196
+
197
+ ```sh
198
+ filecafe collections # same as: filecafe collections list
199
+ filecafe collections --json
200
+ ```
201
+
202
+ Collections are listed newest first. In a terminal:
203
+
204
+ ```
205
+ Launch screenshots (12 files)
206
+ URL: https://file.cafe/c/b7kfVweVXQM
207
+ ID: 01a1a9ea-a04d-70da-8786-d74d331a9720
208
+
209
+ Client review (3 files, expires November 21st 2026, password)
210
+ URL: https://file.cafe/c/gChBn26axib
211
+ ID: 01a1a9ea-9c07-7226-8553-97ac44eb759c
212
+ ```
213
+
214
+ When piped there's one `id<TAB>name<TAB>url` line per collection, and `--json` prints an array of
215
+ collection objects.
216
+
217
+ ### Collection fields
218
+
219
+ | Field | Meaning |
220
+ | --- | --- |
221
+ | `id` | The collection's ID, for `upload --collection` |
222
+ | `name` | Its name |
223
+ | `url` | The link that shares the whole collection |
224
+ | `files_count` | Files currently in it (expired and deleted files don't count) |
225
+ | `password_protected` | Whether the collection page needs a password |
226
+ | `accepts_uploads` | Whether visitors can send files to it (set on file.cafe) |
227
+ | `created_at` | When it was created (ISO 8601) |
228
+ | `expires_at` | When its link stops working (ISO 8601), or `null` if it never expires |
229
+
105
230
  ## Configuration
106
231
 
107
232
  | Setting | How to set | Default |
@@ -127,11 +252,12 @@ To share a file with the user (screenshots, build artifacts, logs, exports), run
127
252
  npx -y filecafe upload <path> --json
128
253
 
129
254
  and give the user the `url` from the JSON output. Upload several files at once by passing
130
- multiple paths. If the command fails with "Not logged in", ask the user to run
255
+ multiple paths. To share several files on one page, add `--new-collection "<name>"` and give
256
+ the user `collection.url` instead. If the command fails with "Not logged in", ask the user to run
131
257
  `npx filecafe login` (or set `FILECAFE_TOKEN`) and then try again.
132
258
  ```
133
259
 
134
- Agents can run `filecafe --help` and `filecafe upload --help` to see every option with examples.
260
+ Agents can run `filecafe --help`, `filecafe upload --help` and `filecafe collections --help` to see every option with examples.
135
261
 
136
262
  ## Development
137
263
 
package/dist/cli.js CHANGED
@@ -1,10 +1,10 @@
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-DPfI7tdr.js";
2
+ import { a as updateCachePath, c as configPath, d as readConfig, f as resolveSettings, l as deleteConfig, m as VERSION, n as fetchLatestVersion, o as updateUpdateCache, p as writeConfig, r as readUpdateCache, t as CHECK_INTERVAL_MS, u as normalizeBaseUrl } from "./update-cache-INu00cnB.js";
3
3
  import { Command } from "commander";
4
- import { homedir, hostname, tmpdir } from "node:os";
4
+ import { execFile, spawn } from "node:child_process";
5
5
  import { realpath, stat } from "node:fs/promises";
6
+ import { homedir, hostname, tmpdir } from "node:os";
6
7
  import { basename, extname, join, sep } from "node:path";
7
- import { execFile, spawn } from "node:child_process";
8
8
  import { createInterface } from "node:readline/promises";
9
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { fileURLToPath } from "node:url";
@@ -140,6 +140,72 @@ async function fetchMe(client) {
140
140
  email: me.email
141
141
  };
142
142
  }
143
+ /** Collections the server returns per page of GET /api/v1/collections. */
144
+ const COLLECTIONS_PER_PAGE = 100;
145
+ /** Stop paging after this many pages, in case a server never returns a short page. */
146
+ const MAX_PAGES = 100;
147
+ function isRecord$1(value) {
148
+ return typeof value === "object" && value !== null && !Array.isArray(value);
149
+ }
150
+ function toCollection(value, what) {
151
+ if (!isRecord$1(value) || typeof value.id !== "string" || typeof value.url !== "string") throw new ApiError(`Unexpected response when ${what}.`, null);
152
+ return {
153
+ id: value.id,
154
+ name: typeof value.name === "string" ? value.name : "",
155
+ url: value.url,
156
+ files_count: typeof value.files_count === "number" ? value.files_count : 0,
157
+ password_protected: value.password_protected === true,
158
+ accepts_uploads: value.accepts_uploads === true,
159
+ created_at: typeof value.created_at === "string" ? value.created_at : null,
160
+ expires_at: typeof value.expires_at === "string" ? value.expires_at : null
161
+ };
162
+ }
163
+ /** A trimmed collection name, or an error message when it is empty or too long. */
164
+ function validateCollectionName(name) {
165
+ const trimmed = name.trim();
166
+ if (!trimmed) return { error: "The collection name cannot be empty." };
167
+ if (Array.from(trimmed).length > 120) return { error: `The collection name must be at most 120 characters.` };
168
+ return { name: trimmed };
169
+ }
170
+ /** Every collection the token's account owns, newest first. */
171
+ async function listCollections(client) {
172
+ const collections = [];
173
+ for (let page = 1; page <= MAX_PAGES; page++) {
174
+ const data = await client.request("GET", `/api/v1/collections?page=${page}`, void 0, { idempotent: true });
175
+ if (!Array.isArray(data)) throw new ApiError("Unexpected response when listing collections.", null);
176
+ collections.push(...data.map((entry) => toCollection(entry, "listing collections")));
177
+ if (data.length < COLLECTIONS_PER_PAGE) break;
178
+ }
179
+ return collections;
180
+ }
181
+ /**
182
+ * Create a collection holding `fileIds` in order, or an empty one to upload into later. The first
183
+ * 100 files go with the create request and the rest are added 100 at a time, so a collection can
184
+ * hold more than one request's worth.
185
+ */
186
+ async function createCollection(client, name, fileIds = []) {
187
+ const created = toCollection(await client.request("POST", "/api/v1/collections", {
188
+ name,
189
+ ...fileIds.length > 0 && { file_ids: fileIds.slice(0, 100) }
190
+ }), "creating the collection");
191
+ let collection = created;
192
+ for (let start = 100; start < fileIds.length; start += 100) try {
193
+ collection = toCollection(await client.request("POST", `/api/v1/collections/${encodeURIComponent(created.id)}/files`, { file_ids: fileIds.slice(start, start + 100) }, { idempotent: true }), "adding files to the collection");
194
+ } catch (error) {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ throw new CollectionIncompleteError(`Created ${created.url}, but adding files ${start + 1}-${Math.min(start + 100, fileIds.length)} failed: ${message}`, collection);
197
+ }
198
+ return collection;
199
+ }
200
+ /** The collection was created but not every file made it in. */
201
+ var CollectionIncompleteError = class extends Error {
202
+ collection;
203
+ constructor(message, collection) {
204
+ super(message);
205
+ this.name = "CollectionIncompleteError";
206
+ this.collection = collection;
207
+ }
208
+ };
143
209
  // src/context.ts
144
210
  /** Open a URL in the default browser without ever throwing. */
145
211
  function openBrowser(url, platform = process.platform) {
@@ -378,113 +444,6 @@ function startSpinner(stream, text, env, platform) {
378
444
  }
379
445
  } };
380
446
  }
381
- // src/commands/login.ts
382
- async function readAll(input) {
383
- let text = "";
384
- for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
385
- return text;
386
- }
387
- const EXPIRED_MESSAGE = "The login code expired before it was approved. Run \"filecafe login\" again.";
388
- function isStartedLogin(value) {
389
- if (!value || typeof value !== "object") return false;
390
- const login = value;
391
- 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";
392
- }
393
- /**
394
- * Ask where the login stands, treating a dropped connection or server hiccup
395
- * as "still pending" so one bad poll does not end the login.
396
- */
397
- async function pollLogin(client, deviceCode) {
398
- try {
399
- return await client.request("POST", "/api/v1/cli/logins/token", { device_code: deviceCode });
400
- } catch (error) {
401
- if (error instanceof ApiError && (error.status === null || error.status >= 500)) return { status: "pending" };
402
- throw error;
403
- }
404
- }
405
- /**
406
- * Start a login on file.cafe, show its code, and poll until it is approved in
407
- * the browser. The token only exists once this collects it, and nothing
408
- * listens on a local port, so it works over SSH too.
409
- */
410
- async function tokenFromBrowser(context, baseUrl) {
411
- const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
412
- const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
413
- if (!isStartedLogin(login)) throw new CliError(`Unexpected response from ${baseUrl} when starting the login. Check the --url option / FILECAFE_URL.`);
414
- const color = colorsFor(context.stderr, context.env);
415
- const link = color.cyan(supportsHyperlinks(context.stderr, context.env) ? hyperlink(login.verification_uri, login.verification_uri_complete) : login.verification_uri);
416
- context.stderr.write(`Your one-time code: ${color.bold(login.user_code)}\n\nOpening your browser to approve this login. Check that the code there matches.\nIf it does not open, visit ${link} and enter the code.\n\n`);
417
- context.openBrowser(login.verification_uri_complete);
418
- const spinner = startSpinner(context.stderr, "Waiting for approval...", context.env, context.platform);
419
- const intervalMs = Math.max(login.interval, 1) * 1e3;
420
- const deadline = context.now() + login.expires_in * 1e3;
421
- try {
422
- while (context.now() < deadline) {
423
- await context.sleep(Math.min(intervalMs, deadline - context.now()));
424
- const result = await pollLogin(client, login.device_code);
425
- switch (result.status) {
426
- case "approved": return result.token;
427
- case "denied": throw new CliError("Login was cancelled in the browser.");
428
- case "expired": throw new CliError(EXPIRED_MESSAGE);
429
- }
430
- }
431
- throw new CliError(EXPIRED_MESSAGE);
432
- } finally {
433
- spinner.stop();
434
- }
435
- }
436
- async function loginCommand(options, globals, context) {
437
- if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
438
- let baseUrl;
439
- try {
440
- baseUrl = normalizeBaseUrl(globals.url || context.env.FILECAFE_URL || "https://file.cafe");
441
- } catch (error) {
442
- throw new CliError(error.message);
443
- }
444
- let token;
445
- if (options.token !== void 0) token = options.token.trim();
446
- else if (options.withToken) {
447
- if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
448
- token = (await readAll(context.stdin)).trim();
449
- } else token = await tokenFromBrowser(context, baseUrl);
450
- if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
451
- let me;
452
- try {
453
- me = await fetchMe(clientFor(context, baseUrl, token));
454
- } catch (error) {
455
- if (error.status === 401) throw new CliError(`That token was rejected by ${baseUrl}. Check that it is correct and has not been revoked.`);
456
- throw new CliError(error.message);
457
- }
458
- await writeConfig(context, {
459
- url: baseUrl,
460
- token
461
- });
462
- const out = colorsFor(context.stdout, context.env);
463
- const err = colorsFor(context.stderr, context.env);
464
- context.stdout.write(`${out.green("Logged in")} as ${out.bold(me.name)} (${me.email})\n`);
465
- context.stderr.write(`${err.gray(`Saved credentials for ${baseUrl} to ${configPath(context)}`)}\n`);
466
- if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n`);
467
- const next = err.level > 0 ? err.cyan("filecafe upload <file>") : "\"filecafe upload <file>\"";
468
- context.stderr.write(`\nRun ${next} to share a file.\n`);
469
- return 0;
470
- }
471
- // src/commands/logout.ts
472
- async function logoutCommand(context) {
473
- const saved = await readConfig(context).catch(() => null);
474
- const out = colorsFor(context.stdout, context.env);
475
- const err = colorsFor(context.stderr, context.env);
476
- if (saved) try {
477
- await clientFor(context, saved.url, saved.token).request("DELETE", "/api/v1/token", void 0, { idempotent: true });
478
- } catch (error) {
479
- if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`${err.yellow("Could not revoke the token")} on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
480
- }
481
- if (await deleteConfig(context)) {
482
- context.stdout.write(saved ? `${out.green("Logged out")} of ${saved.url}.\n` : `${out.green("Logged out")}.\n`);
483
- context.stderr.write(`${err.gray(`Removed ${configPath(context)}`)}\n`);
484
- } else context.stdout.write("Not logged in; nothing to do.\n");
485
- if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n`);
486
- return 0;
487
- }
488
447
  // src/mime.ts
489
448
  /**
490
449
  * A deliberately small extension → MIME type map. The server re-detects the
@@ -641,7 +600,7 @@ function isSignedTarget(value) {
641
600
  function planTransfer(upload, size) {
642
601
  const unexpected = (detail) => new ApiError(`Unexpected response when starting the upload: ${detail}.`, null);
643
602
  const data = upload;
644
- if (!isRecord(data) || typeof data.id !== "string" || typeof data.token !== "string") throw unexpected("missing id or token");
603
+ if (!isRecord(data) || typeof data.id !== "string") throw unexpected("missing id");
645
604
  if ("parts" in data) {
646
605
  const { parts, part_size: partSize } = data;
647
606
  if (typeof partSize !== "number" || !Number.isSafeInteger(partSize) || partSize <= 0) throw unexpected("invalid part_size");
@@ -773,13 +732,12 @@ async function uploadFile(options) {
773
732
  }
774
733
  });
775
734
  });
776
- return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, { token: partUrls.token() }, { idempotent: true });
735
+ return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, void 0, { idempotent: true });
777
736
  }
778
737
  /**
779
738
  * The URL for each part of an upload, in batches of PART_URL_BATCH_SIZE. The first batch comes
780
739
  * 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.
740
+ * when a part in them is about to be uploaded. Each fetch also renews the upload's expiry.
783
741
  */
784
742
  function createPartUrls(options, started, targets) {
785
743
  const now = options.now ?? Date.now;
@@ -787,39 +745,31 @@ function createPartUrls(options, started, targets) {
787
745
  fetchedAt: now(),
788
746
  targets: Promise.resolve(targets.slice(0, PART_URL_BATCH_SIZE))
789
747
  }]]);
790
- let token = started.token;
791
748
  const fetchBatch = async (batch) => {
792
749
  const first = batch * PART_URL_BATCH_SIZE + 1;
793
750
  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 });
751
+ const response = await options.client.request("POST", `/api/v1/uploads/${encodeURIComponent(started.id)}/parts`, { part_numbers: partNumbers }, { idempotent: true });
798
752
  const parts = isRecord(response) && Array.isArray(response.parts) ? response.parts : [];
799
753
  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;
754
+ if (!fresh.every(isSignedTarget)) throw new ApiError("Unexpected response when fetching upload URLs.", null);
802
755
  return fresh.map((part) => ({
803
756
  url: part.url,
804
757
  headers: part.headers
805
758
  }));
806
759
  };
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
- };
760
+ return { async target(index) {
761
+ if (!("parts" in started)) return targets[index];
762
+ const batch = Math.floor(index / PART_URL_BATCH_SIZE);
763
+ let entry = batches.get(batch);
764
+ if (!entry || now() - entry.fetchedAt > PART_URL_MAX_AGE_MS) {
765
+ entry = {
766
+ fetchedAt: now(),
767
+ targets: fetchBatch(batch)
768
+ };
769
+ batches.set(batch, entry);
770
+ }
771
+ return (await entry.targets)[index % PART_URL_BATCH_SIZE];
772
+ } };
823
773
  }
824
774
  // src/commands/upload.ts
825
775
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -846,6 +796,16 @@ function formatExpiry(iso) {
846
796
  }[new Intl.PluralRules("en-US", { type: "ordinal" }).select(day)] ?? "th";
847
797
  return `${date.toLocaleString("en-US", { month: "long" })} ${day}${suffix} ${date.getFullYear()}`;
848
798
  }
799
+ function collectionSummary(collection, url, color) {
800
+ const files = `${collection.files_count} ${collection.files_count === 1 ? "file" : "files"}`;
801
+ return [
802
+ `${color.green("Created collection")} ${color.bold(collection.name)}`,
803
+ `${color.gray("URL:")} ${url}`,
804
+ `${color.gray("Files:")} ${files}`,
805
+ `${color.gray("ID:")} ${collection.id}`,
806
+ ""
807
+ ].join("\n");
808
+ }
849
809
  function summary(result, url, color) {
850
810
  const lines = [
851
811
  `${color.green("Successfully uploaded")} ${color.bold(result.filename)}`,
@@ -920,6 +880,13 @@ function createProgress(context, enabled) {
920
880
  }
921
881
  async function uploadCommand(files, options, globals, context) {
922
882
  if (options.collection !== void 0 && !UUID_PATTERN.test(options.collection)) throw new CliError(`Invalid --collection "${options.collection}". Expected a collection UUID.`);
883
+ let newCollectionName;
884
+ if (options.newCollection !== void 0) {
885
+ if (options.collection !== void 0) throw new CliError("Use either --collection or --new-collection, not both.");
886
+ const checked = validateCollectionName(options.newCollection);
887
+ if ("error" in checked) throw new CliError(`Invalid --new-collection: ${checked.error}`);
888
+ newCollectionName = checked.name;
889
+ }
923
890
  if (files.length === 0) throw new CliError("No files given. Usage: filecafe upload <files...>");
924
891
  const showProgress = Boolean(context.stderr.isTTY) && !options.json && !options.quiet;
925
892
  const err = colorsFor(context.stderr, context.env);
@@ -937,6 +904,9 @@ async function uploadCommand(files, options, globals, context) {
937
904
  const checked = await Promise.all(files.map(validateFile));
938
905
  const invalid = checked.filter((entry) => "error" in entry);
939
906
  const results = [];
907
+ let collection = null;
908
+ let collectionError = null;
909
+ const printFileUrls = newCollectionName === void 0 || showSummary;
940
910
  if (invalid.length > 0) for (const entry of checked) results.push({
941
911
  file: entry.file,
942
912
  ok: false,
@@ -1000,18 +970,206 @@ async function uploadCommand(files, options, globals, context) {
1000
970
  results.push(result);
1001
971
  if (!options.json) {
1002
972
  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`);
1004
- else if (result.ok) context.stderr.write(`${err.yellow(`${file}:`)} uploaded (id ${result.id}), but the server returned no share link.\n`);
973
+ else if (result.ok && result.url) {
974
+ if (printFileUrls) context.stdout.write(`${result.url}\n`);
975
+ } else if (result.ok) context.stderr.write(`${err.yellow(`${file}:`)} uploaded (id ${result.id}), but the server returned no share link.\n`);
1005
976
  else context.stderr.write(`${err.red(`${file}:`)} ${result.error}\n`);
1006
977
  }
1007
978
  }
1008
979
  }
1009
- if (options.json) context.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
980
+ if (newCollectionName !== void 0 && invalid.length === 0) {
981
+ const uploadedIds = results.flatMap((result) => result.ok ? [result.id] : []);
982
+ if (uploadedIds.length === 0) collectionError = "No files were uploaded, so the collection was not created.";
983
+ else {
984
+ progress.update(`Creating collection ${err.bold(newCollectionName)}...`);
985
+ try {
986
+ collection = await createCollection(client, newCollectionName, uploadedIds);
987
+ } catch (error) {
988
+ if (error instanceof CollectionIncompleteError) collection = error.collection;
989
+ collectionError = error instanceof Error ? error.message : String(error);
990
+ } finally {
991
+ progress.clear();
992
+ }
993
+ }
994
+ if (!options.json) {
995
+ if (collection && showSummary) context.stdout.write(`${summaries > 0 ? "\n" : ""}${collectionSummary(collection, styledUrl(context.stdout, context.env, collection.url), out)}`);
996
+ else if (collection) context.stdout.write(`${collection.url}\n`);
997
+ if (collectionError !== null) context.stderr.write(`${err.red("Collection:")} ${collectionError}\n`);
998
+ else if (results.some((result) => !result.ok)) context.stderr.write(`${err.yellow("Collection:")} created without the files that failed to upload.\n`);
999
+ }
1000
+ }
1001
+ if (options.json && newCollectionName !== void 0) {
1002
+ const output = {
1003
+ collection,
1004
+ ...collectionError !== null && { collection_error: collectionError },
1005
+ files: results
1006
+ };
1007
+ context.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
1008
+ } else if (options.json) context.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
1010
1009
  else if (invalid.length > 0) {
1011
1010
  for (const entry of invalid) context.stderr.write(`${err.red(`${entry.file}:`)} ${entry.error}\n`);
1012
1011
  context.stderr.write(`${err.red("Nothing was uploaded.")}\n`);
1013
1012
  }
1014
- return results.every((result) => result.ok) ? 0 : 1;
1013
+ return results.every((result) => result.ok) && collectionError === null ? 0 : 1;
1014
+ }
1015
+ // src/commands/collections.ts
1016
+ /** Tabs and newlines in a name would break the tab-separated output. */
1017
+ function oneLine(value) {
1018
+ return value.replace(/\s+/g, " ").trim();
1019
+ }
1020
+ /** Create an empty collection, to upload into later with --collection. */
1021
+ async function createCollectionCommand(name, options, globals, context) {
1022
+ const checked = validateCollectionName(name);
1023
+ if ("error" in checked) throw new CliError(checked.error);
1024
+ const notice = (message) => context.stderr.write(`${message}\n`);
1025
+ const { client } = await requireSession(context, globals, notice);
1026
+ const collection = await createCollection(client, checked.name);
1027
+ if (options.json) context.stdout.write(`${JSON.stringify(collection, null, 2)}\n`);
1028
+ else if (context.stdout.isTTY) {
1029
+ context.stdout.write(collectionSummary(collection, styledUrl(context.stdout, context.env, collection.url), colorsFor(context.stdout, context.env)));
1030
+ context.stderr.write(`${colorsFor(context.stderr, context.env).gray(`Upload into it with: filecafe upload <files...> --collection ${collection.id}`)}\n`);
1031
+ } else context.stdout.write(`${collection.id}\t${oneLine(collection.name)}\t${collection.url}\n`);
1032
+ return 0;
1033
+ }
1034
+ async function collectionsCommand(options, globals, context) {
1035
+ const notice = (message) => context.stderr.write(`${message}\n`);
1036
+ const { client } = await requireSession(context, globals, notice);
1037
+ const collections = await listCollections(client);
1038
+ if (options.json) {
1039
+ context.stdout.write(`${JSON.stringify(collections, null, 2)}\n`);
1040
+ return 0;
1041
+ }
1042
+ const err = colorsFor(context.stderr, context.env);
1043
+ if (collections.length === 0) {
1044
+ context.stderr.write(`No collections yet. ${err.gray("Create one with: filecafe collections create <name>, or filecafe upload <files...> --new-collection <name>")}\n`);
1045
+ return 0;
1046
+ }
1047
+ if (!context.stdout.isTTY) {
1048
+ for (const collection of collections) context.stdout.write(`${collection.id}\t${oneLine(collection.name)}\t${collection.url}\n`);
1049
+ return 0;
1050
+ }
1051
+ const out = colorsFor(context.stdout, context.env);
1052
+ context.stdout.write(collections.map((collection) => {
1053
+ const details = [
1054
+ `${collection.files_count} ${collection.files_count === 1 ? "file" : "files"}`,
1055
+ ...collection.expires_at ? [`expires ${formatExpiry(collection.expires_at)}`] : [],
1056
+ ...collection.password_protected ? ["password"] : [],
1057
+ ...collection.accepts_uploads ? ["accepts uploads"] : []
1058
+ ];
1059
+ return [
1060
+ `${out.bold(oneLine(collection.name))} ${out.gray(`(${details.join(", ")})`)}`,
1061
+ ` ${out.gray("URL:")} ${styledUrl(context.stdout, context.env, collection.url)}`,
1062
+ ` ${out.gray("ID:")} ${collection.id}`
1063
+ ].join("\n");
1064
+ }).join("\n\n") + "\n");
1065
+ return 0;
1066
+ }
1067
+ // src/commands/login.ts
1068
+ async function readAll(input) {
1069
+ let text = "";
1070
+ for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
1071
+ return text;
1072
+ }
1073
+ const EXPIRED_MESSAGE = "The login code expired before it was approved. Run \"filecafe login\" again.";
1074
+ function isStartedLogin(value) {
1075
+ if (!value || typeof value !== "object") return false;
1076
+ const login = value;
1077
+ 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";
1078
+ }
1079
+ /**
1080
+ * Ask where the login stands, treating a dropped connection or server hiccup
1081
+ * as "still pending" so one bad poll does not end the login.
1082
+ */
1083
+ async function pollLogin(client, deviceCode) {
1084
+ try {
1085
+ return await client.request("POST", "/api/v1/cli/logins/token", { device_code: deviceCode });
1086
+ } catch (error) {
1087
+ if (error instanceof ApiError && (error.status === null || error.status >= 500)) return { status: "pending" };
1088
+ throw error;
1089
+ }
1090
+ }
1091
+ /**
1092
+ * Start a login on file.cafe, show its code, and poll until it is approved in
1093
+ * the browser. The token only exists once this collects it, and nothing
1094
+ * listens on a local port, so it works over SSH too.
1095
+ */
1096
+ async function tokenFromBrowser(context, baseUrl) {
1097
+ const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
1098
+ const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
1099
+ if (!isStartedLogin(login)) throw new CliError(`Unexpected response from ${baseUrl} when starting the login. Check the --url option / FILECAFE_URL.`);
1100
+ const color = colorsFor(context.stderr, context.env);
1101
+ const link = color.cyan(supportsHyperlinks(context.stderr, context.env) ? hyperlink(login.verification_uri, login.verification_uri_complete) : login.verification_uri);
1102
+ context.stderr.write(`Your one-time code: ${color.bold(login.user_code)}\n\nOpening your browser to approve this login. Check that the code there matches.\nIf it does not open, visit ${link} and enter the code.\n\n`);
1103
+ context.openBrowser(login.verification_uri_complete);
1104
+ const spinner = startSpinner(context.stderr, "Waiting for approval...", context.env, context.platform);
1105
+ const intervalMs = Math.max(login.interval, 1) * 1e3;
1106
+ const deadline = context.now() + login.expires_in * 1e3;
1107
+ try {
1108
+ while (context.now() < deadline) {
1109
+ await context.sleep(Math.min(intervalMs, deadline - context.now()));
1110
+ const result = await pollLogin(client, login.device_code);
1111
+ switch (result.status) {
1112
+ case "approved": return result.token;
1113
+ case "denied": throw new CliError("Login was cancelled in the browser.");
1114
+ case "expired": throw new CliError(EXPIRED_MESSAGE);
1115
+ }
1116
+ }
1117
+ throw new CliError(EXPIRED_MESSAGE);
1118
+ } finally {
1119
+ spinner.stop();
1120
+ }
1121
+ }
1122
+ async function loginCommand(options, globals, context) {
1123
+ if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
1124
+ let baseUrl;
1125
+ try {
1126
+ baseUrl = normalizeBaseUrl(globals.url || context.env.FILECAFE_URL || "https://file.cafe");
1127
+ } catch (error) {
1128
+ throw new CliError(error.message);
1129
+ }
1130
+ let token;
1131
+ if (options.token !== void 0) token = options.token.trim();
1132
+ else if (options.withToken) {
1133
+ if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
1134
+ token = (await readAll(context.stdin)).trim();
1135
+ } else token = await tokenFromBrowser(context, baseUrl);
1136
+ if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
1137
+ let me;
1138
+ try {
1139
+ me = await fetchMe(clientFor(context, baseUrl, token));
1140
+ } catch (error) {
1141
+ if (error.status === 401) throw new CliError(`That token was rejected by ${baseUrl}. Check that it is correct and has not been revoked.`);
1142
+ throw new CliError(error.message);
1143
+ }
1144
+ await writeConfig(context, {
1145
+ url: baseUrl,
1146
+ token
1147
+ });
1148
+ const out = colorsFor(context.stdout, context.env);
1149
+ const err = colorsFor(context.stderr, context.env);
1150
+ context.stdout.write(`${out.green("Logged in")} as ${out.bold(me.name)} (${me.email})\n`);
1151
+ context.stderr.write(`${err.gray(`Saved credentials for ${baseUrl} to ${configPath(context)}`)}\n`);
1152
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n`);
1153
+ const next = err.level > 0 ? err.cyan("filecafe upload <file>") : "\"filecafe upload <file>\"";
1154
+ context.stderr.write(`\nRun ${next} to share a file.\n`);
1155
+ return 0;
1156
+ }
1157
+ // src/commands/logout.ts
1158
+ async function logoutCommand(context) {
1159
+ const saved = await readConfig(context).catch(() => null);
1160
+ const out = colorsFor(context.stdout, context.env);
1161
+ const err = colorsFor(context.stderr, context.env);
1162
+ if (saved) try {
1163
+ await clientFor(context, saved.url, saved.token).request("DELETE", "/api/v1/token", void 0, { idempotent: true });
1164
+ } catch (error) {
1165
+ if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`${err.yellow("Could not revoke the token")} on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
1166
+ }
1167
+ if (await deleteConfig(context)) {
1168
+ context.stdout.write(saved ? `${out.green("Logged out")} of ${saved.url}.\n` : `${out.green("Logged out")}.\n`);
1169
+ context.stderr.write(`${err.gray(`Removed ${configPath(context)}`)}\n`);
1170
+ } else context.stdout.write("Not logged in; nothing to do.\n");
1171
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write(`${err.yellow("Note:")} FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n`);
1172
+ return 0;
1015
1173
  }
1016
1174
  // src/commands/whoami.ts
1017
1175
  async function whoamiCommand(options, globals, context) {
@@ -1238,6 +1396,9 @@ Examples:
1238
1396
  $ filecafe upload report.pdf # shows the share URL, size and expiry date
1239
1397
  $ filecafe upload a.png b.mp4 --json # machine-readable results (for scripts and AI agents)
1240
1398
  $ filecafe upload ./build.zip | pbcopy # copy the share URL to the clipboard
1399
+ $ filecafe upload *.png --new-collection "Screenshots" # share several files on one page
1400
+ $ filecafe collections # list your collections and their IDs
1401
+ $ filecafe collections create "Inbox" # an empty collection to upload into with --collection
1241
1402
  $ FILECAFE_TOKEN=... npx filecafe upload notes.txt --json # CI / headless
1242
1403
 
1243
1404
  Environment:
@@ -1257,10 +1418,17 @@ Output:
1257
1418
  {"file": "b.png", "ok": false, "error": "No such file."}
1258
1419
  Exit code is 0 if every file uploaded, 1 if any failed.
1259
1420
 
1421
+ With --new-collection, the files are uploaded first, then one collection is created holding
1422
+ the ones that uploaded. Piped or --quiet output is just the collection's URL, and --json prints
1423
+ {"collection": {"id", "name", "url", "files_count", ...} or null, "files": [...as above]},
1424
+ plus "collection_error" if the collection could not be created. Exit code 1 if any file or
1425
+ the collection failed.
1426
+
1260
1427
  Examples:
1261
1428
  $ filecafe upload screenshot.png
1262
1429
  $ filecafe upload report.pdf data.csv --json
1263
1430
  $ filecafe upload video.mp4 --collection 0b6f9a2e-3c1d-4f7a-9e5b-2d8c4a1f6e3b
1431
+ $ filecafe upload shots/*.png --new-collection "Launch screenshots"
1264
1432
  $ filecafe upload build.zip --quiet | pbcopy
1265
1433
  $ FILECAFE_TOKEN=... filecafe upload logs.txt --json # no saved login needed
1266
1434
  `;
@@ -1292,7 +1460,10 @@ function createProgram(context) {
1292
1460
  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)));
1293
1461
  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)));
1294
1462
  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)));
1295
- 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 }));
1463
+ 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 existing collection (see \"filecafe collections\")").option("--new-collection <name>", "create a collection with this name holding the uploaded files").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 }));
1464
+ const collections = program.command("collections").description("List or create collections (upload --collection <id> adds files to one)");
1465
+ collections.command("list", { isDefault: true }).description("List your collections, newest first").option("--json", "print a JSON array of collections on stdout").addHelpText("after", "\nOutput:\n Terminal: name, file count, URL and ID per collection.\n Piped: one \"id<TAB>name<TAB>url\" line per collection.\n --json: [{\"id\", \"name\", \"url\", \"files_count\", \"password_protected\", \"accepts_uploads\", \"created_at\", \"expires_at\"}]\n\nExamples:\n $ filecafe collections\n $ filecafe collections --json\n").action((options, command) => execute(context, () => collectionsCommand(options, globals(command), context)));
1466
+ collections.command("create").description("Create an empty collection to upload into with upload --collection").argument("<name>", "the collection name (at most 120 characters)").option("--json", "print the new collection as JSON on stdout").addHelpText("after", "\nOutput:\n Terminal: the collection URL and ID.\n Piped: one \"id<TAB>name<TAB>url\" line.\n --json: {\"id\", \"name\", \"url\", \"files_count\", \"password_protected\", \"accepts_uploads\", \"created_at\", \"expires_at\"}\n\nExamples:\n $ filecafe collections create \"Inbox\"\n $ id=$(filecafe collections create \"Builds\" | cut -f1)\n $ filecafe upload build.zip --collection \"$id\"\n").action((name, options, command) => execute(context, () => createCollectionCommand(name, options, globals(command), context)));
1296
1467
  return program;
1297
1468
  }
1298
1469
  await createProgram(createDefaultContext()).parseAsync(process.argv);
@@ -1,7 +1,9 @@
1
- import "node:os";
2
1
  import { chmod, link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
2
+ import "node:os";
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
+ // src/version.ts
6
+ const VERSION = "0.4.1";
5
7
  // src/config.ts
6
8
  const DEFAULT_BASE_URL = "https://file.cafe";
7
9
  /**
@@ -107,8 +109,6 @@ async function resolveSettings(environment, urlOption) {
107
109
  saved
108
110
  };
109
111
  }
110
- // src/version.ts
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. */
@@ -259,4 +259,4 @@ function isRunning(pid) {
259
259
  return error.code === "EPERM";
260
260
  }
261
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 };
262
+ export { updateCachePath as a, configPath as c, readConfig as d, resolveSettings as f, refreshUpdateCache as i, deleteConfig as l, VERSION as m, fetchLatestVersion as n, updateUpdateCache as o, writeConfig as p, readUpdateCache as r, DEFAULT_BASE_URL as s, CHECK_INTERVAL_MS as t, normalizeBaseUrl as u };
@@ -1,4 +1,4 @@
1
- import { i as refreshUpdateCache, s as VERSION } from "./update-cache-DPfI7tdr.js";
1
+ import { i as refreshUpdateCache, m as VERSION } from "./update-cache-INu00cnB.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.5",
3
+ "version": "0.4.1",
4
4
  "description": "Upload files to file.cafe from the command line. Built for AI coding agents, humans, and CI.",
5
5
  "keywords": [
6
6
  "file.cafe",