Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322import { Client, simpleFetchHandler, type FetchHandler } from '@atcute/client';import type { DidDocumentResolver } from '@atcute/identity-resolver';import type { Did, Handle } from '@atcute/lexicons';import { isDid, isHandle } from '@atcute/lexicons/syntax';import * as v from '@atcute/lexicons/validations';import { SdkError } from './errors.ts';import { parseActorIdentifier, type ActorIdentifier } from './identifier.ts';import { withUserAgent } from './user-agent.ts';import { preferGateway, unavailable } from './gateway.ts';
export type DidDocument = Awaited<ReturnType<DidDocumentResolver['resolve']>>;
export interface Actor { did: Did; /** Absent when the DID document's handle does not resolve back to the DID. */ handle?: Handle; /** PDS origin, such as `https://pds.example.com/`. */ pds: string;}
/** Replaces network identity resolution. Tests map fake DIDs to a fake PDS through this. */export interface IdentityResolver { resolveActor(identifier: Did | Handle): Promise<Actor>; resolveDocument(did: Did): Promise<DidDocument>;}
export interface Config { /** * nibling's read gateway (D22), such as `https://api.nibling.dev`, or null to read every service * directly. When set, every read goes there first and falls back to the direct path when it fails. */ gateway: string | null; /** The signed-in account. Reads of its repo skip the gateway's cache so its own saves show at once. */ viewer: Did | null; /** Slingshot base URL, or null to skip it and resolve through PLC and DNS directly. */ slingshot: string | null; /** Constellation base URL, or null to report no backlinks. */ constellation: string | null; /** Answers `com.atproto.identity.resolveHandle` on the fallback path. */ appview: string; plc: string; /** nibling's index (D22), or null when there is none. */ index: string | null; /** * The npm gateway's hostname for an account that has not chosen one (D23), such as * `api.nibling.dev`, or null for none: installs then go straight to the registry. */ npmGateway: string | null; /** * The SSH gateway's hostname (D25), such as `ssh.nibling.dev`, or null to keep tabs from attaching. * A tab connects to it at wss://<host>, or ws on loopback. */ sshGateway: string | null; /** * The realtime relay's origin (the API worker), such as `https://api.nibling.dev`, or null for * none: presence and live edits then reach only this browser's other tabs. */ relay: string | null; identity: IdentityResolver | null; /** Builds the fetch handler for an XRPC service's base URL. */ handlerFor: (service: string) => FetchHandler; /** How long one request to a PDS, identity service, or index may take, body included. */ timeoutMs: number;}
export const defaults: Readonly<Config> = { gateway: null, viewer: null, slingshot: 'https://slingshot.microcosm.blue', constellation: 'https://constellation.microcosm.blue', appview: 'https://public.api.bsky.app', plc: 'https://plc.directory', index: null, npmGateway: 'api.nibling.dev', sshGateway: 'ssh.nibling.dev', relay: null, identity: null, handlerFor: (service) => simpleFetchHandler({ service, fetch: timedFetch }), timeoutMs: 30_000,};
export const config: Config = { ...defaults };
/** * `fetch` that aborts after `config.timeoutMs`, so a server that never answers cannot hang a read, and * names us outside a browser. Identical GETs in flight at once share one request (`coalesce`). */export function timedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { const headers = withUserAgent(init?.headers ?? (input instanceof Request ? input.headers : undefined)); const send = (signal?: AbortSignal | null) => { const timeout = AbortSignal.timeout(config.timeoutMs); return fetch(input, { ...init, headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout }); }; const method = init?.method ?? (input instanceof Request ? input.method : 'GET'); if (method.toUpperCase() !== 'GET' || init?.body != null || input instanceof Request) return send(init?.signal); return coalesce(`${String(input)}\n${[...headers].map(([k, v]) => `${k}:${v}`).join('\n')}`, send, init?.signal ?? undefined);}
const inFlight = new Map<string, Promise<Response>>();
/** * One `send()` per `key` at a time; every caller gets its own clone of the response. A caller's own * signal rejects only its wait, so one caller giving up does not cancel the others. */function coalesce(key: string, send: () => Promise<Response>, signal: AbortSignal | undefined): Promise<Response> { let shared = inFlight.get(key); if (!shared) { shared = send(); inFlight.set(key, shared); const done = () => inFlight.delete(key); shared.then(done, done); } const mine = shared.then((res) => res.clone()); if (!signal) return mine; if (signal.aborted) return Promise.reject(signal.reason); return new Promise((resolve, reject) => { const abort = () => reject(signal.reason); signal.addEventListener('abort', abort, { once: true }); mine.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort)); });}
/** Changing any endpoint or resolver forgets every identity answered so far. */export function configure(options: Partial<Config>): void { Object.assign(config, options); actors.clear(); documents.clear();}
/** * How long a resolved handle, DID, or DID document is reused. A page resolves the same account from * several loaders at once; within this window they share one answer, and a request in flight is shared too. */export const IDENTITY_TTL_MS = 60_000;
interface Memo<T> { value: Promise<T>; /** Infinity while in flight. */ until: number;}
const actors = new Map<string, Memo<Actor>>();const documents = new Map<string, Memo<DidDocument>>();
/** `load()` once per `key` within the TTL. A success is also filed under `aliases`; a failure is forgotten. */function remember<T>(memo: Map<string, Memo<T>>, key: string, load: () => Promise<T>, aliases: (value: T) => string[] = () => []): Promise<T> { const hit = memo.get(key); if (hit && hit.until > Date.now()) return hit.value; const entry: Memo<T> = { value: load(), until: Infinity }; memo.set(key, entry); entry.value.then( (value) => { entry.until = Date.now() + IDENTITY_TTL_MS; for (const alias of aliases(value)) if (alias !== key) memo.set(alias, entry); }, () => { if (memo.get(key) === entry) memo.delete(key); }, ); return entry.value;}
/** * `did:web:<host>`, the DID a service named by its hostname answers to, as a knot's * `describeKnot` reports and as a service-auth token's `aud` names it. A port is percent-encoded. */export function serviceDid(host: string): Did<'web'> { const { host: authority } = new URL(/^https?:\/\//.test(host) ? host : `https://${host}`); return `did:web:${authority.replace(':', '%3A')}`;}
export function serviceClient(service: string): Client { return new Client({ handler: config.handlerFor(service) });}
/** Whether a read of `repo` must skip the gateway's cache: it is the signed-in account's own repo. */export function freshFor(repo: Did | undefined): boolean { return repo !== undefined && repo === config.viewer;}
/** A client for a read: the gateway when one is configured, else (or when it fails) `direct`. */export function readClient(direct: () => FetchHandler | Promise<FetchHandler>, repo?: Did): Client { const gateway = config.gateway ? config.handlerFor(config.gateway) : undefined; return new Client({ handler: preferGateway(gateway, direct, freshFor(repo)) });}
/** An unauthenticated client for reads of `did`'s repo. The direct path is `pds`, or the PDS `did` resolves to without the gateway. */export function repoClient(did: Did, pds?: string): Client { return readClient(async () => config.handlerFor(pds ?? (await resolve(did, false)).pds), did);}
/** A client for a microcosm service, through the gateway when one is configured. Undefined when there is neither. */export function microcosmClient(service: string | null, repo?: Did): Client | undefined { if (!config.gateway && !service) return undefined; return readClient(() => (service ? config.handlerFor(service) : unavailable), repo);}
/** Where a browser can load blob `cid` of `did`'s repo from, such as an `<img src>`. */export function blobUrl(actor: Pick<Actor, 'did' | 'pds'>, cid: string): string { const url = new URL('/xrpc/com.atproto.sync.getBlob', config.gateway ?? actor.pds); url.searchParams.set('did', actor.did); url.searchParams.set('cid', cid); return url.href;}
const miniDoc = v.query('blue.microcosm.identity.resolveMiniDoc', { params: v.object({ identifier: v.actorIdentifierString() }), output: { type: 'lex', schema: v.object({ did: v.didString(), handle: v.string(), pds: v.genericUriString(), }), },});
export async function resolveActor(identifier: string): Promise<Actor> { return resolve(parseIdentifier(identifier), true);}
/** The gateway's `resolveMiniDoc`, then Slingshot's, then PLC and DNS. A repo read falling back from a * failed gateway skips it here too. */function resolve(id: Did | Handle, useGateway: boolean): Promise<Actor> { // A handle and its DID share one entry, so resolving either first answers the other. return remember(actors, id, () => resolveUncached(id, useGateway), (actor) => (actor.handle ? [actor.did, actor.handle] : [actor.did]));}
async function resolveUncached(id: Did | Handle, useGateway: boolean): Promise<Actor> { if (config.identity) return config.identity.resolveActor(id); for (const service of [useGateway ? config.gateway : null, config.slingshot]) { if (!service) continue; const actor = await viaMiniDoc(service, id).catch(() => undefined); if (actor) return actor; } return viaLocal(id);}
const resolveDid = v.query('com.atproto.identity.resolveDid', { params: v.object({ did: v.didString() }), output: { type: 'lex', schema: v.object({ didDoc: v.unknown() }) },});
export function resolveDocument(did: Did): Promise<DidDocument> { return remember(documents, did, () => resolveDocumentUncached(did));}
async function resolveDocumentUncached(did: Did): Promise<DidDocument> { if (config.identity) return config.identity.resolveDocument(did); if (config.gateway) { const res = await serviceClient(config.gateway).call(resolveDid, { params: { did } }).catch(() => undefined); const doc = res?.ok ? (res.data.didDoc as DidDocument) : undefined; if (doc?.id === did) return doc; } try { return await (await didResolver()).resolve(did as Did<'plc' | 'web'>); } catch (cause) { throw new SdkError(`could not resolve ${did}`, 'ERR_NIB_IDENTITY', { cause }); }}
/** Reads a service endpoint, such as `#atproto_pds` or `#tangled_knot`, from a DID document. */export async function resolveService(did: Did, id: `#${string}`): Promise<string | undefined> { const doc = await resolveDocument(did); const entry = doc.service?.find((s) => s.id === id || s.id === `${did}${id}`); const endpoint = entry?.serviceEndpoint; if (typeof endpoint !== 'string') return undefined; const url = URL.parse(endpoint); return url && (url.protocol === 'https:' || url.protocol === 'http:') ? url.origin : undefined;}
/** An unauthenticated client for `did`'s repo (`repoClient`), kept for callers that await it. */export async function publicClient(did: Did): Promise<Client> { return repoClient(did);}
export { parseActorIdentifier, type ActorIdentifier } from './identifier.ts';
function parseIdentifier(identifier: string): Did | Handle { const id = parseActorIdentifier(identifier); if (!id) throw new SdkError(`${JSON.stringify(identifier)} is not a handle or DID`, 'ERR_NIB_IDENTITY'); return id;}
async function viaMiniDoc(service: string, identifier: Did | Handle): Promise<Actor | undefined> { const res = await serviceClient(service).call(miniDoc, { params: { identifier } }); if (!res.ok) return undefined; const { did, handle, pds } = res.data; if (isDid(identifier) ? did !== identifier : handle !== identifier) return undefined; return actor(did, handle, pds);}
async function viaLocal(identifier: Did | Handle): Promise<Actor> { try { const { LocalActorResolver, XrpcHandleResolver } = await import('@atcute/identity-resolver'); const resolver = new LocalActorResolver({ handleResolver: new XrpcHandleResolver({ serviceUrl: config.appview, fetch: timedFetch }), didDocumentResolver: await didResolver(), }); const { did, handle, pds } = await resolver.resolve(identifier); return actor(did, handle, pds); } catch (cause) { throw new SdkError(`could not resolve ${identifier}`, 'ERR_NIB_IDENTITY', { cause }); }}
/** Loaded on first use: the gateway and Slingshot answer almost every lookup, and the resolver and its schemas are most of the SDK's size. */async function didResolver(): Promise<DidDocumentResolver> { const { AtprotoWebDidDocumentResolver, CompositeDidDocumentResolver, PlcDidDocumentResolver } = await import('@atcute/identity-resolver'); return new CompositeDidDocumentResolver({ methods: { plc: new PlcDidDocumentResolver({ apiUrl: config.plc, fetch: timedFetch }), web: new AtprotoWebDidDocumentResolver({ fetch: timedFetch }), }, });}
function actor(did: Did, handle: string, pds: string): Actor { const origin = new URL(pds).href; return isHandle(handle) && handle !== 'handle.invalid' ? { did, handle, pds: origin } : { did, pds: origin };}