190 lines
5.4 KiB
JavaScript
190 lines
5.4 KiB
JavaScript
#!/usr/bin/env node
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
|
|
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..");
|
|
const PROTO_ROOT = path.join(ROOT, "proto", "clawchain");
|
|
const OUT_FILE = path.join(ROOT, "sdk", "src", "generated", "proto-contracts.ts");
|
|
const COSMOS_EXPORT_META_FILE = path.join(
|
|
ROOT,
|
|
"third_party",
|
|
"proto",
|
|
"cosmos-sdk",
|
|
"CLAWCHAIN_COSMOS_SDK_EXPORT.json",
|
|
);
|
|
const CHECK_MODE = process.argv.includes("--check");
|
|
|
|
function walk(dir) {
|
|
const out = [];
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const p = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) out.push(...walk(p));
|
|
else out.push(p);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function toPosix(p) {
|
|
return p.split(path.sep).join("/");
|
|
}
|
|
|
|
function countPlaceholders(s) {
|
|
return (s.match(/\{[^}]+\}/g) ?? []).length;
|
|
}
|
|
|
|
function stripPlaceholders(s) {
|
|
const stripped = s.replace(/\/\{[^}]+\}/g, "");
|
|
return stripped.endsWith("/") && stripped.length > 1 ? stripped.slice(0, -1) : stripped;
|
|
}
|
|
|
|
function bestPath(paths) {
|
|
return [...paths].sort((a, b) => {
|
|
const da = countPlaceholders(a) - countPlaceholders(b);
|
|
if (da !== 0) return da;
|
|
return a.length - b.length;
|
|
})[0];
|
|
}
|
|
|
|
function parseProto(filePath) {
|
|
const src = fs.readFileSync(filePath, "utf8");
|
|
const pkgMatch = src.match(/^\s*package\s+([a-zA-Z0-9_.]+)\s*;/m);
|
|
if (!pkgMatch) return null;
|
|
const pkg = pkgMatch[1];
|
|
|
|
const msgTypeUrls = new Map();
|
|
const queryPaths = new Map();
|
|
|
|
const msgServiceMatch = src.match(/service\s+Msg\s*\{([\s\S]*?)\n\}/m);
|
|
if (msgServiceMatch) {
|
|
const body = msgServiceMatch[1];
|
|
const rpcRe = /rpc\s+\w+\s*\(\s*([A-Za-z0-9_]+)\s*\)\s*returns\s*\(\s*[A-Za-z0-9_]+\s*\)\s*;/g;
|
|
let m;
|
|
while ((m = rpcRe.exec(body)) !== null) {
|
|
const req = m[1];
|
|
if (!req.startsWith("Msg")) continue;
|
|
msgTypeUrls.set(`${pkg}.${req}`, `/${pkg}.${req}`);
|
|
}
|
|
}
|
|
|
|
const queryServiceMatch = src.match(/service\s+Query\s*\{([\s\S]*?)\n\}/m);
|
|
if (queryServiceMatch) {
|
|
const body = queryServiceMatch[1];
|
|
const rpcBlockRe = /rpc\s+([A-Za-z0-9_]+)\s*\([^)]*\)\s*returns\s*\([^)]*\)\s*\{([\s\S]*?)\n\s*\}/g;
|
|
let m;
|
|
while ((m = rpcBlockRe.exec(body)) !== null) {
|
|
const rpcName = m[1];
|
|
const rpcBody = m[2];
|
|
const paths = [];
|
|
|
|
for (const mm of rpcBody.matchAll(/option\s+\(google\.api\.http\)\.(get|post)\s*=\s*"([^"]+)"/g)) {
|
|
paths.push(mm[2]);
|
|
}
|
|
for (const mm of rpcBody.matchAll(/\b(get|post)\s*:\s*"([^"]+)"/g)) {
|
|
paths.push(mm[2]);
|
|
}
|
|
|
|
if (paths.length > 0) {
|
|
queryPaths.set(`${pkg}.Query.${rpcName}`, bestPath(paths));
|
|
}
|
|
}
|
|
}
|
|
|
|
return { pkg, msgTypeUrls, queryPaths };
|
|
}
|
|
|
|
function renderTypeUrls(entries) {
|
|
const lines = [];
|
|
lines.push("export const PROTO_MSG_TYPE_URLS = {");
|
|
for (const [k, v] of entries) lines.push(` "${k}": "${v}",`);
|
|
lines.push("} as const;");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function renderQueryPaths(entries) {
|
|
const lines = [];
|
|
lines.push("export const PROTO_QUERY_HTTP_PATHS = {");
|
|
for (const [k, v] of entries) lines.push(` "${k}": "${v}",`);
|
|
lines.push("} as const;");
|
|
lines.push("");
|
|
lines.push("export const PROTO_QUERY_HTTP_PREFIX_PATHS = {");
|
|
for (const [k, v] of entries) lines.push(` "${k}": "${stripPlaceholders(v)}",`);
|
|
lines.push("} as const;");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function readCosmosExportMetadata() {
|
|
if (!fs.existsSync(COSMOS_EXPORT_META_FILE)) {
|
|
return {
|
|
protoSource: "remote-buf-deps",
|
|
cosmosSdkExport: null,
|
|
};
|
|
}
|
|
try {
|
|
const raw = fs.readFileSync(COSMOS_EXPORT_META_FILE, "utf8");
|
|
const parsed = JSON.parse(raw);
|
|
return {
|
|
protoSource: "local-cosmos-sdk-export",
|
|
cosmosSdkExport: parsed,
|
|
};
|
|
} catch {
|
|
return {
|
|
protoSource: "local-cosmos-sdk-export-invalid-metadata",
|
|
cosmosSdkExport: null,
|
|
};
|
|
}
|
|
}
|
|
|
|
function renderSourceMetadata() {
|
|
const metadata = readCosmosExportMetadata();
|
|
return [
|
|
"export const PROTO_SOURCE_METADATA = " +
|
|
JSON.stringify(metadata, null, 2)
|
|
.split("\n")
|
|
.map((line, idx) => (idx === 0 ? line : ` ${line}`))
|
|
.join("\n") +
|
|
" as const;",
|
|
].join("\n");
|
|
}
|
|
|
|
const files = walk(PROTO_ROOT)
|
|
.filter((f) => /\/v1\/(tx|query)\.proto$/.test(toPosix(f)))
|
|
.sort();
|
|
|
|
const msgEntries = new Map();
|
|
const queryEntries = new Map();
|
|
for (const file of files) {
|
|
const parsed = parseProto(file);
|
|
if (!parsed) continue;
|
|
for (const [k, v] of parsed.msgTypeUrls) msgEntries.set(k, v);
|
|
for (const [k, v] of parsed.queryPaths) queryEntries.set(k, v);
|
|
}
|
|
|
|
const header = [
|
|
"/* eslint-disable */",
|
|
"// Code generated by sdk/scripts/gen-proto-contracts.mjs. DO NOT EDIT.",
|
|
"",
|
|
].join("\n");
|
|
|
|
const content = [
|
|
header,
|
|
renderSourceMetadata(),
|
|
"",
|
|
renderTypeUrls([...msgEntries.entries()].sort((a, b) => a[0].localeCompare(b[0]))),
|
|
"",
|
|
renderQueryPaths([...queryEntries.entries()].sort((a, b) => a[0].localeCompare(b[0]))),
|
|
"",
|
|
].join("\n");
|
|
|
|
if (CHECK_MODE) {
|
|
const current = fs.existsSync(OUT_FILE) ? fs.readFileSync(OUT_FILE, "utf8") : "";
|
|
if (current !== content) {
|
|
console.error("proto-contracts.ts is out of date. Run: npm run proto:gen");
|
|
process.exit(1);
|
|
}
|
|
process.exit(0);
|
|
}
|
|
|
|
fs.mkdirSync(path.dirname(OUT_FILE), { recursive: true });
|
|
fs.writeFileSync(OUT_FILE, content);
|
|
console.log(`generated ${path.relative(ROOT, OUT_FILE)}`);
|