cloudrop 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/LICENSE +21 -0
  3. package/README.md +104 -3
  4. package/dist/adapters/drizzle.d.ts +204 -0
  5. package/dist/adapters/drizzle.js +216 -0
  6. package/dist/adapters/drizzle.js.map +1 -0
  7. package/dist/adapters/prisma.d.ts +81 -0
  8. package/dist/adapters/prisma.js +32 -0
  9. package/dist/adapters/prisma.js.map +1 -0
  10. package/dist/adapters/sql.d.ts +98 -0
  11. package/dist/adapters/sql.js +70 -0
  12. package/dist/adapters/sql.js.map +1 -0
  13. package/dist/client-Dj6ON4MN.d.ts +214 -0
  14. package/dist/client-Y1zUEbCj.js +1561 -0
  15. package/dist/client-Y1zUEbCj.js.map +1 -0
  16. package/dist/client.d.ts +3 -0
  17. package/dist/client.js +3 -0
  18. package/dist/d1-BY2c5bcL.js +16 -0
  19. package/dist/d1-BY2c5bcL.js.map +1 -0
  20. package/dist/errors-CUxMmFAe.js +40 -0
  21. package/dist/errors-CUxMmFAe.js.map +1 -0
  22. package/dist/executor-CEA7WV2W.d.ts +27 -0
  23. package/dist/index.d.ts +421 -0
  24. package/dist/index.js +3011 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/input-DTC476_I.js +13 -0
  27. package/dist/input-DTC476_I.js.map +1 -0
  28. package/dist/next.d.ts +9 -0
  29. package/dist/next.js +14 -0
  30. package/dist/next.js.map +1 -0
  31. package/dist/node.d.ts +32 -0
  32. package/dist/node.js +100 -0
  33. package/dist/node.js.map +1 -0
  34. package/dist/part-size-CvMoobfC.js +9 -0
  35. package/dist/part-size-CvMoobfC.js.map +1 -0
  36. package/dist/react.d.ts +123 -0
  37. package/dist/react.js +355 -0
  38. package/dist/react.js.map +1 -0
  39. package/dist/route-CspI1Ypt.js +72 -0
  40. package/dist/route-CspI1Ypt.js.map +1 -0
  41. package/dist/store-BfCJejGh.d.ts +382 -0
  42. package/dist/tables-DZnw2sPK.d.ts +11 -0
  43. package/dist/transactional-DnvnGsVH.js +672 -0
  44. package/dist/transactional-DnvnGsVH.js.map +1 -0
  45. package/dist/types-BZUOaz_B.js +5 -0
  46. package/dist/types-BZUOaz_B.js.map +1 -0
  47. package/dist/types-BrAx3dA4.d.ts +185 -0
  48. package/package.json +108 -4
package/dist/react.js ADDED
@@ -0,0 +1,355 @@
1
+ import { t as CloudropError } from "./errors-CUxMmFAe.js";
2
+ import { n as isList, t as createCloudropClient } from "./client-Y1zUEbCj.js";
3
+ import { useCallback, useEffect, useInsertionEffect, useRef, useState, useSyncExternalStore } from "react";
4
+ // src/react/job-tracker.ts
5
+ const endedOf = (job) => {
6
+ const { done, failed, aborted } = job.getSnapshot().totals;
7
+ return done + failed + aborted;
8
+ };
9
+ function createJobTracker() {
10
+ const listeners = /* @__PURE__ */ new Set();
11
+ let queued = false;
12
+ const finishing = /* @__PURE__ */ new Set();
13
+ const changed = () => {
14
+ if (queued) return;
15
+ queued = true;
16
+ queueMicrotask(() => {
17
+ queued = false;
18
+ if (finishing.size === 0) for (const listener of listeners) listener();
19
+ });
20
+ };
21
+ return {
22
+ track(job) {
23
+ let ended = endedOf(job);
24
+ let settled = false;
25
+ const stop = job.subscribe(() => {
26
+ const now = endedOf(job);
27
+ if (now === ended) return;
28
+ ended = now;
29
+ const { done, aborted, count } = job.getSnapshot().totals;
30
+ if (done + aborted === count) stop();
31
+ if (now === count && !settled) finishing.add(job);
32
+ changed();
33
+ });
34
+ job.done.then(() => {
35
+ settled = true;
36
+ finishing.delete(job);
37
+ changed();
38
+ });
39
+ changed();
40
+ },
41
+ onChange(listener) {
42
+ listeners.add(listener);
43
+ return () => {
44
+ listeners.delete(listener);
45
+ };
46
+ },
47
+ changed
48
+ };
49
+ }
50
+ // src/react/upload-store.ts
51
+ const EMPTY_VIEW = {
52
+ files: [],
53
+ totals: {
54
+ bytes: 0,
55
+ size: 0,
56
+ progress: 0,
57
+ speed: 0,
58
+ eta: null,
59
+ done: 0,
60
+ failed: 0,
61
+ aborted: 0,
62
+ count: 0
63
+ },
64
+ isUploading: false
65
+ };
66
+ const UPLOADING = /* @__PURE__ */ new Set([
67
+ "queued",
68
+ "uploading",
69
+ "completing"
70
+ ]);
71
+ const SUMMED = [
72
+ "bytes",
73
+ "size",
74
+ "speed",
75
+ "done",
76
+ "failed",
77
+ "aborted",
78
+ "count"
79
+ ];
80
+ function sumTotals(snapshots) {
81
+ const sum = { ...EMPTY_VIEW.totals };
82
+ for (const { totals } of snapshots) for (const key of SUMMED) sum[key] += totals[key];
83
+ const isFinished = sum.done > 0 && sum.done === sum.count - sum.failed - sum.aborted;
84
+ sum.progress = sum.size > 0 ? sum.bytes / sum.size : isFinished ? 1 : 0;
85
+ sum.eta = sum.speed > 0 ? (sum.size - sum.bytes) / sum.speed : null;
86
+ return sum;
87
+ }
88
+ function isSameFile(previous, next) {
89
+ for (const key of Object.keys(next)) if (previous[key] !== next[key]) return false;
90
+ return true;
91
+ }
92
+ function createUploadStore() {
93
+ let jobs = [];
94
+ const listeners = /* @__PURE__ */ new Set();
95
+ const stops = /* @__PURE__ */ new Map();
96
+ let view = EMPTY_VIEW;
97
+ const notify = () => {
98
+ view = build();
99
+ for (const listener of listeners) listener();
100
+ };
101
+ const watch = (job) => stops.set(job, job.subscribe(notify));
102
+ const unwatch = (job) => {
103
+ stops.get(job)?.();
104
+ stops.delete(job);
105
+ };
106
+ const made = /* @__PURE__ */ new WeakMap();
107
+ function fileOf(handle, snapshot) {
108
+ const previous = made.get(handle);
109
+ if (previous && isSameFile(previous.snapshot, snapshot)) return previous.file;
110
+ const file = {
111
+ ...snapshot,
112
+ pause: () => handle.pause(),
113
+ resume: () => handle.resume(),
114
+ abort: () => handle.abort(),
115
+ retry: () => handle.retry()
116
+ };
117
+ made.set(handle, {
118
+ snapshot,
119
+ file
120
+ });
121
+ return file;
122
+ }
123
+ function build() {
124
+ if (jobs.length === 0) return EMPTY_VIEW;
125
+ const snapshots = jobs.map((job) => job.getSnapshot());
126
+ const files = jobs.flatMap((job, index) => (snapshots[index]?.files ?? []).map((snapshot, at) => fileOf(job.files[at], snapshot)));
127
+ return {
128
+ files,
129
+ totals: sumTotals(snapshots),
130
+ isUploading: files.some((file) => UPLOADING.has(file.status))
131
+ };
132
+ }
133
+ return {
134
+ add(job) {
135
+ jobs = [...jobs, job];
136
+ if (listeners.size > 0) watch(job);
137
+ notify();
138
+ },
139
+ jobs: () => jobs,
140
+ clear() {
141
+ const kept = jobs.filter((job) => {
142
+ const { done, aborted, count } = job.getSnapshot().totals;
143
+ return done + aborted < count;
144
+ });
145
+ for (const job of jobs) if (!kept.includes(job)) unwatch(job);
146
+ jobs = kept;
147
+ notify();
148
+ },
149
+ subscribe(listener) {
150
+ if (listeners.size === 0) {
151
+ for (const job of jobs) watch(job);
152
+ view = build();
153
+ }
154
+ listeners.add(listener);
155
+ return () => {
156
+ listeners.delete(listener);
157
+ if (listeners.size === 0) for (const job of jobs) unwatch(job);
158
+ };
159
+ },
160
+ getSnapshot: () => view
161
+ };
162
+ }
163
+ // src/react/use-resumable.ts
164
+ const NO_UPLOADS = [];
165
+ function useResumableWith(source, route) {
166
+ const [uploads, setUploads] = useState(NO_UPLOADS);
167
+ const reads = useRef(0);
168
+ const refresh = useCallback(async () => {
169
+ const read = ++reads.current;
170
+ const client = source.client();
171
+ const answer = client.error ? client : await client.data.resumable(route);
172
+ if (read === reads.current) setUploads(answer.data ?? NO_UPLOADS);
173
+ return answer;
174
+ }, [source, route]);
175
+ useEffect(() => {
176
+ refresh();
177
+ return source.onChange(() => void refresh());
178
+ }, [source, refresh]);
179
+ const changeThenRead = useCallback(async (change) => {
180
+ const client = source.client();
181
+ const answer = client.error ? client : await change(client.data);
182
+ source.changed();
183
+ await refresh();
184
+ return answer;
185
+ }, [source, refresh]);
186
+ return {
187
+ uploads,
188
+ refresh,
189
+ discard: useCallback((upload) => changeThenRead((client) => client.discard(upload)), [changeThenRead]),
190
+ forget: useCallback(() => changeThenRead((client) => client.forget()), [changeThenRead])
191
+ };
192
+ }
193
+ // src/react/drop.ts
194
+ function createDropHandlers(setDragOver, onDrop) {
195
+ let depth = 0;
196
+ const hasFiles = (event) => event.dataTransfer.types.includes("Files");
197
+ return {
198
+ onDragEnter(event) {
199
+ if (!hasFiles(event)) return;
200
+ event.preventDefault();
201
+ depth += 1;
202
+ setDragOver(true);
203
+ },
204
+ onDragOver(event) {
205
+ if (hasFiles(event)) event.preventDefault();
206
+ },
207
+ onDragLeave(event) {
208
+ if (!hasFiles(event)) return;
209
+ depth = Math.max(0, depth - 1);
210
+ if (depth === 0) setDragOver(false);
211
+ },
212
+ onDrop(event) {
213
+ if (!hasFiles(event)) return;
214
+ event.preventDefault();
215
+ depth = 0;
216
+ setDragOver(false);
217
+ onDrop(Array.from(event.dataTransfer.files));
218
+ }
219
+ };
220
+ }
221
+ // src/react/use-upload.ts
222
+ function createController(source, initial, setDragOver) {
223
+ const controller = { latest: initial };
224
+ const jobs = () => source.storeOf(controller.latest.route).jobs();
225
+ function start(begin) {
226
+ const client = source.client();
227
+ if (client.error) return Promise.resolve({
228
+ data: null,
229
+ error: client.error
230
+ });
231
+ const job = begin(client.data);
232
+ source.storeOf(controller.latest.route).add(job);
233
+ source.track(job);
234
+ return job.done;
235
+ }
236
+ const upload = (files, call = {}) => {
237
+ if (files === null || isList(files) && files.length === 0) return Promise.resolve(null);
238
+ const { route, options } = controller.latest;
239
+ const metadata = "metadata" in call ? call.metadata : options.metadata;
240
+ return start((client) => client.start(route, files, { metadata }));
241
+ };
242
+ function resume(...record) {
243
+ if (record.length === 2) return start((client) => client.resume(...record));
244
+ for (const job of jobs()) job.resume();
245
+ }
246
+ const take = (files) => {
247
+ const { error } = source.client();
248
+ if (!error) return void upload(files);
249
+ setTimeout(() => {
250
+ throw error;
251
+ });
252
+ };
253
+ const onChange = (event) => {
254
+ const input = event.currentTarget;
255
+ const picked = Array.from(input.files ?? []);
256
+ input.value = "";
257
+ take(picked);
258
+ };
259
+ const dropProps = createDropHandlers(setDragOver, (files) => take(controller.latest.options.multiple ? files : files.slice(0, 1)));
260
+ return Object.assign(controller, {
261
+ actions: {
262
+ upload,
263
+ pause: () => {
264
+ for (const job of jobs()) job.pause();
265
+ },
266
+ resume,
267
+ abort: () => {
268
+ for (const job of jobs()) job.abort();
269
+ },
270
+ retry: async () => {
271
+ await Promise.all(jobs().map((job) => job.retry()));
272
+ },
273
+ clear: () => source.storeOf(controller.latest.route).clear(),
274
+ getDropProps: () => dropProps
275
+ },
276
+ onChange
277
+ });
278
+ }
279
+ const serverView = () => EMPTY_VIEW;
280
+ function useUploadWith(source, route, options = {}) {
281
+ const [isDragOver, setDragOver] = useState(false);
282
+ const [controller] = useState(() => createController(source, {
283
+ route,
284
+ options
285
+ }, setDragOver));
286
+ useInsertionEffect(() => {
287
+ controller.latest = {
288
+ route,
289
+ options
290
+ };
291
+ });
292
+ const store = source.storeOf(route);
293
+ const view = useSyncExternalStore(store.subscribe, store.getSnapshot, serverView);
294
+ const { multiple = false, accept } = options;
295
+ const getInputProps = useCallback(() => ({
296
+ type: "file",
297
+ multiple,
298
+ accept,
299
+ onChange: controller.onChange
300
+ }), [
301
+ multiple,
302
+ accept,
303
+ controller
304
+ ]);
305
+ return {
306
+ ...view,
307
+ ...controller.actions,
308
+ isDragOver,
309
+ getInputProps
310
+ };
311
+ }
312
+ // src/react.ts
313
+ function createUploadHooks(options = {}) {
314
+ let created;
315
+ function createClient() {
316
+ try {
317
+ return {
318
+ data: "client" in options ? options.client : createCloudropClient(options),
319
+ error: null
320
+ };
321
+ } catch (error) {
322
+ if (error instanceof CloudropError) return {
323
+ data: null,
324
+ error
325
+ };
326
+ throw error;
327
+ }
328
+ }
329
+ const stores = /* @__PURE__ */ new Map();
330
+ const source = {
331
+ ...createJobTracker(),
332
+ client() {
333
+ created ??= createClient();
334
+ return created;
335
+ },
336
+ storeOf(route) {
337
+ const store = stores.get(route) ?? createUploadStore();
338
+ stores.set(route, store);
339
+ return store;
340
+ }
341
+ };
342
+ function useUpload(route, options) {
343
+ return useUploadWith(source, route, options);
344
+ }
345
+ function useResumable(route) {
346
+ return useResumableWith(source, route);
347
+ }
348
+ return {
349
+ useUpload,
350
+ useResumable
351
+ };
352
+ }
353
+ export { createUploadHooks };
354
+
355
+ //# sourceMappingURL=react.js.map
@@ -0,0 +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,MAAM,QAAQ,YAAY,IAAI,YAAY,CAAC,CAAC;CACpD,OAAO,OAAO,SAAS;AACzB;AAEA,SAAgB,mBAA+B;CAC7C,MAAM,4BAAY,IAAI,IAAgB;CAMtC,IAAI,SAAS;CACb,MAAM,4BAAY,IAAI,IAAwB;CAC9C,MAAM,gBAAgB;EACpB,IAAI,QAAQ;EACZ,SAAS;EACT,qBAAqB;GACnB,SAAS;GACT,IAAI,UAAU,SAAS,GAAG,KAAK,MAAM,YAAY,WAAW,SAAS;EACvE,CAAC;CACH;CACA,OAAO;EACL,MAAM,KAAK;GACT,IAAI,QAAQ,QAAQ,GAAG;GACvB,IAAI,UAAU;GACd,MAAM,OAAO,IAAI,gBAAgB;IAC/B,MAAM,MAAM,QAAQ,GAAG;IACvB,IAAI,QAAQ,OAAO;IACnB,QAAQ;IACR,MAAM,EAAE,MAAM,SAAS,UAAU,IAAI,YAAY,CAAC,CAAC;IAEnD,IAAI,OAAO,YAAY,OAAO,KAAK;IACnC,IAAI,QAAQ,SAAS,CAAC,SAAS,UAAU,IAAI,GAAG;IAChD,QAAQ;GACV,CAAC;GAGI,IAAI,KAAK,WAAW;IACvB,UAAU;IACV,UAAU,OAAO,GAAG;IACpB,QAAQ;GACV,CAAC;GACD,QAAQ;EACV;EACA,SAAS,UAAU;GACjB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;CACF;AACF;;ACtDA,MAAa,aAAgC;CAC3C,OAAO,CAAC;CACR,QAAQ;EAAE,OA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a,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;CAGA,OAAO;EAAE;EAAW;CAAa;AACnC"}
@@ -0,0 +1,72 @@
1
+ import { n as configError, t as CloudropError } from "./errors-CUxMmFAe.js";
2
+ import { n as isPlainObject } from "./input-DTC476_I.js";
3
+ // src/server/route.ts
4
+ const DENIED = Symbol.for("cloudrop.unauthorized");
5
+ const STORE = Symbol.for("cloudrop.store");
6
+ const SIGN_IN_MESSAGE = "Sign in to upload files here.";
7
+ const NOT_ALLOWED_MESSAGE = "You are not allowed to upload files here. Ask the site owner for access if you think this is wrong.";
8
+ function unauthorized(message = SIGN_IN_MESSAGE) {
9
+ return {
10
+ [DENIED]: true,
11
+ code: "UNAUTHORIZED",
12
+ message
13
+ };
14
+ }
15
+ function forbidden(message = NOT_ALLOWED_MESSAGE) {
16
+ return {
17
+ [DENIED]: true,
18
+ code: "FORBIDDEN",
19
+ message
20
+ };
21
+ }
22
+ function isRefusal(value) {
23
+ return isPlainObject(value) && value[DENIED] === true;
24
+ }
25
+ function refusalError(refusal) {
26
+ const forbids = refusal.code === "FORBIDDEN";
27
+ const fallback = forbids ? NOT_ALLOWED_MESSAGE : SIGN_IN_MESSAGE;
28
+ const message = typeof refusal.message === "string" && refusal.message !== "" ? refusal.message : fallback;
29
+ return new CloudropError(forbids ? "FORBIDDEN" : "UNAUTHORIZED", message);
30
+ }
31
+ function allowAnyone() {
32
+ return {};
33
+ }
34
+ const CALLBACKS = [
35
+ "prefix",
36
+ "key",
37
+ "owner",
38
+ "onComplete",
39
+ "afterComplete"
40
+ ];
41
+ const POLICY = [
42
+ "accept",
43
+ "maxSize",
44
+ "maxFiles",
45
+ "metadata",
46
+ "visibility",
47
+ "authorize"
48
+ ];
49
+ function checkPlacement(policy, callbacks) {
50
+ const callback = CALLBACKS.find((name) => Object.hasOwn(policy, name));
51
+ 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
+ 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
+ }
55
+ function route(policy, callbacks) {
56
+ const given = policy ?? {};
57
+ checkPlacement(given, callbacks ?? {});
58
+ return { definition: {
59
+ ...given,
60
+ ...callbacks
61
+ } };
62
+ }
63
+ function routeFor(store) {
64
+ return (policy, callbacks) => ({ definition: {
65
+ ...route(policy, callbacks).definition,
66
+ [STORE]: store
67
+ } });
68
+ }
69
+ const storeOfRoute = (definition) => definition[STORE];
70
+ 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
+ //# sourceMappingURL=route-CspI1Ypt.js.map
@@ -0,0 +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,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;AA+HA,MAAM,YAAY;CAAC;CAAU;CAAO;CAAS;CAAc;AAAe;A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