@bsv/sdk
Version:
BSV Blockchain Software Development Kit
73 lines • 2.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidURL = exports.getHashFromURL = exports.getURLForFile = exports.getURLForHash = exports.normalizeURL = void 0;
const Hash_js_1 = require("../primitives/Hash.js");
const utils_js_1 = require("../primitives/utils.js");
/**
* Takes a UHRP URL and removes any prefixes.
* @param {string} URL - The UHRP URL.
* @returns {string} - Normalized URL.
*/
const normalizeURL = (URL) => {
if (URL.toLowerCase().startsWith('uhrp:'))
URL = URL.slice(5);
if (URL.startsWith('//'))
URL = URL.slice(2);
return URL;
};
exports.normalizeURL = normalizeURL;
/**
* Generates a UHRP URL from a given SHA-256 hash.
* @param {number[]} hash - 32-byte SHA-256 hash.
* @returns {string} - Base58Check encoded URL.
*/
const getURLForHash = (hash) => {
if (hash.length !== 32) {
throw new Error('Hash length must be 32 bytes (sha256)');
}
return (0, utils_js_1.toBase58Check)(hash, (0, utils_js_1.toArray)('ce00', 'hex'));
};
exports.getURLForHash = getURLForHash;
/**
* Generates a UHRP URL for a given file.
* @param {number[] | string} file - File content as number array or string.
* @returns {string} - Base58Check encoded URL.
*/
const getURLForFile = (file) => {
const hash = (0, Hash_js_1.sha256)(file);
return (0, exports.getURLForHash)(hash);
};
exports.getURLForFile = getURLForFile;
/**
* Extracts the hash from a UHRP URL.
* @param {string} URL - UHRP URL.
* @returns {number[]} - Extracted SHA-256 hash.
*/
const getHashFromURL = (URL) => {
URL = (0, exports.normalizeURL)(URL);
const { data, prefix } = (0, utils_js_1.fromBase58Check)(URL, undefined, 2);
if (data.length !== 32) {
throw new Error('Invalid length!');
}
if ((0, utils_js_1.toHex)(prefix) !== 'ce00') {
throw new Error('Bad prefix');
}
return data;
};
exports.getHashFromURL = getHashFromURL;
/**
* Checks if a URL is a valid UHRP URL.
* @param {string} URL - The URL to validate.
* @returns {boolean} - True if valid, false otherwise.
*/
const isValidURL = (URL) => {
try {
(0, exports.getHashFromURL)(URL);
return true;
}
catch (e) {
return false;
}
};
exports.isValidURL = isValidURL;
//# sourceMappingURL=StorageUtils.js.map