@writedocs/generator 0.10.14 → 0.10.15

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.
@@ -0,0 +1,41 @@
1
+ // A short, plain-text description for a generated API page's
2
+ // <meta name="description">, from the operation in the spec. OpenAPI
3
+ // descriptions are Markdown and often several paragraphs - a search result
4
+ // shows about 160 characters of plain text.
5
+ // Plain JavaScript: src/cli/generate-api-pages.js runs under plain Node.
6
+
7
+ export const META_DESCRIPTION_LENGTH = 160;
8
+
9
+ /** Markdown (or HTML) as one line of plain text. */
10
+ export function plainLine(markdown) {
11
+ return String(markdown ?? '')
12
+ .replace(/```[\s\S]*?```/g, ' ') // code blocks
13
+ .replace(/<[^>]+>/g, ' ') // HTML tags
14
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') // images -> alt text
15
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') // links -> their text
16
+ .replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, '') // headings, quotes, list markers
17
+ .replace(/(\*\*|\*|~~|`)/g, '') // emphasis and inline code marks (not _: customer_id)
18
+ .replace(/\|/g, ' ') // table cells
19
+ .replace(/\s+/g, ' ')
20
+ .trim();
21
+ }
22
+
23
+ /** `text` cut to `max` characters at a word, with an ellipsis. */
24
+ export function truncateAtWord(text, max = META_DESCRIPTION_LENGTH) {
25
+ if (text.length <= max) return text;
26
+ const cut = text.slice(0, max - 1);
27
+ const lastSpace = cut.lastIndexOf(' ');
28
+ return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).replace(/[\s.,;:!?-]+$/, '')}…`;
29
+ }
30
+
31
+ /** The description for an operation's page: its own `description`, as plain
32
+ * text and cut to length - or, without one, its summary with the method
33
+ * and path ("List all customers - GET /customers"), so the page still has
34
+ * a description that says more than its title. */
35
+ export function operationMetaDescription({ description, summary, method, path }) {
36
+ const text = plainLine(description);
37
+ if (text) return truncateAtWord(text);
38
+ const request = `${method} ${path}`;
39
+ const fallback = summary && summary.trim() ? `${plainLine(summary)} - ${request}` : request;
40
+ return truncateAtWord(fallback);
41
+ }