diff --git a/jsr.json b/jsr.json index c25079c..a75650a 100644 --- a/jsr.json +++ b/jsr.json @@ -1,6 +1,6 @@ { "name": "@nostr/tools", - "version": "2.24.2", + "version": "2.24.3", "exports": { ".": "./index.ts", "./core": "./core.ts", diff --git a/nipad.ts b/nipad.ts new file mode 100644 index 0000000..fdacf9c --- /dev/null +++ b/nipad.ts @@ -0,0 +1,47 @@ +import { Filter } from './filter.ts' + +export type WebAddressPointer = { + filter: Filter + relays?: string[] +} + +/** + * NIP-AD regex. Matches a web URL with a path that may have a Nostr counterpart. + * + * - 0: full match + * - 1: domain + * - 2: path + */ +export const AD_REGEX = /^(?:https?:\/\/)?((?:[\w-]+\.)+[\w-]+)(\/[^\s]*)?$/ +export const isWebAddress = (value?: string | null): value is string => AD_REGEX.test(value || '') + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let _fetch: any + +try { + _fetch = fetch +} catch (_) { + null +} + +export function useFetchImplementation(fetchImplementation: unknown) { + _fetch = fetchImplementation +} + +export async function queryWebAddress(url: string): Promise { + const match = url.match(AD_REGEX) + if (!match) return null + + const [, domain, path = '/'] = match + + try { + const res = await _fetch(`https://${domain}/.well-known/nostr.json?path=${path}`) + if (res.status !== 200) { + throw Error('Wrong response code') + } + const json = await res.json() + return json[path] || null + } catch (_) { + return null + } +} diff --git a/package.json b/package.json index cf5add1..3afe344 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "type": "module", "name": "nostr-tools", - "version": "2.24.2", + "version": "2.24.3", "description": "Tools for making a Nostr client.", "repository": { "type": "git", @@ -258,6 +258,12 @@ "require": "./lib/cjs/nip98.js", "types": "./lib/types/nip98.d.ts" }, + "./nipad": { + "source": "./nipad.ts", + "import": "./lib/esm/nipad.js", + "require": "./lib/cjs/nipad.js", + "types": "./lib/types/nipad.d.ts" + }, "./nip99": { "source": "./nip99.ts", "import": "./lib/esm/nip99.js",