@softure-ai/files 0.2.0 → 0.4.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +131 -4
  3. package/dist/client/index.d.ts +3 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +6 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/send-upload.d.ts +26 -0
  8. package/dist/client/send-upload.d.ts.map +1 -0
  9. package/dist/client/send-upload.js +66 -0
  10. package/dist/client/send-upload.js.map +1 -0
  11. package/dist/client/upload-queue.d.ts +52 -0
  12. package/dist/client/upload-queue.d.ts.map +1 -0
  13. package/dist/client/upload-queue.js +164 -0
  14. package/dist/client/upload-queue.js.map +1 -0
  15. package/dist/index.d.ts +5 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/jobs/index.d.ts +23 -1
  19. package/dist/jobs/index.d.ts.map +1 -1
  20. package/dist/jobs/index.js +46 -11
  21. package/dist/jobs/index.js.map +1 -1
  22. package/dist/mcp/index.d.ts +25 -1
  23. package/dist/mcp/index.d.ts.map +1 -1
  24. package/dist/mcp/index.js +31 -14
  25. package/dist/mcp/index.js.map +1 -1
  26. package/dist/messages/en.d.ts +5 -0
  27. package/dist/messages/en.d.ts.map +1 -1
  28. package/dist/messages/en.js +7 -1
  29. package/dist/messages/en.js.map +1 -1
  30. package/dist/messages/index.d.ts +5 -0
  31. package/dist/messages/index.d.ts.map +1 -1
  32. package/dist/next/index.d.ts +1 -0
  33. package/dist/next/index.d.ts.map +1 -1
  34. package/dist/next/index.js +3 -2
  35. package/dist/next/index.js.map +1 -1
  36. package/dist/next/stored-file-route.d.ts +25 -0
  37. package/dist/next/stored-file-route.d.ts.map +1 -0
  38. package/dist/next/stored-file-route.js +14 -0
  39. package/dist/next/stored-file-route.js.map +1 -0
  40. package/dist/server/index.d.ts +2 -2
  41. package/dist/server/index.d.ts.map +1 -1
  42. package/dist/server/index.js +2 -2
  43. package/dist/server/index.js.map +1 -1
  44. package/dist/server/prune.d.ts +4 -0
  45. package/dist/server/prune.d.ts.map +1 -1
  46. package/dist/server/prune.js +8 -2
  47. package/dist/server/prune.js.map +1 -1
  48. package/dist/server/serve.d.ts +15 -0
  49. package/dist/server/serve.d.ts.map +1 -1
  50. package/dist/server/serve.js +38 -14
  51. package/dist/server/serve.js.map +1 -1
  52. package/dist/server/upload-page.d.ts.map +1 -1
  53. package/dist/server/upload-page.js +16 -23
  54. package/dist/server/upload-page.js.map +1 -1
  55. package/module.json +1 -1
  56. package/package.json +8 -3
  57. package/src/client/index.ts +12 -0
  58. package/src/client/send-upload.ts +89 -0
  59. package/src/client/upload-queue.ts +220 -0
  60. package/src/index.ts +1 -1
  61. package/src/jobs/index.ts +66 -13
  62. package/src/mcp/index.ts +52 -15
  63. package/src/messages/en.ts +7 -1
  64. package/src/next/index.ts +9 -2
  65. package/src/next/stored-file-route.ts +43 -0
  66. package/src/server/index.ts +2 -2
  67. package/src/server/prune.ts +10 -1
  68. package/src/server/serve.ts +51 -14
  69. package/src/server/upload-page.ts +16 -23
package/CHANGELOG.md CHANGED
@@ -4,6 +4,39 @@ Newest first. Each version lists what changed for an app that uses `@softure-ai/
4
4
  in production, the version gets a line `verified in: <app>@<commit>` ([docs/05](../../docs/05-adoption-playbook.md),
5
5
  "Definition of done").
6
6
 
7
+ ## 0.4.0
8
+
9
+ - The `files.prune` job logs every run (#1192): one line `files.prune finished` with `removed`, `freedBytes`,
10
+ `failedFiles`, `deletedUploads`, `failedUploads` and, when at most 10 files went, their ids as `fileIds` (also
11
+ `removed=0 freedBytes=0` for an empty run). `createFilesJobHandlers({ logger })` takes any logger with `info`
12
+ (`createLogger("files")` from `@softure-ai/observability` as it is); `filesJobHandlers` logs to the console.
13
+ - `PruneFilesReport.removedFileIds`: the ids of the first `PRUNE_REPORT_MAX_FILE_IDS` (10) removed files.
14
+ - Migration: none. A test that compares a whole `pruneFiles` report with `toEqual` adds `removedFileIds`.
15
+
16
+ ## 0.3.0
17
+
18
+ - `serveStoredFile(ctx, fileId, request, { ownerId, disposition? })` in `/server` and `createStoredFileRoute({ getOwnerId })`
19
+ in `/next` (#993): the signed-in owner gets a stored file with the answer of a link (`GET`, `HEAD`, single byte
20
+ ranges, the same headers, one `404` for anything missing or another owner's), `inline` by default, with no link to
21
+ mint. The route sits behind the app's sign-in guard (README §4.4). `serveFileLink` answers as before.
22
+ - Migration for an app that mints a link for its own viewing, or that rebuilt the answer from `findFile`, `openFile`
23
+ and `parseRangeHeader`: mount `createStoredFileRoute` under a guarded prefix and point the player or image at
24
+ `/<prefix>/<file id>`; drop the link minting or the copied answer.
25
+ - A browser client, `@softure-ai/files/client` (#988): `sendUpload(file, { uploadUrl, signal, onProgress, fetch })`
26
+ reads the session's `HEAD`, sends only the missing chunks in order with `Content-Range`, reports
27
+ `{ sentBytes, totalBytes }`, honours an `AbortSignal` and answers a `Result` (`files.upload_expired`,
28
+ `files.upload_rejected`, `files.network`, `files.upload_aborted`). `createUploadQueue({ open, finalize })` keeps an
29
+ upload list whose items theme-notion's `UploadItem` takes as they are, with `add`, `retry`, `pause`, `resume`,
30
+ `remove`, `getItems` and `subscribe` (for `useSyncExternalStore`). An app that carries its own chunk loop can drop it.
31
+ - The upload page runs the same `sendUpload` (inlined) and says when its link has expired (`uploadPage.expired`).
32
+ - New messages for the client's codes: `errors.files.upload_expired`, `upload_rejected`, `network`, `upload_aborted`.
33
+ - `registerFileUploadTools` takes `onFinalized(file, ctx)` (#987): it runs after every successful `finalize_upload`,
34
+ a repeated one included, and its returned fields join the answer; a returned `err(code)` answers that code. Also
35
+ `descriptions` (the served text of both tools, defaults exported as `FILE_UPLOAD_TOOL_DESCRIPTIONS`) and `hints`
36
+ (the text answered for an error code). Without them the tools answer as in 0.2.0.
37
+ - Migration for an app that wraps the server to replace the finalize handler or the descriptions: drop the wrapper and
38
+ pass `onFinalized` (its step after `finalizeUpload`, made idempotent), `descriptions` and `hints` instead.
39
+
7
40
  ## 0.2.0
8
41
 
9
42
  - Resumable uploads from clients (#949): table `files.uploads` (migration 0002), `createUpload` (a signed upload URL
package/README.md CHANGED
@@ -28,16 +28,25 @@ sandbox, a phone behind a proxy with a body limit) uploads through a signed URL
28
28
  `Content-Length`, `Accept-Ranges`, `206` for a range, `416` past the end, `Content-Disposition`, and
29
29
  `Cache-Control: private, no-store` (no CDN keeps a copy), and the same `404` for an expired, revoked, deleted or
30
30
  forged link. `revokeFileLinks(ctx, fileId)` stops every link made so far.
31
+ - **The owner's own view**: `serveStoredFile(ctx, fileId, request, { ownerId })` and the Next route
32
+ `createStoredFileRoute({ getOwnerId })` give the signed-in owner the same answer (ranges, headers, one `404`) for a
33
+ player or an image in the app's own page, with no public link. See §4.4.
31
34
  - **Resumable uploads** (`files.uploads`): `createUpload(ctx, { ownerId, name, contentType?, size, sha256?, kind?,
32
35
  ttlSeconds? })` opens a session and answers `{ uploadId, uploadUrl, chunkSize, chunkCount, expiresAt }`. The client
33
36
  sends the file to `uploadUrl` in chunks under the edge's body limit (64 MiB by default), resumes after a dropped
34
37
  connection, and `finalizeUpload(ctx, uploadId)` checks every byte and the optional SHA-256 and saves the file like
35
38
  `saveFile` (quota, dedupe). See §4.1.
39
+ - **A browser client** (`@softure-ai/files/client`): `sendUpload(file, { uploadUrl, signal?, onProgress? })` sends a
40
+ `File` to a session, only the chunks it lacks, and `createUploadQueue({ open, finalize })` keeps an upload list for
41
+ an upload screen (theme-notion's `UploadItem` takes its items as they are). See §4.3.
36
42
  - **MCP upload tools** (`@softure-ai/files/mcp`): `registerFileUploadTools(server, { identity, getContext })` adds
37
43
  `create_upload` (a signed URL, a ready `curl` loop and the browser page) and `finalize_upload`, so an assistant hands
38
44
  over a video without its bytes going through a tool call. See §4.2.
39
45
  - **Retention**: `pruneFiles(ctx)` removes expired and deleted files from storage and the table, and expired upload
40
- sessions with their chunks; the `files.prune` job (`@softure-ai/files/jobs`) runs it hourly.
46
+ sessions with their chunks; the `files.prune` job (`@softure-ai/files/jobs`) runs it hourly. Every run logs one line
47
+ `files.prune finished removed=<n> freedBytes=<b> failedFiles deletedUploads failedUploads`, with the removed ids as
48
+ `fileIds` when at most 10 went; `createFilesJobHandlers({ logger: createLogger("files") })` sends it through
49
+ `@softure-ai/observability` instead of the console.
41
50
  - **A privacy contributor** (the export lists the owner's files, the deletion removes them) and **a health check**
42
51
  (the table answers, storage takes a write, free space above `health.minFreeBytes`).
43
52
  - **`/testing`**: an in-memory driver, a fixed link keyring, `fetchFileLink` (status, headers and bytes of a link,
@@ -179,7 +188,8 @@ The wire protocol on `uploadUrl`:
179
188
  | `GET` | the JSON status (`received`, `receivedBytes`, `missingChunks`, `state`, ...); a browser (`Accept: text/html`) gets the upload page instead |
180
189
 
181
190
  The **upload page** is a small phone-friendly page on the same URL: the person picks the file and it is sent in chunks
182
- with `fetch`, from the missing ones, so pressing Upload again resumes. Its copy is `filesMessages.en.uploadPage`; it
191
+ with `fetch`, from the missing ones, so pressing Upload again resumes. Its loop is `sendUpload` of the browser client
192
+ (§4.3), inlined. Its copy is `filesMessages.en.uploadPage`; it
183
193
  loads nothing external and runs one inline script under a per-response CSP nonce.
184
194
 
185
195
  **Rate limit**: when the app enables `@softure-ai/security`, every request to the upload route counts in the
@@ -191,6 +201,58 @@ Every chunk is its own object in storage (`uploads/<id>/<index>`); `finalizeUplo
191
201
  `saveFile`, which writes the one final object (a multipart upload on S3) and the parts are removed. Storage briefly
192
202
  holds the file twice while a finalize runs. Two parallel finalizes keep one file; a second call answers the same file.
193
203
 
204
+ ### 4.3 The browser client
205
+
206
+ `@softure-ai/files/client` runs in the browser (no Node built-ins, no server code). An app with its own upload screen
207
+ opens the session on the server and sends the file from the client:
208
+
209
+ ```ts
210
+ "use client";
211
+ import { sendUpload } from "@softure-ai/files/client";
212
+
213
+ const opened = await openUpload({ name: file.name, size: file.size }); // a server action around createUpload
214
+ if (!opened.ok) return opened;
215
+ const sent = await sendUpload(file, {
216
+ uploadUrl: opened.value.uploadUrl,
217
+ signal: controller.signal,
218
+ onProgress: ({ sentBytes, totalBytes }) => setProgress(sentBytes / totalBytes),
219
+ });
220
+ if (sent.ok) await finishUpload(opened.value.uploadId); // a server action around finalizeUpload
221
+ ```
222
+
223
+ `sendUpload` reads the session's `HEAD`, takes the chunk size from it and sends only the missing chunks, in order;
224
+ calling it again resumes. It reports `{ sentBytes, totalBytes }` once with what already arrived and after every chunk,
225
+ and answers a `Result`: `files.upload_expired` (`404`: expired, finalized for a write, or forged),
226
+ `files.upload_rejected` (another `4xx`, or a file whose size is not the session's), `files.network` (a failed request,
227
+ `429`, `5xx`) or `files.upload_aborted` (the signal). It never throws for these.
228
+
229
+ For a list of files, `createUploadQueue` does the bookkeeping:
230
+
231
+ ```tsx
232
+ "use client";
233
+ import { createUploadQueue } from "@softure-ai/files/client";
234
+ import { UploadField, UploadItem } from "@softure-ai/theme-notion";
235
+ import { useState, useSyncExternalStore } from "react";
236
+
237
+ const [queue] = useState(() => createUploadQueue({ open: openUpload, finalize: (session) => finishUpload(session.uploadId) }));
238
+ const items = useSyncExternalStore(queue.subscribe, queue.getItems, queue.getItems);
239
+
240
+ <UploadField label={copy.files} onFilesSelected={(files) => queue.add(files)} />
241
+ {items.map((item) => (
242
+ <UploadItem key={item.id} item={item} onRetry={() => queue.retry(item.id)} onPause={() => queue.pause(item.id)}
243
+ onResume={() => queue.resume(item.id)} onRemove={() => queue.remove(item.id)} />
244
+ ))}
245
+ ```
246
+
247
+ - Items are `{ id, name, size, state, progress, error?, errorCode? }`: `queued`, `uploading`, `paused`, `done`,
248
+ `failed`; `progress` 0–100, 100 only once finalized; `getItems` answers the same array until something changes.
249
+ - `open(file)` and `finalize(session, file)` are the app's (usually server actions) and answer a `Result`; their error
250
+ codes land in `errorCode` with the copy of `describeError(code)` (the built-in `files` messages by default, so an
251
+ app passes `(code) => getFilesErrorMessage(myMessages, code)` or its own wording).
252
+ - `concurrency` (1 by default) uploads run at once. `pause` aborts the running send and keeps the session; `resume`
253
+ and `retry` send only what is missing in the same session, and a session that expired is opened again on the next
254
+ `retry`. `remove` stops the upload and drops it; the unfinished session expires and `files.prune` removes it.
255
+
194
256
  ### 4.2 MCP upload tools
195
257
 
196
258
  An MCP tool cannot take a video as an argument. With `@softure-ai/mcp-access`, register the two upload tools in the
@@ -221,6 +283,70 @@ export const createServer = createMcpServerFactory({
221
283
  - Both are write tools: registered only when `identity.canWrite` (mcp-access's write switch). The uploads belong to the
222
284
  token's user (`getOwnerId` changes that). The app's tools then take the `file_id`.
223
285
 
286
+ An app that turns the uploaded file into its own record in the same call, or that words its tool texts its own way,
287
+ passes three more options:
288
+
289
+ ```ts
290
+ registerFileUploadTools(server, {
291
+ identity,
292
+ getContext: () => getFilesContext(),
293
+ // After every successful finalize, a repeated one for the same file included: keep it idempotent.
294
+ onFinalized: async (file) => {
295
+ const asset = await upsertAssetForFile(file.id); // the app's own step, e.g. a row plus a background job
296
+ return asset.ok ? { asset_id: asset.value.id } : asset; // fields join the answer; err(code) answers a failure
297
+ },
298
+ descriptions: { finalize_upload: `Acme: ${FILE_UPLOAD_TOOL_DESCRIPTIONS.finalize_upload}` },
299
+ hints: { "assets.quota_exceeded": "The plan holds no more assets." },
300
+ });
301
+ ```
302
+
303
+ - `onFinalized(file, ctx)`: its returned fields are merged into the `finalize_upload` answer (the file's own fields
304
+ win a name clash); a returned `err(code)` answers that code as a failure; a thrown error answers the generic failure
305
+ and is logged.
306
+ - `descriptions`: the served text of `create_upload` and `finalize_upload`; the defaults are exported as
307
+ `FILE_UPLOAD_TOOL_DESCRIPTIONS`. The catalog entries in `FILE_UPLOAD_MCP_TOOLS` stay as they are.
308
+ - `hints`: the text answered for an error code, followed by the code: the hook's codes and the package's `files.*`
309
+ codes alike. Without a hint a `files.*` code answers its sentence and any other code answers the code alone.
310
+
311
+ ### 4.4 Showing a file to its signed-in owner
312
+
313
+ A link is for someone outside the app (a scheduler, a recipient). To play a stored video or show an image to the
314
+ signed-in owner inside the app's own page, serve it by id through the owner route instead: no link is minted (no
315
+ write), and the file stays unreachable without a session.
316
+
317
+ ```ts
318
+ // app/media/[id]/route.ts
319
+ import { getCurrentUser } from "@softure-ai/auth/next";
320
+ import { createStoredFileRoute } from "@softure-ai/files/next";
321
+
322
+ export const { GET, HEAD } = createStoredFileRoute({
323
+ getOwnerId: async () => (await getCurrentUser())?.id ?? null,
324
+ });
325
+ ```
326
+
327
+ ```tsx
328
+ <video src={`/media/${file.id}`} controls />
329
+ ```
330
+
331
+ The route answers like a link (`GET` and `HEAD`, single byte ranges for seeking, `206`, `416`,
332
+ `Cache-Control: private, no-store`, `nosniff`, the sandboxing CSP) under the file's stored name, `inline` by default
333
+ (`disposition: "attachment"` for a download). Without a session, and for a file that is missing, expired, deleted or
334
+ another owner's, it answers the same `404`, so it never tells whether a file exists. files does not depend on auth:
335
+ the session lookup is the app's `getOwnerId`.
336
+
337
+ **Unlike `/f` and `/u`, this route sits behind the app's sign-in guard**: list its prefix in
338
+ `createAuthGuard(config, { protect: [...] })` and add no edge bypass for it.
339
+
340
+ A route of the app's own (another path shape, an extra permission check) calls the server function with the owner it
341
+ has checked:
342
+
343
+ ```ts
344
+ import { getFilesContext } from "@softure-ai/files/next";
345
+ import { serveStoredFile } from "@softure-ai/files/server";
346
+
347
+ return serveStoredFile(await getFilesContext(), fileId, request, { ownerId: user.id });
348
+ ```
349
+
224
350
  ## 5. Migrations and tables
225
351
 
226
352
  Schema `files`, migration `0001_create_files.sql`, table `files`:
@@ -260,14 +386,15 @@ None.
260
386
  ## 8. Appearance
261
387
 
262
388
  The upload page (§4.1) is plain HTML with a minimal inline style, so it works before any theme loads; an app that
263
- wants its own look builds a page on `createUpload` and the same wire protocol. A file browser is out of scope.
389
+ wants its own look builds a page on `createUpload` and the browser client (§4.3). A file browser is out of scope.
264
390
 
265
391
  ## 9. Copy
266
392
 
267
393
  `filesMessages.en.errors.files.*` has a sentence per error code (`too_large`, `quota_exceeded`, `not_found`, ...);
268
394
  `getFilesErrorMessage(messages, code)` picks one, falling back to the generic failure. The link route's `404` body
269
395
  is a fixed `Not found` for machines, not copy. `uploadPage.*` is the upload page's copy (`{name}`, `{size}`, `{done}`
270
- and `{total}` are filled in).
396
+ and `{total}` are filled in). The browser client's codes (`upload_expired`, `upload_rejected`, `network`,
397
+ `upload_aborted`) have their sentences in the same group.
271
398
 
272
399
  ## 10. Hooks
273
400
 
@@ -0,0 +1,3 @@
1
+ export { sendUpload, type SendUploadErrorCode, type SendUploadOptions, type SendUploadResult, type UploadProgress } from "./send-upload.js";
2
+ export { createUploadQueue, type UploadQueue, type UploadQueueItem, type UploadQueueOptions, type UploadQueueSession, type UploadQueueState, } from "./upload-queue.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAC5I,OAAO,EACL,iBAAiB,EACjB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,GACtB,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,6 @@
1
+ // The browser side of upload sessions: `sendUpload` sends a `File` to a session's signed URL in chunks, resumably,
2
+ // and `createUploadQueue` keeps a list of uploads for an upload screen (theme-notion's `UploadItem` takes its items
3
+ // as they are). No Node built-ins and no server code: safe to import from a client component.
4
+ export { sendUpload } from "./send-upload.js";
5
+ export { createUploadQueue, } from "./upload-queue.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,oHAAoH;AACpH,8FAA8F;AAC9F,OAAO,EAAE,UAAU,EAAgG,MAAM,kBAAkB,CAAC;AAC5I,OAAO,EACL,iBAAiB,GAMlB,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { Err, Ok } from "@softure-ai/core";
2
+ /** Why a send stopped: the session is gone, the route refused it, the network failed, or the caller aborted. */
3
+ export type SendUploadErrorCode = "files.upload_expired" | "files.upload_rejected" | "files.network" | "files.upload_aborted";
4
+ /** Bytes the session holds so far out of the file's size. */
5
+ export interface UploadProgress {
6
+ readonly sentBytes: number;
7
+ readonly totalBytes: number;
8
+ }
9
+ export interface SendUploadOptions {
10
+ /** The session's signed upload URL, as `createUpload` returned it. */
11
+ readonly uploadUrl: string;
12
+ /** Aborts between chunks and the chunk in flight; the send answers `files.upload_aborted`. */
13
+ readonly signal?: AbortSignal;
14
+ /** Called once with what already arrived, then after every chunk. */
15
+ readonly onProgress?: (progress: UploadProgress) => void;
16
+ /** The `fetch` to use; the global one by default. */
17
+ readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
18
+ }
19
+ export type SendUploadResult = Ok<UploadProgress> | Err<SendUploadErrorCode>;
20
+ /**
21
+ * Sends the chunks of `file` the session does not hold yet. Resuming is calling it again: a chunk that arrived is
22
+ * never sent twice. `404` answers `files.upload_expired`, another `4xx` (or a file whose size is not the session's)
23
+ * `files.upload_rejected`, a failed request, `429` or `5xx` `files.network`.
24
+ */
25
+ export declare function sendUpload(file: Blob, options: SendUploadOptions): Promise<SendUploadResult>;
26
+ //# sourceMappingURL=send-upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send-upload.d.ts","sourceRoot":"","sources":["../../src/client/send-upload.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAEhD,gHAAgH;AAChH,MAAM,MAAM,mBAAmB,GAAG,sBAAsB,GAAG,uBAAuB,GAAG,eAAe,GAAG,sBAAsB,CAAC;AAE9H,6DAA6D;AAC7D,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,iBAAiB;IAChC,sEAAsE;IACtE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,8FAA8F;IAC9F,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;IAC9B,qEAAqE;IACrE,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;IACzD,qDAAqD;IACrD,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;CACxE;AAED,MAAM,MAAM,gBAAgB,GAAG,EAAE,CAAC,cAAc,CAAC,GAAG,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAE7E;;;;GAIG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAoDlG"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Sends the chunks of `file` the session does not hold yet. Resuming is calling it again: a chunk that arrived is
3
+ * never sent twice. `404` answers `files.upload_expired`, another `4xx` (or a file whose size is not the session's)
4
+ * `files.upload_rejected`, a failed request, `429` or `5xx` `files.network`.
5
+ */
6
+ export async function sendUpload(file, options) {
7
+ const { uploadUrl, signal, onProgress } = options;
8
+ const request = options.fetch ?? ((url, init) => fetch(url, init));
9
+ const fail = (error) => ({ ok: false, error });
10
+ const failForStatus = (status) => {
11
+ if (status === 404)
12
+ return fail("files.upload_expired");
13
+ return fail(status === 429 || status >= 500 ? "files.network" : "files.upload_rejected");
14
+ };
15
+ const isAborted = () => signal?.aborted === true;
16
+ const call = async (init) => {
17
+ if (isAborted())
18
+ return "files.upload_aborted";
19
+ try {
20
+ return await request(uploadUrl, { ...init, signal: signal ?? null });
21
+ }
22
+ catch {
23
+ // A thrown fetch is the network or the abort; both are expected and answered as a code.
24
+ return isAborted() ? "files.upload_aborted" : "files.network";
25
+ }
26
+ };
27
+ const head = await call({ method: "HEAD" });
28
+ if (typeof head === "string")
29
+ return fail(head);
30
+ if (!head.ok)
31
+ return failForStatus(head.status);
32
+ const totalBytes = Number(head.headers.get("upload-size"));
33
+ const chunkSize = Number(head.headers.get("upload-chunk-size"));
34
+ if (!Number.isSafeInteger(totalBytes) || !Number.isSafeInteger(chunkSize) || chunkSize <= 0 || totalBytes !== file.size) {
35
+ return fail("files.upload_rejected");
36
+ }
37
+ const received = [];
38
+ for (const part of (head.headers.get("upload-received") ?? "").split(",")) {
39
+ const match = /^(\d+)-(\d+)$/.exec(part.trim());
40
+ if (match !== null)
41
+ received.push({ start: Number(match[1]), end: Number(match[2]) });
42
+ }
43
+ const missing = [];
44
+ for (let start = 0; start < totalBytes; start += chunkSize) {
45
+ const end = Math.min(start + chunkSize, totalBytes) - 1;
46
+ if (!received.some((range) => range.start <= start && range.end >= end))
47
+ missing.push({ start, end });
48
+ }
49
+ let sentBytes = totalBytes - missing.reduce((sum, chunk) => sum + chunk.end - chunk.start + 1, 0);
50
+ onProgress?.({ sentBytes, totalBytes });
51
+ for (const chunk of missing) {
52
+ const answer = await call({
53
+ method: "PUT",
54
+ headers: { "content-range": `bytes ${String(chunk.start)}-${String(chunk.end)}/${String(totalBytes)}` },
55
+ body: file.slice(chunk.start, chunk.end + 1),
56
+ });
57
+ if (typeof answer === "string")
58
+ return fail(answer);
59
+ if (!answer.ok)
60
+ return failForStatus(answer.status);
61
+ sentBytes += chunk.end - chunk.start + 1;
62
+ onProgress?.({ sentBytes, totalBytes });
63
+ }
64
+ return { ok: true, value: { sentBytes, totalBytes } };
65
+ }
66
+ //# sourceMappingURL=send-upload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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AG,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;QACzC,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,CAAC;AACxD,CAAC"}
@@ -0,0 +1,52 @@
1
+ import type { ErrorCode, Result } from "@softure-ai/core";
2
+ import { type SendUploadOptions } from "./send-upload.js";
3
+ export type UploadQueueState = "queued" | "uploading" | "paused" | "done" | "failed";
4
+ /** One upload of the list. */
5
+ export interface UploadQueueItem {
6
+ readonly id: string;
7
+ readonly name: string;
8
+ /** In bytes. */
9
+ readonly size: number;
10
+ readonly state: UploadQueueState;
11
+ /** 0-100, what the session holds; 100 only once finalized. */
12
+ readonly progress: number;
13
+ /** The copy for `errorCode`, on a failed item. */
14
+ readonly error?: string;
15
+ /** Why it failed: a `files.*` code of the client or whatever code the app's `open` or `finalize` answered. */
16
+ readonly errorCode?: ErrorCode;
17
+ }
18
+ /** What the app's `open` answers: at least the session's upload URL (`createUpload`'s answer fits). */
19
+ export interface UploadQueueSession {
20
+ readonly uploadUrl: string;
21
+ }
22
+ export interface UploadQueueOptions<TSession extends UploadQueueSession> {
23
+ /** Opens a session for a file, usually a server action around `createUpload`. */
24
+ readonly open: (file: File) => Promise<Result<TSession>>;
25
+ /** Turns a sent session into a stored file, usually a server action around `finalizeUpload`. */
26
+ readonly finalize: (session: TSession, file: File) => Promise<Result<unknown>>;
27
+ /** Uploads sent at the same time; 1 by default. */
28
+ readonly concurrency?: number;
29
+ /** The copy for a failure code; the built-in English `files` messages by default. */
30
+ readonly describeError?: (code: ErrorCode) => string;
31
+ /** The `fetch` the sender uses; the global one by default. */
32
+ readonly fetch?: SendUploadOptions["fetch"];
33
+ }
34
+ export interface UploadQueue {
35
+ /** Queues files (a `FileList` works) and answers their item ids. */
36
+ add(files: Iterable<File> | ArrayLike<File>): string[];
37
+ /** Queues a failed upload again; it keeps its session unless the session expired. */
38
+ retry(id: string): void;
39
+ /** Stops a queued or running upload; what arrived stays in the session. */
40
+ pause(id: string): void;
41
+ /** Queues a paused upload again; it sends only what is missing. */
42
+ resume(id: string): void;
43
+ /** Stops an upload and drops it from the list. An unfinished session expires and `files.prune` removes it. */
44
+ remove(id: string): void;
45
+ /** The list, in the order files were added; the same array until something changes. */
46
+ getItems(): readonly UploadQueueItem[];
47
+ /** Calls `listener` after every change; answers the function that stops it. */
48
+ subscribe(listener: () => void): () => void;
49
+ }
50
+ /** Creates an upload list; `open` and `finalize` are the app's, the sending is the package's. */
51
+ export declare function createUploadQueue<TSession extends UploadQueueSession>(options: UploadQueueOptions<TSession>): UploadQueue;
52
+ //# sourceMappingURL=upload-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-queue.d.ts","sourceRoot":"","sources":["../../src/client/upload-queue.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAc,KAAK,iBAAiB,EAAuB,MAAM,kBAAkB,CAAC;AAE3F,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,WAAW,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;AAErF,8BAA8B;AAC9B,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,gBAAgB;IAChB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,8DAA8D;IAC9D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,kDAAkD;IAClD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,8GAA8G;IAC9G,QAAQ,CAAC,SAAS,CAAC,EAA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,GAAG,MAAM,IAAI,CAAC;CAC7C;AAcD,iGAAiG;AACjG,wBAAgB,iBAAiB,CAAC,QAAQ,SAAS,kBAAkB,EAAE,OAAO,EAAE,kBAAkB,CAAC,QAAQ,CAAC,GAAG,WAAW,CA0IzH"}
@@ -0,0 +1,164 @@
1
+ import { filesMessages, getFilesErrorMessage } from "../messages/index.js";
2
+ import { sendUpload } from "./send-upload.js";
3
+ // A session the server no longer knows: a retry opens a new one.
4
+ const SESSION_GONE_CODES = new Set(["files.upload_expired", "files.not_found"]);
5
+ /** Creates an upload list; `open` and `finalize` are the app's, the sending is the package's. */
6
+ export function createUploadQueue(options) {
7
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? 1));
8
+ const describeError = options.describeError ?? ((code) => getFilesErrorMessage(filesMessages.en, code));
9
+ const entries = new Map();
10
+ const listeners = new Set();
11
+ let items = [];
12
+ let nextId = 1;
13
+ function publish() {
14
+ items = [...entries.values()].map((entry) => entry.item);
15
+ for (const listener of [...listeners])
16
+ listener();
17
+ }
18
+ function setItem(entry, state, progress = entry.item.progress, errorCode) {
19
+ const { id, name, size } = entry.item;
20
+ entry.item = { id, name, size, state, progress, ...(errorCode === undefined ? {} : { errorCode, error: describeError(errorCode) }) };
21
+ publish();
22
+ }
23
+ function fail(entry, code) {
24
+ if (SESSION_GONE_CODES.has(code))
25
+ entry.session = null;
26
+ setItem(entry, "failed", entry.item.progress, code);
27
+ }
28
+ function stop(entry) {
29
+ entry.run += 1;
30
+ entry.controller?.abort();
31
+ entry.controller = null;
32
+ }
33
+ function pump() {
34
+ for (const entry of entries.values()) {
35
+ if (countRunning() >= concurrency)
36
+ return;
37
+ if (entry.item.state === "queued")
38
+ void start(entry);
39
+ }
40
+ }
41
+ function countRunning() {
42
+ let running = 0;
43
+ for (const entry of entries.values())
44
+ if (entry.item.state === "uploading")
45
+ running += 1;
46
+ return running;
47
+ }
48
+ async function start(entry) {
49
+ entry.run += 1;
50
+ const run = entry.run;
51
+ const controller = new AbortController();
52
+ entry.controller = controller;
53
+ const isCurrent = () => entry.run === run && entries.get(entry.item.id) === entry;
54
+ setItem(entry, "uploading");
55
+ try {
56
+ let session = entry.session;
57
+ if (session === null) {
58
+ const opened = await options.open(entry.file);
59
+ // A session opened while the item was paused is kept, so the resume does not open a second one.
60
+ if (opened.ok)
61
+ entry.session = opened.value;
62
+ if (!isCurrent())
63
+ return;
64
+ if (!opened.ok)
65
+ return fail(entry, opened.error);
66
+ session = opened.value;
67
+ }
68
+ const sent = await sendUpload(entry.file, {
69
+ uploadUrl: session.uploadUrl,
70
+ signal: controller.signal,
71
+ onProgress: (progress) => {
72
+ if (isCurrent())
73
+ setItem(entry, "uploading", toPercent(progress));
74
+ },
75
+ ...(options.fetch === undefined ? {} : { fetch: options.fetch }),
76
+ });
77
+ if (!isCurrent())
78
+ return;
79
+ if (!sent.ok)
80
+ return fail(entry, sent.error);
81
+ const finalized = await options.finalize(session, entry.file);
82
+ if (!isCurrent())
83
+ return;
84
+ if (!finalized.ok)
85
+ return fail(entry, finalized.error);
86
+ setItem(entry, "done", 100);
87
+ }
88
+ catch (error) {
89
+ // The app's `open` or `finalize` threw, e.g. a server action whose request failed: the item fails with a
90
+ // retryable code, and the cause goes to the console for the developer.
91
+ console.error(`@softure-ai/files/client: an upload of "${entry.item.name}" stopped on a thrown open or finalize`, error);
92
+ if (isCurrent())
93
+ fail(entry, "files.network");
94
+ }
95
+ finally {
96
+ if (entry.controller === controller)
97
+ entry.controller = null;
98
+ pump();
99
+ }
100
+ }
101
+ function find(id, states) {
102
+ const entry = entries.get(id);
103
+ return entry !== undefined && states.includes(entry.item.state) ? entry : null;
104
+ }
105
+ return {
106
+ add(files) {
107
+ const ids = [];
108
+ for (const file of Array.from(files)) {
109
+ const id = `upload-${String(nextId)}`;
110
+ nextId += 1;
111
+ entries.set(id, { item: { id, name: file.name, size: file.size, state: "queued", progress: 0 }, file, session: null, run: 0, controller: null });
112
+ ids.push(id);
113
+ }
114
+ publish();
115
+ pump();
116
+ return ids;
117
+ },
118
+ retry(id) {
119
+ const entry = find(id, ["failed"]);
120
+ if (entry === null)
121
+ return;
122
+ setItem(entry, "queued");
123
+ pump();
124
+ },
125
+ pause(id) {
126
+ const entry = find(id, ["queued", "uploading"]);
127
+ if (entry === null)
128
+ return;
129
+ stop(entry);
130
+ setItem(entry, "paused");
131
+ pump();
132
+ },
133
+ resume(id) {
134
+ const entry = find(id, ["paused"]);
135
+ if (entry === null)
136
+ return;
137
+ setItem(entry, "queued");
138
+ pump();
139
+ },
140
+ remove(id) {
141
+ const entry = entries.get(id);
142
+ if (entry === undefined)
143
+ return;
144
+ stop(entry);
145
+ entries.delete(id);
146
+ publish();
147
+ pump();
148
+ },
149
+ getItems: () => items,
150
+ subscribe(listener) {
151
+ listeners.add(listener);
152
+ return () => {
153
+ listeners.delete(listener);
154
+ };
155
+ },
156
+ };
157
+ }
158
+ function toPercent(progress) {
159
+ // 100 is kept for a finalized upload: a sent but unfinalized one shows 99 at most.
160
+ if (progress.totalBytes === 0)
161
+ return 99;
162
+ return Math.min(99, Math.floor((progress.sentBytes / progress.totalBytes) * 100));
163
+ }
164
+ //# sourceMappingURL=upload-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-queue.js","sourceRoot":"","sources":["../../src/client/upload-queue.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAA+C,MAAM,kBAAkB,CAAC;AA+D3F,iEAAiE;AACjE,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC,CAAC,sBAAsB,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAErG,iGAAiG;AACjG,MAAM,UAAU,iBAAiB,CAAsC,OAAqC;IAC1G,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC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QACT,CAAC;QACD,QAAQ,EAAE,GAAG,EAAE,CAAC,KAAK;QACrB,SAAS,CAAC,QAAQ;YAChB,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,QAAwB;IACzC,mFAAmF;IACnF,IAAI,QAAQ,CAAC,UAAU,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACzC,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,SAAS,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;AACpF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -32,6 +32,10 @@ export declare const files: import("@softure-ai/core").ModuleFactory<{
32
32
  too_many_uploads: string;
33
33
  upload_incomplete: string;
34
34
  checksum_mismatch: string;
35
+ upload_expired: string;
36
+ upload_rejected: string;
37
+ network: string;
38
+ upload_aborted: string;
35
39
  };
36
40
  core: {
37
41
  unexpected: string;
@@ -47,6 +51,7 @@ export declare const files: import("@softure-ai/core").ModuleFactory<{
47
51
  done: string;
48
52
  wrongSize: string;
49
53
  failed: string;
54
+ expired: string;
50
55
  };
51
56
  }, import("zod").ZodObject<{
52
57
  storage: import("zod").ZodCustom<import("./storage.js").FileStorage, import("./storage.js").FileStorage>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,SAAS,UAAU,CAAC;AAEjC;;;;GAIG;AACH,eAAO,MAAM,wBAAwB;;;;;;CAE8B,CAAC;AAEpE;;;GAGG;AACH,eAAO,MAAM,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,KAAK,QAAQ,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ export const FILES_RATE_LIMIT_BUCKETS = {
22
22
  export const files = defineModule({
23
23
  manifest: {
24
24
  id: MODULE_ID,
25
- version: "0.2.0",
25
+ version: "0.4.0",
26
26
  dependsOn: { jobs: "^0.1.6?", security: "^0.2.5?" },
27
27
  dbSchema: "files",
28
28
  tables: ["files", "uploads"],