58 lines
1.5 KiB
JavaScript
58 lines
1.5 KiB
JavaScript
// nip05.ts
|
|
var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w.-]+)$/;
|
|
var _fetch;
|
|
try {
|
|
_fetch = fetch;
|
|
} catch {
|
|
}
|
|
function useFetchImplementation(fetchImplementation) {
|
|
_fetch = fetchImplementation;
|
|
}
|
|
async function searchDomain(domain, query = "") {
|
|
try {
|
|
let res = await (await _fetch(`https://${domain}/.well-known/nostr.json?name=${query}`)).json();
|
|
return res.names;
|
|
} catch (_) {
|
|
return {};
|
|
}
|
|
}
|
|
async function queryProfile(fullname) {
|
|
const match = fullname.match(NIP05_REGEX);
|
|
if (!match)
|
|
return null;
|
|
const [_, name = "_", domain] = match;
|
|
try {
|
|
const res = await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`);
|
|
const { names, relays } = parseNIP05Result(await res.json());
|
|
const pubkey = names[name];
|
|
return pubkey ? { pubkey, relays: relays?.[pubkey] } : null;
|
|
} catch (_e) {
|
|
return null;
|
|
}
|
|
}
|
|
function parseNIP05Result(json) {
|
|
const result = {
|
|
names: {}
|
|
};
|
|
for (const [name, pubkey] of Object.entries(json.names)) {
|
|
if (typeof name === "string" && typeof pubkey === "string") {
|
|
result.names[name] = pubkey;
|
|
}
|
|
}
|
|
if (json.relays) {
|
|
result.relays = {};
|
|
for (const [pubkey, relays] of Object.entries(json.relays)) {
|
|
if (typeof pubkey === "string" && Array.isArray(relays)) {
|
|
result.relays[pubkey] = relays.filter((relay) => typeof relay === "string");
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
export {
|
|
NIP05_REGEX,
|
|
queryProfile,
|
|
searchDomain,
|
|
useFetchImplementation
|
|
};
|