@mark1russell7/api-report 0.5.2 → 0.5.3

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.
@@ -2,6 +2,25 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSyn
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { globFolders, reportFolders, workspaceGlobs } from "@mark1russell7/conventions/workspace";
4
4
  // src/declarations.ts
5
+ /**
6
+ * This function gives the text of a doc comment: the lines without the `/**` and `*` marks and the
7
+ * spaces at their ends. The first line also loses the spaces at its start. The lines without a `*` mark
8
+ * lose only their common indent. The result keeps the tags, for example `@param`, and the indent after a
9
+ * `*` mark.
10
+ */
11
+ function docText(comment) {
12
+ const inner = comment.replace(/^\/\*\*/, "").replace(/\*\/$/, "").split("\n");
13
+ const marked = (line, index) => index > 0 && /^\s*\*/.test(line);
14
+ const bare = inner.filter((line, index) => index > 0 && !marked(line, index) && line.trim() !== "");
15
+ const indent = bare.length === 0 ? 0 : Math.min(...bare.map((line) => line.length - line.trimStart().length));
16
+ const lines = inner.map((line, index) => {
17
+ if (index === 0) return line.trim();
18
+ return (marked(line, index) ? line.replace(/^\s*\* ?/, "") : line.slice(indent)).trimEnd();
19
+ });
20
+ while (lines.length > 0 && lines[0]?.trim() === "") lines.shift();
21
+ while (lines.length > 0 && lines.at(-1)?.trim() === "") lines.pop();
22
+ return lines.join("\n");
23
+ }
5
24
  const BLOCK_HEADER = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+class|class|interface|const\s+enum|enum|namespace|module|global)\b/;
6
25
  const NAME_START = String.raw`[\p{ID_Start}$_]`;
7
26
  const NAME_PART = String.raw`[\p{ID_Continue}$‌‍]`;
@@ -28,16 +47,30 @@ const DECLARATION = unicode`^(export )?(default )?(?:declare )?(?:abstract )?(?:
28
47
  * comments, the blank lines and the spaces at the ends of the lines.
29
48
  */
30
49
  function statementsOf(source) {
50
+ return documentedStatementsOf(source).map(({ statement }) => statement);
51
+ }
52
+ /**
53
+ * This function splits the text of a declaration file into its top-level statements, as `statementsOf`
54
+ * does. Each statement also has the text of the last doc comment before it at the top level.
55
+ */
56
+ function documentedStatementsOf(source) {
31
57
  const text = source.replace(/\r\n?/g, "\n").replace(/^#![^\n]*\n?/, "");
32
58
  const statements = [];
33
59
  let current = "";
60
+ let doc;
34
61
  let depth = 0;
35
62
  let angle = 0;
36
63
  let body = false;
37
64
  const modes = [];
38
65
  const finish = () => {
39
66
  const lines = current.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim() !== "");
40
- if (lines.length > 0) statements.push(lines.join("\n"));
67
+ if (lines.length > 0) {
68
+ statements.push({
69
+ statement: lines.join("\n"),
70
+ doc
71
+ });
72
+ doc = void 0;
73
+ }
41
74
  current = "";
42
75
  angle = 0;
43
76
  body = false;
@@ -74,7 +107,9 @@ function statementsOf(source) {
74
107
  }
75
108
  if (char === "/" && next === "*") {
76
109
  const end = text.indexOf("*/", index + 2);
77
- index = end < 0 ? text.length : end + 2;
110
+ const stop = end < 0 ? text.length : end + 2;
111
+ if (text.startsWith("/**", index) && text.charAt(index + 3) !== "/" && modes.length === 0 && depth === 0 && current.trim() === "") doc = docText(text.slice(index, stop));
112
+ index = stop;
78
113
  current += " ";
79
114
  continue;
80
115
  }
@@ -166,15 +201,20 @@ function parseDeclarations(source, file = "<text>") {
166
201
  namespaces: [],
167
202
  imports: /* @__PURE__ */ new Map(),
168
203
  ambient: /* @__PURE__ */ new Map(),
169
- references: /* @__PURE__ */ new Set()
204
+ references: /* @__PURE__ */ new Set(),
205
+ docs: /* @__PURE__ */ new Map()
170
206
  };
207
+ let doc;
171
208
  const addLocal = (name, statement) => {
172
209
  info.locals.set(name, [...info.locals.get(name) ?? [], statement]);
210
+ if (doc !== void 0 && doc !== "" && !info.docs.has(name)) info.docs.set(name, doc);
173
211
  };
174
212
  const addAmbient = (label, statement) => {
175
213
  info.ambient.set(label, [...info.ambient.get(label) ?? [], statement]);
176
214
  };
177
- for (const statement of statementsOf(source)) {
215
+ for (const documented of documentedStatementsOf(source)) {
216
+ const { statement } = documented;
217
+ doc = documented.doc;
178
218
  const flat = statement.replace(/\s+/g, " ");
179
219
  for (const found of flat.matchAll(/\bimport\(\s*["']([^"']+)["']\s*\)/g)) info.references.add(found[1] ?? "");
180
220
  let match;
@@ -692,261 +732,6 @@ function binsOf(manifest) {
692
732
  path
693
733
  })).sort((a, b) => byCode(a.name, b.name));
694
734
  }
695
- // src/page.ts
696
- /**
697
- * The check of a hand-written page of an API against the report of its package. A page can explain each
698
- * call, and the check holds its names. Each export shows in the code of the page. The page gives no name
699
- * as an export that the package does not have.
700
- */
701
- /** This function gives the names of each entry of a report, by the subpath of the entry. The members of a namespace are not in the result. */
702
- function reportEntries(report) {
703
- const entries = /* @__PURE__ */ new Map();
704
- let current = null;
705
- for (const line of report.split("\n")) {
706
- if (line.startsWith("## ")) {
707
- const subpath = /^## (\.\S*?)(?: \(.*\))?: /.exec(line)?.[1];
708
- current = null;
709
- if (subpath !== void 0) {
710
- const names = /* @__PURE__ */ new Set();
711
- entries.set(subpath, names);
712
- if (line.endsWith(" names")) current = names;
713
- }
714
- continue;
715
- }
716
- const name = /^(?:type )?([^\s:]+): /.exec(line)?.[1];
717
- if (current !== null && name !== void 0 && name !== "ambient" && !name.includes(".")) current.add(name);
718
- }
719
- return entries;
720
- }
721
- /** This function gives the code blocks and the code spans of a Markdown text. */
722
- function codeOf(text) {
723
- const blocks = [];
724
- const prose = [];
725
- let fence = null;
726
- let block = [];
727
- for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
728
- const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
729
- if (fence === null) {
730
- if (mark === void 0) prose.push(line);
731
- else {
732
- fence = mark;
733
- block = [];
734
- }
735
- } else if (mark !== void 0 && mark[0] === fence[0] && mark.length >= fence.length) {
736
- blocks.push(block.join("\n"));
737
- fence = null;
738
- } else block.push(line);
739
- }
740
- if (fence !== null) blocks.push(block.join("\n"));
741
- return {
742
- blocks,
743
- spans: [...prose.join("\n").matchAll(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g)].map((match) => match[2] ?? "")
744
- };
745
- }
746
- /** This function is true if the code has `name` as a whole word. */
747
- function hasWord(code, name) {
748
- const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
749
- return new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`).test(code);
750
- }
751
- /**
752
- * This function gives the faults of the pages of a package against its report.
753
- *
754
- * An export must show in a code block or a code span of a page. An import from the package in a code block
755
- * must name an export of that entry. A signature, an `interface` or a `type` in a code block must be an
756
- * export of an entry. An exception needs a reason, and an exception that removes no fault is also a fault.
757
- * When `complete` is true, a different page shows each export, so the first rule does not apply.
758
- */
759
- function pageFaults(report, packageName, pages, except = {}, complete = false) {
760
- const entries = reportEntries(report);
761
- const all = new Set([...entries.values()].flatMap((names) => [...names]));
762
- const code = pages.map(codeOf);
763
- const blocks = code.flatMap((item) => item.blocks);
764
- const text = [...blocks, ...code.flatMap((item) => item.spans)].join("\n");
765
- const faults = /* @__PURE__ */ new Map();
766
- const used = /* @__PURE__ */ new Set();
767
- const fault = (name, words) => {
768
- if (Object.hasOwn(except, name)) used.add(name);
769
- else if (!faults.has(name)) faults.set(name, `${name}: ${words}`);
770
- };
771
- if (!complete) {
772
- for (const name of all) if (!hasWord(text, name)) fault(name, "the package exports this name, and no code on the page shows it.");
773
- }
774
- for (const block of blocks) {
775
- for (const match of block.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
776
- const source = match[2] ?? "";
777
- if (source !== packageName && !source.startsWith(`${packageName}/`)) continue;
778
- const names = entries.get(`.${source.slice(packageName.length)}`);
779
- if (names === void 0) {
780
- fault(source, "the page imports from this path, and the package has no such entry.");
781
- continue;
782
- }
783
- for (const part of (match[1] ?? "").split(",")) {
784
- const name = part.replace(/^\s*type\s+/, "").split(/\s+as\s+/)[0]?.trim() ?? "";
785
- if (name !== "" && name !== "default" && !names.has(name)) fault(name, `the page imports this name from ${source}, and that entry does not export it.`);
786
- }
787
- }
788
- for (const line of block.split("\n")) {
789
- const name = /^\s*(?:export\s+)?(?:declare\s+)?function\s+([\w$]+)\s*[<(].*;\s*(?:\/\/.*)?$/.exec(line)?.[1] ?? /^\s*(?:export\s+)?(?:declare\s+)?(?:interface|type)\s+([\w$]+)/.exec(line)?.[1];
790
- if (name !== void 0 && !all.has(name)) fault(name, "the page gives the declaration of this name, and the package does not export it.");
791
- }
792
- }
793
- for (const [name, reason] of Object.entries(except)) if (reason.trim() === "") faults.set(name, `${name}: the exception has no reason.`);
794
- else if (!used.has(name)) faults.set(name, `${name}: the exception removes no fault, so remove it.`);
795
- return [...faults.entries()].sort(([a], [b]) => byCode(a, b)).map(([, words]) => words);
796
- }
797
- // src/reference.ts
798
- /** This function gives the entries of a report and the text of each declaration. */
799
- function readReport(report) {
800
- const entries = [];
801
- const declarations = /* @__PURE__ */ new Map();
802
- let items = null;
803
- let key = null;
804
- let body = [];
805
- const close = () => {
806
- if (key !== null) declarations.set(key, body.join("\n").trimEnd());
807
- };
808
- let inDeclarations = false;
809
- for (const line of report.replace(/\r\n/g, "\n").split("\n")) {
810
- if (inDeclarations) {
811
- const next = /^### (.+)$/.exec(line)?.[1];
812
- if (next === void 0) body.push(line);
813
- else {
814
- close();
815
- key = next;
816
- body = [];
817
- }
818
- continue;
819
- }
820
- if (line.startsWith("## ")) {
821
- inDeclarations = line === "## Declarations";
822
- const subpath = /^## (\.\S*?)(?: \(.*\))?: /.exec(line)?.[1];
823
- items = null;
824
- if (subpath !== void 0) {
825
- const lines = [];
826
- entries.push({
827
- subpath,
828
- items: lines
829
- });
830
- if (line.endsWith(" names")) items = lines;
831
- }
832
- continue;
833
- }
834
- if (items === null) continue;
835
- const match = /^(type )?(.+?): (\S+)(?: \((namespace|external)\))?$/.exec(line);
836
- if (match === null) continue;
837
- const name = match[2] ?? "";
838
- const kind = name === "ambient" ? "ambient" : match[4] ?? "declaration";
839
- items.push({
840
- name,
841
- key: match[3] ?? "",
842
- isType: match[1] !== void 0,
843
- kind
844
- });
845
- }
846
- close();
847
- return {
848
- entries,
849
- declarations
850
- };
851
- }
852
- /** This function gives a fenced block of TypeScript. The fence is longer than each run of backticks in the code. */
853
- function fenced(code) {
854
- const longest = Math.max(2, ...[...code.matchAll(/`+/g)].map((match) => match[0].length));
855
- const fence = "`".repeat(longest + 1);
856
- return `${fence}ts\n${code}\n${fence}`;
857
- }
858
- /** The most characters of a line of an import list. */
859
- const IMPORT_WIDTH = 100;
860
- /** This function gives an import of `names` from `path`, with a line break at `IMPORT_WIDTH`. */
861
- function importOf(names, path) {
862
- const lines = [];
863
- let line = " ";
864
- for (const name of names) {
865
- if (line.length + name.length + 2 > IMPORT_WIDTH) {
866
- lines.push(line);
867
- line = " ";
868
- }
869
- line += ` ${name},`;
870
- }
871
- lines.push(line);
872
- return `import {\n${lines.join("\n")}\n} from ${JSON.stringify(path)};`;
873
- }
874
- /** This function removes the words `export` and `declare` from the start of each statement of a declaration. `declare global` and `declare module` keep the word. */
875
- function plain(declaration) {
876
- return declaration.replace(/^(?:export )?(?:declare (?!global\b|module\b))?/gm, "");
877
- }
878
- /** This pattern finds a name that a bundler changed, to keep two declarations apart: `grid$1`. */
879
- const BUNDLER_NAME = /\$\d+$/;
880
- /** This function gives the name of the declaration of a line of a report. */
881
- function localName(item) {
882
- return item.key.slice(item.key.lastIndexOf("#") + 1);
883
- }
884
- /** This function puts the name of each export of `items` in `code`, where a bundler changed that name. */
885
- function withExportNames(code, items) {
886
- let text = code;
887
- for (const item of items) {
888
- const local = localName(item);
889
- if (!BUNDLER_NAME.test(local) || item.name.includes(".") || item.kind !== "declaration") continue;
890
- const word = new RegExp(`(?<![\\w$])${local.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&")}(?![\\w$])`, "g");
891
- text = text.replace(word, () => item.name);
892
- }
893
- return text;
894
- }
895
- /**
896
- * This function gives the Markdown of the page of each export of a package. Each entry has an import with its
897
- * names. A declaration shows one time, in the first entry that reaches it. A comment tells the name of an
898
- * export when the source gave the declaration a different name. A name from a bundler does not show. A
899
- * comment also tells the package of an external name.
900
- *
901
- * The fields of `frontmatter` go into the front matter, after the title and the description. A field `title` or
902
- * `description` replaces the default.
903
- */
904
- function referencePage(report, packageName, frontmatter = {}) {
905
- const { entries, declarations } = readReport(report);
906
- const fields = {
907
- title: `Each export of ${packageName}`,
908
- description: `Each entry point of ${packageName}, with its exports and their declarations.`,
909
- ...frontmatter
910
- };
911
- const out = [
912
- "---",
913
- "# The command `api-report update` writes this file from the report of the package. Do not edit it.",
914
- ...Object.entries(fields).map(([key, value]) => `${key}: ${JSON.stringify(value)}`),
915
- "---",
916
- "",
917
- "The report of the API of the package makes this page, so the page and the package have the same names. Each section is one entry point. A declaration shows one time, in the first section that has it."
918
- ];
919
- const seen = /* @__PURE__ */ new Set();
920
- for (const entry of entries) {
921
- const path = `${packageName}${entry.subpath.slice(1)}`;
922
- out.push("", `## \`${path}\``, "");
923
- if (entry.items.length === 0) {
924
- out.push("This entry has no declarations.");
925
- continue;
926
- }
927
- const top = entry.items.filter((item) => item.kind !== "ambient" && !item.name.includes(".") && !item.name.startsWith("* "));
928
- const blocks = top.length > 0 ? [fenced(importOf(top.map((item) => `${item.isType ? "type " : ""}${item.name === "default" ? "default as defaultExport" : item.name}`), path))] : [];
929
- const parts = [];
930
- for (const item of entry.items) {
931
- if (seen.has(`${item.name} ${item.key}`)) continue;
932
- seen.add(`${item.name} ${item.key}`);
933
- if (item.kind === "external") {
934
- const from = item.key.slice(0, item.key.lastIndexOf("#"));
935
- parts.push(`// ${item.name} comes from the package ${from}.`);
936
- continue;
937
- }
938
- const text = declarations.get(item.key);
939
- if (text === void 0 || seen.has(item.key)) continue;
940
- seen.add(item.key);
941
- const local = localName(item);
942
- const label = item.kind === "ambient" || local === item.name || BUNDLER_NAME.test(local) ? "" : `// The export ${item.name}:\n`;
943
- parts.push(`${label}${plain(text)}`);
944
- }
945
- if (parts.length > 0) blocks.push(fenced(withExportNames(parts.join("\n\n"), entry.items)));
946
- out.push(blocks.join("\n\n"));
947
- }
948
- return `${out.join("\n")}\n`;
949
- }
950
735
  // src/report.ts
951
736
  /**
952
737
  * The report of the public API of a package, from its built `.d.ts` files.
@@ -1179,6 +964,10 @@ const HEADER_LINES = 5;
1179
964
  * entry, the bins of the manifest, and then the declaration of each name.
1180
965
  */
1181
966
  function apiReport(packageName, root, entries, options = {}) {
967
+ return documentedReport(packageName, root, entries, options).text;
968
+ }
969
+ /** This function gives the report of `apiReport`, and the doc comment of each declaration of the report. */
970
+ function documentedReport(packageName, root, entries, options = {}) {
1182
971
  const manifest = options.manifest ?? {};
1183
972
  const reader = new Reader(root, manifest);
1184
973
  const entryFiles = entries.flatMap((entry) => entry.types === void 0 ? [] : [resolve(root, entry.types)]).filter((file) => existsSync(file));
@@ -1192,6 +981,7 @@ function apiReport(packageName, root, entries, options = {}) {
1192
981
  };
1193
982
  const keyOf = (binding) => binding.kind === "declaration" ? `${path(binding.file)}#${binding.local}` : binding.kind === "namespace" ? `${path(binding.file)}#*` : `${binding.module}#${binding.name}`;
1194
983
  const declarations = /* @__PURE__ */ new Map();
984
+ const docs = /* @__PURE__ */ new Map();
1195
985
  const lines = header(packageName, options.tool ?? "api-report");
1196
986
  if (entries.every((entry) => entry.types === void 0)) lines.push("", "This package has no type declarations: no entry of its package.json gives a .d.ts file.");
1197
987
  /** The lines of the names of a module, and the names of each namespace in it, with `prefix`. */
@@ -1200,7 +990,12 @@ function apiReport(packageName, root, entries, options = {}) {
1200
990
  const key = keyOf(binding);
1201
991
  const isType = typeOnly || binding.typeOnly;
1202
992
  lines.push(`${isType ? "type " : ""}${prefix}${name}: ${key}${binding.kind === "declaration" ? "" : ` (${binding.kind})`}`);
1203
- if (binding.kind === "declaration" && !declarations.has(key)) declarations.set(key, plain((reader.info(binding.file).locals.get(binding.local) ?? []).join("\n")));
993
+ if (binding.kind === "declaration" && !declarations.has(key)) {
994
+ const info = reader.info(binding.file);
995
+ declarations.set(key, plain((info.locals.get(binding.local) ?? []).join("\n")));
996
+ const doc = info.docs.get(binding.local);
997
+ if (doc !== void 0) docs.set(key, doc);
998
+ }
1204
999
  if (binding.kind === "namespace" && !parents.has(binding.file)) names(reader.exportsOf(binding.file), `${prefix}${name}.`, /* @__PURE__ */ new Set([...parents, binding.file]), isType);
1205
1000
  }
1206
1001
  };
@@ -1233,17 +1028,296 @@ function apiReport(packageName, root, entries, options = {}) {
1233
1028
  lines.push("", "## Declarations");
1234
1029
  for (const key of [...declarations.keys()].sort(byCode)) lines.push("", `### ${key}`, declarations.get(key) ?? "");
1235
1030
  }
1236
- return `${lines.join("\n")}\n`;
1031
+ return {
1032
+ packageName,
1033
+ text: `${lines.join("\n")}\n`,
1034
+ docs
1035
+ };
1237
1036
  }
1238
1037
  /** This function gives the report of the package in the folder `dir`. */
1239
1038
  function packageReport(dir, options = {}) {
1039
+ return documentedPackageReport(dir, options).text;
1040
+ }
1041
+ /** This function gives the report of the package in the folder `dir`, and the doc comment of each declaration of the report. */
1042
+ function documentedPackageReport(dir, options = {}) {
1240
1043
  const source = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1241
1044
  const manifest = options.publishConfig === false ? source : publishedManifest(source);
1242
- return apiReport(typeof manifest.name === "string" ? manifest.name : basename(dir), dir, entriesOf(manifest, dir), {
1045
+ return documentedReport(typeof manifest.name === "string" ? manifest.name : basename(dir), dir, entriesOf(manifest, dir), {
1243
1046
  manifest,
1244
1047
  ...options.tool === void 0 ? {} : { tool: options.tool }
1245
1048
  });
1246
1049
  }
1050
+ // src/model.ts
1051
+ /**
1052
+ * The model of the public API of a package, as data. It has each entry, the names of each entry, the
1053
+ * declaration of each name and the text of its doc comment. A page of each export, or a page of a site,
1054
+ * renders this model. The report has the same entries, names and declarations, but no doc comments.
1055
+ */
1056
+ /**
1057
+ * This function gives the model of a report. `docs` gives the text of the doc comment of each key. The
1058
+ * report has no doc comments, so without `docs` the model has no doc comments.
1059
+ */
1060
+ function apiModel(report, packageName, docs = /* @__PURE__ */ new Map()) {
1061
+ const entries = [];
1062
+ const declarations = {};
1063
+ let names = null;
1064
+ let key = null;
1065
+ let body = [];
1066
+ const close = () => {
1067
+ if (key === null) return;
1068
+ const doc = docs.get(key);
1069
+ declarations[key] = {
1070
+ text: body.join("\n").trimEnd(),
1071
+ ...doc === void 0 ? {} : { doc }
1072
+ };
1073
+ };
1074
+ let inDeclarations = false;
1075
+ for (const line of report.replace(/\r\n/g, "\n").split("\n")) {
1076
+ if (inDeclarations) {
1077
+ const next = /^### (.+)$/.exec(line)?.[1];
1078
+ if (next === void 0) body.push(line);
1079
+ else {
1080
+ close();
1081
+ key = next;
1082
+ body = [];
1083
+ }
1084
+ continue;
1085
+ }
1086
+ if (line.startsWith("## ")) {
1087
+ inDeclarations = line === "## Declarations";
1088
+ const subpath = /^## (\.\S*?)(?: \(.*\))?: /.exec(line)?.[1];
1089
+ names = null;
1090
+ if (subpath !== void 0) {
1091
+ const lines = [];
1092
+ entries.push({
1093
+ subpath,
1094
+ names: lines
1095
+ });
1096
+ if (line.endsWith(" names")) names = lines;
1097
+ }
1098
+ continue;
1099
+ }
1100
+ if (names === null) continue;
1101
+ const match = /^(type )?(.+?): (\S+)(?: \((namespace|external)\))?$/.exec(line);
1102
+ if (match === null) continue;
1103
+ const name = match[2] ?? "";
1104
+ const kind = name === "ambient" ? "ambient" : match[4] ?? "declaration";
1105
+ names.push({
1106
+ name,
1107
+ key: match[3] ?? "",
1108
+ isType: match[1] !== void 0,
1109
+ kind
1110
+ });
1111
+ }
1112
+ close();
1113
+ return {
1114
+ packageName,
1115
+ entries,
1116
+ declarations
1117
+ };
1118
+ }
1119
+ /** This function gives the model of the package in the folder `dir`, with the doc comments of its built `.d.ts` files. */
1120
+ function packageModel(dir, options = {}) {
1121
+ const { packageName, text, docs } = documentedPackageReport(dir, options);
1122
+ return apiModel(text, packageName, docs);
1123
+ }
1124
+ // src/page.ts
1125
+ /**
1126
+ * The check of a hand-written page of an API against the report of its package. A page can explain each
1127
+ * call, and the check holds its names. Each export shows in the code of the page. The page gives no name
1128
+ * as an export that the package does not have.
1129
+ */
1130
+ /** This function gives the names of each entry of a report, by the subpath of the entry. The members of a namespace are not in the result. */
1131
+ function reportEntries(report) {
1132
+ const entries = /* @__PURE__ */ new Map();
1133
+ for (const entry of apiModel(report, "").entries) {
1134
+ const names = /* @__PURE__ */ new Set();
1135
+ for (const item of entry.names) if (item.kind !== "ambient" && !item.name.includes(".")) names.add(item.name);
1136
+ entries.set(entry.subpath, names);
1137
+ }
1138
+ return entries;
1139
+ }
1140
+ /** This function gives the code blocks and the code spans of a Markdown text. */
1141
+ function codeOf(text) {
1142
+ const blocks = [];
1143
+ const prose = [];
1144
+ let fence = null;
1145
+ let block = [];
1146
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
1147
+ const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
1148
+ if (fence === null) {
1149
+ if (mark === void 0) prose.push(line);
1150
+ else {
1151
+ fence = mark;
1152
+ block = [];
1153
+ }
1154
+ } else if (mark !== void 0 && mark[0] === fence[0] && mark.length >= fence.length) {
1155
+ blocks.push(block.join("\n"));
1156
+ fence = null;
1157
+ } else block.push(line);
1158
+ }
1159
+ if (fence !== null) blocks.push(block.join("\n"));
1160
+ return {
1161
+ blocks,
1162
+ spans: [...prose.join("\n").matchAll(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g)].map((match) => match[2] ?? "")
1163
+ };
1164
+ }
1165
+ /** This function is true if the code has `name` as a whole word. */
1166
+ function hasWord(code, name) {
1167
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1168
+ return new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`).test(code);
1169
+ }
1170
+ /**
1171
+ * This function gives the faults of the pages of a package against its report.
1172
+ *
1173
+ * An export must show in a code block or a code span of a page. An import from the package in a code block
1174
+ * must name an export of that entry. A signature, an `interface` or a `type` in a code block must be an
1175
+ * export of an entry. An exception needs a reason, and an exception that removes no fault is also a fault.
1176
+ * When `complete` is true, a different page shows each export, so the first rule does not apply.
1177
+ */
1178
+ function pageFaults(report, packageName, pages, except = {}, complete = false) {
1179
+ const entries = reportEntries(report);
1180
+ const all = new Set([...entries.values()].flatMap((names) => [...names]));
1181
+ const code = pages.map(codeOf);
1182
+ const blocks = code.flatMap((item) => item.blocks);
1183
+ const text = [...blocks, ...code.flatMap((item) => item.spans)].join("\n");
1184
+ const faults = /* @__PURE__ */ new Map();
1185
+ const used = /* @__PURE__ */ new Set();
1186
+ const fault = (name, words) => {
1187
+ if (Object.hasOwn(except, name)) used.add(name);
1188
+ else if (!faults.has(name)) faults.set(name, `${name}: ${words}`);
1189
+ };
1190
+ if (!complete) {
1191
+ for (const name of all) if (!hasWord(text, name)) fault(name, "the package exports this name, and no code on the page shows it.");
1192
+ }
1193
+ for (const block of blocks) {
1194
+ for (const match of block.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
1195
+ const source = match[2] ?? "";
1196
+ if (source !== packageName && !source.startsWith(`${packageName}/`)) continue;
1197
+ const names = entries.get(`.${source.slice(packageName.length)}`);
1198
+ if (names === void 0) {
1199
+ fault(source, "the page imports from this path, and the package has no such entry.");
1200
+ continue;
1201
+ }
1202
+ for (const part of (match[1] ?? "").split(",")) {
1203
+ const name = part.replace(/^\s*type\s+/, "").split(/\s+as\s+/)[0]?.trim() ?? "";
1204
+ if (name !== "" && name !== "default" && !names.has(name)) fault(name, `the page imports this name from ${source}, and that entry does not export it.`);
1205
+ }
1206
+ }
1207
+ for (const line of block.split("\n")) {
1208
+ const name = /^\s*(?:export\s+)?(?:declare\s+)?function\s+([\w$]+)\s*[<(].*;\s*(?:\/\/.*)?$/.exec(line)?.[1] ?? /^\s*(?:export\s+)?(?:declare\s+)?(?:interface|type)\s+([\w$]+)/.exec(line)?.[1];
1209
+ if (name !== void 0 && !all.has(name)) fault(name, "the page gives the declaration of this name, and the package does not export it.");
1210
+ }
1211
+ }
1212
+ for (const [name, reason] of Object.entries(except)) if (reason.trim() === "") faults.set(name, `${name}: the exception has no reason.`);
1213
+ else if (!used.has(name)) faults.set(name, `${name}: the exception removes no fault, so remove it.`);
1214
+ return [...faults.entries()].sort(([a], [b]) => byCode(a, b)).map(([, words]) => words);
1215
+ }
1216
+ // src/reference.ts
1217
+ /**
1218
+ * A page of each export of a package, from its report or its model. A library with many exports keeps each
1219
+ * name on this page, and a hand-written page explains the main calls. The report has the names and the
1220
+ * declarations, so this page has the same text as the report in each build. A model can also give the doc
1221
+ * comments.
1222
+ */
1223
+ /** This function gives a fenced block of TypeScript. The fence is longer than each run of backticks in the code. */
1224
+ function fenced(code) {
1225
+ const longest = Math.max(2, ...[...code.matchAll(/`+/g)].map((match) => match[0].length));
1226
+ const fence = "`".repeat(longest + 1);
1227
+ return `${fence}ts\n${code}\n${fence}`;
1228
+ }
1229
+ /** The most characters of a line of an import list. */
1230
+ const IMPORT_WIDTH = 100;
1231
+ /** This function gives an import of `names` from `path`, with a line break at `IMPORT_WIDTH`. */
1232
+ function importOf(names, path) {
1233
+ const lines = [];
1234
+ let line = " ";
1235
+ for (const name of names) {
1236
+ if (line.length + name.length + 2 > IMPORT_WIDTH) {
1237
+ lines.push(line);
1238
+ line = " ";
1239
+ }
1240
+ line += ` ${name},`;
1241
+ }
1242
+ lines.push(line);
1243
+ return `import {\n${lines.join("\n")}\n} from ${JSON.stringify(path)};`;
1244
+ }
1245
+ /** This function removes the words `export` and `declare` from the start of each statement of a declaration. `declare global` and `declare module` keep the word. */
1246
+ function plain(declaration) {
1247
+ return declaration.replace(/^(?:export )?(?:declare (?!global\b|module\b))?/gm, "");
1248
+ }
1249
+ /** This function gives the doc comment of the text `doc`, with a line break at its end. The end mark of a comment in the text does not end the comment. */
1250
+ function docComment(doc) {
1251
+ const lines = doc.replaceAll("*/", "*\\/").split("\n");
1252
+ if (lines.length === 1) return `/** ${lines[0] ?? ""} */\n`;
1253
+ return `/**\n${lines.map((line) => line === "" ? " *" : ` * ${line}`).join("\n")}\n */\n`;
1254
+ }
1255
+ /** This pattern finds a name that a bundler changed, to keep two declarations apart: `grid$1`. */
1256
+ const BUNDLER_NAME = /\$\d+$/;
1257
+ /** This function gives the name of the declaration of a line of a report. */
1258
+ function localName(item) {
1259
+ return item.key.slice(item.key.lastIndexOf("#") + 1);
1260
+ }
1261
+ /** This function puts the name of each export of `items` in `code`, where a bundler changed that name. */
1262
+ function withExportNames(code, items) {
1263
+ let text = code;
1264
+ for (const item of items) {
1265
+ const local = localName(item);
1266
+ if (!BUNDLER_NAME.test(local) || item.name.includes(".") || item.kind !== "declaration") continue;
1267
+ const word = new RegExp(`(?<![\\w$])${local.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&")}(?![\\w$])`, "g");
1268
+ text = text.replace(word, () => item.name);
1269
+ }
1270
+ return text;
1271
+ }
1272
+ function referencePage(report, second, third = {}) {
1273
+ const model = typeof report === "string" ? apiModel(report, typeof second === "string" ? second : "") : report;
1274
+ const frontmatter = typeof report === "string" ? third : typeof second === "object" ? second : {};
1275
+ const { packageName, entries, declarations } = model;
1276
+ const fields = {
1277
+ title: `Each export of ${packageName}`,
1278
+ description: `Each entry point of ${packageName}, with its exports and their declarations.`,
1279
+ ...frontmatter
1280
+ };
1281
+ const out = [
1282
+ "---",
1283
+ "# The command `api-report update` writes this file from the report of the package. Do not edit it.",
1284
+ ...Object.entries(fields).map(([key, value]) => `${key}: ${JSON.stringify(value)}`),
1285
+ "---",
1286
+ "",
1287
+ "The report of the API of the package makes this page, so the page and the package have the same names. Each section is one entry point. A declaration shows one time, in the first section that has it."
1288
+ ];
1289
+ const seen = /* @__PURE__ */ new Set();
1290
+ for (const entry of entries) {
1291
+ const path = `${packageName}${entry.subpath.slice(1)}`;
1292
+ out.push("", `## \`${path}\``, "");
1293
+ const items = entry.names;
1294
+ if (items.length === 0) {
1295
+ out.push("This entry has no declarations.");
1296
+ continue;
1297
+ }
1298
+ const top = items.filter((item) => item.kind !== "ambient" && !item.name.includes(".") && !item.name.startsWith("* "));
1299
+ const blocks = top.length > 0 ? [fenced(importOf(top.map((item) => `${item.isType ? "type " : ""}${item.name === "default" ? "default as defaultExport" : item.name}`), path))] : [];
1300
+ const parts = [];
1301
+ for (const item of items) {
1302
+ if (seen.has(`${item.name} ${item.key}`)) continue;
1303
+ seen.add(`${item.name} ${item.key}`);
1304
+ if (item.kind === "external") {
1305
+ const from = item.key.slice(0, item.key.lastIndexOf("#"));
1306
+ parts.push(`// ${item.name} comes from the package ${from}.`);
1307
+ continue;
1308
+ }
1309
+ const declaration = Object.hasOwn(declarations, item.key) ? declarations[item.key] : void 0;
1310
+ if (declaration === void 0 || seen.has(item.key)) continue;
1311
+ seen.add(item.key);
1312
+ const local = localName(item);
1313
+ const label = item.kind === "ambient" || local === item.name || BUNDLER_NAME.test(local) ? "" : `// The export ${item.name}:\n`;
1314
+ parts.push(`${label}${declaration.doc === void 0 ? "" : docComment(declaration.doc)}${plain(declaration.text)}`);
1315
+ }
1316
+ if (parts.length > 0) blocks.push(fenced(withExportNames(parts.join("\n\n"), items)));
1317
+ out.push(blocks.join("\n\n"));
1318
+ }
1319
+ return `${out.join("\n")}\n`;
1320
+ }
1247
1321
  // src/run.ts
1248
1322
  /**
1249
1323
  * The commands `check` and `update` of the bin `api-report`, as functions. `runReports` compares or
@@ -1301,18 +1375,21 @@ function readPages(value) {
1301
1375
  return value.map((item, index) => {
1302
1376
  const at = `apiReport.pages[${index}]`;
1303
1377
  if (typeof item !== "object" || item === null || Array.isArray(item)) throw new Error(`${at} must be an object.`);
1304
- const { package: folder, pages, except, reference, frontmatter } = item;
1378
+ const { package: folder, pages, except, reference, frontmatter, docs } = item;
1305
1379
  if (typeof folder !== "string" || folder === "") throw new Error(`${at}.package must be a string.`);
1306
1380
  if (reference !== void 0 && (typeof reference !== "string" || !isRootPath(reference))) throw new Error(`${at}.reference must be a path in the repository.`);
1307
1381
  const emptyOk = reference !== void 0;
1308
1382
  if (!Array.isArray(pages) || pages.length === 0 && !emptyOk || !pages.every((page) => typeof page === "string")) throw new Error(`${at}.pages must be an array of paths.`);
1309
1383
  if (frontmatter !== void 0 && reference === void 0) throw new Error(`${at}.frontmatter needs the field reference.`);
1384
+ if (docs !== void 0 && typeof docs !== "boolean") throw new Error(`${at}.docs must be a boolean.`);
1385
+ if (docs !== void 0 && reference === void 0) throw new Error(`${at}.docs needs the field reference.`);
1310
1386
  const fields = frontmatter === void 0 ? void 0 : readFrontmatter(frontmatter, `${at}.frontmatter`);
1311
1387
  const named = {
1312
1388
  package: folder,
1313
1389
  pages,
1314
1390
  ...reference === void 0 ? {} : { reference },
1315
- ...fields === void 0 ? {} : { frontmatter: fields }
1391
+ ...fields === void 0 ? {} : { frontmatter: fields },
1392
+ ...docs === void 0 ? {} : { docs }
1316
1393
  };
1317
1394
  if (except === void 0) return named;
1318
1395
  if (typeof except !== "object" || except === null || Array.isArray(except) || !Object.values(except).every((reason) => typeof reason === "string")) throw new Error(`${at}.except must be an object of names and reasons.`);
@@ -1345,15 +1422,19 @@ function faultsOfPages(root, entry, report, packageName) {
1345
1422
  const missing = entry.pages.filter((page) => !existsSync(resolve(root, page)));
1346
1423
  if (missing.length > 0) return missing.map((page) => `${page}: the page does not exist.`);
1347
1424
  const faults = [];
1348
- if (entry.reference !== void 0 && textOf(resolve(root, entry.reference)) !== referencePage(report, packageName, entry.frontmatter)) faults.push(`${entry.reference}: the page differs from the report. Start the command update, and commit the page.`);
1425
+ if (entry.reference !== void 0 && textOf(resolve(root, entry.reference)) !== referenceOf(entry, report, packageName)) faults.push(`${entry.reference}: the page differs from the report. Start the command update, and commit the page.`);
1349
1426
  const pages = entry.pages.map((page) => readFileSync(resolve(root, page), "utf8"));
1350
- return [...faults, ...pageFaults(report, packageName, pages, entry.except, entry.reference !== void 0)];
1427
+ return [...faults, ...pageFaults(report.text, packageName, pages, entry.except, entry.reference !== void 0)];
1428
+ }
1429
+ /** This function gives the page of each export of one package. With the field `docs`, the page also has the doc comments. */
1430
+ function referenceOf(entry, report, packageName) {
1431
+ return referencePage(apiModel(report.text, packageName, entry.docs === true ? report.docs : void 0), entry.frontmatter);
1351
1432
  }
1352
1433
  /** This function writes the page of each export of one package, and gives its path when the text changes. */
1353
1434
  function writeReference(root, entry, report, packageName) {
1354
1435
  if (entry.reference === void 0) return [];
1355
1436
  const file = resolve(root, entry.reference);
1356
- const text = referencePage(report, packageName, entry.frontmatter);
1437
+ const text = referenceOf(entry, report, packageName);
1357
1438
  if (textOf(file) === text) return [];
1358
1439
  mkdirSync(dirname(file), { recursive: true });
1359
1440
  writeFileSync(file, text);
@@ -1432,9 +1513,9 @@ function runReports(options) {
1432
1513
  }
1433
1514
  continue;
1434
1515
  }
1435
- let text;
1516
+ let documented;
1436
1517
  try {
1437
- text = packageReport(folder, {
1518
+ documented = documentedPackageReport(folder, {
1438
1519
  tool: options.tool ?? "api-report",
1439
1520
  ...options.publishConfig === void 0 ? {} : { publishConfig: options.publishConfig }
1440
1521
  });
@@ -1447,9 +1528,10 @@ function runReports(options) {
1447
1528
  });
1448
1529
  continue;
1449
1530
  }
1531
+ const { text } = documented;
1450
1532
  const ownPages = (options.pages ?? []).filter((entry) => resolve(root, entry.package) === folder);
1451
- const written = options.mode === "update" ? ownPages.flatMap((entry) => writeReference(root, entry, text, manifest.name ?? "")) : [];
1452
- const faults = ownPages.flatMap((entry) => faultsOfPages(root, entry, text, manifest.name ?? ""));
1533
+ const written = options.mode === "update" ? ownPages.flatMap((entry) => writeReference(root, entry, documented, manifest.name ?? "")) : [];
1534
+ const faults = ownPages.flatMap((entry) => faultsOfPages(root, entry, documented, manifest.name ?? ""));
1453
1535
  const onPages = {
1454
1536
  ...options.mode === "check" && faults.length > 0 ? { pageFaults: faults } : {},
1455
1537
  ...written.length > 0 ? { writtenPages: written } : {}
@@ -1639,6 +1721,6 @@ function runCli(args, io) {
1639
1721
  }
1640
1722
  return result.failed ? 1 : 0;
1641
1723
  }
1642
- export { diffLines as C, statementsOf as E, targetOf as S, parseDeclarations as T, byCode as _, runCli as a, patternMatch as b, DEFAULT_TOOL as c, packageReport as d, referencePage as f, binsOf as g, PUBLISH_CONFIG_FIELDS as h, readConfig as i, HEADER_LINES as l, reportEntries as m, USAGE as n, runReports as o, pageFaults as p, formatResult as r, summaryMarkdown as s, REPORT_FILE as t, apiReport as u, declarationPathOf as v, unifiedDiff as w, publishedManifest as x, entriesOf as y };
1724
+ export { publishedManifest as C, parseDeclarations as D, unifiedDiff as E, statementsOf as O, patternMatch as S, diffLines as T, PUBLISH_CONFIG_FIELDS as _, runCli as a, declarationPathOf as b, referencePage as c, apiModel as d, packageModel as f, packageReport as g, apiReport as h, readConfig as i, pageFaults as l, HEADER_LINES as m, USAGE as n, runReports as o, DEFAULT_TOOL as p, formatResult as r, summaryMarkdown as s, REPORT_FILE as t, reportEntries as u, binsOf as v, targetOf as w, entriesOf as x, byCode as y };
1643
1725
 
1644
- //# sourceMappingURL=run-Bw-iqwFC.js.map
1726
+ //# sourceMappingURL=run-DohS8GVx.js.map