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/src/actions/upload.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { encodeAuthorizationHeader } from "../auth.js";
|
|
2
|
-
import { ServerType, UploadType } from "../
|
|
1
|
+
import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
|
|
2
|
+
import { ServerType, UploadType } from "../types.js";
|
|
3
3
|
import HTTPError from "../error.js";
|
|
4
4
|
import { fetchWithTimeout, getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
|
|
5
5
|
import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
|
|
@@ -7,8 +7,10 @@ import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../ty
|
|
|
7
7
|
export type UploadOptions<S extends ServerType, B extends UploadType> = {
|
|
8
8
|
/** AbortSignal to cancel the action */
|
|
9
9
|
signal?: AbortSignal;
|
|
10
|
-
/** Override
|
|
11
|
-
auth?: SignedEvent;
|
|
10
|
+
/** Override authorization event, or true to always use authorization, false to disable authorization */
|
|
11
|
+
auth?: SignedEvent | boolean;
|
|
12
|
+
/** Shared auth event store used to reuse non-expired auth events between requests */
|
|
13
|
+
authEvents?: Set<SignedEvent>;
|
|
12
14
|
/** Request timeout */
|
|
13
15
|
timeout?: number;
|
|
14
16
|
/**
|
|
@@ -36,13 +38,31 @@ export async function uploadBlob<S extends ServerType, B extends UploadType>(
|
|
|
36
38
|
): Promise<BlobDescriptor> {
|
|
37
39
|
const url = new URL("/upload", server);
|
|
38
40
|
const sha256 = await getBlobSha256(blob);
|
|
41
|
+
const resolveAuth = async (preset: boolean = false) => {
|
|
42
|
+
const reused = opts?.authEvents
|
|
43
|
+
? await getReusableAuthEvent(opts.authEvents, { server, type: "upload", blob: sha256 })
|
|
44
|
+
: undefined;
|
|
45
|
+
if (reused) return reused;
|
|
46
|
+
|
|
47
|
+
const auth = await opts?.onAuth?.(server, sha256, "upload", blob);
|
|
48
|
+
if (!auth) throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
|
|
49
|
+
|
|
50
|
+
if (opts?.authEvents) storeAuthEvent(opts.authEvents, auth);
|
|
51
|
+
return auth;
|
|
52
|
+
};
|
|
39
53
|
|
|
40
54
|
const headers: Record<string, string> = {
|
|
41
55
|
"X-SHA-256": sha256,
|
|
42
56
|
};
|
|
43
57
|
|
|
44
|
-
// attach the
|
|
45
|
-
if (opts?.auth)
|
|
58
|
+
// attach the authorization if its already set
|
|
59
|
+
if (opts?.auth) {
|
|
60
|
+
if (typeof opts.auth === "boolean") {
|
|
61
|
+
headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
|
|
62
|
+
} else {
|
|
63
|
+
headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
46
66
|
|
|
47
67
|
// build check headers
|
|
48
68
|
const checkHeaders: Record<string, string> = {
|
|
@@ -75,8 +95,11 @@ export async function uploadBlob<S extends ServerType, B extends UploadType>(
|
|
|
75
95
|
// handle auth and payment
|
|
76
96
|
switch (firstTry.status) {
|
|
77
97
|
case 401: {
|
|
78
|
-
|
|
79
|
-
if (
|
|
98
|
+
// throw an error if auth is requested and disabled
|
|
99
|
+
if (opts?.auth === false) throw new Error("Authorization disabled");
|
|
100
|
+
|
|
101
|
+
// Request authorization event for this upload
|
|
102
|
+
const auth = await resolveAuth();
|
|
80
103
|
|
|
81
104
|
// Try upload with auth
|
|
82
105
|
upload = await fetchWithTimeout(url, {
|
package/src/auth.ts
CHANGED
|
@@ -1,42 +1,128 @@
|
|
|
1
|
-
import { ServerType, UploadType } from "./
|
|
1
|
+
import { ServerType, UploadType } from "./types.js";
|
|
2
2
|
import { AUTH_EVENT_KIND } from "./const.js";
|
|
3
3
|
import { getBlobSha256, isSha256 } from "./helpers/blob.js";
|
|
4
|
-
import { areServersEqual } from "./helpers/url.js";
|
|
4
|
+
import { areServersEqual, getServerHostname } from "./helpers/url.js";
|
|
5
5
|
import { EventTemplate, SignedEvent, Signer } from "./types.js";
|
|
6
6
|
|
|
7
7
|
export const now = () => Math.floor(new Date().valueOf() / 1000);
|
|
8
8
|
export const oneHour = () => now() + 60 * 60;
|
|
9
9
|
|
|
10
|
+
export type AuthRequest = {
|
|
11
|
+
server: ServerType;
|
|
12
|
+
type: AuthType;
|
|
13
|
+
blob?: string | UploadType;
|
|
14
|
+
};
|
|
15
|
+
|
|
10
16
|
/** Encodes an auth event into a nostr authorization header */
|
|
11
17
|
export function encodeAuthorizationHeader(event: SignedEvent) {
|
|
12
|
-
|
|
18
|
+
const json = JSON.stringify(event);
|
|
19
|
+
const bytes = new TextEncoder().encode(json);
|
|
20
|
+
let binary = "";
|
|
21
|
+
|
|
22
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
23
|
+
|
|
24
|
+
return "Nostr " + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
13
25
|
}
|
|
14
26
|
|
|
15
27
|
/** Checks if an auth event matches a server / blob upload */
|
|
16
|
-
export async function
|
|
17
|
-
|
|
28
|
+
export async function doseAuthMatchBlob(
|
|
29
|
+
auth: SignedEvent,
|
|
30
|
+
server: ServerType,
|
|
31
|
+
blob: string | UploadType,
|
|
32
|
+
type: string = "upload",
|
|
33
|
+
) {
|
|
18
34
|
if (type !== "upload" && type !== "media") return false;
|
|
35
|
+
return doesAuthMatchRequest(auth, { server, type, blob });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Returns all tag values for a specific tag name */
|
|
39
|
+
export function getAuthTagValues(auth: SignedEvent, tagName: string) {
|
|
40
|
+
return auth.tags.filter((tag) => tag[0] === tagName).map((tag) => tag[1]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Returns the auth event expiration timestamp if one exists */
|
|
44
|
+
export function getAuthExpiration(auth: SignedEvent) {
|
|
45
|
+
const expiration = auth.tags.find((tag) => tag[0] === "expiration")?.[1];
|
|
46
|
+
if (!expiration) return undefined;
|
|
19
47
|
|
|
20
|
-
const
|
|
48
|
+
const timestamp = Number(expiration);
|
|
49
|
+
if (!Number.isFinite(timestamp)) return undefined;
|
|
50
|
+
|
|
51
|
+
return timestamp;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Returns true if an auth event has expired */
|
|
55
|
+
export function isAuthExpired(auth: SignedEvent, timestamp: number = now()) {
|
|
56
|
+
const expiration = getAuthExpiration(auth);
|
|
57
|
+
return expiration !== undefined && expiration <= timestamp;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Normalizes a server tag value to a lowercase hostname */
|
|
61
|
+
export function normalizeServerTag(server: string | URL) {
|
|
62
|
+
return getServerHostname(server);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function requestRequiresHashTag(type: AuthType) {
|
|
66
|
+
return type === "upload" || type === "media" || type === "delete";
|
|
67
|
+
}
|
|
21
68
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
69
|
+
/** Checks if an auth event can be reused for a request */
|
|
70
|
+
export async function doesAuthMatchRequest(auth: SignedEvent, request: AuthRequest) {
|
|
71
|
+
if (isAuthExpired(auth)) return false;
|
|
72
|
+
|
|
73
|
+
const authType = auth.tags.find((tag) => tag[0] === "t")?.[1];
|
|
74
|
+
if (authType !== request.type) return false;
|
|
75
|
+
|
|
76
|
+
const serverTags = getAuthTagValues(auth, "server");
|
|
77
|
+
if (serverTags.length > 0 && !serverTags.some((server) => areServersEqual(server, request.server))) return false;
|
|
78
|
+
|
|
79
|
+
if (request.type === "list") return true;
|
|
80
|
+
|
|
81
|
+
const blobTags = getAuthTagValues(auth, "x");
|
|
82
|
+
if (!request.blob) return false;
|
|
83
|
+
|
|
84
|
+
const sha256 = typeof request.blob === "string" ? request.blob : await getBlobSha256(request.blob);
|
|
85
|
+
|
|
86
|
+
if (blobTags.length === 0) return !requestRequiresHashTag(request.type);
|
|
87
|
+
return blobTags.includes(sha256);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Finds a reusable auth event in a store and prunes expired events */
|
|
91
|
+
export async function getReusableAuthEvent(authEvents: Set<SignedEvent>, request: AuthRequest) {
|
|
92
|
+
for (const auth of authEvents) {
|
|
93
|
+
if (isAuthExpired(auth)) {
|
|
94
|
+
authEvents.delete(auth);
|
|
95
|
+
continue;
|
|
30
96
|
}
|
|
97
|
+
|
|
98
|
+
if (await doesAuthMatchRequest(auth, request)) return auth;
|
|
31
99
|
}
|
|
32
100
|
|
|
33
|
-
return
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Stores a new auth event in the shared store */
|
|
105
|
+
export function storeAuthEvent(authEvents: Set<SignedEvent>, auth: SignedEvent) {
|
|
106
|
+
authEvents.add(auth);
|
|
107
|
+
return auth;
|
|
34
108
|
}
|
|
35
109
|
|
|
110
|
+
/** @deprecated Use `doseAuthMatchBlob` instead */
|
|
111
|
+
export const doseAuthMatchUpload = doseAuthMatchBlob;
|
|
112
|
+
|
|
36
113
|
async function normalizeToHash(blob: string | UploadType) {
|
|
37
114
|
return typeof blob === "string" ? blob : getBlobSha256(blob);
|
|
38
115
|
}
|
|
39
116
|
|
|
117
|
+
function normalizeServers(servers: string | string[]) {
|
|
118
|
+
const values = Array.isArray(servers) ? servers : [servers];
|
|
119
|
+
return [...new Set(values.map((server) => normalizeServerTag(server)))];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function isDomainName(value: string) {
|
|
123
|
+
return /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value);
|
|
124
|
+
}
|
|
125
|
+
|
|
40
126
|
export type AuthType = "upload" | "list" | "delete" | "get" | "media";
|
|
41
127
|
export type AuthEventOptions = {
|
|
42
128
|
blobs?: string | string[] | UploadType | UploadType[];
|
|
@@ -74,9 +160,7 @@ export async function createAuthEvent(signer: Signer, type: AuthType, options?:
|
|
|
74
160
|
|
|
75
161
|
// add server tags
|
|
76
162
|
if (options?.servers) {
|
|
77
|
-
|
|
78
|
-
for (const server of new Set(options.servers)) draft.tags.push(["server", server]);
|
|
79
|
-
else draft.tags.push(["server", options.servers]);
|
|
163
|
+
for (const server of normalizeServers(options.servers)) draft.tags.push(["server", server]);
|
|
80
164
|
}
|
|
81
165
|
|
|
82
166
|
return await signer(draft);
|
|
@@ -95,7 +179,9 @@ export async function createDownloadAuth(
|
|
|
95
179
|
message: "Download Blob",
|
|
96
180
|
...options,
|
|
97
181
|
blobs: serverOrHash.filter((s) => (typeof s === "string" ? isSha256(s) : true)) as string[] | UploadType[],
|
|
98
|
-
servers: serverOrHash.filter(
|
|
182
|
+
servers: serverOrHash.filter(
|
|
183
|
+
(s) => typeof s === "string" && !isSha256(s) && (URL.canParse(s) || isDomainName(s)),
|
|
184
|
+
) as string[],
|
|
99
185
|
});
|
|
100
186
|
}
|
|
101
187
|
|
package/src/error.ts
CHANGED
|
@@ -1,16 +1,31 @@
|
|
|
1
|
+
export type RejectionCode = "conflict" | "too_large" | "unsupported_type" | "unprocessable";
|
|
2
|
+
|
|
3
|
+
const REJECTION_CODES: Record<number, RejectionCode> = {
|
|
4
|
+
409: "conflict",
|
|
5
|
+
413: "too_large",
|
|
6
|
+
415: "unsupported_type",
|
|
7
|
+
422: "unprocessable",
|
|
8
|
+
};
|
|
9
|
+
|
|
1
10
|
export default class HTTPError extends Error {
|
|
2
11
|
response: Response;
|
|
3
12
|
status: number;
|
|
4
13
|
body?: { message: string };
|
|
14
|
+
code?: RejectionCode;
|
|
5
15
|
|
|
6
16
|
constructor(response: Response, body: { message: string } | string) {
|
|
7
17
|
super(typeof body === "string" ? body : body.message);
|
|
8
18
|
this.response = response;
|
|
9
19
|
this.status = response.status;
|
|
20
|
+
this.code = REJECTION_CODES[response.status];
|
|
10
21
|
|
|
11
22
|
if (typeof body == "object") this.body = body;
|
|
12
23
|
}
|
|
13
24
|
|
|
25
|
+
static isRejection(error: unknown): error is HTTPError & { code: RejectionCode } {
|
|
26
|
+
return error instanceof HTTPError && error.code !== undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
14
29
|
static async handleErrorResponse(res: Response) {
|
|
15
30
|
if (!res.ok) {
|
|
16
31
|
try {
|
package/src/helpers/blob.ts
CHANGED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { isSha256 } from "./blob.js";
|
|
2
|
+
|
|
3
|
+
export type BlossomURI = {
|
|
4
|
+
/** SHA-256 hash of the blob */
|
|
5
|
+
sha256: string;
|
|
6
|
+
/** File extension (e.g. "png", "pdf") */
|
|
7
|
+
ext: string;
|
|
8
|
+
/** Server hints from xs params */
|
|
9
|
+
servers: string[];
|
|
10
|
+
/** Author pubkey hints from as params */
|
|
11
|
+
authors: string[];
|
|
12
|
+
/** Expected blob size in bytes from sz param */
|
|
13
|
+
size?: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Parses a blossom: URI string into its components */
|
|
17
|
+
export function parseBlossomURI(uri: string): BlossomURI {
|
|
18
|
+
if (!uri.startsWith("blossom:")) throw new Error("Invalid blossom URI: missing blossom: scheme");
|
|
19
|
+
|
|
20
|
+
const body = uri.slice("blossom:".length);
|
|
21
|
+
|
|
22
|
+
// split hash.ext from query params
|
|
23
|
+
const queryIndex = body.indexOf("?");
|
|
24
|
+
const path = queryIndex === -1 ? body : body.slice(0, queryIndex);
|
|
25
|
+
const query = queryIndex === -1 ? "" : body.slice(queryIndex + 1);
|
|
26
|
+
|
|
27
|
+
// extract sha256 and extension
|
|
28
|
+
const dotIndex = path.indexOf(".");
|
|
29
|
+
if (dotIndex === -1) throw new Error("Invalid blossom URI: missing file extension");
|
|
30
|
+
|
|
31
|
+
const sha256 = path.slice(0, dotIndex);
|
|
32
|
+
const ext = path.slice(dotIndex + 1);
|
|
33
|
+
|
|
34
|
+
if (!isSha256(sha256)) throw new Error("Invalid blossom URI: invalid sha256 hash");
|
|
35
|
+
if (!ext) throw new Error("Invalid blossom URI: empty file extension");
|
|
36
|
+
|
|
37
|
+
// parse query params
|
|
38
|
+
const params = new URLSearchParams(query);
|
|
39
|
+
const servers = params.getAll("xs");
|
|
40
|
+
const authors = params.getAll("as");
|
|
41
|
+
|
|
42
|
+
const szValue = params.get("sz");
|
|
43
|
+
let size: number | undefined;
|
|
44
|
+
if (szValue !== null) {
|
|
45
|
+
size = Number(szValue);
|
|
46
|
+
if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
|
|
47
|
+
throw new Error("Invalid blossom URI: sz must be a positive integer");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return { sha256, ext, servers, authors, size };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Builds a blossom: URI string from components */
|
|
55
|
+
export function buildBlossomURI(options: BlossomURI): string {
|
|
56
|
+
const params = new URLSearchParams();
|
|
57
|
+
|
|
58
|
+
for (const server of options.servers) params.append("xs", server);
|
|
59
|
+
for (const author of options.authors) params.append("as", author);
|
|
60
|
+
if (options.size !== undefined) params.append("sz", String(options.size));
|
|
61
|
+
|
|
62
|
+
const query = params.toString();
|
|
63
|
+
return `blossom:${options.sha256}.${options.ext}${query ? "?" + query : ""}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Converts a BlossomURI to a native URL object */
|
|
67
|
+
export function blossomURIToURL(uri: string | BlossomURI): URL {
|
|
68
|
+
const str = typeof uri === "string" ? uri : buildBlossomURI(uri);
|
|
69
|
+
return new URL(str);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Parses a blossom: URL object into its components */
|
|
73
|
+
export function blossomURIFromURL(url: URL): BlossomURI {
|
|
74
|
+
if (url.protocol !== "blossom:") throw new Error("Invalid blossom URL: expected blossom: protocol");
|
|
75
|
+
|
|
76
|
+
const path = url.pathname;
|
|
77
|
+
const dotIndex = path.indexOf(".");
|
|
78
|
+
if (dotIndex === -1) throw new Error("Invalid blossom URL: missing file extension");
|
|
79
|
+
|
|
80
|
+
const sha256 = path.slice(0, dotIndex);
|
|
81
|
+
const ext = path.slice(dotIndex + 1);
|
|
82
|
+
|
|
83
|
+
if (!isSha256(sha256)) throw new Error("Invalid blossom URL: invalid sha256 hash");
|
|
84
|
+
if (!ext) throw new Error("Invalid blossom URL: empty file extension");
|
|
85
|
+
|
|
86
|
+
const servers = url.searchParams.getAll("xs");
|
|
87
|
+
const authors = url.searchParams.getAll("as");
|
|
88
|
+
|
|
89
|
+
const szValue = url.searchParams.get("sz");
|
|
90
|
+
let size: number | undefined;
|
|
91
|
+
if (szValue !== null) {
|
|
92
|
+
size = Number(szValue);
|
|
93
|
+
if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
|
|
94
|
+
throw new Error("Invalid blossom URL: sz must be a positive integer");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { sha256, ext, servers, authors, size };
|
|
99
|
+
}
|
package/src/helpers/index.ts
CHANGED
package/src/helpers/url.ts
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
+
/** Normalizes a server reference to a lowercase hostname */
|
|
2
|
+
export function getServerHostname(server: string | URL) {
|
|
3
|
+
if (server instanceof URL) return server.hostname.toLowerCase();
|
|
4
|
+
|
|
5
|
+
if (URL.canParse(server)) return new URL(server).hostname.toLowerCase();
|
|
6
|
+
|
|
7
|
+
return server.toLowerCase();
|
|
8
|
+
}
|
|
9
|
+
|
|
1
10
|
/** Check if two servers are the same */
|
|
2
11
|
export function areServersEqual(a: string | URL, b: string | URL) {
|
|
3
|
-
|
|
4
|
-
const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
|
|
5
|
-
return hostnameA === hostnameB;
|
|
12
|
+
return getServerHostname(a) === getServerHostname(b);
|
|
6
13
|
}
|
|
7
14
|
|
|
8
15
|
/** returns the last sha256 in a URL */
|
package/src/hls.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
FragmentLoaderConstructor,
|
|
3
|
+
FragmentLoaderContext as HlsFragmentLoaderContext,
|
|
4
|
+
HlsConfig as HlsLoaderConfig,
|
|
5
|
+
Loader as HlsLoader,
|
|
6
|
+
LoaderCallbacks as HlsLoaderCallbacks,
|
|
7
|
+
LoaderConfiguration as HlsLoaderConfiguration,
|
|
8
|
+
LoaderContext as HlsLoaderContext,
|
|
9
|
+
LoaderResponse as HlsLoaderResponse,
|
|
10
|
+
LoaderStats as HlsLoaderStats,
|
|
11
|
+
PlaylistLoaderConstructor,
|
|
12
|
+
PlaylistLoaderContext as HlsPlaylistLoaderContext,
|
|
13
|
+
} from "hls.js";
|
|
14
|
+
|
|
15
|
+
export type {
|
|
16
|
+
HlsFragmentLoaderContext,
|
|
17
|
+
HlsLoader,
|
|
18
|
+
HlsLoaderCallbacks,
|
|
19
|
+
HlsLoaderConfig,
|
|
20
|
+
HlsLoaderConfiguration,
|
|
21
|
+
HlsLoaderContext,
|
|
22
|
+
HlsLoaderResponse,
|
|
23
|
+
HlsLoaderStats,
|
|
24
|
+
HlsPlaylistLoaderContext,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type BlossomHlsFallbackInfo = {
|
|
28
|
+
kind: "playlist" | "fragment";
|
|
29
|
+
from: string;
|
|
30
|
+
to: string;
|
|
31
|
+
url: string;
|
|
32
|
+
attempt: number;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type BlossomHlsLoaderOptions = {
|
|
36
|
+
fallbackServers?: (string | URL)[];
|
|
37
|
+
stickyFailover?: boolean;
|
|
38
|
+
penalizeMs?: number;
|
|
39
|
+
retryStatuses?: number[];
|
|
40
|
+
onFallback?: (info: BlossomHlsFallbackInfo) => void;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const DEFAULT_PENALIZE_MS = 30_000;
|
|
44
|
+
|
|
45
|
+
function createEmptyStats(): HlsLoaderStats {
|
|
46
|
+
return {
|
|
47
|
+
aborted: false,
|
|
48
|
+
loaded: 0,
|
|
49
|
+
retry: 0,
|
|
50
|
+
total: 0,
|
|
51
|
+
chunkCount: 0,
|
|
52
|
+
bwEstimate: 0,
|
|
53
|
+
loading: { start: 0, first: 0, end: 0 },
|
|
54
|
+
parsing: { start: 0, end: 0 },
|
|
55
|
+
buffering: { start: 0, first: 0, end: 0 },
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeServer(server: string | URL): string {
|
|
60
|
+
if (server instanceof URL) return server.origin;
|
|
61
|
+
if (!server.includes("://")) return `https://${server}`;
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
return new URL(server).origin;
|
|
65
|
+
} catch {
|
|
66
|
+
return `https://${server}`;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function replaceUrlOrigin(url: string, origin: string): string {
|
|
71
|
+
const next = new URL(url);
|
|
72
|
+
const base = new URL(origin);
|
|
73
|
+
|
|
74
|
+
next.protocol = base.protocol;
|
|
75
|
+
next.host = base.host;
|
|
76
|
+
|
|
77
|
+
return next.toString();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function shouldRetry(code: number, isTimeout: boolean, retryStatuses: Set<number>): boolean {
|
|
81
|
+
return isTimeout || code === 0 || code >= 500 || retryStatuses.has(code);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function createBlossomHlsLoaders(options: BlossomHlsLoaderOptions = {}): {
|
|
85
|
+
pLoader: PlaylistLoaderConstructor;
|
|
86
|
+
fLoader: FragmentLoaderConstructor;
|
|
87
|
+
} {
|
|
88
|
+
const fallbackServers = options.fallbackServers?.map(normalizeServer) ?? [];
|
|
89
|
+
const stickyFailover = options.stickyFailover ?? false;
|
|
90
|
+
const penalizeMs = options.penalizeMs ?? DEFAULT_PENALIZE_MS;
|
|
91
|
+
const retryStatuses = new Set(options.retryStatuses ?? [404]);
|
|
92
|
+
const penalties = new Map<string, number>();
|
|
93
|
+
|
|
94
|
+
function clearExpiredPenalties() {
|
|
95
|
+
const now = Date.now();
|
|
96
|
+
|
|
97
|
+
for (const [origin, expiry] of penalties) {
|
|
98
|
+
if (expiry <= now) penalties.delete(origin);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function penalize(origin: string) {
|
|
103
|
+
if (!stickyFailover) return;
|
|
104
|
+
penalties.set(origin, Date.now() + penalizeMs);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function reward(origin: string) {
|
|
108
|
+
if (!stickyFailover) return;
|
|
109
|
+
penalties.delete(origin);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function getCandidateOrigins(url: string): string[] {
|
|
113
|
+
clearExpiredPenalties();
|
|
114
|
+
|
|
115
|
+
const originalOrigin = new URL(url).origin;
|
|
116
|
+
const seen = new Set<string>();
|
|
117
|
+
const ordered = [originalOrigin, ...fallbackServers].filter((origin) => {
|
|
118
|
+
if (seen.has(origin)) return false;
|
|
119
|
+
seen.add(origin);
|
|
120
|
+
return true;
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
if (!stickyFailover) return ordered;
|
|
124
|
+
|
|
125
|
+
const healthy = ordered.filter((origin) => !penalties.has(origin));
|
|
126
|
+
const penalizedOrigins = ordered.filter((origin) => penalties.has(origin));
|
|
127
|
+
|
|
128
|
+
return healthy.length > 0 ? [...healthy, ...penalizedOrigins] : ordered;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function createLoaderClass<T extends HlsLoaderContext>(
|
|
132
|
+
kind: BlossomHlsFallbackInfo["kind"],
|
|
133
|
+
): new (config: HlsLoaderConfig) => HlsLoader<T> {
|
|
134
|
+
return class BlossomHlsLoader implements HlsLoader<T> {
|
|
135
|
+
public context: T | null = null;
|
|
136
|
+
public stats: HlsLoaderStats = createEmptyStats();
|
|
137
|
+
private activeLoader: HlsLoader<T> | null = null;
|
|
138
|
+
private destroyed = false;
|
|
139
|
+
private aborted = false;
|
|
140
|
+
|
|
141
|
+
constructor(private config: HlsLoaderConfig) {}
|
|
142
|
+
|
|
143
|
+
destroy(): void {
|
|
144
|
+
this.destroyed = true;
|
|
145
|
+
this.activeLoader?.destroy();
|
|
146
|
+
this.activeLoader = null;
|
|
147
|
+
this.context = null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
abort(): void {
|
|
151
|
+
this.aborted = true;
|
|
152
|
+
this.activeLoader?.abort();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
getCacheAge(): number | null {
|
|
156
|
+
return this.activeLoader?.getCacheAge?.() ?? null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
getResponseHeader(name: string): string | null {
|
|
160
|
+
return this.activeLoader?.getResponseHeader?.(name) ?? null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
load(context: T, loaderConfig: HlsLoaderConfiguration, callbacks: HlsLoaderCallbacks<T>): void {
|
|
164
|
+
this.destroyed = false;
|
|
165
|
+
this.aborted = false;
|
|
166
|
+
|
|
167
|
+
const origins = getCandidateOrigins(context.url);
|
|
168
|
+
const BaseLoader = this.config.loader as new (config: HlsLoaderConfig) => HlsLoader<T>;
|
|
169
|
+
|
|
170
|
+
let attempt = 0;
|
|
171
|
+
|
|
172
|
+
const startAttempt = () => {
|
|
173
|
+
if (this.destroyed || this.aborted) return;
|
|
174
|
+
|
|
175
|
+
const origin = origins[attempt];
|
|
176
|
+
const attemptUrl = replaceUrlOrigin(context.url, origin);
|
|
177
|
+
const attemptContext = { ...context, url: attemptUrl };
|
|
178
|
+
const loader = new BaseLoader(this.config);
|
|
179
|
+
|
|
180
|
+
this.activeLoader = loader;
|
|
181
|
+
this.context = attemptContext;
|
|
182
|
+
this.stats = loader.stats;
|
|
183
|
+
|
|
184
|
+
loader.load(attemptContext, loaderConfig, {
|
|
185
|
+
onSuccess: (response, stats, successContext, networkDetails) => {
|
|
186
|
+
this.stats = stats;
|
|
187
|
+
this.context = successContext;
|
|
188
|
+
reward(new URL(successContext.url).origin);
|
|
189
|
+
callbacks.onSuccess(response, stats, successContext, networkDetails);
|
|
190
|
+
},
|
|
191
|
+
onProgress: callbacks.onProgress,
|
|
192
|
+
onAbort: callbacks.onAbort,
|
|
193
|
+
onError: (error, errorContext, networkDetails, stats) => {
|
|
194
|
+
this.stats = stats;
|
|
195
|
+
this.context = errorContext;
|
|
196
|
+
|
|
197
|
+
if (attempt < origins.length - 1 && shouldRetry(error.code, false, retryStatuses)) {
|
|
198
|
+
const failedOrigin = new URL(errorContext.url).origin;
|
|
199
|
+
const nextOrigin = origins[attempt + 1];
|
|
200
|
+
|
|
201
|
+
penalize(failedOrigin);
|
|
202
|
+
this.activeLoader?.destroy();
|
|
203
|
+
this.activeLoader = null;
|
|
204
|
+
options.onFallback?.({
|
|
205
|
+
kind,
|
|
206
|
+
from: failedOrigin,
|
|
207
|
+
to: nextOrigin,
|
|
208
|
+
url: errorContext.url,
|
|
209
|
+
attempt: attempt + 1,
|
|
210
|
+
});
|
|
211
|
+
attempt += 1;
|
|
212
|
+
startAttempt();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
callbacks.onError(error, errorContext, networkDetails, stats);
|
|
217
|
+
},
|
|
218
|
+
onTimeout: (stats, timeoutContext, networkDetails) => {
|
|
219
|
+
this.stats = stats;
|
|
220
|
+
this.context = timeoutContext;
|
|
221
|
+
|
|
222
|
+
if (attempt < origins.length - 1 && shouldRetry(0, true, retryStatuses)) {
|
|
223
|
+
const failedOrigin = new URL(timeoutContext.url).origin;
|
|
224
|
+
const nextOrigin = origins[attempt + 1];
|
|
225
|
+
|
|
226
|
+
penalize(failedOrigin);
|
|
227
|
+
this.activeLoader?.destroy();
|
|
228
|
+
this.activeLoader = null;
|
|
229
|
+
options.onFallback?.({
|
|
230
|
+
kind,
|
|
231
|
+
from: failedOrigin,
|
|
232
|
+
to: nextOrigin,
|
|
233
|
+
url: timeoutContext.url,
|
|
234
|
+
attempt: attempt + 1,
|
|
235
|
+
});
|
|
236
|
+
attempt += 1;
|
|
237
|
+
startAttempt();
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
callbacks.onTimeout(stats, timeoutContext, networkDetails);
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
startAttempt();
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
pLoader: createLoaderClass<HlsPlaylistLoaderContext>("playlist"),
|
|
253
|
+
fLoader: createLoaderClass<HlsFragmentLoaderContext>("fragment"),
|
|
254
|
+
};
|
|
255
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
export * from "./const.js";
|
|
2
2
|
export * from "./auth.js";
|
|
3
|
-
export * from "./client.js";
|
|
4
3
|
export * from "./helpers/index.js";
|
|
5
|
-
export * from "./
|
|
4
|
+
export * from "./media.js";
|
|
6
5
|
export * from "./nostr.js";
|
|
7
6
|
export * from "./error.js";
|
|
8
7
|
export * from "./types.js";
|