normalize-metrics 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oles Gergun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # normalize-metrics
2
+
3
+ Rewrite font vertical metrics so a word sits in the box.
4
+
5
+ The text within a button is not always centered. That is the font’s fault, not yours. You can already trim the line box in CSS with `text-box: trim-both cap alphabetic`. The default is still the untrimmed box, and most type ramps and component kits were written for that default.
6
+
7
+ This CLI rewrites the font for that default case. It only changes how the word sits in the box — not the letters, the look of the font, or anything else.
8
+
9
+ ```
10
+ npm i -g normalize-metrics
11
+ normalize-metrics Inter-Regular.otf
12
+ normalize-metrics ./fonts
13
+ ```
14
+
15
+ Or once, without installing:
16
+
17
+ ```
18
+ npx normalize-metrics ./fonts
19
+ ```
20
+
21
+ A folder means every `.otf`, `.ttf`, `.woff`, and `.woff2` inside it. It writes a normalized copy next to the original. Fonts that already have good metrics are left alone. Variable fonts and TTC collections are skipped in v1.
22
+
23
+ Rewriting a licensed font and redistributing the result may violate the EULA. This tool does not legalize the file.
24
+
25
+ ## Requirements
26
+
27
+ - Node.js 20 or newer
28
+ - Python 3 with [fontTools](https://github.com/fonttools/fonttools) (`pip install fonttools`) — an implementation detail, not a pip product install
29
+
30
+ ## Usage
31
+
32
+ ```
33
+ normalize-metrics <file|folder> [options]
34
+ ```
35
+
36
+ | Option | What it does |
37
+ | --- | --- |
38
+ | `--check` | Report fonts that are still off; write nothing; exit 1 if any are off |
39
+ | `--dry-run` | Same report; write nothing |
40
+ | `--in-place` | Overwrite the original (opt-in) |
41
+ | `--out-dir <dir>` | Write copies into this directory |
42
+ | `--suffix <text>` | Filename suffix for copies (default: `-normalized`) |
43
+ | `--config <file>` | `normalize-metrics.config.json` (or a `package.json` key) |
44
+
45
+ Never overwrites unless you pass `--in-place`.
46
+
47
+ In a repo, add it as a dev dependency and list the folders in the config. `--check` reports fonts that are still off and exits without writing — useful in CI.
48
+
49
+ ```
50
+ npm i -D normalize-metrics
51
+ ```
52
+
53
+ ## Config
54
+
55
+ `normalize-metrics.config.json`, or a `"normalize-metrics"` key in `package.json`:
56
+
57
+ ```json
58
+ {
59
+ "include": ["fonts/**/*.{otf,ttf,woff,woff2}"],
60
+ "exclude": ["**/*-normalized.*"],
61
+ "outDir": null,
62
+ "suffix": "-normalized"
63
+ }
64
+ ```
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const { spawnSync } = require("node:child_process");
5
+ const { join } = require("node:path");
6
+
7
+ const entry = join(__dirname, "..", "dist", "index.js");
8
+ const result = spawnSync(process.execPath, [entry, ...process.argv.slice(2)], {
9
+ stdio: "inherit",
10
+ });
11
+
12
+ if (result.error) {
13
+ console.error(result.error.message);
14
+ process.exit(1);
15
+ }
16
+
17
+ process.exit(result.status ?? 1);
package/dist/args.js ADDED
@@ -0,0 +1,97 @@
1
+ export const HELP = `normalize-metrics — rewrite vertical metrics so a word sits in the box
2
+
3
+ Usage:
4
+ normalize-metrics <file|folder> [options]
5
+ normalize-metrics [options]
6
+
7
+ A folder means every .otf, .ttf, .woff, and .woff2 inside it.
8
+ Writes a normalized copy next to the original. Never overwrites unless --in-place.
9
+ Fonts that already have good metrics are left alone.
10
+
11
+ Options:
12
+ --check report fonts that are still off; write nothing; exit 1 if any are off
13
+ --dry-run same report; write nothing
14
+ --in-place overwrite the original (opt-in)
15
+ --out-dir <dir> write copies into this directory
16
+ --suffix <text> filename suffix for copies (default: -normalized)
17
+ --config <file> normalize-metrics.config.json (or a package.json key)
18
+ -h, --help show this help
19
+ -v, --version print the package version
20
+
21
+ Config (normalize-metrics.config.json or "normalize-metrics" in package.json):
22
+ include, exclude, outDir, suffix
23
+
24
+ Examples:
25
+ normalize-metrics Inter-Regular.otf
26
+ normalize-metrics ./fonts
27
+ npx normalize-metrics ./fonts --check
28
+ `;
29
+ const FLAGS_WITH_VALUE = new Set(["--out-dir", "--suffix", "--config"]);
30
+ export function parseArgs(argv) {
31
+ const args = {
32
+ path: null,
33
+ check: false,
34
+ dryRun: false,
35
+ inPlace: false,
36
+ outDir: null,
37
+ suffix: null,
38
+ configPath: null,
39
+ help: false,
40
+ version: false,
41
+ };
42
+ for (let i = 0; i < argv.length; i += 1) {
43
+ const token = argv[i];
44
+ if (token === "-h" || token === "--help") {
45
+ args.help = true;
46
+ continue;
47
+ }
48
+ if (token === "-v" || token === "--version") {
49
+ args.version = true;
50
+ continue;
51
+ }
52
+ if (token === "--check") {
53
+ args.check = true;
54
+ continue;
55
+ }
56
+ if (token === "--dry-run") {
57
+ args.dryRun = true;
58
+ continue;
59
+ }
60
+ if (token === "--in-place") {
61
+ args.inPlace = true;
62
+ continue;
63
+ }
64
+ if (FLAGS_WITH_VALUE.has(token)) {
65
+ const value = argv[i + 1];
66
+ if (!value || value.startsWith("-")) {
67
+ throw new Error(`${token} needs a value.`);
68
+ }
69
+ i += 1;
70
+ if (token === "--out-dir")
71
+ args.outDir = value;
72
+ if (token === "--suffix")
73
+ args.suffix = value;
74
+ if (token === "--config")
75
+ args.configPath = value;
76
+ continue;
77
+ }
78
+ if (token.startsWith("-")) {
79
+ throw new Error(`Unknown flag: ${token}`);
80
+ }
81
+ if (args.path) {
82
+ throw new Error("Pass one file or one folder.");
83
+ }
84
+ args.path = token;
85
+ }
86
+ if (args.inPlace && args.outDir) {
87
+ throw new Error("Use either --in-place or --out-dir, not both.");
88
+ }
89
+ return args;
90
+ }
91
+ export function modeOf(args) {
92
+ if (args.check)
93
+ return "check";
94
+ if (args.dryRun)
95
+ return "dry-run";
96
+ return "write";
97
+ }
package/dist/config.js ADDED
@@ -0,0 +1,99 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { pathExists } from "./fs-exists.js";
4
+ export const DEFAULT_SUFFIX = "-normalized";
5
+ const DEFAULT_EXCLUDE = [
6
+ "**/node_modules/**",
7
+ "**/.git/**",
8
+ "**/.next/**",
9
+ "**/dist/**",
10
+ "**/__pycache__/**",
11
+ ];
12
+ export function emptyConfig() {
13
+ return {
14
+ include: [],
15
+ exclude: [...DEFAULT_EXCLUDE],
16
+ outDir: null,
17
+ suffix: DEFAULT_SUFFIX,
18
+ };
19
+ }
20
+ function asStringList(value, key) {
21
+ if (value == null)
22
+ return [];
23
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
24
+ throw new Error(`Config "${key}" must be an array of strings.`);
25
+ }
26
+ return value;
27
+ }
28
+ function asOptionalString(value, key) {
29
+ if (value == null || value === "")
30
+ return null;
31
+ if (typeof value !== "string") {
32
+ throw new Error(`Config "${key}" must be a string.`);
33
+ }
34
+ return value;
35
+ }
36
+ function parseRaw(raw, baseDir) {
37
+ const outDir = asOptionalString(raw.outDir, "outDir");
38
+ return {
39
+ include: asStringList(raw.include, "include"),
40
+ exclude: [...DEFAULT_EXCLUDE, ...asStringList(raw.exclude, "exclude")],
41
+ outDir: outDir ? (isAbsolute(outDir) ? outDir : resolve(baseDir, outDir)) : null,
42
+ suffix: asOptionalString(raw.suffix, "suffix") ?? DEFAULT_SUFFIX,
43
+ };
44
+ }
45
+ async function readJson(file) {
46
+ return JSON.parse(await readFile(file, "utf8"));
47
+ }
48
+ export async function loadConfigFile(file) {
49
+ const raw = (await readJson(file));
50
+ return parseRaw(raw ?? {}, dirname(file));
51
+ }
52
+ export async function loadPackageConfig(file) {
53
+ const pkg = (await readJson(file));
54
+ if (!pkg["normalize-metrics"])
55
+ return null;
56
+ return parseRaw(pkg["normalize-metrics"], dirname(file));
57
+ }
58
+ export async function findConfig(startDir, explicit) {
59
+ if (explicit) {
60
+ const file = resolve(startDir, explicit);
61
+ if (!(await pathExists(file))) {
62
+ throw new Error(`Config not found: ${file}`);
63
+ }
64
+ if (file.endsWith("package.json")) {
65
+ return (await loadPackageConfig(file)) ?? emptyConfig();
66
+ }
67
+ return loadConfigFile(file);
68
+ }
69
+ let dir = resolve(startDir);
70
+ while (true) {
71
+ const jsonFile = join(dir, "normalize-metrics.config.json");
72
+ if (await pathExists(jsonFile)) {
73
+ return loadConfigFile(jsonFile);
74
+ }
75
+ const pkgFile = join(dir, "package.json");
76
+ if (await pathExists(pkgFile)) {
77
+ const fromPkg = await loadPackageConfig(pkgFile);
78
+ if (fromPkg)
79
+ return fromPkg;
80
+ }
81
+ const parent = dirname(dir);
82
+ if (parent === dir)
83
+ break;
84
+ dir = parent;
85
+ }
86
+ return emptyConfig();
87
+ }
88
+ export function mergeConfig(config, flags, cwd) {
89
+ return {
90
+ include: config.include,
91
+ exclude: config.exclude,
92
+ outDir: flags.outDir
93
+ ? isAbsolute(flags.outDir)
94
+ ? flags.outDir
95
+ : resolve(cwd, flags.outDir)
96
+ : config.outDir,
97
+ suffix: flags.suffix ?? config.suffix,
98
+ };
99
+ }
@@ -0,0 +1,70 @@
1
+ import { readdir, stat } from "node:fs/promises";
2
+ import { basename, join, relative, resolve, sep } from "node:path";
3
+ import { matchesAny } from "./glob.js";
4
+ const FONT_EXT = new Set([".otf", ".ttf", ".woff", ".woff2", ".ttc"]);
5
+ function extensionOf(name) {
6
+ const match = name.toLowerCase().match(/(\.woff2|\.woff|\.ttf|\.otf|\.ttc)$/);
7
+ return match ? match[1] : "";
8
+ }
9
+ function toPosix(rel) {
10
+ return rel.split(sep).join("/");
11
+ }
12
+ export function isFontName(name) {
13
+ return FONT_EXT.has(extensionOf(name));
14
+ }
15
+ export function kindOf(name) {
16
+ return extensionOf(name) === ".ttc" ? "ttc" : "font";
17
+ }
18
+ function ignoredDir(name) {
19
+ return name === "node_modules" || name === ".git" || name === ".next" || name === "__pycache__";
20
+ }
21
+ async function walk(dir, root, found) {
22
+ const entries = await readdir(dir, { withFileTypes: true });
23
+ for (const entry of entries) {
24
+ const abs = join(dir, entry.name);
25
+ if (entry.isDirectory()) {
26
+ if (!ignoredDir(entry.name))
27
+ await walk(abs, root, found);
28
+ continue;
29
+ }
30
+ if (!entry.isFile() || !isFontName(entry.name))
31
+ continue;
32
+ const rel = toPosix(relative(root, abs)) || entry.name;
33
+ found.push({ abs, rel, name: entry.name, kind: kindOf(entry.name) });
34
+ }
35
+ }
36
+ export async function discover(target, config) {
37
+ const abs = resolve(target);
38
+ const info = await stat(abs);
39
+ if (info.isFile()) {
40
+ if (!isFontName(basename(abs))) {
41
+ throw new Error(`Not a font file: ${basename(abs)}`);
42
+ }
43
+ return [{ abs, rel: basename(abs), name: basename(abs), kind: kindOf(abs) }];
44
+ }
45
+ if (!info.isDirectory()) {
46
+ throw new Error(`Not a file or folder: ${target}`);
47
+ }
48
+ const found = [];
49
+ await walk(abs, abs, found);
50
+ found.sort((a, b) => a.rel.localeCompare(b.rel));
51
+ return found.filter((file) => {
52
+ if (config.exclude.length && matchesAny(file.rel, config.exclude))
53
+ return false;
54
+ if (config.include.length && !matchesAny(file.rel, config.include))
55
+ return false;
56
+ return true;
57
+ });
58
+ }
59
+ export async function discoverFromInclude(cwd, config) {
60
+ if (!config.include.length)
61
+ return [];
62
+ const found = [];
63
+ await walk(cwd, cwd, found);
64
+ found.sort((a, b) => a.rel.localeCompare(b.rel));
65
+ return found.filter((file) => {
66
+ if (config.exclude.length && matchesAny(file.rel, config.exclude))
67
+ return false;
68
+ return matchesAny(file.rel, config.include);
69
+ });
70
+ }
package/dist/engine.js ADDED
@@ -0,0 +1,65 @@
1
+ import { spawn } from "node:child_process";
2
+ import { enginePath } from "./runtime.js";
3
+ function lastJson(text) {
4
+ const line = text
5
+ .trim()
6
+ .split("\n")
7
+ .filter((entry) => entry.trim().startsWith("{"))
8
+ .at(-1);
9
+ if (!line)
10
+ return null;
11
+ return JSON.parse(line);
12
+ }
13
+ export function runEngine(options) {
14
+ const args = [enginePath(), "--progress"];
15
+ if (options.inspect)
16
+ args.push("--inspect");
17
+ if (options.skipIfGood)
18
+ args.push("--skip-if-good");
19
+ args.push(options.input);
20
+ if (options.output && !options.inspect)
21
+ args.push(options.output);
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn(options.python, args, { stdio: ["ignore", "pipe", "pipe"] });
24
+ let stdout = "";
25
+ let stderr = "";
26
+ const takeProgress = (chunk) => {
27
+ for (const line of chunk.split("\n")) {
28
+ const trimmed = line.trim();
29
+ if (!trimmed.startsWith("{"))
30
+ continue;
31
+ try {
32
+ const parsed = JSON.parse(trimmed);
33
+ if (parsed.event === "progress" && typeof parsed.percent === "number") {
34
+ options.onProgress?.({ percent: parsed.percent, phase: parsed.phase ?? "analyzing" });
35
+ }
36
+ }
37
+ catch {
38
+ // fontTools may write non-JSON lines
39
+ }
40
+ }
41
+ };
42
+ child.stdout.on("data", (chunk) => {
43
+ stdout += chunk.toString();
44
+ });
45
+ child.stderr.on("data", (chunk) => {
46
+ const text = chunk.toString();
47
+ stderr += text;
48
+ takeProgress(text);
49
+ });
50
+ child.on("error", reject);
51
+ child.on("close", (code) => {
52
+ try {
53
+ const parsed = lastJson(stdout);
54
+ if (code === 0 && parsed) {
55
+ resolve(parsed);
56
+ return;
57
+ }
58
+ reject(new Error(stderr.trim() || `normalize failed (${code ?? "unknown"})`));
59
+ }
60
+ catch (error) {
61
+ reject(error instanceof Error ? error : new Error(stderr.trim() || "Could not read that font."));
62
+ }
63
+ });
64
+ });
65
+ }
@@ -0,0 +1,10 @@
1
+ import { access } from "node:fs/promises";
2
+ export async function pathExists(path) {
3
+ try {
4
+ await access(path);
5
+ return true;
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ }
package/dist/glob.js ADDED
@@ -0,0 +1,59 @@
1
+ /** Minimal glob matcher for include/exclude. Supports *, **, ?, and {a,b}. */
2
+ function escapeRegExp(value) {
3
+ return value.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, "\\*");
4
+ }
5
+ function expandBraces(pattern) {
6
+ const match = pattern.match(/\{([^{}]+)\}/);
7
+ if (!match || match.index == null)
8
+ return [pattern];
9
+ const start = match.index;
10
+ const [token, inner] = match;
11
+ return inner.split(",").flatMap((choice) => expandBraces(pattern.slice(0, start) + choice + pattern.slice(start + token.length)));
12
+ }
13
+ function globToRegExp(pattern) {
14
+ const normalized = pattern.replaceAll("\\", "/");
15
+ let source = "^";
16
+ let i = 0;
17
+ while (i < normalized.length) {
18
+ if (normalized.startsWith("**/", i)) {
19
+ source += "(?:.*/)?";
20
+ i += 3;
21
+ continue;
22
+ }
23
+ if (normalized.startsWith("**", i)) {
24
+ source += ".*";
25
+ i += 2;
26
+ continue;
27
+ }
28
+ const ch = normalized[i];
29
+ if (ch === "*") {
30
+ source += "[^/]*";
31
+ }
32
+ else if (ch === "?") {
33
+ source += "[^/]";
34
+ }
35
+ else {
36
+ source += escapeRegExp(ch);
37
+ }
38
+ i += 1;
39
+ }
40
+ source += "$";
41
+ return new RegExp(source);
42
+ }
43
+ export function matchesGlob(relPath, pattern) {
44
+ const path = relPath.replaceAll("\\", "/");
45
+ const patterns = expandBraces(pattern);
46
+ return patterns.some((entry) => {
47
+ const trimmed = entry.replaceAll("\\", "/");
48
+ const direct = globToRegExp(trimmed);
49
+ if (direct.test(path))
50
+ return true;
51
+ if (!trimmed.includes("/")) {
52
+ return globToRegExp(`**/${trimmed}`).test(path);
53
+ }
54
+ return false;
55
+ });
56
+ }
57
+ export function matchesAny(relPath, patterns) {
58
+ return patterns.some((pattern) => matchesGlob(relPath, pattern));
59
+ }