ShtukbaseStandard
файл пакета→ .shtukbase/packages/icons/actions/sanitize.ts

actions/sanitize.ts

29 строк, 1.7 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // shtuk run icons sanitize <file.svg> [--write | -o <out.svg>]: drops what the contract refuses (scripts, handlers,
  2. // external links, text, editor metadata, currentColor), keeps the drawing, adds xmlns and a square viewBox when it can.
  3. // Prints the result (or writes it), then validates it: exit 1 if errors remain (a wrong viewBox or size needs a redraw).
  4. import { existsSync, readFileSync, writeFileSync } from 'node:fs';
  5. import { join } from 'node:path';
  6. import { iconStyle, settings } from '../lib/iconlib.ts';
  7. import { sanitize, validate } from '../lib/svg.ts';
  8. const root = process.cwd();
  9. const args = process.argv.slice(2);
  10. const file = args.find((a) => !a.startsWith('-') && args[args.indexOf(a) - 1] !== '-o');
  11. if (!file) {
  12. console.log('usage: shtuk run icons sanitize <file.svg> [--write | -o <out.svg>]');
  13. process.exit(2);
  14. }
  15. const abs = join(root, file.replace(/^\/+/, ''));
  16. if (!existsSync(abs)) { console.error(`${file}: the file does not exist`); process.exit(1); }
  17. const before = readFileSync(abs, 'utf8');
  18. const after = sanitize(before);
  19. const oi = args.indexOf('-o');
  20. const dest = args.includes('--write') ? abs : oi >= 0 && args[oi + 1] ? join(root, args[oi + 1]) : '';
  21. if (dest) writeFileSync(dest, after);
  22. else process.stdout.write(after);
  23. const s = settings(root);
  24. const left = validate(after, s.maxBytes, iconStyle(root, s)?.rules).filter((f) => f.level === 'error');
  25. const note = (t: string) => (dest ? console.log(t) : console.error(t));
  26. note(`${file}: ${before.length} → ${after.length} bytes${dest ? ', written to ' + dest.slice(root.length + 1) : ''}`);
  27. for (const f of left) note(`${file}: still an error: ${f.text}`);
  28. process.exitCode = left.length ? 1 : 0;