58 lines
2.3 KiB
TypeScript
58 lines
2.3 KiB
TypeScript
export const FIFTH_DOMAIN_DISCOVERY_URL = 'https://guanghulab.com/.well-known/guanghu.json'
|
|
|
|
export interface FifthDomainDiscovery {
|
|
access: 'public-read-only'
|
|
canonicalRepository: string
|
|
name: string
|
|
nodeMap: string
|
|
repositoryMap: string
|
|
resolveApi: string
|
|
schema: 'guanghu.ai-discovery/v1'
|
|
searchApi: string
|
|
}
|
|
|
|
type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>
|
|
|
|
function requiredString(document: Record<string, unknown>, key: string): string {
|
|
const value = document[key]
|
|
if (typeof value !== 'string' || !value.trim()) throw new Error(`Fifth Domain discovery is missing ${key}.`)
|
|
return value
|
|
}
|
|
|
|
function requiredHttpsUrl(document: Record<string, unknown>, key: string): string {
|
|
const value = requiredString(document, key)
|
|
if (!value.startsWith('https://guanghulab.com/')) throw new Error(`Fifth Domain discovery ${key} is not a trusted HTTPS route.`)
|
|
return value
|
|
}
|
|
|
|
export function parseFifthDomainDiscovery(value: unknown): FifthDomainDiscovery {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Fifth Domain discovery is not an object.')
|
|
const document = value as Record<string, unknown>
|
|
if (document.schema !== 'guanghu.ai-discovery/v1') throw new Error('Fifth Domain discovery schema is unsupported.')
|
|
if (document.access !== 'public-read-only') throw new Error('Fifth Domain connection must remain public-read-only.')
|
|
|
|
return {
|
|
access: 'public-read-only',
|
|
canonicalRepository: requiredHttpsUrl(document, 'canonical_repository'),
|
|
name: requiredString(document, 'name'),
|
|
nodeMap: requiredHttpsUrl(document, 'server_node_map'),
|
|
repositoryMap: requiredHttpsUrl(document, 'repository_map'),
|
|
resolveApi: requiredHttpsUrl(document, 'resolve_api'),
|
|
schema: 'guanghu.ai-discovery/v1',
|
|
searchApi: requiredHttpsUrl(document, 'search_api'),
|
|
}
|
|
}
|
|
|
|
export async function fetchFifthDomainDiscovery(
|
|
fetcher: Fetcher = fetch,
|
|
signal?: AbortSignal,
|
|
): Promise<FifthDomainDiscovery> {
|
|
const response = await fetcher(FIFTH_DOMAIN_DISCOVERY_URL, {
|
|
cache: 'no-store',
|
|
credentials: 'omit',
|
|
signal,
|
|
})
|
|
if (!response.ok) throw new Error('Fifth Domain public route did not respond successfully.')
|
|
return parseFifthDomainDiscovery(await response.json())
|
|
}
|