blossom-client-sdk 4.0.0 → 5.0.0-0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +246 -92
- package/lib/actions/delete.d.ts +5 -3
- package/lib/actions/delete.js +28 -7
- package/lib/actions/download.d.ts +5 -3
- package/lib/actions/download.js +28 -7
- package/lib/actions/has.d.ts +9 -0
- package/lib/actions/has.js +10 -0
- package/lib/actions/index.d.ts +3 -0
- package/lib/actions/index.js +3 -0
- package/lib/actions/list.d.ts +10 -4
- package/lib/actions/list.js +45 -7
- package/lib/actions/media.d.ts +1 -1
- package/lib/actions/media.js +29 -7
- package/lib/actions/mirror.d.ts +5 -3
- package/lib/actions/mirror.js +28 -7
- package/lib/actions/multi-server.d.ts +63 -43
- package/lib/actions/multi-server.js +208 -88
- package/lib/actions/report.d.ts +11 -0
- package/lib/actions/report.js +35 -0
- package/lib/actions/resolve.d.ts +27 -0
- package/lib/actions/resolve.js +129 -0
- package/lib/actions/upload.d.ts +5 -3
- package/lib/actions/upload.js +28 -7
- package/lib/auth.d.ts +23 -2
- package/lib/auth.js +82 -22
- package/lib/error.d.ts +5 -0
- package/lib/error.js +11 -0
- package/lib/helpers/blob.d.ts +1 -1
- package/lib/helpers/blossom-uri.d.ts +20 -0
- package/lib/helpers/blossom-uri.js +77 -0
- package/lib/helpers/cachu.d.ts +5 -0
- package/lib/helpers/cachu.js +14 -0
- package/lib/helpers/index.d.ts +1 -0
- package/lib/helpers/index.js +1 -0
- package/lib/helpers/url.d.ts +2 -0
- package/lib/helpers/url.js +9 -3
- package/lib/helpers.d.ts +20 -0
- package/lib/helpers.js +73 -0
- package/lib/hls.d.ts +20 -0
- package/lib/hls.js +182 -0
- package/lib/index.d.ts +1 -2
- package/lib/index.js +1 -2
- package/lib/media.d.ts +37 -0
- package/lib/media.js +179 -0
- package/lib/types.d.ts +3 -1
- package/lib/upload.d.ts +13 -0
- package/lib/upload.js +37 -0
- package/package.json +16 -7
- package/src/actions/delete.ts +31 -8
- package/src/actions/download.ts +31 -8
- package/src/actions/has.ts +19 -0
- package/src/actions/index.ts +3 -0
- package/src/actions/list.ts +55 -8
- package/src/actions/media.ts +29 -6
- package/src/actions/mirror.ts +31 -8
- package/src/actions/multi-server.ts +268 -111
- package/src/actions/report.ts +54 -0
- package/src/actions/resolve.ts +159 -0
- package/src/actions/upload.ts +31 -8
- package/src/auth.ts +105 -19
- package/src/error.ts +15 -0
- package/src/helpers/blob.ts +1 -1
- package/src/helpers/blossom-uri.ts +99 -0
- package/src/helpers/index.ts +1 -0
- package/src/helpers/url.ts +10 -3
- package/src/hls.ts +255 -0
- package/src/index.ts +1 -2
- package/src/media.ts +200 -0
- package/src/types.ts +4 -1
- package/lib/client.d.ts +0 -61
- package/lib/client.js +0 -160
- package/lib/image.d.ts +0 -17
- package/lib/image.js +0 -107
- package/src/client.ts +0 -221
- package/src/image.ts +0 -122
package/README.md
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
# 🌸 blossom-client-sdk
|
|
2
2
|
|
|
3
|
-
A client for
|
|
3
|
+
A client for managing blobs on blossom servers
|
|
4
4
|
|
|
5
|
-
[Documentation](https://hzrd149.github.io/blossom-client-sdk/
|
|
5
|
+
[Documentation](https://hzrd149.github.io/blossom-client-sdk/)
|
|
6
6
|
|
|
7
|
-
##
|
|
8
|
-
|
|
9
|
-
### Using the static methods
|
|
7
|
+
## Basic Usage
|
|
10
8
|
|
|
11
9
|
```js
|
|
12
|
-
import {
|
|
10
|
+
import { uploadBlob, createUploadAuth, encodeAuthorizationHeader } from "blossom-client-sdk";
|
|
13
11
|
|
|
14
12
|
async function signer(event) {
|
|
15
13
|
return await window.nostr.signEvent(event);
|
|
16
14
|
}
|
|
17
15
|
|
|
16
|
+
const server = "https://cdn.example.com";
|
|
17
|
+
|
|
18
18
|
// create an upload auth event
|
|
19
|
-
const uploadAuth = await
|
|
19
|
+
const uploadAuth = await createUploadAuth(signer, file);
|
|
20
20
|
|
|
21
21
|
// encode it using base64
|
|
22
|
-
const encodedAuthHeader =
|
|
22
|
+
const encodedAuthHeader = encodeAuthorizationHeader(uploadAuth);
|
|
23
23
|
|
|
24
24
|
// manually make the request
|
|
25
25
|
const res = await fetch(new URL("/upload", server), {
|
|
@@ -28,36 +28,15 @@ const res = await fetch(new URL("/upload", server), {
|
|
|
28
28
|
headers: { authorization: encodedAuthHeader },
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
-
// or use the
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if (res.ok) {
|
|
36
|
-
console.log("Blob uploaded!");
|
|
37
|
-
}
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
### Using the class
|
|
41
|
-
|
|
42
|
-
The `BlossomClient` class can be used to talk to a single server
|
|
43
|
-
|
|
44
|
-
```js
|
|
45
|
-
import { BlossomClient } from "blossom-client-sdk";
|
|
46
|
-
|
|
47
|
-
async function signer(event) {
|
|
48
|
-
return await window.nostr.signEvent(event);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const client = new BlossomClient("https://cdn.example.com", signer);
|
|
52
|
-
|
|
53
|
-
const pubkey = "266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5";
|
|
54
|
-
const blobs = await client.listBlobs(pubkey, undefined, true);
|
|
55
|
-
// passing true as the last argument will make it send an auth event with the list request
|
|
31
|
+
// or use the action function
|
|
32
|
+
const blob = await uploadBlob(server, file, {
|
|
33
|
+
onAuth: async (server, sha256, type) => createUploadAuth(signer, sha256, { type }),
|
|
34
|
+
});
|
|
56
35
|
```
|
|
57
36
|
|
|
58
37
|
### Using with NDK
|
|
59
38
|
|
|
60
|
-
The
|
|
39
|
+
The auth and action functions optionally take a `signer` method that is used to sign the auth events
|
|
61
40
|
|
|
62
41
|
If your using NDK in your app you can use this method
|
|
63
42
|
|
|
@@ -101,45 +80,155 @@ console.log(getHashFromURL("https://example.com/index.html"));
|
|
|
101
80
|
// -> null
|
|
102
81
|
```
|
|
103
82
|
|
|
104
|
-
###
|
|
83
|
+
### Media fallbacks
|
|
105
84
|
|
|
106
|
-
|
|
85
|
+
The SDK provides several methods for handling broken media elements (`<img>`, `<video>`, `<audio>`) by automatically trying alternative blossom servers. Both regular HTTP blob URLs and `blossom:` URIs are supported.
|
|
107
86
|
|
|
108
|
-
|
|
87
|
+
All the media fallback methods require a `getServers` callback to resolve pubkeys to server lists:
|
|
109
88
|
|
|
110
89
|
```js
|
|
111
|
-
import {
|
|
90
|
+
import { USER_BLOSSOM_SERVER_LIST_KIND, getServersFromServerListEvent } from "blossom-client-sdk";
|
|
112
91
|
|
|
113
|
-
const image = new Image();
|
|
114
|
-
image.src = "https://cdn.censorship.com/72cb99b689b4cfe1a9fb6937f779f3f9c65094bf0e6ac72a8f8261efa96653f5.png";
|
|
115
|
-
|
|
116
|
-
// set the pubkey from the kind 1 event this image was found it
|
|
117
|
-
image.dataset.pubkey = event.pubkey;
|
|
118
|
-
|
|
119
|
-
// this is called when
|
|
120
92
|
async function getServers(pubkey) {
|
|
121
93
|
if (pubkey) {
|
|
122
|
-
// use NDK to find the users blossom server list event (k:10063)
|
|
123
94
|
const event = await ndk.fetchEvent({ kinds: [USER_BLOSSOM_SERVER_LIST_KIND], authors: [pubkey] });
|
|
124
|
-
|
|
125
|
-
// if its found return a list of blossom servers
|
|
126
95
|
if (event) return getServersFromServerListEvent(event);
|
|
127
96
|
}
|
|
128
97
|
return undefined;
|
|
129
98
|
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
#### Automatic fallbacks for a DOM tree
|
|
102
|
+
|
|
103
|
+
`handleBrokenMedia` watches a DOM tree for any `<img>`, `<video>`, or `<audio>` elements and automatically handles server fallbacks. It uses a `MutationObserver` to handle dynamically added elements. Returns a cleanup function to remove all listeners and stop observing.
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
import { handleBrokenMedia } from "blossom-client-sdk";
|
|
107
|
+
|
|
108
|
+
// start watching for broken media in the document
|
|
109
|
+
const cleanup = handleBrokenMedia(document.body, getServers);
|
|
110
|
+
|
|
111
|
+
// later, to remove all listeners and stop watching
|
|
112
|
+
cleanup();
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### Blossom URIs in media elements
|
|
116
|
+
|
|
117
|
+
Media elements can use `blossom:` URIs directly in the `src` attribute. The fallback handler will automatically resolve the URI to HTTP URLs using the server hints:
|
|
118
|
+
|
|
119
|
+
```html
|
|
120
|
+
<img src="blossom:b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.png?xs=https://cdn1.com&xs=https://cdn2.com" />
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
When the browser can't load the `blossom:` protocol, the error handler parses the URI, resolves server URLs from `xs` and `as` hints, and sets the first working URL.
|
|
124
|
+
|
|
125
|
+
#### Single element fallbacks
|
|
126
|
+
|
|
127
|
+
`handleMediaFallbacks` attaches an error listener to a single element. For regular HTTP URLs, it extracts the blob hash and looks up alternative servers using a `data-pubkey` attribute on the element or its parents:
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
import { handleMediaFallbacks } from "blossom-client-sdk";
|
|
131
|
+
|
|
132
|
+
const video = document.createElement("video");
|
|
133
|
+
video.src = "https://cdn.example.com/b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.mp4";
|
|
134
|
+
video.dataset.pubkey = event.pubkey;
|
|
135
|
+
|
|
136
|
+
const removeListener = handleMediaFallbacks(video, getServers);
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
#### Get blob URLs without fetching
|
|
140
|
+
|
|
141
|
+
`getBlobUrls` returns an ordered list of URLs for a blob from a blossom URI without fetching anything. Useful for building custom UI or populating `<source>` elements:
|
|
142
|
+
|
|
143
|
+
```js
|
|
144
|
+
import { Actions } from "blossom-client-sdk";
|
|
145
|
+
|
|
146
|
+
const urls = await Actions.getBlobUrls("blossom:b167...4f553.mp4?xs=https://cdn1.com&xs=https://cdn2.com", {
|
|
147
|
+
getServers,
|
|
148
|
+
fallbackServers: ["https://fallback.cdn.com"],
|
|
149
|
+
});
|
|
150
|
+
// -> ["https://cdn1.com/b167...4f553.mp4", "https://cdn2.com/b167...4f553.mp4", "https://fallback.cdn.com/b167...4f553.mp4"]
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### Create `<source>` elements for video/audio
|
|
154
|
+
|
|
155
|
+
`createSourceElements` generates `<source>` elements from a URL list, giving the browser native fallback for `<video>` and `<audio>`:
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
import { Actions, createSourceElements } from "blossom-client-sdk";
|
|
159
|
+
|
|
160
|
+
const urls = await Actions.getBlobUrls("blossom:b167...4f553.mp4?xs=https://cdn1.com&xs=https://cdn2.com");
|
|
161
|
+
const sources = createSourceElements(urls, "video/mp4");
|
|
162
|
+
|
|
163
|
+
const video = document.createElement("video");
|
|
164
|
+
video.append(...sources);
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
#### Resolve to an object URL
|
|
168
|
+
|
|
169
|
+
`resolveToObjectURL` fetches a blob with server fallback and returns a `blob:` object URL that works anywhere:
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
import { Actions } from "blossom-client-sdk";
|
|
173
|
+
|
|
174
|
+
const objectUrl = await Actions.resolveToObjectURL("blossom:b167...4f553.png?xs=https://cdn1.com", { getServers });
|
|
175
|
+
image.src = objectUrl;
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### HLS Video Streaming with Multi-Server Fallback
|
|
130
179
|
|
|
131
|
-
|
|
132
|
-
|
|
180
|
+
The SDK provides a loader factory for `hls.js` that automatically retries failed playlist and fragment requests across multiple Blossom servers. This enables resilient HLS playback even when some servers have missing or unavailable segments.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import Hls from "hls.js";
|
|
184
|
+
import { createBlossomHlsLoaders } from "blossom-client-sdk/hls";
|
|
185
|
+
|
|
186
|
+
// Create fallback loaders for hls.js
|
|
187
|
+
const { pLoader, fLoader } = createBlossomHlsLoaders({
|
|
188
|
+
// Servers to try when the primary fails
|
|
189
|
+
fallbackServers: ["https://cdn-backup1.example", "https://cdn-backup2.example"],
|
|
190
|
+
// Penalize failed origins briefly to prefer healthy ones (default: false)
|
|
191
|
+
stickyFailover: true,
|
|
192
|
+
// How long to penalize failed servers in ms (default: 30000)
|
|
193
|
+
penalizeMs: 30000,
|
|
194
|
+
// HTTP status codes to retry (default: [404])
|
|
195
|
+
retryStatuses: [404, 502, 503],
|
|
196
|
+
// Callback when a fallback occurs
|
|
197
|
+
onFallback: (info) => {
|
|
198
|
+
console.log(`Falling back from ${info.from} to ${info.to} for ${info.kind}`);
|
|
199
|
+
console.log(`Attempt ${info.attempt} for ${info.url}`);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
133
202
|
|
|
134
|
-
|
|
203
|
+
// Initialize hls.js with the fallback loaders
|
|
204
|
+
const hls = new Hls({
|
|
205
|
+
pLoader,
|
|
206
|
+
fLoader,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Load a master playlist from any Blossom server
|
|
210
|
+
hls.loadSource("https://cdn.example.com/abc123def456.m3u8");
|
|
211
|
+
hls.attachMedia(videoElement);
|
|
135
212
|
```
|
|
136
213
|
|
|
214
|
+
**How it works:**
|
|
215
|
+
|
|
216
|
+
- The loaders keep the original playlist/fragment path and query string but swap the origin
|
|
217
|
+
- If the primary server returns a retryable error (404, 5xx, timeout), it automatically tries the next server
|
|
218
|
+
- With `stickyFailover` enabled, failed servers are briefly penalized so subsequent requests prefer healthy ones
|
|
219
|
+
- The loader preserves HTTP headers, byte-range requests, and response type
|
|
220
|
+
|
|
221
|
+
**Requirements:**
|
|
222
|
+
|
|
223
|
+
- `hls.js` must be installed as a peer dependency
|
|
224
|
+
- Blossom HLS playlists should use relative paths with SHA256 hashes as documented in the HLS formatting guide
|
|
225
|
+
|
|
137
226
|
## Other Examples
|
|
138
227
|
|
|
139
|
-
### List
|
|
228
|
+
### List a page of blobs on a server
|
|
140
229
|
|
|
141
230
|
```js
|
|
142
|
-
import {
|
|
231
|
+
import { listBlobs, createListAuth } from "blossom-client-sdk";
|
|
143
232
|
|
|
144
233
|
async function signer(event) {
|
|
145
234
|
return await window.nostr.signEvent(event);
|
|
@@ -148,38 +237,51 @@ async function signer(event) {
|
|
|
148
237
|
const pubkey = "266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5";
|
|
149
238
|
const server = "https://cdn.example.com";
|
|
150
239
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
240
|
+
const blobs = await listBlobs(server, pubkey, {
|
|
241
|
+
onAuth: async () => createListAuth(signer),
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Iterate blob pages on a server
|
|
246
|
+
|
|
247
|
+
```js
|
|
248
|
+
import { iterateBlobs, createListAuth } from "blossom-client-sdk/actions";
|
|
249
|
+
|
|
250
|
+
async function signer(event) {
|
|
251
|
+
return await window.nostr.signEvent(event);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const pubkey = "266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5";
|
|
255
|
+
const server = "https://cdn.example.com";
|
|
256
|
+
|
|
257
|
+
for await (const page of iterateBlobs(server, pubkey, {
|
|
258
|
+
limit: 100,
|
|
259
|
+
onAuth: async () => createListAuth(signer),
|
|
260
|
+
})) {
|
|
261
|
+
console.log(page);
|
|
160
262
|
}
|
|
161
263
|
```
|
|
162
264
|
|
|
163
265
|
### Upload a single blob
|
|
164
266
|
|
|
165
267
|
```js
|
|
166
|
-
import {
|
|
268
|
+
import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
|
|
167
269
|
|
|
168
270
|
async function signer(event) {
|
|
169
271
|
return await window.nostr.signEvent(event);
|
|
170
272
|
}
|
|
171
273
|
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
const blobs = await client.listBlobs();
|
|
274
|
+
const server = "https://cdn.example.com";
|
|
175
275
|
|
|
176
|
-
await
|
|
276
|
+
const blob = await uploadBlob(server, new File(["testing"], "test.txt"), {
|
|
277
|
+
onAuth: async (server, sha256, type) => createUploadAuth(signer, sha256, { type }),
|
|
278
|
+
});
|
|
177
279
|
```
|
|
178
280
|
|
|
179
281
|
### Upload a single blob to multiple servers
|
|
180
282
|
|
|
181
283
|
```js
|
|
182
|
-
import {
|
|
284
|
+
import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
|
|
183
285
|
|
|
184
286
|
async function signer(event) {
|
|
185
287
|
return await window.nostr.signEvent(event);
|
|
@@ -188,21 +290,19 @@ async function signer(event) {
|
|
|
188
290
|
const servers = ["https://cdn.example.com", "https://cdn.other.com"];
|
|
189
291
|
const file = new File(["testing"], "test.txt");
|
|
190
292
|
|
|
191
|
-
const auth = await
|
|
293
|
+
const auth = await createUploadAuth(signer, file, { message: "Upload test.txt" });
|
|
192
294
|
|
|
193
295
|
for (let server of servers) {
|
|
194
|
-
await
|
|
296
|
+
await uploadBlob(server, file, { auth });
|
|
195
297
|
}
|
|
196
298
|
```
|
|
197
299
|
|
|
198
300
|
### Uploading and mirroring to multiple servers
|
|
199
301
|
|
|
200
|
-
The `multiServerUpload` method
|
|
201
|
-
|
|
202
|
-
Example of uploading to each server one at time
|
|
302
|
+
The `multiServerUpload` method uploads a blob to the first server, then mirrors it to the remaining servers. It runs parallel preflight checks (`HEAD /<sha256>`) to detect which servers already have the blob, using `/mirror` to register ownership on those servers instead of re-uploading.
|
|
203
303
|
|
|
204
304
|
```ts
|
|
205
|
-
import { multiServerUpload, createUploadAuth } from "blossom-
|
|
305
|
+
import { multiServerUpload, createUploadAuth } from "blossom-client-sdk";
|
|
206
306
|
|
|
207
307
|
async function signer(event: any) {
|
|
208
308
|
// @ts-expect-error
|
|
@@ -212,23 +312,29 @@ async function signer(event: any) {
|
|
|
212
312
|
const servers = ["https://cdn.server-a.com", "https://cdn.example.com", "https://cdn.other.com"];
|
|
213
313
|
const file = new File(["testing"], "test.txt");
|
|
214
314
|
|
|
215
|
-
// create async generator for upload
|
|
216
315
|
const results = await multiServerUpload(servers, file, {
|
|
217
316
|
onAuth: async (server, sha256, type) => createUploadAuth(signer, sha256, { type }),
|
|
218
|
-
onUpload: (server, blob) => {},
|
|
219
|
-
onError: (server, blob, error) => {
|
|
317
|
+
onUpload: (server, sha256, blob) => {},
|
|
318
|
+
onError: (server, sha256, blob, error) => {
|
|
220
319
|
console.log("Failed to upload to", server);
|
|
221
320
|
console.log(error);
|
|
222
321
|
},
|
|
322
|
+
// handle server rejections (413 too large, 415 unsupported type, etc.)
|
|
323
|
+
onRejection: (server, sha256, blob, error) => {
|
|
324
|
+
console.log(`Server ${server} rejected: ${error.code}`);
|
|
325
|
+
return "skip"; // or "cancel" to abort entirely
|
|
326
|
+
},
|
|
327
|
+
// disable preflight checks if not needed (default: true)
|
|
328
|
+
// preflight: false,
|
|
223
329
|
});
|
|
224
330
|
```
|
|
225
331
|
|
|
226
332
|
### Uploading media and mirroring
|
|
227
333
|
|
|
228
|
-
The `
|
|
334
|
+
The `multiServerMediaUpload` method is designed for media files (images, videos) that should be optimized before distribution. It uploads the blob to a single server's BUD-05 `/media` endpoint for processing, then mirrors the optimized result to all other servers. The original unprocessed blob is never uploaded to other servers since the `/media` endpoint may transform it (resize, re-encode, etc.).
|
|
229
335
|
|
|
230
336
|
```ts
|
|
231
|
-
import {
|
|
337
|
+
import { multiServerMediaUpload, createUploadAuth } from "blossom-client-sdk";
|
|
232
338
|
|
|
233
339
|
async function signer(event: any) {
|
|
234
340
|
// @ts-expect-error
|
|
@@ -238,17 +344,13 @@ async function signer(event: any) {
|
|
|
238
344
|
const servers = ["https://cdn.server-a.com", "https://cdn.example.com", "https://cdn.other.com"];
|
|
239
345
|
const media = new File(["image data"], "image.png");
|
|
240
346
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
// use media upload endpoint
|
|
244
|
-
isMedia: true,
|
|
245
|
-
// use any servers media endpoint
|
|
347
|
+
const results = await multiServerMediaUpload(servers, media, {
|
|
348
|
+
// try any server's /media endpoint, not just the first (default: "first")
|
|
246
349
|
mediaUploadBehavior: "any",
|
|
247
|
-
// if
|
|
350
|
+
// fall back to regular upload if no /media endpoint is found (default: false)
|
|
248
351
|
mediaUploadFallback: true,
|
|
249
|
-
// handle auth requests
|
|
250
352
|
onAuth: async (server, sha256, type) => createUploadAuth(signer, sha256, { type }),
|
|
251
|
-
onError: (server, blob, error) => {
|
|
353
|
+
onError: (server, sha256, blob, error) => {
|
|
252
354
|
console.log("Failed to upload to", server);
|
|
253
355
|
console.log(error);
|
|
254
356
|
},
|
|
@@ -258,7 +360,7 @@ const results = await multiServerUpload(servers, media, {
|
|
|
258
360
|
### Upload and Mirror manually
|
|
259
361
|
|
|
260
362
|
```js
|
|
261
|
-
import {
|
|
363
|
+
import { uploadBlob, mirrorBlob, createUploadAuth } from "blossom-client-sdk";
|
|
262
364
|
|
|
263
365
|
async function signer(event) {
|
|
264
366
|
return await window.nostr.signEvent(event);
|
|
@@ -268,14 +370,66 @@ const mainServer = "https://cdn.server-a.com";
|
|
|
268
370
|
const mirrorServers = ["https://cdn.example.com", "https://cdn.other.com"];
|
|
269
371
|
const file = new File(["testing"], "test.txt");
|
|
270
372
|
|
|
271
|
-
const auth = await
|
|
373
|
+
const auth = await createUploadAuth(signer, file, { message: "Upload test.txt" });
|
|
272
374
|
|
|
273
375
|
// first upload blob to main server
|
|
274
|
-
const blob = await
|
|
376
|
+
const blob = await uploadBlob(mainServer, file, { auth });
|
|
275
377
|
|
|
276
378
|
// then tell mirror servers to download it
|
|
277
379
|
for (let server of mirrorServers) {
|
|
278
|
-
|
|
279
|
-
await BlossomClient.mirrorBlob(server, blob.url, auth);
|
|
380
|
+
await mirrorBlob(server, blob, { auth });
|
|
280
381
|
}
|
|
281
382
|
```
|
|
383
|
+
|
|
384
|
+
### Check if a blob exists
|
|
385
|
+
|
|
386
|
+
```js
|
|
387
|
+
import { hasBlob } from "blossom-client-sdk/actions/has";
|
|
388
|
+
|
|
389
|
+
const exists = await hasBlob(
|
|
390
|
+
"https://cdn.example.com",
|
|
391
|
+
"b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553",
|
|
392
|
+
);
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
### Blossom URIs (BUD-10)
|
|
396
|
+
|
|
397
|
+
Parse and build `blossom:` URIs for referencing blobs across servers
|
|
398
|
+
|
|
399
|
+
```js
|
|
400
|
+
import { parseBlossomURI, buildBlossomURI, blossomURIToURL, blossomURIFromURL } from "blossom-client-sdk";
|
|
401
|
+
|
|
402
|
+
// parse a blossom URI
|
|
403
|
+
const parsed = parseBlossomURI(
|
|
404
|
+
"blossom:b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.pdf?xs=cdn.example.com&as=266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5&sz=1024",
|
|
405
|
+
);
|
|
406
|
+
// -> { sha256: "b167...", ext: "pdf", servers: ["cdn.example.com"], authors: ["2668..."], size: 1024 }
|
|
407
|
+
|
|
408
|
+
// build a blossom URI
|
|
409
|
+
const uri = buildBlossomURI({ sha256: "b167...", ext: "pdf", servers: ["cdn.example.com"], authors: [], size: 1024 });
|
|
410
|
+
// -> "blossom:b167....pdf?xs=cdn.example.com&sz=1024"
|
|
411
|
+
|
|
412
|
+
// convert to/from native URL objects
|
|
413
|
+
const url = blossomURIToURL(parsed);
|
|
414
|
+
const backToParsed = blossomURIFromURL(url);
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
### Resolve and download from a blossom URI
|
|
418
|
+
|
|
419
|
+
The `resolveBlob` function tries servers from the URI hints sequentially and returns the first successful response. Author hints are only resolved if server hints fail.
|
|
420
|
+
|
|
421
|
+
```js
|
|
422
|
+
import { Actions } from "blossom-client-sdk";
|
|
423
|
+
|
|
424
|
+
const response = await Actions.resolveBlob("blossom:b167...4f553.pdf?xs=cdn.example.com&as=2668...08a5", {
|
|
425
|
+
// resolve author pubkeys to server lists (only called if xs servers fail)
|
|
426
|
+
getServers: async (pubkey) => {
|
|
427
|
+
const event = await ndk.fetchEvent({ kinds: [USER_BLOSSOM_SERVER_LIST_KIND], authors: [pubkey] });
|
|
428
|
+
return event ? getServersFromServerListEvent(event) : undefined;
|
|
429
|
+
},
|
|
430
|
+
// additional servers to try as a last resort
|
|
431
|
+
fallbackServers: ["https://fallback.cdn.com"],
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
const blob = await response.blob();
|
|
435
|
+
```
|
package/lib/actions/delete.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { ServerType } from "../
|
|
1
|
+
import { ServerType } from "../types.js";
|
|
2
2
|
import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
|
|
3
3
|
export type DeleteOptions<S extends ServerType> = {
|
|
4
4
|
/** AbortSignal to cancel the action */
|
|
5
5
|
signal?: AbortSignal;
|
|
6
|
-
/** Override
|
|
7
|
-
auth?: SignedEvent;
|
|
6
|
+
/** Override authorization event, or true to always use authorization, false to disable authorization */
|
|
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
|
/**
|
package/lib/actions/delete.js
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
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/fetch.js";
|
|
4
4
|
/** Deletes a blob to a server */
|
|
5
5
|
export async function deleteBlob(server, hash, opts) {
|
|
6
6
|
const url = new URL("/" + hash, server);
|
|
7
|
+
const resolveAuth = async (preset = false) => {
|
|
8
|
+
const reused = opts?.authEvents
|
|
9
|
+
? await getReusableAuthEvent(opts.authEvents, { server, type: "delete", blob: hash })
|
|
10
|
+
: undefined;
|
|
11
|
+
if (reused)
|
|
12
|
+
return reused;
|
|
13
|
+
const auth = await opts?.onAuth?.(server, hash);
|
|
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
|
-
// attach the
|
|
9
|
-
if (opts?.auth)
|
|
10
|
-
|
|
21
|
+
// attach the authorization if its already set
|
|
22
|
+
if (opts?.auth) {
|
|
23
|
+
if (typeof opts.auth === "boolean") {
|
|
24
|
+
headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
11
30
|
let res = await fetchWithTimeout(url, {
|
|
12
31
|
method: "DELETE",
|
|
13
32
|
headers,
|
|
@@ -17,9 +36,11 @@ export async function deleteBlob(server, hash, opts) {
|
|
|
17
36
|
// handle auth and payment
|
|
18
37
|
switch (res.status) {
|
|
19
38
|
case 401: {
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
throw new Error("
|
|
39
|
+
// throw an error if authorization is required but disabled
|
|
40
|
+
if (opts?.auth === false)
|
|
41
|
+
throw new Error("Authorization disabled");
|
|
42
|
+
// request authorization for this request
|
|
43
|
+
const auth = await resolveAuth();
|
|
23
44
|
// Try delete with auth
|
|
24
45
|
res = await fetchWithTimeout(url, {
|
|
25
46
|
signal: opts?.signal,
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { ServerType } from "../
|
|
1
|
+
import { ServerType } from "../types.js";
|
|
2
2
|
import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
|
|
3
3
|
export type DownloadOptions<S extends ServerType> = {
|
|
4
4
|
/** AbortSignal to cancel the action */
|
|
5
5
|
signal?: AbortSignal;
|
|
6
|
-
/** Override
|
|
7
|
-
auth?: SignedEvent;
|
|
6
|
+
/** Override authorization event, or true to always use authorization, false to disable authorization */
|
|
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
|
/**
|
package/lib/actions/download.js
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
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
4
|
/** Downloads a blob from a server and returns the Response */
|
|
5
5
|
export async function downloadBlob(server, hash, opts) {
|
|
6
6
|
const url = new URL("/" + hash, server);
|
|
7
|
+
const resolveAuth = async (preset = false) => {
|
|
8
|
+
const reused = opts?.authEvents
|
|
9
|
+
? await getReusableAuthEvent(opts.authEvents, { server, type: "get", blob: hash })
|
|
10
|
+
: undefined;
|
|
11
|
+
if (reused)
|
|
12
|
+
return reused;
|
|
13
|
+
const auth = await opts?.onAuth?.(server, hash);
|
|
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
|
-
// attach the
|
|
9
|
-
if (opts?.auth)
|
|
10
|
-
|
|
21
|
+
// attach the authorization if its already set
|
|
22
|
+
if (opts?.auth) {
|
|
23
|
+
if (typeof opts.auth === "boolean") {
|
|
24
|
+
headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
11
30
|
let download = await fetchWithTimeout(url, {
|
|
12
31
|
headers,
|
|
13
32
|
signal: opts?.signal,
|
|
@@ -16,9 +35,11 @@ export async function downloadBlob(server, hash, opts) {
|
|
|
16
35
|
// handle auth and payment
|
|
17
36
|
switch (download.status) {
|
|
18
37
|
case 401: {
|
|
19
|
-
|
|
20
|
-
if (
|
|
21
|
-
throw new Error("
|
|
38
|
+
// throw an error if auth is requested and disabled
|
|
39
|
+
if (opts?.auth === false)
|
|
40
|
+
throw new Error("Authorization disabled");
|
|
41
|
+
// Request authorization for this request
|
|
42
|
+
const auth = await resolveAuth();
|
|
22
43
|
// Try download with auth
|
|
23
44
|
download = await fetchWithTimeout(url, {
|
|
24
45
|
headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ServerType } from "../types.js";
|
|
2
|
+
export type HasBlobOptions = {
|
|
3
|
+
/** AbortSignal to cancel the action */
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
/** Request timeout */
|
|
6
|
+
timeout?: number;
|
|
7
|
+
};
|
|
8
|
+
/** Checks if a blob exists on a server */
|
|
9
|
+
export declare function hasBlob<S extends ServerType>(server: S, hash: string, opts?: HasBlobOptions): Promise<boolean>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { fetchWithTimeout } from "../helpers/index.js";
|
|
2
|
+
/** Checks if a blob exists on a server */
|
|
3
|
+
export async function hasBlob(server, hash, opts) {
|
|
4
|
+
const res = await fetchWithTimeout(new URL("/" + hash, server), {
|
|
5
|
+
method: "HEAD",
|
|
6
|
+
signal: opts?.signal,
|
|
7
|
+
timeout: opts?.timeout,
|
|
8
|
+
});
|
|
9
|
+
return res.status !== 404;
|
|
10
|
+
}
|
package/lib/actions/index.d.ts
CHANGED
|
@@ -3,5 +3,8 @@ export * from "./mirror.js";
|
|
|
3
3
|
export * from "./list.js";
|
|
4
4
|
export * from "./delete.js";
|
|
5
5
|
export * from "./download.js";
|
|
6
|
+
export * from "./has.js";
|
|
7
|
+
export * from "./resolve.js";
|
|
6
8
|
export * from "./multi-server.js";
|
|
7
9
|
export * from "./media.js";
|
|
10
|
+
export * from "./report.js";
|
package/lib/actions/index.js
CHANGED
|
@@ -3,5 +3,8 @@ export * from "./mirror.js";
|
|
|
3
3
|
export * from "./list.js";
|
|
4
4
|
export * from "./delete.js";
|
|
5
5
|
export * from "./download.js";
|
|
6
|
+
export * from "./has.js";
|
|
7
|
+
export * from "./resolve.js";
|
|
6
8
|
export * from "./multi-server.js";
|
|
7
9
|
export * from "./media.js";
|
|
10
|
+
export * from "./report.js";
|