@powerhousedao/reactor-attachments 6.2.3-dev.6 → 6.2.3-dev.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/attachment-schema-compiler-rIaJpiHO.js +262 -0
- package/dist/attachment-schema-compiler-rIaJpiHO.js.map +1 -0
- package/dist/client.d.ts +56 -36
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +33 -20
- package/dist/client.js.map +1 -1
- package/dist/hash-BobbR4r4.js +63 -0
- package/dist/hash-BobbR4r4.js.map +1 -0
- package/dist/index.d.ts +81 -111
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +133 -405
- package/dist/index.js.map +1 -1
- package/dist/{null-attachment-transport-CMrO_ZKA.d.ts → interfaces-C4GRlKeB.d.ts} +34 -327
- package/dist/interfaces-C4GRlKeB.d.ts.map +1 -0
- package/dist/null-attachment-transport-Bs4JpmFx.d.ts +327 -0
- package/dist/null-attachment-transport-Bs4JpmFx.d.ts.map +1 -0
- package/dist/{null-attachment-transport-CrsUafCi.js → null-attachment-transport-Cm_kb5ww.js} +37 -283
- package/dist/null-attachment-transport-Cm_kb5ww.js.map +1 -0
- package/dist/replication.d.ts +955 -0
- package/dist/replication.d.ts.map +1 -0
- package/dist/replication.js +1975 -0
- package/dist/replication.js.map +1 -0
- package/dist/switchboard-attachment-transport-BH3ZAmxE.js +284 -0
- package/dist/switchboard-attachment-transport-BH3ZAmxE.js.map +1 -0
- package/dist/types-AagIcjTD.d.ts +61 -0
- package/dist/types-AagIcjTD.d.ts.map +1 -0
- package/package.json +16 -7
- package/dist/null-attachment-transport-CMrO_ZKA.d.ts.map +0 -1
- package/dist/null-attachment-transport-CrsUafCi.js.map +0 -1
package/dist/client.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as parseRef, c as AttachmentPending, f as InvalidAttachmentRef, h as UploadTooLarge, i as createRef, l as AttachmentTransferError, m as SizeMismatch, o as AttachmentAlreadyExists, p as ReservationNotFound, s as AttachmentNotFound, t as SwitchboardAttachmentTransport, u as HashMismatch } from "./switchboard-attachment-transport-BH3ZAmxE.js";
|
|
2
|
+
import { a as RemoteAttachmentUpload, c as createFetchUploadTransport, d as parseAttachmentDownloadTarget, f as parseAttachmentUploadTarget, i as RemoteAttachmentUploadFactory, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-Cm_kb5ww.js";
|
|
3
|
+
import { n as sha256HexOfBlob } from "./hash-BobbR4r4.js";
|
|
2
4
|
//#region src/concurrency.ts
|
|
3
5
|
/**
|
|
4
6
|
* Runs `worker` over `items` with a hard upper bound on simultaneous
|
|
@@ -24,10 +26,11 @@ async function runWithConcurrency(items, worker, options) {
|
|
|
24
26
|
continue;
|
|
25
27
|
}
|
|
26
28
|
try {
|
|
29
|
+
const value = await worker(items[index], index);
|
|
27
30
|
results[index] = {
|
|
28
31
|
index,
|
|
29
32
|
status: "fulfilled",
|
|
30
|
-
value
|
|
33
|
+
value
|
|
31
34
|
};
|
|
32
35
|
} catch (error) {
|
|
33
36
|
results[index] = {
|
|
@@ -238,11 +241,20 @@ function isAttachmentAlreadyExists(err) {
|
|
|
238
241
|
if (err instanceof AttachmentAlreadyExists) return true;
|
|
239
242
|
return err instanceof Error && err.name === "AttachmentAlreadyExists" && typeof err.hash === "string" && typeof err.ref === "string";
|
|
240
243
|
}
|
|
241
|
-
function
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
244
|
+
function dedupedHeader(hash, options) {
|
|
245
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
246
|
+
return {
|
|
247
|
+
hash,
|
|
248
|
+
mimeType: options.mimeType,
|
|
249
|
+
fileName: options.fileName,
|
|
250
|
+
sizeBytes: options.sizeBytes,
|
|
251
|
+
extension: options.extension ?? null,
|
|
252
|
+
status: "available",
|
|
253
|
+
source: "local",
|
|
254
|
+
createdAtUtc: now,
|
|
255
|
+
lastAccessedAtUtc: now,
|
|
256
|
+
expiresAtUtc: null
|
|
257
|
+
};
|
|
246
258
|
}
|
|
247
259
|
/** Stamps an item's index onto its progress events. */
|
|
248
260
|
function itemProgress(options, index) {
|
|
@@ -277,14 +289,15 @@ function batchRunOptions(total, options) {
|
|
|
277
289
|
};
|
|
278
290
|
}
|
|
279
291
|
var AttachmentClientImpl = class {
|
|
292
|
+
service;
|
|
280
293
|
constructor(service) {
|
|
281
294
|
this.service = service;
|
|
282
295
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const hash =
|
|
296
|
+
preprocess(file, opts) {
|
|
297
|
+
return this.hashFile(file, opts);
|
|
298
|
+
}
|
|
299
|
+
async hashFile(file, opts, signal) {
|
|
300
|
+
const hash = await sha256HexOfBlob(file, signal ? { signal } : void 0);
|
|
288
301
|
const ref = createRef(hash);
|
|
289
302
|
const sizeBytes = file.size;
|
|
290
303
|
const options = {
|
|
@@ -293,15 +306,16 @@ var AttachmentClientImpl = class {
|
|
|
293
306
|
clientHash: hash,
|
|
294
307
|
sizeBytes
|
|
295
308
|
};
|
|
296
|
-
const data =
|
|
297
|
-
const stream = () =>
|
|
309
|
+
const data = file.stream();
|
|
310
|
+
const stream = () => file.stream();
|
|
298
311
|
return {
|
|
299
312
|
ref,
|
|
300
313
|
hash,
|
|
301
314
|
sizeBytes,
|
|
302
315
|
options,
|
|
303
316
|
data,
|
|
304
|
-
stream
|
|
317
|
+
stream,
|
|
318
|
+
blob: file
|
|
305
319
|
};
|
|
306
320
|
}
|
|
307
321
|
/**
|
|
@@ -317,13 +331,12 @@ var AttachmentClientImpl = class {
|
|
|
317
331
|
};
|
|
318
332
|
} catch (err) {
|
|
319
333
|
if (!isAttachmentAlreadyExists(err)) throw err;
|
|
320
|
-
const header = await this.service.stat(err.ref);
|
|
321
334
|
return {
|
|
322
335
|
kind: "deduped",
|
|
323
336
|
result: {
|
|
324
337
|
hash: err.hash,
|
|
325
338
|
ref: err.ref,
|
|
326
|
-
header
|
|
339
|
+
header: dedupedHeader(err.hash, options)
|
|
327
340
|
}
|
|
328
341
|
};
|
|
329
342
|
}
|
|
@@ -342,10 +355,10 @@ var AttachmentClientImpl = class {
|
|
|
342
355
|
if ("preprocessed" in input) preprocessed = input.preprocessed;
|
|
343
356
|
else {
|
|
344
357
|
emitter.stage("hashing", { total: input.file.size });
|
|
345
|
-
preprocessed = await this.
|
|
358
|
+
preprocessed = await this.hashFile(input.file, {
|
|
346
359
|
...input.fileName !== void 0 ? { fileName: input.fileName } : {},
|
|
347
360
|
...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {}
|
|
348
|
-
});
|
|
361
|
+
}, signal);
|
|
349
362
|
}
|
|
350
363
|
const sizeBytes = preprocessed.sizeBytes;
|
|
351
364
|
signal?.throwIfAborted();
|
|
@@ -361,7 +374,7 @@ var AttachmentClientImpl = class {
|
|
|
361
374
|
...emitter.active ? { onProgress: (loaded, total) => emitter.bytes(loaded, total ?? sizeBytes) } : {},
|
|
362
375
|
...signal ? { signal } : {}
|
|
363
376
|
};
|
|
364
|
-
const result = await outcome.handle.send(preprocessed.
|
|
377
|
+
const result = await outcome.handle.send(preprocessed.blob, sendOptions);
|
|
365
378
|
emitter.finish();
|
|
366
379
|
return result;
|
|
367
380
|
} catch (err) {
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"sourcesContent":["/**\n * Ordered result of one batch item. `index` always mirrors the input\n * position, so callers can correlate results with inputs regardless of\n * completion order, and successes are retained when siblings fail.\n */\nexport type BatchItemResult<R> =\n | { index: number; status: \"fulfilled\"; value: R }\n | { index: number; status: \"rejected\"; error: unknown };\n\nexport type RunWithConcurrencyOptions<R = unknown> = {\n /** Maximum simultaneously running workers. Must be a positive integer. */\n concurrency: number;\n /**\n * Whole-batch cancellation: unstarted items are rejected with the signal's\n * reason without ever starting, while already-started items keep running —\n * per-item signals are the mechanism for interrupting active work.\n */\n signal?: AbortSignal;\n /**\n * Called once per item as it settles, in completion order, including items\n * the signal skipped before they ever started. That completeness is the\n * point: a caller counting settlements must still reach `items.length`\n * after a whole-batch abort.\n */\n onSettled?: (result: BatchItemResult<R>) => void;\n};\n\n/**\n * Runs `worker` over `items` with a hard upper bound on simultaneous\n * executions. Bounding starts (not just transfers) is what keeps memory flat:\n * an item's preprocessing (hashing/buffering) only begins when a slot frees.\n */\nexport async function runWithConcurrency<T, R>(\n items: readonly T[],\n worker: (item: T, index: number) => Promise<R>,\n options: RunWithConcurrencyOptions<R>,\n): Promise<BatchItemResult<R>[]> {\n const { concurrency, signal, onSettled } = options;\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new Error(\n `concurrency must be a positive integer, got: ${concurrency}`,\n );\n }\n\n const results: BatchItemResult<R>[] = new Array<BatchItemResult<R>>(\n items.length,\n );\n let nextIndex = 0;\n\n async function runLane(): Promise<void> {\n for (;;) {\n const index = nextIndex++;\n if (index >= items.length) return;\n if (signal?.aborted) {\n results[index] = {\n index,\n status: \"rejected\",\n error: signalReason(signal),\n };\n onSettled?.(results[index]);\n continue;\n }\n try {\n const value = await worker(items[index], index);\n results[index] = { index, status: \"fulfilled\", value };\n } catch (error) {\n results[index] = { index, status: \"rejected\", error };\n }\n onSettled?.(results[index]);\n }\n }\n\n const lanes = Array.from(\n { length: Math.min(concurrency, items.length) },\n () => runLane(),\n );\n await Promise.all(lanes);\n return results;\n}\n\nfunction signalReason(signal: AbortSignal): unknown {\n return (\n (signal as { reason?: unknown }).reason ??\n new DOMException(\"The operation was aborted\", \"AbortError\")\n );\n}\n","/**\n * Byte-level progress for attachment transfers.\n *\n * `loaded`/`total` are per-stage, never per-operation. A per-operation\n * denominator would have to weight hashing against transfer, and a confirmed\n * dedup would shrink it mid-flight from 2N to N — the bar would run backwards.\n * Choosing that weighting is a UI decision the client cannot make.\n */\n\nexport type AttachmentStage =\n | \"hashing\"\n | \"reserving\"\n | \"uploading\"\n | \"requesting-download-target\"\n | \"downloading\"\n | \"done\"\n | \"error\";\n\nexport type AttachmentProgress = {\n stage: AttachmentStage;\n /** Bytes moved so far within `stage`. */\n loaded: number;\n /** Denominator for `stage`: file.size for uploads, header.sizeBytes for downloads. */\n total: number | undefined;\n /** True when the stage is running but bytes cannot (yet) be observed. */\n indeterminate: boolean;\n /** Only on a terminal `done` where dedup skipped the transfer entirely. */\n deduped?: true;\n};\n\nexport type AttachmentProgressListener = (progress: AttachmentProgress) => void;\n\nexport type AttachmentProgressOptions = {\n onProgress?: AttachmentProgressListener;\n /** Min ms between byte events within a stage. Default 100. 0 emits every observation. */\n throttleMs?: number;\n};\n\nexport const DEFAULT_PROGRESS_THROTTLE_MS = 100;\n\n/**\n * Fraction in 0..1 for a progress event. Indeterminate and unknown-total\n * events read as 0 — a bar cannot honestly show a position it does not know.\n * A zero total is complete by definition (the dedup case moves no bytes).\n */\nexport function progressFraction(progress: AttachmentProgress): number {\n if (progress.indeterminate) return 0;\n if (progress.total === undefined) return 0;\n if (progress.total === 0) return 1;\n const fraction = progress.loaded / progress.total;\n if (fraction < 0) return 0;\n return fraction > 1 ? 1 : fraction;\n}\n\nexport type ProgressEmitterOptions = AttachmentProgressOptions & {\n /** Injected clock so throttle tests stay synchronous. */\n now?: () => number;\n};\n\n/**\n * Emits `AttachmentProgress` for one single-item operation, upholding:\n *\n * - **I1** exactly one terminal event (`done` or `error`) — never both, never twice.\n * - **I2** on `done`: `indeterminate === false`, `total` is a number, `loaded === total`.\n * - **I3** `loaded` is non-decreasing within a stage and resets to 0 on stage change.\n * - **I4** the terminal event bypasses the throttle unconditionally.\n * - **I5** `error` carries the last known `loaded`/`total`.\n *\n * Leading edge: the first `bytes()` after a `stage()` always emits, so a bar\n * leaves 0 immediately. There is deliberately no trailing-edge timer — it\n * would leak on throw, could fire after the terminal event and violate I1's\n * ordering, and is unnecessary because `finish()` always emits\n * `loaded === total`, making a dropped last intra-stage tick invisible.\n */\nexport class ProgressEmitter {\n private readonly listener: AttachmentProgressListener | undefined;\n private readonly throttleMs: number;\n private readonly now: () => number;\n\n private currentStage: AttachmentStage | undefined;\n private loaded = 0;\n private total: number | undefined;\n private emittedBytesInStage = false;\n private lastEmitAt = Number.NEGATIVE_INFINITY;\n private settled = false;\n\n constructor(options?: ProgressEmitterOptions) {\n this.listener = options?.onProgress;\n this.throttleMs = options?.throttleMs ?? DEFAULT_PROGRESS_THROTTLE_MS;\n this.now = options?.now ?? (() => Date.now());\n }\n\n /** True when a listener is attached; lets callers skip instrumentation entirely. */\n get active(): boolean {\n return this.listener !== undefined;\n }\n\n /**\n * Enter a stage. Always emits and resets `loaded` to 0. Entry is always\n * indeterminate: no bytes have moved yet, and whether they can be observed\n * at all is only proven by a transport actually calling back.\n */\n stage(stage: AttachmentStage, options?: { total?: number }): void {\n if (this.settled) return;\n this.currentStage = stage;\n this.loaded = 0;\n this.total = options?.total;\n this.emittedBytesInStage = false;\n this.emit({\n stage,\n loaded: 0,\n total: this.total,\n indeterminate: true,\n });\n }\n\n /**\n * Report observed bytes within the current stage. Throttled by time, with\n * the first observation after a stage change always emitted.\n */\n bytes(loaded: number, total?: number): void {\n if (this.settled || this.currentStage === undefined) return;\n if (total !== undefined) this.total = total;\n if (loaded > this.loaded) this.loaded = loaded;\n\n const leadingEdge = !this.emittedBytesInStage;\n if (!leadingEdge && this.now() - this.lastEmitAt < this.throttleMs) return;\n this.emittedBytesInStage = true;\n this.emit({\n stage: this.currentStage,\n loaded: this.loaded,\n total: this.total,\n indeterminate: false,\n });\n }\n\n /**\n * Terminal success. `total` defaults to the bytes actually seen so a stage\n * with no known denominator still satisfies I2.\n */\n finish(override?: { loaded?: number; total?: number; deduped?: true }): void {\n if (this.settled) return;\n this.settled = true;\n const total = override?.total ?? this.total ?? this.loaded;\n const loaded = override?.loaded ?? total;\n this.emit({\n stage: \"done\",\n loaded,\n total,\n indeterminate: false,\n ...(override?.deduped ? { deduped: true as const } : {}),\n });\n }\n\n /** Terminal success for a confirmed dedup: no bytes moved, and none needed to. */\n finishDeduped(): void {\n this.finish({ loaded: 0, total: 0, deduped: true });\n }\n\n /** Terminal failure, carrying the last known byte counts. */\n fail(): void {\n if (this.settled) return;\n this.settled = true;\n this.emit({\n stage: \"error\",\n loaded: this.loaded,\n total: this.total,\n indeterminate: false,\n });\n }\n\n private emit(progress: AttachmentProgress): void {\n this.lastEmitAt = this.now();\n this.listener?.(progress);\n }\n}\n\nexport type ByteProgressHooks = {\n /** Cumulative bytes handed to the consumer. */\n onBytes?: (loaded: number) => void;\n /** The source ended and every byte reached the consumer. */\n onDone?: () => void;\n onError?: (error: unknown) => void;\n};\n\n/**\n * Count bytes as a consumer reads them.\n *\n * Uses the manual-reader form rather than `pipeThrough`, whose internal queue\n * reads far ahead of the consumer and would make `loaded` overstate what was\n * actually received. `highWaterMark: 0` is load-bearing for the same reason:\n * at the default of 1 the wrapper pulls one chunk the instant it is\n * constructed, so a caller who never reads still sees bytes counted.\n *\n * `cancel` propagates to the source, which is what keeps reader refcounts\n * (e.g. `KyselyAttachmentStore`'s) correct. Cancelling is an abandonment, not\n * a completion, so it reports `onError` — never `onDone` — carrying the\n * cancel reason the way an `AbortSignal` carries its own, with the DOM's\n * default `AbortError` when the canceller gave none.\n *\n * Returns `source` unchanged when no hook is supplied, so a caller with no\n * listener pays nothing.\n */\nexport function withByteProgress(\n source: ReadableStream<Uint8Array>,\n hooks: ByteProgressHooks,\n): ReadableStream<Uint8Array> {\n if (!hooks.onBytes && !hooks.onDone && !hooks.onError) return source;\n\n let loaded = 0;\n let cancelled = false;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n // A cancel that lands while this read is in flight resolves it as\n // `done`, and closes the stream. Bailing out here is what stops an\n // abandoned transfer from reporting completion, and stops the\n // already-closed controller from throwing a fabricated error into\n // the catch below.\n if (cancelled) return;\n if (done) {\n hooks.onDone?.();\n controller.close();\n return;\n }\n loaded += value.byteLength;\n hooks.onBytes?.(loaded);\n controller.enqueue(value);\n } catch (err) {\n if (cancelled) return;\n hooks.onError?.(err);\n controller.error(err);\n }\n },\n cancel(reason) {\n cancelled = true;\n reader.cancel(reason).catch(() => {});\n hooks.onError?.(reason ?? abortError());\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/** What an `AbortSignal` carries when `abort()` is called with no reason. */\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n runWithConcurrency,\n type BatchItemResult,\n type RunWithConcurrencyOptions,\n} from \"./concurrency.js\";\nimport { AttachmentAlreadyExists } from \"./errors.js\";\nexport type { AttachmentTransferStage } from \"./errors.js\";\nexport {\n runWithConcurrency,\n type BatchItemResult,\n type RunWithConcurrencyOptions,\n} from \"./concurrency.js\";\nimport type { IAttachmentService, IAttachmentUpload } from \"./interfaces.js\";\nimport {\n ProgressEmitter,\n withByteProgress,\n type AttachmentProgress,\n type AttachmentProgressOptions,\n} from \"./progress.js\";\nimport { createRef } from \"./ref.js\";\nimport type {\n AttachmentHeader,\n AttachmentResponse,\n AttachmentSendOptions,\n AttachmentUploadResult,\n HashFirstReserveAttachmentOptions,\n} from \"./types.js\";\n\nexport { AttachmentService } from \"./attachment-service.js\";\nexport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n HashMismatch,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n} from \"./errors.js\";\nexport type {\n IAttachmentReader,\n IAttachmentService,\n IAttachmentStore,\n IAttachmentTransport,\n IAttachmentTransportFactory,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nexport { parseRef, createRef } from \"./ref.js\";\nexport type { ParsedRef } from \"./ref.js\";\nexport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n AttachmentSendOptions,\n AttachmentStatus,\n AttachmentTransportConfig,\n AttachmentUploadResult,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n HashFirstReserveAttachmentOptions,\n UploadFirstReserveAttachmentOptions,\n Reservation,\n ReserveAttachmentOptions,\n TransportFetchResult,\n TransportResponse,\n} from \"./types.js\";\nexport {\n parseAttachmentDownloadTarget,\n parseAttachmentUploadTarget,\n} from \"./targets.js\";\nexport {\n SwitchboardAttachmentTransport,\n type SwitchboardTransportConfig,\n RemoteReservationStore,\n type SwitchboardClientConfig,\n RemoteAttachmentUpload,\n RemoteAttachmentUploadFactory,\n RemoteAttachmentStore,\n createRemoteAttachmentService,\n createFetchUploadTransport,\n createXhrUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n type XhrUploadTransportOptions,\n} from \"./switchboard/index.js\";\nexport { NullAttachmentTransport } from \"./null-attachment-transport.js\";\nexport {\n DEFAULT_PROGRESS_THROTTLE_MS,\n progressFraction,\n ProgressEmitter,\n withByteProgress,\n type AttachmentProgress,\n type AttachmentProgressListener,\n type AttachmentProgressOptions,\n type AttachmentStage,\n type ByteProgressHooks,\n type ProgressEmitterOptions,\n} from \"./progress.js\";\n\nexport type PreprocessResult = {\n ref: AttachmentRef;\n hash: AttachmentHash;\n sizeBytes: number;\n options: HashFirstReserveAttachmentOptions;\n data: ReadableStream<Uint8Array>;\n stream: () => ReadableStream<Uint8Array>;\n};\n\nexport type AttachmentUploadInput = {\n file: Blob;\n fileName?: string;\n mimeType?: string;\n /** Per-item cancellation, checked between stages. */\n signal?: AbortSignal;\n};\n\n/**\n * Upload bytes that were already hashed by a separate `preprocess()` call.\n *\n * This is the canonical two-call flow: the ref must reach the document before\n * the bytes are committed, so callers preprocess, dispatch the operation, then\n * upload. Passing the result back in skips the hashing stage rather than\n * faking a zero-millisecond one.\n */\nexport type AttachmentPreprocessedUploadInput = {\n preprocessed: PreprocessResult;\n signal?: AbortSignal;\n};\n\n/**\n * Every remote download names the document that authorizes its ref; batches\n * may freely mix documents because the anchor travels with each item.\n */\nexport type AttachmentDownloadInput = {\n documentId: string;\n ref: AttachmentRef;\n signal?: AbortSignal;\n};\n\n/**\n * The document keeps its own name and type for an attachment (the same\n * bytes may appear under different names in different documents), so the\n * blob-producing conveniences let callers override what the server header\n * reports from upload time.\n */\nexport type AttachmentBlobOptions = {\n mimeType?: string;\n};\n\nexport type AttachmentSaveOptions = {\n fileName?: string;\n mimeType?: string;\n};\n\nexport type AttachmentBlobResult = {\n blob: Blob;\n header: AttachmentHeader;\n};\n\nexport type AttachmentObjectUrl = {\n /** Ready for img/iframe/video src. Pins memory until revoke() is called. */\n url: string;\n header: AttachmentHeader;\n revoke: () => void;\n};\n\nexport type AttachmentShareLinkInput = {\n documentId: string;\n ref: AttachmentRef;\n /** Requested link lifetime in seconds; the server clamps to its maximum. */\n expiresIn?: number;\n signal?: AbortSignal;\n};\n\n/**\n * A self-contained public URL: anyone holding it can fetch the bytes until\n * expiresAtUtc, with no login and no document access. Minting one requires\n * document read access; once minted it cannot be revoked before expiry.\n */\nexport type AttachmentShareLink = {\n url: string;\n expiresAtUtc: string;\n};\n\n/**\n * Batch progress is per item, carrying the item's `index`. There is\n * deliberately no batch-wide byte total: weighting items against each other is\n * a presentation decision the client cannot make, and a confirmed dedup would\n * shrink the denominator mid-flight.\n */\nexport type AttachmentBatchOptions = {\n /** Bounds preprocessing and transfer together. Defaults to 4. */\n concurrency?: number;\n /** Whole-batch cancellation: stops unstarted items. */\n signal?: AbortSignal;\n onProgress?: (progress: AttachmentProgress & { index: number }) => void;\n /**\n * Fired as each item settles, including items the signal skipped before they\n * started, so `settled` always reaches `total`.\n */\n onItemSettled?: (counts: AttachmentBatchCounts) => void;\n /** Min ms between byte events, applied per item rather than batch-wide. */\n throttleMs?: number;\n};\n\nexport type AttachmentBatchCounts = {\n settled: number;\n completed: number;\n failed: number;\n total: number;\n};\n\nexport const DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;\n\nexport interface IAttachmentClient {\n preprocess(\n file: Blob,\n opts?: { fileName?: string; mimeType?: string },\n ): Promise<PreprocessResult>;\n reserve(\n options: HashFirstReserveAttachmentOptions,\n send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>,\n ): Promise<AttachmentUploadResult>;\n /**\n * Hash, reserve, and transfer one file; a confirmed dedup skips the transfer\n * and reports a terminal `done` carrying `deduped: true` and zero bytes.\n *\n * Also accepts an already-preprocessed payload, so the canonical\n * preprocess -> dispatch -> upload flow reports progress too.\n */\n upload(\n input: AttachmentUploadInput | AttachmentPreprocessedUploadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentUploadResult>;\n /**\n * Document-authorized download of one ref.\n *\n * Resolves as soon as the byte stream is available, with `downloading` as\n * the last event emitted and `loaded: 0`. Byte events and the terminal\n * `done` arrive as the caller reads the stream — and never arrive at all if\n * the caller abandons it.\n */\n download(\n input: AttachmentDownloadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentResponse>;\n /**\n * Document-authorized download materialized as a typed Blob. The Blob's\n * type comes from the server header unless overridden — that's what makes\n * browsers render PDFs inline and images correctly.\n */\n downloadBlob(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentBlobResult>;\n /**\n * Download and hand the bytes to the browser's save-file flow. Browser\n * only. fileName defaults to the server header's; pass the document's own\n * name for per-document naming.\n */\n saveAttachment(\n input: AttachmentDownloadInput,\n options?: AttachmentSaveOptions & AttachmentProgressOptions,\n ): Promise<void>;\n /**\n * Download and expose the bytes as an object URL for inline rendering\n * (img/iframe/video src). Callers MUST call revoke() when done — the URL\n * pins the blob in memory until then.\n */\n downloadObjectUrl(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentObjectUrl>;\n /**\n * Mint a public share link: a presigned URL anyone can fetch until it\n * expires, with no login. Authorized exactly like a download (document\n * read access + the reference index). Requires a presigned-capable\n * storage backend (S3); rejects when the server answers with an\n * authenticated switchboard target, which would not be public.\n */\n getShareLink(input: AttachmentShareLinkInput): Promise<AttachmentShareLink>;\n uploadMany(\n inputs: readonly AttachmentUploadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentUploadResult>[]>;\n downloadMany(\n inputs: readonly AttachmentDownloadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentResponse>[]>;\n}\n\n/**\n * Duck-typed dedup detection: bundlers (notably Vite dev pre-bundling) can\n * load two copies of this package's error classes, one for the service and\n * one for the client wrapper, making a plain instanceof check miss the\n * cross-copy throw. Name plus payload shape identifies the error reliably.\n */\nfunction isAttachmentAlreadyExists(\n err: unknown,\n): err is AttachmentAlreadyExists {\n if (err instanceof AttachmentAlreadyExists) return true;\n return (\n err instanceof Error &&\n err.name === \"AttachmentAlreadyExists\" &&\n typeof (err as { hash?: unknown }).hash === \"string\" &&\n typeof (err as { ref?: unknown }).ref === \"string\"\n );\n}\n\nfunction streamFromBuffer(buf: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(buf);\n controller.close();\n },\n });\n}\n\n/** Stamps an item's index onto its progress events. */\nfunction itemProgress(\n options: AttachmentBatchOptions | undefined,\n index: number,\n): AttachmentProgressOptions | undefined {\n if (!options?.onProgress && options?.throttleMs === undefined) {\n return undefined;\n }\n return {\n ...(options.onProgress\n ? {\n onProgress: (progress: AttachmentProgress) =>\n options.onProgress?.({ ...progress, index }),\n }\n : {}),\n ...(options.throttleMs !== undefined\n ? { throttleMs: options.throttleMs }\n : {}),\n };\n}\n\nfunction batchRunOptions<R>(\n total: number,\n options: AttachmentBatchOptions | undefined,\n): RunWithConcurrencyOptions<R> {\n const onItemSettled = options?.onItemSettled;\n let settled = 0;\n let completed = 0;\n let failed = 0;\n return {\n concurrency: options?.concurrency ?? DEFAULT_ATTACHMENT_BATCH_CONCURRENCY,\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(onItemSettled\n ? {\n onSettled: (result: BatchItemResult<R>) => {\n settled += 1;\n if (result.status === \"fulfilled\") completed += 1;\n else failed += 1;\n onItemSettled({ settled, completed, failed, total });\n },\n }\n : {}),\n };\n}\n\nclass AttachmentClientImpl implements IAttachmentClient {\n constructor(private readonly service: IAttachmentService) {}\n\n async preprocess(\n file: Blob,\n opts?: { fileName?: string; mimeType?: string },\n ): Promise<PreprocessResult> {\n const buf = await file.arrayBuffer();\n const bytes = new Uint8Array(buf);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n const hash = Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\") as AttachmentHash;\n const ref = createRef(hash);\n const sizeBytes = file.size;\n const mimeType = opts?.mimeType ?? file.type;\n const fileName =\n opts?.fileName ?? (file instanceof File ? file.name : \"attachment\");\n const options: HashFirstReserveAttachmentOptions = {\n mimeType,\n fileName,\n clientHash: hash,\n sizeBytes,\n };\n const data = streamFromBuffer(bytes);\n const stream = (): ReadableStream<Uint8Array> => streamFromBuffer(bytes);\n return { ref, hash, sizeBytes, options, data, stream };\n }\n\n /**\n * Reserve, distinguishing a confirmed dedup from a live upload handle in the\n * type rather than with a flag: the two outcomes move a different number of\n * bytes, and every caller has to account for that.\n */\n private async reserveOrDedup(\n options: HashFirstReserveAttachmentOptions,\n ): Promise<\n | { kind: \"handle\"; handle: IAttachmentUpload }\n | { kind: \"deduped\"; result: AttachmentUploadResult }\n > {\n try {\n return { kind: \"handle\", handle: await this.service.reserve(options) };\n } catch (err) {\n if (!isAttachmentAlreadyExists(err)) throw err;\n const header = await this.service.stat(err.ref);\n return {\n kind: \"deduped\",\n result: { hash: err.hash, ref: err.ref, header },\n };\n }\n }\n\n async reserve(\n options: HashFirstReserveAttachmentOptions,\n send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>,\n ): Promise<AttachmentUploadResult> {\n const outcome = await this.reserveOrDedup(options);\n if (outcome.kind === \"deduped\") return outcome.result;\n return send(outcome.handle);\n }\n\n async upload(\n input: AttachmentUploadInput | AttachmentPreprocessedUploadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentUploadResult> {\n const emitter = new ProgressEmitter(options);\n const signal = input.signal;\n try {\n signal?.throwIfAborted();\n\n let preprocessed: PreprocessResult;\n if (\"preprocessed\" in input) {\n preprocessed = input.preprocessed;\n } else {\n // Hashing is genuinely unobservable: preprocess() runs one\n // crypto.subtle.digest over the whole buffer and WebCrypto has no\n // streaming digest. The stage is still reported, with a denominator\n // and indeterminate never cleared, so a UI can name what it waits on.\n emitter.stage(\"hashing\", { total: input.file.size });\n preprocessed = await this.preprocess(input.file, {\n ...(input.fileName !== undefined ? { fileName: input.fileName } : {}),\n ...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),\n });\n }\n const sizeBytes = preprocessed.sizeBytes;\n\n signal?.throwIfAborted();\n emitter.stage(\"reserving\");\n const outcome = await this.reserveOrDedup(preprocessed.options);\n\n // A confirmed dedup never enters `uploading` — the server already holds\n // these bytes, so none are sent. Reporting zero of zero keeps the byte\n // model honest instead of stalling at 0 and then jumping to done.\n if (outcome.kind === \"deduped\") {\n emitter.finishDeduped();\n return outcome.result;\n }\n\n signal?.throwIfAborted();\n emitter.stage(\"uploading\", { total: sizeBytes });\n // `onProgress` only when someone is listening. The XHR transport keys\n // its `upload.onprogress` registration off the option being present, and\n // that registration alone forces a CORS preflight on a presigned PUT —\n // a cost an unwatched upload must not pay for a callback that would\n // discard every event anyway.\n const sendOptions: AttachmentSendOptions = {\n ...(emitter.active\n ? {\n onProgress: (loaded: number, total?: number) =>\n emitter.bytes(loaded, total ?? sizeBytes),\n }\n : {}),\n ...(signal ? { signal } : {}),\n };\n const result = await outcome.handle.send(\n preprocessed.stream(),\n sendOptions,\n );\n emitter.finish();\n return result;\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n /**\n * The single site where download bytes are instrumented.\n *\n * It sits here, above the service, rather than in any store or transport:\n * one logical get can be several byte streams underneath (an evicted\n * attachment is fetched from the transport, written to disk, then re-read),\n * so counting lower down would double-count that path and still miss\n * local-filesystem reads. Wrapping what `service.get` returns covers the\n * presigned, switchboard, legacy and local paths by construction, and\n * `downloadBlob`/`saveAttachment`/`downloadObjectUrl` inherit it.\n */\n private async getWithProgress(\n input: AttachmentDownloadInput,\n emitter: ProgressEmitter,\n ): Promise<AttachmentResponse> {\n const { header, body } = await this.service.get(input.ref, {\n documentId: input.documentId,\n signal: input.signal,\n });\n emitter.stage(\"downloading\", { total: header.sizeBytes });\n if (!emitter.active) return { header, body };\n return {\n header,\n body: withByteProgress(body, {\n onBytes: (loaded) => emitter.bytes(loaded),\n onDone: () => emitter.finish(),\n onError: () => emitter.fail(),\n }),\n };\n }\n\n async download(\n input: AttachmentDownloadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentResponse> {\n const emitter = new ProgressEmitter(options);\n try {\n input.signal?.throwIfAborted();\n emitter.stage(\"requesting-download-target\");\n return await this.getWithProgress(input, emitter);\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n async downloadBlob(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentBlobResult> {\n const emitter = new ProgressEmitter(options);\n try {\n input.signal?.throwIfAborted();\n emitter.stage(\"requesting-download-target\");\n const { header, body } = await this.getWithProgress(input, emitter);\n const reader = body.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value as BlobPart);\n }\n const blob = new Blob(chunks, {\n type: options?.mimeType ?? header.mimeType,\n });\n // Draining the stream already finished the emitter; latching makes this\n // a no-op there, and a guarantee for any body that closes without one.\n emitter.finish();\n return { blob, header };\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n async saveAttachment(\n input: AttachmentDownloadInput,\n options?: AttachmentSaveOptions & AttachmentProgressOptions,\n ): Promise<void> {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"saveAttachment requires a browser environment; use downloadBlob elsewhere\",\n );\n }\n const { blob, header } = await this.downloadBlob(input, options);\n const url = URL.createObjectURL(blob);\n try {\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = options?.fileName ?? header.fileName;\n anchor.click();\n } finally {\n URL.revokeObjectURL(url);\n }\n }\n\n async downloadObjectUrl(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentObjectUrl> {\n const { blob, header } = await this.downloadBlob(input, options);\n const url = URL.createObjectURL(blob);\n let revoked = false;\n return {\n url,\n header,\n revoke: () => {\n if (revoked) return;\n revoked = true;\n URL.revokeObjectURL(url);\n },\n };\n }\n\n async getShareLink(\n input: AttachmentShareLinkInput,\n ): Promise<AttachmentShareLink> {\n input.signal?.throwIfAborted();\n const target = await this.service.getDownloadTarget(input.ref, {\n documentId: input.documentId,\n ...(input.expiresIn !== undefined ? { expiresIn: input.expiresIn } : {}),\n ...(input.signal !== undefined ? { signal: input.signal } : {}),\n });\n if (target.kind !== \"presigned-get\") {\n throw new Error(\n \"Public share links require a presigned-capable storage backend (S3); this server answered with an authenticated target\",\n );\n }\n return { url: target.url, expiresAtUtc: target.expiresAtUtc };\n }\n\n uploadMany(\n inputs: readonly AttachmentUploadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentUploadResult>[]> {\n return runWithConcurrency(\n inputs,\n (input, index) => this.upload(input, itemProgress(options, index)),\n batchRunOptions(inputs.length, options),\n );\n }\n\n /**\n * `concurrency` bounds download-target negotiation, not simultaneous byte\n * transfer: each item resolves when its stream is handed over, and the bytes\n * move only as the caller reads. Byte progress makes that pre-existing\n * behavior visible; it does not change it.\n */\n downloadMany(\n inputs: readonly AttachmentDownloadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentResponse>[]> {\n return runWithConcurrency(\n inputs,\n (input, index) => this.download(input, itemProgress(options, index)),\n batchRunOptions(inputs.length, options),\n );\n }\n}\n\nexport function createAttachmentClient(\n service: IAttachmentService,\n): IAttachmentClient {\n return new AttachmentClientImpl(service);\n}\n"],"mappings":";;;;;;;AAgCA,eAAsB,mBACpB,OACA,QACA,SAC+B;CAC/B,MAAM,EAAE,aAAa,QAAQ,cAAc;AAC3C,KAAI,CAAC,OAAO,UAAU,YAAY,IAAI,cAAc,EAClD,OAAM,IAAI,MACR,gDAAgD,cACjD;CAGH,MAAM,UAAgC,IAAI,MACxC,MAAM,OACP;CACD,IAAI,YAAY;CAEhB,eAAe,UAAyB;AACtC,WAAS;GACP,MAAM,QAAQ;AACd,OAAI,SAAS,MAAM,OAAQ;AAC3B,OAAI,QAAQ,SAAS;AACnB,YAAQ,SAAS;KACf;KACA,QAAQ;KACR,OAAO,aAAa,OAAO;KAC5B;AACD,gBAAY,QAAQ,OAAO;AAC3B;;AAEF,OAAI;AAEF,YAAQ,SAAS;KAAE;KAAO,QAAQ;KAAa,OADjC,MAAM,OAAO,MAAM,QAAQ,MAAM;KACO;YAC/C,OAAO;AACd,YAAQ,SAAS;KAAE;KAAO,QAAQ;KAAY;KAAO;;AAEvD,eAAY,QAAQ,OAAO;;;CAI/B,MAAM,QAAQ,MAAM,KAClB,EAAE,QAAQ,KAAK,IAAI,aAAa,MAAM,OAAO,EAAE,QACzC,SAAS,CAChB;AACD,OAAM,QAAQ,IAAI,MAAM;AACxB,QAAO;;AAGT,SAAS,aAAa,QAA8B;AAClD,QACG,OAAgC,UACjC,IAAI,aAAa,6BAA6B,aAAa;;;;AC7C/D,MAAa,+BAA+B;;;;;;AAO5C,SAAgB,iBAAiB,UAAsC;AACrE,KAAI,SAAS,cAAe,QAAO;AACnC,KAAI,SAAS,UAAU,KAAA,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,YAAY,MAAM;GAClB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,WAAW,GAAG,EAAE;GACvE,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC/D,CAAC;AACF,MAAI,OAAO,SAAS,gBAClB,OAAM,IAAI,MACR,yHACD;AAEH,SAAO;GAAE,KAAK,OAAO;GAAK,cAAc,OAAO;GAAc;;CAG/D,WACE,QACA,SACoD;AACpD,SAAO,mBACL,SACC,OAAO,UAAU,KAAK,OAAO,OAAO,aAAa,SAAS,MAAM,CAAC,EAClE,gBAAgB,OAAO,QAAQ,QAAQ,CACxC;;;;;;;;CASH,aACE,QACA,SACgD;AAChD,SAAO,mBACL,SACC,OAAO,UAAU,KAAK,SAAS,OAAO,aAAa,SAAS,MAAM,CAAC,EACpE,gBAAgB,OAAO,QAAQ,QAAQ,CACxC;;;AAIL,SAAgB,uBACd,SACmB;AACnB,QAAO,IAAI,qBAAqB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"sourcesContent":["/**\n * Ordered result of one batch item. `index` always mirrors the input\n * position, so callers can correlate results with inputs regardless of\n * completion order, and successes are retained when siblings fail.\n */\nexport type BatchItemResult<R> =\n | { index: number; status: \"fulfilled\"; value: R }\n | { index: number; status: \"rejected\"; error: unknown };\n\nexport type RunWithConcurrencyOptions<R = unknown> = {\n /** Maximum simultaneously running workers. Must be a positive integer. */\n concurrency: number;\n /**\n * Whole-batch cancellation: unstarted items are rejected with the signal's\n * reason without ever starting, while already-started items keep running —\n * per-item signals are the mechanism for interrupting active work.\n */\n signal?: AbortSignal;\n /**\n * Called once per item as it settles, in completion order, including items\n * the signal skipped before they ever started. That completeness is the\n * point: a caller counting settlements must still reach `items.length`\n * after a whole-batch abort.\n */\n onSettled?: (result: BatchItemResult<R>) => void;\n};\n\n/**\n * Runs `worker` over `items` with a hard upper bound on simultaneous\n * executions. Bounding starts (not just transfers) is what keeps memory flat:\n * an item's preprocessing (hashing/buffering) only begins when a slot frees.\n */\nexport async function runWithConcurrency<T, R>(\n items: readonly T[],\n worker: (item: T, index: number) => Promise<R>,\n options: RunWithConcurrencyOptions<R>,\n): Promise<BatchItemResult<R>[]> {\n const { concurrency, signal, onSettled } = options;\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new Error(\n `concurrency must be a positive integer, got: ${concurrency}`,\n );\n }\n\n const results: BatchItemResult<R>[] = new Array<BatchItemResult<R>>(\n items.length,\n );\n let nextIndex = 0;\n\n async function runLane(): Promise<void> {\n for (;;) {\n const index = nextIndex++;\n if (index >= items.length) return;\n if (signal?.aborted) {\n results[index] = {\n index,\n status: \"rejected\",\n error: signalReason(signal),\n };\n onSettled?.(results[index]);\n continue;\n }\n try {\n const value = await worker(items[index], index);\n results[index] = { index, status: \"fulfilled\", value };\n } catch (error) {\n results[index] = { index, status: \"rejected\", error };\n }\n onSettled?.(results[index]);\n }\n }\n\n const lanes = Array.from(\n { length: Math.min(concurrency, items.length) },\n () => runLane(),\n );\n await Promise.all(lanes);\n return results;\n}\n\nfunction signalReason(signal: AbortSignal): unknown {\n return (\n (signal as { reason?: unknown }).reason ??\n new DOMException(\"The operation was aborted\", \"AbortError\")\n );\n}\n","/**\n * Byte-level progress for attachment transfers.\n *\n * `loaded`/`total` are per-stage, never per-operation. A per-operation\n * denominator would have to weight hashing against transfer, and a confirmed\n * dedup would shrink it mid-flight from 2N to N — the bar would run backwards.\n * Choosing that weighting is a UI decision the client cannot make.\n */\n\nexport type AttachmentStage =\n | \"hashing\"\n | \"reserving\"\n | \"uploading\"\n | \"requesting-download-target\"\n | \"downloading\"\n | \"done\"\n | \"error\";\n\nexport type AttachmentProgress = {\n stage: AttachmentStage;\n /** Bytes moved so far within `stage`. */\n loaded: number;\n /** Denominator for `stage`: file.size for uploads, header.sizeBytes for downloads. */\n total: number | undefined;\n /** True when the stage is running but bytes cannot (yet) be observed. */\n indeterminate: boolean;\n /** Only on a terminal `done` where dedup skipped the transfer entirely. */\n deduped?: true;\n};\n\nexport type AttachmentProgressListener = (progress: AttachmentProgress) => void;\n\nexport type AttachmentProgressOptions = {\n onProgress?: AttachmentProgressListener;\n /** Min ms between byte events within a stage. Default 100. 0 emits every observation. */\n throttleMs?: number;\n};\n\nexport const DEFAULT_PROGRESS_THROTTLE_MS = 100;\n\n/**\n * Fraction in 0..1 for a progress event. Indeterminate and unknown-total\n * events read as 0 — a bar cannot honestly show a position it does not know.\n * A zero total is complete by definition (the dedup case moves no bytes).\n */\nexport function progressFraction(progress: AttachmentProgress): number {\n if (progress.indeterminate) return 0;\n if (progress.total === undefined) return 0;\n if (progress.total === 0) return 1;\n const fraction = progress.loaded / progress.total;\n if (fraction < 0) return 0;\n return fraction > 1 ? 1 : fraction;\n}\n\nexport type ProgressEmitterOptions = AttachmentProgressOptions & {\n /** Injected clock so throttle tests stay synchronous. */\n now?: () => number;\n};\n\n/**\n * Emits `AttachmentProgress` for one single-item operation, upholding:\n *\n * - **I1** exactly one terminal event (`done` or `error`) — never both, never twice.\n * - **I2** on `done`: `indeterminate === false`, `total` is a number, `loaded === total`.\n * - **I3** `loaded` is non-decreasing within a stage and resets to 0 on stage change.\n * - **I4** the terminal event bypasses the throttle unconditionally.\n * - **I5** `error` carries the last known `loaded`/`total`.\n *\n * Leading edge: the first `bytes()` after a `stage()` always emits, so a bar\n * leaves 0 immediately. There is deliberately no trailing-edge timer — it\n * would leak on throw, could fire after the terminal event and violate I1's\n * ordering, and is unnecessary because `finish()` always emits\n * `loaded === total`, making a dropped last intra-stage tick invisible.\n */\nexport class ProgressEmitter {\n private readonly listener: AttachmentProgressListener | undefined;\n private readonly throttleMs: number;\n private readonly now: () => number;\n\n private currentStage: AttachmentStage | undefined;\n private loaded = 0;\n private total: number | undefined;\n private emittedBytesInStage = false;\n private lastEmitAt = Number.NEGATIVE_INFINITY;\n private settled = false;\n\n constructor(options?: ProgressEmitterOptions) {\n this.listener = options?.onProgress;\n this.throttleMs = options?.throttleMs ?? DEFAULT_PROGRESS_THROTTLE_MS;\n this.now = options?.now ?? (() => Date.now());\n }\n\n /** True when a listener is attached; lets callers skip instrumentation entirely. */\n get active(): boolean {\n return this.listener !== undefined;\n }\n\n /**\n * Enter a stage. Always emits and resets `loaded` to 0. Entry is always\n * indeterminate: no bytes have moved yet, and whether they can be observed\n * at all is only proven by a transport actually calling back.\n */\n stage(stage: AttachmentStage, options?: { total?: number }): void {\n if (this.settled) return;\n this.currentStage = stage;\n this.loaded = 0;\n this.total = options?.total;\n this.emittedBytesInStage = false;\n this.emit({\n stage,\n loaded: 0,\n total: this.total,\n indeterminate: true,\n });\n }\n\n /**\n * Report observed bytes within the current stage. Throttled by time, with\n * the first observation after a stage change always emitted.\n */\n bytes(loaded: number, total?: number): void {\n if (this.settled || this.currentStage === undefined) return;\n if (total !== undefined) this.total = total;\n if (loaded > this.loaded) this.loaded = loaded;\n\n const leadingEdge = !this.emittedBytesInStage;\n if (!leadingEdge && this.now() - this.lastEmitAt < this.throttleMs) return;\n this.emittedBytesInStage = true;\n this.emit({\n stage: this.currentStage,\n loaded: this.loaded,\n total: this.total,\n indeterminate: false,\n });\n }\n\n /**\n * Terminal success. `total` defaults to the bytes actually seen so a stage\n * with no known denominator still satisfies I2.\n */\n finish(override?: { loaded?: number; total?: number; deduped?: true }): void {\n if (this.settled) return;\n this.settled = true;\n const total = override?.total ?? this.total ?? this.loaded;\n const loaded = override?.loaded ?? total;\n this.emit({\n stage: \"done\",\n loaded,\n total,\n indeterminate: false,\n ...(override?.deduped ? { deduped: true as const } : {}),\n });\n }\n\n /** Terminal success for a confirmed dedup: no bytes moved, and none needed to. */\n finishDeduped(): void {\n this.finish({ loaded: 0, total: 0, deduped: true });\n }\n\n /** Terminal failure, carrying the last known byte counts. */\n fail(): void {\n if (this.settled) return;\n this.settled = true;\n this.emit({\n stage: \"error\",\n loaded: this.loaded,\n total: this.total,\n indeterminate: false,\n });\n }\n\n private emit(progress: AttachmentProgress): void {\n this.lastEmitAt = this.now();\n this.listener?.(progress);\n }\n}\n\nexport type ByteProgressHooks = {\n /** Cumulative bytes handed to the consumer. */\n onBytes?: (loaded: number) => void;\n /** The source ended and every byte reached the consumer. */\n onDone?: () => void;\n onError?: (error: unknown) => void;\n};\n\n/**\n * Count bytes as a consumer reads them.\n *\n * Uses the manual-reader form rather than `pipeThrough`, whose internal queue\n * reads far ahead of the consumer and would make `loaded` overstate what was\n * actually received. `highWaterMark: 0` is load-bearing for the same reason:\n * at the default of 1 the wrapper pulls one chunk the instant it is\n * constructed, so a caller who never reads still sees bytes counted.\n *\n * `cancel` propagates to the source, which is what keeps reader refcounts\n * (e.g. `KyselyAttachmentStore`'s) correct. Cancelling is an abandonment, not\n * a completion, so it reports `onError` — never `onDone` — carrying the\n * cancel reason the way an `AbortSignal` carries its own, with the DOM's\n * default `AbortError` when the canceller gave none.\n *\n * Returns `source` unchanged when no hook is supplied, so a caller with no\n * listener pays nothing.\n */\nexport function withByteProgress(\n source: ReadableStream<Uint8Array>,\n hooks: ByteProgressHooks,\n): ReadableStream<Uint8Array> {\n if (!hooks.onBytes && !hooks.onDone && !hooks.onError) return source;\n\n let loaded = 0;\n let cancelled = false;\n const reader = source.getReader();\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n // A cancel that lands while this read is in flight resolves it as\n // `done`, and closes the stream. Bailing out here is what stops an\n // abandoned transfer from reporting completion, and stops the\n // already-closed controller from throwing a fabricated error into\n // the catch below.\n if (cancelled) return;\n if (done) {\n hooks.onDone?.();\n controller.close();\n return;\n }\n loaded += value.byteLength;\n hooks.onBytes?.(loaded);\n controller.enqueue(value);\n } catch (err) {\n if (cancelled) return;\n hooks.onError?.(err);\n controller.error(err);\n }\n },\n cancel(reason) {\n cancelled = true;\n reader.cancel(reason).catch(() => {});\n hooks.onError?.(reason ?? abortError());\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/** What an `AbortSignal` carries when `abort()` is called with no reason. */\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n runWithConcurrency,\n type BatchItemResult,\n type RunWithConcurrencyOptions,\n} from \"./concurrency.js\";\nimport { AttachmentAlreadyExists } from \"./errors.js\";\nexport type { AttachmentTransferStage } from \"./errors.js\";\nexport {\n runWithConcurrency,\n type BatchItemResult,\n type RunWithConcurrencyOptions,\n} from \"./concurrency.js\";\nimport type { IAttachmentService, IAttachmentUpload } from \"./interfaces.js\";\nimport {\n ProgressEmitter,\n withByteProgress,\n type AttachmentProgress,\n type AttachmentProgressOptions,\n} from \"./progress.js\";\nimport { createRef } from \"./ref.js\";\nimport { sha256HexOfBlob } from \"./replication/hash.js\";\nimport type {\n AttachmentHeader,\n AttachmentResponse,\n AttachmentSendOptions,\n AttachmentUploadResult,\n HashFirstReserveAttachmentOptions,\n} from \"./types.js\";\n\nexport { AttachmentService } from \"./attachment-service.js\";\nexport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n HashMismatch,\n InvalidAttachmentRef,\n ReservationNotFound,\n SizeMismatch,\n UploadTooLarge,\n} from \"./errors.js\";\nexport type {\n IAttachmentReader,\n IAttachmentService,\n IAttachmentStore,\n IAttachmentTransport,\n IAttachmentTransportFactory,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nexport { parseRef, createRef } from \"./ref.js\";\nexport type { ParsedRef } from \"./ref.js\";\nexport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n AttachmentSendOptions,\n AttachmentStatOptions,\n AttachmentStatus,\n AttachmentTransportConfig,\n AttachmentUploadResult,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n HashFirstReserveAttachmentOptions,\n UploadFirstReserveAttachmentOptions,\n Reservation,\n ReserveAttachmentOptions,\n TransportFetchResult,\n TransportResponse,\n} from \"./types.js\";\nexport {\n parseAttachmentDownloadTarget,\n parseAttachmentUploadTarget,\n} from \"./targets.js\";\nexport {\n SwitchboardAttachmentTransport,\n type SwitchboardTransportConfig,\n RemoteReservationStore,\n type SwitchboardClientConfig,\n RemoteAttachmentUpload,\n RemoteAttachmentUploadFactory,\n RemoteAttachmentStore,\n createRemoteAttachmentService,\n createFetchUploadTransport,\n createXhrUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n type XhrUploadTransportOptions,\n} from \"./switchboard/index.js\";\nexport { NullAttachmentTransport } from \"./null-attachment-transport.js\";\nexport {\n DEFAULT_PROGRESS_THROTTLE_MS,\n progressFraction,\n ProgressEmitter,\n withByteProgress,\n type AttachmentProgress,\n type AttachmentProgressListener,\n type AttachmentProgressOptions,\n type AttachmentStage,\n type ByteProgressHooks,\n type ProgressEmitterOptions,\n} from \"./progress.js\";\n\nexport type PreprocessResult = {\n ref: AttachmentRef;\n hash: AttachmentHash;\n sizeBytes: number;\n options: HashFirstReserveAttachmentOptions;\n /** @deprecated Read `blob`; this is `blob.stream()`. */\n data: ReadableStream<Uint8Array>;\n /** @deprecated Read `blob`; this is `() => blob.stream()`. */\n stream: () => ReadableStream<Uint8Array>;\n /** The file itself; uploads send it as-is, so a browser streams it from disk. */\n blob: Blob;\n};\n\nexport type AttachmentUploadInput = {\n file: Blob;\n fileName?: string;\n mimeType?: string;\n /** Per-item cancellation, checked between stages. */\n signal?: AbortSignal;\n};\n\n/**\n * Upload bytes that were already hashed by a separate `preprocess()` call.\n *\n * This is the canonical two-call flow: the ref must reach the document before\n * the bytes are committed, so callers preprocess, dispatch the operation, then\n * upload. Passing the result back in skips the hashing stage rather than\n * faking a zero-millisecond one.\n */\nexport type AttachmentPreprocessedUploadInput = {\n preprocessed: PreprocessResult;\n signal?: AbortSignal;\n};\n\n/**\n * Every remote download names the document that authorizes its ref; batches\n * may freely mix documents because the anchor travels with each item.\n */\nexport type AttachmentDownloadInput = {\n documentId: string;\n ref: AttachmentRef;\n signal?: AbortSignal;\n};\n\n/**\n * The document keeps its own name and type for an attachment (the same\n * bytes may appear under different names in different documents), so the\n * blob-producing conveniences let callers override what the server header\n * reports from upload time.\n */\nexport type AttachmentBlobOptions = {\n mimeType?: string;\n};\n\nexport type AttachmentSaveOptions = {\n fileName?: string;\n mimeType?: string;\n};\n\nexport type AttachmentBlobResult = {\n blob: Blob;\n header: AttachmentHeader;\n};\n\nexport type AttachmentObjectUrl = {\n /** Ready for img/iframe/video src. Pins memory until revoke() is called. */\n url: string;\n header: AttachmentHeader;\n revoke: () => void;\n};\n\nexport type AttachmentShareLinkInput = {\n documentId: string;\n ref: AttachmentRef;\n /** Requested link lifetime in seconds; the server clamps to its maximum. */\n expiresIn?: number;\n signal?: AbortSignal;\n};\n\n/**\n * A self-contained public URL: anyone holding it can fetch the bytes until\n * expiresAtUtc, with no login and no document access. Minting one requires\n * document read access; once minted it cannot be revoked before expiry.\n */\nexport type AttachmentShareLink = {\n url: string;\n expiresAtUtc: string;\n};\n\n/**\n * Batch progress is per item, carrying the item's `index`. There is\n * deliberately no batch-wide byte total: weighting items against each other is\n * a presentation decision the client cannot make, and a confirmed dedup would\n * shrink the denominator mid-flight.\n */\nexport type AttachmentBatchOptions = {\n /** Bounds preprocessing and transfer together. Defaults to 4. */\n concurrency?: number;\n /** Whole-batch cancellation: stops unstarted items. */\n signal?: AbortSignal;\n onProgress?: (progress: AttachmentProgress & { index: number }) => void;\n /**\n * Fired as each item settles, including items the signal skipped before they\n * started, so `settled` always reaches `total`.\n */\n onItemSettled?: (counts: AttachmentBatchCounts) => void;\n /** Min ms between byte events, applied per item rather than batch-wide. */\n throttleMs?: number;\n};\n\nexport type AttachmentBatchCounts = {\n settled: number;\n completed: number;\n failed: number;\n total: number;\n};\n\nexport const DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;\n\nexport interface IAttachmentClient {\n preprocess(\n file: Blob,\n opts?: { fileName?: string; mimeType?: string },\n ): Promise<PreprocessResult>;\n reserve(\n options: HashFirstReserveAttachmentOptions,\n send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>,\n ): Promise<AttachmentUploadResult>;\n /**\n * Hash, reserve, and transfer one file; a confirmed dedup skips the transfer\n * and reports a terminal `done` carrying `deduped: true` and zero bytes.\n *\n * Also accepts an already-preprocessed payload, so the canonical\n * preprocess -> dispatch -> upload flow reports progress too.\n */\n upload(\n input: AttachmentUploadInput | AttachmentPreprocessedUploadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentUploadResult>;\n /**\n * Document-authorized download of one ref.\n *\n * Resolves as soon as the byte stream is available, with `downloading` as\n * the last event emitted and `loaded: 0`. Byte events and the terminal\n * `done` arrive as the caller reads the stream — and never arrive at all if\n * the caller abandons it.\n */\n download(\n input: AttachmentDownloadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentResponse>;\n /**\n * Document-authorized download materialized as a typed Blob. The Blob's\n * type comes from the server header unless overridden — that's what makes\n * browsers render PDFs inline and images correctly.\n */\n downloadBlob(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentBlobResult>;\n /**\n * Download and hand the bytes to the browser's save-file flow. Browser\n * only. fileName defaults to the server header's; pass the document's own\n * name for per-document naming.\n */\n saveAttachment(\n input: AttachmentDownloadInput,\n options?: AttachmentSaveOptions & AttachmentProgressOptions,\n ): Promise<void>;\n /**\n * Download and expose the bytes as an object URL for inline rendering\n * (img/iframe/video src). Callers MUST call revoke() when done — the URL\n * pins the blob in memory until then.\n */\n downloadObjectUrl(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentObjectUrl>;\n /**\n * Mint a public share link: a presigned URL anyone can fetch until it\n * expires, with no login. Authorized exactly like a download (document\n * read access + the reference index). Requires a presigned-capable\n * storage backend (S3); rejects when the server answers with an\n * authenticated switchboard target, which would not be public.\n */\n getShareLink(input: AttachmentShareLinkInput): Promise<AttachmentShareLink>;\n uploadMany(\n inputs: readonly AttachmentUploadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentUploadResult>[]>;\n downloadMany(\n inputs: readonly AttachmentDownloadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentResponse>[]>;\n}\n\n/**\n * Duck-typed dedup detection: bundlers (notably Vite dev pre-bundling) can\n * load two copies of this package's error classes, one for the service and\n * one for the client wrapper, making a plain instanceof check miss the\n * cross-copy throw. Name plus payload shape identifies the error reliably.\n */\nfunction isAttachmentAlreadyExists(\n err: unknown,\n): err is AttachmentAlreadyExists {\n if (err instanceof AttachmentAlreadyExists) return true;\n return (\n err instanceof Error &&\n err.name === \"AttachmentAlreadyExists\" &&\n typeof (err as { hash?: unknown }).hash === \"string\" &&\n typeof (err as { ref?: unknown }).ref === \"string\"\n );\n}\n\n// Nothing references the blob yet, so the server header is not readable.\nfunction dedupedHeader(\n hash: AttachmentHash,\n options: HashFirstReserveAttachmentOptions,\n): AttachmentHeader {\n const now = new Date().toISOString();\n return {\n hash,\n mimeType: options.mimeType,\n fileName: options.fileName,\n sizeBytes: options.sizeBytes,\n extension: options.extension ?? null,\n status: \"available\",\n source: \"local\",\n createdAtUtc: now,\n lastAccessedAtUtc: now,\n expiresAtUtc: null,\n };\n}\n\n/** Stamps an item's index onto its progress events. */\nfunction itemProgress(\n options: AttachmentBatchOptions | undefined,\n index: number,\n): AttachmentProgressOptions | undefined {\n if (!options?.onProgress && options?.throttleMs === undefined) {\n return undefined;\n }\n return {\n ...(options.onProgress\n ? {\n onProgress: (progress: AttachmentProgress) =>\n options.onProgress?.({ ...progress, index }),\n }\n : {}),\n ...(options.throttleMs !== undefined\n ? { throttleMs: options.throttleMs }\n : {}),\n };\n}\n\nfunction batchRunOptions<R>(\n total: number,\n options: AttachmentBatchOptions | undefined,\n): RunWithConcurrencyOptions<R> {\n const onItemSettled = options?.onItemSettled;\n let settled = 0;\n let completed = 0;\n let failed = 0;\n return {\n concurrency: options?.concurrency ?? DEFAULT_ATTACHMENT_BATCH_CONCURRENCY,\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(onItemSettled\n ? {\n onSettled: (result: BatchItemResult<R>) => {\n settled += 1;\n if (result.status === \"fulfilled\") completed += 1;\n else failed += 1;\n onItemSettled({ settled, completed, failed, total });\n },\n }\n : {}),\n };\n}\n\nclass AttachmentClientImpl implements IAttachmentClient {\n constructor(private readonly service: IAttachmentService) {}\n\n preprocess(\n file: Blob,\n opts?: { fileName?: string; mimeType?: string },\n ): Promise<PreprocessResult> {\n return this.hashFile(file, opts);\n }\n\n private async hashFile(\n file: Blob,\n opts?: { fileName?: string; mimeType?: string },\n signal?: AbortSignal,\n ): Promise<PreprocessResult> {\n const hash = await sha256HexOfBlob(file, signal ? { signal } : undefined);\n const ref = createRef(hash);\n const sizeBytes = file.size;\n const mimeType = opts?.mimeType ?? file.type;\n const fileName =\n opts?.fileName ?? (file instanceof File ? file.name : \"attachment\");\n const options: HashFirstReserveAttachmentOptions = {\n mimeType,\n fileName,\n clientHash: hash,\n sizeBytes,\n };\n const data = file.stream();\n const stream = (): ReadableStream<Uint8Array> => file.stream();\n return { ref, hash, sizeBytes, options, data, stream, blob: file };\n }\n\n /**\n * Reserve, distinguishing a confirmed dedup from a live upload handle in the\n * type rather than with a flag: the two outcomes move a different number of\n * bytes, and every caller has to account for that.\n */\n private async reserveOrDedup(\n options: HashFirstReserveAttachmentOptions,\n ): Promise<\n | { kind: \"handle\"; handle: IAttachmentUpload }\n | { kind: \"deduped\"; result: AttachmentUploadResult }\n > {\n try {\n return { kind: \"handle\", handle: await this.service.reserve(options) };\n } catch (err) {\n if (!isAttachmentAlreadyExists(err)) throw err;\n return {\n kind: \"deduped\",\n result: {\n hash: err.hash,\n ref: err.ref,\n header: dedupedHeader(err.hash, options),\n },\n };\n }\n }\n\n async reserve(\n options: HashFirstReserveAttachmentOptions,\n send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>,\n ): Promise<AttachmentUploadResult> {\n const outcome = await this.reserveOrDedup(options);\n if (outcome.kind === \"deduped\") return outcome.result;\n return send(outcome.handle);\n }\n\n async upload(\n input: AttachmentUploadInput | AttachmentPreprocessedUploadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentUploadResult> {\n const emitter = new ProgressEmitter(options);\n const signal = input.signal;\n try {\n signal?.throwIfAborted();\n\n let preprocessed: PreprocessResult;\n if (\"preprocessed\" in input) {\n preprocessed = input.preprocessed;\n } else {\n // Hashing reports no bytes, so the stage stays indeterminate; a UI\n // can still name the wait. The signal stops it between slices.\n emitter.stage(\"hashing\", { total: input.file.size });\n preprocessed = await this.hashFile(\n input.file,\n {\n ...(input.fileName !== undefined\n ? { fileName: input.fileName }\n : {}),\n ...(input.mimeType !== undefined\n ? { mimeType: input.mimeType }\n : {}),\n },\n signal,\n );\n }\n const sizeBytes = preprocessed.sizeBytes;\n\n signal?.throwIfAborted();\n emitter.stage(\"reserving\");\n const outcome = await this.reserveOrDedup(preprocessed.options);\n\n // A confirmed dedup never enters `uploading` — the server already holds\n // these bytes, so none are sent. Reporting zero of zero keeps the byte\n // model honest instead of stalling at 0 and then jumping to done.\n if (outcome.kind === \"deduped\") {\n emitter.finishDeduped();\n return outcome.result;\n }\n\n signal?.throwIfAborted();\n emitter.stage(\"uploading\", { total: sizeBytes });\n // `onProgress` only when someone is listening. The XHR transport keys\n // its `upload.onprogress` registration off the option being present, and\n // that registration alone forces a CORS preflight on a presigned PUT —\n // a cost an unwatched upload must not pay for a callback that would\n // discard every event anyway.\n const sendOptions: AttachmentSendOptions = {\n ...(emitter.active\n ? {\n onProgress: (loaded: number, total?: number) =>\n emitter.bytes(loaded, total ?? sizeBytes),\n }\n : {}),\n ...(signal ? { signal } : {}),\n };\n const result = await outcome.handle.send(preprocessed.blob, sendOptions);\n emitter.finish();\n return result;\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n /**\n * The single site where download bytes are instrumented.\n *\n * It sits here, above the service, rather than in any store or transport:\n * one logical get can be several byte streams underneath (an evicted\n * attachment is fetched from the transport, written to disk, then re-read),\n * so counting lower down would double-count that path and still miss\n * local-filesystem reads. Wrapping what `service.get` returns covers the\n * presigned, switchboard, legacy and local paths by construction, and\n * `downloadBlob`/`saveAttachment`/`downloadObjectUrl` inherit it.\n */\n private async getWithProgress(\n input: AttachmentDownloadInput,\n emitter: ProgressEmitter,\n ): Promise<AttachmentResponse> {\n const { header, body } = await this.service.get(input.ref, {\n documentId: input.documentId,\n signal: input.signal,\n });\n emitter.stage(\"downloading\", { total: header.sizeBytes });\n if (!emitter.active) return { header, body };\n return {\n header,\n body: withByteProgress(body, {\n onBytes: (loaded) => emitter.bytes(loaded),\n onDone: () => emitter.finish(),\n onError: () => emitter.fail(),\n }),\n };\n }\n\n async download(\n input: AttachmentDownloadInput,\n options?: AttachmentProgressOptions,\n ): Promise<AttachmentResponse> {\n const emitter = new ProgressEmitter(options);\n try {\n input.signal?.throwIfAborted();\n emitter.stage(\"requesting-download-target\");\n return await this.getWithProgress(input, emitter);\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n async downloadBlob(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentBlobResult> {\n const emitter = new ProgressEmitter(options);\n try {\n input.signal?.throwIfAborted();\n emitter.stage(\"requesting-download-target\");\n const { header, body } = await this.getWithProgress(input, emitter);\n const reader = body.getReader();\n const chunks: BlobPart[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value as BlobPart);\n }\n const blob = new Blob(chunks, {\n type: options?.mimeType ?? header.mimeType,\n });\n // Draining the stream already finished the emitter; latching makes this\n // a no-op there, and a guarantee for any body that closes without one.\n emitter.finish();\n return { blob, header };\n } catch (err) {\n emitter.fail();\n throw err;\n }\n }\n\n async saveAttachment(\n input: AttachmentDownloadInput,\n options?: AttachmentSaveOptions & AttachmentProgressOptions,\n ): Promise<void> {\n if (typeof document === \"undefined\") {\n throw new Error(\n \"saveAttachment requires a browser environment; use downloadBlob elsewhere\",\n );\n }\n const { blob, header } = await this.downloadBlob(input, options);\n const url = URL.createObjectURL(blob);\n try {\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = options?.fileName ?? header.fileName;\n anchor.click();\n } finally {\n URL.revokeObjectURL(url);\n }\n }\n\n async downloadObjectUrl(\n input: AttachmentDownloadInput,\n options?: AttachmentBlobOptions & AttachmentProgressOptions,\n ): Promise<AttachmentObjectUrl> {\n const { blob, header } = await this.downloadBlob(input, options);\n const url = URL.createObjectURL(blob);\n let revoked = false;\n return {\n url,\n header,\n revoke: () => {\n if (revoked) return;\n revoked = true;\n URL.revokeObjectURL(url);\n },\n };\n }\n\n async getShareLink(\n input: AttachmentShareLinkInput,\n ): Promise<AttachmentShareLink> {\n input.signal?.throwIfAborted();\n const target = await this.service.getDownloadTarget(input.ref, {\n documentId: input.documentId,\n ...(input.expiresIn !== undefined ? { expiresIn: input.expiresIn } : {}),\n ...(input.signal !== undefined ? { signal: input.signal } : {}),\n });\n if (target.kind !== \"presigned-get\") {\n throw new Error(\n \"Public share links require a presigned-capable storage backend (S3); this server answered with an authenticated target\",\n );\n }\n return { url: target.url, expiresAtUtc: target.expiresAtUtc };\n }\n\n uploadMany(\n inputs: readonly AttachmentUploadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentUploadResult>[]> {\n return runWithConcurrency(\n inputs,\n (input, index) => this.upload(input, itemProgress(options, index)),\n batchRunOptions(inputs.length, options),\n );\n }\n\n /**\n * `concurrency` bounds download-target negotiation, not simultaneous byte\n * transfer: each item resolves when its stream is handed over, and the bytes\n * move only as the caller reads. Byte progress makes that pre-existing\n * behavior visible; it does not change it.\n */\n downloadMany(\n inputs: readonly AttachmentDownloadInput[],\n options?: AttachmentBatchOptions,\n ): Promise<BatchItemResult<AttachmentResponse>[]> {\n return runWithConcurrency(\n inputs,\n (input, index) => this.download(input, itemProgress(options, index)),\n batchRunOptions(inputs.length, options),\n );\n }\n}\n\nexport function createAttachmentClient(\n service: IAttachmentService,\n): IAttachmentClient {\n return new AttachmentClientImpl(service);\n}\n"],"mappings":";;;;;;;;;AAgCA,eAAsB,mBACpB,OACA,QACA,SAC+B;CAC/B,MAAM,EAAE,aAAa,QAAQ,cAAc;CAC3C,IAAI,CAAC,OAAO,UAAU,WAAW,KAAK,cAAc,GAClD,MAAM,IAAI,MACR,gDAAgD,aAClD;CAGF,MAAM,UAAgC,IAAI,MACxC,MAAM,MACR;CACA,IAAI,YAAY;CAEhB,eAAe,UAAyB;EACtC,SAAS;GACP,MAAM,QAAQ;GACd,IAAI,SAAS,MAAM,QAAQ;GAC3B,IAAI,QAAQ,SAAS;IACnB,QAAQ,SAAS;KACf;KACA,QAAQ;KACR,OAAO,aAAa,MAAM;IAC5B;IACA,YAAY,QAAQ,MAAM;IAC1B;GACF;GACA,IAAI;IACF,MAAM,QAAQ,MAAM,OAAO,MAAM,QAAQ,KAAK;IAC9C,QAAQ,SAAS;KAAE;KAAO,QAAQ;KAAa;IAAM;GACvD,SAAS,OAAO;IACd,QAAQ,SAAS;KAAE;KAAO,QAAQ;KAAY;IAAM;GACtD;GACA,YAAY,QAAQ,MAAM;EAC5B;CACF;CAEA,MAAM,QAAQ,MAAM,KAClB,EAAE,QAAQ,KAAK,IAAI,aAAa,MAAM,MAAM,EAAE,SACxC,QAAQ,CAChB;CACA,MAAM,QAAQ,IAAI,KAAK;CACvB,OAAO;AACT;AAEA,SAAS,aAAa,QAA8B;CAClD,OACG,OAAgC,UACjC,IAAI,aAAa,6BAA6B,YAAY;AAE9D;;;AC/CA,MAAa,+BAA+B;;;;;;AAO5C,SAAgB,iBAAiB,UAAsC;CACrE,IAAI,SAAS,eAAe,OAAO;CACnC,IAAI,S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;GACzB;EACF;CACF;CAEA,MAAM,aACJ,OAC8B;EAC9B,MAAM,QAAQ,eAAe;EAC7B,MAAM,SAAS,MAAM,KAAK,QAAQ,kBAAkB,MAAM,KAAK;GAC7D,YAAY,MAAM;GAClB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;GACtE,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;EAC/D,CAAC;EACD,IAAI,OAAO,SAAS,iBAClB,MAAM,IAAI,MACR,wHACF;EAEF,OAAO;GAAE,KAAK,OAAO;GAAK,cAAc,OAAO;EAAa;CAC9D;CAEA,WACE,QACA,SACoD;EACpD,OAAO,mBACL,SACC,OAAO,UAAU,KAAK,OAAO,OAAO,aAAa,SAAS,KAAK,CAAC,GACjE,gBAAgB,OAAO,QAAQ,OAAO,CACxC;CACF;;;;;;;CAQA,aACE,QACA,SACgD;EAChD,OAAO,mBACL,SACC,OAAO,UAAU,KAAK,SAAS,OAAO,aAAa,SAAS,KAAK,CAAC,GACnE,gBAAgB,OAAO,QAAQ,OAAO,CACxC;CACF;AACF;AAEA,SAAgB,uBACd,SACmB;CACnB,OAAO,IAAI,qBAAqB,OAAO;AACzC"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
2
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
3
|
+
const nodeCrypto = globalThis.process?.getBuiltinModule?.("node:crypto");
|
|
4
|
+
/** Native SHA-256 from node:crypto, or undefined outside Node. */
|
|
5
|
+
function nodeSha256() {
|
|
6
|
+
if (!nodeCrypto) return void 0;
|
|
7
|
+
const hash = nodeCrypto.createHash("sha256");
|
|
8
|
+
return {
|
|
9
|
+
update: (bytes) => void hash.update(bytes),
|
|
10
|
+
hex: () => hash.digest("hex")
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** SHA-256 in JavaScript, for browsers; about 10x slower than native. */
|
|
14
|
+
function jsSha256() {
|
|
15
|
+
const hash = sha256.create();
|
|
16
|
+
return {
|
|
17
|
+
update: (bytes) => void hash.update(bytes),
|
|
18
|
+
hex: () => bytesToHex(hash.digest())
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Lowercase SHA-256 hex of `bytes` -- the `attachment://v1:` hash format
|
|
23
|
+
* (`packages/reactor/src/attachments/types.ts`).
|
|
24
|
+
*
|
|
25
|
+
* WebCrypto, so the same code runs in Node and in a browser realm. There is no
|
|
26
|
+
* streaming digest in WebCrypto, which is why verification happens over
|
|
27
|
+
* collected bytes.
|
|
28
|
+
*/
|
|
29
|
+
async function sha256Hex(bytes) {
|
|
30
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", digestable(bytes));
|
|
31
|
+
return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
32
|
+
}
|
|
33
|
+
/** WebCrypto refuses a SharedArrayBuffer-backed view, so only that one is copied. */
|
|
34
|
+
function digestable(bytes) {
|
|
35
|
+
if (typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) {
|
|
36
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
37
|
+
copy.set(bytes);
|
|
38
|
+
return copy;
|
|
39
|
+
}
|
|
40
|
+
return bytes;
|
|
41
|
+
}
|
|
42
|
+
/** Same digest as `sha256Hex`, in bounded memory: natively in slices in Node, and in a
|
|
43
|
+
* browser whole up to `oneShotMaxBytes`, then in JavaScript slices (no ~2 GB read). */
|
|
44
|
+
async function sha256HexOfBlob(blob, options) {
|
|
45
|
+
const chunkBytes = options?.chunkBytes ?? 8388608;
|
|
46
|
+
if (!Number.isInteger(chunkBytes) || chunkBytes <= 0) throw new RangeError("chunkBytes must be a positive integer");
|
|
47
|
+
options?.signal?.throwIfAborted();
|
|
48
|
+
let hasher = (options?.native ?? nodeSha256)();
|
|
49
|
+
if (!hasher) {
|
|
50
|
+
if (blob.size <= (options?.oneShotMaxBytes ?? 268435456)) return sha256Hex(new Uint8Array(await blob.arrayBuffer()));
|
|
51
|
+
hasher = jsSha256();
|
|
52
|
+
}
|
|
53
|
+
for (let offset = 0; offset < blob.size; offset += chunkBytes) {
|
|
54
|
+
options?.signal?.throwIfAborted();
|
|
55
|
+
const chunk = blob.slice(offset, offset + chunkBytes);
|
|
56
|
+
hasher.update(new Uint8Array(await chunk.arrayBuffer()));
|
|
57
|
+
}
|
|
58
|
+
return hasher.hex();
|
|
59
|
+
}
|
|
60
|
+
//#endregion
|
|
61
|
+
export { sha256HexOfBlob as n, sha256Hex as t };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=hash-BobbR4r4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash-BobbR4r4.js","names":[],"sources":["../src/replication/hash.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport type { AttachmentHash } from \"@powerhousedao/reactor\";\n\n/** Bytes read per `Blob.slice` when hashing a Blob incrementally. */\nexport const DEFAULT_HASH_CHUNK_BYTES = 8 * 1024 * 1024;\n\n/** Largest Blob a browser hashes in one native WebCrypto call; it is held in memory. */\nexport const ONE_SHOT_HASH_MAX_BYTES = 256 * 1024 * 1024;\n\n/** An incremental SHA-256: WebCrypto has none, so these fill the gap. */\nexport type IncrementalSha256 = {\n update(bytes: Uint8Array): void;\n hex(): string;\n};\n\ntype NodeCrypto = {\n createHash(algorithm: \"sha256\"): {\n update(bytes: Uint8Array): unknown;\n digest(encoding: \"hex\"): string;\n };\n};\n\n// A call, not an import, so browser bundles never see node:crypto.\nconst nodeCrypto = (\n globalThis as {\n process?: { getBuiltinModule?: (id: string) => unknown };\n }\n).process?.getBuiltinModule?.(\"node:crypto\") as NodeCrypto | undefined;\n\n/** Native SHA-256 from node:crypto, or undefined outside Node. */\nexport function nodeSha256(): IncrementalSha256 | undefined {\n if (!nodeCrypto) return undefined;\n const hash = nodeCrypto.createHash(\"sha256\");\n return {\n update: (bytes) => void hash.update(bytes),\n hex: () => hash.digest(\"hex\"),\n };\n}\n\n/** SHA-256 in JavaScript, for browsers; about 10x slower than native. */\nexport function jsSha256(): IncrementalSha256 {\n const hash = sha256.create();\n return {\n update: (bytes) => void hash.update(bytes),\n hex: () => bytesToHex(hash.digest()),\n };\n}\n\n/**\n * Lowercase SHA-256 hex of `bytes` -- the `attachment://v1:` hash format\n * (`packages/reactor/src/attachments/types.ts`).\n *\n * WebCrypto, so the same code runs in Node and in a browser realm. There is no\n * streaming digest in WebCrypto, which is why verification happens over\n * collected bytes.\n */\nexport async function sha256Hex(bytes: Uint8Array): Promise<AttachmentHash> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n digestable(bytes),\n );\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/** WebCrypto refuses a SharedArrayBuffer-backed view, so only that one is copied. */\nfunction digestable(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n if (\n typeof SharedArrayBuffer !== \"undefined\" &&\n bytes.buffer instanceof SharedArrayBuffer\n ) {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n }\n return bytes as Uint8Array<ArrayBuffer>;\n}\n\nexport type BlobHashOptions = {\n chunkBytes?: number;\n /** Without a native hasher: up to this size, one WebCrypto call over the whole Blob. */\n oneShotMaxBytes?: number;\n /** The native incremental hasher; defaults to node:crypto, absent in a browser. */\n native?: () => IncrementalSha256 | undefined;\n signal?: AbortSignal;\n};\n\n/** Same digest as `sha256Hex`, in bounded memory: natively in slices in Node, and in a\n * browser whole up to `oneShotMaxBytes`, then in JavaScript slices (no ~2 GB read). */\nexport async function sha256HexOfBlob(\n blob: Blob,\n options?: BlobHashOptions,\n): Promise<AttachmentHash> {\n const chunkBytes = options?.chunkBytes ?? DEFAULT_HASH_CHUNK_BYTES;\n if (!Number.isInteger(chunkBytes) || chunkBytes <= 0) {\n throw new RangeError(\"chunkBytes must be a positive integer\");\n }\n options?.signal?.throwIfAborted();\n let hasher = (options?.native ?? nodeSha256)();\n if (!hasher) {\n if (blob.size <= (options?.oneShotMaxBytes ?? ONE_SHOT_HASH_MAX_BYTES)) {\n return sha256Hex(new Uint8Array(await blob.arrayBuffer()));\n }\n hasher = jsSha256();\n }\n for (let offset = 0; offset < blob.size; offset += chunkBytes) {\n options?.signal?.throwIfAborted();\n const chunk = blob.slice(offset, offset + chunkBytes);\n hasher.update(new Uint8Array(await chunk.arrayBuffer()));\n }\n return hasher.hex();\n}\n"],"mappings":";;AAwBA,MAAM,aACJ,WAGA,SAAS,mBAAmB,aAAa;;AAG3C,SAAgB,aAA4C;CAC1D,IAAI,CAAC,YAAY,OAAO,KAAA;CACxB,MAAM,OAAO,WAAW,WAAW,QAAQ;CAC3C,OAAO;EACL,SAAS,UAAU,KAAK,KAAK,OAAO,KAAK;EACzC,WAAW,KAAK,OAAO,KAAK;CAC9B;AACF;;AAGA,SAAgB,WAA8B;CAC5C,MAAM,OAAO,OAAO,OAAO;CAC3B,OAAO;EACL,SAAS,UAAU,KAAK,KAAK,OAAO,KAAK;EACzC,WAAW,WAAW,KAAK,OAAO,CAAC;CACrC;AACF;;;;;;;;;AAUA,eAAsB,UAAU,OAA4C;CAC1E,MAAM,SAAS,MAAM,WAAW,OAAO,OAAO,OAC5C,WACA,WAAW,KAAK,CAClB;CACA,OAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,CAAC,CACtC,KAAK,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CACjD,KAAK,EAAE;AACZ;;AAGA,SAAS,WAAW,OAA4C;CAC9D,IACE,OAAO,sBAAsB,eAC7B,MAAM,kBAAkB,mBACxB;EACA,MAAM,OAAO,IAAI,WAAW,MAAM,UAAU;EAC5C,KAAK,IAAI,KAAK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