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/CHANGELOG.md +80 -0
- package/README.md +11 -3
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/drizzle.js +3 -3
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/adapters/prisma.js +1 -1
- package/dist/adapters/sql.d.ts +1 -1
- package/dist/adapters/sql.js +1 -1
- package/dist/{client-Dj6ON4MN.d.ts → client-CP_ajLF4.d.ts} +43 -25
- package/dist/{client-Y1zUEbCj.js → client-ePVHwvMv.js} +126 -40
- package/dist/client-ePVHwvMv.js.map +1 -0
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/errors-CUxMmFAe.js.map +1 -1
- package/dist/index.d.ts +67 -6
- package/dist/index.js +357 -114
- package/dist/index.js.map +1 -1
- package/dist/next.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/react.d.ts +18 -4
- package/dist/react.js +23 -3
- package/dist/react.js.map +1 -1
- package/dist/{route-CspI1Ypt.js → route-C8-YjzdY.js} +3 -2
- package/dist/{route-CspI1Ypt.js.map → route-C8-YjzdY.js.map} +1 -1
- package/dist/{store-BfCJejGh.d.ts → store-B539nY3J.d.ts} +41 -3
- package/dist/{transactional-DnvnGsVH.js → transactional-CiNwMiDb.js} +215 -105
- package/dist/transactional-CiNwMiDb.js.map +1 -0
- package/dist/{types-BrAx3dA4.d.ts → types-CFfMw-n_.d.ts} +1 -1
- package/package.json +7 -7
- package/dist/client-Y1zUEbCj.js.map +0 -1
- package/dist/transactional-DnvnGsVH.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cloudrop",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Fast, resumable, direct-to-bucket file uploads for Cloudflare R2 and S3-compatible storage.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
},
|
|
79
79
|
"devDependencies": {
|
|
80
80
|
"@arethetypeswrong/cli": "^0.18.5",
|
|
81
|
-
"@cloudflare/workers-types": "5.
|
|
81
|
+
"@cloudflare/workers-types": "5.20261119.1",
|
|
82
82
|
"@libsql/client": "^0.18.0",
|
|
83
83
|
"@prisma/adapter-better-sqlite3": "^7.10.1",
|
|
84
84
|
"@prisma/adapter-pg": "^7.10.1",
|
|
@@ -93,12 +93,12 @@
|
|
|
93
93
|
"@types/react": "^19.3.0",
|
|
94
94
|
"@types/react-dom": "^19.3.0",
|
|
95
95
|
"aws4fetch": "^1.0.20",
|
|
96
|
-
"better-sqlite3": "^
|
|
96
|
+
"better-sqlite3": "^13.2.0",
|
|
97
97
|
"drizzle-orm": "1.0.0-rc.5",
|
|
98
|
-
"fast-check": "^4.10.
|
|
98
|
+
"fast-check": "^4.10.3",
|
|
99
99
|
"happy-dom": "^21.0.4",
|
|
100
100
|
"pg": "^8.23.1",
|
|
101
|
-
"postgres": "^4.
|
|
101
|
+
"postgres": "^4.1.1",
|
|
102
102
|
"prisma": "^7.10.1",
|
|
103
103
|
"publint": "^0.3.25",
|
|
104
104
|
"react": "^19.3.1",
|
|
@@ -106,7 +106,7 @@
|
|
|
106
106
|
"size-limit": "^14.3.0",
|
|
107
107
|
"tsdown": "^0.23.7",
|
|
108
108
|
"typescript": "^7.0.2",
|
|
109
|
-
"vitest": "^5.1.
|
|
110
|
-
"wrangler": "^4.
|
|
109
|
+
"vitest": "^5.1.1",
|
|
110
|
+
"wrangler": "^4.166.0"
|
|
111
111
|
}
|
|
112
112
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-Y1zUEbCj.js","names":["expiresSoon","expiresSoon"],"sources":["../src/client/arguments.ts","../src/client/failures.ts","../src/client/locks.ts","../src/client/records.ts","../src/client/retry.ts","../src/client/parts.ts","../src/client/upload.ts","../src/client/discard.ts","../src/client/answers.ts","../src/client/endpoints.ts","../src/client/progress.ts","../src/client/entry.ts","../src/client/fingerprint.ts","../src/client/persist.ts","../src/client/file-run.ts","../src/client/launch.ts","../src/client/lifecycle.ts","../src/client/job-run.ts","../src/client/job-snapshot.ts","../src/client/retry-file.ts","../src/client/store.ts","../src/client/job.ts","../src/client/pool.ts","../src/client/resume.ts","../src/client/bucket.ts","../src/client/transport.ts","../src/client.ts"],"sourcesContent":["// What plain JavaScript can get wrong in upload() and start(), refused before any request (S17, ruling S-2).\n\nimport { fail, ok, type Result } from \"../errors.ts\";\nimport { invalidInput, isPlainObject } from \"../input.ts\";\n\nexport interface Arguments {\n route: string;\n files: File[];\n metadata: unknown;\n signal: AbortSignal;\n}\n\n/** A list of files as a caller passes it: an array, `input.files`, or any other object with a numeric `length`. */\nexport const isList = (value: unknown): value is ArrayLike<unknown> =>\n typeof value === \"object\" && value !== null && \"length\" in value && typeof value.length === \"number\";\n\nconst refuse = (message: string) => fail(invalidInput(message));\n\nfunction encodesAsJson(value: unknown): boolean {\n try {\n JSON.stringify(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction readFiles(files: unknown): Result<File[]> {\n if (files instanceof File) return ok([files]);\n if (!isList(files)) return refuse('Pass the file as a File, such as one from <input type=\"file\">.');\n const list = Array.from(files);\n if (!list.every((file) => file instanceof File)) {\n return refuse('Pass the files as File objects, such as input.files from <input type=\"file\" multiple>.');\n }\n return list.length === 0 ? refuse(\"Pass at least one file to upload.\") : ok(list);\n}\n\nexport function readArguments(route: unknown, files: unknown, options: unknown): Result<Arguments> {\n if (typeof route !== \"string\" || route === \"\") {\n return refuse('Name the upload route as text, such as upload(\"avatar\", file).');\n }\n const read = readFiles(files);\n if (read.error) return read;\n if (options !== undefined && !isPlainObject(options)) {\n return refuse(\"Pass the upload options as an object, such as { metadata, signal }.\");\n }\n // A signal per call, not one module-level object: the package declares sideEffects: false.\n const { metadata, signal = new AbortController().signal } = options ?? {};\n if (!(signal instanceof AbortSignal)) {\n return refuse(\"options.signal must be an AbortSignal, such as new AbortController().signal.\");\n }\n // Retrying cannot fix a BigInt or a cycle, so it is the caller's mistake, not a network failure.\n if (!encodesAsJson(metadata)) {\n return refuse(\n \"options.metadata must be JSON data, such as objects, strings and numbers: it holds a value JSON cannot encode, such as a BigInt or a circular reference.\",\n );\n }\n return ok({ route, files: read.data, metadata, signal });\n}\n","// Every message the client writes. Each is a fixed sentence, at most with an HTTP status: never a URL, a token or what\n// the storage service answered (spec §7.7).\n\nimport { CloudropError } from \"../errors.ts\";\n\n/** Failures that a new attempt with the same ticket cannot fix (ruling M3-U31), so neither can a resume (M4-F1). */\nexport const NEEDS_NEW_TICKET: Set<string | undefined> = new Set([\n \"UPLOAD_EXPIRED\",\n \"INVALID_TOKEN\",\n \"UPLOAD_REJECTED\",\n \"VERIFICATION_FAILED\",\n // The upload is gone and nothing of it was stored (M3-U74): its ticket can never finish it.\n \"NO_SUCH_UPLOAD\",\n]);\n\n/** `error` as the error of one file of a job: the same answer, with `file` set and the original as its cause. */\nexport const withFile = (error: CloudropError, { id, file }: { id: string; file: File }): CloudropError =>\n // The spread copies the error's own fields (retryable, status, storageCode, parts), never its message or cause.\n new CloudropError(error.code, error.message, { ...error, file: { id, name: file.name }, cause: error });\n\nexport const aborted = (): CloudropError =>\n new CloudropError(\"ABORTED\", \"The upload was cancelled. Start it again to upload the file.\");\n\n// The next three end a resume() before any request (resume design §2.1); storageUnavailable, below, answers\n// resumable(), discard() and forget() when the browser's storage fails, never an upload.\nexport const uploadInUse = (): CloudropError =>\n new CloudropError(\n \"UPLOAD_IN_USE\",\n \"This upload is being sent in this browser, in this tab or another. Finish or cancel it there, then try again.\",\n );\n\nexport const notResumable = (): CloudropError =>\n new CloudropError(\n \"NOT_FOUND\",\n \"This upload can no longer be resumed: it finished, was cancelled or expired. Start it again.\",\n );\n\nexport const notSameFile = (): CloudropError =>\n new CloudropError(\n \"INVALID_INPUT\",\n \"This is not the file the upload started with. Pick the same file again to resume it.\",\n );\n\n// The next two end a discard() before any request (M3-U93); uploadInUse above does too.\nexport const notListed = (): CloudropError =>\n new CloudropError(\n \"NOT_FOUND\",\n \"This upload is no longer in this browser's list: it finished, or was cancelled or discarded. Read the list again.\",\n );\n\nexport const lockRefused = (): CloudropError =>\n new CloudropError(\n \"STORAGE_ERROR\",\n \"The browser did not let this page lock the upload, so it was left as it was. Reload the page, then try again.\",\n );\n\nexport const storageUnavailable = (): CloudropError =>\n new CloudropError(\n \"STORAGE_ERROR\",\n \"The browser's storage for unfinished uploads could not be read or written. Uploads still work; resuming after a reload may not.\",\n );\n\nexport const serverUnreachable = (): CloudropError =>\n new CloudropError(\"NETWORK_ERROR\", \"The upload server could not be reached. Check the connection, then try again.\", {\n retryable: true,\n });\n\n// A page cannot tell a network failure from R2 refusing the URL itself (a bad signature, an expired URL): those answers\n// carry no CORS headers (docs/research/r2-spike-findings.md, \"Browser refusals and checksums, 2026-11-16\"). A bucket\n// CORS rule that misses the page's origin or a signed header looks the same, so for a developer this error usually\n// means: check that rule first (docs/guide/troubleshooting.md).\nexport const bucketUnreachable = (): CloudropError =>\n new CloudropError(\n \"NETWORK_ERROR\",\n \"The file could not reach the storage service, or the storage service refused it. Try again, and contact the site owner if it keeps failing.\",\n { retryable: true },\n );\n\n/** A proxy's rate-limit page in front of the app: it passes, so it is retried (rulings S-4, S-7). */\nexport const serverBusy = (): CloudropError =>\n new CloudropError(\"RATE_LIMITED\", \"The upload server is busy. Try again in a moment.\", { retryable: true });\n\n/**\n * A non-JSON answer or one of the wrong shape: a wrong basePath, a proxy's page, or another cloudrop version. Worth\n * retrying from 500 on.\n */\nexport const unreadableAnswer = (status: number): CloudropError =>\n new CloudropError(\n \"SERVER_ERROR\",\n `The upload server sent an answer this client cannot read (HTTP ${status}). Check that basePath points at the cloudrop handler and that the server runs the same cloudrop version.`,\n { retryable: status >= 500 },\n );\n\nexport const signatureMismatch = (): CloudropError =>\n new CloudropError(\n \"UPLOAD_REJECTED\",\n \"The storage service refused the file because its bytes do not match what the server signed. Pick the file again and start a new upload.\",\n );\n\nexport const linkRefused = (): CloudropError =>\n new CloudropError(\n \"UPLOAD_REJECTED\",\n \"The storage service refused the upload link, also after it was renewed. Check the server's clock and the storage credentials' permissions, then start the upload again.\",\n );\n\nexport const uploadRejected = (status: number): CloudropError =>\n new CloudropError(\n \"UPLOAD_REJECTED\",\n `The storage service refused the file (HTTP ${status}). Start the upload again, and contact the site owner if it keeps failing.`,\n );\n\n// The next two repeat the server's wording for the same conditions (storageFailure in server/http.ts), which the\n// client cannot import.\nexport const storageBusy = (): CloudropError =>\n new CloudropError(\"RATE_LIMITED\", \"The storage service is busy. Try again in a moment.\", { retryable: true });\n\nexport const storageDown = (): CloudropError =>\n new CloudropError(\"STORAGE_ERROR\", \"The storage service failed. Try again in a moment.\", { retryable: true });\n","// One holder at a time sends an upload (spec §3.5, rulings M3-U69, M3-U73, M3-U88): a Web Lock per upload id, held for\n// as long as this page keeps the upload's ticket alive, not for one run (audit C2). Persistence needs it: no record is\n// saved or resumed without the lock.\n\ninterface UploadLock {\n /**\n * true once this page holds the lock; false when another holder has it, this page included; undefined when the\n * browser refuses Web Locks here (no navigator.locks, a document no longer active, an opaque origin).\n */\n readonly taken: Promise<boolean | undefined>;\n /** Lets the lock go. Called before the answer, it lets the lock go as soon as it is granted; again, it does nothing. */\n release(): void;\n}\n\n/** Asks for the Web Lock of upload `id` without waiting (M3-U73). */\nexport function lockUpload(id: string): UploadLock {\n let release!: () => void;\n const until = new Promise<void>((resolve) => {\n release = resolve;\n });\n const locks = globalThis.navigator?.locks;\n const taken = new Promise<boolean | undefined>((resolve) => {\n if (!locks) return resolve(undefined);\n locks\n .request(`cloudrop:upload:${id}`, { ifAvailable: true }, (lock) => {\n resolve(lock !== null);\n return lock && until;\n })\n .catch(() => resolve(undefined));\n });\n return { taken, release };\n}\n","// The browser's store of unfinished multipart uploads, so that one can resume after a reload (resume spec §3.1, §3.2;\n// rulings M3-U70 to M3-U72). An upload only queues writes here: it never waits for the store or fails on it. Reads\n// report a failure as STORAGE_ERROR, never with the browser's own text.\n\nimport { fail, ok, type Result } from \"../errors.ts\";\nimport { countParts } from \"../part-size.ts\";\nimport { storageUnavailable } from \"./failures.ts\";\n\n/** One multipart upload as IndexedDB keeps it: never a presigned URL, an ETag or a part list (spec §3.1). */\nexport interface UploadRecord {\n id: string;\n namespace: string;\n route: string;\n /** As sent to /upload. */\n metadata: unknown;\n name: string;\n size: number;\n type: string;\n lastModified: number;\n fingerprint: string;\n token: string;\n key: string;\n partSize: number;\n partCount: number;\n expiresAt: string;\n /** Milliseconds since the epoch, for newest first. */\n savedAt: number;\n}\n\nexport interface Records {\n /**\n * False when persistence is off or the runtime has no indexedDB or no Web Locks: then nothing is read or written\n * (spec §3.7, M3-U88).\n */\n readonly enabled: boolean;\n /**\n * Queued in its place when called, also when the record is still being made (its fingerprint is read from the file):\n * a remove called after it runs after it. Never rejects; a failure, or a record that could not be made (a rejection),\n * is dropped: an upload never waits for or fails on the store.\n */\n save(record: UploadRecord | Promise<UploadRecord>): void;\n /** Resolves once the delete has run (a failure resolves STORAGE_ERROR); most callers ignore it. */\n remove(id: string): Promise<Result<unknown>>;\n /** The namespace's unexpired records, newest first (`savedAt` descending); expired ones are removed. */\n list(namespace: string): Promise<Result<UploadRecord[]>>;\n /** Deletes the namespace's records, or every record when `namespace` is null; resolves the count. */\n clear(namespace: string | null): Promise<Result<number>>;\n}\n\nconst STORE = \"uploads\";\n\n/** A record with less time left than this counts as expired, so a listed upload has time to start (M3-U72, §3.6). */\nconst EXPIRY_MARGIN_MS = 60_000;\n\n/**\n * True when a record that expires at `expiresAt` counts as expired at `now`: less than the margin is left. NaN, from an\n * expiresAt that is not a date, compares false, so such a record counts as expired.\n */\nexport const expiresSoon = (expiresAt: string, now: number): boolean =>\n !(Date.parse(expiresAt) - now >= EXPIRY_MARGIN_MS);\n\nconst noRecords: Records = {\n enabled: false,\n save: () => undefined,\n remove: async () => ok(undefined),\n list: async () => ok([]),\n clear: async () => ok(0),\n};\n\n/** Database `cloudrop`, version 1, store `uploads` keyed by `id`, no index (M3-U70). */\nfunction open(factory: IDBFactory): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = factory.open(\"cloudrop\", 1);\n request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: \"id\" });\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/**\n * The type of each field of a record, checked on every record read: the database is shared with every script and\n * library version of the origin (M3-U80).\n */\nconst SHAPE = {\n id: \"string\",\n namespace: \"string\",\n route: \"string\",\n name: \"string\",\n size: \"number\",\n type: \"string\",\n lastModified: \"number\",\n fingerprint: \"string\",\n token: \"string\",\n key: \"string\",\n partSize: \"number\",\n partCount: \"number\",\n expiresAt: \"string\",\n savedAt: \"number\",\n};\n\nconst isRecord = (value: unknown): value is UploadRecord =>\n typeof value === \"object\" &&\n value !== null &&\n Object.entries(SHAPE).every(([field, type]) => typeof (value as Record<string, unknown>)[field] === type);\n\ntype Work<T> = (store: IDBObjectStore, settle: (value: T) => void) => void;\n\n/** Runs `work` in one transaction; resolves with the value it settled once the transaction commits. */\nfunction transact<T>(database: IDBDatabase, work: Work<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const transaction = database.transaction(STORE, \"readwrite\");\n let value: T;\n transaction.oncomplete = () => resolve(value);\n // A failed request aborts its transaction, and so does a failed commit (a full disk).\n transaction.onabort = () => reject(transaction.error);\n work(transaction.objectStore(STORE), (settled) => {\n value = settled;\n });\n });\n}\n\nconst onResult = <T>(request: IDBRequest<T>, use: (result: T) => void): void => {\n request.onsuccess = () => use(request.result);\n};\n\n/**\n * A store over globalThis.indexedDB; a no-op one (lists [], counts 0) when `enabled` is false or the runtime has no\n * indexedDB or no navigator.locks, looked for once, now (M3-U89). Without Web Locks another holder could complete an\n * upload that this page's /abort then deletes, so nothing is kept (M3-U88).\n */\nexport function createRecords(enabled: boolean, now: () => number = () => Date.now()): Records {\n const factory: IDBFactory | undefined = enabled && globalThis.navigator?.locks ? globalThis.indexedDB : undefined;\n if (factory == null) return noRecords;\n\n // Opened on the first operation and kept. A failed open, or a connection the browser closed (site data cleared, a\n // newer schema in another tab), is opened again by the next operation, so one bad moment does not end resuming for\n // the page's life (M3-U71).\n let database: Promise<IDBDatabase> | undefined;\n const connect = (): Promise<IDBDatabase> => {\n const drop = () => {\n if (database === opening) database = undefined;\n };\n const opening = open(factory).then((connection) => {\n connection.onclose = drop;\n connection.onversionchange = () => {\n connection.close();\n drop();\n };\n return connection;\n });\n opening.catch(drop);\n return opening;\n };\n // Every operation runs after the one made before it, so a remove made after a save never runs first (M3-U71).\n let queue: Promise<unknown> = Promise.resolve();\n\n const enqueue = <T>(work: Work<T> | Promise<Work<T>>): Promise<Result<T>> => {\n const done = queue.then(async () => {\n const ready = await work;\n database ??= connect();\n const connection = await database;\n try {\n return ok(await transact(connection, ready));\n } catch (error) {\n // transaction() throws InvalidStateError on a connection that closed without telling us: open a new one next.\n if (error instanceof DOMException && error.name === \"InvalidStateError\") database = undefined;\n throw error;\n }\n });\n const result = done.catch(() => fail(storageUnavailable()));\n queue = result;\n return result;\n };\n\n /**\n * Whether `value`, stored under `id`, is a record this client can use. One that expired, has another shape, or a\n * part count its size and part size do not give (as answers.ts checks a live ticket, audit M2) or above the 10,000\n * parts S3 and R2 allow (Infinity from a part size of 0 included: final review M1), is deleted.\n */\n const usable = (store: IDBObjectStore, id: IDBValidKey, value: unknown): value is UploadRecord => {\n if (\n isRecord(value) &&\n value.partCount <= 10_000 &&\n value.partCount === countParts(value.size, value.partSize) &&\n !expiresSoon(value.expiresAt, now())\n ) {\n return true;\n }\n if (value !== undefined) store.delete(id);\n return false;\n };\n\n return {\n enabled: true,\n save(pending) {\n const work = Promise.resolve(pending).then((record) => (store: IDBObjectStore) => {\n store.put(record);\n // Expired records of any namespace are dropped too: their tokens no longer work (spec §3.2).\n onResult(store.getAll(), (all: UploadRecord[]) => {\n for (const stale of all) usable(store, stale.id, stale);\n });\n });\n // Handled at once: a record that fails while earlier operations still run is no unhandled rejection.\n work.catch(() => undefined);\n void enqueue(work);\n },\n remove: (id) => enqueue((store) => store.delete(id)),\n list: (namespace) =>\n enqueue((store, settle) =>\n onResult(store.getAll(), (all: UploadRecord[]) => {\n const live = all.filter((record) => usable(store, record.id, record) && record.namespace === namespace);\n settle(live.sort((a, b) => b.savedAt - a.savedAt));\n }),\n ),\n clear: (namespace) =>\n enqueue((store, settle) =>\n onResult(store.getAll(), (all: UploadRecord[]) => {\n const doomed = namespace === null ? all : all.filter((record) => record.namespace === namespace);\n for (const record of doomed) store.delete(record.id);\n settle(doomed.length);\n }),\n ),\n };\n}\n","// The retry budget every client request shares (spec §6.2's first row, decision S9).\n\nimport { type CloudropError, fail, type Result } from \"../errors.ts\";\nimport { aborted } from \"./failures.ts\";\n\n/** Attempts per request, the first one included. */\nexport const MAX_ATTEMPTS: number = 6;\n\nconst BASE_DELAY_MS = 500;\nconst MAX_DELAY_MS = 20_000;\n\n/** Full jitter: a random wait up to 0.5 s, 1 s, 2 s… (at most 20 s), never shorter than the answer's Retry-After. */\nexport function retryDelay(failedAttempts: number, retryAfterMs = 0): number {\n const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (failedAttempts - 1));\n return Math.min(MAX_DELAY_MS, Math.max(retryAfterMs, Math.random() * ceiling));\n}\n\n/** A Retry-After header in milliseconds: delay seconds or an HTTP date. 0 when absent, past or unreadable. */\nexport function parseRetryAfter(value: string | null, now: number = Date.now()): number {\n if (value === null) return 0;\n const waitMs = /^\\d+$/.test(value.trim()) ? Number(value) * 1000 : Date.parse(value) - now;\n return Number.isFinite(waitMs) ? Math.max(waitMs, 0) : 0;\n}\n\n// Kept beside the error rather than as a field of CloudropError, which is public and would promise it.\nconst retryAfters = new WeakMap<CloudropError, number>();\n\n/** The Retry-After recorded for `error`'s answer, 0 when none. */\nexport const retryAfterOf = (error: CloudropError): number => retryAfters.get(error) ?? 0;\n\n/** Records that `error`'s request must not be tried again before `retryAfterMs` (its answer's Retry-After). */\nexport function waitAtLeast(error: CloudropError, retryAfterMs: number): CloudropError {\n retryAfters.set(error, retryAfterMs);\n return error;\n}\n\n/** Waits `ms`, or less when the signal fires. Never rejects: the caller checks `signal.aborted` afterwards. */\nexport function pause(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\n/**\n * Calls `run` until it succeeds, fails with an error that is not retryable, or has used MAX_ATTEMPTS. A cancel before\n * an attempt or during a pause returns ABORTED; an answer that arrives after a cancel is returned as it is, since a\n * request that finished must not be reported as cancelled. `first` continues a budget earlier attempts used, and `run`\n * hears which attempt it makes.\n */\nexport async function withRetry<T>(\n run: (attempt: number) => Promise<Result<T>>,\n signal: AbortSignal,\n first = 1,\n): Promise<Result<T>> {\n for (let attempt = first; ; attempt++) {\n if (signal.aborted) return fail(aborted());\n const result = await run(attempt);\n const { error } = result;\n if (!error?.retryable || attempt === MAX_ATTEMPTS) return result;\n await pause(retryDelay(attempt, retryAfterOf(error)), signal);\n }\n}\n","// Sends the parts of one multipart upload: four at a time, signing the parts the ticket did not cover lazily, renewing\n// URLs that expire, retrying within one budget, and stopping on a cancel or once one part has failed the file\n// (decisions S11, S12; spec §6.1, §6.2).\n\nimport { type CloudropError, fail, ok, type Result } from \"../errors.ts\";\nimport { PARTS_PER_SIGN, type SignedPart, type SignedRequest } from \"../protocol/types.ts\";\nimport type { BucketOutcome } from \"./bucket.ts\";\nimport { aborted, unreadableAnswer } from \"./failures.ts\";\nimport { MAX_ATTEMPTS, pause, retryAfterOf, retryDelay } from \"./retry.ts\";\n\n/** At most this many parts of one file in flight (spec §6.1). */\nconst PARTS_IN_FLIGHT = 4;\n\nexport interface PartSender {\n signal: AbortSignal;\n /**\n * The upload's URLs by part number: the ticket's, then each one /sign answers, kept across passes so a part signed\n * or renewed once is not signed again (M4-F8).\n */\n urls: Map<number, SignedRequest>;\n /** POST /sign for these parts; the answer holds exactly them (answers.ts checks it). */\n sign(partNumbers: readonly number[]): Promise<Result<SignedPart[]>>;\n /** PUT this part's bytes to the URL. `stop` fires on a cancel or once the file has failed: start nothing after it. */\n put(target: SignedRequest, partNumber: number, stop: AbortSignal): Promise<BucketOutcome>;\n}\n\ntype Step =\n | { kind: \"done\" }\n | { kind: \"fail\"; error: CloudropError }\n | { kind: \"again\"; renew: boolean; waitMs: number };\n\n/** A URL with less time left than this by the client's clock is renewed before it is used (S11). */\nconst RENEW_MARGIN_MS = 60_000;\n\ninterface Run {\n sender: PartSender;\n partNumbers: readonly number[];\n /** The /sign call that workers reaching unsigned parts share. */\n batch: Promise<CloudropError | null> | null;\n /** The first part failure that fails the file. */\n failure: CloudropError | null;\n /** Fires on a cancel or once the file has failed, so a part waiting to retry stops at once. */\n stop: AbortController;\n}\n\nconst expiresSoon = (target: SignedRequest): boolean => Date.parse(target.expiresAt) - Date.now() < RENEW_MARGIN_MS;\n\n/** A /sign failure, seen as the outcome of a part's attempt so one budget covers both. */\nfunction signFailure(error: CloudropError): BucketOutcome {\n if (error.code === \"ABORTED\") return { kind: \"aborted\", error };\n return error.retryable ? { kind: \"retry\", error, retryAfterMs: retryAfterOf(error) } : { kind: \"rejected\", error };\n}\n\n/** What to do after an attempt: `attempt` is its number, `renewed` whether this part's URL was already renewed. */\nexport function nextStep(outcome: BucketOutcome, attempt: number, renewed: boolean): Step {\n if (outcome.kind === \"stored\") return { kind: \"done\" };\n // Rejected or aborted: the outcomes without a wait (`kind` alone cannot narrow their shared union member).\n if (!(\"retryAfterMs\" in outcome)) return { kind: \"fail\", error: outcome.error };\n // A renewed URL refused as expired again will not get better (S11).\n if (attempt >= MAX_ATTEMPTS || (outcome.kind === \"expired\" && renewed)) return { kind: \"fail\", error: outcome.error };\n // A failure the browser hides (an expired R2 URL answers without CORS headers) or a readable expiry: new URL, once.\n const renew = (outcome.kind === \"opaque\" || outcome.kind === \"expired\") && !renewed;\n // A readable expiry is retried at once with the new URL; every other failure waits first (spec §6.2).\n const waitMs = renew && outcome.kind === \"expired\" ? 0 : retryDelay(attempt, outcome.retryAfterMs);\n return { kind: \"again\", renew, waitMs };\n}\n\n/** Signs `partNumber` and the next unsigned parts, at most PARTS_PER_SIGN, in one call that waiting workers share. */\nfunction signAhead(run: Run, partNumber: number): Promise<CloudropError | null> {\n if (run.batch) return run.batch;\n const unsigned = run.partNumbers.filter((n) => n !== partNumber && !run.sender.urls.has(n));\n const call = run.sender.sign([partNumber, ...unsigned].slice(0, PARTS_PER_SIGN)).then((signed) => {\n run.batch = null;\n if (signed.error) return signed.error;\n for (const part of signed.data) run.sender.urls.set(part.partNumber, part);\n return null;\n });\n run.batch = call;\n return call;\n}\n\nasync function urlFor(run: Run, partNumber: number, renew: boolean): Promise<Result<SignedRequest>> {\n let known = run.sender.urls.get(partNumber);\n // A batch that did not include this part (another worker started it) is followed by one that does. A third pass\n // would mean a /sign answer that leaves the part out, which answers.ts refuses: stop rather than spin.\n for (let pass = 1; known === undefined; pass++) {\n if (pass > 2) return fail(unreadableAnswer(200));\n const error = await signAhead(run, partNumber);\n if (error) return fail(error);\n known = run.sender.urls.get(partNumber);\n }\n if (!renew && !expiresSoon(known)) return ok(known);\n const renewed = await run.sender.sign([partNumber]);\n if (renewed.error) return renewed;\n const [part] = renewed.data;\n if (part === undefined) return fail(unreadableAnswer(200)); // unreachable: answers.ts checked the parts\n run.sender.urls.set(partNumber, part);\n return ok(part);\n}\n\n/** Why no new attempt may start: a cancel, or another part that failed the file (its error is the call's). */\nconst stopped = (run: Run): CloudropError | null => (run.sender.signal.aborted ? aborted() : run.failure);\n\nasync function sendPart(run: Run, partNumber: number): Promise<CloudropError | null> {\n let renew = false;\n let renewed = false;\n for (let attempt = 1; ; attempt++) {\n if (stopped(run)) return stopped(run);\n const target = await urlFor(run, partNumber, renew);\n // urlFor may have waited for a /sign; the upload may have been cancelled or have failed meanwhile.\n if (stopped(run)) return stopped(run);\n const outcome = target.error\n ? signFailure(target.error)\n : await run.sender.put(target.data, partNumber, run.stop.signal);\n const step = nextStep(outcome, attempt, renewed);\n if (step.kind === \"done\") return null;\n if (step.kind === \"fail\") return step.error;\n // A renewal whose /sign failed is still owed: the next attempt must not reuse the refused URL.\n renew = step.renew || (renew && target.error !== null);\n renewed ||= step.renew;\n await pause(step.waitMs, run.stop.signal);\n }\n}\n\n/** Sends `partNumbers` (ascending), at most PARTS_IN_FLIGHT at a time. The first part that fails for good fails the call. */\nexport async function sendParts(sender: PartSender, partNumbers: readonly number[]): Promise<Result<void>> {\n const run: Run = {\n sender,\n partNumbers,\n batch: null,\n failure: null,\n stop: new AbortController(),\n };\n const cancel = () => run.stop.abort();\n sender.signal.addEventListener(\"abort\", cancel, { once: true });\n const queue = [...partNumbers];\n // The first part that fails for good stops new parts and new attempts; requests already sent finish (spec §6.2).\n const worker = async (): Promise<void> => {\n for (let next = queue.shift(); next !== undefined && run.failure === null; next = queue.shift()) {\n // Read before `run.failure ??=`: `run.failure ??= await sendPart(…)` would test it before the await and let a\n // later success overwrite another worker's failure with null.\n const error = await sendPart(run, next);\n run.failure ??= error;\n if (run.failure) run.stop.abort();\n }\n };\n await Promise.all(Array.from({ length: Math.min(PARTS_IN_FLIGHT, queue.length) }, worker));\n // The caller's signal may outlive this call: drop the listener that holds the run.\n sender.signal.removeEventListener(\"abort\", cancel);\n return run.failure ? fail(run.failure) : ok(undefined);\n}\n","// One pass of a file: the bytes that have not landed as one PUT or as parts, each PUT holding a slot of the client's\n// pool, then /complete with up to two repair rounds (decisions S13, S14). file-run.ts runs the passes and decides how\n// the file ends.\n\nimport { fail, ok, type Result } from \"../errors.ts\";\nimport { sizeOfPart } from \"../part-size.ts\";\nimport type { CompleteResponse, MultipartTicket, SignedPart, SignedRequest } from \"../protocol/types.ts\";\nimport type { BucketOutcome } from \"./bucket.ts\";\nimport type { Endpoints, Ticket } from \"./endpoints.ts\";\nimport type { Entry } from \"./entry.ts\";\nimport { aborted } from \"./failures.ts\";\nimport type { Leftovers } from \"./lifecycle.ts\";\nimport { type PartSender, sendParts } from \"./parts.ts\";\nimport type { Pool } from \"./pool.ts\";\nimport type { Records } from \"./records.ts\";\nimport { withRetry } from \"./retry.ts\";\nimport type { PutObject } from \"./transport.ts\";\n\n/** /complete may answer PARTS_MISSING this many times before the file fails (S13). */\nconst REPAIR_ROUNDS = 2;\n\nexport interface UploadContext {\n endpoints: Endpoints;\n put: PutObject;\n /** The client's connection slots: every bucket PUT holds one (spec §4.4). */\n pool: Pool;\n /** Which waiting PUTs the pool grants first: the earlier file's, or the smaller file's (spec §4.4). */\n order: \"added\" | \"smallest-first\";\n /** The next file's rank in the pool, counting from 1 across the client's uploads (ruling M3-U9). */\n nextRank(): number;\n /** The failed files' tickets that pagehide frees (ruling M3-U33). */\n leftovers: Leftovers;\n /**\n * A failed file keeps its ticket and parts for retry(): start() jobs; upload() has no handle to retry with\n * (M3-U29).\n */\n keepFailed: boolean;\n /** The browser's store of unfinished multipart uploads (resume spec §3.1); a no-op one with persistence off. */\n records: Records;\n /** Keeps one signed-in user's records apart from another's (ruling M3-U79). */\n namespace: string;\n /**\n * One claim per holder of an upload: a ticket, from its arrival to its unlock, and a resume, from resume() to its\n * refusal or its upload's unlock. resumable() leaves out every upload with a claim (M4-F22).\n */\n claims: Set<{ id: string }>;\n}\n\n/**\n * Claims upload `id` until the returned function is called; again, it does nothing. Each holder releases only its own\n * claim, so two holders of one upload, such as two resumes in flight, never release each other's (M4-F22).\n */\nexport function claim({ claims }: UploadContext, id: string): () => void {\n const made = { id };\n claims.add(made);\n return () => claims.delete(made);\n}\n\nfunction bodyOf(ticket: Ticket, file: File, partNumber: number): Blob {\n if (ticket.kind === \"single\") return file;\n const start = (partNumber - 1) * ticket.partSize;\n return file.slice(start, start + sizeOfPart(file.size, ticket.partSize, partNumber));\n}\n\n/** A file's upload under one ticket, across its passes and same-ticket retries. */\nexport interface Upload {\n readonly ticket: Ticket;\n readonly entry: Entry;\n /** Some /complete got no answer or a SERVER_ERROR, so the server may have completed the file: a cancel keeps it. */\n mayBeComplete: boolean;\n /** The PARTS_MISSING repair rounds started so far. */\n repairs: number;\n /**\n * The page gave its ticket up: its /abort was sent, or a reload may resume it (giveUp, M4-F1). A retry needs a new\n * ticket, and no /abort follows (M3-U33).\n */\n dropped: boolean;\n /** Lets go of the upload's Web Lock, held while the page keeps the ticket (M3-U73); a no-op when none was taken. */\n unlock(): void;\n /**\n * Rebuilt from a record by resume() and still waiting for its probe's first answer that lists what landed: success\n * or PARTS_MISSING (resume spec §3.4). Until then every part counts as landed and no byte as sent.\n */\n probe: boolean;\n /** Every URL signed for it so far (PartSender.urls). */\n readonly urls: Map<number, SignedRequest>;\n}\n\n/** `entry`'s upload under `ticket`, from its first pass; `probe` when resume() rebuilt it from a record. */\nexport function newUpload(ticket: Ticket, entry: Entry, unlock: () => void, probe = false): Upload {\n // A single PUT is part 1 of 1, so one routine sends both kinds.\n const signed = ticket.kind === \"single\" ? [{ partNumber: 1, ...ticket.put }] : ticket.parts;\n const urls = new Map(signed.map((part) => [part.partNumber, part]));\n return { ticket, entry, mayBeComplete: false, repairs: 0, dropped: false, unlock, probe, urls };\n}\n\n/** The file moves to `status` and the job hears of it at once. Sending starts the speed from 0. */\nfunction moveTo(entry: Entry, status: \"uploading\" | \"completing\"): void {\n if (status === \"uploading\") entry.meter.restart(Date.now());\n entry.status = status;\n entry.changed(true);\n}\n\n/** Sends through `signal`, the pass's: a pause or a cancel aborts the PUTs and /sign calls in flight. */\nfunction senderFor(context: UploadContext, { ticket, entry, urls }: Upload, signal: AbortSignal): PartSender {\n const { file, rank } = entry;\n const { pool } = context;\n // A slot is held for the PUT alone: it is free again before a retry's wait (spec §4.4). A part still waiting for one\n // when the file is cancelled or has failed never starts; a PUT already sent finishes (spec §6.2).\n const put = async (target: SignedRequest, partNumber: number, stop: AbortSignal): Promise<BucketOutcome> => {\n const place = context.order === \"smallest-first\" ? [file.size, rank, partNumber] : [rank, partNumber];\n const release = await pool.acquire(place, stop);\n try {\n // `stop` may also fire between the grant and this line: the slot goes back unused (ruling M3-U21).\n if (release === null || stop.aborted) return { kind: \"aborted\", error: aborted() };\n // Never from paused or a settled status (ruling M3-U21): those abort the pass, and `stop` with it.\n if (entry.status === \"queued\") moveTo(entry, \"uploading\");\n const body = bodyOf(ticket, file, partNumber);\n const outcome = await context.put(target, body, signal, (sent) => {\n // Only bytes above this part's earlier best: a retry sending them again is no throughput.\n const added = entry.progress.sent(partNumber, sent, body.size);\n if (added === 0) return;\n pool.sent(added);\n entry.meter.add(added, Date.now());\n entry.changed(false);\n });\n if (outcome.kind === \"stored\") entry.landed.add(partNumber);\n // Before the release below, so the slot it frees goes back to a pool already halved (ruling M3-U45).\n if (outcome.kind === \"opaque\" || (outcome.kind === \"retry\" && outcome.error.code === \"RATE_LIMITED\")) {\n pool.slowDown();\n }\n return outcome;\n } finally {\n release?.();\n }\n };\n if (ticket.kind === \"multipart\") {\n return { signal, urls, put, sign: (parts) => context.endpoints.signParts(ticket.token, parts, signal) };\n }\n const sign = async (): Promise<Result<SignedPart[]>> => {\n const renewed = await context.endpoints.signSingle(ticket.token, signal);\n return renewed.error ? renewed : ok([{ partNumber: 1, ...renewed.data }]);\n };\n return { signal, urls, put, sign };\n}\n\n/**\n * A resumed upload's probe got `done`. Its first answer that lists what landed, success or PARTS_MISSING naming\n * `missing`, ends the probe: the parts it did not name count their whole size from now; no byte flowed, so neither the\n * pool nor the speed hears of them (M3-U75, audit I3). That PARTS_MISSING is the list of what is left, not a repair:\n * it takes no repair round. Any other answer leaves the probe for a retry to send again.\n */\nfunction probed(upload: Upload, done: Result<unknown>, missing: readonly number[] | undefined): void {\n if (done.error && !missing) return;\n const { entry, ticket } = upload;\n upload.probe = false;\n // Only a multipart ticket is probed: each size comes from the plan, without slicing the file (final review M2).\n const { partSize } = ticket as MultipartTicket;\n // A Set: 0.6 ms instead of 20 ms for an array at 10,000 parts with 9,000 missing (M4-F7).\n const lacking = new Set(missing);\n for (const part of entry.landed) {\n const size = sizeOfPart(entry.file.size, partSize, part);\n if (!lacking.has(part)) entry.progress.sent(part, size, size);\n }\n // The caller counts a repair round for this answer next: given back here.\n if (missing) upload.repairs--;\n}\n\n/** Sends the parts that have not landed and completes the file. ABORTED when `signal` (the pass's) fired first. */\nexport async function sendAndComplete(\n context: UploadContext,\n upload: Upload,\n signal: AbortSignal,\n): Promise<Result<CompleteResponse<unknown>>> {\n const { ticket, entry } = upload;\n const sender = senderFor(context, upload, signal);\n const partNumbers = Array.from({ length: ticket.kind === \"single\" ? 1 : ticket.partCount }, (_, index) => index + 1);\n // Without the signal: the server may finish a /complete (and run onComplete) after the browser stopped waiting (S14).\n const complete = async (): Promise<Result<CompleteResponse<unknown>>> => {\n const done = await context.endpoints.complete(ticket.token);\n const code = done.error?.code;\n // PARTS_MISSING clears the doubt wherever it arrives: the server sends it only while the multipart upload is still\n // open, so no earlier /complete finished the file and /abort deletes nothing recorded (ruling S-9). NO_SUCH_UPLOAD\n // too: the server sends it once it found the upload gone and no object of it stored (server/complete.ts, M3-U83).\n if (code === \"PARTS_MISSING\" || code === \"NO_SUCH_UPLOAD\") upload.mayBeComplete = false;\n // Otherwise sticky: a later answer does not undo an earlier /complete that may have finished (S14, M3-H16).\n else upload.mayBeComplete ||= code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\";\n return done;\n };\n for (;;) {\n const unsent = partNumbers.filter((partNumber) => !entry.landed.has(partNumber));\n const sent = await sendParts(sender, unsent);\n if (sent.error) return fail(sent.error);\n // Paused after the last part landed: /complete waits for the next pass, which sends nothing first.\n if (signal.aborted) return fail(aborted());\n moveTo(entry, \"completing\");\n const done = await withRetry(complete, entry.cancel.signal);\n const missing = done.error?.code === \"PARTS_MISSING\" ? done.error.parts : undefined;\n if (upload.probe) probed(upload, done, missing);\n // A cancel during /complete ends the file with this answer rather than start a repair (M4-F4).\n if (!missing?.length || upload.repairs === REPAIR_ROUNDS || entry.cancel.signal.aborted) return done;\n upload.repairs++;\n for (const partNumber of missing) entry.landed.delete(partNumber);\n // Uploading again at once, so a pause applies to the repair (ruling M3-U4).\n moveTo(entry, \"uploading\");\n }\n}\n","// discard(upload) (decisions M3-U93, M3-U94): drops one unfinished upload that resumable() listed, without its file.\n// Under the upload's lock, as a resume would run it, the record's own token is sent to /abort with `keep`, which aborts\n// an unfinished multipart upload and, with a store, ends its row and frees its reservation, but never deletes an object\n// that landed: a /complete may have finished the upload while the page heard nothing (M3-U82, M3-H16). Then the record\n// is deleted and, once that delete has run, the lock let go.\n\nimport { fail, ok, type Result } from \"../errors.ts\";\nimport { invalidInput } from \"../input.ts\";\nimport { lockRefused, NEEDS_NEW_TICKET, notListed, uploadInUse } from \"./failures.ts\";\nimport { lockUpload } from \"./locks.ts\";\nimport { expiresSoon } from \"./records.ts\";\nimport { claim, type UploadContext } from \"./upload.ts\";\n\nexport async function discard(context: UploadContext, upload: unknown): Promise<Result<{ aborted: boolean }>> {\n const { id, expiresAt } = (upload ?? {}) as { id?: unknown; expiresAt?: unknown };\n if (typeof id !== \"string\") return fail(invalidInput(\"Pass discard() an upload from resumable().\"));\n // Claimed before the first await, as a resume claims (M4-F22): resumable() leaves it out from now on.\n const release = claim(context, id);\n try {\n const { data, error } = await context.records.list(context.namespace);\n if (error) return fail(error);\n const record = data.find((saved) => saved.id === id);\n // An expired record was deleted by that read, its token with it: there is nothing to send /abort with.\n if (!record) {\n const expired = typeof expiresAt === \"string\" && expiresSoon(expiresAt, Date.now());\n return expired ? ok({ aborted: false }) : fail(notListed());\n }\n const lock = lockUpload(id);\n const taken = await lock.taken;\n // Another holder may complete it, and an /abort would then delete the finished object (M3-U73). Where the browser\n // refuses Web Locks, nothing that needs one runs (M3-U88).\n if (!taken) return fail(taken === false ? uploadInUse() : lockRefused());\n try {\n // The server takes an expired token for /abort, so a record still listed can always be aborted (spec §5.5).\n const answer = await context.endpoints.abort(record.token, { keep: true });\n // A token the server refuses for good cannot abort anything, now or later; any other failure may pass on another\n // try, so the record stays for it.\n if (answer.error && !NEEDS_NEW_TICKET.has(answer.error.code)) return fail(answer.error);\n // Deleted before the lock goes, so no other tab finds the record free in between. Its result is not read: the\n // server's part is done, and a record that survives a failed delete is aborted again harmlessly.\n await context.records.remove(id);\n return ok({ aborted: answer.error === null });\n } finally {\n lock.release();\n }\n } finally {\n release();\n }\n}\n","// The shape checks for the four endpoints' answers (decision S16). The server is trusted, but the answer may come from\n// a proxy, a wrong basePath or another cloudrop version: each reader returns its typed value, or null for any other\n// shape, so a bad answer becomes an error instead of a TypeError deep in the upload.\n\nimport type { CloudropErrorCode } from \"../errors.ts\";\nimport { isPlainObject } from \"../input.ts\";\nimport { countParts } from \"../part-size.ts\";\nimport type {\n CompleteResponse,\n ErrorBody,\n MultipartTicket,\n SignedPart,\n SignedRequest,\n SingleTicket,\n UploadedFile,\n} from \"../protocol/types.ts\";\nimport type { Ticket } from \"./endpoints.ts\";\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isTime = (value: unknown): value is string => isString(value) && !Number.isNaN(Date.parse(value));\nconst isSafeInteger = (value: unknown): value is number => Number.isSafeInteger(value);\nconst isCount = (value: unknown): value is number => isSafeInteger(value) && value > 0;\n\nfunction isSignedRequest(value: unknown): value is SignedRequest {\n return (\n isPlainObject(value) &&\n isString(value.url) &&\n isPlainObject(value.headers) &&\n Object.values(value.headers).every(isString) &&\n isTime(value.expiresAt)\n );\n}\n\nfunction isSignedPart(value: unknown, isWanted: (partNumber: number) => boolean): value is SignedPart {\n return (\n isPlainObject(value) && isSafeInteger(value.partNumber) && isWanted(value.partNumber) && isSignedRequest(value)\n );\n}\n\nfunction hasTicketFields(value: unknown): value is Record<string, unknown> {\n return (\n isPlainObject(value) &&\n isString(value.id) &&\n isString(value.key) &&\n isString(value.token) &&\n isTime(value.expiresAt)\n );\n}\n\nfunction isSingle(value: unknown): value is SingleTicket {\n return hasTicketFields(value) && value.kind === \"single\" && isSignedRequest(value.put);\n}\n\nfunction isMultipart(value: unknown, size: number): value is MultipartTicket {\n if (!hasTicketFields(value) || value.kind !== \"multipart\") return false;\n const { partSize, partCount, parts } = value;\n return (\n isCount(partSize) &&\n isCount(partCount) &&\n // The plan in the token decides (S7): a client that would cut the file differently must stop here.\n partCount === countParts(size, partSize) &&\n Array.isArray(parts) &&\n parts.every((part) => isSignedPart(part, (partNumber) => partNumber >= 1 && partNumber <= partCount))\n );\n}\n\nfunction isUploadedFile(value: unknown): value is UploadedFile {\n return (\n isPlainObject(value) &&\n isString(value.id) &&\n isString(value.key) &&\n isString(value.name) &&\n isString(value.type) &&\n typeof value.size === \"number\" &&\n (value.url === null || isString(value.url))\n );\n}\n\nfunction readError(value: unknown): ErrorBody | null {\n if (!isPlainObject(value)) return null;\n const { code, message, retryable, parts } = value;\n if (!isString(code) || !isString(message) || typeof retryable !== \"boolean\") return null;\n // A code this client does not know passes through: a newer server may send one, and `message` still explains it.\n const body = { code: code as CloudropErrorCode, message, retryable };\n return Array.isArray(parts) && parts.every(isCount) ? { ...body, parts } : body;\n}\n\nfunction readFileTicket(value: unknown, size: number): Ticket | ErrorBody | null {\n if (isSingle(value) || isMultipart(value, size)) return value;\n return isPlainObject(value) && value.kind === \"rejected\" ? readError(value.error) : null;\n}\n\n/**\n * The tickets of /upload, one per file in the order sent: a single or multipart ticket, or the error body of a rejected\n * file. One that cannot be read makes the whole answer unreadable.\n */\nexport function readTickets(json: unknown, files: readonly File[]): (Ticket | ErrorBody)[] | null {\n if (!isPlainObject(json) || !Array.isArray(json.files) || json.files.length !== files.length) return null;\n const answers: unknown[] = json.files;\n const tickets = files.map((file, index) => readFileTicket(answers[index], file.size));\n return tickets.every((ticket) => ticket !== null) ? tickets : null;\n}\n\n/** `{ put }` of /sign for a single PUT. */\nexport function readSignedRequest(json: unknown): SignedRequest | null {\n return isPlainObject(json) && isSignedRequest(json.put) ? json.put : null;\n}\n\n/** `{ parts }` of /sign, holding exactly the asked part numbers, each once: a missing one would never be sent. */\nexport function readSignedParts(json: unknown, asked: readonly number[]): SignedPart[] | null {\n if (!isPlainObject(json) || !Array.isArray(json.parts) || json.parts.length !== asked.length) return null;\n const unanswered = new Set(asked);\n return json.parts.every((part) => isSignedPart(part, (partNumber) => unanswered.delete(partNumber)))\n ? json.parts\n : null;\n}\n\n/** `{ file, data }` of /complete; `data` is any JSON value, null without onComplete. */\nexport function readCompleted(json: unknown): CompleteResponse<unknown> | null {\n return isPlainObject(json) && isUploadedFile(json.file) && \"data\" in json\n ? { file: json.file, data: json.data }\n : null;\n}\n\n/** `{ error }` of a non-2xx answer; `parts`, when it is not a list of part numbers, is dropped. */\nexport function readErrorBody(json: unknown): ErrorBody | null {\n return isPlainObject(json) ? readError(json.error) : null;\n}\n","// The client's calls to the four server endpoints (spec §5). Each answer is checked before it is used (decision S16).\n\nimport { CloudropError, fail, ok, type Result } from \"../errors.ts\";\nimport type {\n CompleteResponse,\n Endpoint,\n ErrorBody,\n MultipartTicket,\n SignedPart,\n SignedRequest,\n SingleTicket,\n UploadRequest,\n} from \"../protocol/types.ts\";\nimport { readCompleted, readErrorBody, readSignedParts, readSignedRequest, readTickets } from \"./answers.ts\";\nimport { aborted, serverBusy, serverUnreachable, unreadableAnswer } from \"./failures.ts\";\nimport { parseRetryAfter, waitAtLeast } from \"./retry.ts\";\n\n/** How the client sends every request: the endpoints' POSTs and the bucket's PUTs. */\nexport type ClientFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nexport type Ticket = SingleTicket | MultipartTicket;\n\nexport interface Endpoints {\n /**\n * POST /upload for every file at once: one entry per file, in order; a rejected file is its error, which carries the\n * answer's Retry-After (M3-U92). `idempotencyKey` names the ask: every retry of one ask sends the same.\n */\n start(\n route: string,\n files: readonly File[],\n metadata: unknown,\n idempotencyKey: string,\n signal: AbortSignal,\n ): Promise<Result<(Ticket | CloudropError)[]>>;\n /** POST /sign { token }: a new URL for a single PUT. */\n signSingle(token: string, signal: AbortSignal): Promise<Result<SignedRequest>>;\n /** POST /sign { token, parts }: one URL per asked part, nothing else. */\n signParts(token: string, parts: readonly number[], signal: AbortSignal): Promise<Result<SignedPart[]>>;\n /** POST /complete { token }, without the caller's signal: a cancel must not cut off a /complete the server may finish. */\n complete(token: string): Promise<Result<CompleteResponse<unknown>>>;\n /**\n * POST /abort { token }, once, with keepalive so a closing tab still delivers it; never rejects. Only discard() reads\n * the result (M3-U93), and only discard() sends `keep` (M3-U94), without keepalive (M3-U95); the answer's id is\n * ignored.\n */\n abort(token: string, options?: { keep: true }): Promise<Result<true>>;\n}\n\n// How long each call may wait for its whole answer, so a server that never answers cannot hold a file queued,\n// completing or cancelling for good (M4-F3). /complete may list 10,000 parts, which the server verifies first.\nconst ASK_TIMEOUT_MS = 30_000;\nconst COMPLETE_TIMEOUT_MS = 120_000;\nconst ABORT_TIMEOUT_MS = 10_000;\n\n/** The parsed body, or undefined (which JSON never is) when it is not JSON: every reader refuses it. */\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** A non-2xx answer without cloudrop's error body. A 429 page says the cause is load, not a wrong basePath (S-7). */\nconst refusal = (status: number): CloudropError => (status === 429 ? serverBusy() : unreadableAnswer(status));\n\n// The body's retryable and parts are the error's options.\nconst toError = (body: ErrorBody): CloudropError => new CloudropError(body.code, body.message, body);\n\nexport function createEndpoints(basePath: string, fetch: ClientFetch): Endpoints {\n /**\n * POSTs `body` as JSON and reads a 2xx answer with `read`. Never rejects. No whole answer within `timeoutMs` is\n * NETWORK_ERROR, as no answer is; ABORTED only when `signal` fired.\n */\n async function post<T>(\n endpoint: Endpoint,\n body: unknown,\n {\n signal,\n keepalive,\n timeoutMs = ASK_TIMEOUT_MS,\n }: { signal?: AbortSignal; keepalive?: boolean; timeoutMs?: number },\n read: (json: unknown, retryAfterMs: number) => T | null,\n ): Promise<Result<T>> {\n // Without AbortSignal.any (ruling M3-U19): one controller that the timeout and the caller's signal both abort.\n const controller = new AbortController();\n const stop = () => controller.abort();\n const timeout = setTimeout(stop, timeoutMs);\n signal?.addEventListener(\"abort\", stop, { once: true });\n if (signal?.aborted) stop();\n let response: Response;\n let text: string;\n try {\n // \"include\": a page on a trusted origin sends its session cookie, which authorize may read (S8).\n response = await fetch(`${basePath}/${endpoint}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n credentials: \"include\",\n signal: controller.signal,\n keepalive,\n });\n // A body cut off on the way counts as no answer: for /complete, the server may have finished.\n text = await response.text();\n } catch {\n return fail(signal?.aborted ? aborted() : serverUnreachable());\n } finally {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", stop);\n }\n const json = parseJson(text);\n const retryAfterMs = parseRetryAfter(response.headers.get(\"retry-after\"));\n if (!response.ok) {\n const body = readErrorBody(json);\n return fail(waitAtLeast(body ? toError(body) : refusal(response.status), retryAfterMs));\n }\n const data = read(json, retryAfterMs);\n return data === null ? fail(unreadableAnswer(response.status)) : ok(data);\n }\n\n return {\n start(route, files, metadata, idempotencyKey, signal) {\n // JSON.stringify leaves out a metadata of undefined, as UploadRequest's optional field allows.\n const request: UploadRequest = {\n route,\n files: files.map(({ name, size, type }) => ({ name, size, type })),\n metadata,\n idempotencyKey,\n };\n return post(\n \"upload\",\n request,\n { signal },\n (json, retryAfterMs) =>\n readTickets(json, files)?.map((ticket) =>\n \"kind\" in ticket ? ticket : waitAtLeast(toError(ticket), retryAfterMs),\n ) ?? null,\n );\n },\n signSingle: (token, signal) => post(\"sign\", { token }, { signal }, readSignedRequest),\n signParts: (token, parts, signal) =>\n post(\"sign\", { token, parts }, { signal }, (json) => readSignedParts(json, parts)),\n complete: (token) => post(\"complete\", { token }, { timeoutMs: COMPLETE_TIMEOUT_MS }, readCompleted),\n // A failed /abort changes nothing for a cancelled upload; the lifecycle rule cleans up. A browser allows a document\n // 64 KiB of keepalive bodies in flight together, and a token may be 12 KiB, so discard(), which a live page awaits and\n // may run for many uploads at once, sends without keepalive (M3-U95).\n abort: (token, options) =>\n post(\n \"abort\",\n { token, ...options },\n { keepalive: options?.keep !== true, timeoutMs: ABORT_TIMEOUT_MS },\n () => true,\n ),\n };\n}\n","// How much of a file has been sent (spec §4.2) and how fast (spec §4.3).\n\n/** The speed's time constant: the average follows a change in rate within about 3 s. */\nconst TIME_CONSTANT_MS = 3000;\n\nexport interface Progress {\n /** Bytes counted for the file: the sum over its parts of the most each attempt ever sent. Never decreases. */\n readonly bytes: number;\n /** The current attempt of `part` has sent `sent` of `partSize` bytes. Returns what this added to `bytes`. */\n sent(part: number, sent: number, partSize: number): number;\n}\n\nexport function createProgress(): Progress {\n const best = new Map<number, number>();\n let bytes = 0;\n return {\n get bytes() {\n return bytes;\n },\n sent(part, sent, partSize) {\n const before = best.get(part) ?? 0;\n const reached = Math.min(sent, partSize);\n // A re-sent attempt adds nothing until it passes what an earlier attempt of the same part reached.\n if (reached <= before) return 0;\n best.set(part, reached);\n bytes += reached - before;\n return reached - before;\n },\n };\n}\n\nexport interface Meter {\n /** `bytes` more were sent by `now` (ms). */\n add(bytes: number, now: number): void;\n /** Bytes per second at `now`, decayed since the last add. */\n speed(now: number): number;\n /** Starts from 0 at `now`: when a file starts or resumes sending. */\n restart(now: number): void;\n}\n\n/** A meter at rest: restart() starts it when the file starts sending. */\nexport function createMeter(): Meter {\n let rate = 0;\n let last = 0;\n // Bytes reported in the same millisecond as `last`: no time has passed to divide them by.\n let pending = 0;\n return {\n add(bytes, at) {\n const elapsed = at - last;\n if (elapsed <= 0) {\n pending += bytes;\n return;\n }\n const alpha = 1 - Math.exp(-elapsed / TIME_CONSTANT_MS);\n rate += alpha * (((bytes + pending) * 1000) / elapsed - rate);\n pending = 0;\n last = at;\n },\n speed: (at) => rate * Math.exp(-Math.max(0, at - last) / TIME_CONSTANT_MS),\n restart(at) {\n rate = 0;\n last = at;\n pending = 0;\n },\n };\n}\n","// One file of a job and where it stands (spec §2.1): its status, bytes and speed, how it settles, and its pause and\n// resume (spec §4.5). file-run.ts runs it from its ticket to its outcome.\n\nimport type { CloudropError } from \"../errors.ts\";\nimport type { CompleteResponse } from \"../protocol/types.ts\";\nimport { createMeter, createProgress, type Meter, type Progress } from \"./progress.ts\";\nimport type { FileOutcome, FileStatus } from \"./types.ts\";\nimport type { Upload } from \"./upload.ts\";\n\n/** One file of a job and where it stands. */\nexport interface Entry {\n readonly id: string;\n readonly file: File;\n /** The file's place in the pool's queue (ruling M3-U9). */\n readonly rank: number;\n status: FileStatus;\n result: CompleteResponse<unknown> | null;\n error: CloudropError | null;\n /** The bytes sent so far; a new ticket starts a new count (ruling M3-U36). */\n progress: Progress;\n /** How fast they are sent. */\n readonly meter: Meter;\n /** Fires on abort() of the running file or the job, and when the job's signal fires. */\n readonly cancel: AbortController;\n /** The current sending pass: pause() aborts it, and so does a cancel. */\n pass: AbortController | null;\n /** Ends the wait of a paused file: resume() and a cancel call it. */\n wake: (() => void) | null;\n /**\n * Paused by the page going offline, so going online resumes it; the caller's pause() or resume() clears it\n * (M3-U28).\n */\n networkPaused: boolean;\n /** The part numbers the bucket stored (1 for a single PUT): a new pass sends only the others. */\n readonly landed: Set<number>;\n /** The current ticket's upload, which a retry with the same ticket continues; null without a ticket. */\n upload: Upload | null;\n /** How the file first settled, which `done` reports whatever a retry does later (M3-U35). */\n firstOutcome: FileOutcome<unknown> | null;\n /** The file's current run, from its /upload or retry until it settles. */\n run: Promise<void>;\n /** Tells the job something changed; `urgent` for a status change. */\n changed(urgent: boolean): void;\n}\n\nexport function createEntry(file: File, rank: number, changed: (urgent: boolean) => void): Entry {\n const entry: Entry = {\n id: String(rank),\n file,\n rank,\n status: \"queued\",\n result: null,\n error: null,\n progress: createProgress(),\n meter: createMeter(),\n cancel: new AbortController(),\n pass: null,\n wake: null,\n networkPaused: false,\n landed: new Set(),\n upload: null,\n firstOutcome: null,\n run: Promise.resolve(),\n changed,\n };\n // The pass's signal is the only one its requests hear (/complete excepted), so a cancel aborts the pass too, and wakes\n // a paused file to end it. One listener per file, whatever its runs, does what AbortSignal.any would, without raising\n // the browser floor to Safari 17.4.\n entry.cancel.signal.addEventListener(\"abort\", () => {\n entry.pass?.abort();\n entry.wake?.();\n });\n return entry;\n}\n\nexport function outcomeOf({ id, file, status, result, error }: Entry): FileOutcome<unknown> {\n const { name } = file;\n if (status === \"done\" && result) return { id, name, status, result };\n // Every settled entry without a result holds its error: settle() sets both.\n return { id, name, status: status === \"aborted\" ? \"aborted\" : \"failed\", error: error as CloudropError };\n}\n\n/** The file's status is final for now: the first time, its outcome is the one `done` reports. */\nexport function settled(entry: Entry): void {\n entry.firstOutcome ??= outcomeOf(entry);\n entry.changed(true);\n}\n\n/** Ends `entry` without success. `error` is final: callers set `file` on it when it is the file's own. */\nexport function settle(entry: Entry, status: \"failed\" | \"aborted\", error: CloudropError): void {\n entry.error = error;\n entry.status = status;\n settled(entry);\n}\n\n/** Holds a paused `entry` until resume() or a cancel wakes it; a file that is not paused goes on at once. */\nexport async function held(entry: Entry): Promise<void> {\n while (entry.status === \"paused\" && !entry.cancel.signal.aborted) {\n // Waking it again later does nothing.\n await new Promise<void>((resolve) => {\n entry.wake = resolve;\n });\n }\n}\n\n/**\n * Stops a queued or uploading file's PUTs; a completing or settled file ignores it (ruling M3-U4). `byNetwork` marks a\n * pause by the page going offline; the caller's pause of a file already paused makes the pause the caller's (M3-U28).\n */\nexport function pauseFile(entry: Entry, byNetwork = false): void {\n if (entry.status === \"paused\" && !byNetwork) entry.networkPaused = false;\n if (entry.status !== \"queued\" && entry.status !== \"uploading\") return;\n entry.networkPaused = byNetwork;\n entry.status = \"paused\";\n entry.changed(true);\n entry.pass?.abort();\n}\n\n/** Queues a paused file's parts that have not landed again. */\nexport function resumeFile(entry: Entry): void {\n if (entry.status !== \"paused\") return;\n entry.networkPaused = false;\n entry.status = \"queued\";\n entry.changed(true);\n entry.wake?.();\n}\n","// Whether a picked file is the one an unfinished upload started with (spec §3.3). A heuristic: an edit between the\n// edges, with the same size and timestamp, is not seen.\n\nconst EDGE = 64 * 1024;\n\n/**\n * Hex SHA-256 of the first 64 KiB then the last 64 KiB (the whole file up to 128 KiB). Rejects only when the browser\n * can no longer read the file. Persistence runs only in a secure context, where crypto.subtle exists (M3-U88).\n */\nexport async function fingerprintOf(file: File): Promise<string> {\n const edges = file.size <= 2 * EDGE ? file : new Blob([file.slice(0, EDGE), file.slice(-EDGE)]);\n const digest = await crypto.subtle.digest(\"SHA-256\", await edges.arrayBuffer());\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Whether `file` is the record's file: name, size, lastModified, type and fingerprint equal (spec §3.3). */\nexport async function isSameFile(\n record: { name: string; size: number; type: string; lastModified: number; fingerprint: string },\n file: File,\n): Promise<boolean> {\n try {\n return (\n file.name === record.name &&\n file.size === record.size &&\n file.type === record.type &&\n file.lastModified === record.lastModified &&\n (await fingerprintOf(file)) === record.fingerprint\n );\n } catch {\n // A browser refuses to read a picked file that changed on disk since: it is no longer the upload's file.\n return false;\n }\n}\n","// What a page keeps of a multipart upload while it holds the upload's ticket (resume spec §3.1, §3.2, §3.5): a record\n// in the browser's store, so that the upload can resume after a reload, and the upload's Web Lock, so that no other\n// holder sends it meanwhile. Both are taken when the ticket arrives, from start(), upload() or a retry's new ticket, and\n// both go when the page gives the ticket up (audit C2, I5), through letGo:\n// - the file ends done (runFile);\n// - its /abort is sent (drop): a cancel, abort() or the job's signal on a failed file, and the failure of a single PUT\n// in upload() or at pagehide; the lock is let go only once the /abort is answered, so no other tab completes what\n// it then deletes;\n// - a cancel, or abort() of a failed file, when a /complete may have finished it and no /abort is sent (end, abortFile);\n// - a retry's new ticket replaces it (requeue).\n// A failed file of start() keeps both, for retry(). A failed multipart file of upload(), and one of start() at pagehide,\n// keeps its record for a resume after a reload and lets the lock go, sending no /abort (giveUp, M4-F1); so does one of\n// upload() that a /complete may have finished: this page has no handle to send it again (ruling M3-U82).\n\nimport type { Ticket } from \"./endpoints.ts\";\nimport type { Entry } from \"./entry.ts\";\nimport { fingerprintOf } from \"./fingerprint.ts\";\nimport type { Job } from \"./job-run.ts\";\nimport { lockUpload } from \"./locks.ts\";\nimport { claim, newUpload, type Upload, type UploadContext } from \"./upload.ts\";\n\n/** `entry`'s upload under the ticket that just arrived; a persisted one is locked at once, and saved once locked. */\nexport function uploadOf({ context, args }: Job, entry: Entry, ticket: Ticket): Upload {\n const { records, namespace } = context;\n // A single PUT cannot resume, and with persistence off nothing could resume it: neither is saved nor locked. The\n // upload does not wait for the lock: no other holder can know an id /upload just made (ruling M3-U81).\n let unlock = () => {};\n if (ticket.kind === \"multipart\" && records.enabled) {\n const lock = lockUpload(ticket.id);\n const release = claim(context, ticket.id);\n unlock = () => {\n release();\n lock.release();\n };\n const { file } = entry;\n // Queued now, while the lock is asked for and then the file's edges are hashed: a letGo of a file that ends at once\n // is queued after it (M3-U80). Saved only under the lock (M3-U88): a record no lock guards could be resumed while\n // this page still holds the ticket, whose /abort would then delete the finished object. A refused lock, or a file\n // the browser can no longer read, rejects, and the store drops the save.\n records.save(\n lock.taken\n .then((taken) => (taken ? fingerprintOf(file) : Promise.reject()))\n .then((fingerprint) => ({\n id: ticket.id,\n namespace,\n route: args.route,\n // What /upload received: a structured clone would keep what JSON leaves out, and throw on a function (I12).\n metadata: args.metadata === undefined ? undefined : JSON.parse(JSON.stringify(args.metadata)),\n name: file.name,\n size: file.size,\n type: file.type,\n lastModified: file.lastModified,\n fingerprint,\n token: ticket.token,\n key: ticket.key,\n partSize: ticket.partSize,\n partCount: ticket.partCount,\n expiresAt: ticket.expiresAt,\n savedAt: Date.now(),\n })),\n );\n }\n return newUpload(ticket, entry, unlock);\n}\n\n/**\n * The page gives `upload`'s ticket up: its record is deleted at once and its lock let go, once `answered` settles when\n * given (an /abort in flight, which never rejects). Again, it changes nothing.\n */\nexport function letGo(context: UploadContext, upload: Upload, answered?: Promise<void>): void {\n if (upload.ticket.kind === \"multipart\") context.records.remove(upload.ticket.id);\n if (answered) void answered.then(upload.unlock);\n else upload.unlock();\n}\n","// One file of a job after /upload, from its ticket to its outcome: passes that send its bytes and /complete\n// (upload.ts), paused and resumed in between (entry.ts), then an ending without success (a cancel or a failure). A\n// cancel tells the server unless a /complete may have finished the file (decisions S14, S15, ruling S-18); a failure\n// of start() keeps the ticket and the parts for retry() (spec §4.7), and one of upload() gives the ticket up (M3-U29,\n// M4-F1).\n\nimport type { CloudropError } from \"../errors.ts\";\nimport { type Entry, held, settle, settled } from \"./entry.ts\";\nimport { aborted, NEEDS_NEW_TICKET, withFile } from \"./failures.ts\";\nimport { letGo } from \"./persist.ts\";\nimport { sendAndComplete, type Upload, type UploadContext } from \"./upload.ts\";\n\n/**\n * Sends the /abort that frees `upload`'s parts and deletes its own object, once, and gives its ticket up. The record\n * goes at once; the lock only once the server has answered: another tab that took it sooner could complete the upload,\n * and this /abort, with a live token, would then delete the finished object (M3-U73).\n */\nexport function drop(context: UploadContext, upload: Upload): Promise<void> {\n upload.dropped = true;\n const answered = context.endpoints.abort(upload.ticket.token).then(() => undefined);\n letGo(context, upload, answered);\n return answered;\n}\n\n/**\n * Gives a failed file's ticket up (M4-F1). A multipart ticket a reload can resume keeps its record and sends no\n * /abort, now or later: another tab may resume and complete the upload, and the bucket's lifecycle rule removes parts\n * never resumed. Any other ticket is dropped: a single PUT, one of a client that keeps no records, and one whose\n * failure the same ticket can never fix (a refusal, M3-U31), which a resume would only repeat.\n */\nexport function giveUp(context: UploadContext, upload: Upload): void {\n const { error } = upload.entry;\n const resumable = upload.ticket.kind === \"multipart\" && context.records.enabled && error?.retryable;\n if (!resumable || NEEDS_NEW_TICKET.has(error.code)) return void drop(context, upload);\n upload.dropped = true;\n upload.unlock();\n}\n\n/**\n * Cancels a file (ruling M3-U38). A running one ends aborted through its run, which tells the server. One still\n * waiting for its ticket has nothing to tell the server and ends aborted at once (M3-U11, M4-F2). A failed one ends\n * aborted at once and frees what it kept (M3-U32), unless a /complete may have finished it (keep-or-abort, M3-S14,\n * M3-H16).\n */\nexport function abortFile(context: UploadContext, entry: Entry): void {\n const { status, upload } = entry;\n if (status === \"done\" || status === \"aborted\") return;\n if (status !== \"failed\") {\n entry.cancel.abort();\n if (!upload) settle(entry, \"aborted\", withFile(aborted(), entry));\n return;\n }\n context.leftovers.release(entry);\n settle(entry, \"aborted\", withFile(aborted(), entry));\n if (!upload || upload.dropped) return;\n if (upload.mayBeComplete) letGo(context, upload);\n else void drop(context, upload);\n}\n\n/** Ends the file after `error`. A cancel is reported as one, whatever ended the pass. */\nasync function end(context: UploadContext, upload: Upload, error: CloudropError) {\n const { entry, mayBeComplete } = upload;\n const failed = !entry.cancel.signal.aborted;\n if (failed && context.keepFailed) {\n // Held before the status settles: a listener may retry the file at once, which lets it go again. A /complete\n // that may have finished the file is never undone by pagehide (M3-U33).\n if (!mayBeComplete) context.leftovers.hold(entry);\n return settle(entry, \"failed\", withFile(error, entry));\n }\n // The status settles first, so a page shows a cancel at once rather than when the server answers (ruling M3-U11).\n settle(entry, failed ? \"failed\" : \"aborted\", withFile(failed ? error : aborted(), entry));\n // A /complete that may have succeeded keeps the file rather than delete a recorded one (M3-H15, M3-H16). Otherwise\n // /abort frees the parts and deletes this upload's own object, which no lifecycle rule removes (S-18).\n if (failed) {\n // A failure of upload() keeps the record of a /complete in doubt for a resume, which only /complete can settle, and\n // lets the lock go: this page cannot send the file again (M3-U82). Any other is given up (M4-F1); an /abort that\n // sends finishes in the background: abort() never rejects, so nothing is left unhandled.\n if (mayBeComplete) upload.unlock();\n else giveUp(context, upload);\n return;\n }\n // A cancel ends the upload. Its /abort is waited for, and `done` with it, so the caller knows the server was told.\n if (mayBeComplete) letGo(context, upload);\n else await drop(context, upload);\n}\n\n/** What a resumed upload's probe answers when the upload is gone and was not completed (M3-U74). */\nconst GONE = new Set([\"UPLOAD_EXPIRED\", \"INVALID_TOKEN\", \"NO_SUCH_UPLOAD\"]);\n\n/**\n * Sends the file and completes it, one pass at a time: a pause ends the pass, a resume starts the next. `upload` is\n * kept across passes and same-ticket retries, so neither forgets a /complete that may have finished nor the parts that\n * landed. A file cancelled before this starts sends nothing but the /abort that tells the server. Resolves with the\n * probe's error, the file not settled, when a resumed upload turns out gone: the caller starts it over (M3-U74).\n */\nexport async function runFile(context: UploadContext, upload: Upload): Promise<CloudropError | undefined> {\n const { entry } = upload;\n const { cancel } = entry;\n while (!cancel.signal.aborted) {\n if (entry.status === \"paused\") {\n await held(entry);\n continue;\n }\n const pass = new AbortController();\n entry.pass = pass;\n const result = await sendAndComplete(context, upload, pass.signal);\n // A completed upload stays completed: /abort with a live token would delete it (ruling M2-X1).\n if (!result.error) {\n letGo(context, upload);\n entry.result = result.data;\n entry.status = \"done\";\n settled(entry);\n return;\n }\n const { code } = result.error;\n if (upload.probe && GONE.has(code) && !cancel.signal.aborted) return result.error;\n // Paused: the next pass starts after resume(). A failure that won the race with the pause ends the file.\n const paused = code === \"ABORTED\" && pass.signal.aborted && !cancel.signal.aborted;\n if (!paused) {\n await end(context, upload, result.error);\n return;\n }\n }\n await end(context, upload, aborted());\n}\n","// Asking /upload for tickets, then running each file on its share of the answer (spec §4.4). The job's own /upload and\n// a retry's of several files run on the job's signal; a one-file /upload (a re-ask after a refusal, a one-file\n// retry()'s new ticket, a resumed file's start over) runs on that file's own signals (M3-U92).\n\nimport { CloudropError, fail, type Result } from \"../errors.ts\";\nimport type { Ticket } from \"./endpoints.ts\";\nimport { type Entry, held, settle } from \"./entry.ts\";\nimport { aborted, unreadableAnswer, withFile } from \"./failures.ts\";\nimport type { Job } from \"./job-run.ts\";\nimport { uploadOf } from \"./persist.ts\";\nimport { MAX_ATTEMPTS, pause, retryAfterOf, retryDelay, withRetry } from \"./retry.ts\";\n\n/**\n * A new `/upload` idempotency key: 128 random bits as 32 hex digits. Not `crypto.randomUUID()`, which a page outside a\n * secure context (plain http on a LAN address) does not have, while uploads work there.\n */\nconst newRequestKey = (): string =>\n Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n/**\n * A file /upload refused at `attempt`. A retryable refusal asks again for this file alone, within the budget and after\n * the wait of any request's retry (M3-U92); the file stays queued meanwhile. A file cancelled meanwhile ends aborted\n * and sends nothing: it holds no ticket the server must be told about (M3-U51). Resolves once the file has settled.\n */\nasync function refused(job: Job, entry: Entry, refusal: CloudropError, attempt: number): Promise<void> {\n if (!refusal.retryable || attempt === MAX_ATTEMPTS) return settle(entry, \"failed\", withFile(refusal, entry));\n await launch(job, [entry], attempt + 1, retryDelay(attempt, retryAfterOf(refusal)));\n return entry.run;\n}\n\n/** One file's share of an /upload answer, given at `attempt`. `whole`: the /upload asked for every file of the job. */\nasync function runEntry(\n job: Job,\n entry: Entry,\n answer: Result<(Ticket | CloudropError)[]>,\n index: number,\n whole: boolean,\n attempt: number,\n): Promise<void> {\n // Cancelled meanwhile, it ended then (M4-F2): a ticket it was given gets its /abort and nothing else.\n if (entry.status === \"aborted\") {\n const late = answer.error ? undefined : answer.data[index];\n if (late && !(late instanceof CloudropError)) void job.context.endpoints.abort(late.token);\n return;\n }\n // The error is the job's when /upload asked for every file, and the file's own when a retry asked for some (M3-U3).\n if (answer.error) return settle(entry, \"failed\", whole ? answer.error : withFile(answer.error, entry));\n // readTickets answers one ticket per file; a missing one would otherwise leave the file queued for good.\n const ticket = answer.data[index] ?? unreadableAnswer(200);\n if (ticket instanceof CloudropError) return refused(job, entry, ticket, attempt);\n entry.upload = uploadOf(job, entry, ticket);\n await job.runUpload(entry.upload);\n}\n\n/**\n * Calls `ask` through the retry budget, from attempt `next()`, after waiting `waitMs` (a refusal's backoff), with\n * `entry`'s pause and cancel ending the wait and the backoff. A pause, offline included, holds the file, then asks at\n * once with the count kept (M3-U92). A cancel's ABORTED is returned as it is. The whole ask is watched in one bracket:\n * watching again would call online(), which resumes a file offline paused (M3-U48).\n */\nfunction askAlone<T>(\n job: Job,\n entry: Entry,\n ask: (attempt: number) => Promise<Result<T>>,\n next: () => number,\n waitMs: number,\n): Promise<Result<T>> {\n const { signal } = entry.cancel;\n return job.watch(async () => {\n for (let wait = waitMs; ; wait = 0) {\n if (entry.status === \"paused\") wait = 0;\n await held(entry);\n if (signal.aborted) return fail(aborted());\n // pauseFile and a cancel abort the pass, which here is the wait and the backoff.\n const pass = new AbortController();\n entry.pass = pass;\n if (wait > 0) await pause(wait, pass.signal);\n const answer = await withRetry(ask, pass.signal, next());\n // A pause ended the wait only when this pass fired, as in runFile: an answer may carry ABORTED itself.\n if (answer.error?.code !== \"ABORTED\" || !pass.signal.aborted || signal.aborted) return answer;\n }\n });\n}\n\n/**\n * Asks one /upload for tickets for `entries`, then runs every file at once (the pool decides who sends); each\n * `entry.run` settles with its file. Resolves with the /upload's refusal when it asked for every file of the job.\n * With `first`, the attempt of the budget it starts at, it asks for its one file alone, on that file's own signals\n * (M3-U92), after `waitMs`: a cancel stops the request and the waits, a pause ends a wait and holds the file, and\n * resume() asks at once with the attempt count kept. `first` above 1 is a re-ask after a refusal, so never the whole\n * job, whose /upload has answered.\n */\nexport async function launch(\n job: Job,\n entries: readonly Entry[],\n first?: number,\n waitMs = 0,\n): Promise<CloudropError | null> {\n const { context, args } = job;\n const files = entries.map((entry) => entry.file);\n const own = first === undefined ? undefined : entries[0];\n // job.abort() and the caller's signal cancel every file, so a file's own signal hears them too.\n const signal = own ? own.cancel.signal : job.signal;\n let attempt = (first ?? 1) - 1;\n // One key per ask, shared by its retries: with a store, a retry after a lost answer supersedes what that answer held.\n const key = newRequestKey();\n const ask = (at: number) => {\n attempt = at;\n return context.endpoints.start(args.route, files, args.metadata, key, signal);\n };\n const started = (own ? askAlone(job, own, ask, () => attempt + 1, waitMs) : withRetry(ask, signal)).then((answer) =>\n answer.error && signal.aborted ? fail(aborted()) : answer,\n );\n const whole = (first ?? 1) === 1 && entries.length === job.entries.length;\n entries.forEach((entry, index) => {\n entry.run = started.then((answer) => runEntry(job, entry, answer, index, whole, attempt)).finally(job.idle);\n });\n const { error } = await started;\n return whole ? error : null;\n}\n","// The page's events that reach a job: connectivity while a file runs (spec §4.6, rulings M3-U28, M3-U39 and M3-U48),\n// and pagehide while a failed file holds its ticket (spec §4.7, M3-U33).\n\nimport type { Entry } from \"./entry.ts\";\nimport type { Upload } from \"./upload.ts\";\n\n/**\n * Calls `offline` and `online` on the page's connectivity events until the returned function runs, and one of them at\n * once for where the page is now: an `online` that came while nobody listened must still resume what `offline` paused.\n * A no-op where the global has no addEventListener (Node); Deno and Workers have one and never fire these events, which\n * is harmless.\n */\nexport function watchConnectivity(offline: () => void, online: () => void): () => void {\n // Without listeners no `online` would ever resume what an early `offline` paused.\n if (typeof globalThis.addEventListener !== \"function\") return () => {};\n addEventListener(\"offline\", offline);\n addEventListener(\"online\", online);\n if (globalThis.navigator?.onLine === false) offline();\n else online();\n return () => {\n removeEventListener(\"offline\", offline);\n removeEventListener(\"online\", online);\n };\n}\n\n/** Gives failed files' tickets up when the page hides: one pagehide listener while any is held (M3-U33). */\nexport interface Leftovers {\n hold(entry: Entry): void;\n release(entry: Entry): void;\n}\n\n/** `entry`'s upload while its ticket lasts; after that the bucket's lifecycle rule removes it (spec §4.7, M3-U33). */\nfunction unexpired({ upload }: Entry) {\n return upload && Date.parse(upload.ticket.expiresAt) > Date.now() ? upload : null;\n}\n\n/**\n * On pagehide, calls `giveUp` (file-run.ts: the ticket marked dropped, so a retry after a back-forward cache restore\n * asks for a new one; a keepalive /abort unless a reload can resume it, M4-F1) for every held ticket that has not\n * expired. Expired tickets are let go on pagehide and on hold.\n */\nexport function createLeftovers(giveUp: (upload: Upload) => void): Leftovers {\n const held = new Set<Entry>();\n // The page adds the same listener once, and removing one it does not hold does nothing.\n const sync = () => {\n for (const entry of held) if (!unexpired(entry)) held.delete(entry);\n // No page hides where the global has no addEventListener (Node).\n if (typeof globalThis.addEventListener !== \"function\") return;\n if (held.size > 0) addEventListener(\"pagehide\", pagehide);\n else removeEventListener(\"pagehide\", pagehide);\n };\n function pagehide() {\n for (const entry of held) {\n const upload = unexpired(entry);\n if (upload) giveUp(upload);\n }\n held.clear();\n sync();\n }\n return {\n hold(entry) {\n held.add(entry);\n sync();\n },\n release(entry) {\n held.delete(entry);\n sync();\n },\n };\n}\n","// A job's runs after start(): one /upload for every file (launch.ts), each file then run on its own through the\n// client's pool, and one result with an outcome per file (spec §2.2, §4.4, §4.6). Files are independent: one failing\n// never stops another. A retry (retry-file.ts) runs files again through the same job.\n\nimport { fail } from \"../errors.ts\";\nimport type { Arguments } from \"./arguments.ts\";\nimport { type Entry, outcomeOf, pauseFile, resumeFile } from \"./entry.ts\";\nimport { abortFile, runFile } from \"./file-run.ts\";\nimport { launch } from \"./launch.ts\";\nimport { watchConnectivity } from \"./lifecycle.ts\";\nimport { letGo } from \"./persist.ts\";\nimport { createProgress } from \"./progress.ts\";\nimport type { FileOutcome, UploadResult } from \"./types.ts\";\nimport type { Upload, UploadContext } from \"./upload.ts\";\n\n/** What a job's runs and retries share. */\nexport interface Job {\n readonly context: UploadContext;\n readonly args: Arguments;\n readonly entries: readonly Entry[];\n /** Fires on abort() of the job and when the caller's signal fires: it stops an /upload in flight. */\n readonly signal: AbortSignal;\n /** Ends every file (ruling M3-U38). */\n abort(): void;\n /**\n * Runs `upload` until its file settles, with the page's connectivity watched meanwhile. A resumed upload that turns\n * out gone starts over within the run (M3-U74).\n */\n runUpload(upload: Upload): Promise<void>;\n /** Runs `run` with the page's connectivity watched meanwhile (M3-U49). */\n watch<T>(run: () => Promise<T>): Promise<T>;\n /** Hears the caller's signal from now on (a run starts), or stops once no file runs or holds its ticket (M3-U38). */\n listen(): void;\n idle(): void;\n}\n\nconst settledStatus = ({ status }: Entry) => status === \"done\" || status === \"failed\" || status === \"aborted\";\n\n/** Still sending, or failed and holding a ticket whose /abort the caller's signal would send. */\nconst busy = (entry: Entry) =>\n !settledStatus(entry) ||\n (entry.status === \"failed\" && !!entry.upload && !entry.upload.dropped && !entry.upload.mayBeComplete);\n\nexport function createJob(context: UploadContext, args: Arguments, entries: readonly Entry[]): Job {\n const controller = new AbortController();\n const { signal } = controller;\n const abort = () => controller.abort();\n // The caller's signal may outlive the job: the listener that holds it goes once nothing is left to cancel. A signal\n // adds the same listener once however often listen() runs, and removing one it does not hold does nothing.\n const idle = () => {\n if (!entries.some(busy)) args.signal.removeEventListener(\"abort\", abort);\n };\n signal.addEventListener(\"abort\", () => {\n for (const entry of entries) abortFile(context, entry);\n idle();\n });\n // The page's connectivity is watched from the first run's start to the last one's end. Offline pauses every file\n // that can pause; online resumes only those it paused (rulings M3-U28, M3-U39).\n let running = 0;\n let unwatch = () => {};\n const offline = () => {\n for (const entry of entries) pauseFile(entry, true);\n };\n const online = () => {\n for (const entry of entries) if (entry.networkPaused) resumeFile(entry);\n };\n const job: Job = {\n context,\n args,\n entries,\n signal,\n abort,\n runUpload: (upload) =>\n job.watch(() => runFile(context, upload).then((gone) => gone && startOver(job, upload.entry))),\n watch(run) {\n running += 1;\n if (running === 1) unwatch = watchConnectivity(offline, online);\n return run().finally(() => {\n running -= 1;\n if (running === 0) unwatch();\n });\n },\n listen() {\n args.signal.addEventListener(\"abort\", abort);\n if (args.signal.aborted) abort();\n },\n idle,\n };\n return job;\n}\n\n/**\n * `entry` forgets its ticket, without the /abort that file-run.ts's drop sends, and waits for a new one, which starts\n * from no parts and no bytes (M3-U36).\n */\nexport function forgetTicket(context: UploadContext, entry: Entry): void {\n // The new ticket's record replaces this one's, under the new id (resume spec §3.2). A ticket already given up let\n // go then: a record giveUp kept may be another tab's now (M4-F1).\n if (entry.upload && !entry.upload.dropped) letGo(context, entry.upload);\n entry.upload = null;\n entry.landed.clear();\n entry.progress = createProgress();\n}\n\n/**\n * A resumed upload whose probe found it gone asks /upload for a new ticket with the record's route and metadata, on the\n * file's own signals as any one-file /upload (M3-U92), and sends the whole file, without settling in between (M3-U74).\n * Resolves once the file has settled.\n */\nasync function startOver(job: Job, entry: Entry): Promise<void> {\n // No /abort for the old ticket, as for a retry's new ticket (M3-U55): the bucket's lifecycle rule frees its parts.\n forgetTicket(job.context, entry);\n entry.status = \"queued\";\n entry.changed(true);\n await launch(job, [entry], 1);\n await entry.run;\n}\n\n/**\n * Resolves with the outcomes of `entries` once every file has settled, also those a retry restarted meanwhile. They are\n * read in the step that sees every file settled: another retry may start a file again before the caller resumes.\n */\nexport async function allSettled(entries: readonly Entry[]): Promise<FileOutcome<unknown>[]> {\n while (!entries.every(settledStatus)) await Promise.all(entries.map((entry) => entry.run));\n return entries.map(outcomeOf);\n}\n\n/** The job's result over `files`: the first file, in the order passed, that did not end done (ruling M3-U3). */\nexport function resultOf(files: FileOutcome<unknown>[]): UploadResult<unknown> {\n return { data: { files }, error: files.find((outcome) => outcome.status !== \"done\")?.error ?? null };\n}\n\n/** The first run: `done` settles once every file first settled, with those outcomes, whatever a retry did (M3-U35). */\nexport function firstRun(job: Job): Promise<UploadResult<unknown>> {\n const { entries } = job;\n job.listen();\n const refused = launch(job, entries);\n const runs = entries.map((entry) => entry.run);\n return Promise.all([refused, ...runs]).then(([error]) =>\n // Every file has settled once its first run ended, which recorded its outcome.\n error ? fail(error) : resultOf(entries.map((entry) => entry.firstOutcome as FileOutcome<unknown>)),\n );\n}\n","// The snapshot a page renders of a job (spec §2.1, §4.2, §4.3): each file's bytes, progress, speed and time left, and\n// totals over the files that did not fail or abort.\n\nimport type { Entry } from \"./entry.ts\";\nimport type { FileSnapshot, FileStatus, JobSnapshot } from \"./types.ts\";\n\n/** `part` of `whole`; when the whole is 0 bytes, 1 once `finished` and 0 before. */\nconst fraction = (part: number, whole: number, finished: boolean) => (whole > 0 ? part / whole : finished ? 1 : 0);\n/** Seconds to send `left` bytes at `speed`; unknown while nothing is sent. */\nconst etaOf = (left: number, speed: number) => (speed > 0 ? left / speed : null);\n\nfunction fileSnapshot(entry: Entry, now: number): FileSnapshot<unknown> {\n const { id, file, status, result, error } = entry;\n const { name, size, type } = file;\n // A file is done only once every part was stored, and a stored part counts its whole size: done means bytes = size.\n const bytes = entry.progress.bytes;\n const speed = status === \"uploading\" ? entry.meter.speed(now) : 0;\n const progress = fraction(bytes, size, status === \"done\");\n return { id, name, size, type, status, bytes, progress, speed, eta: etaOf(size - bytes, speed), error, result };\n}\n\nconst sum = (files: readonly FileSnapshot<unknown>[], key: \"bytes\" | \"size\" | \"speed\") =>\n files.reduce((total, file) => total + file[key], 0);\n\nexport function snapshotOf(entries: readonly Entry[]): JobSnapshot<unknown> {\n const now = Date.now();\n const files = entries.map((entry) => fileSnapshot(entry, now));\n const counting = (status: FileStatus) => files.filter((file) => file.status === status).length;\n // A failed or aborted file sends no more: counting it would hold the job below 1 and its bytes in the ETA.\n const counted = files.filter((file) => file.status !== \"failed\" && file.status !== \"aborted\");\n const bytes = sum(counted, \"bytes\");\n const size = sum(counted, \"size\");\n const speed = sum(counted, \"speed\");\n const done = counting(\"done\");\n return {\n files,\n totals: {\n bytes,\n size,\n // A job with nothing left to count has delivered nothing: 0, not a finished 1.\n progress: fraction(bytes, size, done > 0 && done === counted.length),\n speed,\n eta: etaOf(size - bytes, speed),\n done,\n failed: counting(\"failed\"),\n aborted: counting(\"aborted\"),\n count: files.length,\n },\n };\n}\n","// retry() of a failed file (spec §4.7, rulings M3-U30, M3-U31, M3-U34, M3-U36, M3-U37): the same ticket when a new\n// attempt with it can succeed, so the parts that landed are not sent again; otherwise a new ticket from /upload, shared\n// by every file of one job.retry() that needs one.\n\nimport type { CloudropError } from \"../errors.ts\";\nimport type { Entry } from \"./entry.ts\";\nimport { NEEDS_NEW_TICKET } from \"./failures.ts\";\nimport { allSettled, forgetTicket, type Job } from \"./job-run.ts\";\nimport { launch } from \"./launch.ts\";\nimport type { FileOutcome } from \"./types.ts\";\n\n/**\n * Whether a retry of the failed `entry` asks /upload for a new ticket, decided when it is called (M3-U30): never when\n * a /complete may have finished the file, which only /complete with its ticket can tell; always without a ticket,\n * with one that expired or whose /abort was sent, or after a failure in M3-U31.\n */\nfunction needsTicket({ upload, error }: Entry): boolean {\n if (!upload) return true;\n if (upload.mayBeComplete) return false;\n return upload.dropped || Date.parse(upload.ticket.expiresAt) <= Date.now() || NEEDS_NEW_TICKET.has(error?.code);\n}\n\n/** Queues a failed file again without telling the page. A new ticket starts from no parts and no bytes (M3-U36); the\n * speed starts from 0 when the file sends again, as on every start. */\nfunction requeue(job: Job, entry: Entry, fresh: boolean): void {\n job.context.leftovers.release(entry);\n if (fresh) forgetTicket(job.context, entry);\n else if (entry.upload) {\n // The same ticket repairs from round 0 again (M3-U50), and sends again the parts its last /complete found missing.\n entry.upload.repairs = 0;\n if (entry.error?.code === \"PARTS_MISSING\") for (const part of entry.error.parts ?? []) entry.landed.delete(part);\n }\n entry.error = null;\n entry.status = \"queued\";\n}\n\n/** What a retry ended with: the outcome of every file it was given, and the refusal of an /upload for the whole job. */\nexport interface Retried {\n outcomes: FileOutcome<unknown>[];\n refused: CloudropError | null;\n}\n\n/**\n * Retries the failed files among `entries`: those that need a ticket share one /upload (M3-U34). Files that have not\n * settled are waited for, done and aborted ones left as they are (M3-U37). Resolves once every file of `entries` has\n * settled, with their outcomes and the /upload's refusal when it asked for every file of the job.\n */\nexport async function retryFiles(job: Job, entries: readonly Entry[]): Promise<Retried> {\n const failed = entries.filter((entry) => entry.status === \"failed\");\n const fresh = failed.filter(needsTicket);\n for (const entry of failed) requeue(job, entry, fresh.includes(entry));\n // One publish once every file is queued (M3-U59): a listener that retries then finds none failed and only waits. One\n // that pauses or cancels a file leaves it to its run below, which ends a cancelled one as job.abort() would.\n failed[0]?.changed(true);\n // After the requeue: a signal that fired meanwhile cancels the files as queued ones, which tells the server.\n if (failed.length > 0) job.listen();\n for (const entry of failed) {\n const { upload } = entry;\n if (upload) entry.run = job.runUpload(upload).finally(job.idle);\n }\n // One file's new ticket stops on that file's cancel and pause, as its re-asks do (M3-U92).\n const refused = fresh.length > 0 ? launch(job, fresh, fresh.length === 1 ? 1 : undefined) : null;\n const outcomes = await allSettled(entries);\n return { outcomes, refused: await refused };\n}\n","// The snapshot a page renders (spec §2.1): the same object until something changes, listeners at most every 100 ms\n// while bytes flow and at once on a status change, and a refresh every second while a file uploads (ruling M3-U7).\n\nconst THROTTLE_MS = 100;\nconst REFRESH_MS = 1000;\n\nexport interface Store<T> {\n get(): T;\n subscribe(listener: () => void): () => void;\n /** Something changed: `urgent` (a status) publishes now; bytes publish at most every 100 ms. */\n changed(urgent: boolean): void;\n}\n\nexport function createStore<T>(build: () => T, active: () => boolean): Store<T> {\n let snapshot = build();\n let lastMs = -Infinity;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let dueMs = Infinity;\n const listeners = new Set<() => void>();\n\n const schedule = (atMs: number) => {\n if (timer !== undefined && dueMs <= atMs) return;\n clearTimeout(timer);\n dueMs = atMs;\n timer = setTimeout(publish, Math.max(0, atMs - Date.now()));\n };\n function publish() {\n clearTimeout(timer);\n timer = undefined;\n dueMs = Infinity;\n snapshot = build();\n lastMs = Date.now();\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch (error) {\n // The upload and the other listeners go on; the page still sees the error as uncaught (ruling M3-U8).\n setTimeout(() => {\n throw error;\n });\n }\n }\n if (active()) schedule(lastMs + REFRESH_MS);\n }\n return {\n get: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n changed: (urgent) => (urgent ? publish() : schedule(lastMs + THROTTLE_MS)),\n };\n}\n","// start(): several files through one /upload, each file run on its own through the client's pool (job-run.ts), retried\n// on request (retry-file.ts), and the snapshot a page renders meanwhile (job-snapshot.ts). The handles pause, resume,\n// cancel and retry one file or all of them.\n\nimport { fail, type Result } from \"../errors.ts\";\nimport { type Arguments, readArguments } from \"./arguments.ts\";\nimport { createEntry, type Entry, pauseFile, resumeFile } from \"./entry.ts\";\nimport { abortFile } from \"./file-run.ts\";\nimport { createJob, firstRun, type Job, resultOf } from \"./job-run.ts\";\nimport { snapshotOf } from \"./job-snapshot.ts\";\nimport { type Retried, retryFiles } from \"./retry-file.ts\";\nimport { createStore } from \"./store.ts\";\nimport type { FileHandle, FileOutcome, UploadJob, UploadResult } from \"./types.ts\";\nimport type { UploadContext } from \"./upload.ts\";\n\n/** Retries the failed files among `entries` (retryFiles, unless the job retries its own way). */\ntype Retry = (job: Job, entries: readonly Entry[]) => Promise<Retried>;\n\nfunction handleOf(job: Job, entry: Entry, retry: Retry): FileHandle {\n return {\n id: entry.id,\n name: entry.file.name,\n pause: () => pauseFile(entry),\n resume: () => resumeFile(entry),\n abort: () => {\n abortFile(job.context, entry);\n job.idle();\n },\n retry: async () => (await retry(job, [entry])).outcomes[0] as FileOutcome<unknown>,\n };\n}\n\nexport function startJob(context: UploadContext, route: unknown, files: unknown, options: unknown): UploadJob<unknown> {\n return createUploadJob(context, readArguments(route, files, options), firstRun);\n}\n\n/**\n * A job over the files of `args` that `run` starts and `retry` retries, as start() and resume() return it. A job\n * refused for its arguments has no files, and a snapshot that says so; its `done` and `retry()` answer with the refusal\n * (ruling M3-U37).\n */\nexport function createUploadJob(\n context: UploadContext,\n args: Result<Arguments>,\n run: (job: Job) => Promise<UploadResult<unknown>>,\n retry: Retry = retryFiles,\n): UploadJob<unknown> {\n // `changed` is only called once the job runs, after the store below exists.\n const entries = (args.error ? [] : args.data.files).map((file) =>\n createEntry(file, context.nextRank(), (urgent) => store.changed(urgent)),\n );\n const store = createStore(\n () => snapshotOf(entries),\n () => entries.some((entry) => entry.status === \"uploading\"),\n );\n const job = args.error ? null : createJob(context, args.data, entries);\n const done = args.error ? Promise.resolve(args) : run(job as Job);\n return {\n files: job ? entries.map((entry) => handleOf(job, entry, retry)) : [],\n done,\n abort: () => job?.abort(),\n pause: () => {\n for (const entry of entries) pauseFile(entry);\n },\n resume: () => entries.forEach(resumeFile),\n // Every failed file, resolving with every file's current outcome once all have settled.\n retry: async () => {\n if (!job) return done;\n const { outcomes, refused } = await retry(job, job.entries);\n return refused ? fail(refused) : resultOf(outcomes);\n },\n // Taken from the store as they are: neither needs `this`.\n subscribe: store.subscribe,\n getSnapshot: store.get,\n };\n}\n","// The connection slots one client shares between all its uploads (spec §4.4). A slot is held by one bucket PUT;\n// calls to the upload server take none. An automatic pool sizes itself from the bytes the bucket accepts: it weighs a\n// window of at least 2 s whenever it is used, never on a timer, so an idle client holds none (ruling M3-U23).\n\n/** Gives the slot back. Calling it more than once frees one slot. */\nexport type Release = () => void;\n\nexport interface Pool {\n /** Waits for a free slot, lower rank first (compared element by element, ties in arrival order); null when the\n * signal fires first. Calling the release more than once frees one slot. */\n acquire(rank: readonly number[], signal: AbortSignal): Promise<Release | null>;\n /** Bytes the bucket accepted; an automatic pool grows on them. */\n sent(bytes: number): void;\n /** A network error, a stall or a 429/503: an automatic pool halves (at least 1) and does not grow in the next\n * window (rulings M3-U24, M3-U25). */\n slowDown(): void;\n}\n\ninterface Waiter {\n rank: readonly number[];\n grant(release: Release): void;\n}\n\n/** Measured on R2 on 2026-11-16: 4 connections sent 60 MiB/s and 16 sent 71 MiB/s (spec §4.4). */\nconst AUTO_START = 4;\nconst AUTO_MAX = 8;\nconst WINDOW_MS = 2000;\n/** A longer window means PUTs held their slots without sending: it says nothing about speed and is not compared. */\nconst LONGEST_WINDOW_MS = 4000;\n/** The rise in bytes per millisecond over the previous window that adds a slot. */\nconst RISE = 1.1;\n\n/** Whether rank `a` goes before rank `b`: the first element that differs decides; equal ranks keep arrival order. */\nconst before = (a: readonly number[], b: readonly number[]): boolean => {\n for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return (a[i] ?? 0) < (b[i] ?? 0);\n return false;\n};\n\nexport function createPool(size: number | \"auto\", now: () => number = () => Date.now()): Pool {\n const auto = size === \"auto\";\n let slots = auto ? AUTO_START : size;\n let inUse = 0;\n const waiting: Waiter[] = [];\n // The window being measured; the first acquire starts the first one. `lastRate` is the previous window's bytes per\n // millisecond, 0 when there is none to compare with.\n let windowStart = 0;\n let windowBytes = 0;\n let lastRate = 0;\n // Set by slowDown until a window closes (ruling M3-U24). Restarting the window after idleness keeps it: the PUTs of\n // one outage often all give their slots back before their retries ask again.\n let hold = false;\n\n const restart = (rate: number) => {\n lastRate = rate;\n windowStart = now();\n windowBytes = 0;\n };\n\n /** Closes a window that is due, one slot more when work waits and bytes per ms rose; then fills the free slots. */\n const update = () => {\n const elapsed = now() - windowStart;\n if (auto && elapsed >= WINDOW_MS) {\n const rate = elapsed > LONGEST_WINDOW_MS ? 0 : windowBytes / elapsed;\n // `lastRate > 0` also keeps a pool that sends nothing from reading 0 after 0 as a rise.\n if (!hold && waiting.length > 0 && lastRate > 0 && rate >= lastRate * RISE && slots < AUTO_MAX) slots++;\n restart(rate);\n hold = false;\n }\n while (inUse < slots) {\n const next = waiting.shift();\n if (!next) return;\n inUse++;\n next.grant(releaser());\n }\n };\n\n const releaser = (): Release => {\n let used = false;\n return () => {\n if (used) return;\n used = true;\n inUse--;\n update();\n };\n };\n\n return {\n acquire(rank, signal) {\n if (signal.aborted) return Promise.resolve(null);\n // A window that began while nothing was sending would read as slow, and the next one as a rise. Nobody waits\n // when no slot is in use: every release grants the waiters it can.\n if (inUse === 0) restart(0);\n // update() grants the waiters first, so a free slot left after it means nobody waits: no overtaking.\n update();\n if (inUse < slots) {\n inUse++;\n return Promise.resolve(releaser());\n }\n return new Promise((resolve) => {\n const drop = () => {\n waiting.splice(waiting.indexOf(entry), 1);\n resolve(null);\n };\n const entry: Waiter = {\n rank,\n grant: (release) => {\n signal.removeEventListener(\"abort\", drop);\n resolve(release);\n },\n };\n const at = waiting.findIndex((other) => before(rank, other.rank));\n waiting.splice(at === -1 ? waiting.length : at, 0, entry);\n signal.addEventListener(\"abort\", drop, { once: true });\n });\n },\n sent(bytes) {\n // Weighed before these bytes count: they belong to the window that starts now if one closed.\n update();\n windowBytes += bytes;\n },\n slowDown() {\n if (!auto || hold) return;\n slots = Math.max(1, Math.floor(slots / 2));\n restart(lastRate);\n hold = true;\n },\n };\n}\n","// After a reload (resume spec §2, §3.3–§3.7): the unfinished multipart uploads this browser keeps, resuming one with\n// the file the user picked again, and forgetting them at sign-out. A resumed file asks /complete first which parts the\n// bucket lacks, so it sends only those, or nothing when the upload already finished.\n\nimport { CloudropError, fail, ok, type Result } from \"../errors.ts\";\nimport { invalidInput, isPlainObject } from \"../input.ts\";\nimport { readArguments } from \"./arguments.ts\";\nimport type { Ticket } from \"./endpoints.ts\";\nimport { type Entry, settle } from \"./entry.ts\";\nimport { notResumable, notSameFile, uploadInUse } from \"./failures.ts\";\nimport { isSameFile } from \"./fingerprint.ts\";\nimport { createUploadJob } from \"./job.ts\";\nimport { allSettled, type Job, resultOf } from \"./job-run.ts\";\nimport { lockUpload } from \"./locks.ts\";\nimport type { UploadRecord } from \"./records.ts\";\nimport { type Retried, retryFiles } from \"./retry-file.ts\";\nimport type { FileOutcome, ResumableUpload, UploadJob } from \"./types.ts\";\nimport { claim, newUpload, type UploadContext } from \"./upload.ts\";\n\n/** The namespace's unfinished uploads, newest first, for `route` or every route, without a token, key or metadata. */\nexport async function resumable(context: UploadContext, route?: string): Promise<Result<ResumableUpload[]>> {\n const listed = await context.records.list(context.namespace);\n if (listed.error) return listed;\n // An upload this client holds is continued through its own job, and resume() would refuse it (M4-F22).\n const claimed = new Set(Array.from(context.claims, ({ id }) => id));\n return ok(\n listed.data\n .filter((record) => (route === undefined || record.route === route) && !claimed.has(record.id))\n // Exactly these fields (M3-U77).\n .map(({ id, route, name, size, type, lastModified, expiresAt }) => ({\n id,\n route,\n name,\n size,\n type,\n lastModified,\n expiresAt,\n })),\n );\n}\n\n/** forget() deletes the client's namespace, forget({ all: true }) every record of this browser (M3-U78). */\nexport async function forget(context: UploadContext, options: unknown): Promise<Result<{ forgotten: number }>> {\n const all = options !== undefined;\n // Exactly { all: true }: forget(userId) would otherwise look as if it forgot that user.\n if (all && !(isPlainObject(options) && options.all === true && Object.keys(options).length === 1)) {\n return fail(\n invalidInput(\n \"Call forget() for this client's unfinished uploads, or forget({ all: true }) for every one in this browser.\",\n ),\n );\n }\n const cleared = await context.records.clear(all ? null : context.namespace);\n return cleared.error ? cleared : ok({ forgotten: cleared.data });\n}\n\n/** The record of upload `id` with its lock taken, or why it cannot be resumed, checked in M3-U76's order. */\nasync function check(\n context: UploadContext,\n id: string,\n file: File,\n): Promise<CloudropError | { record: UploadRecord; unlock: () => void }> {\n // Claimed from the call, before the first await, so resumable() no longer lists it. A refusal releases this claim\n // only, as the upload's unlock does; another holder's claim, such as a running file's, stays (M4-F22).\n const release = claim(context, id);\n const refuse = (refusal: CloudropError) => {\n release();\n return refusal;\n };\n const { data, error } = await context.records.list(context.namespace);\n // A store that cannot be read says so; a record that is gone, expired or another namespace's cannot be resumed.\n const record = data?.find((saved) => saved.id === id);\n if (!record) return refuse(error ?? notResumable());\n if (!(await isSameFile(record, file))) return refuse(notSameFile());\n const lock = lockUpload(id);\n const taken = await lock.taken;\n if (taken) {\n const unlock = () => {\n release();\n lock.release();\n };\n return { record, unlock };\n }\n // Where the browser refuses Web Locks, nothing can be resumed (M3-U88).\n return refuse(taken === false ? uploadInUse() : notResumable());\n}\n\n/**\n * Checks the record, the file and the lock, then runs the upload rebuilt from the record, which starts at /complete\n * with every part counted as landed (resume spec §3.4); `passed` hears that the checks passed. A failed check, or a\n * cancel meanwhile, ends the file before any request (audit I7). Resolves once the file has settled, with that\n * refusal, or null once the upload ran.\n */\nasync function resumeRun(job: Job, id: string, passed: () => void): Promise<CloudropError | null> {\n const { context, args } = job;\n const [entry] = job.entries as [Entry];\n job.listen();\n const checked = await check(context, id, entry.file);\n // Cancelled while checking, it ended then (M4-F2): nothing was sent, and the record stays for a later resume.\n if (entry.cancel.signal.aborted) {\n if (!(checked instanceof CloudropError)) checked.unlock();\n job.idle();\n return entry.error;\n }\n if (checked instanceof CloudropError) {\n settle(entry, \"failed\", checked);\n job.idle();\n return checked;\n }\n const { record, unlock } = checked;\n passed();\n // From the record: a start over asks /upload with the route and metadata the upload began with (M3-U74).\n args.route = record.route;\n args.metadata = record.metadata;\n // The record holds every field of the ticket but its URLs: every part is signed through /sign when needed. Its\n // expiry is the record's, verbatim, which a retry reads (audit M14).\n const ticket: Ticket = { ...record, kind: \"multipart\", parts: [] };\n for (let part = 1; part <= record.partCount; part++) entry.landed.add(part);\n const upload = newUpload(ticket, entry, unlock, true);\n entry.upload = upload;\n // Settled once this run ends, a start over included.\n await job.runUpload(upload).finally(job.idle);\n return null;\n}\n\n/** retry() of a file whose checks refused: queued again, it is checked again, then runs when they pass (M3-U90). */\nasync function checkAgain(job: Job, run: (job: Job) => Promise<CloudropError | null>): Promise<Retried> {\n const [entry] = job.entries as [Entry];\n entry.error = null;\n entry.status = \"queued\";\n // The checks are the file's run before the page hears of it: a listener that retries waits for them.\n const refused = run(job);\n entry.changed(true);\n return { refused: await refused, outcomes: await allSettled(job.entries) };\n}\n\n/** resume(upload, file, options?): a job of one file, its route and metadata from the record (M3-U76). */\nexport function resumeJob(\n context: UploadContext,\n upload: unknown,\n file: unknown,\n options: unknown,\n): UploadJob<unknown> {\n const id = (upload as { id?: unknown } | null | undefined)?.id;\n // The options as start() reads them. The route and the metadata come from the record once it is read.\n const args =\n typeof id === \"string\" && file instanceof File\n ? readArguments(\"resume\", file, options)\n : fail(invalidInput(\"Pass resume() an upload from resumable() and the File the user picked again.\"));\n // Until a check passes the job has no route or metadata to ask /upload with, so a retry of the refused file checks\n // again; once one passed, a retry is any job's (M3-U90).\n let checksPassed = false;\n const run = (job: Job) => {\n const resumed = resumeRun(job, id as string, () => {\n checksPassed = true;\n });\n // The file's run is the whole of it, checks to settling: a retry() meanwhile waits for all of it (M3-U90, M4-F5).\n // A start over hands it to its /upload's run, which this one awaits.\n (job.entries[0] as Entry).run = resumed.then(() => {});\n return resumed;\n };\n // The run starts only when the arguments passed, the id included.\n return createUploadJob(\n context,\n args,\n async (job) => {\n const refused = await run(job);\n // Its first outcome, whatever a retry did since (M3-U35).\n return refused ? fail(refused) : resultOf([(job.entries[0] as Entry).firstOutcome as FileOutcome<unknown>]);\n },\n (job, entries) =>\n checksPassed || job.entries[0]?.status !== \"failed\" ? retryFiles(job, entries) : checkAgain(job, run),\n );\n}\n","// What the bucket answered to a presigned PUT, and what the client does about it (decision S10).\n\nimport type { CloudropError } from \"../errors.ts\";\nimport type { SignedRequest } from \"../protocol/types.ts\";\nimport type { ClientFetch } from \"./endpoints.ts\";\nimport {\n aborted,\n bucketUnreachable,\n linkRefused,\n signatureMismatch,\n storageBusy,\n storageDown,\n uploadRejected,\n} from \"./failures.ts\";\nimport { parseRetryAfter } from \"./retry.ts\";\n\n/**\n * stored: the object or part is in the bucket. opaque: no answer could be read; renew the URL once, wait, retry.\n * expired: renew the URL once and retry at once. retry: wait at least `retryAfterMs`, then retry. rejected and\n * aborted: stop. `error` is what the caller returns once it stops trying.\n */\nexport type BucketOutcome =\n | { kind: \"stored\" }\n | { kind: \"opaque\" | \"expired\" | \"retry\"; error: CloudropError; retryAfterMs: number }\n | { kind: \"rejected\" | \"aborted\"; error: CloudropError };\n\n/** The S3 error code in a storage answer's XML body. */\nconst STORAGE_CODE = /<Code>([A-Za-z]{1,64})<\\/Code>/;\n\n/**\n * A storage answer that is not a success, from its status, body and Retry-After header, as the server's driver\n * classifies: by status; the body's S3 code only tells a bad signature from an expired URL.\n */\nexport function classifyAnswer(status: number, body: string, retryAfter: string | null): BucketOutcome {\n const storageCode = STORAGE_CODE.exec(body)?.[1];\n const retryAfterMs = parseRetryAfter(retryAfter);\n if (status === 403) {\n // R2 and Wrangler say ExpiredRequest, RustFS says AccessDenied: every other 403 is worth one renewal.\n return storageCode === \"SignatureDoesNotMatch\"\n ? { kind: \"rejected\", error: signatureMismatch() }\n : { kind: \"expired\", error: linkRefused(), retryAfterMs };\n }\n // R2 throttles with 429 and the S3 code ServiceUnavailable (spike Q9), so the status decides.\n if (status === 429 || status === 503) return { kind: \"retry\", error: storageBusy(), retryAfterMs };\n // 501 Not Implemented: the storage service lacks the feature, so a retry can never succeed.\n if (status === 408 || (status >= 500 && status !== 501)) return { kind: \"retry\", error: storageDown(), retryAfterMs };\n return { kind: \"rejected\", error: uploadRejected(status) };\n}\n\n/** A PUT that got no readable answer: cancelled by the caller, or lost to the network or a refusal without CORS. */\nexport function unreachable(signal: AbortSignal): BucketOutcome {\n return signal.aborted\n ? { kind: \"aborted\", error: aborted() }\n : { kind: \"opaque\", error: bucketUnreachable(), retryAfterMs: 0 };\n}\n\n/** Sends one presigned PUT with exactly the signed headers. Never rejects. */\nexport async function putObject(\n fetch: ClientFetch,\n target: SignedRequest,\n body: Blob,\n signal: AbortSignal,\n): Promise<BucketOutcome> {\n let response: Response;\n try {\n // No cookies: the URL is the credential, and a credentialed request needs CORS rules the bucket does not send.\n response = await fetch(target.url, { method: \"PUT\", headers: target.headers, body, credentials: \"omit\", signal });\n } catch {\n // Not only the network: R2 sends a refused URL (expired, bad signature) without CORS headers, which a browser shows\n // as a throw (r2-spike-findings.md, \"Browser refusals and checksums, 2026-11-16\").\n return unreachable(signal);\n }\n // 412: a retried create-only PUT whose first attempt already stored the object (spec §5.4).\n if (response.ok || response.status === 412) {\n // Frees the connection; a body that already failed changes nothing.\n await response.body?.cancel().catch(() => undefined);\n return { kind: \"stored\" };\n }\n const text = await response.text().catch(() => \"\");\n return classifyAnswer(response.status, text, response.headers.get(\"retry-after\"));\n}\n","// One presigned PUT to the bucket. In a browser it goes through XMLHttpRequest, the one web API that reports upload\n// progress; with a fetch option, or where there is no XMLHttpRequest, through fetch, which reports a part's bytes only\n// when it is stored (spec §4.1, ruling M3-U6).\n\nimport type { SignedRequest } from \"../protocol/types.ts\";\nimport { type BucketOutcome, classifyAnswer, putObject, unreachable } from \"./bucket.ts\";\nimport type { ClientFetch } from \"./endpoints.ts\";\n\nexport type PutObject = (\n target: SignedRequest,\n body: Blob,\n signal: AbortSignal,\n /** The bytes of `body` sent so far by this attempt; with fetch, called once with body.size when it is stored. */\n onBytes: (sent: number) => void,\n) => Promise<BucketOutcome>;\n\n// A stall is the network-error outcome (ruling M3-U27, spec §4.6): the PUT is given up, costs one attempt and is sent\n// again. An answer that comes more than 30 s after the body was sent, or an XHR the browser queues behind its per-host\n// connection limit, counts as a stall too (ruling M3-U47).\n/** How long an XHR may go without a progress event; with fetch, the time a PUT gets on top of its bytes. */\nconst STALL_MS = 30_000;\n/** 100 KiB/s: the slowest upload a fetch PUT, which reports no progress, is given time for. */\nconst SLOWEST_BYTES_PER_MS = 102.4;\n\nconst putWithXhr: PutObject = (target, body, signal, onBytes) =>\n new Promise((resolve) => {\n if (signal.aborted) return resolve(unreachable(signal));\n // Read on every PUT, so a page that wraps XMLHttpRequest after the client was created is seen (ruling M3-U6).\n const xhr = new globalThis.XMLHttpRequest();\n const cancel = () => xhr.abort();\n let stall: ReturnType<typeof setTimeout> | undefined;\n // An abort settles through onabort below: opaque while the caller's signal has not fired.\n const watch = () => {\n clearTimeout(stall);\n stall = setTimeout(cancel, STALL_MS);\n };\n const settle = (outcome: BucketOutcome) => {\n clearTimeout(stall);\n signal.removeEventListener(\"abort\", cancel);\n resolve(outcome);\n };\n xhr.upload.onprogress = (event) => {\n watch();\n onBytes(event.loaded);\n };\n xhr.onload = () => {\n // 412: a retried create-only PUT whose first attempt already stored the object (spec §5.4).\n if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 412) {\n onBytes(body.size);\n return settle({ kind: \"stored\" });\n }\n if (xhr.status === 0) return settle(unreachable(signal));\n settle(classifyAnswer(xhr.status, xhr.responseText, xhr.getResponseHeader(\"retry-after\")));\n };\n // A network failure and a refusal without CORS headers look the same here, as with fetch (decision S10).\n const lost = () => settle(unreachable(signal));\n xhr.onerror = lost;\n xhr.ontimeout = lost;\n xhr.onabort = lost;\n try {\n xhr.open(\"PUT\", target.url);\n for (const [name, value] of Object.entries(target.headers)) xhr.setRequestHeader(name, value);\n // No cookies: XMLHttpRequest sends none cross-origin unless withCredentials is set, and it stays unset.\n watch();\n xhr.send(body);\n } catch {\n // A URL or header the browser refuses throws here, as fetch throws a TypeError for it: the same outcome.\n return settle(unreachable(signal));\n }\n signal.addEventListener(\"abort\", cancel, { once: true });\n });\n\n/** XMLHttpRequest when there is one and no fetch option was passed; otherwise `send` (ruling M3-U6). */\nexport function createPut(fetchOption: ClientFetch | undefined, send: ClientFetch): PutObject {\n if (fetchOption === undefined && typeof globalThis.XMLHttpRequest === \"function\") return putWithXhr;\n return async (target, body, signal, onBytes) => {\n // Without AbortSignal.any (ruling M3-U19): one controller that the timeout and the caller's signal both abort.\n const controller = new AbortController();\n const stop = () => controller.abort();\n const timeout = setTimeout(stop, STALL_MS + body.size / SLOWEST_BYTES_PER_MS);\n signal.addEventListener(\"abort\", stop, { once: true });\n if (signal.aborted) stop();\n try {\n const outcome = await putObject(send, target, body, controller.signal);\n if (outcome.kind === \"stored\") onBytes(body.size);\n // Aborted by the timeout rather than the caller: opaque, as a stalled XHR is.\n return outcome.kind === \"aborted\" ? unreachable(signal) : outcome;\n } finally {\n clearTimeout(timeout);\n signal.removeEventListener(\"abort\", stop);\n }\n };\n}\n","// The cloudrop/client entry: createCloudropClient and the types a browser app annotates with (decision S4).\n\nimport { isList } from \"./client/arguments.ts\";\nimport { discard } from \"./client/discard.ts\";\nimport { type ClientFetch, createEndpoints } from \"./client/endpoints.ts\";\nimport { giveUp } from \"./client/file-run.ts\";\nimport { startJob } from \"./client/job.ts\";\nimport { createLeftovers } from \"./client/lifecycle.ts\";\nimport { createPool } from \"./client/pool.ts\";\nimport { createRecords } from \"./client/records.ts\";\nimport { forget, resumable, resumeJob } from \"./client/resume.ts\";\nimport { createPut } from \"./client/transport.ts\";\nimport type { FileOutcome, ResumableUpload, UploadJob, UploadResult } from \"./client/types.ts\";\nimport type { UploadContext } from \"./client/upload.ts\";\nimport { configError, fail, ok, type Result } from \"./errors.ts\";\nimport type { CompleteResponse, InferableCloudrop, RouteMetadata, RouteName, RouteResult } from \"./protocol/types.ts\";\n\nexport type {\n FileHandle,\n FileOutcome,\n FileSnapshot,\n FileStatus,\n JobSnapshot,\n ResumableUpload,\n UploadJob,\n UploadResult,\n} from \"./client/types.ts\";\nexport { CloudropError, type CloudropErrorCode, type Result } from \"./errors.ts\";\n// The wire types of the four endpoints, and the route inference types a client user annotates with (InferableCloudrop,\n// RouteMetadata, RouteName, RouteResult; S4, ruling M3-H13), which the root entry exports too.\nexport type {\n AbortRequest,\n AbortResponse,\n CompleteRequest,\n CompleteResponse,\n Endpoint,\n ErrorBody,\n ErrorResponse,\n FileDescriptor,\n FileTicket,\n InferableCloudrop,\n MultipartTicket,\n RejectedFile,\n RouteMetadata,\n RouteName,\n RouteResult,\n SignedPart,\n SignedRequest,\n SignRequest,\n SignResponse,\n SingleTicket,\n UploadedFile,\n UploadRequest,\n UploadResponse,\n} from \"./protocol/types.ts\";\n\nexport interface ClientOptions {\n /** Where the server's handler is mounted: a path on this page's origin or an absolute URL. Default \"/api/cloudrop\". */\n basePath?: string;\n /** Replaces the global fetch, for tests and runtimes that bring their own. */\n fetch?: ClientFetch;\n /**\n * How many bucket PUTs this client sends at once, across all its uploads: 1 to 16, or \"auto\" (the default), which\n * starts at 4, adds one while the bytes sent keep rising, up to 8, and halves on a network error or a busy bucket.\n */\n concurrency?: number | \"auto\";\n /** Which PUTs go first when they wait for a connection: \"added\" (the default) or \"smallest-first\" by file size. */\n order?: \"added\" | \"smallest-first\";\n /**\n * Keeps each unfinished multipart upload in the browser's IndexedDB, with its upload token, until the file ends, so\n * that it can resume after a reload. Default true; false keeps nothing on disk.\n */\n persist?: boolean;\n /**\n * Keeps one signed-in user's unfinished uploads apart from another's in the same browser: pass the user's id. At most\n * 256 characters; default \"\".\n */\n namespace?: string;\n}\n\nexport interface UploadOptions<TMetadata = unknown> {\n /** Validated by the route's schema on the server. */\n metadata?: TMetadata;\n /** Cancels the upload: requests stop, the server is told, and the result is ABORTED. */\n signal?: AbortSignal;\n}\n\n/** The options argument is required when the route's metadata is. */\nexport type UploadArguments<TMetadata> = undefined extends TMetadata\n ? [options?: UploadOptions<TMetadata>]\n : [options: UploadOptions<TMetadata> & { metadata: TMetadata }];\n\nexport interface CloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop> {\n /** Sends one file or several through one /upload; each file then runs on its own through the client's pool. */\n start<TName extends RouteName<TCloudrop>>(\n route: TName,\n files: File | ArrayLike<File>,\n ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>\n ): UploadJob<RouteResult<TCloudrop, TName>>;\n // The list overload comes first: ReturnType and Parameters read the last one, the single file of earlier versions.\n /** Uploads several files, such as input.files, and resolves with an outcome per file once all have settled. */\n upload<TName extends RouteName<TCloudrop>>(\n route: TName,\n files: ArrayLike<File>,\n ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>\n ): Promise<UploadResult<RouteResult<TCloudrop, TName>>>;\n /** Uploads one file and resolves with the route's result or the error. */\n upload<TName extends RouteName<TCloudrop>>(\n route: TName,\n file: File,\n ...options: UploadArguments<RouteMetadata<TCloudrop, TName>>\n ): Promise<Result<CompleteResponse<RouteResult<TCloudrop, TName>>>>;\n /** The unfinished uploads this browser keeps for the client's namespace, newest first: of `route`, or of all. */\n resumable<TName extends RouteName<TCloudrop> = RouteName<TCloudrop>>(\n route?: TName,\n ): Promise<Result<ResumableUpload<TName>[]>>;\n /**\n * Continues an unfinished upload with the file the user picked again: the server is asked first which parts the\n * bucket lacks, and only those are sent. The route and the metadata are the upload's own.\n */\n resume<TName extends RouteName<TCloudrop>>(\n upload: ResumableUpload<TName>,\n file: File,\n options?: { signal?: AbortSignal },\n ): UploadJob<RouteResult<TCloudrop, TName>>;\n /**\n * Drops one unfinished upload from resumable() without its file: the server is told to abort it, and its record is\n * deleted. `aborted` is true once the server accepted the /abort, which keeps a file whose /complete finished; false\n * when the token could no longer abort anything (the bucket's lifecycle rule cleans up).\n */\n discard(upload: ResumableUpload<RouteName<TCloudrop>>): Promise<Result<{ aborted: boolean }>>;\n /** Deletes the namespace's unfinished uploads, which sign-out should do, or every one in this browser with `all`. */\n forget(options?: { all: true }): Promise<Result<{ forgotten: number }>>;\n}\n\n/** A one-file job's result as that file's Result (ruling M3-U5). */\nfunction oneFile(result: UploadResult<unknown>): Result<CompleteResponse<unknown>> {\n if (result.error) return fail(result.error);\n // No error: the job's one file ended done.\n const [outcome] = result.data.files as [FileOutcome<unknown> & { status: \"done\" }];\n return ok(outcome.result);\n}\n\n/** A path such as /api/cloudrop, or an absolute http(s) URL ending in one; no trailing slash, query or fragment (S17). */\nconst BASE_PATH = /^(?:https?:\\/\\/[^/?#\\s]+)?(?:\\/[^/?#\\s]+)+$/;\n\n/** The options with their defaults; a wrong one throws its configuration error (S17, M3-U41, M3-U42, M3-U79). */\nfunction readOptions(\n options: ClientOptions | null,\n): Required<Omit<ClientOptions, \"fetch\">> & Pick<ClientOptions, \"fetch\"> {\n // null counts as no options, as createCloudrop reads its own (readConfig in server/config.ts).\n const {\n basePath = \"/api/cloudrop\",\n fetch,\n concurrency = \"auto\",\n order = \"added\",\n persist = true,\n namespace = \"\",\n } = options ?? {};\n if (typeof basePath !== \"string\" || !BASE_PATH.test(basePath)) {\n throw configError(\n 'basePath must be where the cloudrop handler is mounted, such as \"/api/cloudrop\" or \"https://api.example.com/api/cloudrop\": no trailing slash, query or fragment.',\n );\n }\n if (fetch !== undefined && typeof fetch !== \"function\") throw configError(\"The fetch option must be a function.\");\n if (concurrency !== \"auto\" && !(Number.isInteger(concurrency) && concurrency >= 1 && concurrency <= 16)) {\n throw configError('concurrency must be \"auto\" or a whole number from 1 to 16.');\n }\n if (order !== \"added\" && order !== \"smallest-first\") {\n throw configError('order must be \"added\" or \"smallest-first\".');\n }\n if (typeof persist !== \"boolean\") throw configError(\"persist must be true or false.\");\n if (typeof namespace !== \"string\" || namespace.length > 256) {\n throw configError(\"namespace must be a string of at most 256 characters, such as the signed-in user's id.\");\n }\n if (typeof (fetch ?? globalThis.fetch) !== \"function\") {\n throw configError(\"No fetch is available here. Pass createCloudropClient({ fetch }).\");\n }\n return { basePath, fetch, concurrency, order, persist, namespace };\n}\n\nexport function createCloudropClient<TCloudrop extends InferableCloudrop = InferableCloudrop>(\n options: ClientOptions = {},\n): CloudropClient<TCloudrop> {\n const { basePath, fetch, concurrency, order, persist, namespace } = readOptions(options);\n // Looked up on every request, so a fetch patched later is used, and called on globalThis: a browser throws \"Illegal\n // invocation\" when fetch runs as a method of another object (S18).\n const send: ClientFetch = fetch ?? ((url, init) => globalThis.fetch(url, init));\n // Bucket PUTs go through XMLHttpRequest in a browser unless a fetch option was passed (spec §4.1, ruling M3-U6).\n let rank = 0;\n const endpoints = createEndpoints(basePath, send);\n const context: UploadContext = {\n endpoints,\n put: createPut(fetch, send),\n pool: createPool(concurrency),\n order,\n nextRank: () => ++rank,\n // Called only when the page hides, after `context` below exists.\n leftovers: createLeftovers((held) => giveUp(context, held)),\n keepFailed: true,\n records: createRecords(persist),\n namespace,\n claims: new Set(),\n };\n // The server's types reach the client through `import type` only, so the wire answer cannot be checked against them\n // at run time: the casts below give the route's result type to what the server sent.\n function upload(\n route: unknown,\n files: unknown,\n options?: unknown,\n ): Promise<UploadResult<unknown> | Result<CompleteResponse<unknown>>> {\n // No handle to retry with: a failed file tells the server at once (ruling M3-U29).\n const { done } = startJob({ ...context, keepFailed: false }, route, files, options);\n // Anything that is not a list goes the one-file way, so a wrong argument keeps the message it had.\n return isList(files) ? done : done.then(oneFile);\n }\n // No `this`: `const { upload } = createCloudropClient()` works (S2).\n return {\n start: (route, files, ...rest) =>\n startJob(context, route, files, rest[0]) as UploadJob<RouteResult<TCloudrop, typeof route>>,\n upload: upload as CloudropClient<TCloudrop>[\"upload\"],\n resumable: (route) => resumable(context, route) as Promise<Result<ResumableUpload<typeof route & string>[]>>,\n resume: (upload, file, options) =>\n resumeJob(context, upload, file, options) as UploadJob<RouteResult<TCloudrop, typeof upload.route>>,\n discard: (upload) => discard(context, upload),\n forget: (options) => forget(context, options),\n };\n}\n"],"mappings":";;;;AAaA,MAAa,UAAU,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,SAAS,OAAO,MAAM,WA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