glosslint 0.0.0 → 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/dist/cli.mjs ADDED
@@ -0,0 +1,591 @@
1
+ #!/usr/bin/env node
2
+ import { n as formatFindings, r as toJson } from "./format-CQ9xdJYe.mjs";
3
+ import { a as explain, c as testCorpus, d as createMatcher, i as readGlossary, m as kindOf, n as GLOSSARY_PROBLEMS, o as explainMatches, s as printCorpus, t as DEFAULT_GLOSSARY } from "./glossary-lk7EwGey.mjs";
4
+ import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
+ import { extname, relative, resolve, sep } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import process from "node:process";
8
+ import { cac } from "cac";
9
+ import { escapePath, glob, isDynamicPattern } from "tinyglobby";
10
+ // package.json
11
+ var version = "0.1.0";
12
+ // src/cli.ts
13
+ /** Codes of the errors the CLI prints itself, next to the corpus's `GLOSSLINT_C00x`. */
14
+ const CLI_ERRORS = {
15
+ noConfig: "GLOSSLINT_C009",
16
+ loadConfig: "GLOSSLINT_C010",
17
+ notCorpus: "GLOSSLINT_C008",
18
+ usage: "GLOSSLINT_USAGE",
19
+ failed: "GLOSSLINT_ERROR"
20
+ };
21
+ const CONFIG_FILES = [
22
+ "glosslint.config.ts",
23
+ "glosslint.config.mts",
24
+ "glosslint.config.js",
25
+ "glosslint.config.mjs"
26
+ ];
27
+ const DEFAULT_EXTENSIONS = [
28
+ "md",
29
+ "mdx",
30
+ "txt"
31
+ ];
32
+ const MARKDOWN = /* @__PURE__ */ new Set([
33
+ ".md",
34
+ ".mdx",
35
+ ".markdown"
36
+ ]);
37
+ /** An error the CLI prints as a tree and exits 2 on: a bad config or a bad command line. */
38
+ var CliError = class extends Error {
39
+ code;
40
+ why;
41
+ fix;
42
+ term;
43
+ config;
44
+ constructor(options) {
45
+ super(options.why);
46
+ this.code = options.code;
47
+ this.why = options.why;
48
+ this.fix = options.fix;
49
+ if (options.term !== void 0) this.term = options.term;
50
+ if (options.config !== void 0) this.config = options.config;
51
+ }
52
+ };
53
+ function isConfigError(error) {
54
+ return error instanceof Error && error.name === "GlosslintConfigError" && typeof error.code === "string" && typeof error.fix === "string";
55
+ }
56
+ function isCorpus(value) {
57
+ return typeof value === "object" && value !== null && value.kind === "glosslint.corpus" && Array.isArray(value.terms) && Array.isArray(value.allow);
58
+ }
59
+ const paint = (on, code, text) => on ? `\u001B[${code}m${text}\u001B[0m` : text;
60
+ const toPosix = (path) => path.split(sep).join("/");
61
+ function displayPath(cwd, file) {
62
+ return toPosix(relative(cwd, file)) || ".";
63
+ }
64
+ /**
65
+ * Finds the corpus: `config`, else `glossary`, else `glosslint.config.{ts,mts,js,mjs}` in `cwd`, else
66
+ * `.agents/glossary.md` in `cwd`.
67
+ */
68
+ async function loadCorpus(cwd, options = {}) {
69
+ const { config, glossary } = options;
70
+ if (config !== void 0 && glossary !== void 0) throw usage("--config and --glossary both name the corpus.", "Pass one of them: --glossary for a glossary file, --config for a config.");
71
+ if (config !== void 0) return importConfig(cwd, resolve(cwd, config), config);
72
+ if (glossary !== void 0) return loadGlossary(cwd, glossary, true);
73
+ const found = CONFIG_FILES.map((name) => resolve(cwd, name)).find((path) => existsSync(path));
74
+ if (found) return importConfig(cwd, found);
75
+ if (existsSync(resolve(cwd, ".agents/glossary.md"))) return loadGlossary(cwd, DEFAULT_GLOSSARY, false);
76
+ throw new CliError({
77
+ code: CLI_ERRORS.noConfig,
78
+ why: `No ${DEFAULT_GLOSSARY} and no glosslint.config.ts, .mts, .js or .mjs in the current folder.`,
79
+ fix: `Create ${DEFAULT_GLOSSARY} with \`# Glossary\` and a \`## Term\` section per term, or pass --glossary <path> or --config <path>.`
80
+ });
81
+ }
82
+ /** `G004` to `G008`: the problems only a person can fix, which leave no corpus. */
83
+ function leavesNoCorpus(problem) {
84
+ return !problem.fixable && problem.code !== GLOSSARY_PROBLEMS.failingExample;
85
+ }
86
+ function missingGlossary(cwd, file, given) {
87
+ const shown = displayPath(cwd, file);
88
+ return new CliError({
89
+ code: CLI_ERRORS.noConfig,
90
+ why: given ? `The glossary "${shown}" does not exist.` : `No glossary at ${shown}.`,
91
+ fix: given ? "Check the path given to --glossary." : `Create ${shown} with \`# Glossary\` and a \`## Term\` section per term, or pass --glossary <path>.`
92
+ });
93
+ }
94
+ /** Reads a glossary file as a corpus, or throws its first problem that leaves no corpus. */
95
+ function loadGlossary(cwd, path, given) {
96
+ const file = resolve(cwd, path);
97
+ if (!existsSync(file)) throw missingGlossary(cwd, file, given);
98
+ const { problems, corpus } = readGlossary(readFileSync(file, "utf8"));
99
+ if (corpus) return {
100
+ corpus,
101
+ file,
102
+ from: "glossary"
103
+ };
104
+ const blocking = problems.filter(leavesNoCorpus);
105
+ const first = blocking[0];
106
+ const doctor = given ? `glosslint doctor --glossary ${path}` : "glosslint doctor";
107
+ const more = blocking.length > 1 ? ` ${count(blocking.length - 1, "more problem")}: run \`${doctor}\` to list them.` : "";
108
+ throw new CliError({
109
+ code: first.code,
110
+ why: `${displayPath(cwd, file)}:${first.line}: ${first.why}`,
111
+ fix: `${first.fix}${more}`,
112
+ ...first.term === void 0 ? {} : { term: first.term }
113
+ });
114
+ }
115
+ /** Imports a config and returns its default export, which must be a corpus. */
116
+ async function importConfig(cwd, file, given) {
117
+ if (given !== void 0 && !existsSync(file)) throw new CliError({
118
+ code: CLI_ERRORS.noConfig,
119
+ why: `The config "${given}" does not exist.`,
120
+ fix: "Check the path given to --config."
121
+ });
122
+ const shown = displayPath(cwd, file);
123
+ let loaded;
124
+ try {
125
+ loaded = await import(pathToFileURL(file).href);
126
+ } catch (error) {
127
+ if (isConfigError(error)) throw Object.assign(error, { config: shown });
128
+ throw new CliError({
129
+ code: CLI_ERRORS.loadConfig,
130
+ why: `Could not load ${shown}: ${error instanceof Error ? error.message : String(error)}`,
131
+ fix: "Fix the error in the config, then run glosslint again.",
132
+ config: shown
133
+ });
134
+ }
135
+ if (!isCorpus(loaded.default)) throw new CliError({
136
+ code: CLI_ERRORS.notCorpus,
137
+ why: `${shown} does not export a corpus as its default export.`,
138
+ fix: "End the config with `export default defineCorpus({ … })`.",
139
+ config: shown
140
+ });
141
+ return {
142
+ corpus: loaded.default,
143
+ file,
144
+ from: "config"
145
+ };
146
+ }
147
+ /** Blanks a span with spaces, keeping line breaks, so every offset and line stays where it was. */
148
+ function blank(text) {
149
+ return text.replace(/[^\n\r]/g, " ");
150
+ }
151
+ const FRONTMATTER = /^(?:---|\+\+\+)\r?\n[\s\S]*?\r?\n(?:---|\+\+\+|\.\.\.)[ \t]*(?:\r?\n|$)/;
152
+ const FENCE = /^[ \t]*((?:>[ \t]?)*)[ \t]*((?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})([^\n]*)$/;
153
+ const HTML_COMMENT = /<!--[\s\S]*?(?:-->|$)/g;
154
+ const INLINE_CODE = /(?<!`)(`+)(?!`)(?:(?!\r?\n[ \t]*\r?\n)[\s\S])*?[^`]\1(?!`)/g;
155
+ const LINK_TARGET = /(?<=\])\((?:[^()\s]|\([^()\s]*\))*(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^()\n]*\)))?\s*\)/g;
156
+ const LINK_REFERENCE = /(?<=\])\[[^\]\n]*\]/g;
157
+ const REFERENCE_DEFINITION = /^ {0,3}\[[^\]\n]+\]:[ \t]*\S.*$/gm;
158
+ const AUTOLINK = /<(?:[a-z][a-z\d+.-]*:[^\s<>]*|[^\s<>@]+@[^\s<>]+)>/gi;
159
+ const TAG = /<\/?[A-Za-z][^<>]*>/g;
160
+ const LINE_PREFIX = /^( {0,3}(?:>[ \t]?)*)(#{1,6}(?=[ \t]|\r?$)|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t]))?([ \t]+\[[ xX]\](?=[ \t]))?/;
161
+ const HEADING = /^ {0,3}#{1,6}(?:[ \t]|\r?$)/;
162
+ const LIST_ITEM = /^ {0,3}(?:>[ \t]?)*(?:[-*+]|\d{1,9}[.)])[ \t]/;
163
+ /**
164
+ * Blanks what is not prose in Markdown, keeping every offset: frontmatter, fenced code, HTML
165
+ * comments and tags, inline code, link targets and references, and the markers of headings, lists
166
+ * and quotes. In MDX, `import` and `export` lines too.
167
+ */
168
+ function maskMarkdown(text, options = {}) {
169
+ let out = text.replace(FRONTMATTER, blank);
170
+ const lines = out.split("\n");
171
+ let fence;
172
+ for (const [index, line] of lines.entries()) {
173
+ const match = FENCE.exec(line);
174
+ const marker = match?.[3];
175
+ const depth = match?.[1]?.split(">").length ?? 0;
176
+ if (fence !== void 0) {
177
+ if (marker && !match[2] && depth === fence.depth && marker[0] === fence.marker[0] && marker.length >= fence.marker.length && match[4].trim() === "") fence = void 0;
178
+ lines[index] = blank(line);
179
+ } else if (marker) {
180
+ fence = {
181
+ marker,
182
+ depth
183
+ };
184
+ lines[index] = blank(line);
185
+ } else if (options.mdx && /^(?:import|export)\s/.test(line)) lines[index] = blank(line);
186
+ }
187
+ out = lines.join("\n");
188
+ out = out.replace(HTML_COMMENT, blank);
189
+ out = out.replace(INLINE_CODE, blank);
190
+ out = out.replace(REFERENCE_DEFINITION, blank);
191
+ out = out.replace(LINK_TARGET, blank);
192
+ out = out.replace(LINK_REFERENCE, blank);
193
+ out = out.replace(AUTOLINK, blank);
194
+ out = out.replace(TAG, blank);
195
+ return out.split("\n").map((line) => {
196
+ let masked = line.replace(LINE_PREFIX, blank);
197
+ if (HEADING.test(line)) masked = masked.replace(/[ \t]#+[ \t]*(?=\r?$)/, blank);
198
+ return masked;
199
+ }).join("\n");
200
+ }
201
+ const TABLE_DELIMITER = /^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*\r?$/;
202
+ /** Splits text into the pieces checked one at a time: headings, table cells, list items and paragraphs. */
203
+ function blocks(original, masked, markdown) {
204
+ const found = [];
205
+ let current;
206
+ const flush = () => {
207
+ if (current) found.push(current);
208
+ current = void 0;
209
+ };
210
+ let start = 0;
211
+ const lines = masked.split("\n");
212
+ for (const [index, line] of lines.entries()) {
213
+ const end = start + line.length;
214
+ const source = original.slice(start, end);
215
+ if (line.trim() === "") flush();
216
+ else if (markdown && HEADING.test(source)) {
217
+ flush();
218
+ found.push({
219
+ start,
220
+ end,
221
+ kind: "label"
222
+ });
223
+ } else if (markdown && source.trimStart().startsWith("|")) {
224
+ flush();
225
+ const header = TABLE_DELIMITER.test(lines[index + 1] ?? "");
226
+ let cellStart = start;
227
+ for (const cell of line.split("|")) {
228
+ if (cell.trim() !== "") found.push({
229
+ start: cellStart,
230
+ end: cellStart + cell.length,
231
+ kind: header ? "header" : kindOf({ text: cell })
232
+ });
233
+ cellStart += cell.length + 1;
234
+ }
235
+ } else if (markdown && LIST_ITEM.test(source)) {
236
+ flush();
237
+ current = {
238
+ start,
239
+ end,
240
+ kind: "sentence"
241
+ };
242
+ } else if (current) current.end = end;
243
+ else current = {
244
+ start,
245
+ end,
246
+ kind: "sentence"
247
+ };
248
+ start = end + 1;
249
+ }
250
+ flush();
251
+ return found;
252
+ }
253
+ function summarize(term) {
254
+ return {
255
+ term: term.term,
256
+ ...term.description ? { description: term.description } : {},
257
+ ...term.nuance ? { nuance: term.nuance } : {}
258
+ };
259
+ }
260
+ /** Checks one file's text. Markdown is masked first, so code and link targets are never reported. */
261
+ function checkFileText(matcher, text, file, options = {}) {
262
+ const markdown = options.markdown ?? false;
263
+ const masked = markdown ? maskMarkdown(text, { mdx: options.mdx ?? false }) : text;
264
+ const lineStarts = [0];
265
+ for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) lineStarts.push(index + 1);
266
+ const lineOf = (offset) => {
267
+ let low = 0;
268
+ let high = lineStarts.length - 1;
269
+ while (low < high) {
270
+ const mid = low + high + 1 >> 1;
271
+ if (lineStarts[mid] <= offset) low = mid;
272
+ else high = mid - 1;
273
+ }
274
+ return low;
275
+ };
276
+ const lineEnd = (line) => (lineStarts[line + 1] ?? text.length + 1) - 1;
277
+ const findings = [];
278
+ for (const block of blocks(text, masked, markdown)) for (const finding of matcher.check(masked.slice(block.start, block.end), block.kind)) {
279
+ const start = block.start + finding.start;
280
+ const end = block.start + finding.end;
281
+ const line = lineOf(start);
282
+ const lineStart = lineStarts[line];
283
+ findings.push(toCliFinding(finding, {
284
+ file,
285
+ text,
286
+ start,
287
+ end,
288
+ line,
289
+ lineStart,
290
+ lineEnd: lineEnd(lineOf(end))
291
+ }));
292
+ }
293
+ return findings;
294
+ }
295
+ function toCliFinding(finding, at) {
296
+ const { fix, term, start: _start, end: _end, ...rest } = finding;
297
+ const result = fix ? (at.text.slice(at.lineStart, at.start) + fix.replace + at.text.slice(at.end, at.lineEnd)).replace(/\s+/g, " ").trim() : void 0;
298
+ return {
299
+ code: rest.code,
300
+ file: at.file,
301
+ line: at.line + 1,
302
+ column: at.start - at.lineStart + 1,
303
+ start: at.start,
304
+ end: at.end,
305
+ text: at.text.slice(at.start, at.end),
306
+ message: rest.message,
307
+ ...rest.why ? { why: rest.why } : {},
308
+ ...fix && result !== void 0 ? { fix: {
309
+ ...fix,
310
+ result
311
+ } } : {},
312
+ term: summarize(term),
313
+ ...rest.see ? { see: rest.see } : {}
314
+ };
315
+ }
316
+ function usage(why, fix) {
317
+ return new CliError({
318
+ code: CLI_ERRORS.usage,
319
+ why,
320
+ fix
321
+ });
322
+ }
323
+ /** The files `check` reads: named files as they are, folders by extension, and glob patterns. */
324
+ async function collectFiles(paths, cwd, extensions = DEFAULT_EXTENSIONS) {
325
+ const files = /* @__PURE__ */ new Set();
326
+ const patterns = [];
327
+ const ext = extensions.length === 1 ? extensions[0] : `{${extensions.join(",")}}`;
328
+ for (const path of paths.length > 0 ? paths : ["."]) {
329
+ if (isDynamicPattern(path)) {
330
+ patterns.push(path);
331
+ continue;
332
+ }
333
+ const absolute = resolve(cwd, path);
334
+ if (!existsSync(absolute)) throw usage(`"${path}" does not exist.`, "Pass files, folders or glob patterns that exist.");
335
+ if (statSync(absolute).isDirectory()) {
336
+ const folder = toPosix(relative(cwd, absolute));
337
+ patterns.push(folder ? `${escapePath(folder)}/**/*.${ext}` : `**/*.${ext}`);
338
+ } else files.add(absolute);
339
+ }
340
+ if (patterns.length > 0) for (const file of await glob(patterns, {
341
+ cwd,
342
+ absolute: true,
343
+ ignore: ["**/node_modules/**", "**/.git/**"]
344
+ })) files.add(resolve(file));
345
+ return [...files].sort((a, b) => displayPath(cwd, a).localeCompare(displayPath(cwd, b)));
346
+ }
347
+ function useColor(options, io) {
348
+ return options.color ?? io.color ?? false;
349
+ }
350
+ function parseExtensions(ext) {
351
+ if (ext === void 0) return DEFAULT_EXTENSIONS;
352
+ const list = String(ext).split(",").map((item) => item.trim().replace(/^\./, "")).filter(Boolean);
353
+ if (list.length === 0) throw usage(`--ext is empty.`, "Pass extensions such as --ext md,mdx.");
354
+ return list;
355
+ }
356
+ /** `glosslint check`: reports every finding in the files, as text or JSON. Exits 1 on findings. */
357
+ async function runCheck(paths, options, io) {
358
+ const format = options.format ?? "text";
359
+ if (format !== "text" && format !== "json") throw usage(`--format is "${format}".`, "Use --format text or --format json.");
360
+ const extensions = parseExtensions(options.ext);
361
+ const loaded = await loadCorpus(io.cwd, options);
362
+ const matcher = createMatcher(loaded.corpus);
363
+ const files = (await collectFiles(paths, io.cwd, extensions)).filter((file) => loaded.from !== "glossary" || file !== loaded.file);
364
+ const findings = [];
365
+ for (const file of files) {
366
+ const extension = extname(file).toLowerCase();
367
+ findings.push(...checkFileText(matcher, readFileSync(file, "utf8"), displayPath(io.cwd, file), {
368
+ markdown: MARKDOWN.has(extension),
369
+ mdx: extension === ".mdx"
370
+ }));
371
+ }
372
+ if (format === "json") io.stdout(`${JSON.stringify(toJson(findings, files.length), null, 2)}\n`);
373
+ else io.stdout(`${formatFindings(findings, {
374
+ color: useColor(options, io),
375
+ files: files.length
376
+ })}\n`);
377
+ return findings.length > 0 ? 1 : 0;
378
+ }
379
+ function describe(finding) {
380
+ if (finding.code === "GLOSSLINT_AVOID") return `"${finding.text}" is an avoid word for ${finding.term.term}.`;
381
+ const replace = finding.fix?.replace ?? finding.term.term;
382
+ return finding.code === "GLOSSLINT_CASE" ? `"${finding.text}" is written "${replace}".` : `"${finding.text}" is spelled "${replace}".`;
383
+ }
384
+ function failureLines(failure) {
385
+ const key = failure.term.term;
386
+ if (failure.expected === "none") {
387
+ const about = failure.findings.filter((finding) => finding.term.term === key);
388
+ const avoid = about.some((finding) => finding.code === "GLOSSLINT_AVOID");
389
+ return [
390
+ `good example "${failure.example}" was flagged:`,
391
+ ...about.map(describe),
392
+ avoid ? "└ narrow the avoid word or move the example" : "└ fix the example or the term's spelling"
393
+ ];
394
+ }
395
+ if (failure.findings.length === 0) return [`bad example "${failure.example}" was not flagged.`, "└ add the wording to \"avoid\" or fix the example"];
396
+ return [
397
+ `bad example "${failure.example}" was flagged only for other terms:`,
398
+ ...failure.findings.map(describe),
399
+ "└ add the wording to \"avoid\" or fix the example"
400
+ ];
401
+ }
402
+ const count = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
403
+ /** `glosslint test`: checks every term's good and bad examples. Exits 1 when one fails. */
404
+ async function runTest(options, io) {
405
+ const { corpus } = await loadCorpus(io.cwd, options);
406
+ const color = useColor(options, io);
407
+ const tested = corpus.terms.filter((term) => (term.examples?.good?.length ?? 0) + (term.examples?.bad?.length ?? 0) > 0);
408
+ if (tested.length === 0) {
409
+ io.stdout("No term has examples.\n");
410
+ return 0;
411
+ }
412
+ const failures = testCorpus(corpus);
413
+ const width = Math.max(...tested.map((term) => term.term.length)) + 2;
414
+ const indent = " ".repeat(width + 2);
415
+ const lines = [];
416
+ let failing = 0;
417
+ for (const term of tested) {
418
+ const own = failures.filter((failure) => failure.term === term);
419
+ const name = term.term.padEnd(width);
420
+ if (own.length === 0) {
421
+ const good = term.examples?.good?.length ?? 0;
422
+ const bad = term.examples?.bad?.length ?? 0;
423
+ lines.push(`${paint(color, "32", "✓")} ${name}${good} good, ${bad} bad`);
424
+ continue;
425
+ }
426
+ failing++;
427
+ const details = own.flatMap(failureLines);
428
+ lines.push(`${paint(color, "31", "✗")} ${name}${details[0]}`);
429
+ for (const detail of details.slice(1)) lines.push(`${indent}${detail}`);
430
+ }
431
+ io.stdout(`${lines.join("\n")}\n\n${count(tested.length, "term")}, ${failing} failing.\n`);
432
+ return failing > 0 ? 1 : 0;
433
+ }
434
+ /** `glosslint print`: writes the corpus as a Markdown glossary or as JSON. */
435
+ async function runPrint(options, io) {
436
+ const format = options.format ?? "md";
437
+ if (format !== "md" && format !== "json") throw usage(`--format is "${format}".`, "Use --format md or --format json.");
438
+ const { corpus } = await loadCorpus(io.cwd, options);
439
+ io.stdout(printCorpus(corpus, format));
440
+ return 0;
441
+ }
442
+ /** `glosslint explain`: what the corpus says about a word or phrase. Exits 1 when no term matches. */
443
+ async function runExplain(query, options, io) {
444
+ const { corpus } = await loadCorpus(io.cwd, options);
445
+ io.stdout(`${explain(corpus, query)}\n`);
446
+ return explainMatches(corpus, query).length > 0 ? 0 : 1;
447
+ }
448
+ function formatProblem(problem, color) {
449
+ const lines = [["fix", problem.fix]];
450
+ if (problem.term && !problem.why.includes(`"${problem.term}"`)) lines.unshift(["term", problem.term]);
451
+ const branches = lines.map(([label, text], index) => {
452
+ const branch = index === lines.length - 1 ? "╰▶" : "├▶";
453
+ return `${paint(color, "2", branch)} ${paint(color, "1", `${label}:`)} ${text}`;
454
+ });
455
+ const where = paint(color, "36", `${problem.file}:${problem.line}`);
456
+ return [`${paint(color, "1;31", `[${problem.code}]`)} ${where}: ${problem.why}`, ...branches].join("\n");
457
+ }
458
+ /**
459
+ * `glosslint doctor`: reports the problems of the glossary file, and with `fix` rewrites it in canonical
460
+ * form when no problem would drop text. Exits 0 with no problems left, 1 with problems, 2 with no file.
461
+ */
462
+ async function runDoctor(options, io) {
463
+ const format = options.format ?? "text";
464
+ if (format !== "text" && format !== "json") throw usage(`--format is "${format}".`, "Use --format text or --format json.");
465
+ const file = resolve(io.cwd, options.glossary ?? ".agents/glossary.md");
466
+ if (!existsSync(file)) throw missingGlossary(io.cwd, file, options.glossary !== void 0);
467
+ const shown = displayPath(io.cwd, file);
468
+ let result = readGlossary(readFileSync(file, "utf8"));
469
+ let fixed = 0;
470
+ if (options.fix && result.fixed !== void 0) {
471
+ fixed = result.problems.filter((problem) => problem.fixable).length;
472
+ writeFileSync(file, result.fixed);
473
+ result = readGlossary(result.fixed);
474
+ }
475
+ const problems = result.problems.map((problem) => ({
476
+ file: shown,
477
+ ...problem
478
+ }));
479
+ const fixable = problems.filter((problem) => problem.fixable).length;
480
+ if (format === "json") {
481
+ const report = {
482
+ problems,
483
+ summary: {
484
+ file: shown,
485
+ problems: problems.length,
486
+ fixable,
487
+ fixed
488
+ }
489
+ };
490
+ io.stdout(`${JSON.stringify(report, null, 2)}\n`);
491
+ return problems.length > 0 ? 1 : 0;
492
+ }
493
+ const color = useColor(options, io);
494
+ const summary = [];
495
+ if (fixed > 0) summary.push(`Fixed ${count(fixed, "problem")} in ${shown}.`);
496
+ if (problems.length === 0) {
497
+ if (fixed === 0) summary.push(`No problems in ${shown}.`);
498
+ } else if (fixed > 0) summary.push(`${count(problems.length, "problem")} left.`);
499
+ else {
500
+ const canFix = result.fixed !== void 0 ? `, ${fixable} fixable with --fix` : "";
501
+ summary.push(`${count(problems.length, "problem")} in ${shown}${canFix}.`);
502
+ if (options.fix && fixable > 0) summary.push("The file is unchanged: --fix would drop text, so fix the other problems first.");
503
+ }
504
+ const blocks = problems.map((problem) => formatProblem(problem, color));
505
+ io.stdout(`${[...blocks, summary.join(" ")].join("\n\n")}\n`);
506
+ return problems.length > 0 ? 1 : 0;
507
+ }
508
+ /** Prints a config or usage error as a tree on stderr. */
509
+ function printError(error, io, color) {
510
+ const branches = [];
511
+ if (error.term && !error.why.includes(`"${error.term}"`)) branches.push(["term", error.term]);
512
+ branches.push(["fix", error.fix]);
513
+ if (error.config) branches.push(["config", error.config]);
514
+ const lines = branches.map(([label, text], index) => {
515
+ const branch = index === branches.length - 1 ? "╰▶" : "├▶";
516
+ return `${paint(color, "2", branch)} ${paint(color, "1", `${label}:`)} ${text}`;
517
+ });
518
+ io.stderr(`${[`${paint(color, "1;31", `[${error.code}]`)} ${error.why}`, ...lines].join("\n")}\n`);
519
+ }
520
+ function defaultIo() {
521
+ return {
522
+ cwd: process.cwd(),
523
+ stdout: (text) => process.stdout.write(text),
524
+ stderr: (text) => process.stderr.write(text),
525
+ color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR
526
+ };
527
+ }
528
+ /** Runs the CLI on `argv` (the arguments after the program name) and resolves to the exit code. */
529
+ async function main(argv, io = defaultIo()) {
530
+ const cli = cac("glosslint");
531
+ let run;
532
+ let color = io.color ?? false;
533
+ const configOption = "Config file (default: glosslint.config.{ts,mts,js,mjs})";
534
+ const glossaryOption = `Glossary file, read when there is no config (default: ${DEFAULT_GLOSSARY})`;
535
+ const colorOption = "Color the output (default: when writing to a terminal)";
536
+ cli.command("[...paths]", "Check Markdown and text files against the corpus").alias("check").option("--glossary <path>", glossaryOption).option("--config <path>", configOption).option("--format <format>", "Output format: text or json", { default: "text" }).option("--ext <list>", "Extensions read in folders, comma-separated (default: md,mdx,txt)").option("--color", colorOption).action((paths, options) => {
537
+ run = () => runCheck(paths, options, io);
538
+ });
539
+ cli.command("test", "Check every term's good and bad examples").option("--glossary <path>", glossaryOption).option("--config <path>", configOption).option("--color", colorOption).action((options) => {
540
+ run = () => runTest(options, io);
541
+ });
542
+ cli.command("print", "Print the corpus as a Markdown glossary or JSON").option("--glossary <path>", glossaryOption).option("--config <path>", configOption).option("--format <format>", "Output format: md or json", { default: "md" }).action((options) => {
543
+ run = () => runPrint(options, io);
544
+ });
545
+ cli.command("explain <query>", "Show what the corpus says about a word or phrase").option("--glossary <path>", glossaryOption).option("--config <path>", configOption).action((query, options) => {
546
+ run = () => runExplain(String(query), options, io);
547
+ });
548
+ cli.command("doctor", "Report the glossary file's problems, and fix the ones it can with --fix").option("--glossary <path>", `Glossary file (default: ${DEFAULT_GLOSSARY})`).option("--fix", "Rewrite the file in canonical form, unless that would drop text").option("--format <format>", "Output format: text or json", { default: "text" }).option("--color", colorOption).action((options) => {
549
+ run = () => runDoctor(options, io);
550
+ });
551
+ cli.help();
552
+ cli.version(version);
553
+ try {
554
+ const parsed = cli.parse([
555
+ "node",
556
+ "glosslint",
557
+ ...argv
558
+ ], { run: false });
559
+ if (typeof parsed.options.color === "boolean") color = parsed.options.color;
560
+ if (!cli.matchedCommand) return 0;
561
+ cli.runMatchedCommand();
562
+ return run ? await run() : 0;
563
+ } catch (error) {
564
+ if (error instanceof CliError || isConfigError(error)) {
565
+ printError(error, io, color);
566
+ return 2;
567
+ }
568
+ if (error instanceof Error && error.name === "CACError") {
569
+ printError({
570
+ code: CLI_ERRORS.usage,
571
+ why: `${error.message}.`,
572
+ fix: "Run glosslint --help for the commands and options."
573
+ }, io, color);
574
+ return 2;
575
+ }
576
+ const message = error instanceof Error ? error.message : String(error);
577
+ io.stderr(`${paint(color, "1;31", `[${CLI_ERRORS.failed}]`)} ${message.split("\n")[0]}\n`);
578
+ return 2;
579
+ }
580
+ }
581
+ function isBin() {
582
+ const entry = process.argv[1];
583
+ if (!entry) return false;
584
+ try {
585
+ return import.meta.url === pathToFileURL(realpathSync(entry)).href;
586
+ } catch {
587
+ return false;
588
+ }
589
+ }
590
+ if (isBin()) process.exitCode = await main(process.argv.slice(2));
591
+ export { CLI_ERRORS, checkFileText, collectFiles, loadCorpus, main, maskMarkdown, runCheck, runDoctor, runExplain, runPrint, runTest };
@@ -0,0 +1,29 @@
1
+ import { c as Corpus, h as KindOf } from "./types-Bbp_cYfZ.mjs";
2
+ import { Linter } from "eslint";
3
+ /** Options of the ESLint config. */
4
+ export interface GlosslintEslintOptions {
5
+ /** The glossary file to read instead of `.agents/glossary.md`. A string resolves from the current folder. */
6
+ glossary?: string | URL;
7
+ /** A corpus to use instead of a glossary file, such as `defineCorpus({ extends: [fromGlossary()], … })`. */
8
+ corpus?: Corpus;
9
+ /** Files the rules run on. */
10
+ files?: string[];
11
+ /**
12
+ * Callees whose first argument is never checked, added to `t`, `$t`, `te` and `tm`. Defaults to
13
+ * `endsWith`, `startsWith`, `includes` and `querySelector*`; a name ending in `*` matches as a prefix.
14
+ */
15
+ ignoreCallees?: string[];
16
+ /** Report avoid words in declared names too. Off by default, since a rename touches every caller. */
17
+ identifierAvoid?: boolean;
18
+ /**
19
+ * Decides whether a string is a label, header or sentence before glosslint's own `kindOf`, from its
20
+ * text, name and file. Return `undefined` to leave a string to glosslint.
21
+ */
22
+ kindOf?: KindOf;
23
+ }
24
+ /**
25
+ * ESLint flat configs that run glosslint's rules: `...glosslint()`. The corpus comes from `corpus`, else
26
+ * from the `glossary` file, else from `.agents/glossary.md`, read once when the config is built. They set
27
+ * no parser: your config supplies typescript-eslint, vue-eslint-parser or yaml-eslint-parser.
28
+ */
29
+ export default function glosslint(options?: GlosslintEslintOptions): Linter.Config[];
@@ -0,0 +1,39 @@
1
+ import { h as CONFIG_ERRORS, r as fromGlossary, y as GlosslintConfigError } from "./glossary-lk7EwGey.mjs";
2
+ import { n as DEFAULT_IGNORE_CALLEES, t as createRules } from "./rules-D-PrDySk.mjs";
3
+ // src/eslint.ts
4
+ /**
5
+ * ESLint flat configs that run glosslint's rules: `...glosslint()`. The corpus comes from `corpus`, else
6
+ * from the `glossary` file, else from `.agents/glossary.md`, read once when the config is built. They set
7
+ * no parser: your config supplies typescript-eslint, vue-eslint-parser or yaml-eslint-parser.
8
+ */
9
+ function glosslint(options = {}) {
10
+ if (options.corpus && options.glossary !== void 0) throw new GlosslintConfigError({
11
+ code: CONFIG_ERRORS.glossaryAndCorpus,
12
+ why: "glosslint() takes `glossary` or `corpus`, not both.",
13
+ fix: "Pass `glossary` to read a file, or `corpus` with `extends: [fromGlossary(…)]` to add to one."
14
+ });
15
+ const binding = {
16
+ corpus: options.corpus ?? fromGlossary(options.glossary),
17
+ settings: {
18
+ ignoreCallees: options.ignoreCallees ?? DEFAULT_IGNORE_CALLEES,
19
+ identifierAvoid: options.identifierAvoid ?? false,
20
+ ...options.kindOf ? { kindOf: options.kindOf } : {}
21
+ }
22
+ };
23
+ const plugin = {
24
+ meta: { name: "glosslint" },
25
+ rules: createRules(() => binding)
26
+ };
27
+ return [{
28
+ name: "glosslint",
29
+ ...options.files ? { files: options.files } : {},
30
+ plugins: { glosslint: plugin },
31
+ rules: {
32
+ "glosslint/term": "error",
33
+ "glosslint/avoid": "error",
34
+ "glosslint/comment": "error",
35
+ "glosslint/identifier": "warn"
36
+ }
37
+ }];
38
+ }
39
+ export { glosslint as default };