blossom-client-sdk 4.1.0 → 5.0.0-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +246 -92
  2. package/lib/actions/delete.d.ts +3 -1
  3. package/lib/actions/delete.js +17 -8
  4. package/lib/actions/download.d.ts +3 -1
  5. package/lib/actions/download.js +17 -8
  6. package/lib/actions/has.d.ts +9 -0
  7. package/lib/actions/has.js +10 -0
  8. package/lib/actions/index.d.ts +3 -0
  9. package/lib/actions/index.js +3 -0
  10. package/lib/actions/list.d.ts +8 -2
  11. package/lib/actions/list.js +35 -9
  12. package/lib/actions/media.d.ts +1 -1
  13. package/lib/actions/media.js +18 -8
  14. package/lib/actions/mirror.d.ts +3 -1
  15. package/lib/actions/mirror.js +17 -8
  16. package/lib/actions/multi-server.d.ts +63 -43
  17. package/lib/actions/multi-server.js +205 -96
  18. package/lib/actions/report.d.ts +11 -0
  19. package/lib/actions/report.js +35 -0
  20. package/lib/actions/resolve.d.ts +27 -0
  21. package/lib/actions/resolve.js +129 -0
  22. package/lib/actions/upload.d.ts +3 -1
  23. package/lib/actions/upload.js +17 -8
  24. package/lib/auth.d.ts +20 -1
  25. package/lib/auth.js +80 -22
  26. package/lib/error.d.ts +5 -0
  27. package/lib/error.js +11 -0
  28. package/lib/helpers/blob.d.ts +1 -1
  29. package/lib/helpers/blossom-uri.d.ts +20 -0
  30. package/lib/helpers/blossom-uri.js +77 -0
  31. package/lib/helpers/cachu.d.ts +5 -0
  32. package/lib/helpers/cachu.js +14 -0
  33. package/lib/helpers/cashu.d.ts +4 -4
  34. package/lib/helpers/cashu.js +2 -2
  35. package/lib/helpers/index.d.ts +1 -0
  36. package/lib/helpers/index.js +1 -0
  37. package/lib/helpers/url.d.ts +2 -0
  38. package/lib/helpers/url.js +9 -3
  39. package/lib/helpers.d.ts +20 -0
  40. package/lib/helpers.js +73 -0
  41. package/lib/hls.d.ts +20 -0
  42. package/lib/hls.js +182 -0
  43. package/lib/index.d.ts +1 -2
  44. package/lib/index.js +1 -2
  45. package/lib/media.d.ts +37 -0
  46. package/lib/media.js +179 -0
  47. package/lib/types.d.ts +35 -3
  48. package/lib/upload.d.ts +13 -0
  49. package/lib/upload.js +37 -0
  50. package/package.json +21 -8
  51. package/src/actions/delete.ts +19 -7
  52. package/src/actions/download.ts +19 -7
  53. package/src/actions/has.ts +19 -0
  54. package/src/actions/index.ts +3 -0
  55. package/src/actions/list.ts +43 -8
  56. package/src/actions/media.ts +19 -7
  57. package/src/actions/mirror.ts +19 -7
  58. package/src/actions/multi-server.ts +264 -118
  59. package/src/actions/report.ts +54 -0
  60. package/src/actions/resolve.ts +159 -0
  61. package/src/actions/upload.ts +19 -7
  62. package/src/auth.ts +99 -21
  63. package/src/error.ts +15 -0
  64. package/src/helpers/blob.ts +1 -1
  65. package/src/helpers/blossom-uri.ts +99 -0
  66. package/src/helpers/cashu.ts +10 -7
  67. package/src/helpers/index.ts +1 -0
  68. package/src/helpers/url.ts +10 -3
  69. package/src/hls.ts +255 -0
  70. package/src/index.ts +1 -2
  71. package/src/media.ts +200 -0
  72. package/src/types.ts +42 -4
  73. package/lib/client.d.ts +0 -61
  74. package/lib/client.js +0 -160
  75. package/lib/image.d.ts +0 -17
  76. package/lib/image.js +0 -107
  77. package/src/client.ts +0 -221
  78. package/src/image.ts +0 -122
@@ -1,12 +1,16 @@
1
- import { ServerType } from "../client.js";
1
+ import { ServerType } from "../types.js";
2
2
  import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
3
3
  export type ListOptions<S extends ServerType> = {
4
4
  /** AbortSignal to cancel the action */
5
5
  signal?: AbortSignal;
6
6
  /** Override authorization event, or true to always use authorization, false to disable authorization */
7
7
  auth?: SignedEvent | boolean;
8
+ /** Shared auth event store used to reuse non-expired auth events between requests */
9
+ authEvents?: Set<SignedEvent>;
8
10
  /** Request timeout */
9
11
  timeout?: number;
12
+ cursor?: string;
13
+ limit?: number;
10
14
  since?: number;
11
15
  until?: number;
12
16
  /**
@@ -21,5 +25,7 @@ export type ListOptions<S extends ServerType> = {
21
25
  */
22
26
  onAuth?: (server: S) => Promise<SignedEvent>;
23
27
  };
24
- /** Mirrors a blob to a server */
28
+ /** Lists a page of blobs from a server */
25
29
  export declare function listBlobs<S extends ServerType>(server: S, pubkey: string, opts?: ListOptions<S>): Promise<BlobDescriptor[]>;
30
+ /** Iterates through blob pages using cursor-based pagination */
31
+ export declare function iterateBlobs<S extends ServerType>(server: S, pubkey: string, opts?: ListOptions<S>): AsyncGenerator<BlobDescriptor[], void, void>;
@@ -1,21 +1,34 @@
1
1
  import HTTPError from "../error.js";
2
- import { encodeAuthorizationHeader } from "../auth.js";
2
+ import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
- /** Mirrors a blob to a server */
4
+ /** Lists a page of blobs from a server */
5
5
  export async function listBlobs(server, pubkey, opts) {
6
6
  const url = new URL(`/list/` + pubkey, server);
7
+ if (opts?.cursor)
8
+ url.searchParams.append("cursor", opts.cursor);
9
+ if (opts?.limit)
10
+ url.searchParams.append("limit", String(opts.limit));
7
11
  if (opts?.since)
8
12
  url.searchParams.append("since", String(opts.since));
9
13
  if (opts?.until)
10
14
  url.searchParams.append("until", String(opts.until));
15
+ const resolveAuth = async (preset = false) => {
16
+ const reused = opts?.authEvents ? await getReusableAuthEvent(opts.authEvents, { server, type: "list" }) : undefined;
17
+ if (reused)
18
+ return reused;
19
+ const auth = await opts?.onAuth?.(server);
20
+ if (!auth)
21
+ throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
22
+ if (opts?.authEvents)
23
+ storeAuthEvent(opts.authEvents, auth);
24
+ return auth;
25
+ };
11
26
  // attach the auth if its already set
12
27
  const headers = {};
13
28
  // attach the authorization if its already set
14
29
  if (opts?.auth) {
15
30
  if (typeof opts.auth === "boolean") {
16
- if (!opts.onAuth)
17
- throw new Error("Missing onAuth handler");
18
- headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server));
31
+ headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
19
32
  }
20
33
  else {
21
34
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
@@ -28,9 +41,7 @@ export async function listBlobs(server, pubkey, opts) {
28
41
  // throw an error if auth is requested and disabled
29
42
  if (opts?.auth === false)
30
43
  throw new Error("Authorization disabled");
31
- const auth = await opts?.onAuth?.(server);
32
- if (!auth)
33
- throw new Error("Missing auth handler");
44
+ const auth = await resolveAuth();
34
45
  // Try list with auth
35
46
  list = await fetchWithTimeout(url, {
36
47
  headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
@@ -44,7 +55,7 @@ export async function listBlobs(server, pubkey, opts) {
44
55
  throw new Error("Missing payment handler");
45
56
  const { getEncodedToken } = await import("@cashu/cashu-ts");
46
57
  const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
47
- const request = getPaymentRequestFromHeaders(list.headers);
58
+ const request = await getPaymentRequestFromHeaders(list.headers);
48
59
  const token = await opts.onPayment(server, request);
49
60
  const payment = getEncodedToken(token);
50
61
  // Try list with payment
@@ -61,3 +72,18 @@ export async function listBlobs(server, pubkey, opts) {
61
72
  // return blob descriptor
62
73
  return list.json();
63
74
  }
75
+ /** Iterates through blob pages using cursor-based pagination */
76
+ export async function* iterateBlobs(server, pubkey, opts) {
77
+ let cursor = opts?.cursor;
78
+ while (true) {
79
+ const page = await listBlobs(server, pubkey, { ...opts, cursor });
80
+ if (page.length === 0)
81
+ return;
82
+ yield page;
83
+ if (opts?.limit && page.length < opts.limit)
84
+ return;
85
+ cursor = page[page.length - 1]?.sha256;
86
+ if (!cursor)
87
+ return;
88
+ }
89
+ }
@@ -1,4 +1,4 @@
1
- import { ServerType, UploadType } from "../client.js";
1
+ import { ServerType, UploadType } from "../types.js";
2
2
  import { BlobDescriptor } from "../types.js";
3
3
  import { UploadOptions } from "./upload.js";
4
4
  /** Error thrown when /media endpoint is not present on a server */
@@ -1,6 +1,6 @@
1
1
  import { getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
2
2
  import HTTPError from "../error.js";
3
- import { encodeAuthorizationHeader } from "../auth.js";
3
+ import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
4
4
  /** Error thrown when /media endpoint is not present on a server */
5
5
  export class MediaEndpointMissingError extends Error {
6
6
  }
@@ -8,15 +8,27 @@ export class MediaEndpointMissingError extends Error {
8
8
  export async function uploadMedia(server, blob, opts) {
9
9
  const url = new URL("/media", server);
10
10
  const sha256 = await getBlobSha256(blob);
11
+ const authEvents = opts?.authEvents;
12
+ const resolveAuth = async (preset = false) => {
13
+ const reused = authEvents
14
+ ? await getReusableAuthEvent(authEvents, { server, type: "media", blob: sha256 })
15
+ : undefined;
16
+ if (reused)
17
+ return reused;
18
+ const auth = await opts?.onAuth?.(server, sha256, "media", blob);
19
+ if (!auth)
20
+ throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
21
+ if (authEvents)
22
+ storeAuthEvent(authEvents, auth);
23
+ return auth;
24
+ };
11
25
  const headers = {
12
26
  "X-SHA-256": sha256,
13
27
  };
14
28
  // attach the authorization if its already set
15
29
  if (opts?.auth) {
16
30
  if (typeof opts.auth === "boolean") {
17
- if (!opts.onAuth)
18
- throw new Error("Missing onAuth handler");
19
- headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, sha256, "media", blob));
31
+ headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
20
32
  }
21
33
  else {
22
34
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
@@ -48,9 +60,7 @@ export async function uploadMedia(server, blob, opts) {
48
60
  if (opts?.auth === false)
49
61
  throw new Error("Authorization disabled");
50
62
  // Request authorization event for this upload
51
- const auth = await opts?.onAuth?.(server, sha256, "media", blob);
52
- if (!auth)
53
- throw new Error("Missing auth handler");
63
+ const auth = await resolveAuth();
54
64
  // Try upload with auth
55
65
  upload = await fetch(url, {
56
66
  signal: opts?.signal,
@@ -65,7 +75,7 @@ export async function uploadMedia(server, blob, opts) {
65
75
  throw new Error("Missing payment handler");
66
76
  const { getEncodedToken } = await import("@cashu/cashu-ts");
67
77
  const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
68
- const request = getPaymentRequestFromHeaders(firstTry.headers);
78
+ const request = await getPaymentRequestFromHeaders(firstTry.headers);
69
79
  const token = await opts.onPayment(server, sha256, blob, request);
70
80
  const payment = getEncodedToken(token);
71
81
  // Try upload with payment
@@ -1,10 +1,12 @@
1
- import { ServerType } from "../client.js";
1
+ import { ServerType } from "../types.js";
2
2
  import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
3
3
  export type MirrorOptions<S extends ServerType> = {
4
4
  /** AbortSignal to cancel the action */
5
5
  signal?: AbortSignal;
6
6
  /** Override authorization event, or true to always use authorization, false to disable authorization */
7
7
  auth?: SignedEvent | boolean;
8
+ /** Shared auth event store used to reuse non-expired auth events between requests */
9
+ authEvents?: Set<SignedEvent>;
8
10
  /** Request timeout */
9
11
  timeout?: number;
10
12
  /**
@@ -1,9 +1,22 @@
1
- import { encodeAuthorizationHeader } from "../auth.js";
1
+ import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
2
  import HTTPError from "../error.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
4
  /** Mirrors a blob to a server */
5
5
  export async function mirrorBlob(server, blob, opts) {
6
6
  const url = new URL("/mirror", server);
7
+ const resolveAuth = async (preset = false) => {
8
+ const reused = opts?.authEvents
9
+ ? await getReusableAuthEvent(opts.authEvents, { server, type: "upload", blob: blob.sha256 })
10
+ : undefined;
11
+ if (reused)
12
+ return reused;
13
+ const auth = await opts?.onAuth?.(server, blob.sha256, blob);
14
+ if (!auth)
15
+ throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
16
+ if (opts?.authEvents)
17
+ storeAuthEvent(opts.authEvents, auth);
18
+ return auth;
19
+ };
7
20
  const headers = {
8
21
  "X-SHA-256": blob.sha256,
9
22
  "X-Content-Length": String(blob.size),
@@ -14,9 +27,7 @@ export async function mirrorBlob(server, blob, opts) {
14
27
  // attach the authorization if its already set
15
28
  if (opts?.auth) {
16
29
  if (typeof opts.auth === "boolean") {
17
- if (!opts.onAuth)
18
- throw new Error("Missing onAuth handler");
19
- headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, blob.sha256, blob));
30
+ headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
20
31
  }
21
32
  else {
22
33
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
@@ -36,9 +47,7 @@ export async function mirrorBlob(server, blob, opts) {
36
47
  if (opts?.auth === false)
37
48
  throw new Error("Authorization disabled");
38
49
  // Request authorization event for this mirror
39
- const auth = await opts?.onAuth?.(server, blob.sha256, blob);
40
- if (!auth)
41
- throw new Error("Missing auth handler");
50
+ const auth = await resolveAuth();
42
51
  // Try mirror with auth
43
52
  mirror = await fetchWithTimeout(url, {
44
53
  signal: opts?.signal,
@@ -54,7 +63,7 @@ export async function mirrorBlob(server, blob, opts) {
54
63
  throw new Error("Missing payment handler");
55
64
  const { getEncodedToken } = await import("@cashu/cashu-ts");
56
65
  const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
57
- const request = getPaymentRequestFromHeaders(mirror.headers);
66
+ const request = await getPaymentRequestFromHeaders(mirror.headers);
58
67
  const token = await opts.onPayment(server, blob.sha256, blob, request);
59
68
  const payment = getEncodedToken(token);
60
69
  // Try mirror with payment
@@ -1,66 +1,86 @@
1
- import { ServerType, UploadType } from "../client.js";
2
- import { BlobDescriptor } from "../types.js";
1
+ import { ServerType, UploadType } from "../types.js";
2
+ import { BlobDescriptor, RejectionAction } from "../types.js";
3
+ import HTTPError from "../error.js";
3
4
  import { UploadOptions } from "./upload.js";
4
- export type MultiServerUploadOptions<S extends ServerType, B extends UploadType> = UploadOptions<S, B> & {
5
- /**
6
- * Signals this blob should be treated as a media file and should attempt to use BUD-05 /media endpoint for upload on first server
7
- * @default false
8
- */
9
- isMedia?: boolean;
10
- /**
11
- * If isMedia is enabled, this determines how /media endpoints should be prioritized
12
- * - "first" Only use the first server in the list to optimize the media
13
- * - "any" Use any server in the list to optimize the media
14
- * @default "first"
15
- */
16
- mediaUploadBehavior?: "first" | "any";
17
- /**
18
- * If isMedia is enabled, should the raw blob be uploaded if no /media endpoint can be found
19
- * @default false
20
- */
21
- mediaUploadFallback?: boolean;
5
+ export type MultiServerUploadOptions<TServer extends ServerType, TUpload extends UploadType> = UploadOptions<TServer, TUpload> & {
22
6
  /**
23
7
  * Timeout for mirror requests
24
8
  * @default 5000
25
9
  */
26
10
  mirrorTimeout?: number;
11
+ /**
12
+ * Run parallel HEAD /<sha256> checks on all servers before starting uploads.
13
+ * Servers that already have the blob will use /mirror to register ownership instead of /upload.
14
+ * @default true
15
+ */
16
+ preflight?: boolean;
27
17
  /**
28
18
  * called on blob when uploaded to started to a server
29
19
  * @param server
30
20
  * @param sha256 the hash of the blob being uploaded or mirrored
31
21
  * @param blob the original blob
32
22
  */
33
- onStart?: (server: S, sha256: string, blob: B) => void;
23
+ onStart?: (server: TServer, sha256: string, blob: TUpload) => void;
34
24
  /** called when upload to a server is complete */
35
- onUpload?: (server: S, sha256: string, blob: B) => void;
25
+ onUpload?: (server: TServer, sha256: string, blob: TUpload) => void;
36
26
  /** called when upload to a server fails */
37
- onError?: (server: S, sha256: string, blob: B, error: Error) => void;
27
+ onError?: (server: TServer, sha256: string, blob: TUpload, error: Error) => void;
28
+ /**
29
+ * Called when a server rejects the upload with a known BUD-02 status (409, 413, 415, 422).
30
+ * Return "skip" to skip this server and continue, or "cancel" to abort the entire upload.
31
+ * If not provided, rejections are reported via onError.
32
+ */
33
+ onRejection?: (server: TServer, sha256: string, blob: TUpload, error: HTTPError) => RejectionAction | Promise<RejectionAction>;
34
+ };
35
+ export type MultiServerMediaUploadOptions<TServer extends ServerType, TUpload extends UploadType> = MultiServerUploadOptions<TServer, TUpload> & {
36
+ /**
37
+ * Determines how /media endpoints should be prioritized
38
+ * - "first" Only use the first server in the list to optimize the media
39
+ * - "any" Use any server in the list to optimize the media
40
+ * @default "first"
41
+ */
42
+ mediaUploadBehavior?: "first" | "any";
43
+ /**
44
+ * Should the raw blob be uploaded if no /media endpoint can be found
45
+ * @default false
46
+ */
47
+ mediaUploadFallback?: boolean;
38
48
  };
39
49
  /**
40
- * Creates an AsyncGenerator that can be used to upload a blob to multiple servers
41
- * @param servers A Set or Array of servers to upload to
42
- * @param blob The blob to be uploaded
43
- * @param signer An async function used for signing nostr events
44
- * @returns The BlobDescriptor if successful
50
+ * Upload a blob to multiple servers
51
+ *
52
+ * Uploads the blob to the first server, then mirrors to the remaining servers.
53
+ * Uses parallel preflight checks (HEAD /<sha256>) to detect which servers already have the blob.
45
54
  *
46
55
  * ```mermaid
47
56
  * flowchart LR
48
- * isMedia{"isMedia"} -- yes --> media["/media"]
49
- * isMedia -- no --> upload["/upload"]
50
- * media --> ifmedia{"Successful"}
51
- * ifmedia -- yes --> next["Next server"]
52
- * ifmedia -- no --> iffallback{"fallback"}
53
- * iffallback -- yes --> upload
54
- * iffallback -- no --> abort
55
- * upload -- complete --> next
56
- * next --> uploaded{"Uploaded"}
57
- * uploaded -- yes --> mirror["/mirror"]
58
- * uploaded -- no --> upload
59
- * mirror --> isMirror{"Successful"}
57
+ * preflight["HEAD /<sha256>"] --> hasBlob{"Has blob?"}
58
+ * hasBlob -- yes --> mirror["/mirror"]
59
+ * hasBlob -- no --> upload["/upload"]
60
+ * upload -- complete --> next["Next server"]
61
+ * next --> hasBlob
62
+ * mirror --> isMirror{"Successful?"}
60
63
  * isMirror -- yes --> next
61
- * isMirror -- no --> ifMediaAbort{"isMedia"}
62
- * ifMediaAbort -- no --> upload
63
- * ifMediaAbort -- yes --> next
64
+ * isMirror -- no --> upload
64
65
  * ```
65
66
  */
66
67
  export declare function multiServerUpload<S extends ServerType, B extends UploadType>(servers: Iterable<S>, blob: B, opts?: MultiServerUploadOptions<S, B>): Promise<Map<S, BlobDescriptor>>;
68
+ /**
69
+ * Upload media to multiple servers using BUD-05 optimization
70
+ *
71
+ * Uploads the blob to a /media endpoint on one server for optimization,
72
+ * then mirrors the optimized result to the remaining servers.
73
+ * The blob is never re-uploaded to other servers since the /media endpoint may transform it.
74
+ *
75
+ * ```mermaid
76
+ * flowchart LR
77
+ * media["/media"] --> ifmedia{"Successful?"}
78
+ * ifmedia -- yes --> preflight["HEAD /<sha256>"]
79
+ * ifmedia -- no --> iffallback{"fallback?"}
80
+ * iffallback -- yes --> upload["multiServerUpload"]
81
+ * iffallback -- no --> abort
82
+ * preflight --> mirror["/mirror"]
83
+ * mirror --> next["Next server"]
84
+ * ```
85
+ */
86
+ export declare function multiServerMediaUpload<S extends ServerType, B extends UploadType>(servers: Iterable<S>, blob: B, opts?: MultiServerMediaUploadOptions<S, B>): Promise<Map<S, BlobDescriptor>>;