const BASE = (typeof window !== "undefined" && window.__BASE__) || "";
async function _get(path) {
const url = BASE + path;
const r = await fetch(url);
if (!r.ok) throw new Error(`${url}: ${r.status} ${r.statusText}`);
return r.json();
}
async function _post(path, body) {
const url = BASE + path;
const r = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
if (!r.ok) throw new Error(`${url}: ${r.status} ${r.statusText}`);
return r.json();
}
const _eid = (id) => encodeURIComponent(id).replace(/%2F/g, "/");
let _base = "";
export const API = {
setDataset: (id) => { _base = id ? `/d/${encodeURIComponent(id)}` : ""; },
datasets: () => _get("/api/datasets"),
manifest: () => _get(`${_base}/api/manifest`),
treemap: (body) => _post(`${_base}/api/treemap`, body),
geo: (body) => _post(`${_base}/api/geo`, body),
timeseriesTreemap: (body) => _post(`${_base}/api/series`, body),
scatter: (body) => _post(`${_base}/api/scatter`, body),
search: (q, axis) => _get(`${_base}/api/search?q=${encodeURIComponent(q)}` +
(axis ? `&axis=${encodeURIComponent(axis)}` : "")),
entity: (id) => _get(`${_base}/api/entity/${_eid(id)}`),
entitySeries: (id, metric, window, resolution) =>
_get(`${_base}/api/entity/${_eid(id)}/series` +
`?metric=${encodeURIComponent(metric)}&window=${encodeURIComponent(window)}` +
`&resolution=${encodeURIComponent(resolution || "d")}`),
entityOhlc: (id, window, resolution) =>
_get(`${_base}/api/entity/${_eid(id)}/ohlc` +
`?window=${encodeURIComponent(window)}&resolution=${encodeURIComponent(resolution || "d")}`),
filterOptions: (facet) => _get(`${_base}/api/filter-options/${encodeURIComponent(facet)}`),
};