cloudrop 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/next.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as RequestHandler } from "./types-BrAx3dA4.js";
1
+ import { m as RequestHandler } from "./types-CFfMw-n_.js";
2
2
  export interface NextRouteHandlers {
3
3
  GET(request: Request): Promise<Response>;
4
4
  POST(request: Request): Promise<Response>;
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as RequestHandler } from "./types-BrAx3dA4.js";
1
+ import { m as RequestHandler } from "./types-CFfMw-n_.js";
2
2
  /** The parts of Node's IncomingMessage this adapter reads. */
3
3
  export interface NodeRequest extends AsyncIterable<Uint8Array> {
4
4
  method?: string;
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as RouteResult, g as RouteName, h as RouteMetadata, k as Result, u as InferableCloudrop } from "./types-BrAx3dA4.js";
2
- import { c as FileSnapshot, d as ResumableUpload, n as CloudropClient, p as UploadResult, s as FileOutcome, t as ClientOptions, u as JobSnapshot } from "./client-Dj6ON4MN.js";
1
+ import { _ as RouteResult, g as RouteName, h as RouteMetadata, k as Result, u as InferableCloudrop } from "./types-CFfMw-n_.js";
2
+ import { f as UploadResult, l as JobSnapshot, o as FileOutcome, p as ClientOptions, s as FileSnapshot, t as CloudropClient, u as ResumableUpload } from "./client-CP_ajLF4.js";
3
3
  import { ChangeEvent, DragEvent } from "react";
4
4
  /** The client's options, to create the client on first use in the browser; or `{ client }` to share one. */
5
5
  type UploadHooksOptions<TCloudrop extends InferableCloudrop> = ClientOptions | {
@@ -83,6 +83,11 @@ type ResumableOf<TName extends string> = TName extends string ? ResumableUpload<
83
83
  interface UseResumableResult<TName extends string> {
84
84
  /** The client's resumable() list, newest first; `[]` on the server, before the first read and when it failed. */
85
85
  uploads: readonly ResumableOf<TName>[];
86
+ /**
87
+ * The ids of the listed uploads this hook's discard() is dropping, from the call until the list is read again: a
88
+ * second discard() of one of them would answer UPLOAD_IN_USE, so a page disables its button meanwhile.
89
+ */
90
+ discarding: ReadonlySet<string>;
86
91
  /** Reads the list again; resolves with the client's answer, whose error says why the list is empty. */
87
92
  refresh(): Promise<Result<ResumableOf<TName>[]>>;
88
93
  /**
@@ -112,12 +117,21 @@ interface UploadHooks<TCloudrop extends InferableCloudrop> {
112
117
  * after mount and whenever an upload of these hooks may have changed them.
113
118
  */
114
119
  useResumable<TName extends RouteName<TCloudrop> = RouteName<TCloudrop>>(route?: TName): UseResumableResult<TName>;
120
+ /**
121
+ * The client's close(), for every route the hooks upload to: afterwards every upload resolves CLIENT_CLOSED. Without
122
+ * options, as when the user changed in another tab, multipart uploads keep their records for that user's next
123
+ * client; with `{ abort: true }`, at sign-out, every file is cancelled and the server told. Resolves once every file
124
+ * stopped and each /abort was answered. Not a hook: call it from an event handler or an effect.
125
+ */
126
+ close(options?: {
127
+ abort: true;
128
+ }): Promise<void>;
115
129
  }
116
130
  /**
117
131
  * Creates `useUpload` and `useResumable` for one server's routes: `createUploadHooks<typeof cloudrop>()`, with a type
118
132
  * import of the server's `cloudrop`. Takes the client's options, or `{ client }` to share a client. The client is
119
- * created at the first upload or resumable read in the browser, never during a server render; a wrong option makes
120
- * upload(), resume() and refresh() resolve with its INVALID_CONFIG error.
133
+ * created at the first upload, resumable read or close() in the browser, never during a server render; a wrong option
134
+ * makes upload(), resume() and refresh() resolve with its INVALID_CONFIG error.
121
135
  */
122
136
  export declare function createUploadHooks<TCloudrop extends InferableCloudrop = InferableCloudrop>(options?: UploadHooksOptions<TCloudrop>): UploadHooks<TCloudrop>;
123
137
  export type { DropProps, InputProps, UploadHooks, UploadHooksOptions, UploadItem, UseResumableResult, UseUploadOptions, UseUploadResult };
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as CloudropError } from "./errors-CUxMmFAe.js";
2
- import { n as isList, t as createCloudropClient } from "./client-Y1zUEbCj.js";
2
+ import { n as isList, t as createCloudropClient } from "./client-ePVHwvMv.js";
3
3
  import { useCallback, useEffect, useInsertionEffect, useRef, useState, useSyncExternalStore } from "react";
4
4
  // src/react/job-tracker.ts
5
5
  const endedOf = (job) => {
@@ -162,8 +162,11 @@ function createUploadStore() {
162
162
  }
163
163
  // src/react/use-resumable.ts
164
164
  const NO_UPLOADS = [];
165
+ const NO_IDS = /* @__PURE__ */ new Set();
165
166
  function useResumableWith(source, route) {
166
167
  const [uploads, setUploads] = useState(NO_UPLOADS);
168
+ const [discarding, setDiscarding] = useState(NO_IDS);
169
+ const inFlight = useRef(/* @__PURE__ */ new Map());
167
170
  const reads = useRef(0);
168
171
  const refresh = useCallback(async () => {
169
172
  const read = ++reads.current;
@@ -185,8 +188,23 @@ function useResumableWith(source, route) {
185
188
  }, [source, refresh]);
186
189
  return {
187
190
  uploads,
191
+ discarding,
188
192
  refresh,
189
- discard: useCallback((upload) => changeThenRead((client) => client.discard(upload)), [changeThenRead]),
193
+ discard: useCallback(async (upload) => {
194
+ const id = String(upload?.id);
195
+ const count = (step) => {
196
+ const calls = (inFlight.current.get(id) ?? 0) + step;
197
+ if (calls > 0) inFlight.current.set(id, calls);
198
+ else inFlight.current.delete(id);
199
+ setDiscarding(new Set(inFlight.current.keys()));
200
+ };
201
+ count(1);
202
+ try {
203
+ return await changeThenRead((client) => client.discard(upload));
204
+ } finally {
205
+ count(-1);
206
+ }
207
+ }, [changeThenRead]),
190
208
  forget: useCallback(() => changeThenRead((client) => client.forget()), [changeThenRead])
191
209
  };
192
210
  }
@@ -345,9 +363,11 @@ function createUploadHooks(options = {}) {
345
363
  function useResumable(route) {
346
364
  return useResumableWith(source, route);
347
365
  }
366
+ const close = (options) => source.client().data?.close(options) ?? Promise.resolve();
348
367
  return {
349
368
  useUpload,
350
- useResumable
369
+ useResumable,
370
+ close
351
371
  };
352
372
  }
353
373
  export { createUploadHooks };
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../src/react/job-tracker.ts","../src/react/upload-store.ts","../src/react/use-resumable.ts","../src/react/drop.ts","../src/react/use-upload.ts","../src/react.ts"],"sourcesContent":["// The jobs every hook of one factory started, for useResumable (M4-B3, M4-B12): the client's resumable() leaves out the\n// uploads this page holds (M4-F22), so the list is read again whenever that may have changed.\n\nimport type { UploadJob } from \"../client.ts\";\n\nexport interface JobTracker {\n /** Follows a job that start() or resume() just returned. */\n track(job: UploadJob<unknown>): void;\n /**\n * Calls `listener` when a tracked job starts, when one of its files ends or starts again, and when it settles;\n * returns the unsubscribe.\n */\n onChange(listener: () => void): () => void;\n /** Tells every listener that the list may have changed: a discard() or forget() through one hook. */\n changed(): void;\n}\n\n/** done + failed + aborted: it changes when a file ends, and when retry() sends a failed one again. */\nconst endedOf = (job: UploadJob<unknown>) => {\n const { done, failed, aborted } = job.getSnapshot().totals;\n return done + failed + aborted;\n};\n\nexport function createJobTracker(): JobTracker {\n const listeners = new Set<() => void>();\n // In a microtask: a file cancelled while its /complete is in doubt settles, which publishes, and only then does the\n // client delete its record and release its claim (end() and letGo in client/file-run.ts and persist.ts). A read\n // started inside the publish would be queued before that removal and list the deleted record. One microtask per\n // burst: cancelling a job ends all its files at once, and each would cost a read of IndexedDB. A job whose every file\n // has settled but whose `done` has not yet calls changed() again when it does, so the burst's read waits for that.\n let queued = false;\n const finishing = new Set<UploadJob<unknown>>();\n const changed = () => {\n if (queued) return;\n queued = true;\n queueMicrotask(() => {\n queued = false;\n if (finishing.size === 0) for (const listener of listeners) listener();\n });\n };\n return {\n track(job) {\n let ended = endedOf(job);\n let settled = false;\n const stop = job.subscribe(() => {\n const now = endedOf(job);\n if (now === ended) return;\n ended = now;\n const { done, aborted, count } = job.getSnapshot().totals;\n // Done and aborted files are final and keep no ticket: the job changes nothing more.\n if (done + aborted === count) stop();\n if (now === count && !settled) finishing.add(job);\n changed();\n });\n // A resume cancelled while its checks run ends at once, and lets the upload go only when they end, before it\n // settles.\n void job.done.then(() => {\n settled = true;\n finishing.delete(job);\n changed();\n });\n changed();\n },\n onChange(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n changed,\n };\n}\n","// What the useUpload hooks of one route render, kept in the factory for useSyncExternalStore: the files of every job\n// started on the route, in start order, each with its file's controls, and totals across those jobs. A component that\n// mounts again finds its jobs here (M4-B2). It listens to the jobs only while React listens to it, so a route no\n// component shows subscribes to nothing, and it never cancels a job: the client owns them (M4-B4).\n\nimport type { FileHandle, FileSnapshot, FileStatus, JobSnapshot, UploadJob } from \"../client.ts\";\nimport type { UploadItem } from \"./types.ts\";\n\ntype Totals = JobSnapshot<unknown>[\"totals\"];\n\nexport interface UploadView<R> {\n files: readonly UploadItem<R>[];\n totals: Totals;\n isUploading: boolean;\n}\n\n/** The state before any upload, and React's server snapshot: one constant, so hydration renders the same. */\nexport const EMPTY_VIEW: UploadView<never> = {\n files: [],\n totals: { bytes: 0, size: 0, progress: 0, speed: 0, eta: null, done: 0, failed: 0, aborted: 0, count: 0 },\n isUploading: false,\n};\n\nconst UPLOADING: ReadonlySet<FileStatus> = new Set([\"queued\", \"uploading\", \"completing\"]);\nconst SUMMED = [\"bytes\", \"size\", \"speed\", \"done\", \"failed\", \"aborted\", \"count\"] as const;\n\n/** As the client's job totals (job-snapshot.ts), summed over jobs: failed and aborted files hold no job below 1. */\nfunction sumTotals(snapshots: readonly JobSnapshot<unknown>[]): Totals {\n const sum: Totals = { ...EMPTY_VIEW.totals };\n for (const { totals } of snapshots) for (const key of SUMMED) sum[key] += totals[key];\n const isFinished = sum.done > 0 && sum.done === sum.count - sum.failed - sum.aborted;\n sum.progress = sum.size > 0 ? sum.bytes / sum.size : isFinished ? 1 : 0;\n sum.eta = sum.speed > 0 ? (sum.size - sum.bytes) / sum.speed : null;\n return sum;\n}\n\n/** True when every field is the same: the client builds a new snapshot of every file of a job when one file changes. */\nfunction isSameFile(previous: FileSnapshot<unknown>, next: FileSnapshot<unknown>): boolean {\n for (const key of Object.keys(next) as (keyof FileSnapshot<unknown>)[]) if (previous[key] !== next[key]) return false;\n return true;\n}\n\nexport interface UploadStore<R> {\n add(job: UploadJob<R>): void;\n jobs(): readonly UploadJob<R>[];\n /** Drops the jobs whose every file ended done or aborted. */\n clear(): void;\n subscribe(listener: () => void): () => void;\n getSnapshot(): UploadView<R>;\n}\n\nexport function createUploadStore<R>(): UploadStore<R> {\n let jobs: readonly UploadJob<R>[] = [];\n const listeners = new Set<() => void>();\n const stops = new Map<UploadJob<R>, () => void>();\n // Rebuilt on every change, so getSnapshot returns the same object until the next one.\n let view: UploadView<R> = EMPTY_VIEW;\n const notify = () => {\n view = build();\n for (const listener of listeners) listener();\n };\n const watch = (job: UploadJob<R>) => stops.set(job, job.subscribe(notify));\n const unwatch = (job: UploadJob<R>) => {\n stops.get(job)?.();\n stops.delete(job);\n };\n\n // Each file's last snapshot and the object made from it, by handle: the object stays while the fields do.\n const made = new WeakMap<FileHandle<R>, { snapshot: FileSnapshot<R>; file: UploadItem<R> }>();\n function fileOf(handle: FileHandle<R>, snapshot: FileSnapshot<R>): UploadItem<R> {\n const previous = made.get(handle);\n if (previous && isSameFile(previous.snapshot, snapshot)) return previous.file;\n const file = {\n ...snapshot,\n pause: () => handle.pause(),\n resume: () => handle.resume(),\n abort: () => handle.abort(),\n retry: () => handle.retry(),\n };\n made.set(handle, { snapshot, file });\n return file;\n }\n\n function build(): UploadView<R> {\n if (jobs.length === 0) return EMPTY_VIEW;\n const snapshots = jobs.map((job) => job.getSnapshot());\n // A job's handles and its snapshot's files are in the same order: the order the files were passed.\n const files = jobs.flatMap((job, index) =>\n (snapshots[index]?.files ?? []).map((snapshot, at) => fileOf(job.files[at] as FileHandle<R>, snapshot)),\n );\n return { files, totals: sumTotals(snapshots), isUploading: files.some((file) => UPLOADING.has(file.status)) };\n }\n\n return {\n add(job) {\n jobs = [...jobs, job];\n if (listeners.size > 0) watch(job);\n notify();\n },\n jobs: () => jobs,\n clear() {\n // A failed file stays: retry() can still send it, and the client keeps its ticket and parts for that.\n const kept = jobs.filter((job) => {\n const { done, aborted, count } = job.getSnapshot().totals;\n return done + aborted < count;\n });\n for (const job of jobs) if (!kept.includes(job)) unwatch(job);\n jobs = kept;\n notify();\n },\n subscribe(listener) {\n if (listeners.size === 0) {\n for (const job of jobs) watch(job);\n // Nobody heard what the jobs did meanwhile, such as under a hidden <Activity>.\n view = build();\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) for (const job of jobs) unwatch(job);\n };\n },\n getSnapshot: () => view,\n };\n}\n","// useResumable (spec §6.1, M4-B3, M4-B12): the client's resumable() list, which leaves out the uploads this page holds\n// (M4-F22), read after mount and whenever a job of the hooks may have changed it (job-tracker.ts). Only reads happen in\n// the effect; StrictMode's second effect reads once more and changes nothing.\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { CloudropClient, Result, ResumableUpload } from \"../client.ts\";\nimport type { UseResumableResult } from \"./types.ts\";\nimport type { HookSource } from \"./use-upload.ts\";\n\n/** One constant, so the server render and the first browser render agree. */\nconst NO_UPLOADS: readonly ResumableUpload[] = [];\n\nexport function useResumableWith(source: HookSource, route?: string): UseResumableResult<string> {\n const [uploads, setUploads] = useState(NO_UPLOADS);\n const reads = useRef(0);\n const refresh = useCallback(async (): Promise<Result<ResumableUpload[]>> => {\n const read = ++reads.current;\n const client = source.client();\n const answer = client.error ? client : await client.data.resumable(route);\n // A read that answers after a newer one started must not replace the newer list.\n if (read === reads.current) setUploads(answer.data ?? NO_UPLOADS);\n return answer;\n }, [source, route]);\n useEffect(() => {\n void refresh();\n return source.onChange(() => void refresh());\n }, [source, refresh]);\n /**\n * Runs `change` on the client, then reads the list again, whatever it answered: a failed discard keeps its record.\n * Every other useResumable of the factory reads again too, since one route's discard shows in a list of every route.\n */\n const changeThenRead = useCallback(\n async <T>(change: (client: CloudropClient) => Promise<Result<T>>): Promise<Result<T>> => {\n const client = source.client();\n const answer = client.error ? client : await change(client.data);\n source.changed();\n await refresh();\n return answer;\n },\n [source, refresh],\n );\n const discard = useCallback(\n (upload: ResumableUpload) => changeThenRead((client) => client.discard(upload)),\n [changeThenRead],\n );\n const forget = useCallback(() => changeThenRead((client) => client.forget()), [changeThenRead]);\n return { uploads, refresh, discard, forget };\n}\n","// getDropProps(): drag-and-drop on any element (spec §6.1, M4-B2).\n\nimport type { DragEvent } from \"react\";\nimport type { DropProps } from \"./types.ts\";\n\n/**\n * Handlers that report whether files are dragged over the element and pass dropped files on. Enters and leaves are\n * counted rather than toggled: moving onto a child fires dragenter on the child before dragleave on the element, so a\n * toggle would flicker off over every child. Only drags that carry files count: dragged text or a link keeps the\n * browser's own behaviour, such as dropping text into an input inside the element.\n */\nexport function createDropHandlers(setDragOver: (isOver: boolean) => void, onDrop: (files: File[]) => void): DropProps {\n let depth = 0;\n const hasFiles = (event: DragEvent<HTMLElement>) => event.dataTransfer.types.includes(\"Files\");\n return {\n onDragEnter(event) {\n if (!hasFiles(event)) return;\n event.preventDefault();\n depth += 1;\n setDragOver(true);\n },\n // A browser drops only on an element whose dragover was cancelled.\n onDragOver(event) {\n if (hasFiles(event)) event.preventDefault();\n },\n onDragLeave(event) {\n if (!hasFiles(event)) return;\n depth = Math.max(0, depth - 1);\n if (depth === 0) setDragOver(false);\n },\n onDrop(event) {\n if (!hasFiles(event)) return;\n // Without it the browser opens the file in place of the page.\n event.preventDefault();\n depth = 0;\n setDragOver(false);\n onDrop(Array.from(event.dataTransfer.files));\n },\n };\n}\n","// useUpload (spec §6.1, M4-B2, M4-B4): the jobs a factory's hooks started on one route, rendered through\n// useSyncExternalStore. No upload starts in an effect or during render, so StrictMode's second render and second effect\n// start nothing.\n\nimport { useCallback, useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { isList } from \"../client/arguments.ts\";\nimport type { CloudropClient, Result, ResumableUpload, UploadJob, UploadResult } from \"../client.ts\";\nimport { createDropHandlers } from \"./drop.ts\";\nimport type { JobTracker } from \"./job-tracker.ts\";\nimport type { InputProps, UseUploadOptions, UseUploadResult } from \"./types.ts\";\nimport { EMPTY_VIEW, type UploadStore } from \"./upload-store.ts\";\n\n/** What createUploadHooks shares with its hooks: the client and the jobs they started. */\nexport interface HookSource extends JobTracker {\n /** The jobs started on `route` through any hook of the factory: they outlive the component that started them. */\n storeOf(route: string): UploadStore<unknown>;\n /**\n * The client, created on the first call: in a handler or an effect, so never during a server render. A wrong option\n * gives its INVALID_CONFIG error, which upload(), resume() and refresh() resolve with.\n */\n client(): Result<CloudropClient>;\n}\n\ninterface Latest {\n route: string;\n options: UseUploadOptions<unknown>;\n}\n\ntype Hook = UseUploadResult<unknown, string, unknown>;\n\n/** Everything of a hook that keeps its identity across renders: React keeps one per component instance. */\nfunction createController(source: HookSource, initial: Latest, setDragOver: (isOver: boolean) => void) {\n // Event handlers read the committed render's route and options, so the functions below never change.\n const controller = { latest: initial };\n const jobs = () => source.storeOf(controller.latest.route).jobs();\n\n function start(begin: (client: CloudropClient) => UploadJob<unknown>): Promise<UploadResult<unknown>> {\n const client = source.client();\n if (client.error) return Promise.resolve({ data: null, error: client.error });\n const job = begin(client.data);\n source.storeOf(controller.latest.route).add(job);\n source.track(job);\n return job.done;\n }\n const upload: Hook[\"upload\"] = (files, call = {}) => {\n // Anything but null or an empty list goes to the client, which checks it is a File or a list of them (readFiles in\n // client/arguments.ts).\n if (files === null || (isList(files) && files.length === 0)) return Promise.resolve(null);\n const { route, options } = controller.latest;\n const metadata = \"metadata\" in call ? call.metadata : options.metadata;\n return start((client) => client.start(route, files, { metadata }));\n };\n function resume(): void;\n function resume(upload: ResumableUpload, file: File): Promise<UploadResult<unknown>>;\n function resume(...record: [] | [ResumableUpload, File]): Promise<UploadResult<unknown>> | undefined {\n if (record.length === 2) return start((client) => client.resume(...record));\n for (const job of jobs()) job.resume();\n }\n /** Files from a pick or a drop: no caller sees the result, so a wrong client option is thrown in a task (M3-U8). */\n const take = (files: File[]) => {\n const { error } = source.client();\n if (!error) return void upload(files);\n setTimeout(() => {\n throw error;\n });\n };\n const onChange: InputProps[\"onChange\"] = (event) => {\n const input = event.currentTarget;\n const picked = Array.from(input.files ?? []);\n // Cleared so that picking the same file again uploads it: Chromium fires `cancel`, not `change`, for an unchanged\n // selection.\n input.value = \"\";\n take(picked);\n };\n const dropProps = createDropHandlers(setDragOver, (files) =>\n take(controller.latest.options.multiple ? files : files.slice(0, 1)),\n );\n const actions: Pick<Hook, \"upload\" | \"pause\" | \"resume\" | \"abort\" | \"retry\" | \"clear\" | \"getDropProps\"> = {\n upload,\n pause: () => {\n for (const job of jobs()) job.pause();\n },\n resume,\n abort: () => {\n for (const job of jobs()) job.abort();\n },\n retry: async () => {\n await Promise.all(jobs().map((job) => job.retry()));\n },\n clear: () => source.storeOf(controller.latest.route).clear(),\n getDropProps: () => dropProps,\n };\n return Object.assign(controller, { actions, onChange });\n}\n\nconst serverView = () => EMPTY_VIEW;\n\nexport function useUploadWith(source: HookSource, route: string, options: UseUploadOptions<unknown> = {}): Hook {\n const [isDragOver, setDragOver] = useState(false);\n const [controller] = useState(() => createController(source, { route, options }, setDragOver));\n useInsertionEffect(() => {\n controller.latest = { route, options };\n });\n const store = source.storeOf(route);\n const view = useSyncExternalStore(store.subscribe, store.getSnapshot, serverView);\n const { multiple = false, accept } = options;\n // Built from this render's options, so a changed `accept` reaches the input in the same render.\n const getInputProps = useCallback(\n (): InputProps => ({ type: \"file\", multiple, accept, onChange: controller.onChange }),\n [multiple, accept, controller],\n );\n return { ...view, ...controller.actions, isDragOver, getInputProps };\n}\n","// The cloudrop/react entry: React hooks over cloudrop/client (spec §6, M4-B1 to M4-B6). `react` is an optional peer\n// dependency of this entry only (M4-B7).\n\nimport {\n type CloudropClient,\n CloudropError,\n createCloudropClient,\n type InferableCloudrop,\n type Result,\n} from \"./client.ts\";\nimport { createJobTracker } from \"./react/job-tracker.ts\";\nimport type { UploadHooks, UploadHooksOptions, UseUploadOptions } from \"./react/types.ts\";\nimport { createUploadStore, type UploadStore } from \"./react/upload-store.ts\";\nimport { useResumableWith } from \"./react/use-resumable.ts\";\nimport { type HookSource, useUploadWith } from \"./react/use-upload.ts\";\n\nexport type {\n DropProps,\n InputProps,\n UploadHooks,\n UploadHooksOptions,\n UploadItem,\n UseResumableResult,\n UseUploadOptions,\n UseUploadResult,\n} from \"./react/types.ts\";\n\n/**\n * Creates `useUpload` and `useResumable` for one server's routes: `createUploadHooks<typeof cloudrop>()`, with a type\n * import of the server's `cloudrop`. Takes the client's options, or `{ client }` to share a client. The client is\n * created at the first upload or resumable read in the browser, never during a server render; a wrong option makes\n * upload(), resume() and refresh() resolve with its INVALID_CONFIG error.\n */\nexport function createUploadHooks<TCloudrop extends InferableCloudrop = InferableCloudrop>(\n options: UploadHooksOptions<TCloudrop> = {},\n): UploadHooks<TCloudrop> {\n let created: Result<CloudropClient> | undefined;\n function createClient(): Result<CloudropClient> {\n try {\n const client = \"client\" in options ? options.client : createCloudropClient<TCloudrop>(options);\n return { data: client as CloudropClient, error: null };\n } catch (error) {\n // createCloudropClient throws only its configuration error (readOptions in client.ts).\n if (error instanceof CloudropError) return { data: null, error };\n throw error;\n }\n }\n const stores = new Map<string, UploadStore<unknown>>();\n const source: HookSource = {\n ...createJobTracker(),\n client() {\n created ??= createClient();\n return created;\n },\n storeOf(route) {\n const store = stores.get(route) ?? createUploadStore();\n stores.set(route, store);\n return store;\n },\n };\n // The factory (M4-B1) runs once, at module level where an app defines its hooks, so the hooks it returns never\n // change.\n // biome-ignore lint/correctness/noComponentHookFactories: route types are inferred only through a factory.\n function useUpload(route: string, options?: UseUploadOptions<unknown>) {\n return useUploadWith(source, route, options);\n }\n // biome-ignore lint/correctness/noComponentHookFactories: as useUpload above.\n function useResumable(route?: string) {\n return useResumableWith(source, route);\n }\n // The hooks run on route names as plain strings: the casts give them the types the server's type carries, as\n // createCloudropClient does.\n return { useUpload, useResumable } as UploadHooks<TCloudrop>;\n}\n"],"mappings":";;;;AAkBA,MAAM,WAAW,QAA4B;CAC3C,MAAM,EAAE,MA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J,SAAS,eAAuC;EAC9C,IAAI;GAEF,OAAO;IAAE,MADM,YAAY,UAAU,QAAQ,SAAS,qBAAgC,OAAO;IACpD,OAAO;GAAK;EACvD,SAAS,OAAO;GAEd,IAAI,iBAAiB,eAAe,OAAO;IAAE,MAAM;IAAM;GAAM;GAC/D,MAAM;EACR;CACF;CACA,MAAM,yBAAS,IAAI,IAAkC;CACrD,MAAM,SAAqB;EACzB,GAAG,iBAAiB;EACpB,SAAS;GACP,YAAY,aAAa;GACzB,OAAO;EACT;EACA,QAAQ,OAAO;GACb,MAAM,QAAQ,OAAO,IAAI,KAAK,KAAK,kBAAkB;GACrD,OAAO,IAAI,OAAO,KAAK;GACvB,OAAO;EACT;CACF;CAIA,SAAS,UAAU,OAAe,SAAqC;EACrE,OAAO,cAAc,QAAQ,OAAO,OAAO;CAC7C;CAEA,SAAS,aAAa,OAAgB;EACpC,OAAO,iBAAiB,QAAQ,KAAK;CACvC;CAGA,OAAO;EAAE;EAAW;CAAa;AACnC"}
1
+ {"version":3,"file":"react.js","names":[],"sources":["../src/react/job-tracker.ts","../src/react/upload-store.ts","../src/react/use-resumable.ts","../src/react/drop.ts","../src/react/use-upload.ts","../src/react.ts"],"sourcesContent":["// The jobs every hook of one factory started, for useResumable (M4-B3, M4-B12): the client's resumable() leaves out the\n// uploads this page holds (M4-F22), so the list is read again whenever that may have changed.\n\nimport type { UploadJob } from \"../client.ts\";\n\nexport interface JobTracker {\n /** Follows a job that start() or resume() just returned. */\n track(job: UploadJob<unknown>): void;\n /**\n * Calls `listener` when a tracked job starts, when one of its files ends or starts again, and when it settles;\n * returns the unsubscribe.\n */\n onChange(listener: () => void): () => void;\n /** Tells every listener that the list may have changed: a discard() or forget() through one hook. */\n changed(): void;\n}\n\n/** done + failed + aborted: it changes when a file ends, and when retry() sends a failed one again. */\nconst endedOf = (job: UploadJob<unknown>) => {\n const { done, failed, aborted } = job.getSnapshot().totals;\n return done + failed + aborted;\n};\n\nexport function createJobTracker(): JobTracker {\n const listeners = new Set<() => void>();\n // In a microtask: a file cancelled while its /complete is in doubt settles, which publishes, and only then does the\n // client delete its record and release its claim (end() and letGo in client/file-run.ts and persist.ts). A read\n // started inside the publish would be queued before that removal and list the deleted record. One microtask per\n // burst: cancelling a job ends all its files at once, and each would cost a read of IndexedDB. A job whose every file\n // has settled but whose `done` has not yet calls changed() again when it does, so the burst's read waits for that.\n let queued = false;\n const finishing = new Set<UploadJob<unknown>>();\n const changed = () => {\n if (queued) return;\n queued = true;\n queueMicrotask(() => {\n queued = false;\n if (finishing.size === 0) for (const listener of listeners) listener();\n });\n };\n return {\n track(job) {\n let ended = endedOf(job);\n let settled = false;\n const stop = job.subscribe(() => {\n const now = endedOf(job);\n if (now === ended) return;\n ended = now;\n const { done, aborted, count } = job.getSnapshot().totals;\n // Done and aborted files are final and keep no ticket: the job changes nothing more.\n if (done + aborted === count) stop();\n if (now === count && !settled) finishing.add(job);\n changed();\n });\n // A resume cancelled while its checks run ends at once, and lets the upload go only when they end, before it\n // settles.\n void job.done.then(() => {\n settled = true;\n finishing.delete(job);\n changed();\n });\n changed();\n },\n onChange(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n changed,\n };\n}\n","// What the useUpload hooks of one route render, kept in the factory for useSyncExternalStore: the files of every job\n// started on the route, in start order, each with its file's controls, and totals across those jobs. A component that\n// mounts again finds its jobs here (M4-B2). It listens to the jobs only while React listens to it, so a route no\n// component shows subscribes to nothing, and it never cancels a job: the client owns them (M4-B4).\n\nimport type { FileHandle, FileSnapshot, FileStatus, JobSnapshot, UploadJob } from \"../client.ts\";\nimport type { UploadItem } from \"./types.ts\";\n\ntype Totals = JobSnapshot<unknown>[\"totals\"];\n\nexport interface UploadView<R> {\n files: readonly UploadItem<R>[];\n totals: Totals;\n isUploading: boolean;\n}\n\n/** The state before any upload, and React's server snapshot: one constant, so hydration renders the same. */\nexport const EMPTY_VIEW: UploadView<never> = {\n files: [],\n totals: { bytes: 0, size: 0, progress: 0, speed: 0, eta: null, done: 0, failed: 0, aborted: 0, count: 0 },\n isUploading: false,\n};\n\nconst UPLOADING: ReadonlySet<FileStatus> = new Set([\"queued\", \"uploading\", \"completing\"]);\nconst SUMMED = [\"bytes\", \"size\", \"speed\", \"done\", \"failed\", \"aborted\", \"count\"] as const;\n\n/** As the client's job totals (job-snapshot.ts), summed over jobs: failed and aborted files hold no job below 1. */\nfunction sumTotals(snapshots: readonly JobSnapshot<unknown>[]): Totals {\n const sum: Totals = { ...EMPTY_VIEW.totals };\n for (const { totals } of snapshots) for (const key of SUMMED) sum[key] += totals[key];\n const isFinished = sum.done > 0 && sum.done === sum.count - sum.failed - sum.aborted;\n sum.progress = sum.size > 0 ? sum.bytes / sum.size : isFinished ? 1 : 0;\n sum.eta = sum.speed > 0 ? (sum.size - sum.bytes) / sum.speed : null;\n return sum;\n}\n\n/** True when every field is the same: the client builds a new snapshot of every file of a job when one file changes. */\nfunction isSameFile(previous: FileSnapshot<unknown>, next: FileSnapshot<unknown>): boolean {\n for (const key of Object.keys(next) as (keyof FileSnapshot<unknown>)[]) if (previous[key] !== next[key]) return false;\n return true;\n}\n\nexport interface UploadStore<R> {\n add(job: UploadJob<R>): void;\n jobs(): readonly UploadJob<R>[];\n /** Drops the jobs whose every file ended done or aborted. */\n clear(): void;\n subscribe(listener: () => void): () => void;\n getSnapshot(): UploadView<R>;\n}\n\nexport function createUploadStore<R>(): UploadStore<R> {\n let jobs: readonly UploadJob<R>[] = [];\n const listeners = new Set<() => void>();\n const stops = new Map<UploadJob<R>, () => void>();\n // Rebuilt on every change, so getSnapshot returns the same object until the next one.\n let view: UploadView<R> = EMPTY_VIEW;\n const notify = () => {\n view = build();\n for (const listener of listeners) listener();\n };\n const watch = (job: UploadJob<R>) => stops.set(job, job.subscribe(notify));\n const unwatch = (job: UploadJob<R>) => {\n stops.get(job)?.();\n stops.delete(job);\n };\n\n // Each file's last snapshot and the object made from it, by handle: the object stays while the fields do.\n const made = new WeakMap<FileHandle<R>, { snapshot: FileSnapshot<R>; file: UploadItem<R> }>();\n function fileOf(handle: FileHandle<R>, snapshot: FileSnapshot<R>): UploadItem<R> {\n const previous = made.get(handle);\n if (previous && isSameFile(previous.snapshot, snapshot)) return previous.file;\n const file = {\n ...snapshot,\n pause: () => handle.pause(),\n resume: () => handle.resume(),\n abort: () => handle.abort(),\n retry: () => handle.retry(),\n };\n made.set(handle, { snapshot, file });\n return file;\n }\n\n function build(): UploadView<R> {\n if (jobs.length === 0) return EMPTY_VIEW;\n const snapshots = jobs.map((job) => job.getSnapshot());\n // A job's handles and its snapshot's files are in the same order: the order the files were passed.\n const files = jobs.flatMap((job, index) =>\n (snapshots[index]?.files ?? []).map((snapshot, at) => fileOf(job.files[at] as FileHandle<R>, snapshot)),\n );\n return { files, totals: sumTotals(snapshots), isUploading: files.some((file) => UPLOADING.has(file.status)) };\n }\n\n return {\n add(job) {\n jobs = [...jobs, job];\n if (listeners.size > 0) watch(job);\n notify();\n },\n jobs: () => jobs,\n clear() {\n // A failed file stays: retry() can still send it, and the client keeps its ticket and parts for that.\n const kept = jobs.filter((job) => {\n const { done, aborted, count } = job.getSnapshot().totals;\n return done + aborted < count;\n });\n for (const job of jobs) if (!kept.includes(job)) unwatch(job);\n jobs = kept;\n notify();\n },\n subscribe(listener) {\n if (listeners.size === 0) {\n for (const job of jobs) watch(job);\n // Nobody heard what the jobs did meanwhile, such as under a hidden <Activity>.\n view = build();\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) for (const job of jobs) unwatch(job);\n };\n },\n getSnapshot: () => view,\n };\n}\n","// useResumable (spec §6.1, M4-B3, M4-B12): the client's resumable() list, which leaves out the uploads this page holds\n// (M4-F22), read after mount and whenever a job of the hooks may have changed it (job-tracker.ts). Only reads happen in\n// the effect; StrictMode's second effect reads once more and changes nothing.\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { CloudropClient, Result, ResumableUpload } from \"../client.ts\";\nimport type { UseResumableResult } from \"./types.ts\";\nimport type { HookSource } from \"./use-upload.ts\";\n\n/** Constants, so the server render and the first browser render agree. */\nconst NO_UPLOADS: readonly ResumableUpload[] = [];\nconst NO_IDS: ReadonlySet<string> = new Set();\n\nexport function useResumableWith(source: HookSource, route?: string): UseResumableResult<string> {\n const [uploads, setUploads] = useState(NO_UPLOADS);\n const [discarding, setDiscarding] = useState(NO_IDS);\n // Calls in flight per id: a second press, refused UPLOAD_IN_USE at once, must not end the first one's hold.\n const inFlight = useRef(new Map<string, number>());\n const reads = useRef(0);\n const refresh = useCallback(async (): Promise<Result<ResumableUpload[]>> => {\n const read = ++reads.current;\n const client = source.client();\n const answer = client.error ? client : await client.data.resumable(route);\n // A read that answers after a newer one started must not replace the newer list.\n if (read === reads.current) setUploads(answer.data ?? NO_UPLOADS);\n return answer;\n }, [source, route]);\n useEffect(() => {\n void refresh();\n return source.onChange(() => void refresh());\n }, [source, refresh]);\n /**\n * Runs `change` on the client, then reads the list again, whatever it answered: a failed discard keeps its record.\n * Every other useResumable of the factory reads again too, since one route's discard shows in a list of every route.\n */\n const changeThenRead = useCallback(\n async <T>(change: (client: CloudropClient) => Promise<Result<T>>): Promise<Result<T>> => {\n const client = source.client();\n const answer = client.error ? client : await change(client.data);\n source.changed();\n await refresh();\n return answer;\n },\n [source, refresh],\n );\n const discard = useCallback(\n async (upload: ResumableUpload) => {\n // The client refuses a wrong argument at once, so its id is held only until then.\n const id = String(upload?.id);\n const count = (step: number) => {\n const calls = (inFlight.current.get(id) ?? 0) + step;\n if (calls > 0) inFlight.current.set(id, calls);\n else inFlight.current.delete(id);\n setDiscarding(new Set(inFlight.current.keys()));\n };\n count(1);\n try {\n return await changeThenRead((client) => client.discard(upload));\n } finally {\n count(-1);\n }\n },\n [changeThenRead],\n );\n const forget = useCallback(() => changeThenRead((client) => client.forget()), [changeThenRead]);\n return { uploads, discarding, refresh, discard, forget };\n}\n","// getDropProps(): drag-and-drop on any element (spec §6.1, M4-B2).\n\nimport type { DragEvent } from \"react\";\nimport type { DropProps } from \"./types.ts\";\n\n/**\n * Handlers that report whether files are dragged over the element and pass dropped files on. Enters and leaves are\n * counted rather than toggled: moving onto a child fires dragenter on the child before dragleave on the element, so a\n * toggle would flicker off over every child. Only drags that carry files count: dragged text or a link keeps the\n * browser's own behaviour, such as dropping text into an input inside the element.\n */\nexport function createDropHandlers(setDragOver: (isOver: boolean) => void, onDrop: (files: File[]) => void): DropProps {\n let depth = 0;\n const hasFiles = (event: DragEvent<HTMLElement>) => event.dataTransfer.types.includes(\"Files\");\n return {\n onDragEnter(event) {\n if (!hasFiles(event)) return;\n event.preventDefault();\n depth += 1;\n setDragOver(true);\n },\n // A browser drops only on an element whose dragover was cancelled.\n onDragOver(event) {\n if (hasFiles(event)) event.preventDefault();\n },\n onDragLeave(event) {\n if (!hasFiles(event)) return;\n depth = Math.max(0, depth - 1);\n if (depth === 0) setDragOver(false);\n },\n onDrop(event) {\n if (!hasFiles(event)) return;\n // Without it the browser opens the file in place of the page.\n event.preventDefault();\n depth = 0;\n setDragOver(false);\n onDrop(Array.from(event.dataTransfer.files));\n },\n };\n}\n","// useUpload (spec §6.1, M4-B2, M4-B4): the jobs a factory's hooks started on one route, rendered through\n// useSyncExternalStore. No upload starts in an effect or during render, so StrictMode's second render and second effect\n// start nothing.\n\nimport { useCallback, useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { isList } from \"../client/arguments.ts\";\nimport type { CloudropClient, Result, ResumableUpload, UploadJob, UploadResult } from \"../client.ts\";\nimport { createDropHandlers } from \"./drop.ts\";\nimport type { JobTracker } from \"./job-tracker.ts\";\nimport type { InputProps, UseUploadOptions, UseUploadResult } from \"./types.ts\";\nimport { EMPTY_VIEW, type UploadStore } from \"./upload-store.ts\";\n\n/** What createUploadHooks shares with its hooks: the client and the jobs they started. */\nexport interface HookSource extends JobTracker {\n /** The jobs started on `route` through any hook of the factory: they outlive the component that started them. */\n storeOf(route: string): UploadStore<unknown>;\n /**\n * The client, created on the first call: in a handler or an effect, so never during a server render. A wrong option\n * gives its INVALID_CONFIG error, which upload(), resume() and refresh() resolve with.\n */\n client(): Result<CloudropClient>;\n}\n\ninterface Latest {\n route: string;\n options: UseUploadOptions<unknown>;\n}\n\ntype Hook = UseUploadResult<unknown, string, unknown>;\n\n/** Everything of a hook that keeps its identity across renders: React keeps one per component instance. */\nfunction createController(source: HookSource, initial: Latest, setDragOver: (isOver: boolean) => void) {\n // Event handlers read the committed render's route and options, so the functions below never change.\n const controller = { latest: initial };\n const jobs = () => source.storeOf(controller.latest.route).jobs();\n\n function start(begin: (client: CloudropClient) => UploadJob<unknown>): Promise<UploadResult<unknown>> {\n const client = source.client();\n if (client.error) return Promise.resolve({ data: null, error: client.error });\n const job = begin(client.data);\n source.storeOf(controller.latest.route).add(job);\n source.track(job);\n return job.done;\n }\n const upload: Hook[\"upload\"] = (files, call = {}) => {\n // Anything but null or an empty list goes to the client, which checks it is a File or a list of them (readFiles in\n // client/arguments.ts).\n if (files === null || (isList(files) && files.length === 0)) return Promise.resolve(null);\n const { route, options } = controller.latest;\n const metadata = \"metadata\" in call ? call.metadata : options.metadata;\n return start((client) => client.start(route, files, { metadata }));\n };\n function resume(): void;\n function resume(upload: ResumableUpload, file: File): Promise<UploadResult<unknown>>;\n function resume(...record: [] | [ResumableUpload, File]): Promise<UploadResult<unknown>> | undefined {\n if (record.length === 2) return start((client) => client.resume(...record));\n for (const job of jobs()) job.resume();\n }\n /** Files from a pick or a drop: no caller sees the result, so a wrong client option is thrown in a task (M3-U8). */\n const take = (files: File[]) => {\n const { error } = source.client();\n if (!error) return void upload(files);\n setTimeout(() => {\n throw error;\n });\n };\n const onChange: InputProps[\"onChange\"] = (event) => {\n const input = event.currentTarget;\n const picked = Array.from(input.files ?? []);\n // Cleared so that picking the same file again uploads it: Chromium fires `cancel`, not `change`, for an unchanged\n // selection.\n input.value = \"\";\n take(picked);\n };\n const dropProps = createDropHandlers(setDragOver, (files) =>\n take(controller.latest.options.multiple ? files : files.slice(0, 1)),\n );\n const actions: Pick<Hook, \"upload\" | \"pause\" | \"resume\" | \"abort\" | \"retry\" | \"clear\" | \"getDropProps\"> = {\n upload,\n pause: () => {\n for (const job of jobs()) job.pause();\n },\n resume,\n abort: () => {\n for (const job of jobs()) job.abort();\n },\n retry: async () => {\n await Promise.all(jobs().map((job) => job.retry()));\n },\n clear: () => source.storeOf(controller.latest.route).clear(),\n getDropProps: () => dropProps,\n };\n return Object.assign(controller, { actions, onChange });\n}\n\nconst serverView = () => EMPTY_VIEW;\n\nexport function useUploadWith(source: HookSource, route: string, options: UseUploadOptions<unknown> = {}): Hook {\n const [isDragOver, setDragOver] = useState(false);\n const [controller] = useState(() => createController(source, { route, options }, setDragOver));\n useInsertionEffect(() => {\n controller.latest = { route, options };\n });\n const store = source.storeOf(route);\n const view = useSyncExternalStore(store.subscribe, store.getSnapshot, serverView);\n const { multiple = false, accept } = options;\n // Built from this render's options, so a changed `accept` reaches the input in the same render.\n const getInputProps = useCallback(\n (): InputProps => ({ type: \"file\", multiple, accept, onChange: controller.onChange }),\n [multiple, accept, controller],\n );\n return { ...view, ...controller.actions, isDragOver, getInputProps };\n}\n","// The cloudrop/react entry: React hooks over cloudrop/client (spec §6, M4-B1 to M4-B6). `react` is an optional peer\n// dependency of this entry only (M4-B7).\n\nimport {\n type CloudropClient,\n CloudropError,\n createCloudropClient,\n type InferableCloudrop,\n type Result,\n} from \"./client.ts\";\nimport { createJobTracker } from \"./react/job-tracker.ts\";\nimport type { UploadHooks, UploadHooksOptions, UseUploadOptions } from \"./react/types.ts\";\nimport { createUploadStore, type UploadStore } from \"./react/upload-store.ts\";\nimport { useResumableWith } from \"./react/use-resumable.ts\";\nimport { type HookSource, useUploadWith } from \"./react/use-upload.ts\";\n\nexport type {\n DropProps,\n InputProps,\n UploadHooks,\n UploadHooksOptions,\n UploadItem,\n UseResumableResult,\n UseUploadOptions,\n UseUploadResult,\n} from \"./react/types.ts\";\n\n/**\n * Creates `useUpload` and `useResumable` for one server's routes: `createUploadHooks<typeof cloudrop>()`, with a type\n * import of the server's `cloudrop`. Takes the client's options, or `{ client }` to share a client. The client is\n * created at the first upload, resumable read or close() in the browser, never during a server render; a wrong option\n * makes upload(), resume() and refresh() resolve with its INVALID_CONFIG error.\n */\nexport function createUploadHooks<TCloudrop extends InferableCloudrop = InferableCloudrop>(\n options: UploadHooksOptions<TCloudrop> = {},\n): UploadHooks<TCloudrop> {\n let created: Result<CloudropClient> | undefined;\n function createClient(): Result<CloudropClient> {\n try {\n const client = \"client\" in options ? options.client : createCloudropClient<TCloudrop>(options);\n return { data: client as CloudropClient, error: null };\n } catch (error) {\n // createCloudropClient throws only its configuration error (readOptions in client.ts).\n if (error instanceof CloudropError) return { data: null, error };\n throw error;\n }\n }\n const stores = new Map<string, UploadStore<unknown>>();\n const source: HookSource = {\n ...createJobTracker(),\n client() {\n created ??= createClient();\n return created;\n },\n storeOf(route) {\n const store = stores.get(route) ?? createUploadStore();\n stores.set(route, store);\n return store;\n },\n };\n // The factory (M4-B1) runs once, at module level where an app defines its hooks, so the hooks it returns never\n // change.\n // biome-ignore lint/correctness/noComponentHookFactories: route types are inferred only through a factory.\n function useUpload(route: string, options?: UseUploadOptions<unknown>) {\n return useUploadWith(source, route, options);\n }\n // biome-ignore lint/correctness/noComponentHookFactories: as useUpload above.\n function useResumable(route?: string) {\n return useResumableWith(source, route);\n }\n // The client's own stop, every route's uploads included (M8-L7); a client with a wrong option has nothing to stop.\n const close: UploadHooks<TCloudrop>[\"close\"] = (options) => source.client().data?.close(options) ?? Promise.resolve();\n // The hooks run on route names as plain strings: the casts give them the types the server's type carries, as\n // createCloudropClient does.\n return { useUpload, useResumable, close } as UploadHooks<TCloudrop>;\n}\n"],"mappings":";;;;AAkBA,MAAM,WAAW,QAA4B;CAC3C,MAAM,EAAE,MAAM,QAAQ,YAAY,IAAI,YAAY,CAAC,CAAC;CACpD,OAAO,OAAO,SAAS;AACzB;AAEA,SAAgB,mBAA+B;CAC7C,MAAM,4BAA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;CACvC,CAAC;CACD,MAAM,QAAQ,OAAO,QAAQ,KAAK;CAClC,MAAM,OAAO,qBAAqB,MAAM,WAAW,MAAM,aAAa,UAAU;CAChF,MAAM,EAAE,WAAW,OAAO,WAAW;CAErC,MAAM,gBAAgB,mBACD;EAAE,MAAM;EAAQ;EAAU;EAAQ,UAAU,WAAW;CAAS,IACnF;EAAC;EAAU;EAAQ;CAAU,CAC/B;CACA,OAAO;EAAE,GAAG;EAAM,GAAG,WAAW;EAAS;EAAY;CAAc;AACrE;;AC/EA,SAAgB,kBACd,UAAyC,CAAC,GAClB;CACxB,IAAI;CACJ,SAAS,eAAuC;EAC9C,IAAI;GAEF,OAAO;IAAE,MADM,YAAY,UAAU,QAAQ,SAAS,qBAAgC,OAAO;IACpD,OAAO;GAAK;EACvD,SAAS,OAAO;GAEd,IAAI,iBAAiB,eAAe,OAAO;IAAE,MAAM;IAAM;GAAM;GAC/D,MAAM;EACR;CACF;CACA,MAAM,yBAAS,IAAI,IAAkC;CACrD,MAAM,SAAqB;EACzB,GAAG,iBAAiB;EACpB,SAAS;GACP,YAAY,aAAa;GACzB,OAAO;EACT;EACA,QAAQ,OAAO;GACb,MAAM,QAAQ,OAAO,IAAI,KAAK,KAAK,kBAAkB;GACrD,OAAO,IAAI,OAAO,KAAK;GACvB,OAAO;EACT;CACF;CAIA,SAAS,UAAU,OAAe,SAAqC;EACrE,OAAO,cAAc,QAAQ,OAAO,OAAO;CAC7C;CAEA,SAAS,aAAa,OAAgB;EACpC,OAAO,iBAAiB,QAAQ,KAAK;CACvC;CAEA,MAAM,SAA0C,YAAY,OAAO,OAAO,CAAC,CAAC,MAAM,MAAM,OAAO,KAAK,QAAQ,QAAQ;CAGpH,OAAO;EAAE;EAAW;EAAc;CAAM;AAC1C"}
@@ -44,13 +44,14 @@ const POLICY = [
44
44
  "maxFiles",
45
45
  "metadata",
46
46
  "visibility",
47
+ "replace",
47
48
  "authorize"
48
49
  ];
49
50
  function checkPlacement(policy, callbacks) {
50
51
  const callback = CALLBACKS.find((name) => Object.hasOwn(policy, name));
51
52
  if (callback) throw configError(`route(): ${callback} belongs in the second argument, which holds prefix, key, owner, onComplete and afterComplete: route({ accept, maxSize, authorize }, { ${callback} }).`);
52
53
  const option = POLICY.find((name) => Object.hasOwn(callbacks, name));
53
- if (option) throw configError(`route(): ${option} belongs in the first argument, which holds accept, maxSize, maxFiles, metadata, visibility and authorize. The second takes only prefix, key, owner, onComplete and afterComplete.`);
54
+ if (option) throw configError(`route(): ${option} belongs in the first argument, which holds accept, maxSize, maxFiles, metadata, visibility, replace and authorize. The second takes only prefix, key, owner, onComplete and afterComplete.`);
54
55
  }
55
56
  function route(policy, callbacks) {
56
57
  const given = policy ?? {};
@@ -69,4 +70,4 @@ function routeFor(store) {
69
70
  const storeOfRoute = (definition) => definition[STORE];
70
71
  export { route as a, unauthorized as c, refusalError as i, forbidden as n, routeFor as o, isRefusal as r, storeOfRoute as s, allowAnyone as t };
71
72
 
72
- //# sourceMappingURL=route-CspI1Ypt.js.map
73
+ //# sourceMappingURL=route-C8-YjzdY.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-CspI1Ypt.js","names":[],"sources":["../src/server/route.ts"],"sourcesContent":["import { CloudropError, configError } from \"../errors.ts\";\nimport { isPlainObject } from \"../input.ts\";\nimport type { Jsonified, UploadedFile } from \"../protocol/types.ts\";\nimport type { SchemaInput, SchemaOutput, StandardSchema } from \"./schema.ts\";\nimport type { Size } from \"./size.ts\";\n\nexport type Awaitable<T> = T | Promise<T>;\n\n// Symbol.for, not Symbol(): two copies of cloudrop in one app must recognise each other's refusals, or one would read\n// as a signed-in user.\nconst DENIED: unique symbol = Symbol.for(\"cloudrop.unauthorized\");\n// Symbol.for for the same reason: an adapter may come from another copy of cloudrop than the server.\nconst STORE: unique symbol = Symbol.for(\"cloudrop.store\");\n\n/**\n * Returned by `authorize` to refuse an upload: `unauthorized()` answers UNAUTHORIZED (401), `forbidden()` FORBIDDEN\n * (403), with `message`.\n */\nexport interface Refusal {\n readonly [DENIED]: true;\n /** Absent on a refusal from a copy of cloudrop that predates forbidden(): it means UNAUTHORIZED. */\n readonly code?: \"UNAUTHORIZED\" | \"FORBIDDEN\";\n readonly message: string;\n}\n\nconst SIGN_IN_MESSAGE = \"Sign in to upload files here.\";\nconst NOT_ALLOWED_MESSAGE =\n \"You are not allowed to upload files here. Ask the site owner for access if you think this is wrong.\";\n\n/** For a caller who is not signed in. */\nexport function unauthorized(message: string = SIGN_IN_MESSAGE): Refusal {\n return { [DENIED]: true, code: \"UNAUTHORIZED\", message };\n}\n\n/** For a signed-in caller who may not upload this: a quota, a plan or a role. */\nexport function forbidden(message: string = NOT_ALLOWED_MESSAGE): Refusal {\n return { [DENIED]: true, code: \"FORBIDDEN\", message };\n}\n\n/** Only a plain object carrying the brand refuses: a Response or an Error is never read as a refusal or as a user. */\nexport function isRefusal(value: unknown): value is Refusal {\n return isPlainObject(value) && (value as Partial<Refusal>)[DENIED] === true;\n}\n\n/** A refusal built by plain JavaScript or another copy of cloudrop may lack a code or a message; it still refuses. */\nexport function refusalError(refusal: Refusal): CloudropError {\n const forbids = refusal.code === \"FORBIDDEN\";\n const fallback = forbids ? NOT_ALLOWED_MESSAGE : SIGN_IN_MESSAGE;\n const message = typeof refusal.message === \"string\" && refusal.message !== \"\" ? refusal.message : fallback;\n return new CloudropError(forbids ? \"FORBIDDEN\" : \"UNAUTHORIZED\", message);\n}\n\n/** `authorize: allowAnyone` makes a route public. It must be written out: public uploads are never a default. */\nexport function allowAnyone(): object {\n return {};\n}\n\n/** Names cloudrop puts into every route context; an authorize result's own fields with these names are replaced. */\ntype ReservedName = \"request\" | \"metadata\" | \"file\";\n\nexport interface AuthorizeContext<TMetadata> {\n request: Request;\n metadata: TMetadata;\n}\n\n/** `owner` sees the live authorize result inside `/upload`, once for all of its files. */\nexport type OwnerContext<TAuth, TMetadata> = Omit<TAuth, ReservedName> & { request: Request; metadata: TMetadata };\n\n/** `prefix` and `key` see the live authorize result; this runs inside `/upload`, once per file. */\nexport type KeyContext<TAuth, TMetadata> = OwnerContext<TAuth, TMetadata> & {\n file: { id: string; name: string; size: number; type: string; ext: string };\n};\n\n/** `onComplete` runs inside `/complete`, so it sees what the token carried: the JSON form of each value. */\nexport type CompleteContext<TAuth, TMetadata> = Omit<Jsonified<TAuth>, ReservedName> & {\n request: Request;\n file: UploadedFile;\n /** undefined on a route without a schema, and possibly undefined when the schema's output can be. */\n metadata: Jsonified<TMetadata> | (undefined extends TMetadata ? undefined : never);\n};\n\n/** What `/complete` sends as `data`: the JSON form of the result, and null where `onComplete` gave undefined or nothing. */\ntype CompleteData<TResult> = Jsonified<TResult> | (undefined extends TResult ? null : never);\n\n/** `afterComplete` sees what `onComplete` sees, plus the `data` the client was sent. */\nexport type AfterCompleteContext<TAuth, TMetadata, TResult> = CompleteContext<TAuth, TMetadata> & {\n data: CompleteData<Awaited<TResult>>;\n};\n\n/** A store's extra context (an adapter's `tx`) replaces an authorize field of the same name. */\ntype WithExtra<TContext, TExtra> = [keyof TExtra] extends [never] ? TContext : Omit<TContext, keyof TExtra> & TExtra;\n\ntype NoExtra = Record<never, never>;\n\n/** route()'s first argument: every option that is not typed from authorize's result. */\nexport interface RoutePolicy<TAuth extends object, TSchema extends StandardSchema | undefined> {\n /** MIME types such as \"image/png\", \"image/*\" or \"*\\/*\". The file name's extension must agree with the type. */\n accept: string | readonly string[];\n /** Bytes, or \"5MB\" style (binary units). */\n maxSize: Size;\n /** Files per `/upload` call, 1 to 100. Default 10. */\n maxFiles?: number;\n /** Any Standard Schema (zod, valibot, arktype). Its output, as JSON, must fit in 2 KiB. */\n metadata?: TSchema;\n /** \"public\" needs the storage's `publicUrl`. Default: \"public\" when the storage has one, otherwise \"private\". */\n visibility?: \"public\" | \"private\";\n /**\n * Required. Return a plain object with the facts later steps need (they are signed into the upload token, which the\n * browser can read: return ids, never secrets), or `unauthorized()` or `forbidden()`. `allowAnyone` makes the route\n * public.\n *\n * It runs only in `/upload`. The token it signs is the authority for the next 24 hours, so a session revoked\n * mid-upload can still finish that upload; check the session again in `onComplete` when that matters.\n */\n authorize: (context: AuthorizeContext<SchemaOutput<TSchema>>) => Awaitable<TAuth | Refusal>;\n}\n\n/**\n * route()'s second argument: the callbacks typed from authorize's result. A separate argument because TypeScript\n * infers from callbacks left to right within one object, so one written before authorize would see `object`.\n */\nexport interface RouteCallbacks<TAuth extends object, TMetadata, TResult, TExtra extends object = NoExtra> {\n /** Folder for generated keys `<prefix>/<ulid><ext>`. Sanitized like every key. */\n prefix?: (context: KeyContext<TAuth, TMetadata>) => string;\n /**\n * The whole key instead of `<prefix>/<ulid><ext>`. Sanitized like every key. It must be unique: a rejected or\n * aborted upload's object is deleted by key once a HEAD, or a create-only completion, shows the object is this\n * upload's. The delete is not conditional, so another file stored under the same key between the two requests\n * would be deleted.\n */\n key?: (context: KeyContext<TAuth, TMetadata>) => string;\n /**\n * Runs inside `/complete`, at least once per file; its JSON result reaches the client as `data`.\n *\n * `authorize` is not called again here: `request` carries the caller's cookies and headers, so re-check a session\n * that may have been revoked since `/upload`. Until the token expires (24 hours after `/upload`), whoever holds it\n * can also delete this file through `/abort`, even after `onComplete` has run. A database store closes that gap and\n * runs `onComplete` once per file: inside the store's transaction with `tx` when its route comes from the store's own\n * `route()`, otherwise again only after a crash between claiming the file and recording its completion.\n */\n onComplete?: (context: WithExtra<CompleteContext<TAuth, TMetadata>, TExtra>) => Awaitable<TResult>;\n /**\n * With a store: who the file counts against for `quota` and `api.usage`, 1 to 255 characters, or null for no one.\n * Runs once per `/upload`. Not the authorize result signed into the token; return an id, such as a user or team id.\n */\n owner?: (context: OwnerContext<TAuth, TMetadata>) => Awaitable<string | null>;\n /**\n * With a store: runs after the completion is recorded, at most once per file and best effort. A crash right after the\n * recording skips it, and a throw is logged while the client still gets its answer, which waits for it: keep it short.\n * Call storage and other network services here, not in `onComplete`; for work that must happen, write an outbox row\n * through `tx` in `onComplete`. Write it after `onComplete`: TypeScript infers `data`'s type from `onComplete` only\n * when `onComplete` comes first.\n */\n afterComplete?: (context: AfterCompleteContext<TAuth, TMetadata, TResult>) => Awaitable<void>;\n}\n\n/**\n * A route with its types erased, as the server runs it. Method syntax makes the typed callbacks assignable: route()\n * has already checked each one against its own context type.\n */\nexport interface RouteDefinition {\n accept: string | readonly string[];\n maxSize: Size;\n maxFiles?: number;\n metadata?: StandardSchema;\n visibility?: \"public\" | \"private\";\n authorize(context: AuthorizeContext<unknown>): Awaitable<unknown>;\n prefix?(context: KeyContext<object, unknown>): string;\n key?(context: KeyContext<object, unknown>): string;\n owner?(context: OwnerContext<object, unknown>): Awaitable<string | null>;\n onComplete?(context: { request: Request; file: UploadedFile; metadata: unknown }): unknown;\n afterComplete?(context: { request: Request; file: UploadedFile; metadata: unknown; data: unknown }): unknown;\n /** The store whose `route()` made this route, whose `tx` its `onComplete` expects. */\n readonly [STORE]?: object;\n}\n\nexport interface Route<TMetadataInput = unknown, TResult = unknown> {\n readonly definition: RouteDefinition;\n /** Type-only: never set at runtime. */\n readonly \"~types\"?: { readonly metadata: TMetadataInput; readonly result: TResult };\n}\n\nconst CALLBACKS = [\"prefix\", \"key\", \"owner\", \"onComplete\", \"afterComplete\"] as const;\nconst POLICY = [\"accept\", \"maxSize\", \"maxFiles\", \"metadata\", \"visibility\", \"authorize\"] as const;\n\n/** JavaScript callers get no type error for an option in the wrong argument, and there it would do nothing. */\nfunction checkPlacement(policy: object, callbacks: object): void {\n const callback = CALLBACKS.find((name) => Object.hasOwn(policy, name));\n if (callback) {\n throw configError(\n `route(): ${callback} belongs in the second argument, which holds prefix, key, owner, onComplete and afterComplete: route({ accept, maxSize, authorize }, { ${callback} }).`,\n );\n }\n const option = POLICY.find((name) => Object.hasOwn(callbacks, name));\n if (option) {\n throw configError(\n `route(): ${option} belongs in the first argument, which holds accept, maxSize, maxFiles, metadata, visibility and authorize. The second takes only prefix, key, owner, onComplete and afterComplete.`,\n );\n }\n}\n\n/**\n * An upload route: `route({ accept, maxSize, authorize }, { prefix, onComplete })`. The second argument is optional\n * and typed from what `authorize` returns.\n */\nexport function route<TAuth extends object, TSchema extends StandardSchema | undefined = undefined, TResult = null>(\n policy: RoutePolicy<TAuth, TSchema>,\n callbacks?: RouteCallbacks<TAuth, SchemaOutput<TSchema>, TResult>,\n // NoInfer: written inside createCloudrop({ routes }), the call would otherwise infer TResult from the expected Route\n // and type a route without onComplete as unknown, not null.\n): NoInfer<Route<SchemaInput<TSchema>, CompleteData<Awaited<TResult>>>> {\n // Plain JavaScript may pass anything; createCloudrop reports a definition without authorize or accept.\n const given: object = policy ?? {};\n checkPlacement(given, callbacks ?? {});\n // The checker cannot relate onComplete's context while TAuth is generic (Jsonified<TAuth> stays deferred); the\n // handler builds exactly the contexts typed above.\n return { definition: { ...given, ...callbacks } as RouteDefinition };\n}\n\n/** route(), typed with a store's extra `onComplete` context. */\nexport type RouteFunction<TExtra extends object> = <\n TAuth extends object,\n TSchema extends StandardSchema | undefined = undefined,\n TResult = null,\n>(\n policy: RoutePolicy<TAuth, TSchema>,\n callbacks?: RouteCallbacks<TAuth, SchemaOutput<TSchema>, TResult, TExtra>,\n) => NoInfer<Route<SchemaInput<TSchema>, CompleteData<Awaited<TResult>>>>;\n\n/**\n * For store adapters: a route() whose routes belong to `store`, so their `onComplete` is typed with `TExtra` (the\n * store's `tx`). createCloudrop refuses such a route unless `store` is its store and has a transaction.\n */\nexport function routeFor<TExtra extends object>(store: object): RouteFunction<TExtra> {\n return (policy, callbacks) => ({\n definition: { ...route(policy, callbacks as RouteCallbacks<object, unknown, unknown>).definition, [STORE]: store },\n });\n}\n\n/** The store whose route() made the route, if any. */\nexport const storeOfRoute = (definition: RouteDefinition): object | undefined => definition[STORE];\n"],"mappings":";;;AAUA,MAAM,SAAwB,OAAO,IAAI,uBAAuB;AAEhE,MAAM,QAAuB,OAAO,IAAI,gBAAgB;AAaxD,MAAM,kBAAkB;AACxB,MAAM,sBACJ;AAGF,SAAgB,aAAa,UAAkB,iBAA0B;CACvE,O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
1
+ {"version":3,"file":"route-C8-YjzdY.js","names":[],"sources":["../src/server/route.ts"],"sourcesContent":["import { CloudropError, configError } from \"../errors.ts\";\nimport { isPlainObject } from \"../input.ts\";\nimport type { Jsonified, UploadedFile } from \"../protocol/types.ts\";\nimport type { SchemaInput, SchemaOutput, StandardSchema } from \"./schema.ts\";\nimport type { Size } from \"./size.ts\";\n\nexport type Awaitable<T> = T | Promise<T>;\n\n// Symbol.for, not Symbol(): two copies of cloudrop in one app must recognise each other's refusals, or one would read\n// as a signed-in user.\nconst DENIED: unique symbol = Symbol.for(\"cloudrop.unauthorized\");\n// Symbol.for for the same reason: an adapter may come from another copy of cloudrop than the server.\nconst STORE: unique symbol = Symbol.for(\"cloudrop.store\");\n\n/**\n * Returned by `authorize` to refuse an upload: `unauthorized()` answers UNAUTHORIZED (401), `forbidden()` FORBIDDEN\n * (403), with `message`.\n */\nexport interface Refusal {\n readonly [DENIED]: true;\n /** Absent on a refusal from a copy of cloudrop that predates forbidden(): it means UNAUTHORIZED. */\n readonly code?: \"UNAUTHORIZED\" | \"FORBIDDEN\";\n readonly message: string;\n}\n\nconst SIGN_IN_MESSAGE = \"Sign in to upload files here.\";\nconst NOT_ALLOWED_MESSAGE =\n \"You are not allowed to upload files here. Ask the site owner for access if you think this is wrong.\";\n\n/** For a caller who is not signed in. */\nexport function unauthorized(message: string = SIGN_IN_MESSAGE): Refusal {\n return { [DENIED]: true, code: \"UNAUTHORIZED\", message };\n}\n\n/** For a signed-in caller who may not upload this: a quota, a plan or a role. */\nexport function forbidden(message: string = NOT_ALLOWED_MESSAGE): Refusal {\n return { [DENIED]: true, code: \"FORBIDDEN\", message };\n}\n\n/** Only a plain object carrying the brand refuses: a Response or an Error is never read as a refusal or as a user. */\nexport function isRefusal(value: unknown): value is Refusal {\n return isPlainObject(value) && (value as Partial<Refusal>)[DENIED] === true;\n}\n\n/** A refusal built by plain JavaScript or another copy of cloudrop may lack a code or a message; it still refuses. */\nexport function refusalError(refusal: Refusal): CloudropError {\n const forbids = refusal.code === \"FORBIDDEN\";\n const fallback = forbids ? NOT_ALLOWED_MESSAGE : SIGN_IN_MESSAGE;\n const message = typeof refusal.message === \"string\" && refusal.message !== \"\" ? refusal.message : fallback;\n return new CloudropError(forbids ? \"FORBIDDEN\" : \"UNAUTHORIZED\", message);\n}\n\n/** `authorize: allowAnyone` makes a route public. It must be written out: public uploads are never a default. */\nexport function allowAnyone(): object {\n return {};\n}\n\n/** Names cloudrop puts into every route context; an authorize result's own fields with these names are replaced. */\ntype ReservedName = \"request\" | \"metadata\" | \"file\";\n\nexport interface AuthorizeContext<TMetadata> {\n request: Request;\n metadata: TMetadata;\n}\n\n/** `owner` sees the live authorize result inside `/upload`, once for all of its files. */\nexport type OwnerContext<TAuth, TMetadata> = Omit<TAuth, ReservedName> & { request: Request; metadata: TMetadata };\n\n/** `prefix` and `key` see the live authorize result; this runs inside `/upload`, once per file. */\nexport type KeyContext<TAuth, TMetadata> = OwnerContext<TAuth, TMetadata> & {\n file: { id: string; name: string; size: number; type: string; ext: string };\n};\n\n/** `onComplete` runs inside `/complete`, so it sees what the token carried: the JSON form of each value. */\nexport type CompleteContext<TAuth, TMetadata> = Omit<Jsonified<TAuth>, ReservedName> & {\n request: Request;\n file: UploadedFile;\n /** undefined on a route without a schema, and possibly undefined when the schema's output can be. */\n metadata: Jsonified<TMetadata> | (undefined extends TMetadata ? undefined : never);\n};\n\n/** What `/complete` sends as `data`: the JSON form of the result, and null where `onComplete` gave undefined or nothing. */\ntype CompleteData<TResult> = Jsonified<TResult> | (undefined extends TResult ? null : never);\n\n/** `afterComplete` sees what `onComplete` sees, plus the `data` the client was sent. */\nexport type AfterCompleteContext<TAuth, TMetadata, TResult> = CompleteContext<TAuth, TMetadata> & {\n data: CompleteData<Awaited<TResult>>;\n};\n\n/** A store's extra context (an adapter's `tx`) replaces an authorize field of the same name. */\ntype WithExtra<TContext, TExtra> = [keyof TExtra] extends [never] ? TContext : Omit<TContext, keyof TExtra> & TExtra;\n\ntype NoExtra = Record<never, never>;\n\n/** route()'s first argument: every option that is not typed from authorize's result. */\nexport interface RoutePolicy<TAuth extends object, TSchema extends StandardSchema | undefined> {\n /** MIME types such as \"image/png\", \"image/*\" or \"*\\/*\". The file name's extension must agree with the type. */\n accept: string | readonly string[];\n /** Bytes, or \"5MB\" style (binary units). */\n maxSize: Size;\n /** Files per `/upload` call, 1 to 100. Default 10. */\n maxFiles?: number;\n /** Any Standard Schema (zod, valibot, arktype). Its output, as JSON, must fit in 2 KiB. */\n metadata?: TSchema;\n /** \"public\" needs the storage's `publicUrl`. Default: \"public\" when the storage has one, otherwise \"private\". */\n visibility?: \"public\" | \"private\";\n /**\n * With a store and `owner`: one file per owner, such as an avatar. The completion that records a new file deletes the\n * owner's previous ones on this route in the same database write, so two uploads at once leave exactly one; their\n * objects are removed right after, and by the sweep if that fails. Read the kept file with `api.files`, not a pointer\n * set in `onComplete` (store guide). `maxFiles` is then 1; under a quota the owner needs room for both files.\n */\n replace?: boolean;\n /**\n * Required. Return a plain object with the facts later steps need (they are signed into the upload token, which the\n * browser can read: return ids, never secrets), or `unauthorized()` or `forbidden()`. `allowAnyone` makes the route\n * public.\n *\n * It runs only in `/upload`. The token it signs is the authority for the next 24 hours, so a session revoked\n * mid-upload can still finish that upload; check the session again in `onComplete` when that matters.\n */\n authorize: (context: AuthorizeContext<SchemaOutput<TSchema>>) => Awaitable<TAuth | Refusal>;\n}\n\n/**\n * route()'s second argument: the callbacks typed from authorize's result. A separate argument because TypeScript\n * infers from callbacks left to right within one object, so one written before authorize would see `object`.\n */\nexport interface RouteCallbacks<TAuth extends object, TMetadata, TResult, TExtra extends object = NoExtra> {\n /** Folder for generated keys `<prefix>/<ulid><ext>`. Sanitized like every key. */\n prefix?: (context: KeyContext<TAuth, TMetadata>) => string;\n /**\n * The whole key instead of `<prefix>/<ulid><ext>`. Sanitized like every key. It must be unique: a rejected or\n * aborted upload's object is deleted by key once a HEAD, or a create-only completion, shows the object is this\n * upload's. The delete is not conditional, so another file stored under the same key between the two requests\n * would be deleted.\n */\n key?: (context: KeyContext<TAuth, TMetadata>) => string;\n /**\n * Runs inside `/complete`, at least once per file; its JSON result reaches the client as `data`.\n *\n * `authorize` is not called again here: `request` carries the caller's cookies and headers, so re-check a session\n * that may have been revoked since `/upload`. Until the token expires (24 hours after `/upload`), whoever holds it\n * can also delete this file through `/abort`, even after `onComplete` has run. A database store closes that gap and\n * runs `onComplete` once per file: inside the store's transaction with `tx` when its route comes from the store's own\n * `route()`, otherwise again only after a crash between claiming the file and recording its completion.\n */\n onComplete?: (context: WithExtra<CompleteContext<TAuth, TMetadata>, TExtra>) => Awaitable<TResult>;\n /**\n * With a store: who the file counts against for `quota` and `api.usage`, 1 to 255 characters, or null for no one.\n * Runs once per `/upload`. Not the authorize result signed into the token; return an id, such as a user or team id.\n */\n owner?: (context: OwnerContext<TAuth, TMetadata>) => Awaitable<string | null>;\n /**\n * With a store: runs after the completion is recorded, at most once per file and best effort. A crash right after the\n * recording skips it, and a throw is logged while the client still gets its answer, which waits for it: keep it short.\n * Call storage and other network services here, not in `onComplete`; for work that must happen, write an outbox row\n * through `tx` in `onComplete`. Write it after `onComplete`: TypeScript infers `data`'s type from `onComplete` only\n * when `onComplete` comes first.\n */\n afterComplete?: (context: AfterCompleteContext<TAuth, TMetadata, TResult>) => Awaitable<void>;\n}\n\n/**\n * A route with its types erased, as the server runs it. Method syntax makes the typed callbacks assignable: route()\n * has already checked each one against its own context type.\n */\nexport interface RouteDefinition {\n accept: string | readonly string[];\n maxSize: Size;\n maxFiles?: number;\n metadata?: StandardSchema;\n visibility?: \"public\" | \"private\";\n replace?: boolean;\n authorize(context: AuthorizeContext<unknown>): Awaitable<unknown>;\n prefix?(context: KeyContext<object, unknown>): string;\n key?(context: KeyContext<object, unknown>): string;\n owner?(context: OwnerContext<object, unknown>): Awaitable<string | null>;\n onComplete?(context: { request: Request; file: UploadedFile; metadata: unknown }): unknown;\n afterComplete?(context: { request: Request; file: UploadedFile; metadata: unknown; data: unknown }): unknown;\n /** The store whose `route()` made this route, whose `tx` its `onComplete` expects. */\n readonly [STORE]?: object;\n}\n\nexport interface Route<TMetadataInput = unknown, TResult = unknown> {\n readonly definition: RouteDefinition;\n /** Type-only: never set at runtime. */\n readonly \"~types\"?: { readonly metadata: TMetadataInput; readonly result: TResult };\n}\n\nconst CALLBACKS = [\"prefix\", \"key\", \"owner\", \"onComplete\", \"afterComplete\"] as const;\nconst POLICY = [\"accept\", \"maxSize\", \"maxFiles\", \"metadata\", \"visibility\", \"replace\", \"authorize\"] as const;\n\n/** JavaScript callers get no type error for an option in the wrong argument, and there it would do nothing. */\nfunction checkPlacement(policy: object, callbacks: object): void {\n const callback = CALLBACKS.find((name) => Object.hasOwn(policy, name));\n if (callback) {\n throw configError(\n `route(): ${callback} belongs in the second argument, which holds prefix, key, owner, onComplete and afterComplete: route({ accept, maxSize, authorize }, { ${callback} }).`,\n );\n }\n const option = POLICY.find((name) => Object.hasOwn(callbacks, name));\n if (option) {\n throw configError(\n `route(): ${option} belongs in the first argument, which holds accept, maxSize, maxFiles, metadata, visibility, replace and authorize. The second takes only prefix, key, owner, onComplete and afterComplete.`,\n );\n }\n}\n\n/**\n * An upload route: `route({ accept, maxSize, authorize }, { prefix, onComplete })`. The second argument is optional\n * and typed from what `authorize` returns.\n */\nexport function route<TAuth extends object, TSchema extends StandardSchema | undefined = undefined, TResult = null>(\n policy: RoutePolicy<TAuth, TSchema>,\n callbacks?: RouteCallbacks<TAuth, SchemaOutput<TSchema>, TResult>,\n // NoInfer: written inside createCloudrop({ routes }), the call would otherwise infer TResult from the expected Route\n // and type a route without onComplete as unknown, not null.\n): NoInfer<Route<SchemaInput<TSchema>, CompleteData<Awaited<TResult>>>> {\n // Plain JavaScript may pass anything; createCloudrop reports a definition without authorize or accept.\n const given: object = policy ?? {};\n checkPlacement(given, callbacks ?? {});\n // The checker cannot relate onComplete's context while TAuth is generic (Jsonified<TAuth> stays deferred); the\n // handler builds exactly the contexts typed above.\n return { definition: { ...given, ...callbacks } as RouteDefinition };\n}\n\n/** route(), typed with a store's extra `onComplete` context. */\nexport type RouteFunction<TExtra extends object> = <\n TAuth extends object,\n TSchema extends StandardSchema | undefined = undefined,\n TResult = null,\n>(\n policy: RoutePolicy<TAuth, TSchema>,\n callbacks?: RouteCallbacks<TAuth, SchemaOutput<TSchema>, TResult, TExtra>,\n) => NoInfer<Route<SchemaInput<TSchema>, CompleteData<Awaited<TResult>>>>;\n\n/**\n * For store adapters: a route() whose routes belong to `store`, so their `onComplete` is typed with `TExtra` (the\n * store's `tx`). createCloudrop refuses such a route unless `store` is its store and has a transaction.\n */\nexport function routeFor<TExtra extends object>(store: object): RouteFunction<TExtra> {\n return (policy, callbacks) => ({\n definition: { ...route(policy, callbacks as RouteCallbacks<object, unknown, unknown>).definition, [STORE]: store },\n });\n}\n\n/** The store whose route() made the route, if any. */\nexport const storeOfRoute = (definition: RouteDefinition): object | undefined => definition[STORE];\n"],"mappings":";;;AAUA,MAAM,SAAwB,OAAO,IAAI,uBAAuB;AAEhE,MAAM,QAAuB,OAAO,IAAI,gBAAgB;AAaxD,MAAM,kBAAkB;AACxB,MAAM,sBACJ;AAGF,SAAgB,aAAa,UAAkB,iBAA0B;CACvE,OAAO;GAAG,SAAS;EAAM,MAAM;EAAgB;CAAQ;AACzD;AAGA,SAAgB,UAAU,UAAkB,qBAA8B;CACxE,OAAO;GAAG,SAAS;EAAM,MAAM;EAAa;CAAQ;AACtD;AAGA,SAAgB,UAAU,OAAkC;CAC1D,OAAO,cAAc,KAAK,KAAM,MAA2B,YAAY;AACzE;AAGA,SAAgB,aAAa,SAAiC;CAC5D,MAAM,UAAU,QAAQ,SAAS;CACjC,MAAM,WAAW,UAAU,sBAAsB;CACjD,MAAM,UAAU,OAAO,QAAQ,YAAY,YAAY,QAAQ,YAAY,KAAK,QAAQ,UAAU;CAClG,OAAO,IAAI,cAAc,UAAU,cAAc,gBAAgB,OAAO;AAC1E;AAGA,SAAgB,cAAsB;CACpC,OAAO,CAAC;AACV;AAuIA,MAAM,YAAY;CAAC;CAAU;CAAO;CAAS;CAAc;AAAe;AAC1E,MAAM,SAAS;CAAC;CAAU;CAAW;CAAY;CAAY;CAAc;CAAW;AAAW;AAGjG,SAAS,eAAe,QAAgB,WAAyB;CAC/D,MAAM,WAAW,UAAU,MAAM,SAAS,OAAO,OAAO,QAAQ,IAAI,CAAC;CACrE,IAAI,UACF,MAAM,YACJ,YAAY,SAAS,yIAAyI,SAAS,KACzK;CAEF,MAAM,SAAS,OAAO,MAAM,SAAS,OAAO,OAAO,WAAW,IAAI,CAAC;CACnE,IAAI,QACF,MAAM,YACJ,YAAY,OAAO,4LACrB;AAEJ;AAMA,SAAgB,MACd,QACA,WAGsE;CAEtE,MAAM,QAAgB,UAAU,CAAC;CACjC,eAAe,OAAO,aAAa,CAAC,CAAC;CAGrC,OAAO,EAAE,YAAY;EAAE,GAAG;EAAO,GAAG;CAAU,EAAqB;AACrE;AAgBA,SAAgB,SAAgC,OAAsC;CACpF,QAAQ,QAAQ,eAAe,EAC7B,YAAY;EAAE,GAAG,MAAM,QAAQ,SAAqD,CAAC,CAAC;GAAa,QAAQ;CAAM,EACnH;AACF;AAGA,MAAa,gBAAgB,eAAoD,WAAW"}
@@ -1,4 +1,4 @@
1
- import { T as UploadedFile, d as Jsonified } from "./types-BrAx3dA4.js";
1
+ import { T as UploadedFile, d as Jsonified } from "./types-CFfMw-n_.js";
2
2
  interface StandardSchema<Input = unknown, Output = Input> {
3
3
  readonly "~standard": {
4
4
  readonly version: 1;
@@ -94,6 +94,13 @@ interface RoutePolicy<TAuth extends object, TSchema extends StandardSchema | und
94
94
  metadata?: TSchema;
95
95
  /** "public" needs the storage's `publicUrl`. Default: "public" when the storage has one, otherwise "private". */
96
96
  visibility?: "public" | "private";
97
+ /**
98
+ * With a store and `owner`: one file per owner, such as an avatar. The completion that records a new file deletes the
99
+ * owner's previous ones on this route in the same database write, so two uploads at once leave exactly one; their
100
+ * objects are removed right after, and by the sweep if that fails. Read the kept file with `api.files`, not a pointer
101
+ * set in `onComplete` (store guide). `maxFiles` is then 1; under a quota the owner needs room for both files.
102
+ */
103
+ replace?: boolean;
97
104
  /**
98
105
  * Required. Return a plain object with the facts later steps need (they are signed into the upload token, which the
99
106
  * browser can read: return ids, never secrets), or `unauthorized()` or `forbidden()`. `allowAnyone` makes the route
@@ -152,6 +159,7 @@ interface RouteDefinition {
152
159
  maxFiles?: number;
153
160
  metadata?: StandardSchema;
154
161
  visibility?: "public" | "private";
162
+ replace?: boolean;
155
163
  authorize(context: AuthorizeContext<unknown>): Awaitable<unknown>;
156
164
  prefix?(context: KeyContext<object, unknown>): string;
157
165
  key?(context: KeyContext<object, unknown>): string;
@@ -244,6 +252,10 @@ type Transition = {
244
252
  changed: false;
245
253
  record: FileRecord | null;
246
254
  };
255
+ /** What `complete` did: the transition, and the files `replace` deleted in the same unit (none without it). */
256
+ type Completion = Transition & {
257
+ replaced: FileRecord[];
258
+ };
247
259
  /** An owner's counters, kept for every row with an owner whether or not a quota is set. */
248
260
  interface OwnerUsage {
249
261
  /** Bytes of the owner's `pending` and `completing` rows. */
@@ -311,8 +323,16 @@ interface CloudropStore<TTx = never> {
311
323
  * by the size, active bytes rise by it and files by one. Unchanged for any other row: a repeat answers the completed
312
324
  * row, a lost claim the row another `/complete` holds. `claim` and `claimed_at` stay as they were, recording which
313
325
  * claim completed the row.
326
+ *
327
+ * With `replace`, and when the row has an owner, the same unit also ends every other `completed` row of that owner on
328
+ * the row's route as `deleted` (`ended_at = now`, `cleaned_at` left null), releasing their active bytes and files, and
329
+ * answers them, as they are now, in `replaced`. Two such completions of one owner and route never both keep their
330
+ * previous files: the second sees the first's row as completed and replaces it. Without `replace`, or when nothing
331
+ * changed, `replaced` is empty.
314
332
  */
315
- complete(id: string, claim: string, result: string | null, now: Date): Promise<Transition>;
333
+ complete(id: string, claim: string, result: string | null, now: Date, options?: {
334
+ replace?: boolean;
335
+ }): Promise<Completion>;
316
336
  /**
317
337
  * Moves a row from exactly `from` to `to` and sets `ended_at = now`; `cleaned: true` also sets `cleaned_at = now`.
318
338
  * Usage follows `from`: `pending` or `completing` releases the reserved bytes; `completed` releases the active bytes
@@ -344,6 +364,24 @@ interface CloudropStore<TTx = never> {
344
364
  records: FileRecord[];
345
365
  cursor: string | null;
346
366
  }>;
367
+ /**
368
+ * One page of an owner's rows in any of `statuses` (none: an empty page), newest first: by `created_at`, then id, both
369
+ * descending, and on `route` alone when it is not null. One page is read in one statement, so a row in one of the
370
+ * statuses when it runs is on it or on a later page, whatever status changes happen meanwhile. At most `limit`
371
+ * records; `cursor` continues after the previous page (keyset, so rows that leave the statuses between pages skip
372
+ * nothing) and is null on the last page. A cursor is `<milliseconds>:<id>`, the last row's `created_at` and id (the
373
+ * file API refuses any other before calling the store).
374
+ */
375
+ list(input: {
376
+ owner: string;
377
+ statuses: readonly FileStatus[];
378
+ route: string | null;
379
+ limit: number;
380
+ cursor: string | null;
381
+ }): Promise<{
382
+ records: FileRecord[];
383
+ cursor: string | null;
384
+ }>;
347
385
  /** Sets `cleaned_at = now` on a row that has none; a cleaned or missing row is left as it is. */
348
386
  cleaned(id: string, now: Date): Promise<void>;
349
387
  /** The owner's counters; zeros for an owner the store has never counted. */
@@ -379,4 +417,4 @@ type TransactionalStore<TTx> = CloudropStore<TTx> & Required<Pick<CloudropStore<
379
417
  tx: TTx;
380
418
  }>;
381
419
  };
382
- export { forbidden as C, StandardSchema as D, Size as E, allowAnyone as S, unauthorized as T, Route as _, FileStatus as a, RouteFunction as b, TransactionalStore as c, AuthorizeContext as d, Awaitable as f, Refusal as g, OwnerContext as h, FileRecord as i, Transition as l, KeyContext as m, CloudropStore as n, NewFile as o, CompleteContext as p, EndedStatus as r, OwnerUsage as s, ClaimOutcome as t, AfterCompleteContext as u, RouteCallbacks as v, route as w, RoutePolicy as x, RouteDefinition as y };
420
+ export { allowAnyone as C, Size as D, unauthorized as E, StandardSchema as O, RoutePolicy as S, route as T, Refusal as _, FileRecord as a, RouteDefinition as b, OwnerUsage as c, AfterCompleteContext as d, AuthorizeContext as f, OwnerContext as g, KeyContext as h, EndedStatus as i, TransactionalStore as l, CompleteContext as m, CloudropStore as n, FileStatus as o, Awaitable as p, Completion as r, NewFile as s, ClaimOutcome as t, Transition as u, Route as v, forbidden as w, RouteFunction as x, RouteCallbacks as y };