nomadro/packages/sdk/src/client.ts
Eric ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00

167 lines
5.2 KiB
TypeScript

import { buildOpenApiDocument } from "./openapi";
import {
NOMADRO_TOOLS,
PUBLIC_API_PREFIX,
PUBLIC_API_VERSION,
type NomadroToolName,
} from "./tools";
export type NomadroClientOptions = {
/** Origin of portal, e.g. https://nomadro.com — no trailing slash */
baseUrl?: string;
/** Optional public API key */
apiKey?: string;
/** Social guest id for write endpoints */
guestId?: string;
fetch?: typeof fetch;
};
export type JsonMap = Record<string, unknown>;
function joinUrl(base: string, path: string): string {
return `${base.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
}
function fillPath(template: string, params: JsonMap): string {
return template.replace(/\{(\w+)\}/g, (_, key: string) => {
const v = params[key];
if (v == null) throw new Error(`missing path param ${key}`);
return encodeURIComponent(String(v));
});
}
export function createNomadroClient(opts: NomadroClientOptions = {}) {
const envOrigin =
(typeof process !== "undefined" &&
(process.env?.NOMADRO_PUBLIC_ORIGIN ||
process.env?.NEXT_PUBLIC_SITE_URL)) ||
"";
const baseUrl = (
opts.baseUrl ||
envOrigin ||
"https://nomadro.com"
).replace(/\/$/, "");
const doFetch = opts.fetch || fetch;
async function request(
method: "GET" | "POST",
path: string,
query?: JsonMap,
body?: JsonMap,
): Promise<JsonMap> {
const url = new URL(joinUrl(baseUrl, `${PUBLIC_API_PREFIX}${path}`));
if (query) {
for (const [k, v] of Object.entries(query)) {
if (v == null || v === "") continue;
url.searchParams.set(k, String(v));
}
}
const headers: Record<string, string> = {
Accept: "application/json",
};
if (opts.apiKey) headers["X-Nomadro-Key"] = opts.apiKey;
if (opts.guestId) headers["X-Social-Guest-Id"] = opts.guestId;
if (body) headers["Content-Type"] = "application/json";
const res = await doFetch(url.toString(), {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
cache: "no-store",
});
const data = (await res.json().catch(() => ({}))) as JsonMap;
if (!res.ok) {
const err = new Error(
String(data.detail || data.error || `HTTP ${res.status}`),
) as Error & { status?: number; data?: JsonMap };
err.status = res.status;
err.data = data;
throw err;
}
return data;
}
return {
baseUrl,
version: PUBLIC_API_VERSION,
tools: NOMADRO_TOOLS,
openapi: () => buildOpenApiDocument({ servers: [{ url: baseUrl }] }),
health: () => request("GET", "/health"),
getMeta: () => request("GET", "/meta"),
getConfig: () => request("GET", "/config"),
listTools: () => request("GET", "/tools"),
listMapCities: (q?: {
west?: number;
south?: number;
east?: number;
north?: number;
}) => request("GET", "/social/cities", q as JsonMap),
searchCities: (q: { q: string; limit?: number; lang?: string }) =>
request("GET", "/social/cities/search", q as JsonMap),
listMeetups: (q?: { keyword?: string }) =>
request("GET", "/social/meetups", q as JsonMap),
openMeetup: (q: { meetupId: string; nick?: string }) =>
request("GET", fillPath("/social/meetups/{meetupId}", q), {
nick: q.nick,
}),
listGigs: (q?: { kind?: string; keyword?: string }) =>
request("GET", "/social/gigs", q as JsonMap),
applyGig: (q: {
gigId: string;
name: string;
contact: string;
note?: string;
}) =>
request(
"POST",
fillPath("/social/gigs/{gigId}/apply", q),
undefined,
{ name: q.name, contact: q.contact, note: q.note },
),
joinSocial: (q?: { email?: string; locale?: string }) =>
request("GET", "/social/join", q as JsonMap),
checkVip: (q: { email: string }) =>
request("GET", "/vip/check", q as JsonMap),
listNavLinks: (q?: { q?: string; limit?: number }) =>
request("GET", "/nav/links", q as JsonMap),
listSocialRoutes: () => request("GET", "/social/routes"),
/** Invoke any tool by name (MCP-friendly). */
async callTool(name: NomadroToolName, args: JsonMap = {}) {
switch (name) {
case "health":
return this.health();
case "getMeta":
return this.getMeta();
case "getConfig":
return this.getConfig();
case "listMapCities":
return this.listMapCities(args as never);
case "searchCities":
return this.searchCities(args as never);
case "listMeetups":
return this.listMeetups(args as never);
case "openMeetup":
return this.openMeetup(args as never);
case "listGigs":
return this.listGigs(args as never);
case "applyGig":
return this.applyGig(args as never);
case "joinSocial":
return this.joinSocial(args as never);
case "checkVip":
return this.checkVip(args as never);
case "listNavLinks":
return this.listNavLinks(args as never);
case "listSocialRoutes":
return this.listSocialRoutes();
default:
throw new Error(`unknown tool ${name}`);
}
},
};
}
export type NomadroClient = ReturnType<typeof createNomadroClient>;