@powerhousedao/reactor-attachments 6.2.3-dev.81 → 6.2.3-dev.83

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/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as InvalidAttachmentRef, D as AttachmentTransferStage, E as AttachmentTransferError, M as SizeMismatch, N as UploadTooLarge, O as HashMismatch, S as AttachmentAlreadyExists, T as AttachmentPending, _ as createRef, a as RemoteAttachmentUpload, b as parseAttachmentDownloadTarget, c as XhrUploadTransportOptions, d as AttachmentUploadResponse, f as AttachmentUploadTransport, g as ParsedRef, h as SwitchboardTransportConfig, i as RemoteAttachmentUploadFactory, j as ReservationNotFound, l as createXhrUploadTransport, m as SwitchboardAttachmentTransport, n as createRemoteAttachmentService, o as RemoteReservationStore, p as createFetchUploadTransport, r as RemoteAttachmentStore, s as SwitchboardClientConfig, t as NullAttachmentTransport, u as AttachmentUploadRequest, v as parseRef, w as AttachmentNotFound, x as parseAttachmentUploadTarget, y as AttachmentService } from "./null-attachment-transport-Bs4JpmFx.js";
2
- import { A as UploadFirstReserveAttachmentOptions, C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, S as AttachmentTransportConfig, T as HashFirstReserveAttachmentOptions, _ as AttachmentResponse, a as IAttachmentTransport, b as AttachmentStatus, c as IAttachmentUploadFactory, f as AttachmentDownloadOptions, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore, k as TransportResponse, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, o as IAttachmentTransportFactory, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, v as AttachmentSendOptions, w as AttachmentUploadTarget, x as AttachmentTargetHeaders, y as AttachmentStatOptions } from "./interfaces-C4GRlKeB.js";
1
+ import { A as HashMismatch, C as parseAttachmentUploadTarget, D as AttachmentPending, E as AttachmentNotFound, F as UploadTooLarge, M as InvalidAttachmentRef, N as ReservationNotFound, O as AttachmentTransferError, P as SizeMismatch, S as parseAttachmentDownloadTarget, _ as SwitchboardTransportConfig, a as RemoteAttachmentStore, b as parseRef, c as RemoteReservationStore, d as createXhrUploadTransport, f as AttachmentUploadRequest, g as SwitchboardAttachmentTransport, h as createFetchUploadTransport, i as createRemoteAttachmentService, k as AttachmentTransferStage, l as SwitchboardClientConfig, m as AttachmentUploadTransport, n as RoutingAttachmentService, o as RemoteAttachmentUploadFactory, p as AttachmentUploadResponse, r as NullAttachmentTransport, s as RemoteAttachmentUpload, t as AttachmentRouteResolver, u as XhrUploadTransportOptions, v as ParsedRef, w as AttachmentAlreadyExists, x as AttachmentService, y as createRef } from "./routing-attachment-service-Dri6e2Vz.js";
2
+ import { A as UploadFirstReserveAttachmentOptions, C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, S as AttachmentTransportConfig, T as HashFirstReserveAttachmentOptions, _ as AttachmentResponse, a as IAttachmentTransport, b as AttachmentStatus, c as IAttachmentUploadFactory, f as AttachmentDownloadOptions, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore, k as TransportResponse, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, o as IAttachmentTransportFactory, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, v as AttachmentSendOptions, w as AttachmentUploadTarget, x as AttachmentTargetHeaders, y as AttachmentStatOptions } from "./interfaces-cFMtcMqR.js";
3
3
  import { AttachmentHash, AttachmentRef } from "@powerhousedao/reactor";
4
4
  //#region src/concurrency.d.ts
5
5
  /**
@@ -162,6 +162,12 @@ type ByteProgressHooks = {
162
162
  export declare function withByteProgress(source: ReadableStream<Uint8Array>, hooks: ByteProgressHooks): ReadableStream<Uint8Array>;
163
163
  //#endregion
164
164
  //#region src/client.d.ts
165
+ export type PreprocessOptions = {
166
+ fileName?: string;
167
+ mimeType?: string;
168
+ /** The document the attachment is for; see `ReserveAttachmentOptions`. */
169
+ documentId?: string;
170
+ };
165
171
  export type PreprocessResult = {
166
172
  ref: AttachmentRef;
167
173
  hash: AttachmentHash;
@@ -178,6 +184,8 @@ export type AttachmentUploadInput = {
178
184
  file: Blob;
179
185
  fileName?: string;
180
186
  mimeType?: string;
187
+ /** The document the attachment is for; see `ReserveAttachmentOptions`. */
188
+ documentId?: string;
181
189
  /** Per-item cancellation, checked between stages. */
182
190
  signal?: AbortSignal;
183
191
  };
@@ -271,10 +279,7 @@ export type AttachmentBatchCounts = {
271
279
  };
272
280
  export declare const DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;
273
281
  export interface IAttachmentClient {
274
- preprocess(file: Blob, opts?: {
275
- fileName?: string;
276
- mimeType?: string;
277
- }): Promise<PreprocessResult>;
282
+ preprocess(file: Blob, opts?: PreprocessOptions): Promise<PreprocessResult>;
278
283
  reserve(options: HashFirstReserveAttachmentOptions, send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>): Promise<AttachmentUploadResult>;
279
284
  /**
280
285
  * Hash, reserve, and transfer one file; a confirmed dedup skips the transfer
@@ -324,6 +329,6 @@ export interface IAttachmentClient {
324
329
  }
325
330
  export declare function createAttachmentClient(service: IAttachmentService): IAttachmentClient;
326
331
  //#endregion
327
- export { AttachmentAlreadyExists, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, AttachmentNotFound, AttachmentPending, type AttachmentProgress, type AttachmentProgressListener, type AttachmentProgressOptions, type AttachmentResponse, type AttachmentSendOptions, AttachmentService, type AttachmentStage, type AttachmentStatOptions, type AttachmentStatus, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type BatchItemResult, type ByteProgressHooks, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentReader, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, type ProgressEmitterOptions, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, type RunWithConcurrencyOptions, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
332
+ export { AttachmentAlreadyExists, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, AttachmentNotFound, AttachmentPending, type AttachmentProgress, type AttachmentProgressListener, type AttachmentProgressOptions, type AttachmentResponse, type AttachmentRouteResolver, type AttachmentSendOptions, AttachmentService, type AttachmentStage, type AttachmentStatOptions, type AttachmentStatus, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type BatchItemResult, type ByteProgressHooks, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentReader, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, type ProgressEmitterOptions, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, RoutingAttachmentService, type RunWithConcurrencyOptions, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
328
333
  export {};
329
334
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"mappings":";;;;;;;;;KAKY,gBAAgB;EACtB;EAAe;EAAqB,OAAO;;EAC3C;EAAe;EAAoB;;KAE7B,0BAA0B;;EAEpC;;;;;;EAMA,SAAS;;;;;;;EAOT,aAAa,QAAQ,gBAAgB;;;;;;;wBAQjB,mBAAmB,GAAG,GAC1C,gBAAgB,KAChB,SAAS,MAAM,GAAG,kBAAkB,QAAQ,IAC5C,SAAS,0BAA0B,KAClC,QAAQ,gBAAgB;;;;;;;;;;;KC3Bf;KASA;EACV,OAAO;;EAEP;;EAEA;;EAEA;;EAEA;;KAGU,8BAA8B,UAAU;KAExC;EACV,aAAa;;EAEb;;qBAGW;;;;;;wBAOG,iBAAiB,UAAU;KAS/B,yBAAyB;;EAEnC;;;;;;;;;;;;;;;;;qBAkBW;mBACM;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAU;;MAOlB;;;;;;EASJ,MAAM,OAAO,iBAAiB;IAAY;;;;;;EAkB1C,MAAM,gBAAgB;;;;;EAoBtB,OAAO;IAAa;IAAiB;IAAgB;;;EAerD;;EAKA;UAWQ;;KAME;;EAEV,WAAW;;EAEX;EACA,WAAW;;;;;;;;;;;;;;;;;;;;wBAqBG,iBACd,QAAQ,eAAe,aACvB,OAAO,oBACN,eAAe;;;YCjGN;EACV,KAAK;EACL,MAAM;EACN;EACA,SAAS;;EAET,MAAM,eAAe;;EAErB,cAAc,eAAe;;EAE7B,MAAM;;YAGI;EACV,MAAM;EACN;EACA;;EAEA,SAAS;;;;;;;;;;YAWC;EACV,cAAc;EACd,SAAS;;;;;;YAOC;EACV;EACA,KAAK;EACL,SAAS;;;;;;;;YASC;EACV;;YAGU;EACV;EACA;;YAGU;EACV,MAAM;EACN,QAAQ;;YAGE;;EAEV;EACA,QAAQ;EACR;;YAGU;EACV;EACA,KAAK;;EAEL;EACA,SAAS;;;;;;;YAQC;EACV;EACA;;;;;;;;YASU;;EAEV;;EAEA,SAAS;EACT,cAAc,UAAU;IAAuB;;;;;;EAK/C,iBAAiB,QAAQ;;EAEzB;;YAGU;EACV;EACA;EACA;EACA;;qBAGW;iBAEI;EACf,WACE,MAAM,MACN;IAAS;IAAmB;MAC3B,QAAQ;EACX,QACE,SAAS,mCACT,OAAO,QAAQ,sBAAsB,QAAQ,0BAC5C,QAAQ;;;;;;;;EAQX,OACE,OAAO,wBAAwB,mCAC/B,UAAU,4BACT,QAAQ;;;;;;;;;EASX,SACE,OAAO,yBACP,UAAU,4BACT,QAAQ;;;;;;EAMX,aACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;EAMX,eACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC;;;;;;EAMH,kBACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;;;EAQX,aAAa,OAAO,2BAA2B,QAAQ;EACvD,WACE,iBAAiB,yBACjB,UAAU,yBACT,QAAQ,gBAAgB;EAC3B,aACE,iBAAiB,2BACjB,UAAU,yBACT,QAAQ,gBAAgB;;wBA6Xb,uBACd,SAAS,qBACR"}
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"mappings":";;;;;;;;;KAKY,gBAAgB;EACtB;EAAe;EAAqB,OAAO;;EAC3C;EAAe;EAAoB;;KAE7B,0BAA0B;;EAEpC;;;;;;EAMA,SAAS;;;;;;;EAOT,aAAa,QAAQ,gBAAgB;;;;;;;wBAQjB,mBAAmB,GAAG,GAC1C,gBAAgB,KAChB,SAA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C5C,QAAQ;;;;;;;;EAQX,OACE,OAAO,wBAAwB,mCAC/B,UAAU,4BACT,QAAQ;;;;;;;;;EASX,SACE,OAAO,yBACP,UAAU,4BACT,QAAQ;;;;;;EAMX,aACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;EAMX,eACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC;;;;;;EAMH,kBACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;;;EAQX,aAAa,OAAO,2BAA2B,QAAQ;EACvD,WACE,iBAAiB,yBACjB,UAAU,yBACT,QAAQ,gBAAgB;EAC3B,aACE,iBAAiB,2BACjB,UAAU,yBACT,QAAQ,gBAAgB;;wBAgYb,uBACd,SAAS,qBACR"}
package/dist/client.js CHANGED
@@ -1,5 +1,5 @@
1
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-BMa3MUA2.js";
2
+ import { a as RemoteAttachmentUploadFactory, c as createXhrUploadTransport, d as AttachmentService, f as parseAttachmentDownloadTarget, i as RemoteAttachmentStore, l as createFetchUploadTransport, n as NullAttachmentTransport, o as RemoteAttachmentUpload, p as parseAttachmentUploadTarget, r as createRemoteAttachmentService, s as RemoteReservationStore, t as RoutingAttachmentService } from "./routing-attachment-service-CDHYlnyp.js";
3
3
  import { n as sha256HexOfBlob } from "./hash-BobbR4r4.js";
4
4
  //#region src/concurrency.ts
5
5
  /**
@@ -304,7 +304,8 @@ var AttachmentClientImpl = class {
304
304
  mimeType: opts?.mimeType ?? file.type,
305
305
  fileName: opts?.fileName ?? (file instanceof File ? file.name : "attachment"),
306
306
  clientHash: hash,
307
- sizeBytes
307
+ sizeBytes,
308
+ ...opts?.documentId !== void 0 ? { documentId: opts.documentId } : {}
308
309
  };
309
310
  const data = file.stream();
310
311
  const stream = () => file.stream();
@@ -357,7 +358,8 @@ var AttachmentClientImpl = class {
357
358
  emitter.stage("hashing", { total: input.file.size });
358
359
  preprocessed = await this.hashFile(input.file, {
359
360
  ...input.fileName !== void 0 ? { fileName: input.fileName } : {},
360
- ...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {}
361
+ ...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {},
362
+ ...input.documentId !== void 0 ? { documentId: input.documentId } : {}
361
363
  }, signal);
362
364
  }
363
365
  const sizeBytes = preprocessed.sizeBytes;
@@ -504,6 +506,6 @@ function createAttachmentClient(service) {
504
506
  return new AttachmentClientImpl(service);
505
507
  }
506
508
  //#endregion
507
- export { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };
509
+ export { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, RoutingAttachmentService, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };
508
510
 
509
511
  //# sourceMappingURL=client.js.map
@@ -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 { 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,cA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AO,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"}
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 RoutingAttachmentService,\n type AttachmentRouteResolver,\n} from \"./routing/routing-attachment-service.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 PreprocessOptions = {\n fileName?: string;\n mimeType?: string;\n /** The document the attachment is for; see `ReserveAttachmentOptions`. */\n documentId?: string;\n};\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 /** The document the attachment is for; see `ReserveAttachmentOptions`. */\n documentId?: 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(file: Blob, opts?: PreprocessOptions): 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(file: Blob, opts?: PreprocessOptions): Promise<PreprocessResult> {\n return this.hashFile(file, opts);\n }\n\n private async hashFile(\n file: Blob,\n opts?: PreprocessOptions,\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 ...(opts?.documentId !== undefined\n ? { documentId: opts.documentId }\n : {}),\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 ...(input.documentId !== undefined\n ? { documentId: input.documentId }\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;;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,kBACJ,OACA,SAC8B;EAC9B,MAAM,EAAE,MAAM,WAAW,MAAM,KAAK,aAAa,OAAO,OAAO;EAC/D,MAAM,MAAM,IAAI,gBAAgB,IAAI;EACpC,IAAI,UAAU;EACd,OAAO;GACL;GACA;GACA,cAAc;IACZ,IAAI,SAAS;IACb,UAAU;IACV,IAAI,gBAAgB,GAAG;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"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as InvalidAttachmentRef, C as AttachmentMetadataField, D as AttachmentTransferStage, E as AttachmentTransferError, M as SizeMismatch, N as UploadTooLarge, O as HashMismatch, S as AttachmentAlreadyExists, T as AttachmentPending, _ as createRef, a as RemoteAttachmentUpload, b as parseAttachmentDownloadTarget, c as XhrUploadTransportOptions, d as AttachmentUploadResponse, f as AttachmentUploadTransport, g as ParsedRef, h as SwitchboardTransportConfig, i as RemoteAttachmentUploadFactory, j as ReservationNotFound, k as InvalidAttachmentMetadata, l as createXhrUploadTransport, m as SwitchboardAttachmentTransport, n as createRemoteAttachmentService, o as RemoteReservationStore, p as createFetchUploadTransport, r as RemoteAttachmentStore, s as SwitchboardClientConfig, t as NullAttachmentTransport, u as AttachmentUploadRequest, v as parseRef, w as AttachmentNotFound, x as parseAttachmentUploadTarget, y as AttachmentService } from "./null-attachment-transport-Bs4JpmFx.js";
2
- import { A as UploadFirstReserveAttachmentOptions, C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, S as AttachmentTransportConfig, T as HashFirstReserveAttachmentOptions, _ as AttachmentResponse, a as IAttachmentTransport, b as AttachmentStatus, c as IAttachmentUploadFactory, d as AttachmentBackendKind, f as AttachmentDownloadOptions, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore, k as TransportResponse, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, o as IAttachmentTransportFactory, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, t as IAttachmentBackend, u as AttachmentBackendHealth, v as AttachmentSendOptions, w as AttachmentUploadTarget, x as AttachmentTargetHeaders, y as AttachmentStatOptions } from "./interfaces-C4GRlKeB.js";
1
+ import { A as HashMismatch, C as parseAttachmentUploadTarget, D as AttachmentPending, E as AttachmentNotFound, F as UploadTooLarge, M as InvalidAttachmentRef, N as ReservationNotFound, O as AttachmentTransferError, P as SizeMismatch, S as parseAttachmentDownloadTarget, T as AttachmentMetadataField, _ as SwitchboardTransportConfig, a as RemoteAttachmentStore, b as parseRef, c as RemoteReservationStore, d as createXhrUploadTransport, f as AttachmentUploadRequest, g as SwitchboardAttachmentTransport, h as createFetchUploadTransport, i as createRemoteAttachmentService, j as InvalidAttachmentMetadata, k as AttachmentTransferStage, l as SwitchboardClientConfig, m as AttachmentUploadTransport, n as RoutingAttachmentService, o as RemoteAttachmentUploadFactory, p as AttachmentUploadResponse, r as NullAttachmentTransport, s as RemoteAttachmentUpload, t as AttachmentRouteResolver, u as XhrUploadTransportOptions, v as ParsedRef, w as AttachmentAlreadyExists, x as AttachmentService, y as createRef } from "./routing-attachment-service-Dri6e2Vz.js";
2
+ import { A as UploadFirstReserveAttachmentOptions, C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, S as AttachmentTransportConfig, T as HashFirstReserveAttachmentOptions, _ as AttachmentResponse, a as IAttachmentTransport, b as AttachmentStatus, c as IAttachmentUploadFactory, d as AttachmentBackendKind, f as AttachmentDownloadOptions, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore, k as TransportResponse, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, o as IAttachmentTransportFactory, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, t as IAttachmentBackend, u as AttachmentBackendHealth, v as AttachmentSendOptions, w as AttachmentUploadTarget, x as AttachmentTargetHeaders, y as AttachmentStatOptions } from "./interfaces-cFMtcMqR.js";
3
3
  import { a as IAttachmentReferenceScanner, c as IAttachmentSchemaCompiler, i as IAttachmentReferenceReader, n as AttachmentReferencePageResult, o as IAttachmentReferenceWriter, s as CompiledAttachmentExtractor, t as AttachmentReferenceInput } from "./types-AagIcjTD.js";
4
4
  import { Kysely } from "kysely";
5
5
  import { AttachmentHash, AttachmentRef, BaseReadModel, DocumentViewDatabase, IConsistencyTracker, IDocumentModelRegistry, IOperationIndex, IWriteCache } from "@powerhousedao/reactor";
@@ -337,6 +337,6 @@ export declare class S3AttachmentUploadFactory implements IAttachmentUploadFacto
337
337
  createUpload(reservation: Reservation): IAttachmentUpload;
338
338
  }
339
339
  //#endregion
340
- export { AttachmentAlreadyExists, type AttachmentBackendHealth, type AttachmentBackendKind, type AttachmentBuildResult, type AttachmentDatabase, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, type AttachmentMetadataField, AttachmentNotFound, AttachmentPending, type AttachmentReferenceIndexBuildResult, type AttachmentReferenceInput, type AttachmentReferenceMigrationResult, type AttachmentResponse, type AttachmentSendOptions, AttachmentService, type AttachmentStatOptions, type AttachmentStatus, type AttachmentStorageConfig, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type CompiledAttachmentExtractor, type FilesystemAttachmentBackendConfig, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentBackend, type IAttachmentReader, type IAttachmentReferenceReader, type IAttachmentReferenceWriter, type IAttachmentSchemaCompiler, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentMetadata, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, type ReserveMetadata, type S3AttachmentBackendDependencies, type S3AttachmentConfig, type S3CommandClient, type S3Presigner, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
340
+ export { AttachmentAlreadyExists, type AttachmentBackendHealth, type AttachmentBackendKind, type AttachmentBuildResult, type AttachmentDatabase, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, type AttachmentMetadataField, AttachmentNotFound, AttachmentPending, type AttachmentReferenceIndexBuildResult, type AttachmentReferenceInput, type AttachmentReferenceMigrationResult, type AttachmentResponse, type AttachmentRouteResolver, type AttachmentSendOptions, AttachmentService, type AttachmentStatOptions, type AttachmentStatus, type AttachmentStorageConfig, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type CompiledAttachmentExtractor, type FilesystemAttachmentBackendConfig, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentBackend, type IAttachmentReader, type IAttachmentReferenceReader, type IAttachmentReferenceWriter, type IAttachmentSchemaCompiler, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentMetadata, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, type ReserveMetadata, RoutingAttachmentService, type S3AttachmentBackendDependencies, type S3AttachmentConfig, type S3CommandClient, type S3Presigner, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
341
341
  export {};
342
342
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as parseRef, c as AttachmentPending, d as InvalidAttachmentMetadata, 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, l as isBlob, n as createRemoteAttachmentService, o as RemoteReservationStore, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService } from "./null-attachment-transport-BMa3MUA2.js";
2
+ import { a as RemoteAttachmentUploadFactory, c as createXhrUploadTransport, d as AttachmentService, f as parseAttachmentDownloadTarget, i as RemoteAttachmentStore, l as createFetchUploadTransport, n as NullAttachmentTransport, o as RemoteAttachmentUpload, p as parseAttachmentUploadTarget, r as createRemoteAttachmentService, s as RemoteReservationStore, t as RoutingAttachmentService, u as isBlob } from "./routing-attachment-service-CDHYlnyp.js";
3
3
  import { t as AttachmentSchemaCompiler } from "./attachment-schema-compiler-BytE6Hev.js";
4
4
  import { dirname, join } from "node:path";
5
5
  import { Migrator, sql } from "kysely";
@@ -1328,6 +1328,6 @@ function createS3AttachmentBackend(db, config, dependencies = {}) {
1328
1328
  return new S3AttachmentBackend(db, config, dependencies);
1329
1329
  }
1330
1330
  //#endregion
1331
- export { ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE, ATTACHMENT_REFERENCE_MIGRATION_TABLE, ATTACHMENT_REFERENCE_READ_MODEL_ID, ATTACHMENT_REFERENCE_SCHEMA, ATTACHMENT_SCHEMA, AttachmentAlreadyExists, AttachmentBuilder, AttachmentNotFound, AttachmentPending, AttachmentReferenceIndexBuilder, AttachmentReferenceReadModel, AttachmentSchemaCompiler, AttachmentService, AttachmentTransferError, DEFAULT_RESERVATION_TTL_MS, DEFAULT_S3_ATTACHMENT_PREFIX, DEFAULT_S3_DOWNLOAD_TTL_SECONDS, DEFAULT_S3_UPLOAD_TTL_SECONDS, DirectAttachmentUpload, DirectAttachmentUploadFactory, FilesystemAttachmentBackend, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, KyselyAttachmentReferenceStore, KyselyAttachmentStore, KyselyReservationStore, MAX_S3_PRESIGN_TTL_SECONDS, NullAttachmentTransport, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, S3AttachmentBackend, S3AttachmentPrimitives, S3AttachmentUploadFactory, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createFetchUploadTransport, createRef, createRemoteAttachmentService, createS3AttachmentBackend, createS3AttachmentPrimitives, createXhrUploadTransport, deriveS3AttachmentKey, getAttachmentReferenceMigrationStatus, normalizeS3AttachmentPrefix, parseAttachmentDownloadTarget, parseAttachmentStorageConfig, parseAttachmentUploadTarget, parseRef, rollbackAttachmentReferenceMigration, runAttachmentMigrations, runAttachmentReferenceMigrations, sha256HexToBase64, validateReserveMetadata };
1331
+ export { ATTACHMENT_REFERENCE_MIGRATION_LOCK_TABLE, ATTACHMENT_REFERENCE_MIGRATION_TABLE, ATTACHMENT_REFERENCE_READ_MODEL_ID, ATTACHMENT_REFERENCE_SCHEMA, ATTACHMENT_SCHEMA, AttachmentAlreadyExists, AttachmentBuilder, AttachmentNotFound, AttachmentPending, AttachmentReferenceIndexBuilder, AttachmentReferenceReadModel, AttachmentSchemaCompiler, AttachmentService, AttachmentTransferError, DEFAULT_RESERVATION_TTL_MS, DEFAULT_S3_ATTACHMENT_PREFIX, DEFAULT_S3_DOWNLOAD_TTL_SECONDS, DEFAULT_S3_UPLOAD_TTL_SECONDS, DirectAttachmentUpload, DirectAttachmentUploadFactory, FilesystemAttachmentBackend, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, KyselyAttachmentReferenceStore, KyselyAttachmentStore, KyselyReservationStore, MAX_S3_PRESIGN_TTL_SECONDS, NullAttachmentTransport, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, RoutingAttachmentService, S3AttachmentBackend, S3AttachmentPrimitives, S3AttachmentUploadFactory, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createFetchUploadTransport, createRef, createRemoteAttachmentService, createS3AttachmentBackend, createS3AttachmentPrimitives, createXhrUploadTransport, deriveS3AttachmentKey, getAttachmentReferenceMigrationStatus, normalizeS3AttachmentPrefix, parseAttachmentDownloadTarget, parseAttachmentStorageConfig, parseAttachmentUploadTarget, parseRef, rollbackAttachmentReferenceMigration, runAttachmentMigrations, runAttachmentReferenceMigrations, sha256HexToBase64, validateReserveMetadata };
1332
1332
 
1333
1333
  //# sourceMappingURL=index.js.map
@@ -66,6 +66,8 @@ type UploadFirstReserveAttachmentOptions = {
66
66
  extension?: string | null;
67
67
  clientHash?: undefined;
68
68
  sizeBytes?: undefined;
69
+ /** The document the attachment is for; a routing service reserves on its backend. */
70
+ documentId?: string;
69
71
  };
70
72
  /**
71
73
  * Hash-first reservation. clientHash is present and sizeBytes is required.
@@ -88,6 +90,8 @@ type HashFirstReserveAttachmentOptions = {
88
90
  * ingest: an upload whose actual byte count differs is rejected.
89
91
  */
90
92
  sizeBytes: number;
93
+ /** The document the attachment is for; a routing service reserves on its backend. */
94
+ documentId?: string;
91
95
  };
92
96
  /**
93
97
  * Options provided when reserving an attachment slot.
@@ -568,4 +572,4 @@ interface IAttachmentBackend {
568
572
  //#endregion
569
573
  export { UploadFirstReserveAttachmentOptions as A, AttachmentUploadResult as C, ReserveAttachmentOptions as D, Reservation as E, TransportFetchResult as O, AttachmentTransportConfig as S, HashFirstReserveAttachmentOptions as T, AttachmentResponse as _, IAttachmentTransport as a, AttachmentStatus as b, IAttachmentUploadFactory as c, AttachmentBackendKind as d, AttachmentDownloadOptions as f, AttachmentMetadata as g, AttachmentHeader as h, IAttachmentStore as i, TransportResponse as k, IReservationStore as l, AttachmentDownloadTargetOptions as m, IAttachmentReader as n, IAttachmentTransportFactory as o, AttachmentDownloadTarget as p, IAttachmentService as r, IAttachmentUpload as s, IAttachmentBackend as t, AttachmentBackendHealth as u, AttachmentSendOptions as v, AttachmentUploadTarget as w, AttachmentTargetHeaders as x, AttachmentStatOptions as y };
570
574
  export {};
571
- //# sourceMappingURL=interfaces-C4GRlKeB.d.ts.map
575
+ //# sourceMappingURL=interfaces-cFMtcMqR.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interfaces-cFMtcMqR.d.ts","names":[],"sources":["../src/types.ts","../src/interfaces.ts"],"mappings":";;KAEY;KAEA;EACV,MAAM;EACN;;;;;;;KAQU;;;;;;;KAQA;EACV,MAAM;EACN;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;;;;;;;;;;;;;;;;;;;KAsBU;EACV;EACA;EACA;EACA;EACA;EACA;;;;;;KAOU;EACV;EACA;EACA;EACA;EACA;;EAEA;;;;;;;;;KAUU;EACV;EACA;EACA;;;;EAIA,YAAY;;;;;;EAMZ;;EAEA;;;;;;;;;;;;KAaU,2BACR,sCACA;;;;KAKQ;EACV,MAAM;EACN,KAAK;EACL,QAAQ;;;;;;;;;;KAWE;EACV,cAAc,gBAAgB;EAC9B,SAAS;;;;;;;KAQC;EACV;EACA,SAAS;;;KAIC;EACV;;;;;;;;KASU;EACV;EACA;EACA,SAAS;;;KAIC,0BAA0B,SAAS;KAEnC;EACV;EACA;EACA;EACA,SAAS;EACT;;KAGU;EACV;EACA;EACA;EACA,SAAS;EACT;;;KAIU,yBACR,oCACA;KAEQ;EACV;EACA;EACA;EACA,SAAS;EACT;;KAGU;EACV;EACA;EACA;EACA,SAAS;EACT;;;KAIU,2BACR,sCACA;;;;KAKQ;EACV,QAAQ;EACR,MAAM,eAAe;;;;;;;;KASX;EACV,MAAM;EACN,UAAU;EACV,MAAM,eAAe;;;;;;;;KASX;EACN;EAAc,UAAU;;EAExB;EACA,MAAM;EACN;EACA;;EAEA;;EAEA;;EAEA;;;;;KAKM;EACV;EACA,YAAY;;;;;;;;;KAUF;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA,eAAe;;;;;;;;UC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sBACE,MAAM,gBACN,sBACC,QAAQ;EACX,OAAO,MAAM,iBAAiB;EAC9B,UAAU,QAAQ"}
@@ -1,4 +1,4 @@
1
- import { O as TransportFetchResult, _ as AttachmentResponse, a as IAttachmentTransport, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore } from "./interfaces-C4GRlKeB.js";
1
+ import { O as TransportFetchResult, _ as AttachmentResponse, a as IAttachmentTransport, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore } from "./interfaces-cFMtcMqR.js";
2
2
  import { a as IAttachmentReferenceScanner, c as IAttachmentSchemaCompiler, i as IAttachmentReferenceReader, n as AttachmentReferencePageResult, r as AttachmentReferenceRow } from "./types-AagIcjTD.js";
3
3
  import { AttachmentHash, AttachmentRef, IDocumentModelRegistry, IEventBus, IReactorClient, ISyncManager, JwtHandler, LocalChannelPort } from "@powerhousedao/reactor";
4
4
  import { AuthSubject, OperationWithContext } from "@powerhousedao/shared/document-model";
@@ -769,6 +769,43 @@ var NullAttachmentTransport = class {
769
769
  }
770
770
  };
771
771
  //#endregion
772
- export { RemoteAttachmentUpload as a, createFetchUploadTransport as c, parseAttachmentDownloadTarget as d, parseAttachmentUploadTarget as f, RemoteAttachmentUploadFactory as i, isBlob as l, createRemoteAttachmentService as n, RemoteReservationStore as o, RemoteAttachmentStore as r, createXhrUploadTransport as s, NullAttachmentTransport as t, AttachmentService as u };
772
+ //#region src/routing/routing-attachment-service.ts
773
+ /** Routes by `documentId` to its backend's service; anything unroutable goes to `fallback`. */
774
+ var RoutingAttachmentService = class {
775
+ resolve;
776
+ byBackend;
777
+ fallback;
778
+ constructor(resolve, byBackend, fallback) {
779
+ this.resolve = resolve;
780
+ this.byBackend = byBackend;
781
+ this.fallback = fallback;
782
+ }
783
+ async reserve(options) {
784
+ const { documentId, ...rest } = options;
785
+ return (await this.serviceFor(documentId)).reserve(rest);
786
+ }
787
+ async stat(ref, options) {
788
+ return (await this.serviceFor(options?.documentId)).stat(ref, options);
789
+ }
790
+ async get(ref, options) {
791
+ return (options === void 0 || options instanceof AbortSignal ? this.fallback : await this.serviceFor(options.documentId, options.signal)).get(ref, options);
792
+ }
793
+ async getDownloadTarget(ref, options) {
794
+ return (await this.serviceFor(options.documentId, options.signal)).getDownloadTarget(ref, options);
795
+ }
796
+ async serviceFor(documentId, signal) {
797
+ if (documentId === void 0) return this.fallback;
798
+ let backend;
799
+ try {
800
+ backend = await this.resolve(documentId, signal);
801
+ } catch (error) {
802
+ if (signal?.aborted) throw error;
803
+ return this.fallback;
804
+ }
805
+ return this.byBackend.get(backend) ?? this.fallback;
806
+ }
807
+ };
808
+ //#endregion
809
+ export { RemoteAttachmentUploadFactory as a, createXhrUploadTransport as c, AttachmentService as d, parseAttachmentDownloadTarget as f, RemoteAttachmentStore as i, createFetchUploadTransport as l, NullAttachmentTransport as n, RemoteAttachmentUpload as o, parseAttachmentUploadTarget as p, createRemoteAttachmentService as r, RemoteReservationStore as s, RoutingAttachmentService as t, isBlob as u };
773
810
 
774
- //# sourceMappingURL=null-attachment-transport-BMa3MUA2.js.map
811
+ //# sourceMappingURL=routing-attachment-service-CDHYlnyp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing-attachment-service-CDHYlnyp.js","names":["isRecord","isRecord","isRecord"],"sources":["../src/targets.ts","../src/attachment-service.ts","../src/blob.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts","../src/routing/routing-attachment-service.ts"],"sourcesContent":["import type {\n AttachmentDownloadTarget,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n} from \"./types.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseUrl(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"Attachment target URL must be a non-empty string\");\n }\n if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) {\n throw new Error(\"Attachment target URL must not contain raw whitespace\");\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\"Attachment target URL is invalid\");\n }\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\"\n ) {\n throw new Error(\n \"Attachment target URL must be HTTP(S) and must not contain credentials\",\n );\n }\n // Return the original string: presigned URLs are opaque and must never be\n // normalized, decoded, reordered, or otherwise reconstructed.\n return value;\n}\n\nfunction parseHeaders(value: unknown): AttachmentTargetHeaders {\n if (!isRecord(value)) {\n throw new Error(\"Attachment target headers must be an object\");\n }\n // A null prototype preserves valid names such as `__proto__` as ordinary\n // own properties instead of invoking Object.prototype setters.\n const headers = Object.create(null) as Record<string, string>;\n const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n for (const [name, headerValue] of Object.entries(value)) {\n if (!headerName.test(name)) {\n throw new Error(`Attachment target header name is invalid: ${name}`);\n }\n if (\n typeof headerValue !== \"string\" ||\n hasForbiddenHeaderCharacter(headerValue)\n ) {\n throw new Error(`Attachment target header value is invalid: ${name}`);\n }\n headers[name] = headerValue;\n }\n return headers;\n}\n\nfunction hasForbiddenHeaderCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // Horizontal tab is valid field whitespace. Other C0 controls, DEL, and\n // especially CR/LF are forbidden to prevent header injection.\n if (code <= 8 || (code >= 10 && code <= 31) || code === 127 || code > 255) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasForbiddenUrlWhitespace(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // URL parsing may silently trim or percent-encode raw ASCII whitespace.\n // Reject it so the validated opaque string is exactly what Fetch receives.\n if (code <= 32 || code === 127) return true;\n }\n return false;\n}\n\nfunction parseExpiry(value: unknown, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n return value;\n}\n\nexport function parseAttachmentUploadTarget(\n value: unknown,\n): AttachmentUploadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment upload target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Switchboard upload target method must be PUT\");\n }\n return {\n kind: \"switchboard\",\n method: \"PUT\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-put\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Presigned upload target method must be PUT\");\n }\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment upload target kind is unknown\");\n }\n}\n\nexport function parseAttachmentDownloadTarget(\n value: unknown,\n): AttachmentDownloadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment download target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"GET\") {\n throw new Error(\"Switchboard download target method must be GET\");\n }\n return {\n kind: \"switchboard\",\n method: \"GET\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-get\":\n if (value.method !== \"GET\") {\n throw new Error(\"Presigned download target method must be GET\");\n }\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment download target kind is unknown\");\n }\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n} from \"./errors.js\";\nimport type {\n IAttachmentReader,\n IAttachmentBackend,\n IAttachmentService,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nimport { createRef, parseRef } from \"./ref.js\";\nimport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentResponse,\n AttachmentStatOptions,\n ReserveAttachmentOptions,\n} from \"./types.js\";\n\nconst CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;\n\nexport class AttachmentService implements IAttachmentService {\n constructor(\n private readonly store: IAttachmentReader,\n private readonly reservations: IReservationStore,\n private readonly uploadFactory: IAttachmentUploadFactory,\n private readonly backend?: IAttachmentBackend,\n ) {}\n\n async reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload> {\n if (options.clientHash !== undefined) {\n return this.reserveHashFirst(options);\n }\n if (this.backend?.kind === \"s3\") {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n const reservation = await this.reservations.create(options);\n return this.uploadFactory.createUpload(reservation);\n }\n\n async stat(\n ref: AttachmentRef,\n options?: AttachmentStatOptions,\n ): Promise<AttachmentHeader> {\n const { hash } = parseRef(ref);\n return options?.documentId === undefined\n ? this.store.stat(hash)\n : this.store.stat(hash, options.documentId);\n }\n\n async get(\n ref: AttachmentRef,\n options?: AbortSignal | AttachmentDownloadOptions,\n ): Promise<AttachmentResponse> {\n const { hash } = parseRef(ref);\n const normalized =\n options === undefined || options instanceof AbortSignal\n ? { signal: options }\n : options;\n return normalized.documentId === undefined\n ? this.store.get(hash, normalized.signal)\n : this.store.get(hash, normalized.signal, normalized.documentId);\n }\n\n getDownloadTarget(\n ref: AttachmentRef,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { hash } = parseRef(ref);\n const getTarget = this.store.getDownloadTarget?.bind(this.store);\n if (getTarget === undefined) {\n return Promise.reject(\n new Error(\n \"Download targets are not supported by this attachment store: only remote stores negotiate direct URLs\",\n ),\n );\n }\n return getTarget(hash, options);\n }\n\n private async reserveHashFirst(\n options: ReserveAttachmentOptions,\n ): Promise<IAttachmentUpload> {\n const normalized = options.clientHash!.toLowerCase() as AttachmentHash;\n if (!CLIENT_HASH_PATTERN.test(normalized)) {\n throw new Error(\n `clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`,\n );\n }\n // Zero is a real size: an empty file has a well-defined hash (the hash of\n // no bytes) and is stored like any other. Mail carries them, and refusing\n // one failed the whole step that tried to ingest the message.\n if (\n options.sizeBytes === undefined ||\n !Number.isSafeInteger(options.sizeBytes) ||\n options.sizeBytes < 0\n ) {\n throw new Error(\n \"sizeBytes must be a non-negative safe integer when clientHash is provided\",\n );\n }\n\n const normalizedOptions: ReserveAttachmentOptions = {\n ...options,\n clientHash: normalized,\n };\n\n let existingHeader: AttachmentHeader | null = null;\n try {\n existingHeader = await this.store.stat(normalized);\n } catch (err) {\n if (\n !(err instanceof AttachmentNotFound) &&\n !(err instanceof AttachmentPending)\n ) {\n throw err;\n }\n }\n\n if (existingHeader !== null) {\n if (this.backend?.kind === \"s3\") {\n if (await this.backend.exists(normalized)) {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n } else if (existingHeader.status === \"available\") {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n }\n\n const reservation = await this.reservations.create(normalizedOptions);\n if (this.backend?.kind !== \"s3\") {\n return this.uploadFactory.createUpload(reservation);\n }\n const uploadTarget = await this.backend.prepareUploadTarget(reservation);\n return this.uploadFactory.createUpload({ ...reservation, uploadTarget });\n }\n}\n","/** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */\nexport function isBlob(data: ReadableStream<Uint8Array> | Blob): data is Blob {\n return !(\"getReader\" in data);\n}\n","/**\n * The seam every attachment upload PUT goes through.\n *\n * It exists because `fetch` cannot report upload-side progress: there is no\n * event between \"request issued\" and \"response received\". Naming the transport\n * lets an implementation that *can* count bytes (see\n * `createXhrUploadTransport`) be substituted without the upload code knowing\n * which one it holds — and it is also the right seam for a future multipart\n * upload, which needs one request per part.\n */\n\n/**\n * Headers are forwarded VERBATIM. A presigned target's headers are part of a\n * signature: normalizing their casing, or adding so much as one header,\n * invalidates it.\n */\nexport type AttachmentUploadRequest = {\n url: string;\n method: \"PUT\";\n headers: Record<string, string>;\n body: Blob;\n /** Called with cumulative bytes handed to the socket, when observable. */\n onProgress?: (loaded: number, total: number) => void;\n signal?: AbortSignal;\n};\n\n/**\n * The only response surface the upload code reads. A real `Response`\n * satisfies this structurally, which is what lets the fetch transport be an\n * identity pass-through rather than an adapter.\n */\nexport type AttachmentUploadResponse = {\n readonly status: number;\n readonly statusText: string;\n readonly ok: boolean;\n json(): Promise<unknown>;\n};\n\nexport type AttachmentUploadTransport = (\n request: AttachmentUploadRequest,\n) => Promise<AttachmentUploadResponse>;\n\n/**\n * The default transport. Ignores `onProgress` — fetch has no upload-side\n * progress event, and silence is how a transport reports that bytes are\n * unobservable.\n */\nexport function createFetchUploadTransport(\n fetchFn: typeof fetch,\n): AttachmentUploadTransport {\n return (request) =>\n fetchFn(request.url, {\n method: request.method,\n headers: request.headers,\n body: request.body,\n ...(request.signal ? { signal: request.signal } : {}),\n });\n}\n","import {\n createFetchUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\n\nexport type XhrUploadTransportOptions = {\n /**\n * Used where `XMLHttpRequest` does not exist (Node). Defaults to the global\n * fetch, resolved at call time.\n */\n fetchFn?: typeof fetch;\n};\n\n/**\n * Upload transport backed by `XMLHttpRequest`, the only browser API that\n * reports upload-side byte progress (`xhr.upload.onprogress`). Everything else\n * about the request is identical to the fetch path.\n *\n * Capability detection happens **inside** the returned function, never at\n * module load: this module is reachable from the client entry, which is\n * executed in Node by the entrypoint tests, and Node has no\n * `XMLHttpRequest`. Detecting per call also means a test can install a fake on\n * `globalThis` without any module-registry reset.\n */\nexport function createXhrUploadTransport(\n options?: XhrUploadTransportOptions,\n): AttachmentUploadTransport {\n return (request) => {\n const XhrCtor = globalThis.XMLHttpRequest;\n if (typeof XhrCtor !== \"function\") {\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n return createFetchUploadTransport(fetchFn.bind(globalThis))(request);\n }\n return sendWithXhr(new XhrCtor(), request);\n };\n}\n\n/**\n * Mirrors fetch's observable behavior closely enough that\n * `RemoteAttachmentUpload` cannot tell the two apart:\n *\n * - `responseType` is left at `\"\"`, so a non-JSON 422 body still reaches the\n * caller's `json()` and fails there rather than being swallowed.\n * - status 0 never resolves. XHR reports 0 for network failure, CORS refusal\n * and abort alike; resolving it would fabricate a transfer error claiming\n * the provider answered 0.\n * - failures reject with fetch's error shapes: `TypeError` for network,\n * `AbortError` for abort.\n */\nfunction sendWithXhr(\n xhr: XMLHttpRequest,\n request: AttachmentUploadRequest,\n): Promise<AttachmentUploadResponse> {\n return new Promise<AttachmentUploadResponse>((resolve, reject) => {\n const signal = request.signal;\n let settled = false;\n\n const abortListener = () => xhr.abort();\n const detach = () => signal?.removeEventListener(\"abort\", abortListener);\n const succeed = (response: AttachmentUploadResponse) => {\n if (settled) return;\n settled = true;\n detach();\n resolve(response);\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n detach();\n reject(error);\n };\n\n if (signal?.aborted) {\n fail(abortError());\n return;\n }\n\n xhr.open(request.method, request.url, true);\n // Verbatim: a presigned target's headers are part of its signature.\n for (const [name, value] of Object.entries(request.headers)) {\n xhr.setRequestHeader(name, value);\n }\n\n // Attached before send(), and only when a caller is listening — merely\n // registering an upload listener forces a CORS preflight.\n if (request.onProgress) {\n xhr.upload.addEventListener(\"progress\", (event: ProgressEvent) => {\n if (!event.lengthComputable) return;\n request.onProgress?.(event.loaded, event.total);\n });\n }\n\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 0) {\n fail(networkError());\n return;\n }\n succeed(toResponse(xhr));\n });\n xhr.addEventListener(\"error\", () => fail(networkError()));\n xhr.addEventListener(\"timeout\", () => fail(networkError()));\n xhr.addEventListener(\"abort\", () => fail(abortError()));\n\n signal?.addEventListener(\"abort\", abortListener);\n xhr.send(request.body);\n });\n}\n\nfunction toResponse(xhr: XMLHttpRequest): AttachmentUploadResponse {\n return {\n status: xhr.status,\n statusText: xhr.statusText,\n ok: xhr.status >= 200 && xhr.status < 300,\n json: () => {\n try {\n return Promise.resolve(JSON.parse(xhr.responseText));\n } catch (err) {\n return Promise.reject(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n },\n };\n}\n\nfunction networkError(): TypeError {\n return new TypeError(\"Failed to fetch\");\n}\n\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentRef, JwtHandler } from \"@powerhousedao/reactor\";\nimport { AttachmentAlreadyExists, ReservationNotFound } from \"../errors.js\";\nimport type { IReservationStore } from \"../interfaces.js\";\nimport { createRef, parseRef } from \"../ref.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../types.js\";\nimport { parseAttachmentUploadTarget } from \"../targets.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { AttachmentUploadTransport } from \"./upload-transport.js\";\n\nexport type SwitchboardClientConfig = {\n remoteUrl: string;\n jwtHandler?: JwtHandler;\n fetchFn?: typeof fetch;\n /**\n * Transport for upload PUTs only, so a browser host can opt into\n * XMLHttpRequest and get real upload progress.\n *\n * An explicit `fetchFn` always wins over this. The precedence is\n * one-directional on purpose: under this rule, adding `uploadTransport` to a\n * config that already pins `fetchFn` is a provable no-op, whereas the\n * reverse rule would let `{ ...config, uploadTransport }` silently route the\n * largest request in the system around a test's mock and onto the network.\n */\n uploadTransport?: AttachmentUploadTransport;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deriveExtension(fileName: string): string | null {\n const idx = fileName.lastIndexOf(\".\");\n if (idx <= 0 || idx === fileName.length - 1) return null;\n return fileName.slice(idx + 1).toLowerCase();\n}\n\nfunction isReservationBase(value: unknown): value is Record<string, unknown> & {\n reservationId: string;\n mimeType: string;\n fileName: string;\n extension: string | null;\n createdAtUtc: string;\n expiresAtUtc: string;\n} {\n if (!isRecord(value)) return false;\n if (typeof value.reservationId !== \"string\") return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (typeof value.expiresAtUtc !== \"string\") return false;\n return true;\n}\n\nfunction isReservation(value: unknown): value is Reservation {\n if (!isReservationBase(value)) return false;\n // clientHash and sizeBytes may be absent on responses from older\n // switchboards; treat missing as null (normalized below in get()).\n if (\n value.clientHash !== undefined &&\n value.clientHash !== null &&\n typeof value.clientHash !== \"string\"\n ) {\n return false;\n }\n if (\n value.sizeBytes !== undefined &&\n value.sizeBytes !== null &&\n typeof value.sizeBytes !== \"number\"\n ) {\n return false;\n }\n return true;\n}\n\nexport class RemoteReservationStore implements IReservationStore {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const extension = options.extension ?? deriveExtension(options.fileName);\n\n const bodyObj: Record<string, unknown> = {\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n };\n if (options.clientHash !== undefined) {\n bodyObj.clientHash = options.clientHash;\n }\n if (options.sizeBytes !== undefined) {\n bodyObj.sizeBytes = options.sizeBytes;\n }\n\n const response = await this.fetchFn(url, {\n method: \"POST\",\n headers: { ...authHeaders, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(bodyObj),\n });\n\n if (response.status === 409) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n if (\n isRecord(body) &&\n body.error === \"already_exists\" &&\n options.clientHash !== undefined\n ) {\n let ref: AttachmentRef;\n if (typeof body.ref === \"string\") {\n try {\n parseRef(body.ref as AttachmentRef);\n ref = body.ref as AttachmentRef;\n } catch {\n ref = createRef(options.clientHash);\n }\n } else {\n ref = createRef(options.clientHash);\n }\n throw new AttachmentAlreadyExists(options.clientHash, ref);\n }\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let json: unknown;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Reservation create returned non-JSON response\");\n }\n if (\n typeof json !== \"object\" ||\n json === null ||\n typeof (json as Record<string, unknown>).reservationId !== \"string\" ||\n ((json as Record<string, unknown>).reservationId as string).length === 0\n ) {\n throw new Error(\n \"Reservation create returned a payload missing a non-empty reservationId string\",\n );\n }\n const body = json as {\n reservationId: string;\n ref?: string | null;\n createdAtUtc?: string;\n expiresAtUtc?: string;\n uploadTarget?: unknown;\n };\n // The server is the source of truth for both timestamps. We synthesize\n // only as a last-resort fallback for older switchboards that don't\n // include them in the response; in that case the client cannot know the\n // server's TTL, so expiresAtUtc is a best-effort placeholder.\n const now = new Date();\n return {\n reservationId: body.reservationId,\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n createdAtUtc: body.createdAtUtc ?? now.toISOString(),\n expiresAtUtc:\n body.expiresAtUtc ??\n new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),\n clientHash: options.clientHash ?? null,\n sizeBytes: options.sizeBytes ?? null,\n ...(body.uploadTarget === undefined\n ? {}\n : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }),\n };\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, { headers: authHeaders });\n\n if (response.status === 404) {\n throw new ReservationNotFound(reservationId);\n }\n if (!response.ok) {\n throw new Error(\n `Reservation get failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n throw new Error(\"Reservation get returned non-JSON response\");\n }\n if (!isReservation(parsed)) {\n throw new Error(\n \"Reservation get returned a payload that does not match the Reservation shape\",\n );\n }\n return {\n reservationId: parsed.reservationId,\n mimeType: parsed.mimeType,\n fileName: parsed.fileName,\n extension: parsed.extension,\n createdAtUtc: parsed.createdAtUtc,\n expiresAtUtc: parsed.expiresAtUtc,\n // Normalize fields that may be absent on older switchboard responses.\n clientHash: parsed.clientHash ?? null,\n sizeBytes: parsed.sizeBytes ?? null,\n ...(parsed.uploadTarget === undefined\n ? {}\n : {\n uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget),\n }),\n };\n }\n\n async delete(reservationId: string): Promise<void> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"DELETE\",\n headers: authHeaders,\n });\n\n // 2xx = success; 404 / 410 = already gone, treat as idempotent success.\n if (!response.ok && response.status !== 404 && response.status !== 410) {\n throw new Error(\n `Reservation delete failed: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n // Sweeping is the server's responsibility; clients have no authority to\n // delete reservations on a remote switchboard.\n deleteExpired(): Promise<number> {\n return Promise.reject(\n new Error(\"RemoteReservationStore.deleteExpired is not supported\"),\n );\n }\n}\n","import type {\n AttachmentHash,\n AttachmentRef,\n JwtHandler,\n} from \"@powerhousedao/reactor\";\nimport {\n AttachmentTransferError,\n HashMismatch,\n SizeMismatch,\n} from \"../errors.js\";\nimport type { IAttachmentUpload } from \"../interfaces.js\";\nimport { createRef } from \"../ref.js\";\nimport type {\n AttachmentSendOptions,\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\nimport {\n createFetchUploadTransport,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * A Blob goes out untouched, so a File streams from disk. A stream is\n * buffered: browsers don't portably accept a ReadableStream request body.\n */\nasync function toBody(data: ReadableStream<Uint8Array> | Blob): Promise<Blob> {\n return isBlob(data) ? data : new Response(data).blob();\n}\n\nexport class RemoteAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n private readonly reservation: Reservation;\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly uploadTransport: AttachmentUploadTransport;\n\n constructor(reservation: Reservation, config: SwitchboardClientConfig) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash !== null\n ? createRef(reservation.clientHash)\n : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n if (reservation.uploadTarget) {\n this.uploadTarget = reservation.uploadTarget;\n }\n this.reservation = reservation;\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n // fetchFn wins: pinning fetch must not be silently overridden.\n this.uploadTransport = config.fetchFn\n ? createFetchUploadTransport(config.fetchFn.bind(globalThis))\n : (config.uploadTransport ??\n createFetchUploadTransport(globalThis.fetch.bind(globalThis)));\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n // Presigned targets bypass Switchboard entirely: bytes go straight to the\n // provider with the exact signed headers. Switchboard targets (and the\n // legacy no-target wire) keep the authenticated reservation PUT below.\n if (this.uploadTarget?.kind === \"presigned-put\") {\n return this.sendPresigned(this.uploadTarget, data, options);\n }\n const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const body = await toBody(data);\n\n // Always upload as octet-stream. The server reads the real mime type from\n // the reservation row; sending the user's mime type here (e.g. application/json)\n // would let Express body-parser drain the request body before our handler runs,\n // silently writing zero bytes.\n const response = await this.uploadTransport({\n url,\n method: \"PUT\",\n headers: { ...authHeaders, \"Content-Type\": \"application/octet-stream\" },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n\n if (response.status === 422) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n if (isRecord(errorBody)) {\n if (\n errorBody.error === \"hash_mismatch\" &&\n typeof errorBody.claimed === \"string\" &&\n typeof errorBody.actual === \"string\"\n ) {\n throw new HashMismatch(errorBody.claimed, errorBody.actual);\n }\n if (\n errorBody.error === \"size_mismatch\" &&\n typeof errorBody.declared === \"number\" &&\n typeof errorBody.actual === \"number\"\n ) {\n throw new SizeMismatch(errorBody.declared, errorBody.actual);\n }\n }\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as AttachmentUploadResult;\n }\n\n /**\n * Direct provider upload: PUT the bytes to the presigned URL with exactly\n * the returned headers — never the Switchboard JWT — and treat any 2xx as\n * final success with no follow-up control request. The result is\n * synthesized from the hash-first reservation, which is the only path that\n * can produce a presigned target.\n */\n private async sendPresigned(\n target: AttachmentUploadTarget,\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (this.reservation.clientHash === null || this.ref === null) {\n throw new Error(\n \"Presigned upload targets require a hash-first reservation\",\n );\n }\n\n const body = await toBody(data);\n const response = await this.uploadTransport({\n url: target.url,\n method: target.method,\n headers: { ...target.headers },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-put\", response.status);\n }\n\n const hash = this.reservation.clientHash as AttachmentHash;\n const now = new Date().toISOString();\n return {\n hash,\n ref: this.ref,\n header: {\n hash,\n mimeType: this.reservation.mimeType,\n fileName: this.reservation.fileName,\n sizeBytes: this.reservation.sizeBytes ?? body.size,\n extension: this.reservation.extension,\n status: \"available\",\n source: \"local\",\n createdAtUtc: this.reservation.createdAtUtc || now,\n lastAccessedAtUtc: now,\n expiresAtUtc: null,\n },\n };\n }\n}\n","import type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport { RemoteAttachmentUpload } from \"./remote-attachment-upload.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nexport class RemoteAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(private readonly config: SwitchboardClientConfig) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new RemoteAttachmentUpload(reservation, this.config);\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { JwtHandler } from \"@powerhousedao/reactor\";\nimport {\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n} from \"../errors.js\";\nimport type { IAttachmentReader } from \"../interfaces.js\";\nimport { parseAttachmentDownloadTarget } from \"../targets.js\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nconst MISSING_DOCUMENT_ID =\n \"Remote attachment reads require the documentId whose operations reference the attachment\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAttachmentMetadata(value: unknown): value is AttachmentMetadata {\n if (!isRecord(value)) return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (\n typeof value.sizeBytes !== \"number\" ||\n !Number.isFinite(value.sizeBytes) ||\n value.sizeBytes < 0\n ) {\n return false;\n }\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (\n value.lastAccessedAtUtc !== undefined &&\n typeof value.lastAccessedAtUtc !== \"string\"\n ) {\n return false;\n }\n return true;\n}\n\nfunction contentTypeFallback(response: Response): AttachmentMetadata {\n const contentLength = response.headers.get(\"Content-Length\");\n if (contentLength === null) {\n throw new Error(\n \"Switchboard response missing both Attachment-Metadata and Content-Length headers\",\n );\n }\n const sizeBytes = Number(contentLength);\n if (!Number.isInteger(sizeBytes) || sizeBytes < 0) {\n throw new Error(\n `Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`,\n );\n }\n // Last-Modified is the closest legitimate signal we have for an original\n // creation time when Attachment-Metadata is absent. If that's missing too,\n // fall back to the response date (still server-attributed). This is\n // imperfect — Last-Modified reflects the most recent change, not the\n // original upload — but unlike sizeBytes there is no zero-equivalent\n // sentinel for a date, and downstream consumers expect a value.\n const lastModified = response.headers.get(\"Last-Modified\");\n const dateHeader = response.headers.get(\"Date\");\n const createdAtUtc = lastModified\n ? new Date(lastModified).toISOString()\n : dateHeader\n ? new Date(dateHeader).toISOString()\n : new Date().toISOString();\n\n return {\n // application/octet-stream is the RFC 2046 sentinel for \"unknown binary\",\n // and \"unknown\" is a non-real filename sentinel; neither is a fabricated\n // semantic value the way Content-Length=0 would be.\n mimeType:\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n fileName: \"unknown\",\n sizeBytes,\n extension: null,\n createdAtUtc,\n lastAccessedAtUtc: createdAtUtc,\n };\n}\n\nfunction parseMetadata(response: Response): AttachmentMetadata {\n // Compute the fallback at most once; both the recovery path inside the\n // header parser and the outer \"no header / parse failed\" path share it.\n let fallbackCache: AttachmentMetadata | undefined;\n const fallback = (): AttachmentMetadata => {\n if (fallbackCache === undefined) {\n fallbackCache = contentTypeFallback(response);\n }\n return fallbackCache;\n };\n\n const metaHeader = response.headers.get(\"Attachment-Metadata\");\n if (metaHeader) {\n try {\n const parsed: unknown = JSON.parse(metaHeader);\n if (isRecord(parsed)) {\n if (parsed.extension === undefined) {\n parsed.extension = null;\n }\n // Older switchboards may omit these timestamps; fall back to the\n // Date/Last-Modified header so we never produce client-clock-stamped\n // values when the server has authority.\n if (parsed.createdAtUtc === undefined) {\n parsed.createdAtUtc = fallback().createdAtUtc;\n }\n if (parsed.lastAccessedAtUtc === undefined) {\n parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n }\n }\n if (isAttachmentMetadata(parsed)) {\n return parsed;\n }\n } catch {\n // fall through to Content-Type fallback\n }\n }\n return fallback();\n}\n\ntype PendingInfo = {\n expiresAtUtc: string;\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n};\n\ntype PartialPendingInfo = {\n expiresAtUtc: string;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n};\n\nfunction parsePendingExpiry(response: Response): PartialPendingInfo | null {\n const header = response.headers.get(\"Attachment-Pending\");\n if (!header) return null;\n try {\n const parsed: unknown = JSON.parse(header);\n if (!isRecord(parsed)) return null;\n if (typeof parsed.expiresAtUtc !== \"string\") return null;\n const result: PartialPendingInfo = { expiresAtUtc: parsed.expiresAtUtc };\n if (typeof parsed.mimeType === \"string\") result.mimeType = parsed.mimeType;\n if (typeof parsed.fileName === \"string\") result.fileName = parsed.fileName;\n if (\n typeof parsed.sizeBytes === \"number\" &&\n Number.isFinite(parsed.sizeBytes) &&\n parsed.sizeBytes >= 0\n ) {\n result.sizeBytes = parsed.sizeBytes;\n }\n return result;\n } catch {\n return null;\n }\n}\n\nfunction parsePendingHeader(response: Response): PendingInfo | null {\n const partial = parsePendingExpiry(response);\n if (!partial) return null;\n if (\n typeof partial.mimeType !== \"string\" ||\n typeof partial.fileName !== \"string\" ||\n partial.sizeBytes === undefined\n ) {\n return null;\n }\n return {\n expiresAtUtc: partial.expiresAtUtc,\n mimeType: partial.mimeType,\n fileName: partial.fileName,\n sizeBytes: partial.sizeBytes,\n };\n}\n\nexport class RemoteAttachmentStore implements IAttachmentReader {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n /**\n * Get attachment metadata. Normally returns a pending AttachmentHeader\n * (status: 'pending') when the server responds 202 with a full\n * Attachment-Pending header. When only expiresAtUtc is present in the\n * header (degraded wire), throws AttachmentPending instead -- the\n * AttachmentPending throw is the degraded-wire case.\n */\n async stat(\n hash: AttachmentHash,\n documentId?: string,\n ): Promise<AttachmentHeader> {\n // The server answers a hash-only HEAD 404; hash-first reserve relies on\n // that to leave the dedup decision to the server's 409.\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"HEAD\",\n headers: authHeaders,\n });\n\n if (response.status === 202) {\n const fullPending = parsePendingHeader(response);\n if (fullPending) {\n return buildPendingHeader(hash, fullPending);\n }\n const partial = parsePendingExpiry(response);\n if (partial) {\n throw new AttachmentPending(hash, partial.expiresAtUtc);\n }\n throw new Error(\n \"Attachment stat returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment stat failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const metadata = parseMetadata(response);\n return buildHeader(hash, metadata);\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new Error(MISSING_DOCUMENT_ID);\n }\n const target = await this.getDownloadTarget(hash, { documentId, signal });\n if (target.kind === \"presigned-get\") {\n return this.fetchPresigned(hash, target, signal);\n }\n return this.fetchAttachment(hash, target, signal);\n }\n\n /**\n * Asks Switchboard for an authorized download target. The request carries\n * the JWT; the response is runtime-validated before any byte transfer.\n * Public so callers can mint direct URLs (previews, share links) without\n * transferring bytes; `expiresIn` requests a caller-chosen lifetime.\n */\n async getDownloadTarget(\n hash: AttachmentHash,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { documentId, expiresIn, signal } = options;\n const expiry =\n expiresIn === undefined\n ? \"\"\n : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;\n const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"download-target\", response.status);\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new AttachmentTransferError(\"download-target\");\n }\n return parseAttachmentDownloadTarget(body);\n }\n\n /**\n * Executes a presigned GET with exactly the returned headers and no JWT.\n * A provider 404 means the object is missing despite available metadata\n * (the accepted abandoned-upload trade-off) and surfaces as the same typed\n * not-found error callers already handle.\n */\n private async fetchPresigned(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const response = await this.fetchFn(target.url, {\n signal,\n headers: { ...target.headers },\n });\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-get\", response.status);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n\n private async fetchAttachment(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const url = target.url;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const headers = { ...target.headers, ...authHeaders };\n\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 202) {\n const pending = parsePendingExpiry(response);\n if (!pending) {\n throw new Error(\n \"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n throw new AttachmentPending(hash, pending.expiresAtUtc);\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment fetch failed: ${response.status} ${response.statusText}`,\n );\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n}\n\nfunction buildHeader(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n): AttachmentHeader {\n return {\n hash,\n mimeType: metadata.mimeType,\n fileName: metadata.fileName,\n sizeBytes: metadata.sizeBytes,\n extension: metadata.extension,\n status: \"available\",\n source: \"sync\",\n createdAtUtc: metadata.createdAtUtc,\n lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,\n expiresAtUtc: null,\n };\n}\n\nfunction buildPendingHeader(\n hash: AttachmentHash,\n pending: PendingInfo,\n): AttachmentHeader {\n const now = new Date().toISOString();\n return {\n hash,\n mimeType: pending.mimeType,\n fileName: pending.fileName,\n sizeBytes: pending.sizeBytes,\n extension: null,\n status: \"pending\",\n source: \"sync\",\n createdAtUtc: now,\n lastAccessedAtUtc: now,\n expiresAtUtc: pending.expiresAtUtc,\n };\n}\n","import { AttachmentService } from \"../attachment-service.js\";\nimport type { IAttachmentService } from \"../interfaces.js\";\nimport { RemoteAttachmentStore } from \"./remote-attachment-store.js\";\nimport { RemoteAttachmentUploadFactory } from \"./remote-attachment-upload-factory.js\";\nimport {\n RemoteReservationStore,\n type SwitchboardClientConfig,\n} from \"./remote-reservation-store.js\";\n\nexport function createRemoteAttachmentService(\n config: SwitchboardClientConfig,\n): IAttachmentService {\n const reservations = new RemoteReservationStore(config);\n const uploadFactory = new RemoteAttachmentUploadFactory(config);\n const store = new RemoteAttachmentStore(config);\n return new AttachmentService(store, reservations, uploadFactory);\n}\n","import type { IAttachmentTransport } from \"./interfaces.js\";\nimport type { TransportFetchResult } from \"./types.js\";\n\n/**\n * No-op transport for deployments without remote sync.\n * fetch() always returns not-found, announce() and push() are no-ops.\n */\nexport class NullAttachmentTransport implements IAttachmentTransport {\n fetch(): Promise<TransportFetchResult> {\n return Promise.resolve({ kind: \"not-found\" });\n }\n\n announce(): Promise<void> {\n return Promise.resolve();\n }\n\n push(): Promise<void> {\n return Promise.resolve();\n }\n}\n","import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport type { IAttachmentService, IAttachmentUpload } from \"../interfaces.js\";\nimport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentResponse,\n AttachmentStatOptions,\n ReserveAttachmentOptions,\n} from \"../types.js\";\n\n/** The name of the backend that serves a document, e.g. a router's `locate`. */\nexport type AttachmentRouteResolver = (\n documentId: string,\n signal?: AbortSignal,\n) => Promise<string>;\n\n/** Routes by `documentId` to its backend's service; anything unroutable goes to `fallback`. */\nexport class RoutingAttachmentService implements IAttachmentService {\n constructor(\n private readonly resolve: AttachmentRouteResolver,\n private readonly byBackend: ReadonlyMap<string, IAttachmentService>,\n private readonly fallback: IAttachmentService,\n ) {}\n\n async reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload> {\n const { documentId, ...rest } = options;\n const service = await this.serviceFor(documentId);\n return service.reserve(rest as ReserveAttachmentOptions);\n }\n\n async stat(\n ref: AttachmentRef,\n options?: AttachmentStatOptions,\n ): Promise<AttachmentHeader> {\n const service = await this.serviceFor(options?.documentId);\n return service.stat(ref, options);\n }\n\n async get(\n ref: AttachmentRef,\n options?: AbortSignal | AttachmentDownloadOptions,\n ): Promise<AttachmentResponse> {\n const service =\n options === undefined || options instanceof AbortSignal\n ? this.fallback\n : await this.serviceFor(options.documentId, options.signal);\n return service.get(ref, options);\n }\n\n async getDownloadTarget(\n ref: AttachmentRef,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const service = await this.serviceFor(options.documentId, options.signal);\n return service.getDownloadTarget(ref, options);\n }\n\n private async serviceFor(\n documentId: string | undefined,\n signal?: AbortSignal,\n ): Promise<IAttachmentService> {\n if (documentId === undefined) return this.fallback;\n let backend: string;\n try {\n backend = await this.resolve(documentId, signal);\n } catch (error) {\n if (signal?.aborted) throw error;\n return this.fallback;\n }\n return this.byBackend.get(backend) ?? this.fallback;\n }\n}\n"],"mappings":";;AAMA,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAwB;CACxC,IAAI,OAAO,UAAU,YAAY,MAAM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- import { C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, _ as AttachmentResponse, a as IAttachmentTransport, c as IAttachmentUploadFactory, f as AttachmentDownloadOptions, h as AttachmentHeader, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, t as IAttachmentBackend, v as AttachmentSendOptions, w as AttachmentUploadTarget, y as AttachmentStatOptions } from "./interfaces-C4GRlKeB.js";
1
+ import { C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, _ as AttachmentResponse, a as IAttachmentTransport, c as IAttachmentUploadFactory, f as AttachmentDownloadOptions, h as AttachmentHeader, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, t as IAttachmentBackend, v as AttachmentSendOptions, w as AttachmentUploadTarget, y as AttachmentStatOptions } from "./interfaces-cFMtcMqR.js";
2
2
  import { AttachmentHash, AttachmentRef, JwtHandler } from "@powerhousedao/reactor";
3
3
  //#region src/errors.d.ts
4
4
  /**
@@ -322,6 +322,22 @@ declare class NullAttachmentTransport implements IAttachmentTransport {
322
322
  push(): Promise<void>;
323
323
  }
324
324
  //#endregion
325
- export { InvalidAttachmentRef as A, AttachmentMetadataField as C, AttachmentTransferStage as D, AttachmentTransferError as E, SizeMismatch as M, UploadTooLarge as N, HashMismatch as O, AttachmentAlreadyExists as S, AttachmentPending as T, createRef as _, RemoteAttachmentUpload as a, parseAttachmentDownloadTarget as b, XhrUploadTransportOptions as c, AttachmentUploadResponse as d, AttachmentUploadTransport as f, ParsedRef as g, SwitchboardTransportConfig as h, RemoteAttachmentUploadFactory as i, ReservationNotFound as j, InvalidAttachmentMetadata as k, createXhrUploadTransport as l, SwitchboardAttachmentTransport as m, createRemoteAttachmentService as n, RemoteReservationStore as o, createFetchUploadTransport as p, RemoteAttachmentStore as r, SwitchboardClientConfig as s, NullAttachmentTransport as t, AttachmentUploadRequest as u, parseRef as v, AttachmentNotFound as w, parseAttachmentUploadTarget as x, AttachmentService as y };
325
+ //#region src/routing/routing-attachment-service.d.ts
326
+ /** The name of the backend that serves a document, e.g. a router's `locate`. */
327
+ type AttachmentRouteResolver = (documentId: string, signal?: AbortSignal) => Promise<string>;
328
+ /** Routes by `documentId` to its backend's service; anything unroutable goes to `fallback`. */
329
+ declare class RoutingAttachmentService implements IAttachmentService {
330
+ private readonly resolve;
331
+ private readonly byBackend;
332
+ private readonly fallback;
333
+ constructor(resolve: AttachmentRouteResolver, byBackend: ReadonlyMap<string, IAttachmentService>, fallback: IAttachmentService);
334
+ reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload>;
335
+ stat(ref: AttachmentRef, options?: AttachmentStatOptions): Promise<AttachmentHeader>;
336
+ get(ref: AttachmentRef, options?: AbortSignal | AttachmentDownloadOptions): Promise<AttachmentResponse>;
337
+ getDownloadTarget(ref: AttachmentRef, options: AttachmentDownloadTargetOptions): Promise<AttachmentDownloadTarget>;
338
+ private serviceFor;
339
+ }
340
+ //#endregion
341
+ export { HashMismatch as A, parseAttachmentUploadTarget as C, AttachmentPending as D, AttachmentNotFound as E, UploadTooLarge as F, InvalidAttachmentRef as M, ReservationNotFound as N, AttachmentTransferError as O, SizeMismatch as P, parseAttachmentDownloadTarget as S, AttachmentMetadataField as T, SwitchboardTransportConfig as _, RemoteAttachmentStore as a, parseRef as b, RemoteReservationStore as c, createXhrUploadTransport as d, AttachmentUploadRequest as f, SwitchboardAttachmentTransport as g, createFetchUploadTransport as h, createRemoteAttachmentService as i, InvalidAttachmentMetadata as j, AttachmentTransferStage as k, SwitchboardClientConfig as l, AttachmentUploadTransport as m, RoutingAttachmentService as n, RemoteAttachmentUploadFactory as o, AttachmentUploadResponse as p, NullAttachmentTransport as r, RemoteAttachmentUpload as s, AttachmentRouteResolver as t, XhrUploadTransportOptions as u, ParsedRef as v, AttachmentAlreadyExists as w, AttachmentService as x, createRef as y };
326
342
  export {};
327
- //# sourceMappingURL=null-attachment-transport-Bs4JpmFx.d.ts.map
343
+ //# sourceMappingURL=routing-attachment-service-Dri6e2Vz.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing-attachment-service-Dri6e2Vz.d.ts","names":[],"sources":["../src/errors.ts","../src/targets.ts","../src/attachment-service.ts","../src/ref.ts","../src/switchboard/switchboard-attachment-transport.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts","../src/routing/routing-attachment-service.ts"],"mappings":";;;;;;cAKa,2BAA2B;EACtC,YAAY;;;;;cASD,4BAA4B;EACvC,YAAY;;;;;cASD,6BAA6B;EACxC,YAAY;;;KAOF;;;;;cAMC,kCAAkC;WACpC,OAAO;EAChB,YAAY,OAAO;;;;;;cAWR,uBAAuB;WACzB;EACT,YAAY;;;;;;;cAYD,gCAAgC;WAClC,MAAM;WACN,KAAK;EACd,YAAY,MAAM,gBAAgB,KAAK;;;;;;;cAa5B,qBAAqB;WACvB,SAAS;WACT,QAAQ;EACjB,YAAY,SAAS,gBAAgB,QAAQ;;;;;;;;;;;;;cAmBlC,qBAAqB;WACvB;WACA;EACT,YAAY,kBAAkB;;;;;;;;;;;;;KAmBpB;;;;;;cAWC,gCAAgC;WAClC,OAAO;WACP;EAET,YAAY,OAAO,yBAAyB;;cAYjC,0BAA0B;WAC5B,MAAM;WACN;WACA;aAEM;aACA;aACA;;EAIf,YACE,MAAM,gBACN,sBACA;IAAS;IAAkB;IAAkB;;;;;iBCzEjC,4BACd,iBACC;iBAoCa,8BACd,iBACC;;;cC3GU,6BAA6B;mBAErB;mBACA;mBACA;mBACA;EAJnB,YACmB,OAAO,mBACP,cAAc,mBACd,eAAe,0BACf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C,aAAa,aAAa,cAAc;;;;cC8K7B,iCAAiC;mBAC3B;mBACA;mBACA;EAEjB,YAAY,QAAQ;;;;;;;;EAad,KACJ,MAAM,gBACN,sBACC,QAAQ;EAyCL,IACJ,MAAM,gBACN,SAAS,aACT,sBACC,QAAQ;;;;;;;EAiBL,kBACJ,MAAM,gBACN,SAAS,kCACR,QAAQ;;;;;;;UAgCG;UAsBA;;;;iBC5TA,8BACd,QAAQ,0BACP;;;;;;;cCJU,mCAAmC;EAC9C,SAAS,QAAQ;EAIjB,YAAY;EAIZ,QAAQ;;;;;KCHE,2BACV,oBACA,SAAS,gBACN;;cAGQ,oCAAoC;mBAE5B;mBACA;mBACA;EAHnB,YACmB,SAAS,yBACT,WAAW,oBAAoB,qBAC/B,UAAU;EAGvB,QAAQ,SAAS,2BAA2B,QAAQ;EAMpD,KACJ,KAAK,eACL,UAAU,wBACT,QAAQ;EAKL,IACJ,KAAK,eACL,UAAU,cAAc,4BACvB,QAAQ;EAQL,kBACJ,KAAK,eACL,SAAS,kCACR,QAAQ;UAKG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/reactor-attachments",
3
- "version": "6.2.3-dev.81",
3
+ "version": "6.2.3-dev.83",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "repository": {
@@ -36,10 +36,10 @@
36
36
  "@aws-sdk/client-s3": "3.1087.0",
37
37
  "@aws-sdk/s3-request-presigner": "3.1087.0",
38
38
  "@noble/hashes": "^1.8.0",
39
- "@powerhousedao/reactor": "6.2.3-dev.81",
40
- "@powerhousedao/shared": "6.2.3-dev.81",
39
+ "@powerhousedao/reactor": "6.2.3-dev.83",
40
+ "@powerhousedao/shared": "6.2.3-dev.83",
41
41
  "change-case": "5.4.4",
42
- "document-model": "6.2.3-dev.81",
42
+ "document-model": "6.2.3-dev.83",
43
43
  "graphql": "^16",
44
44
  "kysely": "0.28.16"
45
45
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"interfaces-C4GRlKeB.d.ts","names":[],"sources":["../src/types.ts","../src/interfaces.ts"],"mappings":";;KAEY;KAEA;EACV,MAAM;EACN;;;;;;;KAQU;;;;;;;KAQA;EACV,MAAM;EACN;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;;;;;;;;;;;;;;;;;;;KAsBU;EACV;EACA;EACA;EACA;EACA;EACA;;;;;;KAOU;EACV;EACA;EACA;EACA;EACA;;;;;;;;;KAUU;EACV;EACA;EACA;;;;EAIA,YAAY;;;;;;EAMZ;;;;;;;;;;;;KAaU,2BACR,sCACA;;;;KAKQ;EACV,MAAM;EACN,KAAK;EACL,QAAQ;;;;;;;;;;KAWE;EACV,cAAc,gBAAgB;EAC9B,SAAS;;;;;;;KAQC;EACV;EACA,SAAS;;;KAIC;EACV;;;;;;;;KASU;EACV;EACA;EACA,SAAS;;;KAIC,0BAA0B,SAAS;KAEnC;EACV;EACA;EACA;EACA,SAAS;EACT;;KAGU;EACV;EACA;EACA;EACA,SAAS;EACT;;;KAIU,yBACR,oCACA;KAEQ;EACV;EACA;EACA;EACA,SAAS;EACT;;KAGU;EACV;EACA;EACA;EACA,SAAS;EACT;;;KAIU,2BACR,sCACA;;;;KAKQ;EACV,QAAQ;EACR,MAAM,eAAe;;;;;;;;KASX;EACV,MAAM;EACN,UAAU;EACV,MAAM,eAAe;;;;;;;;KASX;EACN;EAAc,UAAU;;EAExB;EACA,MAAM;EACN;EACA;;EAEA;;EAEA;;EAEA;;;;;KAKM;EACV;EACA,YAAY;;;;;;;;;KAUF;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA,eAAe;;;;;;;;UC3PA;;;;;;;;;;;;;;;;;;;EAmBf,QAAQ,SAAS,2BAA2B,QAAQ;;;;;;;;;;;;EAapD,KACE,KAAK,eACL,UAAU,wBACT,QAAQ;;;;;;;;;;;;;;;;;EAkBX,IACE,KAAK,eACL,UAAU,cAAc,4BACvB,QAAQ;;;;;;;;;;;EAYX,kBACE,KAAK,eACL,SAAS,kCACR,QAAQ;;;;;;UAOI;;;;EAIf;;;;;;EAOA,KAAK;;;;;;WAOI;;WAGA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuCxB,KACE,MAAM,eAAe,cAAc,MACnC,UAAU,wBACT,QAAQ;;;;;;;;;;;UAYI;;;;;;;;;;;;;;EAcf,KAAK,MAAM,gBAAgB,sBAAsB,QAAQ;;;;;;;;;;;;;;;;;;;EAoBzD,IACE,MAAM,gBACN,SAAS,aACT,sBACC,QAAQ;;;;;;EAOX,mBACE,MAAM,gBACN,SAAS,kCACR,QAAQ;;;;;;;;UASI,yBAAyB;;;;;;;EAOxC,IAAI,MAAM,iBAAiB;;;;;;;;;;;;EAa3B,IACE,MAAM,gBACN,UAAU,oBACV,MAAM,eAAe,cACpB;;;;;;;;;;;;;;;;EAiBH,MAAM,MAAM,iBAAiB;;;;;EAM7B,eAAe;;;;;;;;;UAUA;;;;;;;;;;;;;;;EAef,MACE,MAAM,gBACN,oBACA,SAAS,cACR,QAAQ;;;;;;;EAQX,SAAS,MAAM,iBAAiB;;;;;;;;;;;EAYhC,KACE,MAAM,gBACN,gBACA,MAAM,eAAe,cACpB;;;;;;UAOY;EACf,SAAS,QAAQ,4BAA4B;;;;;;UAO9B;EACf,OAAO,SAAS,2BAA2B,QAAQ;EACnD,IAAI,wBAAwB,QAAQ;EACpC,OAAO,wBAAwB;;;;;;;;EAS/B,cAAc,MAAM,OAAO;;;;;;;UAQZ;EACf,aAAa,aAAa,cAAc;;;;;;;UAQzB;WACN,MAAM;EACf,oBACE,aAAa,cACZ,QAAQ;;;;;;EAMX,sBACE,MAAM,gBACN,sBACC,QAAQ;EACX,OAAO,MAAM,iBAAiB;EAC9B,UAAU,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"null-attachment-transport-BMa3MUA2.js","names":["isRecord","isRecord","isRecord"],"sources":["../src/targets.ts","../src/attachment-service.ts","../src/blob.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts"],"sourcesContent":["import type {\n AttachmentDownloadTarget,\n AttachmentTargetHeaders,\n AttachmentUploadTarget,\n} from \"./types.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseUrl(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"Attachment target URL must be a non-empty string\");\n }\n if (value.trim() !== value || hasForbiddenUrlWhitespace(value)) {\n throw new Error(\"Attachment target URL must not contain raw whitespace\");\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new Error(\"Attachment target URL is invalid\");\n }\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\"\n ) {\n throw new Error(\n \"Attachment target URL must be HTTP(S) and must not contain credentials\",\n );\n }\n // Return the original string: presigned URLs are opaque and must never be\n // normalized, decoded, reordered, or otherwise reconstructed.\n return value;\n}\n\nfunction parseHeaders(value: unknown): AttachmentTargetHeaders {\n if (!isRecord(value)) {\n throw new Error(\"Attachment target headers must be an object\");\n }\n // A null prototype preserves valid names such as `__proto__` as ordinary\n // own properties instead of invoking Object.prototype setters.\n const headers = Object.create(null) as Record<string, string>;\n const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n for (const [name, headerValue] of Object.entries(value)) {\n if (!headerName.test(name)) {\n throw new Error(`Attachment target header name is invalid: ${name}`);\n }\n if (\n typeof headerValue !== \"string\" ||\n hasForbiddenHeaderCharacter(headerValue)\n ) {\n throw new Error(`Attachment target header value is invalid: ${name}`);\n }\n headers[name] = headerValue;\n }\n return headers;\n}\n\nfunction hasForbiddenHeaderCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // Horizontal tab is valid field whitespace. Other C0 controls, DEL, and\n // especially CR/LF are forbidden to prevent header injection.\n if (code <= 8 || (code >= 10 && code <= 31) || code === 127 || code > 255) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasForbiddenUrlWhitespace(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n // URL parsing may silently trim or percent-encode raw ASCII whitespace.\n // Reject it so the validated opaque string is exactly what Fetch receives.\n if (code <= 32 || code === 127) return true;\n }\n return false;\n}\n\nfunction parseExpiry(value: unknown, required: boolean): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\") {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime()) || parsed.toISOString() !== value) {\n throw new Error(\"Attachment target expiry must be an ISO 8601 UTC string\");\n }\n return value;\n}\n\nexport function parseAttachmentUploadTarget(\n value: unknown,\n): AttachmentUploadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment upload target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Switchboard upload target method must be PUT\");\n }\n return {\n kind: \"switchboard\",\n method: \"PUT\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-put\":\n if (value.method !== \"PUT\") {\n throw new Error(\"Presigned upload target method must be PUT\");\n }\n return {\n kind: \"presigned-put\",\n method: \"PUT\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment upload target kind is unknown\");\n }\n}\n\nexport function parseAttachmentDownloadTarget(\n value: unknown,\n): AttachmentDownloadTarget {\n if (!isRecord(value)) {\n throw new Error(\"Attachment download target must be an object\");\n }\n const url = parseUrl(value.url);\n const headers = parseHeaders(value.headers);\n switch (value.kind) {\n case \"switchboard\":\n if (value.method !== \"GET\") {\n throw new Error(\"Switchboard download target method must be GET\");\n }\n return {\n kind: \"switchboard\",\n method: \"GET\",\n url,\n headers,\n ...(value.expiresAtUtc === undefined\n ? {}\n : { expiresAtUtc: parseExpiry(value.expiresAtUtc, false) }),\n };\n case \"presigned-get\":\n if (value.method !== \"GET\") {\n throw new Error(\"Presigned download target method must be GET\");\n }\n return {\n kind: \"presigned-get\",\n method: \"GET\",\n url,\n headers,\n expiresAtUtc: parseExpiry(value.expiresAtUtc, true)!,\n };\n default:\n throw new Error(\"Attachment download target kind is unknown\");\n }\n}\n","import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\nimport {\n AttachmentAlreadyExists,\n AttachmentNotFound,\n AttachmentPending,\n} from \"./errors.js\";\nimport type {\n IAttachmentReader,\n IAttachmentBackend,\n IAttachmentService,\n IAttachmentUpload,\n IAttachmentUploadFactory,\n IReservationStore,\n} from \"./interfaces.js\";\nimport { createRef, parseRef } from \"./ref.js\";\nimport type {\n AttachmentDownloadOptions,\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentResponse,\n AttachmentStatOptions,\n ReserveAttachmentOptions,\n} from \"./types.js\";\n\nconst CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;\n\nexport class AttachmentService implements IAttachmentService {\n constructor(\n private readonly store: IAttachmentReader,\n private readonly reservations: IReservationStore,\n private readonly uploadFactory: IAttachmentUploadFactory,\n private readonly backend?: IAttachmentBackend,\n ) {}\n\n async reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload> {\n if (options.clientHash !== undefined) {\n return this.reserveHashFirst(options);\n }\n if (this.backend?.kind === \"s3\") {\n throw new Error(\"S3 attachment reservations require a client hash\");\n }\n const reservation = await this.reservations.create(options);\n return this.uploadFactory.createUpload(reservation);\n }\n\n async stat(\n ref: AttachmentRef,\n options?: AttachmentStatOptions,\n ): Promise<AttachmentHeader> {\n const { hash } = parseRef(ref);\n return options?.documentId === undefined\n ? this.store.stat(hash)\n : this.store.stat(hash, options.documentId);\n }\n\n async get(\n ref: AttachmentRef,\n options?: AbortSignal | AttachmentDownloadOptions,\n ): Promise<AttachmentResponse> {\n const { hash } = parseRef(ref);\n const normalized =\n options === undefined || options instanceof AbortSignal\n ? { signal: options }\n : options;\n return normalized.documentId === undefined\n ? this.store.get(hash, normalized.signal)\n : this.store.get(hash, normalized.signal, normalized.documentId);\n }\n\n getDownloadTarget(\n ref: AttachmentRef,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { hash } = parseRef(ref);\n const getTarget = this.store.getDownloadTarget?.bind(this.store);\n if (getTarget === undefined) {\n return Promise.reject(\n new Error(\n \"Download targets are not supported by this attachment store: only remote stores negotiate direct URLs\",\n ),\n );\n }\n return getTarget(hash, options);\n }\n\n private async reserveHashFirst(\n options: ReserveAttachmentOptions,\n ): Promise<IAttachmentUpload> {\n const normalized = options.clientHash!.toLowerCase() as AttachmentHash;\n if (!CLIENT_HASH_PATTERN.test(normalized)) {\n throw new Error(\n `clientHash must be a 64-character lowercase hex string, got: ${options.clientHash}`,\n );\n }\n // Zero is a real size: an empty file has a well-defined hash (the hash of\n // no bytes) and is stored like any other. Mail carries them, and refusing\n // one failed the whole step that tried to ingest the message.\n if (\n options.sizeBytes === undefined ||\n !Number.isSafeInteger(options.sizeBytes) ||\n options.sizeBytes < 0\n ) {\n throw new Error(\n \"sizeBytes must be a non-negative safe integer when clientHash is provided\",\n );\n }\n\n const normalizedOptions: ReserveAttachmentOptions = {\n ...options,\n clientHash: normalized,\n };\n\n let existingHeader: AttachmentHeader | null = null;\n try {\n existingHeader = await this.store.stat(normalized);\n } catch (err) {\n if (\n !(err instanceof AttachmentNotFound) &&\n !(err instanceof AttachmentPending)\n ) {\n throw err;\n }\n }\n\n if (existingHeader !== null) {\n if (this.backend?.kind === \"s3\") {\n if (await this.backend.exists(normalized)) {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n } else if (existingHeader.status === \"available\") {\n throw new AttachmentAlreadyExists(normalized, createRef(normalized));\n }\n }\n\n const reservation = await this.reservations.create(normalizedOptions);\n if (this.backend?.kind !== \"s3\") {\n return this.uploadFactory.createUpload(reservation);\n }\n const uploadTarget = await this.backend.prepareUploadTarget(reservation);\n return this.uploadFactory.createUpload({ ...reservation, uploadTarget });\n }\n}\n","/** Tells a Blob from a stream by shape: `instanceof Blob` misses other realms and polyfills. */\nexport function isBlob(data: ReadableStream<Uint8Array> | Blob): data is Blob {\n return !(\"getReader\" in data);\n}\n","/**\n * The seam every attachment upload PUT goes through.\n *\n * It exists because `fetch` cannot report upload-side progress: there is no\n * event between \"request issued\" and \"response received\". Naming the transport\n * lets an implementation that *can* count bytes (see\n * `createXhrUploadTransport`) be substituted without the upload code knowing\n * which one it holds — and it is also the right seam for a future multipart\n * upload, which needs one request per part.\n */\n\n/**\n * Headers are forwarded VERBATIM. A presigned target's headers are part of a\n * signature: normalizing their casing, or adding so much as one header,\n * invalidates it.\n */\nexport type AttachmentUploadRequest = {\n url: string;\n method: \"PUT\";\n headers: Record<string, string>;\n body: Blob;\n /** Called with cumulative bytes handed to the socket, when observable. */\n onProgress?: (loaded: number, total: number) => void;\n signal?: AbortSignal;\n};\n\n/**\n * The only response surface the upload code reads. A real `Response`\n * satisfies this structurally, which is what lets the fetch transport be an\n * identity pass-through rather than an adapter.\n */\nexport type AttachmentUploadResponse = {\n readonly status: number;\n readonly statusText: string;\n readonly ok: boolean;\n json(): Promise<unknown>;\n};\n\nexport type AttachmentUploadTransport = (\n request: AttachmentUploadRequest,\n) => Promise<AttachmentUploadResponse>;\n\n/**\n * The default transport. Ignores `onProgress` — fetch has no upload-side\n * progress event, and silence is how a transport reports that bytes are\n * unobservable.\n */\nexport function createFetchUploadTransport(\n fetchFn: typeof fetch,\n): AttachmentUploadTransport {\n return (request) =>\n fetchFn(request.url, {\n method: request.method,\n headers: request.headers,\n body: request.body,\n ...(request.signal ? { signal: request.signal } : {}),\n });\n}\n","import {\n createFetchUploadTransport,\n type AttachmentUploadRequest,\n type AttachmentUploadResponse,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\n\nexport type XhrUploadTransportOptions = {\n /**\n * Used where `XMLHttpRequest` does not exist (Node). Defaults to the global\n * fetch, resolved at call time.\n */\n fetchFn?: typeof fetch;\n};\n\n/**\n * Upload transport backed by `XMLHttpRequest`, the only browser API that\n * reports upload-side byte progress (`xhr.upload.onprogress`). Everything else\n * about the request is identical to the fetch path.\n *\n * Capability detection happens **inside** the returned function, never at\n * module load: this module is reachable from the client entry, which is\n * executed in Node by the entrypoint tests, and Node has no\n * `XMLHttpRequest`. Detecting per call also means a test can install a fake on\n * `globalThis` without any module-registry reset.\n */\nexport function createXhrUploadTransport(\n options?: XhrUploadTransportOptions,\n): AttachmentUploadTransport {\n return (request) => {\n const XhrCtor = globalThis.XMLHttpRequest;\n if (typeof XhrCtor !== \"function\") {\n const fetchFn = options?.fetchFn ?? globalThis.fetch;\n return createFetchUploadTransport(fetchFn.bind(globalThis))(request);\n }\n return sendWithXhr(new XhrCtor(), request);\n };\n}\n\n/**\n * Mirrors fetch's observable behavior closely enough that\n * `RemoteAttachmentUpload` cannot tell the two apart:\n *\n * - `responseType` is left at `\"\"`, so a non-JSON 422 body still reaches the\n * caller's `json()` and fails there rather than being swallowed.\n * - status 0 never resolves. XHR reports 0 for network failure, CORS refusal\n * and abort alike; resolving it would fabricate a transfer error claiming\n * the provider answered 0.\n * - failures reject with fetch's error shapes: `TypeError` for network,\n * `AbortError` for abort.\n */\nfunction sendWithXhr(\n xhr: XMLHttpRequest,\n request: AttachmentUploadRequest,\n): Promise<AttachmentUploadResponse> {\n return new Promise<AttachmentUploadResponse>((resolve, reject) => {\n const signal = request.signal;\n let settled = false;\n\n const abortListener = () => xhr.abort();\n const detach = () => signal?.removeEventListener(\"abort\", abortListener);\n const succeed = (response: AttachmentUploadResponse) => {\n if (settled) return;\n settled = true;\n detach();\n resolve(response);\n };\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n detach();\n reject(error);\n };\n\n if (signal?.aborted) {\n fail(abortError());\n return;\n }\n\n xhr.open(request.method, request.url, true);\n // Verbatim: a presigned target's headers are part of its signature.\n for (const [name, value] of Object.entries(request.headers)) {\n xhr.setRequestHeader(name, value);\n }\n\n // Attached before send(), and only when a caller is listening — merely\n // registering an upload listener forces a CORS preflight.\n if (request.onProgress) {\n xhr.upload.addEventListener(\"progress\", (event: ProgressEvent) => {\n if (!event.lengthComputable) return;\n request.onProgress?.(event.loaded, event.total);\n });\n }\n\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 0) {\n fail(networkError());\n return;\n }\n succeed(toResponse(xhr));\n });\n xhr.addEventListener(\"error\", () => fail(networkError()));\n xhr.addEventListener(\"timeout\", () => fail(networkError()));\n xhr.addEventListener(\"abort\", () => fail(abortError()));\n\n signal?.addEventListener(\"abort\", abortListener);\n xhr.send(request.body);\n });\n}\n\nfunction toResponse(xhr: XMLHttpRequest): AttachmentUploadResponse {\n return {\n status: xhr.status,\n statusText: xhr.statusText,\n ok: xhr.status >= 200 && xhr.status < 300,\n json: () => {\n try {\n return Promise.resolve(JSON.parse(xhr.responseText));\n } catch (err) {\n return Promise.reject(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n },\n };\n}\n\nfunction networkError(): TypeError {\n return new TypeError(\"Failed to fetch\");\n}\n\nfunction abortError(): DOMException {\n return new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { AttachmentRef, JwtHandler } from \"@powerhousedao/reactor\";\nimport { AttachmentAlreadyExists, ReservationNotFound } from \"../errors.js\";\nimport type { IReservationStore } from \"../interfaces.js\";\nimport { createRef, parseRef } from \"../ref.js\";\nimport type { Reservation, ReserveAttachmentOptions } from \"../types.js\";\nimport { parseAttachmentUploadTarget } from \"../targets.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { AttachmentUploadTransport } from \"./upload-transport.js\";\n\nexport type SwitchboardClientConfig = {\n remoteUrl: string;\n jwtHandler?: JwtHandler;\n fetchFn?: typeof fetch;\n /**\n * Transport for upload PUTs only, so a browser host can opt into\n * XMLHttpRequest and get real upload progress.\n *\n * An explicit `fetchFn` always wins over this. The precedence is\n * one-directional on purpose: under this rule, adding `uploadTransport` to a\n * config that already pins `fetchFn` is a provable no-op, whereas the\n * reverse rule would let `{ ...config, uploadTransport }` silently route the\n * largest request in the system around a test's mock and onto the network.\n */\n uploadTransport?: AttachmentUploadTransport;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction deriveExtension(fileName: string): string | null {\n const idx = fileName.lastIndexOf(\".\");\n if (idx <= 0 || idx === fileName.length - 1) return null;\n return fileName.slice(idx + 1).toLowerCase();\n}\n\nfunction isReservationBase(value: unknown): value is Record<string, unknown> & {\n reservationId: string;\n mimeType: string;\n fileName: string;\n extension: string | null;\n createdAtUtc: string;\n expiresAtUtc: string;\n} {\n if (!isRecord(value)) return false;\n if (typeof value.reservationId !== \"string\") return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (typeof value.expiresAtUtc !== \"string\") return false;\n return true;\n}\n\nfunction isReservation(value: unknown): value is Reservation {\n if (!isReservationBase(value)) return false;\n // clientHash and sizeBytes may be absent on responses from older\n // switchboards; treat missing as null (normalized below in get()).\n if (\n value.clientHash !== undefined &&\n value.clientHash !== null &&\n typeof value.clientHash !== \"string\"\n ) {\n return false;\n }\n if (\n value.sizeBytes !== undefined &&\n value.sizeBytes !== null &&\n typeof value.sizeBytes !== \"number\"\n ) {\n return false;\n }\n return true;\n}\n\nexport class RemoteReservationStore implements IReservationStore {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n async create(options: ReserveAttachmentOptions): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const extension = options.extension ?? deriveExtension(options.fileName);\n\n const bodyObj: Record<string, unknown> = {\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n };\n if (options.clientHash !== undefined) {\n bodyObj.clientHash = options.clientHash;\n }\n if (options.sizeBytes !== undefined) {\n bodyObj.sizeBytes = options.sizeBytes;\n }\n\n const response = await this.fetchFn(url, {\n method: \"POST\",\n headers: { ...authHeaders, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(bodyObj),\n });\n\n if (response.status === 409) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n if (\n isRecord(body) &&\n body.error === \"already_exists\" &&\n options.clientHash !== undefined\n ) {\n let ref: AttachmentRef;\n if (typeof body.ref === \"string\") {\n try {\n parseRef(body.ref as AttachmentRef);\n ref = body.ref as AttachmentRef;\n } catch {\n ref = createRef(options.clientHash);\n }\n } else {\n ref = createRef(options.clientHash);\n }\n throw new AttachmentAlreadyExists(options.clientHash, ref);\n }\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Reservation create failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let json: unknown;\n try {\n json = await response.json();\n } catch {\n throw new Error(\"Reservation create returned non-JSON response\");\n }\n if (\n typeof json !== \"object\" ||\n json === null ||\n typeof (json as Record<string, unknown>).reservationId !== \"string\" ||\n ((json as Record<string, unknown>).reservationId as string).length === 0\n ) {\n throw new Error(\n \"Reservation create returned a payload missing a non-empty reservationId string\",\n );\n }\n const body = json as {\n reservationId: string;\n ref?: string | null;\n createdAtUtc?: string;\n expiresAtUtc?: string;\n uploadTarget?: unknown;\n };\n // The server is the source of truth for both timestamps. We synthesize\n // only as a last-resort fallback for older switchboards that don't\n // include them in the response; in that case the client cannot know the\n // server's TTL, so expiresAtUtc is a best-effort placeholder.\n const now = new Date();\n return {\n reservationId: body.reservationId,\n mimeType: options.mimeType,\n fileName: options.fileName,\n extension,\n createdAtUtc: body.createdAtUtc ?? now.toISOString(),\n expiresAtUtc:\n body.expiresAtUtc ??\n new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString(),\n clientHash: options.clientHash ?? null,\n sizeBytes: options.sizeBytes ?? null,\n ...(body.uploadTarget === undefined\n ? {}\n : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }),\n };\n }\n\n async get(reservationId: string): Promise<Reservation> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, { headers: authHeaders });\n\n if (response.status === 404) {\n throw new ReservationNotFound(reservationId);\n }\n if (!response.ok) {\n throw new Error(\n `Reservation get failed: ${response.status} ${response.statusText}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = await response.json();\n } catch {\n throw new Error(\"Reservation get returned non-JSON response\");\n }\n if (!isReservation(parsed)) {\n throw new Error(\n \"Reservation get returned a payload that does not match the Reservation shape\",\n );\n }\n return {\n reservationId: parsed.reservationId,\n mimeType: parsed.mimeType,\n fileName: parsed.fileName,\n extension: parsed.extension,\n createdAtUtc: parsed.createdAtUtc,\n expiresAtUtc: parsed.expiresAtUtc,\n // Normalize fields that may be absent on older switchboard responses.\n clientHash: parsed.clientHash ?? null,\n sizeBytes: parsed.sizeBytes ?? null,\n ...(parsed.uploadTarget === undefined\n ? {}\n : {\n uploadTarget: parseAttachmentUploadTarget(parsed.uploadTarget),\n }),\n };\n }\n\n async delete(reservationId: string): Promise<void> {\n const url = `${this.remoteUrl}/attachments/reservations/${encodeURIComponent(reservationId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"DELETE\",\n headers: authHeaders,\n });\n\n // 2xx = success; 404 / 410 = already gone, treat as idempotent success.\n if (!response.ok && response.status !== 404 && response.status !== 410) {\n throw new Error(\n `Reservation delete failed: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n // Sweeping is the server's responsibility; clients have no authority to\n // delete reservations on a remote switchboard.\n deleteExpired(): Promise<number> {\n return Promise.reject(\n new Error(\"RemoteReservationStore.deleteExpired is not supported\"),\n );\n }\n}\n","import type {\n AttachmentHash,\n AttachmentRef,\n JwtHandler,\n} from \"@powerhousedao/reactor\";\nimport {\n AttachmentTransferError,\n HashMismatch,\n SizeMismatch,\n} from \"../errors.js\";\nimport type { IAttachmentUpload } from \"../interfaces.js\";\nimport { createRef } from \"../ref.js\";\nimport type {\n AttachmentSendOptions,\n AttachmentUploadResult,\n AttachmentUploadTarget,\n Reservation,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\nimport {\n createFetchUploadTransport,\n type AttachmentUploadTransport,\n} from \"./upload-transport.js\";\nimport { isBlob } from \"../blob.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * A Blob goes out untouched, so a File streams from disk. A stream is\n * buffered: browsers don't portably accept a ReadableStream request body.\n */\nasync function toBody(data: ReadableStream<Uint8Array> | Blob): Promise<Blob> {\n return isBlob(data) ? data : new Response(data).blob();\n}\n\nexport class RemoteAttachmentUpload implements IAttachmentUpload {\n readonly reservationId: string;\n readonly ref: AttachmentRef | null;\n readonly expiresAtUtc: string;\n readonly uploadTarget?: AttachmentUploadTarget;\n private readonly reservation: Reservation;\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly uploadTransport: AttachmentUploadTransport;\n\n constructor(reservation: Reservation, config: SwitchboardClientConfig) {\n this.reservationId = reservation.reservationId;\n this.ref =\n reservation.clientHash !== null\n ? createRef(reservation.clientHash)\n : null;\n this.expiresAtUtc = reservation.expiresAtUtc;\n if (reservation.uploadTarget) {\n this.uploadTarget = reservation.uploadTarget;\n }\n this.reservation = reservation;\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n // fetchFn wins: pinning fetch must not be silently overridden.\n this.uploadTransport = config.fetchFn\n ? createFetchUploadTransport(config.fetchFn.bind(globalThis))\n : (config.uploadTransport ??\n createFetchUploadTransport(globalThis.fetch.bind(globalThis)));\n }\n\n async send(\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n // Presigned targets bypass Switchboard entirely: bytes go straight to the\n // provider with the exact signed headers. Switchboard targets (and the\n // legacy no-target wire) keep the authenticated reservation PUT below.\n if (this.uploadTarget?.kind === \"presigned-put\") {\n return this.sendPresigned(this.uploadTarget, data, options);\n }\n const url = `${this.remoteUrl}/attachments/reservations/${this.reservationId}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const body = await toBody(data);\n\n // Always upload as octet-stream. The server reads the real mime type from\n // the reservation row; sending the user's mime type here (e.g. application/json)\n // would let Express body-parser drain the request body before our handler runs,\n // silently writing zero bytes.\n const response = await this.uploadTransport({\n url,\n method: \"PUT\",\n headers: { ...authHeaders, \"Content-Type\": \"application/octet-stream\" },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n\n if (response.status === 422) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n if (isRecord(errorBody)) {\n if (\n errorBody.error === \"hash_mismatch\" &&\n typeof errorBody.claimed === \"string\" &&\n typeof errorBody.actual === \"string\"\n ) {\n throw new HashMismatch(errorBody.claimed, errorBody.actual);\n }\n if (\n errorBody.error === \"size_mismatch\" &&\n typeof errorBody.declared === \"number\" &&\n typeof errorBody.actual === \"number\"\n ) {\n throw new SizeMismatch(errorBody.declared, errorBody.actual);\n }\n }\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `Attachment upload failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as AttachmentUploadResult;\n }\n\n /**\n * Direct provider upload: PUT the bytes to the presigned URL with exactly\n * the returned headers — never the Switchboard JWT — and treat any 2xx as\n * final success with no follow-up control request. The result is\n * synthesized from the hash-first reservation, which is the only path that\n * can produce a presigned target.\n */\n private async sendPresigned(\n target: AttachmentUploadTarget,\n data: ReadableStream<Uint8Array> | Blob,\n options?: AttachmentSendOptions,\n ): Promise<AttachmentUploadResult> {\n if (this.reservation.clientHash === null || this.ref === null) {\n throw new Error(\n \"Presigned upload targets require a hash-first reservation\",\n );\n }\n\n const body = await toBody(data);\n const response = await this.uploadTransport({\n url: target.url,\n method: target.method,\n headers: { ...target.headers },\n body,\n ...(options?.onProgress\n ? {\n onProgress: (loaded: number, total: number) =>\n options.onProgress?.(loaded, total),\n }\n : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-put\", response.status);\n }\n\n const hash = this.reservation.clientHash as AttachmentHash;\n const now = new Date().toISOString();\n return {\n hash,\n ref: this.ref,\n header: {\n hash,\n mimeType: this.reservation.mimeType,\n fileName: this.reservation.fileName,\n sizeBytes: this.reservation.sizeBytes ?? body.size,\n extension: this.reservation.extension,\n status: \"available\",\n source: \"local\",\n createdAtUtc: this.reservation.createdAtUtc || now,\n lastAccessedAtUtc: now,\n expiresAtUtc: null,\n },\n };\n }\n}\n","import type {\n IAttachmentUpload,\n IAttachmentUploadFactory,\n} from \"../interfaces.js\";\nimport type { Reservation } from \"../types.js\";\nimport { RemoteAttachmentUpload } from \"./remote-attachment-upload.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nexport class RemoteAttachmentUploadFactory implements IAttachmentUploadFactory {\n constructor(private readonly config: SwitchboardClientConfig) {}\n\n createUpload(reservation: Reservation): IAttachmentUpload {\n return new RemoteAttachmentUpload(reservation, this.config);\n }\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { JwtHandler } from \"@powerhousedao/reactor\";\nimport {\n AttachmentNotFound,\n AttachmentPending,\n AttachmentTransferError,\n} from \"../errors.js\";\nimport type { IAttachmentReader } from \"../interfaces.js\";\nimport { parseAttachmentDownloadTarget } from \"../targets.js\";\nimport type {\n AttachmentDownloadTarget,\n AttachmentDownloadTargetOptions,\n AttachmentHeader,\n AttachmentMetadata,\n AttachmentResponse,\n} from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\nimport type { SwitchboardClientConfig } from \"./remote-reservation-store.js\";\n\nconst MISSING_DOCUMENT_ID =\n \"Remote attachment reads require the documentId whose operations reference the attachment\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAttachmentMetadata(value: unknown): value is AttachmentMetadata {\n if (!isRecord(value)) return false;\n if (typeof value.mimeType !== \"string\") return false;\n if (typeof value.fileName !== \"string\") return false;\n if (\n typeof value.sizeBytes !== \"number\" ||\n !Number.isFinite(value.sizeBytes) ||\n value.sizeBytes < 0\n ) {\n return false;\n }\n if (value.extension !== null && typeof value.extension !== \"string\") {\n return false;\n }\n if (typeof value.createdAtUtc !== \"string\") return false;\n if (\n value.lastAccessedAtUtc !== undefined &&\n typeof value.lastAccessedAtUtc !== \"string\"\n ) {\n return false;\n }\n return true;\n}\n\nfunction contentTypeFallback(response: Response): AttachmentMetadata {\n const contentLength = response.headers.get(\"Content-Length\");\n if (contentLength === null) {\n throw new Error(\n \"Switchboard response missing both Attachment-Metadata and Content-Length headers\",\n );\n }\n const sizeBytes = Number(contentLength);\n if (!Number.isInteger(sizeBytes) || sizeBytes < 0) {\n throw new Error(\n `Switchboard response has invalid Content-Length header: ${JSON.stringify(contentLength)}`,\n );\n }\n // Last-Modified is the closest legitimate signal we have for an original\n // creation time when Attachment-Metadata is absent. If that's missing too,\n // fall back to the response date (still server-attributed). This is\n // imperfect — Last-Modified reflects the most recent change, not the\n // original upload — but unlike sizeBytes there is no zero-equivalent\n // sentinel for a date, and downstream consumers expect a value.\n const lastModified = response.headers.get(\"Last-Modified\");\n const dateHeader = response.headers.get(\"Date\");\n const createdAtUtc = lastModified\n ? new Date(lastModified).toISOString()\n : dateHeader\n ? new Date(dateHeader).toISOString()\n : new Date().toISOString();\n\n return {\n // application/octet-stream is the RFC 2046 sentinel for \"unknown binary\",\n // and \"unknown\" is a non-real filename sentinel; neither is a fabricated\n // semantic value the way Content-Length=0 would be.\n mimeType:\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\",\n fileName: \"unknown\",\n sizeBytes,\n extension: null,\n createdAtUtc,\n lastAccessedAtUtc: createdAtUtc,\n };\n}\n\nfunction parseMetadata(response: Response): AttachmentMetadata {\n // Compute the fallback at most once; both the recovery path inside the\n // header parser and the outer \"no header / parse failed\" path share it.\n let fallbackCache: AttachmentMetadata | undefined;\n const fallback = (): AttachmentMetadata => {\n if (fallbackCache === undefined) {\n fallbackCache = contentTypeFallback(response);\n }\n return fallbackCache;\n };\n\n const metaHeader = response.headers.get(\"Attachment-Metadata\");\n if (metaHeader) {\n try {\n const parsed: unknown = JSON.parse(metaHeader);\n if (isRecord(parsed)) {\n if (parsed.extension === undefined) {\n parsed.extension = null;\n }\n // Older switchboards may omit these timestamps; fall back to the\n // Date/Last-Modified header so we never produce client-clock-stamped\n // values when the server has authority.\n if (parsed.createdAtUtc === undefined) {\n parsed.createdAtUtc = fallback().createdAtUtc;\n }\n if (parsed.lastAccessedAtUtc === undefined) {\n parsed.lastAccessedAtUtc = fallback().lastAccessedAtUtc;\n }\n }\n if (isAttachmentMetadata(parsed)) {\n return parsed;\n }\n } catch {\n // fall through to Content-Type fallback\n }\n }\n return fallback();\n}\n\ntype PendingInfo = {\n expiresAtUtc: string;\n mimeType: string;\n fileName: string;\n sizeBytes: number;\n};\n\ntype PartialPendingInfo = {\n expiresAtUtc: string;\n mimeType?: string;\n fileName?: string;\n sizeBytes?: number;\n};\n\nfunction parsePendingExpiry(response: Response): PartialPendingInfo | null {\n const header = response.headers.get(\"Attachment-Pending\");\n if (!header) return null;\n try {\n const parsed: unknown = JSON.parse(header);\n if (!isRecord(parsed)) return null;\n if (typeof parsed.expiresAtUtc !== \"string\") return null;\n const result: PartialPendingInfo = { expiresAtUtc: parsed.expiresAtUtc };\n if (typeof parsed.mimeType === \"string\") result.mimeType = parsed.mimeType;\n if (typeof parsed.fileName === \"string\") result.fileName = parsed.fileName;\n if (\n typeof parsed.sizeBytes === \"number\" &&\n Number.isFinite(parsed.sizeBytes) &&\n parsed.sizeBytes >= 0\n ) {\n result.sizeBytes = parsed.sizeBytes;\n }\n return result;\n } catch {\n return null;\n }\n}\n\nfunction parsePendingHeader(response: Response): PendingInfo | null {\n const partial = parsePendingExpiry(response);\n if (!partial) return null;\n if (\n typeof partial.mimeType !== \"string\" ||\n typeof partial.fileName !== \"string\" ||\n partial.sizeBytes === undefined\n ) {\n return null;\n }\n return {\n expiresAtUtc: partial.expiresAtUtc,\n mimeType: partial.mimeType,\n fileName: partial.fileName,\n sizeBytes: partial.sizeBytes,\n };\n}\n\nexport class RemoteAttachmentStore implements IAttachmentReader {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardClientConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n /**\n * Get attachment metadata. Normally returns a pending AttachmentHeader\n * (status: 'pending') when the server responds 202 with a full\n * Attachment-Pending header. When only expiresAtUtc is present in the\n * header (degraded wire), throws AttachmentPending instead -- the\n * AttachmentPending throw is the degraded-wire case.\n */\n async stat(\n hash: AttachmentHash,\n documentId?: string,\n ): Promise<AttachmentHeader> {\n // The server answers a hash-only HEAD 404; hash-first reserve relies on\n // that to leave the dedup decision to the server's 409.\n if (documentId === undefined) {\n throw new AttachmentNotFound(hash);\n }\n const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"HEAD\",\n headers: authHeaders,\n });\n\n if (response.status === 202) {\n const fullPending = parsePendingHeader(response);\n if (fullPending) {\n return buildPendingHeader(hash, fullPending);\n }\n const partial = parsePendingExpiry(response);\n if (partial) {\n throw new AttachmentPending(hash, partial.expiresAtUtc);\n }\n throw new Error(\n \"Attachment stat returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment stat failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const metadata = parseMetadata(response);\n return buildHeader(hash, metadata);\n }\n\n async get(\n hash: AttachmentHash,\n signal?: AbortSignal,\n documentId?: string,\n ): Promise<AttachmentResponse> {\n if (documentId === undefined) {\n throw new Error(MISSING_DOCUMENT_ID);\n }\n const target = await this.getDownloadTarget(hash, { documentId, signal });\n if (target.kind === \"presigned-get\") {\n return this.fetchPresigned(hash, target, signal);\n }\n return this.fetchAttachment(hash, target, signal);\n }\n\n /**\n * Asks Switchboard for an authorized download target. The request carries\n * the JWT; the response is runtime-validated before any byte transfer.\n * Public so callers can mint direct URLs (previews, share links) without\n * transferring bytes; `expiresIn` requests a caller-chosen lifetime.\n */\n async getDownloadTarget(\n hash: AttachmentHash,\n options: AttachmentDownloadTargetOptions,\n ): Promise<AttachmentDownloadTarget> {\n const { documentId, expiresIn, signal } = options;\n const expiry =\n expiresIn === undefined\n ? \"\"\n : `&expiresIn=${encodeURIComponent(String(expiresIn))}`;\n const url = `${this.remoteUrl}/attachments/${hash}/download-target?documentId=${encodeURIComponent(documentId)}${expiry}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"download-target\", response.status);\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new AttachmentTransferError(\"download-target\");\n }\n return parseAttachmentDownloadTarget(body);\n }\n\n /**\n * Executes a presigned GET with exactly the returned headers and no JWT.\n * A provider 404 means the object is missing despite available metadata\n * (the accepted abandoned-upload trade-off) and surfaces as the same typed\n * not-found error callers already handle.\n */\n private async fetchPresigned(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const response = await this.fetchFn(target.url, {\n signal,\n headers: { ...target.headers },\n });\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new AttachmentTransferError(\"presigned-get\", response.status);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n\n private async fetchAttachment(\n hash: AttachmentHash,\n target: AttachmentDownloadTarget,\n signal?: AbortSignal,\n ): Promise<AttachmentResponse> {\n const url = target.url;\n const authHeaders = await buildAuthHeaders(url, this.jwtHandler);\n const headers = { ...target.headers, ...authHeaders };\n\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 202) {\n const pending = parsePendingExpiry(response);\n if (!pending) {\n throw new Error(\n \"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n throw new AttachmentPending(hash, pending.expiresAtUtc);\n }\n\n if (response.status === 404) {\n throw new AttachmentNotFound(hash);\n }\n if (!response.ok) {\n throw new Error(\n `Attachment fetch failed: ${response.status} ${response.statusText}`,\n );\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const metadata = parseMetadata(response);\n return { header: buildHeader(hash, metadata), body: response.body };\n }\n}\n\nfunction buildHeader(\n hash: AttachmentHash,\n metadata: AttachmentMetadata,\n): AttachmentHeader {\n return {\n hash,\n mimeType: metadata.mimeType,\n fileName: metadata.fileName,\n sizeBytes: metadata.sizeBytes,\n extension: metadata.extension,\n status: \"available\",\n source: \"sync\",\n createdAtUtc: metadata.createdAtUtc,\n lastAccessedAtUtc: metadata.lastAccessedAtUtc ?? metadata.createdAtUtc,\n expiresAtUtc: null,\n };\n}\n\nfunction buildPendingHeader(\n hash: AttachmentHash,\n pending: PendingInfo,\n): AttachmentHeader {\n const now = new Date().toISOString();\n return {\n hash,\n mimeType: pending.mimeType,\n fileName: pending.fileName,\n sizeBytes: pending.sizeBytes,\n extension: null,\n status: \"pending\",\n source: \"sync\",\n createdAtUtc: now,\n lastAccessedAtUtc: now,\n expiresAtUtc: pending.expiresAtUtc,\n };\n}\n","import { AttachmentService } from \"../attachment-service.js\";\nimport type { IAttachmentService } from \"../interfaces.js\";\nimport { RemoteAttachmentStore } from \"./remote-attachment-store.js\";\nimport { RemoteAttachmentUploadFactory } from \"./remote-attachment-upload-factory.js\";\nimport {\n RemoteReservationStore,\n type SwitchboardClientConfig,\n} from \"./remote-reservation-store.js\";\n\nexport function createRemoteAttachmentService(\n config: SwitchboardClientConfig,\n): IAttachmentService {\n const reservations = new RemoteReservationStore(config);\n const uploadFactory = new RemoteAttachmentUploadFactory(config);\n const store = new RemoteAttachmentStore(config);\n return new AttachmentService(store, reservations, uploadFactory);\n}\n","import type { IAttachmentTransport } from \"./interfaces.js\";\nimport type { TransportFetchResult } from \"./types.js\";\n\n/**\n * No-op transport for deployments without remote sync.\n * fetch() always returns not-found, announce() and push() are no-ops.\n */\nexport class NullAttachmentTransport implements IAttachmentTransport {\n fetch(): Promise<TransportFetchResult> {\n return Promise.resolve({ kind: \"not-found\" });\n }\n\n announce(): Promise<void> {\n return Promise.resolve();\n }\n\n push(): Promise<void> {\n return Promise.resolve();\n }\n}\n"],"mappings":";;AAMA,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAwB;CACxC,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAChD,MAAM,IAAI,MAAM,kDAAkD;CAEpE,IAAI,MAAM,KAAK,MAAM,SAAS,0BAA0B,KAAK,GAC3D,MAAM,IAAI,MAAM,uDAAuD;CAEzE,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,KAAK;CACxB,QAAQ;EACN,MAAM,IAAI,MAAM,kCAAkC;CACpD;CACA,IACG,OAAO,aAAa,WAAW,OAAO,aAAa,YACpD,OAAO,aAAa,MACpB,OAAO,aAAa,IAEpB,MAAM,IAAI,MACR,wEACF;CAIF,OAAO;AACT;AAEA,SAAS,aAAa,OAAyC;CAC7D,IAAI,CAACA,WAAS,KAAK,GACjB,MAAM,IAAI,MAAM,6CAA6C;CAI/D,MAAM,UAAU,OAAO,OAAO,IAAI;CAClC,MAAM,aAAa;CACnB,KAAK,MAAM,CAAC,MAAM,gBAAgB,OAAO,QAAQ,KAAK,GAAG;EACvD,IAAI,CAAC,WAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,6CAA6C,MAAM;EAErE,IACE,OAAO,gBAAgB,YACvB,4BAA4B,WAAW,GAEvC,MAAM,IAAI,MAAM,8CAA8C,MAAM;EAEtE,QAAQ,QAAQ;CAClB;CACA,OAAO;AACT;AAEA,SAAS,4BAA4B,OAAwB;CAC3D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAA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BAAqB,SAAS;EAC1D,cAAc;CAChB;AACF;AAEA,SAAS,mBACP,MACA,SACkB;CAClB,MAAM,uBAAM,IAAI,KAAK,EAAA,CAAE,YAAY;CACnC,OAAO;EACL;EACA,UAAU,QAAQ;EAClB,UAAU,QAAQ;EAClB,WAAW,QAAQ;EACnB,WAAW;EACX,QAAQ;EACR,QAAQ;EACR,cAAc;EACd,mBAAmB;EACnB,cAAc,QAAQ;CACxB;AACF;;;ACrYA,SAAgB,8BACd,QACoB;CACpB,MAAM,eAAe,IAAI,uBAAuB,MAAM;CACtD,MAAM,gBAAgB,IAAI,8BAA8B,MAAM;CAE9D,OAAO,IAAI,kBAAkB,IADX,sBAAsB,MACX,GAAO,cAAc,aAAa;AACjE;;;;;;;ACTA,IAAa,0BAAb,MAAqE;CACnE,QAAuC;EACrC,OAAO,QAAQ,QAAQ,EAAE,MAAM,YAAY,CAAC;CAC9C;CAEA,WAA0B;EACxB,OAAO,QAAQ,QAAQ;CACzB;CAEA,OAAsB;EACpB,OAAO,QAAQ,QAAQ;CACzB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"null-attachment-transport-Bs4JpmFx.d.ts","names":[],"sources":["../src/errors.ts","../src/targets.ts","../src/attachment-service.ts","../src/ref.ts","../src/switchboard/switchboard-attachment-transport.ts","../src/switchboard/upload-transport.ts","../src/switchboard/xhr-upload-transport.ts","../src/switchboard/remote-reservation-store.ts","../src/switchboard/remote-attachment-upload.ts","../src/switchboard/remote-attachment-upload-factory.ts","../src/switchboard/remote-attachment-store.ts","../src/switchboard/create-remote-attachment-service.ts","../src/null-attachment-transport.ts"],"mappings":";;;;;;cAKa,2BAA2B;EACtC,YAAY;;;;;cASD,4BAA4B;EACvC,YAAY;;;;;cASD,6BAA6B;EACxC,YAAY;;;KAOF;;;;;cAMC,kCAAkC;WACpC,OAAO;EAChB,YAAY,OAAO;;;;;;cAWR,uBAAuB;WACzB;EACT,YAAY;;;;;;;cAYD,gCAAgC;WAClC,MAAM;WAC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