filecafe 0.3.2 → 0.3.4

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/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-BDT0cPCo.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-BOFin4Gp.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";
@@ -607,18 +607,22 @@ function guessMimeType(filename) {
607
607
  /** An error while transferring bytes to the upload server. */
608
608
  var TransferError = class extends Error {
609
609
  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) {
610
+ constructor(message, status) {
613
611
  super(message);
614
612
  this.name = "TransferError";
615
613
  this.status = status;
616
- this.restartUpload = restartUpload;
617
614
  }
618
615
  };
619
616
  const DEFAULT_CONCURRENCY = 4;
620
617
  const DEFAULT_PART_RETRIES = 3;
621
618
  const DEFAULT_PART_TIMEOUT_MS = 9e5;
619
+ /**
620
+ * Multipart uploads use the start response's URLs for the first batch of parts and fetch each
621
+ * later batch just before uploading it, so a long upload never sends a part to an expired URL.
622
+ */
623
+ const PART_URL_BATCH_SIZE = 50;
624
+ /** Fetch a batch's URLs again once they are this old. file.cafe signs them for two hours. */
625
+ const PART_URL_MAX_AGE_MS = 36e5;
622
626
  function isRecord(value) {
623
627
  return typeof value === "object" && value !== null && !Array.isArray(value);
624
628
  }
@@ -660,19 +664,31 @@ function describeFetchError(error) {
660
664
  }
661
665
  return String(error);
662
666
  }
663
- /** PUT one byte range, retrying network errors and 5xx responses. Returns the upload receipt. */
667
+ /** PUT one byte range, retrying network errors and 5xx responses. */
664
668
  async function putPart(target, body, options) {
665
669
  for (let attempt = 0;; attempt++) {
666
670
  options.signal.throwIfAborted();
671
+ let sent = 0;
672
+ const counted = body.stream().pipeThrough(new TransformStream({ transform(chunk, controller) {
673
+ sent += chunk.byteLength;
674
+ options.onBytes?.(chunk.byteLength);
675
+ controller.enqueue(chunk);
676
+ } }));
677
+ const failed = () => options.onBytes?.(-sent);
667
678
  let response;
668
679
  try {
669
680
  response = await options.fetch(target.url, {
670
681
  method: "PUT",
671
- headers: target.headers,
672
- body,
682
+ headers: {
683
+ ...target.headers,
684
+ "Content-Length": String(body.size)
685
+ },
686
+ body: counted,
687
+ duplex: "half",
673
688
  signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
674
689
  });
675
690
  } catch (error) {
691
+ failed();
676
692
  if (options.signal.aborted) throw options.signal.reason;
677
693
  if (attempt < options.maxRetries) {
678
694
  await options.sleep(1e3 * 2 ** attempt);
@@ -680,14 +696,12 @@ async function putPart(target, body, options) {
680
696
  }
681
697
  throw new TransferError(`Upload of ${options.label} failed: network error (${describeFetchError(error)}).`, null);
682
698
  }
683
- if (response.ok) {
699
+ if (response.ok || response.status === 412 && attempt > 0) {
684
700
  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;
701
+ return;
688
702
  }
703
+ failed();
689
704
  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
705
  if (response.status >= 500 && attempt < options.maxRetries) {
692
706
  await options.sleep(1e3 * 2 ** attempt);
693
707
  continue;
@@ -716,8 +730,14 @@ async function runPool(count, concurrency, controller, worker) {
716
730
  await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, count)) }, runner));
717
731
  if (firstError !== null) throw firstError;
718
732
  }
719
- async function transferOnce(options, blob) {
733
+ /**
734
+ * Upload one file: start the upload, PUT each part (in parallel for multipart), then complete
735
+ * it. file.cafe checks the stored file when completing, so nothing else needs to be sent back.
736
+ */
737
+ async function uploadFile(options) {
720
738
  const { client, size } = options;
739
+ const blob = await openAsBlob(options.path);
740
+ if (blob.size !== size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
721
741
  const started = await client.request("POST", "/api/v1/uploads", {
722
742
  filename: options.filename,
723
743
  size,
@@ -725,48 +745,73 @@ async function transferOnce(options, blob) {
725
745
  ...options.collectionId ? { collection_id: options.collectionId } : {}
726
746
  });
727
747
  const { targets, partSize } = planTransfer(started, size);
728
- const requireReceipt = started.requires_receipts !== false;
729
- const receipts = new Array(targets.length).fill(null);
748
+ const partUrls = createPartUrls(options, started, targets);
730
749
  const controller = new AbortController();
731
750
  let uploadedBytes = 0;
732
751
  options.onProgress?.(0, size);
733
752
  await runPool(targets.length, options.concurrency ?? DEFAULT_CONCURRENCY, controller, async (index) => {
734
753
  const start = index * partSize;
735
754
  const end = Math.min(start + partSize, size);
736
- const target = targets[index];
737
- receipts[index] = await putPart(target, blob.slice(start, end), {
755
+ await putPart(await partUrls.target(index), blob.slice(start, end), {
738
756
  fetch: options.fetch,
739
757
  sleep: options.sleep,
740
758
  maxRetries: options.maxPartRetries ?? DEFAULT_PART_RETRIES,
741
759
  timeoutMs: options.partTimeoutMs ?? DEFAULT_PART_TIMEOUT_MS,
742
760
  signal: controller.signal,
743
- requireReceipt,
744
- label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename
761
+ label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename,
762
+ onBytes: (bytes) => {
763
+ uploadedBytes += bytes;
764
+ options.onProgress?.(uploadedBytes, size);
765
+ }
745
766
  });
746
- uploadedBytes += end - start;
747
- options.onProgress?.(uploadedBytes, size);
748
767
  });
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 });
768
+ return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, { token: partUrls.token() }, { idempotent: true });
753
769
  }
754
770
  /**
755
- * Upload one file: start the upload, PUT each part (in parallel for multipart),
756
- * then complete it with the receipts in part order.
771
+ * The URL for each part of an upload, in batches of PART_URL_BATCH_SIZE. The first batch comes
772
+ * from the start response; later ones, and any batch older than PART_URL_MAX_AGE_MS, are fetched
773
+ * when a part in them is about to be uploaded. Each fetch also renews the upload ticket, so the
774
+ * latest token is the one to complete with.
757
775
  */
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
- }
776
+ function createPartUrls(options, started, targets) {
777
+ const now = options.now ?? Date.now;
778
+ const batches = /* @__PURE__ */ new Map([[0, {
779
+ fetchedAt: now(),
780
+ targets: Promise.resolve(targets.slice(0, PART_URL_BATCH_SIZE))
781
+ }]]);
782
+ let token = started.token;
783
+ const fetchBatch = async (batch) => {
784
+ const first = batch * PART_URL_BATCH_SIZE + 1;
785
+ const partNumbers = Array.from({ length: Math.min(PART_URL_BATCH_SIZE, targets.length - first + 1) }, (_, i) => first + i);
786
+ const response = await options.client.request("POST", `/api/v1/uploads/${encodeURIComponent(started.id)}/parts`, {
787
+ token,
788
+ part_numbers: partNumbers
789
+ }, { idempotent: true });
790
+ const parts = isRecord(response) && Array.isArray(response.parts) ? response.parts : [];
791
+ const fresh = partNumbers.map((partNumber) => parts.find((part) => isRecord(part) && part.part_number === partNumber));
792
+ if (!isRecord(response) || typeof response.token !== "string" || !fresh.every(isSignedTarget)) throw new ApiError("Unexpected response when fetching upload URLs.", null);
793
+ token = response.token;
794
+ return fresh.map((part) => ({
795
+ url: part.url,
796
+ headers: part.headers
797
+ }));
798
+ };
799
+ return {
800
+ async target(index) {
801
+ if (!("parts" in started)) return targets[index];
802
+ const batch = Math.floor(index / PART_URL_BATCH_SIZE);
803
+ let entry = batches.get(batch);
804
+ if (!entry || now() - entry.fetchedAt > PART_URL_MAX_AGE_MS) {
805
+ entry = {
806
+ fetchedAt: now(),
807
+ targets: fetchBatch(batch)
808
+ };
809
+ batches.set(batch, entry);
810
+ }
811
+ return (await entry.targets)[index % PART_URL_BATCH_SIZE];
812
+ },
813
+ token: () => token
814
+ };
770
815
  }
771
816
  // src/commands/upload.ts
772
817
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -877,6 +922,7 @@ async function uploadCommand(files, options, globals, context) {
877
922
  else {
878
923
  const filename = uploadFilename(file);
879
924
  progress.update(`Uploading ${err.bold(filename)} (${formatBytes(size)})...`);
925
+ let lastDrawn = -Infinity;
880
926
  try {
881
927
  const completed = await uploadFile({
882
928
  client,
@@ -888,8 +934,10 @@ async function uploadCommand(files, options, globals, context) {
888
934
  mimeType: guessMimeType(filename),
889
935
  collectionId: options.collection,
890
936
  concurrency: options.concurrency,
891
- onNotice: notice,
937
+ now: context.now,
892
938
  onProgress: (uploaded, total) => {
939
+ if (uploaded < total && context.now() - lastDrawn < 100) return;
940
+ lastDrawn = context.now();
893
941
  if (uploaded > 0 && total > 0) {
894
942
  const percent = Math.floor(uploaded / total * 100);
895
943
  progress.update(`Uploading ${err.bold(filename)} ${err.cyan(`${percent}%`)} (${formatBytes(uploaded)} / ${formatBytes(total)})`);
@@ -1009,7 +1057,7 @@ function startUpdateCheck(context) {
1009
1057
  async function offerUpdate(context, version) {
1010
1058
  const color = colorsFor(context.stderr, context.env);
1011
1059
  const run = (command) => color.cyan(command);
1012
- context.stderr.write(version ? `\nUpdate available for filecafe (${color.gray(VERSION)} → ${color.green(version)}).\nChangelog: ${color.cyan(`${RELEASES_URL}/v${version}`)}\n` : "\nA newer version of filecafe may be available.\n");
1060
+ 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");
1013
1061
  if (context.env.npm_command === "exec" || context.scriptPath.replaceAll("\\", "/").includes("/_npx/")) {
1014
1062
  context.stderr.write(`Run: ${run("npx filecafe@latest")}\n`);
1015
1063
  return;
@@ -1019,7 +1067,8 @@ async function offerUpdate(context, version) {
1019
1067
  context.stderr.write(installer ? `Run: ${run(installer.join(" "))}\n` : UNKNOWN_INSTALL);
1020
1068
  return;
1021
1069
  }
1022
- if (!await context.confirm(`Would you like to upgrade now? ${color.gray("(Y/n)")} `)) return;
1070
+ const question = `${color.gray("?")} ${color.bold("Would you like to upgrade now?")} ${color.gray("(Y/n)")} `;
1071
+ if (!await context.confirm(question)) return;
1023
1072
  const installer = await detectInstaller(context);
1024
1073
  if (!installer) {
1025
1074
  context.stderr.write(UNKNOWN_INSTALL);
@@ -108,7 +108,7 @@ async function resolveSettings(environment, urlOption) {
108
108
  };
109
109
  }
110
110
  // src/version.ts
111
- const VERSION = "0.3.2";
111
+ const VERSION = "0.3.4";
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-BDT0cPCo.js";
1
+ import { i as refreshUpdateCache, s as VERSION } from "./update-cache-BOFin4Gp.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.2",
3
+ "version": "0.3.4",
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",