everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
163 lines (161 loc) • 6.34 kB
JavaScript
import { fetchJsonOrNull, fetchRaw } from "../../utils/http-client.mjs";
import { keyPathOf, parseRuntimeRef } from "./keys.mjs";
import { Context, Data, Layer } from "effect";
//#region src/services/registry/client.ts
const FASTKV_TESTNET_URL = "https://kv.test.fastnear.com";
const FASTKV_MAINNET_URL = "https://kv.main.fastnear.com";
const REGISTRY_NAMESPACE_TESTNET = "dev.allthethings.testnet";
const REGISTRY_NAMESPACE_MAINNET = "dev.everything.near";
/** The network a signing account publishes on — the account suffix is the
* network. One function; nothing else may derive a base URL. */
function networkIdForAccount(accountId) {
return accountId.endsWith(".testnet") ? "testnet" : "mainnet";
}
function registryBaseUrlForNetwork(network) {
return network === "testnet" ? FASTKV_TESTNET_URL : FASTKV_MAINNET_URL;
}
function registryNamespaceForNetwork(network, registry) {
if (registry) return registry;
return network === "testnet" ? REGISTRY_NAMESPACE_TESTNET : REGISTRY_NAMESPACE_MAINNET;
}
var RegistryError = class extends Data.TaggedError("RegistryError") {
get message() {
return this.kind === "absent" ? `Not published in the registry: ${this.key}` : `Registry read failed: ${this.key}`;
}
};
const parseValue = (value, key) => {
if (typeof value === "string" && value.length > 0) return JSON.parse(value);
if (value === null || value === void 0 || value === "") throw new RegistryError({
key,
kind: "absent"
});
if (typeof value !== "object") throw new RegistryError({
key,
kind: "unreachable",
cause: `Invalid value for ${key}`
});
return value;
};
const toEntry = (entry) => ({
key: entry.key ?? "",
value: entry.value,
blockHeight: entry.block_height ?? 0,
blockTimestampNs: String(entry.block_timestamp ?? ""),
...entry.tx_hash ? { txHash: entry.tx_hash } : {}
});
const parseJsonish = (value) => typeof value === "string" && value.length > 0 ? JSON.parse(value) : value;
const HISTORY_MAX_LIMIT = 200;
const HISTORY_DEFAULT_LIMIT = 20;
function buildUrl(key, surface, opts) {
const { accountId } = parseRuntimeRef(key.ref);
const network = networkIdForAccount(accountId);
const namespace = registryNamespaceForNetwork(network, opts?.registry);
const encodedKey = encodeURIComponent(keyPathOf(key));
return `${registryBaseUrlForNetwork(network)}/v0/${surface}/${encodeURIComponent(namespace)}/${encodeURIComponent(accountId)}/${encodedKey}`;
}
async function readLatest(key, opts) {
const wire = keyPathOf(key);
try {
const headers = { accept: "application/json" };
const response = opts?.fetchImpl ? await opts.fetchImpl(buildUrl(key, "latest", opts), { headers }) : await fetchRaw(buildUrl(key, "latest", opts), { headers });
if (!response.ok) {
if (response.status === 404) throw new RegistryError({
key: wire,
kind: "absent"
});
throw new RegistryError({
key: wire,
kind: "unreachable",
cause: `HTTP ${response.status}`
});
}
const value = (await response.json())?.entries?.find(Boolean)?.value;
if (value === void 0 || value === null || value === "") throw new RegistryError({
key: wire,
kind: "absent"
});
return parseValue(value, wire);
} catch (error) {
if (error instanceof RegistryError) throw error;
throw new RegistryError({
key: wire,
kind: "unreachable",
cause: error
});
}
}
async function listLatest(input, opts) {
const ref = input.ref;
const accountId = ref ? parseRuntimeRef(ref).accountId : REGISTRY_NAMESPACE_MAINNET;
const network = networkIdForAccount(accountId);
const namespace = registryNamespaceForNetwork(network, opts?.registry);
const url = `${registryBaseUrlForNetwork(network)}${ref ? `/v0/latest/${encodeURIComponent(namespace)}/${encodeURIComponent(accountId)}` : `/v0/latest/${encodeURIComponent(namespace)}`}`;
const body = JSON.stringify({
limit: input.limit ?? 50,
...input.keyPrefix ? { key_prefix: input.keyPrefix } : {},
...input.pageToken ? { page_token: input.pageToken } : {},
...input.includeMetadata ? { include_metadata: true } : {}
});
const payload = opts?.fetchImpl ? await opts.fetchImpl(url, {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json"
},
body
}) : await fetchRaw(url, {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json"
},
body
});
if (!payload.ok) throw new RegistryError({
key: input.keyPrefix ?? namespace,
kind: "unreachable",
cause: `HTTP ${payload.status}`
});
const parsed = await payload.json();
return {
entries: (parsed?.entries ?? []).filter((entry) => entry !== null).map(toEntry),
pageToken: parsed?.page_token ?? null
};
}
async function readHistory(key, limit, opts) {
const capped = Math.max(1, Math.min(limit ?? HISTORY_DEFAULT_LIMIT, HISTORY_MAX_LIMIT));
const url = `${buildUrl(key, "history", opts)}?limit=${capped}`;
return ((await fetchJsonOrNull(url, {
headers: { accept: "application/json" },
retries: 3
}))?.entries ?? []).filter((entry) => entry !== null).map((entry) => {
const mapped = toEntry(entry);
return {
blockHeight: mapped.blockHeight,
blockTimestampNs: mapped.blockTimestampNs,
...mapped.txHash ? { txHash: mapped.txHash } : {},
value: parseJsonish(mapped.value)
};
}).sort((a, b) => b.blockHeight - a.blockHeight);
}
/** The canonical latest-state URL for a key — for display and external
* links (the client owns all URL derivation; nothing else builds one). */
function latestUrlFor(key, opts) {
return buildUrl(key, "latest", opts);
}
/** The plain-function seam — module is the implementation, tag is the seam. */
const registryClientShape = {
read: (key, opts) => readLatest(key, opts),
readOrNull: (key, opts) => readLatest(key, opts).catch((error) => {
if (error instanceof RegistryError && error.kind === "absent") return null;
throw error;
}),
list: (input, opts) => listLatest(input, opts),
history: (key, limit, opts) => readHistory(key, limit, opts)
};
var RegistryClient = class extends Context.Service()("everything-dev/registry/client") {
static Live = Layer.succeed(this, this.of(registryClientShape));
};
//#endregion
export { RegistryClient, RegistryError, latestUrlFor, networkIdForAccount, registryBaseUrlForNetwork, registryClientShape, registryNamespaceForNetwork };
//# sourceMappingURL=client.mjs.map