blossom-client-sdk 4.1.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 +3 -1
- package/lib/actions/delete.js +16 -7
- package/lib/actions/download.d.ts +3 -1
- package/lib/actions/download.js +16 -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 +8 -2
- package/lib/actions/list.js +34 -8
- package/lib/actions/media.d.ts +1 -1
- package/lib/actions/media.js +17 -7
- package/lib/actions/mirror.d.ts +3 -1
- package/lib/actions/mirror.js +16 -7
- package/lib/actions/multi-server.d.ts +63 -43
- package/lib/actions/multi-server.js +205 -96
- 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 +3 -1
- package/lib/actions/upload.js +16 -7
- package/lib/auth.d.ts +20 -1
- package/lib/auth.js +80 -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 +18 -6
- package/src/actions/download.ts +18 -6
- package/src/actions/has.ts +19 -0
- package/src/actions/index.ts +3 -0
- package/src/actions/list.ts +42 -7
- package/src/actions/media.ts +18 -6
- package/src/actions/mirror.ts +18 -6
- package/src/actions/multi-server.ts +264 -118
- package/src/actions/report.ts +54 -0
- package/src/actions/resolve.ts +159 -0
- package/src/actions/upload.ts +18 -6
- package/src/auth.ts +99 -21
- 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/lib/auth.js
CHANGED
|
@@ -1,37 +1,98 @@
|
|
|
1
1
|
import { AUTH_EVENT_KIND } from "./const.js";
|
|
2
2
|
import { getBlobSha256, isSha256 } from "./helpers/blob.js";
|
|
3
|
-
import { areServersEqual } from "./helpers/url.js";
|
|
3
|
+
import { areServersEqual, getServerHostname } from "./helpers/url.js";
|
|
4
4
|
export const now = () => Math.floor(new Date().valueOf() / 1000);
|
|
5
5
|
export const oneHour = () => now() + 60 * 60;
|
|
6
6
|
/** Encodes an auth event into a nostr authorization header */
|
|
7
7
|
export function encodeAuthorizationHeader(event) {
|
|
8
|
-
|
|
8
|
+
const json = JSON.stringify(event);
|
|
9
|
+
const bytes = new TextEncoder().encode(json);
|
|
10
|
+
let binary = "";
|
|
11
|
+
for (const byte of bytes)
|
|
12
|
+
binary += String.fromCharCode(byte);
|
|
13
|
+
return "Nostr " + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
9
14
|
}
|
|
10
15
|
/** Checks if an auth event matches a server / blob upload */
|
|
11
16
|
export async function doseAuthMatchBlob(auth, server, blob, type = "upload") {
|
|
12
|
-
|
|
13
|
-
if (authType !== type)
|
|
17
|
+
if (type !== "upload" && type !== "media")
|
|
14
18
|
return false;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
19
|
+
return doesAuthMatchRequest(auth, { server, type, blob });
|
|
20
|
+
}
|
|
21
|
+
/** Returns all tag values for a specific tag name */
|
|
22
|
+
export function getAuthTagValues(auth, tagName) {
|
|
23
|
+
return auth.tags.filter((tag) => tag[0] === tagName).map((tag) => tag[1]);
|
|
24
|
+
}
|
|
25
|
+
/** Returns the auth event expiration timestamp if one exists */
|
|
26
|
+
export function getAuthExpiration(auth) {
|
|
27
|
+
const expiration = auth.tags.find((tag) => tag[0] === "expiration")?.[1];
|
|
28
|
+
if (!expiration)
|
|
29
|
+
return undefined;
|
|
30
|
+
const timestamp = Number(expiration);
|
|
31
|
+
if (!Number.isFinite(timestamp))
|
|
32
|
+
return undefined;
|
|
33
|
+
return timestamp;
|
|
34
|
+
}
|
|
35
|
+
/** Returns true if an auth event has expired */
|
|
36
|
+
export function isAuthExpired(auth, timestamp = now()) {
|
|
37
|
+
const expiration = getAuthExpiration(auth);
|
|
38
|
+
return expiration !== undefined && expiration <= timestamp;
|
|
39
|
+
}
|
|
40
|
+
/** Normalizes a server tag value to a lowercase hostname */
|
|
41
|
+
export function normalizeServerTag(server) {
|
|
42
|
+
return getServerHostname(server);
|
|
43
|
+
}
|
|
44
|
+
function requestRequiresHashTag(type) {
|
|
45
|
+
return type === "upload" || type === "media" || type === "delete";
|
|
46
|
+
}
|
|
47
|
+
/** Checks if an auth event can be reused for a request */
|
|
48
|
+
export async function doesAuthMatchRequest(auth, request) {
|
|
49
|
+
if (isAuthExpired(auth))
|
|
50
|
+
return false;
|
|
51
|
+
const authType = auth.tags.find((tag) => tag[0] === "t")?.[1];
|
|
52
|
+
if (authType !== request.type)
|
|
53
|
+
return false;
|
|
54
|
+
const serverTags = getAuthTagValues(auth, "server");
|
|
55
|
+
if (serverTags.length > 0 && !serverTags.some((server) => areServersEqual(server, request.server)))
|
|
56
|
+
return false;
|
|
57
|
+
if (request.type === "list")
|
|
58
|
+
return true;
|
|
59
|
+
const blobTags = getAuthTagValues(auth, "x");
|
|
60
|
+
if (!request.blob)
|
|
61
|
+
return false;
|
|
62
|
+
const sha256 = typeof request.blob === "string" ? request.blob : await getBlobSha256(request.blob);
|
|
63
|
+
if (blobTags.length === 0)
|
|
64
|
+
return !requestRequiresHashTag(request.type);
|
|
65
|
+
return blobTags.includes(sha256);
|
|
66
|
+
}
|
|
67
|
+
/** Finds a reusable auth event in a store and prunes expired events */
|
|
68
|
+
export async function getReusableAuthEvent(authEvents, request) {
|
|
69
|
+
for (const auth of authEvents) {
|
|
70
|
+
if (isAuthExpired(auth)) {
|
|
71
|
+
authEvents.delete(auth);
|
|
72
|
+
continue;
|
|
26
73
|
}
|
|
74
|
+
if (await doesAuthMatchRequest(auth, request))
|
|
75
|
+
return auth;
|
|
27
76
|
}
|
|
28
|
-
return
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
/** Stores a new auth event in the shared store */
|
|
80
|
+
export function storeAuthEvent(authEvents, auth) {
|
|
81
|
+
authEvents.add(auth);
|
|
82
|
+
return auth;
|
|
29
83
|
}
|
|
30
84
|
/** @deprecated Use `doseAuthMatchBlob` instead */
|
|
31
85
|
export const doseAuthMatchUpload = doseAuthMatchBlob;
|
|
32
86
|
async function normalizeToHash(blob) {
|
|
33
87
|
return typeof blob === "string" ? blob : getBlobSha256(blob);
|
|
34
88
|
}
|
|
89
|
+
function normalizeServers(servers) {
|
|
90
|
+
const values = Array.isArray(servers) ? servers : [servers];
|
|
91
|
+
return [...new Set(values.map((server) => normalizeServerTag(server)))];
|
|
92
|
+
}
|
|
93
|
+
function isDomainName(value) {
|
|
94
|
+
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);
|
|
95
|
+
}
|
|
35
96
|
/** Generic auth event builder */
|
|
36
97
|
export async function createAuthEvent(signer, type, options) {
|
|
37
98
|
const draft = {
|
|
@@ -61,11 +122,8 @@ export async function createAuthEvent(signer, type, options) {
|
|
|
61
122
|
}
|
|
62
123
|
// add server tags
|
|
63
124
|
if (options?.servers) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
draft.tags.push(["server", server]);
|
|
67
|
-
else
|
|
68
|
-
draft.tags.push(["server", options.servers]);
|
|
125
|
+
for (const server of normalizeServers(options.servers))
|
|
126
|
+
draft.tags.push(["server", server]);
|
|
69
127
|
}
|
|
70
128
|
return await signer(draft);
|
|
71
129
|
}
|
|
@@ -77,7 +135,7 @@ export async function createDownloadAuth(signer, serverOrHash, options) {
|
|
|
77
135
|
message: "Download Blob",
|
|
78
136
|
...options,
|
|
79
137
|
blobs: serverOrHash.filter((s) => (typeof s === "string" ? isSha256(s) : true)),
|
|
80
|
-
servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && URL.canParse(s)),
|
|
138
|
+
servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && (URL.canParse(s) || isDomainName(s))),
|
|
81
139
|
});
|
|
82
140
|
}
|
|
83
141
|
/** Creates an upload or media upload auth event */
|
package/lib/error.d.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
|
+
export type RejectionCode = "conflict" | "too_large" | "unsupported_type" | "unprocessable";
|
|
1
2
|
export default class HTTPError extends Error {
|
|
2
3
|
response: Response;
|
|
3
4
|
status: number;
|
|
4
5
|
body?: {
|
|
5
6
|
message: string;
|
|
6
7
|
};
|
|
8
|
+
code?: RejectionCode;
|
|
7
9
|
constructor(response: Response, body: {
|
|
8
10
|
message: string;
|
|
9
11
|
} | string);
|
|
12
|
+
static isRejection(error: unknown): error is HTTPError & {
|
|
13
|
+
code: RejectionCode;
|
|
14
|
+
};
|
|
10
15
|
static handleErrorResponse(res: Response): Promise<void>;
|
|
11
16
|
}
|
package/lib/error.js
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
1
|
+
const REJECTION_CODES = {
|
|
2
|
+
409: "conflict",
|
|
3
|
+
413: "too_large",
|
|
4
|
+
415: "unsupported_type",
|
|
5
|
+
422: "unprocessable",
|
|
6
|
+
};
|
|
1
7
|
export default class HTTPError extends Error {
|
|
2
8
|
response;
|
|
3
9
|
status;
|
|
4
10
|
body;
|
|
11
|
+
code;
|
|
5
12
|
constructor(response, body) {
|
|
6
13
|
super(typeof body === "string" ? body : body.message);
|
|
7
14
|
this.response = response;
|
|
8
15
|
this.status = response.status;
|
|
16
|
+
this.code = REJECTION_CODES[response.status];
|
|
9
17
|
if (typeof body == "object")
|
|
10
18
|
this.body = body;
|
|
11
19
|
}
|
|
20
|
+
static isRejection(error) {
|
|
21
|
+
return error instanceof HTTPError && error.code !== undefined;
|
|
22
|
+
}
|
|
12
23
|
static async handleErrorResponse(res) {
|
|
13
24
|
if (!res.ok) {
|
|
14
25
|
try {
|
package/lib/helpers/blob.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UploadType } from "../
|
|
1
|
+
import { UploadType } from "../types.js";
|
|
2
2
|
/** Checks if a string is a 64 length hex string */
|
|
3
3
|
export declare function isSha256(str: string): RegExpMatchArray | null;
|
|
4
4
|
/** A symbol use to store the sha256 hash of a blob on a Blob instance */
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export type BlossomURI = {
|
|
2
|
+
/** SHA-256 hash of the blob */
|
|
3
|
+
sha256: string;
|
|
4
|
+
/** File extension (e.g. "png", "pdf") */
|
|
5
|
+
ext: string;
|
|
6
|
+
/** Server hints from xs params */
|
|
7
|
+
servers: string[];
|
|
8
|
+
/** Author pubkey hints from as params */
|
|
9
|
+
authors: string[];
|
|
10
|
+
/** Expected blob size in bytes from sz param */
|
|
11
|
+
size?: number;
|
|
12
|
+
};
|
|
13
|
+
/** Parses a blossom: URI string into its components */
|
|
14
|
+
export declare function parseBlossomURI(uri: string): BlossomURI;
|
|
15
|
+
/** Builds a blossom: URI string from components */
|
|
16
|
+
export declare function buildBlossomURI(options: BlossomURI): string;
|
|
17
|
+
/** Converts a BlossomURI to a native URL object */
|
|
18
|
+
export declare function blossomURIToURL(uri: string | BlossomURI): URL;
|
|
19
|
+
/** Parses a blossom: URL object into its components */
|
|
20
|
+
export declare function blossomURIFromURL(url: URL): BlossomURI;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { isSha256 } from "./blob.js";
|
|
2
|
+
/** Parses a blossom: URI string into its components */
|
|
3
|
+
export function parseBlossomURI(uri) {
|
|
4
|
+
if (!uri.startsWith("blossom:"))
|
|
5
|
+
throw new Error("Invalid blossom URI: missing blossom: scheme");
|
|
6
|
+
const body = uri.slice("blossom:".length);
|
|
7
|
+
// split hash.ext from query params
|
|
8
|
+
const queryIndex = body.indexOf("?");
|
|
9
|
+
const path = queryIndex === -1 ? body : body.slice(0, queryIndex);
|
|
10
|
+
const query = queryIndex === -1 ? "" : body.slice(queryIndex + 1);
|
|
11
|
+
// extract sha256 and extension
|
|
12
|
+
const dotIndex = path.indexOf(".");
|
|
13
|
+
if (dotIndex === -1)
|
|
14
|
+
throw new Error("Invalid blossom URI: missing file extension");
|
|
15
|
+
const sha256 = path.slice(0, dotIndex);
|
|
16
|
+
const ext = path.slice(dotIndex + 1);
|
|
17
|
+
if (!isSha256(sha256))
|
|
18
|
+
throw new Error("Invalid blossom URI: invalid sha256 hash");
|
|
19
|
+
if (!ext)
|
|
20
|
+
throw new Error("Invalid blossom URI: empty file extension");
|
|
21
|
+
// parse query params
|
|
22
|
+
const params = new URLSearchParams(query);
|
|
23
|
+
const servers = params.getAll("xs");
|
|
24
|
+
const authors = params.getAll("as");
|
|
25
|
+
const szValue = params.get("sz");
|
|
26
|
+
let size;
|
|
27
|
+
if (szValue !== null) {
|
|
28
|
+
size = Number(szValue);
|
|
29
|
+
if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
|
|
30
|
+
throw new Error("Invalid blossom URI: sz must be a positive integer");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return { sha256, ext, servers, authors, size };
|
|
34
|
+
}
|
|
35
|
+
/** Builds a blossom: URI string from components */
|
|
36
|
+
export function buildBlossomURI(options) {
|
|
37
|
+
const params = new URLSearchParams();
|
|
38
|
+
for (const server of options.servers)
|
|
39
|
+
params.append("xs", server);
|
|
40
|
+
for (const author of options.authors)
|
|
41
|
+
params.append("as", author);
|
|
42
|
+
if (options.size !== undefined)
|
|
43
|
+
params.append("sz", String(options.size));
|
|
44
|
+
const query = params.toString();
|
|
45
|
+
return `blossom:${options.sha256}.${options.ext}${query ? "?" + query : ""}`;
|
|
46
|
+
}
|
|
47
|
+
/** Converts a BlossomURI to a native URL object */
|
|
48
|
+
export function blossomURIToURL(uri) {
|
|
49
|
+
const str = typeof uri === "string" ? uri : buildBlossomURI(uri);
|
|
50
|
+
return new URL(str);
|
|
51
|
+
}
|
|
52
|
+
/** Parses a blossom: URL object into its components */
|
|
53
|
+
export function blossomURIFromURL(url) {
|
|
54
|
+
if (url.protocol !== "blossom:")
|
|
55
|
+
throw new Error("Invalid blossom URL: expected blossom: protocol");
|
|
56
|
+
const path = url.pathname;
|
|
57
|
+
const dotIndex = path.indexOf(".");
|
|
58
|
+
if (dotIndex === -1)
|
|
59
|
+
throw new Error("Invalid blossom URL: missing file extension");
|
|
60
|
+
const sha256 = path.slice(0, dotIndex);
|
|
61
|
+
const ext = path.slice(dotIndex + 1);
|
|
62
|
+
if (!isSha256(sha256))
|
|
63
|
+
throw new Error("Invalid blossom URL: invalid sha256 hash");
|
|
64
|
+
if (!ext)
|
|
65
|
+
throw new Error("Invalid blossom URL: empty file extension");
|
|
66
|
+
const servers = url.searchParams.getAll("xs");
|
|
67
|
+
const authors = url.searchParams.getAll("as");
|
|
68
|
+
const szValue = url.searchParams.get("sz");
|
|
69
|
+
let size;
|
|
70
|
+
if (szValue !== null) {
|
|
71
|
+
size = Number(szValue);
|
|
72
|
+
if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
|
|
73
|
+
throw new Error("Invalid blossom URL: sz must be a positive integer");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return { sha256, ext, servers, authors, size };
|
|
77
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { PaymentRequest } from "../types.js";
|
|
2
|
+
/** Extracts a cashu-ts PaymentRequest from Headers */
|
|
3
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
|
|
4
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
|
|
5
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { decodePaymentRequest } from "@cashu/cashu-ts";
|
|
2
|
+
export function getPaymentRequestFromHeaders(headers, quite = false) {
|
|
3
|
+
const header = headers.get("X-Cashu");
|
|
4
|
+
if (!header) {
|
|
5
|
+
if (!quite)
|
|
6
|
+
throw new Error("Missing cashu header");
|
|
7
|
+
else
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
const request = decodePaymentRequest(header);
|
|
11
|
+
// Clear the transport, since NUT-23 is only in-band payments
|
|
12
|
+
request.transport = [];
|
|
13
|
+
return request;
|
|
14
|
+
}
|
package/lib/helpers/index.d.ts
CHANGED
package/lib/helpers/index.js
CHANGED
package/lib/helpers/url.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Normalizes a server reference to a lowercase hostname */
|
|
2
|
+
export declare function getServerHostname(server: string | URL): string;
|
|
1
3
|
/** Check if two servers are the same */
|
|
2
4
|
export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
|
|
3
5
|
/** returns the last sha256 in a URL */
|
package/lib/helpers/url.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
/** Normalizes a server reference to a lowercase hostname */
|
|
2
|
+
export function getServerHostname(server) {
|
|
3
|
+
if (server instanceof URL)
|
|
4
|
+
return server.hostname.toLowerCase();
|
|
5
|
+
if (URL.canParse(server))
|
|
6
|
+
return new URL(server).hostname.toLowerCase();
|
|
7
|
+
return server.toLowerCase();
|
|
8
|
+
}
|
|
1
9
|
/** Check if two servers are the same */
|
|
2
10
|
export function areServersEqual(a, b) {
|
|
3
|
-
|
|
4
|
-
const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
|
|
5
|
-
return hostnameA === hostnameB;
|
|
11
|
+
return getServerHostname(a) === getServerHostname(b);
|
|
6
12
|
}
|
|
7
13
|
/** returns the last sha256 in a URL */
|
|
8
14
|
export function getHashFromURL(url) {
|
package/lib/helpers.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type UploadType } from "./client.js";
|
|
2
|
+
import { PaymentRequest } from "./types.js";
|
|
3
|
+
export declare function isSha256(str: string): RegExpMatchArray | null;
|
|
4
|
+
/** returns the last sha256 in a URL */
|
|
5
|
+
export declare function getHashFromURL(url: string | URL): string | null;
|
|
6
|
+
export declare const BlobHashSymbol: unique symbol;
|
|
7
|
+
/** gets or calculates the sha2456 of a Blob */
|
|
8
|
+
export declare function getBlobSha256(blob: UploadType): string | Promise<string>;
|
|
9
|
+
/** Calculates the sha2456 of a Blob */
|
|
10
|
+
export declare function computeBlobSha256(blob: UploadType): Promise<string>;
|
|
11
|
+
/** Returns the size of the blob in bytes */
|
|
12
|
+
export declare function getBlobSize(blob: UploadType): number;
|
|
13
|
+
/** Returns the mime type of the blob */
|
|
14
|
+
export declare function getBlobType(blob: UploadType): string | undefined;
|
|
15
|
+
/** Check if two servers are the same */
|
|
16
|
+
export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
|
|
17
|
+
/** Extracts a cashu-ts PaymentRequest from Headers */
|
|
18
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
|
|
19
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
|
|
20
|
+
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
|
package/lib/helpers.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { bytesToHex } from "@noble/hashes/utils";
|
|
2
|
+
export function isSha256(str) {
|
|
3
|
+
return str.match(/^[0-9a-f]{64}$/);
|
|
4
|
+
}
|
|
5
|
+
/** returns the last sha256 in a URL */
|
|
6
|
+
export function getHashFromURL(url) {
|
|
7
|
+
if (typeof url === "string")
|
|
8
|
+
url = new URL(url);
|
|
9
|
+
const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi));
|
|
10
|
+
if (hashes.length > 0)
|
|
11
|
+
return hashes[hashes.length - 1][0];
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
export const BlobHashSymbol = Symbol.for("sha256");
|
|
15
|
+
/** gets or calculates the sha2456 of a Blob */
|
|
16
|
+
export function getBlobSha256(blob) {
|
|
17
|
+
if (Reflect.has(blob, BlobHashSymbol))
|
|
18
|
+
return Reflect.get(blob, BlobHashSymbol);
|
|
19
|
+
return computeBlobSha256(blob).then((hash) => {
|
|
20
|
+
Reflect.set(blob, BlobHashSymbol, hash);
|
|
21
|
+
return hash;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** Calculates the sha2456 of a Blob */
|
|
25
|
+
export async function computeBlobSha256(blob) {
|
|
26
|
+
let buffer;
|
|
27
|
+
if (blob instanceof File || blob instanceof Blob) {
|
|
28
|
+
buffer = await blob.arrayBuffer();
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
// nodejs Buffer
|
|
32
|
+
buffer = blob;
|
|
33
|
+
}
|
|
34
|
+
let hash;
|
|
35
|
+
if (crypto.subtle) {
|
|
36
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
|
|
37
|
+
hash = new Uint8Array(hashBuffer);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
const { sha256 } = await import("@noble/hashes/sha256");
|
|
41
|
+
hash = sha256.create().update(new Uint8Array(buffer)).digest();
|
|
42
|
+
}
|
|
43
|
+
return bytesToHex(hash);
|
|
44
|
+
}
|
|
45
|
+
/** Returns the size of the blob in bytes */
|
|
46
|
+
export function getBlobSize(blob) {
|
|
47
|
+
if (blob instanceof File || blob instanceof Blob) {
|
|
48
|
+
return blob.size;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
// nodejs Buffer
|
|
52
|
+
return blob.length;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Returns the mime type of the blob */
|
|
56
|
+
export function getBlobType(blob) {
|
|
57
|
+
if (blob instanceof File || blob instanceof Blob) {
|
|
58
|
+
return blob.type;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
/** Check if two servers are the same */
|
|
63
|
+
export function areServersEqual(a, b) {
|
|
64
|
+
const hostnameA = a instanceof URL ? a.hostname : new URL(a).hostname;
|
|
65
|
+
const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
|
|
66
|
+
return hostnameA === hostnameB;
|
|
67
|
+
}
|
|
68
|
+
export function getPaymentRequestFromHeaders(headers, quite = false) {
|
|
69
|
+
const header = headers.get("X-Cashu");
|
|
70
|
+
if (!header && !quite)
|
|
71
|
+
throw new Error("Missing cashu header");
|
|
72
|
+
return header ? JSON.parse(atob(header)) : undefined;
|
|
73
|
+
}
|
package/lib/hls.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { FragmentLoaderConstructor, FragmentLoaderContext as HlsFragmentLoaderContext, HlsConfig as HlsLoaderConfig, Loader as HlsLoader, LoaderCallbacks as HlsLoaderCallbacks, LoaderConfiguration as HlsLoaderConfiguration, LoaderContext as HlsLoaderContext, LoaderResponse as HlsLoaderResponse, LoaderStats as HlsLoaderStats, PlaylistLoaderConstructor, PlaylistLoaderContext as HlsPlaylistLoaderContext } from "hls.js";
|
|
2
|
+
export type { HlsFragmentLoaderContext, HlsLoader, HlsLoaderCallbacks, HlsLoaderConfig, HlsLoaderConfiguration, HlsLoaderContext, HlsLoaderResponse, HlsLoaderStats, HlsPlaylistLoaderContext, };
|
|
3
|
+
export type BlossomHlsFallbackInfo = {
|
|
4
|
+
kind: "playlist" | "fragment";
|
|
5
|
+
from: string;
|
|
6
|
+
to: string;
|
|
7
|
+
url: string;
|
|
8
|
+
attempt: number;
|
|
9
|
+
};
|
|
10
|
+
export type BlossomHlsLoaderOptions = {
|
|
11
|
+
fallbackServers?: (string | URL)[];
|
|
12
|
+
stickyFailover?: boolean;
|
|
13
|
+
penalizeMs?: number;
|
|
14
|
+
retryStatuses?: number[];
|
|
15
|
+
onFallback?: (info: BlossomHlsFallbackInfo) => void;
|
|
16
|
+
};
|
|
17
|
+
export declare function createBlossomHlsLoaders(options?: BlossomHlsLoaderOptions): {
|
|
18
|
+
pLoader: PlaylistLoaderConstructor;
|
|
19
|
+
fLoader: FragmentLoaderConstructor;
|
|
20
|
+
};
|
package/lib/hls.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
const DEFAULT_PENALIZE_MS = 30_000;
|
|
2
|
+
function createEmptyStats() {
|
|
3
|
+
return {
|
|
4
|
+
aborted: false,
|
|
5
|
+
loaded: 0,
|
|
6
|
+
retry: 0,
|
|
7
|
+
total: 0,
|
|
8
|
+
chunkCount: 0,
|
|
9
|
+
bwEstimate: 0,
|
|
10
|
+
loading: { start: 0, first: 0, end: 0 },
|
|
11
|
+
parsing: { start: 0, end: 0 },
|
|
12
|
+
buffering: { start: 0, first: 0, end: 0 },
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function normalizeServer(server) {
|
|
16
|
+
if (server instanceof URL)
|
|
17
|
+
return server.origin;
|
|
18
|
+
if (!server.includes("://"))
|
|
19
|
+
return `https://${server}`;
|
|
20
|
+
try {
|
|
21
|
+
return new URL(server).origin;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return `https://${server}`;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function replaceUrlOrigin(url, origin) {
|
|
28
|
+
const next = new URL(url);
|
|
29
|
+
const base = new URL(origin);
|
|
30
|
+
next.protocol = base.protocol;
|
|
31
|
+
next.host = base.host;
|
|
32
|
+
return next.toString();
|
|
33
|
+
}
|
|
34
|
+
function shouldRetry(code, isTimeout, retryStatuses) {
|
|
35
|
+
return isTimeout || code === 0 || code >= 500 || retryStatuses.has(code);
|
|
36
|
+
}
|
|
37
|
+
export function createBlossomHlsLoaders(options = {}) {
|
|
38
|
+
const fallbackServers = options.fallbackServers?.map(normalizeServer) ?? [];
|
|
39
|
+
const stickyFailover = options.stickyFailover ?? false;
|
|
40
|
+
const penalizeMs = options.penalizeMs ?? DEFAULT_PENALIZE_MS;
|
|
41
|
+
const retryStatuses = new Set(options.retryStatuses ?? [404]);
|
|
42
|
+
const penalties = new Map();
|
|
43
|
+
function clearExpiredPenalties() {
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
for (const [origin, expiry] of penalties) {
|
|
46
|
+
if (expiry <= now)
|
|
47
|
+
penalties.delete(origin);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function penalize(origin) {
|
|
51
|
+
if (!stickyFailover)
|
|
52
|
+
return;
|
|
53
|
+
penalties.set(origin, Date.now() + penalizeMs);
|
|
54
|
+
}
|
|
55
|
+
function reward(origin) {
|
|
56
|
+
if (!stickyFailover)
|
|
57
|
+
return;
|
|
58
|
+
penalties.delete(origin);
|
|
59
|
+
}
|
|
60
|
+
function getCandidateOrigins(url) {
|
|
61
|
+
clearExpiredPenalties();
|
|
62
|
+
const originalOrigin = new URL(url).origin;
|
|
63
|
+
const seen = new Set();
|
|
64
|
+
const ordered = [originalOrigin, ...fallbackServers].filter((origin) => {
|
|
65
|
+
if (seen.has(origin))
|
|
66
|
+
return false;
|
|
67
|
+
seen.add(origin);
|
|
68
|
+
return true;
|
|
69
|
+
});
|
|
70
|
+
if (!stickyFailover)
|
|
71
|
+
return ordered;
|
|
72
|
+
const healthy = ordered.filter((origin) => !penalties.has(origin));
|
|
73
|
+
const penalizedOrigins = ordered.filter((origin) => penalties.has(origin));
|
|
74
|
+
return healthy.length > 0 ? [...healthy, ...penalizedOrigins] : ordered;
|
|
75
|
+
}
|
|
76
|
+
function createLoaderClass(kind) {
|
|
77
|
+
return class BlossomHlsLoader {
|
|
78
|
+
config;
|
|
79
|
+
context = null;
|
|
80
|
+
stats = createEmptyStats();
|
|
81
|
+
activeLoader = null;
|
|
82
|
+
destroyed = false;
|
|
83
|
+
aborted = false;
|
|
84
|
+
constructor(config) {
|
|
85
|
+
this.config = config;
|
|
86
|
+
}
|
|
87
|
+
destroy() {
|
|
88
|
+
this.destroyed = true;
|
|
89
|
+
this.activeLoader?.destroy();
|
|
90
|
+
this.activeLoader = null;
|
|
91
|
+
this.context = null;
|
|
92
|
+
}
|
|
93
|
+
abort() {
|
|
94
|
+
this.aborted = true;
|
|
95
|
+
this.activeLoader?.abort();
|
|
96
|
+
}
|
|
97
|
+
getCacheAge() {
|
|
98
|
+
return this.activeLoader?.getCacheAge?.() ?? null;
|
|
99
|
+
}
|
|
100
|
+
getResponseHeader(name) {
|
|
101
|
+
return this.activeLoader?.getResponseHeader?.(name) ?? null;
|
|
102
|
+
}
|
|
103
|
+
load(context, loaderConfig, callbacks) {
|
|
104
|
+
this.destroyed = false;
|
|
105
|
+
this.aborted = false;
|
|
106
|
+
const origins = getCandidateOrigins(context.url);
|
|
107
|
+
const BaseLoader = this.config.loader;
|
|
108
|
+
let attempt = 0;
|
|
109
|
+
const startAttempt = () => {
|
|
110
|
+
if (this.destroyed || this.aborted)
|
|
111
|
+
return;
|
|
112
|
+
const origin = origins[attempt];
|
|
113
|
+
const attemptUrl = replaceUrlOrigin(context.url, origin);
|
|
114
|
+
const attemptContext = { ...context, url: attemptUrl };
|
|
115
|
+
const loader = new BaseLoader(this.config);
|
|
116
|
+
this.activeLoader = loader;
|
|
117
|
+
this.context = attemptContext;
|
|
118
|
+
this.stats = loader.stats;
|
|
119
|
+
loader.load(attemptContext, loaderConfig, {
|
|
120
|
+
onSuccess: (response, stats, successContext, networkDetails) => {
|
|
121
|
+
this.stats = stats;
|
|
122
|
+
this.context = successContext;
|
|
123
|
+
reward(new URL(successContext.url).origin);
|
|
124
|
+
callbacks.onSuccess(response, stats, successContext, networkDetails);
|
|
125
|
+
},
|
|
126
|
+
onProgress: callbacks.onProgress,
|
|
127
|
+
onAbort: callbacks.onAbort,
|
|
128
|
+
onError: (error, errorContext, networkDetails, stats) => {
|
|
129
|
+
this.stats = stats;
|
|
130
|
+
this.context = errorContext;
|
|
131
|
+
if (attempt < origins.length - 1 && shouldRetry(error.code, false, retryStatuses)) {
|
|
132
|
+
const failedOrigin = new URL(errorContext.url).origin;
|
|
133
|
+
const nextOrigin = origins[attempt + 1];
|
|
134
|
+
penalize(failedOrigin);
|
|
135
|
+
this.activeLoader?.destroy();
|
|
136
|
+
this.activeLoader = null;
|
|
137
|
+
options.onFallback?.({
|
|
138
|
+
kind,
|
|
139
|
+
from: failedOrigin,
|
|
140
|
+
to: nextOrigin,
|
|
141
|
+
url: errorContext.url,
|
|
142
|
+
attempt: attempt + 1,
|
|
143
|
+
});
|
|
144
|
+
attempt += 1;
|
|
145
|
+
startAttempt();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
callbacks.onError(error, errorContext, networkDetails, stats);
|
|
149
|
+
},
|
|
150
|
+
onTimeout: (stats, timeoutContext, networkDetails) => {
|
|
151
|
+
this.stats = stats;
|
|
152
|
+
this.context = timeoutContext;
|
|
153
|
+
if (attempt < origins.length - 1 && shouldRetry(0, true, retryStatuses)) {
|
|
154
|
+
const failedOrigin = new URL(timeoutContext.url).origin;
|
|
155
|
+
const nextOrigin = origins[attempt + 1];
|
|
156
|
+
penalize(failedOrigin);
|
|
157
|
+
this.activeLoader?.destroy();
|
|
158
|
+
this.activeLoader = null;
|
|
159
|
+
options.onFallback?.({
|
|
160
|
+
kind,
|
|
161
|
+
from: failedOrigin,
|
|
162
|
+
to: nextOrigin,
|
|
163
|
+
url: timeoutContext.url,
|
|
164
|
+
attempt: attempt + 1,
|
|
165
|
+
});
|
|
166
|
+
attempt += 1;
|
|
167
|
+
startAttempt();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
callbacks.onTimeout(stats, timeoutContext, networkDetails);
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
startAttempt();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
pLoader: createLoaderClass("playlist"),
|
|
180
|
+
fLoader: createLoaderClass("fragment"),
|
|
181
|
+
};
|
|
182
|
+
}
|
package/lib/index.d.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";
|
package/lib/index.js
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";
|