format-catalog.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env node
  2. 'use strict';
  3. // 把接口目录和参数库写成「每个接口一行」的紧凑格式。
  4. // 体积比缩进格式小约三分之一,同时每个接口独占一行,git diff 仍然逐接口可读。
  5. // 用脚本改过目录后运行 `npm run catalog:format`。
  6. const fs = require('fs');
  7. const path = require('path');
  8. const CATALOG_DIR = path.resolve(__dirname, '..', 'mcp', 'catalog');
  9. const CATALOG_PATH = path.join(CATALOG_DIR, 'voc-social-endpoints.json');
  10. const PARAMS_DIR = path.join(CATALOG_DIR, 'params');
  11. function readJson(file) {
  12. const text = fs.readFileSync(file, 'utf8');
  13. return JSON.parse(text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text);
  14. }
  15. function formatCatalog(catalog) {
  16. const { endpoints, ...header } = catalog;
  17. const head = JSON.stringify(header, null, 2).replace(/\n}$/, '');
  18. const rows = (endpoints || []).map(item => ` ${JSON.stringify(item)}`).join(',\n');
  19. return `${head},\n "endpoints": [\n${rows}\n ]\n}\n`;
  20. }
  21. function formatParams(store) {
  22. const rows = Object.entries(store).map(([id, params]) => ` ${JSON.stringify(id)}: ${JSON.stringify(params)}`).join(',\n');
  23. return `{\n${rows}\n}\n`;
  24. }
  25. function writeIfChanged(file, content, original) {
  26. // 格式化不能改变数据:写入前确认解析结果与原数据完全一致。
  27. if (JSON.stringify(JSON.parse(content)) !== JSON.stringify(original)) {
  28. throw new Error(`formatting would change data: ${file}`);
  29. }
  30. const before = fs.readFileSync(file, 'utf8');
  31. if (before === content) return 0;
  32. fs.writeFileSync(file, content, 'utf8');
  33. return Buffer.byteLength(before, 'utf8') - Buffer.byteLength(content, 'utf8');
  34. }
  35. let saved = 0;
  36. const catalog = readJson(CATALOG_PATH);
  37. saved += writeIfChanged(CATALOG_PATH, formatCatalog(catalog), catalog);
  38. for (const name of fs.readdirSync(PARAMS_DIR).filter(item => item.endsWith('.json'))) {
  39. const file = path.join(PARAMS_DIR, name);
  40. const store = readJson(file);
  41. saved += writeIfChanged(file, formatParams(store), store);
  42. }
  43. console.log(`catalog formatted, ${Math.round(saved / 1024)}KB smaller`);