@powerhousedao/reactor-attachments 6.2.3-dev.8 → 6.2.3-staging.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
1
  import { AttachmentHash, AttachmentRef, JwtHandler } from "@powerhousedao/reactor";
2
-
3
2
  //#region src/errors.d.ts
4
3
  /**
5
4
  * Thrown when an attachment ref or hash is not known to the store.
@@ -230,6 +229,10 @@ type AttachmentDownloadOptions = {
230
229
  documentId?: string;
231
230
  signal?: AbortSignal;
232
231
  };
232
+ /** Options form of IAttachmentService.stat. */
233
+ type AttachmentStatOptions = {
234
+ documentId?: string;
235
+ };
233
236
  /**
234
237
  * Options for minting a raw download target without transferring bytes
235
238
  * (previews, share links). `documentId` is required: targets are always
@@ -373,8 +376,11 @@ interface IAttachmentService {
373
376
  * Returns an AttachmentHeader with status='pending' and expiresAtUtc set if
374
377
  * the hash has an active reservation but no committed bytes. Callers must
375
378
  * check header.status to distinguish pending from available.
379
+ *
380
+ * `documentId` names the document that authorizes the read. Remote readers
381
+ * require it; local/direct readers ignore it.
376
382
  */
377
- stat(ref: AttachmentRef): Promise<AttachmentHeader>;
383
+ stat(ref: AttachmentRef, options?: AttachmentStatOptions): Promise<AttachmentHeader>;
378
384
  /**
379
385
  * Retrieve attachment data.
380
386
  *
@@ -389,8 +395,7 @@ interface IAttachmentService {
389
395
  * callers cannot tune it.
390
396
  *
391
397
  * The options form carries the document id that authorizes a remote
392
- * download; local/direct readers ignore it. The bare-signal form remains
393
- * supported for source compatibility.
398
+ * download. Remote readers require it; local/direct readers ignore it.
394
399
  */
395
400
  get(ref: AttachmentRef, options?: AbortSignal | AttachmentDownloadOptions): Promise<AttachmentResponse>;
396
401
  /**
@@ -483,16 +488,19 @@ interface IAttachmentReader {
483
488
  * Returns an AttachmentHeader with status='pending' and expiresAtUtc set if
484
489
  * the hash has an active reservation but no committed bytes. Callers must
485
490
  * check header.status to distinguish pending from available.
491
+ *
492
+ * `documentId` is the authorization anchor: remote readers require it,
493
+ * local/direct readers ignore it.
486
494
  */
487
- stat(hash: AttachmentHash): Promise<AttachmentHeader>;
495
+ stat(hash: AttachmentHash, documentId?: string): Promise<AttachmentHeader>;
488
496
  /**
489
497
  * Retrieve attachment header and data stream by hash.
490
498
  * Updates lastAccessedAtUtc on access.
491
499
  *
492
- * If the data has been evicted, re-fetches it from the transport,
493
- * restores it locally via put(), and returns the data. This makes
494
- * eviction transparent to callers -- get() always succeeds for
495
- * any known, available hash.
500
+ * If the data has been evicted or was never local, re-fetches it from the
501
+ * transport on behalf of `documentId`, restores it locally via put(), and
502
+ * returns the data. Without a `documentId` there is nothing to authorize
503
+ * the remote fetch, so only locally available bytes are served.
496
504
  *
497
505
  * @throws AttachmentNotFound if the hash is unknown (no metadata
498
506
  * record exists and no pending reservation).
@@ -500,8 +508,8 @@ interface IAttachmentReader {
500
508
  * upload; bytes are not yet available. There is no store-level
501
509
  * wait -- polling is the caller's responsibility.
502
510
  *
503
- * `documentId` is the authorization anchor for remote readers that must
504
- * negotiate a download target; local/direct readers ignore it.
511
+ * `documentId` is the authorization anchor: remote readers require it,
512
+ * and local stores pass it to the transport when they must re-fetch.
505
513
  */
506
514
  get(hash: AttachmentHash, signal?: AbortSignal, documentId?: string): Promise<AttachmentResponse>;
507
515
  /**
@@ -577,9 +585,11 @@ interface IAttachmentTransport {
577
585
  * or to retry indefinitely on a permanently missing hash.
578
586
  *
579
587
  * @param hash - Content hash of the attachment
588
+ * @param documentId - Document whose operations reference the attachment;
589
+ * the remote authorizes the fetch through it
580
590
  * @param signal - Abort signal for cancellation
581
591
  */
582
- fetch(hash: AttachmentHash, signal?: AbortSignal): Promise<TransportFetchResult>;
592
+ fetch(hash: AttachmentHash, documentId: string, signal?: AbortSignal): Promise<TransportFetchResult>;
583
593
  /**
584
594
  * Announce that this reactor has attachment data available.
585
595
  *
@@ -661,7 +671,7 @@ declare class AttachmentService implements IAttachmentService {
661
671
  private readonly backend?;
662
672
  constructor(store: IAttachmentReader, reservations: IReservationStore, uploadFactory: IAttachmentUploadFactory, backend?: IAttachmentBackend | undefined);
663
673
  reserve(options: ReserveAttachmentOptions): Promise<IAttachmentUpload>;
664
- stat(ref: AttachmentRef): Promise<AttachmentHeader>;
674
+ stat(ref: AttachmentRef, options?: AttachmentStatOptions): Promise<AttachmentHeader>;
665
675
  get(ref: AttachmentRef, options?: AbortSignal | AttachmentDownloadOptions): Promise<AttachmentResponse>;
666
676
  getDownloadTarget(ref: AttachmentRef, options: AttachmentDownloadTargetOptions): Promise<AttachmentDownloadTarget>;
667
677
  private reserveHashFirst;
@@ -686,7 +696,7 @@ declare class SwitchboardAttachmentTransport implements IAttachmentTransport {
686
696
  private readonly jwtHandler?;
687
697
  private readonly fetchFn;
688
698
  constructor(config: SwitchboardTransportConfig);
689
- fetch(hash: AttachmentHash, signal?: AbortSignal): Promise<TransportFetchResult>;
699
+ fetch(hash: AttachmentHash, documentId: string, signal?: AbortSignal): Promise<TransportFetchResult>;
690
700
  announce(_hash: AttachmentHash): Promise<void>;
691
701
  push(hash: AttachmentHash, remote: string, data: ReadableStream<Uint8Array>): Promise<void>;
692
702
  private parsePendingExpiry;
@@ -713,7 +723,8 @@ type AttachmentUploadRequest = {
713
723
  url: string;
714
724
  method: "PUT";
715
725
  headers: Record<string, string>;
716
- body: Blob; /** Called with cumulative bytes handed to the socket, when observable. */
726
+ body: Blob;
727
+ /** Called with cumulative bytes handed to the socket, when observable. */
717
728
  onProgress?: (loaded: number, total: number) => void;
718
729
  signal?: AbortSignal;
719
730
  };
@@ -827,7 +838,7 @@ declare class RemoteAttachmentStore implements IAttachmentReader {
827
838
  * header (degraded wire), throws AttachmentPending instead -- the
828
839
  * AttachmentPending throw is the degraded-wire case.
829
840
  */
830
- stat(hash: AttachmentHash): Promise<AttachmentHeader>;
841
+ stat(hash: AttachmentHash, documentId?: string): Promise<AttachmentHeader>;
831
842
  get(hash: AttachmentHash, signal?: AbortSignal, documentId?: string): Promise<AttachmentResponse>;
832
843
  /**
833
844
  * Asks Switchboard for an authorized download target. The request carries
@@ -860,5 +871,6 @@ declare class NullAttachmentTransport implements IAttachmentTransport {
860
871
  push(): Promise<void>;
861
872
  }
862
873
  //#endregion
863
- export { AttachmentPending as $, IReservationStore as A, AttachmentStatus as B, IAttachmentReader as C, IAttachmentTransportFactory as D, IAttachmentTransport as E, AttachmentDownloadTargetOptions as F, HashFirstReserveAttachmentOptions as G, AttachmentTransportConfig as H, AttachmentHeader as I, TransportFetchResult as J, Reservation as K, AttachmentMetadata as L, AttachmentBackendKind as M, AttachmentDownloadOptions as N, IAttachmentUpload as O, AttachmentDownloadTarget as P, AttachmentNotFound as Q, AttachmentResponse as R, IAttachmentBackend as S, IAttachmentStore as T, AttachmentUploadResult as U, AttachmentTargetHeaders as V, AttachmentUploadTarget as W, UploadFirstReserveAttachmentOptions as X, TransportResponse as Y, AttachmentAlreadyExists as Z, createRef as _, RemoteAttachmentUpload as a, SizeMismatch as at, parseAttachmentDownloadTarget as b, XhrUploadTransportOptions as c, AttachmentUploadResponse as d, AttachmentTransferError as et, AttachmentUploadTransport as f, ParsedRef as g, SwitchboardTransportConfig as h, RemoteAttachmentUploadFactory as i, ReservationNotFound as it, AttachmentBackendHealth as j, IAttachmentUploadFactory as k, createXhrUploadTransport as l, SwitchboardAttachmentTransport as m, createRemoteAttachmentService as n, HashMismatch as nt, RemoteReservationStore as o, UploadTooLarge as ot, createFetchUploadTransport as p, ReserveAttachmentOptions as q, RemoteAttachmentStore as r, InvalidAttachmentRef as rt, SwitchboardClientConfig as s, NullAttachmentTransport as t, AttachmentTransferStage as tt, AttachmentUploadRequest as u, parseRef as v, IAttachmentService as w, parseAttachmentUploadTarget as x, AttachmentService as y, AttachmentSendOptions as z };
864
- //# sourceMappingURL=null-attachment-transport-CMrO_ZKA.d.ts.map
874
+ export { AttachmentNotFound as $, IReservationStore as A, AttachmentStatOptions as B, IAttachmentReader as C, IAttachmentTransportFactory as D, IAttachmentTransport as E, AttachmentDownloadTargetOptions as F, AttachmentUploadTarget as G, AttachmentTargetHeaders as H, AttachmentHeader as I, ReserveAttachmentOptions as J, HashFirstReserveAttachmentOptions as K, AttachmentMetadata as L, AttachmentBackendKind as M, AttachmentDownloadOptions as N, IAttachmentUpload as O, AttachmentDownloadTarget as P, AttachmentAlreadyExists as Q, AttachmentResponse as R, IAttachmentBackend as S, IAttachmentStore as T, AttachmentTransportConfig as U, AttachmentStatus as V, AttachmentUploadResult as W, TransportResponse as X, TransportFetchResult as Y, UploadFirstReserveAttachmentOptions as Z, createRef as _, RemoteAttachmentUpload as a, ReservationNotFound as at, parseAttachmentDownloadTarget as b, XhrUploadTransportOptions as c, AttachmentUploadResponse as d, AttachmentPending as et, AttachmentUploadTransport as f, ParsedRef as g, SwitchboardTransportConfig as h, RemoteAttachmentUploadFactory as i, InvalidAttachmentRef as it, AttachmentBackendHealth as j, IAttachmentUploadFactory as k, createXhrUploadTransport as l, SwitchboardAttachmentTransport as m, createRemoteAttachmentService as n, AttachmentTransferStage as nt, RemoteReservationStore as o, SizeMismatch as ot, createFetchUploadTransport as p, Reservation as q, RemoteAttachmentStore as r, HashMismatch as rt, SwitchboardClientConfig as s, UploadTooLarge as st, NullAttachmentTransport as t, AttachmentTransferError as tt, AttachmentUploadRequest as u, parseRef as v, IAttachmentService as w, parseAttachmentUploadTarget as x, AttachmentService as y, AttachmentSendOptions as z };
875
+ export {};
876
+ //# sourceMappingURL=null-attachment-transport-BkM6rq4R.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"null-attachment-transport-BkM6rq4R.d.ts","names":[],"sources":["../src/errors.ts","../src/types.ts","../src/interfaces.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;;;;;;cAUD,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;;;;;KCrJrC;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;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d,gBAAgB,QACf;;;KC1CS;;;;;EAKV,iBAAiB;;;;;;;;;;;;;iBAcH,yBACd,UAAU,4BACT;;;KCnBS;EACV;EACA,aAAa;EACb,iBAAiB;;;;;;;;;;;EAWjB,kBAAkB;;cAsDP,kCAAkC;mBAC5B;mBACA;mBACA;EAEjB,YAAY,QAAQ;EAMd,OAAO,SAAS,2BAA2B,QAAQ;EA0GnD,IAAI,wBAAwB,QAAQ;EA4CpC,OAAO,wBAAwB;EAmBrC,iBAAiB;;;;cCpON,kCAAkC;WACpC;WACA,KAAK;WACL;WACA,eAAe;mBACP;mBACA;mBACA;mBACA;EAEjB,YAAY,aAAa,aAAa,QAAQ;EAoBxC,KACJ,MAAM,eAAe,aACrB,UAAU,wBACT,QAAQ;;;;;;;;UAgFG;;;;cCtIH,yCAAyC;mBACvB;EAA7B,YAA6B,QAAQ;EAErC,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"}
@@ -236,6 +236,10 @@ function createRef(hash, version = DEFAULT_VERSION) {
236
236
  //#region src/attachment-service.ts
237
237
  const CLIENT_HASH_PATTERN = /^[a-f0-9]{64}$/;
238
238
  var AttachmentService = class {
239
+ store;
240
+ reservations;
241
+ uploadFactory;
242
+ backend;
239
243
  constructor(store, reservations, uploadFactory, backend) {
240
244
  this.store = store;
241
245
  this.reservations = reservations;
@@ -248,9 +252,9 @@ var AttachmentService = class {
248
252
  const reservation = await this.reservations.create(options);
249
253
  return this.uploadFactory.createUpload(reservation);
250
254
  }
251
- async stat(ref) {
255
+ async stat(ref, options) {
252
256
  const { hash } = parseRef(ref);
253
- return this.store.stat(hash);
257
+ return options?.documentId === void 0 ? this.store.stat(hash) : this.store.stat(hash, options.documentId);
254
258
  }
255
259
  async get(ref, options) {
256
260
  const { hash } = parseRef(ref);
@@ -312,8 +316,8 @@ var SwitchboardAttachmentTransport = class {
312
316
  this.jwtHandler = config.jwtHandler;
313
317
  this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);
314
318
  }
315
- async fetch(hash, signal) {
316
- const url = `${this.remoteUrl}/attachments/${hash}`;
319
+ async fetch(hash, documentId, signal) {
320
+ const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;
317
321
  const headers = await buildAuthHeaders(url, this.jwtHandler);
318
322
  const response = await this.fetchFn(url, {
319
323
  signal,
@@ -623,7 +627,7 @@ var RemoteReservationStore = class {
623
627
  fileName: options.fileName,
624
628
  extension,
625
629
  createdAtUtc: body.createdAtUtc ?? now.toISOString(),
626
- expiresAtUtc: body.expiresAtUtc ?? new Date(now.getTime() + 1440 * 60 * 1e3).toISOString(),
630
+ expiresAtUtc: body.expiresAtUtc ?? new Date(now.getTime() + 864e5).toISOString(),
627
631
  clientHash: options.clientHash ?? null,
628
632
  sizeBytes: options.sizeBytes ?? null,
629
633
  ...body.uploadTarget === void 0 ? {} : { uploadTarget: parseAttachmentUploadTarget(body.uploadTarget) }
@@ -765,6 +769,7 @@ var RemoteAttachmentUpload = class {
765
769
  //#endregion
766
770
  //#region src/switchboard/remote-attachment-upload-factory.ts
767
771
  var RemoteAttachmentUploadFactory = class {
772
+ config;
768
773
  constructor(config) {
769
774
  this.config = config;
770
775
  }
@@ -774,6 +779,7 @@ var RemoteAttachmentUploadFactory = class {
774
779
  };
775
780
  //#endregion
776
781
  //#region src/switchboard/remote-attachment-store.ts
782
+ const MISSING_DOCUMENT_ID = "Remote attachment reads require the documentId whose operations reference the attachment";
777
783
  function isRecord(value) {
778
784
  return typeof value === "object" && value !== null && !Array.isArray(value);
779
785
  }
@@ -865,8 +871,9 @@ var RemoteAttachmentStore = class {
865
871
  * header (degraded wire), throws AttachmentPending instead -- the
866
872
  * AttachmentPending throw is the degraded-wire case.
867
873
  */
868
- async stat(hash) {
869
- const url = `${this.remoteUrl}/attachments/${hash}`;
874
+ async stat(hash, documentId) {
875
+ if (documentId === void 0) throw new AttachmentNotFound(hash);
876
+ const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;
870
877
  const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
871
878
  const response = await this.fetchFn(url, {
872
879
  method: "HEAD",
@@ -884,13 +891,13 @@ var RemoteAttachmentStore = class {
884
891
  return buildHeader(hash, parseMetadata(response));
885
892
  }
886
893
  async get(hash, signal, documentId) {
887
- if (documentId === void 0) return this.fetchAttachment(hash, signal);
894
+ if (documentId === void 0) throw new Error(MISSING_DOCUMENT_ID);
888
895
  const target = await this.getDownloadTarget(hash, {
889
896
  documentId,
890
897
  signal
891
898
  });
892
899
  if (target.kind === "presigned-get") return this.fetchPresigned(hash, target, signal);
893
- return this.fetchAttachment(hash, signal, target);
900
+ return this.fetchAttachment(hash, target, signal);
894
901
  }
895
902
  /**
896
903
  * Asks Switchboard for an authorized download target. The request carries
@@ -936,11 +943,11 @@ var RemoteAttachmentStore = class {
936
943
  body: response.body
937
944
  };
938
945
  }
939
- async fetchAttachment(hash, signal, target) {
940
- const url = target?.url ?? `${this.remoteUrl}/attachments/${hash}`;
946
+ async fetchAttachment(hash, target, signal) {
947
+ const url = target.url;
941
948
  const authHeaders = await buildAuthHeaders(url, this.jwtHandler);
942
949
  const headers = {
943
- ...target?.headers,
950
+ ...target.headers,
944
951
  ...authHeaders
945
952
  };
946
953
  const response = await this.fetchFn(url, {
@@ -1017,4 +1024,4 @@ var NullAttachmentTransport = class {
1017
1024
  //#endregion
1018
1025
  export { UploadTooLarge as C, SizeMismatch as S, AttachmentPending as _, RemoteAttachmentUpload as a, InvalidAttachmentRef as b, createFetchUploadTransport as c, createRef as d, parseRef as f, AttachmentNotFound as g, AttachmentAlreadyExists as h, RemoteAttachmentUploadFactory as i, SwitchboardAttachmentTransport as l, parseAttachmentUploadTarget as m, createRemoteAttachmentService as n, RemoteReservationStore as o, parseAttachmentDownloadTarget as p, RemoteAttachmentStore as r, createXhrUploadTransport as s, NullAttachmentTransport as t, AttachmentService as u, AttachmentTransferError as v, ReservationNotFound as x, HashMismatch as y };
1019
1026
 
1020
- //# sourceMappingURL=null-attachment-transport-CrsUafCi.js.map
1027
+ //# sourceMappingURL=null-attachment-transport-D53Rz9lE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"null-attachment-transport-D53Rz9lE.js","names":["isRecord","isRecord","contentTypeFallback","isAttachmentMetadata","isRecord","isRecord"],"sources":["../src/errors.ts","../src/targets.ts","../src/ref.ts","../src/attachment-service.ts","../src/switchboard/build-auth-headers.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"],"sourcesContent":["import type { AttachmentHash, AttachmentRef } from \"@powerhousedao/reactor\";\n\n/**\n * Thrown when an attachment ref or hash is not known to the store.\n */\nexport class AttachmentNotFound extends Error {\n constructor(identifier: string) {\n super(`Attachment not found: ${identifier}`);\n this.name = \"AttachmentNotFound\";\n }\n}\n\n/**\n * Thrown when a reservation ID is not found in the reservation store.\n */\nexport class ReservationNotFound extends Error {\n constructor(reservationId: string) {\n super(`Reservation not found: ${reservationId}`);\n this.name = \"ReservationNotFound\";\n }\n}\n\n/**\n * Thrown when an attachment ref string does not match the expected format.\n */\nexport class InvalidAttachmentRef extends Error {\n constructor(ref: string) {\n super(`Invalid attachment ref: ${ref}`);\n this.name = \"InvalidAttachmentRef\";\n }\n}\n\n/**\n * Thrown when an upload exceeds the configured maximum byte cap.\n * Route handlers should map this to HTTP 413 Payload Too Large.\n */\nexport class UploadTooLarge extends Error {\n readonly maxBytes: number;\n constructor(maxBytes: number) {\n super(`Upload exceeds maximum size of ${maxBytes} bytes`);\n this.name = \"UploadTooLarge\";\n this.maxBytes = maxBytes;\n }\n}\n\n/**\n * Thrown by reserve() when the claimed hash is already available in the store.\n * The caller should use err.ref directly and upload nothing -- this is the\n * dedup fast path: duplicate content never leaves the client.\n */\nexport class AttachmentAlreadyExists extends Error {\n readonly hash: AttachmentHash;\n readonly ref: AttachmentRef;\n constructor(hash: AttachmentHash, ref: AttachmentRef) {\n super(`Attachment already exists for hash: ${hash}`);\n this.name = \"AttachmentAlreadyExists\";\n this.hash = hash;\n this.ref = ref;\n }\n}\n\n/**\n * Thrown by send() when the server-computed hash of the uploaded bytes\n * does not match the hash claimed at reservation time. Nothing is committed;\n * the reservation is retained so the client can retry with correct bytes.\n */\nexport class HashMismatch extends Error {\n readonly claimed: AttachmentHash;\n readonly actual: AttachmentHash;\n constructor(claimed: AttachmentHash, actual: AttachmentHash) {\n super(`Hash mismatch: claimed ${claimed} but computed ${actual}`);\n this.name = \"HashMismatch\";\n this.claimed = claimed;\n this.actual = actual;\n }\n}\n\n/**\n * Thrown by send() when the uploaded byte count does not equal the\n * sizeBytes declared at reservation time. The handle may reject\n * mid-stream as soon as the count exceeds the declaration.\n * Nothing is committed; the reservation is retained for retry.\n *\n * \"actual\" is the byte count received from the stream before aborting --\n * it includes the chunk that crossed the declaration and can exceed bytes\n * persisted. On mid-stream aborts the true total is unknown; at least\n * \"actual\" bytes were sent.\n */\nexport class SizeMismatch extends Error {\n readonly declared: number;\n readonly actual: number;\n constructor(declared: number, actual: number) {\n super(`Size mismatch: declared ${declared} bytes but received ${actual}`);\n this.name = \"SizeMismatch\";\n this.declared = declared;\n this.actual = actual;\n }\n}\n\n/**\n * Thrown by get() when the hash is reserved by an in-flight upload and\n * bytes are not yet available anywhere. Deliberately NOT a subclass of\n * AttachmentNotFound -- callers must distinguish \"retry later\" from \"unknown\".\n * After expiresAtUtc has passed the hash reads as not found.\n *\n * metadata is populated when the reservation is local and its fields are\n * known (mimeType, fileName, sizeBytes). It is undefined when the pending\n * state is learned from a remote transport that did not supply the full\n * Attachment-Pending header (transport-pending / degraded wire case).\n */\nexport type AttachmentTransferStage =\n | \"download-target\"\n | \"switchboard-get\"\n | \"presigned-get\"\n | \"presigned-put\";\n\n/**\n * Thrown when a remote transfer step fails. Identifies the stage only; it\n * intentionally carries no URL, signature query, bucket key, or bearer\n * material so it is always safe to log or surface.\n */\nexport class AttachmentTransferError extends Error {\n readonly stage: AttachmentTransferStage;\n readonly status: number | undefined;\n\n constructor(stage: AttachmentTransferStage, status?: number) {\n super(\n status === undefined\n ? `Attachment ${stage} request failed`\n : `Attachment ${stage} request failed with status ${status}`,\n );\n this.name = \"AttachmentTransferError\";\n this.stage = stage;\n this.status = status;\n }\n}\n\nexport class AttachmentPending extends Error {\n readonly hash: AttachmentHash;\n readonly expiresAtUtc: string;\n readonly metadata:\n | {\n readonly mimeType: string;\n readonly fileName: string;\n readonly sizeBytes: number;\n }\n | undefined;\n\n constructor(\n hash: AttachmentHash,\n expiresAtUtc: string,\n meta?: { mimeType: string; fileName: string; sizeBytes: number },\n ) {\n super(\n `Attachment pending upload for hash: ${hash}, expires: ${expiresAtUtc}`,\n );\n this.name = \"AttachmentPending\";\n this.hash = hash;\n this.expiresAtUtc = expiresAtUtc;\n this.metadata = meta;\n }\n}\n","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 { InvalidAttachmentRef } from \"./errors.js\";\n\nconst REF_PATTERN = /^attachment:\\/\\/v(\\d+):(.+)$/;\nconst DEFAULT_VERSION = 1;\n\nexport type ParsedRef = {\n version: number;\n hash: AttachmentHash;\n};\n\nexport function parseRef(ref: AttachmentRef): ParsedRef {\n const match = REF_PATTERN.exec(ref);\n if (!match) {\n throw new InvalidAttachmentRef(ref);\n }\n return {\n version: Number(match[1]),\n hash: match[2],\n };\n}\n\nexport function createRef(\n hash: AttachmentHash,\n version: number = DEFAULT_VERSION,\n): AttachmentRef {\n return `attachment://v${version}:${hash}`;\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 if (\n options.sizeBytes === undefined ||\n !Number.isInteger(options.sizeBytes) ||\n options.sizeBytes <= 0 ||\n !Number.isSafeInteger(options.sizeBytes)\n ) {\n throw new Error(\n \"sizeBytes must be a positive 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","import type { JwtHandler } from \"@powerhousedao/reactor\";\n\nexport async function buildAuthHeaders(\n url: string,\n jwtHandler: JwtHandler | undefined,\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {};\n if (jwtHandler) {\n const token = await jwtHandler(url);\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n }\n return headers;\n}\n","import type { AttachmentHash } from \"@powerhousedao/reactor\";\nimport type { JwtHandler } from \"@powerhousedao/reactor\";\nimport type { IAttachmentTransport } from \"../interfaces.js\";\nimport type { AttachmentMetadata, TransportFetchResult } from \"../types.js\";\nimport { buildAuthHeaders } from \"./build-auth-headers.js\";\n\nexport type SwitchboardTransportConfig = {\n remoteUrl: string;\n jwtHandler?: JwtHandler;\n fetchFn?: typeof fetch;\n};\n\nexport class SwitchboardAttachmentTransport implements IAttachmentTransport {\n private readonly remoteUrl: string;\n private readonly jwtHandler?: JwtHandler;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: SwitchboardTransportConfig) {\n this.remoteUrl = config.remoteUrl;\n this.jwtHandler = config.jwtHandler;\n this.fetchFn = (config.fetchFn ?? globalThis.fetch).bind(globalThis);\n }\n\n async fetch(\n hash: AttachmentHash,\n documentId: string,\n signal?: AbortSignal,\n ): Promise<TransportFetchResult> {\n const url = `${this.remoteUrl}/attachments/${hash}?documentId=${encodeURIComponent(documentId)}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, { signal, headers });\n\n if (response.status === 202) {\n const expiresAtUtc = this.parsePendingExpiry(response);\n if (!expiresAtUtc) {\n throw new Error(\n \"Attachment fetch returned 202 with missing or malformed Attachment-Pending header\",\n );\n }\n const retryAfterMs = parseRetryAfterMs(response);\n return { kind: \"pending\", hash, expiresAtUtc, retryAfterMs };\n }\n\n if (response.status === 404) {\n return { kind: \"not-found\" };\n }\n\n if (!response.ok) {\n throw new Error(\n `Attachment fetch failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const metadata = this.parseMetadataHeaders(response);\n const body = response.body;\n if (!body) {\n throw new Error(\"Response body is null\");\n }\n\n return { kind: \"data\", response: { hash, metadata, body } };\n }\n\n async announce(_hash: AttachmentHash): Promise<void> {\n // No-op for switchboard -- data is already on the server after upload.\n }\n\n async push(\n hash: AttachmentHash,\n remote: string,\n data: ReadableStream<Uint8Array>,\n ): Promise<void> {\n const url = `${remote}/attachments/${hash}`;\n const headers = await buildAuthHeaders(url, this.jwtHandler);\n\n const response = await this.fetchFn(url, {\n method: \"PUT\",\n body: data,\n headers,\n // @ts-expect-error Node fetch requires duplex for streaming request bodies\n duplex: \"half\",\n });\n\n if (!response.ok) {\n throw new Error(\n `Attachment push failed: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n private parsePendingExpiry(response: Response): string | 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 return parsed.expiresAtUtc;\n } catch {\n return null;\n }\n }\n\n private parseMetadataHeaders(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 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}\n\nconst DEFAULT_RETRY_AFTER_MS = 5000;\n\nfunction parseRetryAfterMs(response: Response): number {\n const retryAfter = response.headers.get(\"Retry-After\");\n if (!retryAfter) return DEFAULT_RETRY_AFTER_MS;\n const seconds = Number(retryAfter);\n if (!Number.isFinite(seconds) || seconds < 0) return DEFAULT_RETRY_AFTER_MS;\n return Math.round(seconds * 1000);\n}\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 header (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","/**\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\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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>,\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 // Buffer the stream to a Blob. Streaming request bodies aren't universally\n // supported in browsers (Firefox stringifies the stream to \"[object\n // ReadableStream]\" even with duplex: \"half\"); buffering is the only\n // portable option for attachment uploads.\n const body = await new Response(data).blob();\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>,\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 // Buffer for the same browser-compatibility reasons as the proxy path.\n const body = await new Response(data).blob();\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":";;;;AAKA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,YAAoB;EAC9B,MAAM,yBAAyB,YAAY;EAC3C,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,YAAY,eAAuB;EACjC,MAAM,0BAA0B,eAAe;EAC/C,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,KAAa;EACvB,MAAM,2BAA2B,KAAK;EACtC,KAAK,OAAO;CACd;AACF;;;;;AAMA,IAAa,iBAAb,cAAoC,MAAM;CACxC;CACA,YAAY,UAAkB;EAC5B,MAAM,kCAAkC,SAAS,OAAO;EACxD,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;;;;;AAOA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CACA,YAAY,MAAsB,KAAoB;EACpD,MAAM,uCAAuC,MAAM;EACnD,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,MAAM;CACb;AACF;;;;;;AAOA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CACA,YAAY,SAAyB,QAAwB;EAC3D,MAAM,0BAA0B,QAAQ,gBAAgB,QAAQ;EAChE,KAAK,OAAO;EACZ,KAAK,UAAU;EACf,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;AAaA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CACA,YAAY,UAAkB,QAAgB;EAC5C,MAAM,2BAA2B,SAAS,sBAAsB,QAAQ;EACxE,KAAK,OAAO;EACZ,KAAK,WAAW;EAChB,KAAK,SAAS;CAChB;AACF;;;;;;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ACZ,MAAM,IAAI,MACR,4BAA4B,SAAS,OAAO,GAAG,SAAS,YAC1D;EAEF,IAAI,CAAC,SAAS,MACZ,MAAM,IAAI,MAAM,uBAAuB;EAIzC,OAAO;GAAE,QAAQ,YAAY,MADZ,cAAc,QACW,CAAC;GAAG,MAAM,SAAS;EAAK;CACpE;AACF;AAEA,SAAS,YACP,MACA,UACkB;CAClB,OAAO;EACL;EACA,UAAU,SAAS;EACnB,UAAU,SAAS;EACnB,WAAW,SAAS;EACpB,WAAW,SAAS;EACpB,QAAQ;EACR,QAAQ;EACR,cAAc,SAAS;EACvB,mBAAmB,SAAS,qBAAqB,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/reactor-attachments",
3
- "version": "6.2.3-dev.8",
3
+ "version": "6.2.3-staging.0",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "repository": {
@@ -31,8 +31,8 @@
31
31
  "@aws-sdk/client-s3": "3.1087.0",
32
32
  "@aws-sdk/s3-request-presigner": "3.1087.0",
33
33
  "@powerhousedao/document-engineering": "1.40.5",
34
- "@powerhousedao/reactor": "6.2.3-dev.8",
35
- "@powerhousedao/shared": "6.2.3-dev.8",
34
+ "@powerhousedao/reactor": "6.2.3-staging.0",
35
+ "@powerhousedao/shared": "6.2.3-staging.0",
36
36
  "change-case": "5.4.4",
37
37
  "graphql": "^16",
38
38
  "kysely": "0.28.16"
@@ -40,8 +40,8 @@
40
40
  "devDependencies": {
41
41
  "@electric-sql/pglite": "0.3.15",
42
42
  "kysely-pglite-dialect": "1.2.0",
43
- "tsdown": "0.21.1",
44
- "tsx": "4.21.0",
43
+ "tsdown": "0.23.0",
44
+ "tsx": "4.23.13",
45
45
  "vitest": "4.1.1"
46
46
  },
47
47
  "description": "Content-addressed attachment service for the Powerhouse reactor — decouples large binaries from the action pipeline using opaque refs.",
@@ -60,7 +60,7 @@
60
60
  "homepage": "https://academy.vetra.io/academy/Reference/Reactor/AttachmentService",
61
61
  "scripts": {
62
62
  "tsc": "tsc",
63
- "lint": "eslint",
63
+ "lint": "cd ../.. && oxlint packages/reactor-attachments",
64
64
  "build": "tsdown",
65
65
  "test": "vitest --run",
66
66
  "verify:s3-compatibility": "tsx scripts/verify-s3-compatibility.ts"
@@ -1 +0,0 @@
1
- {"version":3,"file":"null-attachment-transport-CMrO_ZKA.d.ts","names":[],"sources":["../src/errors.ts","../src/types.ts","../src/interfaces.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":";;;;;AAKA;cAAa,kBAAA,SAA2B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