@writedocs/generator 0.19.0 → 0.21.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.
@@ -0,0 +1,135 @@
1
+ // Turns a ReadMe recipe (its `.md` export) into a writedocs page.
2
+ //
3
+ // A recipe is a walkthrough: the complete code in each language, then one
4
+ // `# Heading` per step, each naming the lines of the code it is about:
5
+ //
6
+ // ```python Python <- the code, one fence per language
7
+ // ...
8
+ // ```
9
+ // ```json Response Example <- optional: a fence whose title says "response"
10
+ // ...
11
+ // ```
12
+ //
13
+ // # Encode the credentials
14
+ //
15
+ // <!-- python@10-15 --> <- the step's lines, per language ("6-8,23-24")
16
+ // <!-- csharp@16-21 -->
17
+ //
18
+ // You can get your credentials ...
19
+ //
20
+ // On ReadMe the code sits beside the steps and the step's lines light up
21
+ // as you go. Here: the code goes in <RequestExample> (and responses in
22
+ // <ResponseExample>), which writedocs pins in the right-hand column, and
23
+ // the steps become <Steps>, each with its text and the lines it names, as
24
+ // a <CodeGroup> with one tab per language.
25
+
26
+ import { convertReadmeBody, splitBody, normalizeFenceInfo, jsxAttr } from './readme-mdx.js';
27
+
28
+ const RANGE_RE = /<!--\s*([\w#+.-]+)@([\d,\s-]+)\s*-->/g;
29
+
30
+ /** "6-8,23-24" -> [[6, 8], [23, 24]]. */
31
+ export function parseLineRanges(spec) {
32
+ return String(spec)
33
+ .split(',')
34
+ .map((part) => part.trim())
35
+ .filter(Boolean)
36
+ .map((part) => {
37
+ const [a, b] = part.split('-').map((n) => Number(n.trim()));
38
+ return [a, Number.isFinite(b) ? b : a];
39
+ })
40
+ .filter(([a, b]) => Number.isFinite(a) && a >= 1 && b >= a);
41
+ }
42
+
43
+ /** The lines `ranges` names (1-based, inclusive), ranges apart joined by
44
+ * an empty line, with their common indentation removed. */
45
+ export function sliceLines(lines, ranges) {
46
+ const parts = ranges.map(([a, b]) => lines.slice(a - 1, b)).filter((p) => p.length);
47
+ const all = parts.flat().filter((l) => l.trim());
48
+ const indent = all.length ? Math.min(...all.map((l) => /^\s*/.exec(l)[0].length)) : 0;
49
+ return parts.map((p) => p.map((l) => l.slice(indent)).join('\n')).join('\n\n');
50
+ }
51
+
52
+ /** Strips the export's frontmatter and its `# Title` line. */
53
+ function splitTitle(markdown) {
54
+ let md = String(markdown ?? '').replace(/\r\n?/g, '\n').replace(/^---\n[\s\S]*?\n---\n/, '');
55
+ const m = /^\s*#\s+(.+?)\s*\n/.exec(md);
56
+ let title = null;
57
+ if (m) {
58
+ title = m[1].trim();
59
+ md = md.slice(m[0].length);
60
+ }
61
+ return { title, body: md };
62
+ }
63
+
64
+ /**
65
+ * @param {string} markdown the recipe's .md export
66
+ * @param {object} ctx as for convertReadmeBody
67
+ * @returns {{ title: string | null, body: string }}
68
+ */
69
+ export function convertRecipe(markdown, ctx) {
70
+ const { title, body } = splitTitle(markdown);
71
+ const segments = splitBody(body);
72
+
73
+ // The leading code fences, before the first step heading.
74
+ const code = [];
75
+ let s = 0;
76
+ while (s < segments.length) {
77
+ const seg = segments[s];
78
+ if (seg.kind === 'code') code.push(seg);
79
+ else if (seg.kind !== 'text' || seg.lines.some((l) => /^#{1,6}\s/.test(l))) break;
80
+ else if (seg.lines.some((l) => l.trim())) break;
81
+ s++;
82
+ }
83
+ const rest = segments.slice(s);
84
+
85
+ const isResponse = (seg) => /response/i.test(seg.info);
86
+ const requests = code.filter((c) => !isResponse(c));
87
+ const responses = code.filter(isResponse);
88
+ const byLang = new Map(requests.map((c) => [c.info.split(/\s+/)[0].toLowerCase(), c]));
89
+ const fence = (c, text) => ['```' + normalizeFenceInfo(c.info, { inGroup: true }), text, '```'].join('\n');
90
+ const exampleBlock = (tag, blocks) => (blocks.length ? `<${tag}>\n${blocks.map((c) => fence(c, c.body.join('\n'))).join('\n\n')}\n</${tag}>` : '');
91
+
92
+ // The steps: split the rest of the page at its top-level headings.
93
+ const restText = rest
94
+ .map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.indent + seg.marks + seg.info, ...seg.body, seg.indent + seg.marks].join('\n') : `<HTMLBlock>{\`${seg.html}\`}</HTMLBlock>`))
95
+ .join('\n');
96
+ const steps = [];
97
+ const intro = [];
98
+ let current = null;
99
+ let inFence = false;
100
+ for (const line of restText.split('\n')) {
101
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
102
+ const h = !inFence && /^#\s+(.+?)\s*#*\s*$/.exec(line);
103
+ if (h) {
104
+ current = { title: h[1], lines: [] };
105
+ steps.push(current);
106
+ } else (current ? current.lines : intro).push(line);
107
+ }
108
+
109
+ const parts = [];
110
+ const introText = convertReadmeBody(intro.join('\n'), ctx);
111
+ if (introText) parts.push(introText);
112
+ const req = exampleBlock('RequestExample', requests);
113
+ if (req) parts.push(req);
114
+ const res = exampleBlock('ResponseExample', responses);
115
+ if (res) parts.push(res);
116
+
117
+ if (steps.length) {
118
+ const rendered = steps.map((step) => {
119
+ const text = step.lines.join('\n');
120
+ const excerpts = [];
121
+ for (const m of text.matchAll(RANGE_RE)) {
122
+ const c = byLang.get(m[1].toLowerCase());
123
+ if (!c) continue;
124
+ const lines = sliceLines(c.body, parseLineRanges(m[2]));
125
+ if (lines.trim()) excerpts.push(fence(c, lines));
126
+ }
127
+ const description = convertReadmeBody(text.replace(RANGE_RE, ''), ctx);
128
+ const code = excerpts.length > 1 ? `<CodeGroup>\n${excerpts.join('\n')}\n</CodeGroup>` : excerpts[0] ?? '';
129
+ const inner = [description, code].filter(Boolean).join('\n\n');
130
+ return `<Step ${jsxAttr('title', step.title)}>\n\n${inner}\n\n</Step>`;
131
+ });
132
+ parts.push(`<Steps>\n\n${rendered.join('\n\n')}\n\n</Steps>`);
133
+ }
134
+ return { title, body: parts.join('\n\n') };
135
+ }
@@ -0,0 +1,53 @@
1
+ // Where an OpenAPI group with `openapi.renderer: "scalar"` may put its
2
+ // reference: it's a page of its own at the group's `openapi.path`
3
+ // (lib/scalar-reference.js), so that path can't be the site's root, nor the
4
+ // address of one of the project's pages. One wording for every command that
5
+ // refuses it: the build, `dev` and `broken-links` (generate-api-pages.js),
6
+ // and `writedocs validate` - the root in writedocs.json's schema
7
+ // (config-schema.ts, which the WriteDocs platform validates writedocs.json
8
+ // with too), a page's address in its pages pass (content-check.js), the only
9
+ // one with the project's files.
10
+ //
11
+ // Plain JavaScript with no Node import: config-schema.ts imports it, and the
12
+ // platform's Worker runs that.
13
+
14
+ /** `openapi.path` without its slashes - "" for the root. */
15
+ export function scalarPathPrefix(rawPath) {
16
+ return String(rawPath ?? '').replace(/^\/+|\/+$/g, '');
17
+ }
18
+
19
+ /** The refusal of a "scalar" group at the root. */
20
+ export function scalarRootPathMessage(group, rawPath) {
21
+ return (
22
+ `writedocs.json's "${group}" group has openapi.renderer "scalar" and openapi.path "${rawPath}" - ` +
23
+ 'the reference is a page at that path, so give it one of its own, like "/api".'
24
+ );
25
+ }
26
+
27
+ /** The refusal of a "scalar" group at a page's address (`prefix`, no slashes). */
28
+ export function scalarPagePathMessage(group, prefix) {
29
+ return (
30
+ `writedocs.json's "${group}" group has openapi.renderer "scalar" - its reference is the page at /${prefix}/, ` +
31
+ 'and a page of the project is already there. Move that page or give the group another openapi.path.'
32
+ );
33
+ }
34
+
35
+ /** Every OpenAPI group of a `navigation` value with `renderer: "scalar"`,
36
+ * with its path from `navigation` (keys and indexes). Any shape - it walks
37
+ * every object and array, so it finds a group wherever the schema allows
38
+ * one. */
39
+ export function scalarGroups(navigation) {
40
+ const found = [];
41
+ const walk = (node, trail) => {
42
+ if (!node || typeof node !== 'object') return;
43
+ if (Array.isArray(node)) return node.forEach((child, i) => walk(child, [...trail, i]));
44
+ const openapi = node.openapi;
45
+ if (typeof node.group === 'string' && openapi && typeof openapi === 'object' && !Array.isArray(openapi)) {
46
+ if (openapi.renderer === 'scalar' && typeof openapi.path === 'string') found.push({ group: node.group, path: openapi.path, trail });
47
+ return;
48
+ }
49
+ for (const [key, value] of Object.entries(node)) walk(value, [...trail, key]);
50
+ };
51
+ walk(navigation, []);
52
+ return found;
53
+ }
@@ -0,0 +1,59 @@
1
+ // What the skeleton of Scalar's API reference shows while Scalar loads
2
+ // (ScalarReference.astro): the parts of the reference's first screen whose
3
+ // size depends on the spec - its title, the two badges, the first paragraph
4
+ // of its description, and which of the Server and Authentication blocks it
5
+ // has - so the skeleton takes the same room as the reference that replaces
6
+ // it. The rest of the skeleton (the sidebar, the bar of operations, the
7
+ // Client Libraries block) is the same for every spec.
8
+ //
9
+ // The text is drawn as bars the shape of the text (transparent, in the
10
+ // reference's own sizes): a title or description that wraps to two lines in
11
+ // the reference wraps to two lines in the skeleton too.
12
+ //
13
+ // Plain JavaScript so the tests can import it.
14
+ import { plainLine, truncateAtWord } from './meta-description.js';
15
+
16
+ /** The longest description paragraph the skeleton carries, in characters:
17
+ * a few lines - the page shouldn't carry a long introduction twice. */
18
+ export const SKELETON_TEXT_LENGTH = 400;
19
+
20
+ /** Scalar's Authentication block, by the type of the scheme it shows first:
21
+ * an HTTP bearer token is one row (67px, measured); an API key - and every
22
+ * other type - more (100px, an API key's, measured). */
23
+ export const AUTH_BLOCK_HEIGHT = { bearer: 67, other: 100 };
24
+
25
+ /** The first paragraph of a Markdown description, as plain text. */
26
+ function firstParagraph(markdown) {
27
+ const blocks = String(markdown ?? '')
28
+ .replace(/\r\n/g, '\n')
29
+ .split(/\n\s*\n/)
30
+ .map((block) => plainLine(block))
31
+ .filter(Boolean);
32
+ return blocks.length ? truncateAtWord(blocks[0], SKELETON_TEXT_LENGTH) : '';
33
+ }
34
+
35
+ /** The scheme Scalar selects first: the first one the spec's top-level
36
+ * `security` asks for, else the first it defines. */
37
+ function firstScheme(spec) {
38
+ const schemes = spec?.components?.securitySchemes ?? spec?.securityDefinitions ?? {};
39
+ const names = Object.keys(schemes);
40
+ if (!names.length) return null;
41
+ const asked = (Array.isArray(spec?.security) ? spec.security : []).flatMap((requirement) => Object.keys(requirement ?? {}));
42
+ const name = asked.find((n) => n in schemes) ?? names[0];
43
+ return schemes[name] ?? null;
44
+ }
45
+
46
+ /** The skeleton's spec-dependent parts, from the bundled spec. */
47
+ export function scalarSkeleton(spec) {
48
+ const info = spec?.info ?? {};
49
+ const openapi = spec?.openapi ?? spec?.swagger;
50
+ const scheme = firstScheme(spec);
51
+ const bearer = scheme?.type === 'http' && String(scheme.scheme ?? '').toLowerCase() === 'bearer';
52
+ return {
53
+ title: plainLine(info.title) || 'API',
54
+ badges: [info.version ? String(info.version) : null, openapi ? `OpenAPI ${openapi}` : null].filter(Boolean),
55
+ description: firstParagraph(info.description),
56
+ server: Array.isArray(spec?.servers) ? spec.servers.length > 0 : Boolean(spec?.host),
57
+ auth: scheme ? (bearer ? AUTH_BLOCK_HEIGHT.bearer : AUTH_BLOCK_HEIGHT.other) : 0,
58
+ };
59
+ }
@@ -114,7 +114,7 @@ export const SCALAR_REFERENCE_RULES = [
114
114
  [`${R} .operation-title`, '--font-size: 1.5rem; --font-weight: 700; line-height: 1.6;', "an operation's title: the site's h2"],
115
115
  [`${R} .markdown`, '--markdown-line-height: 1.6; color: var(--wd-text);', "text: the site's line height and text color (Scalar's is the heading color)"],
116
116
  [`${R} .section`, 'padding-block: 2.75rem;', "the space around a section: the site's before an h2"],
117
- [`${R} .introduction-section`, 'padding-top: 3.5rem;', "the reference's title where the site's h1 is"],
117
+ [`${R} .introduction-section`, 'padding-top: 3.5rem;', "room above the reference's title for its version badges (placed above it, the next rule), and the title below them"],
118
118
  [`${R} .introduction-section .section-content`, 'position: relative;', 'so the version badges can sit above the title'],
119
119
  [`${R} .introduction-section .section-content > :first-child:has(.badge)`, 'position: absolute; bottom: 100%; margin-bottom: 0.5rem;', "the version badges above the title, without pushing it down"],
120
120
  ];
@@ -128,13 +128,10 @@ export const SCALAR_REFERENCE_RULES = [
128
128
  * custom header's height. The content's left margin is the site's article
129
129
  * padding when Scalar's own container query would give it 60px. */
130
130
  export function scalarReferenceThemeCss() {
131
- // The at-rule of a container query, written in two parts: Tailwind scans
132
- // this package's own files for class names, and the at-rule's name in one
133
- // piece is also the name of one of its classes - whose rule then went into
134
- // every site's stylesheet (gerador/13, found by comparing builds). Inside
135
- // this function, not at the top of the module: a top-level call can't be
136
- // dropped by the bundler, and was left in the Try it's chunk.
137
- const CONTAINER_QUERY = ['@', 'container'].join('');
131
+ // Words here are safe from Tailwind: src/lib isn't read for class names
132
+ // (src/styles/global.css). Before it was left out, this at-rule's name and
133
+ // the word in the focus ring's reason above each put a rule into every
134
+ // site's stylesheet (gerador/13 and 14).
138
135
  const declarations = (vars) =>
139
136
  Object.entries(vars)
140
137
  .map(([name, value]) => ` ${name}: ${value};`)
@@ -157,15 +154,17 @@ ${declarations(SCALAR_REFERENCE_VARIABLES)}
157
154
  }
158
155
  }
159
156
  ` +
160
- // The site's phone layout (base.css, 860px) puts the page's title 12px
161
- // lower under its top bar: the reference's title follows.
157
+ // In the site's phone layout (base.css, 860px) Scalar's bar of
158
+ // operations is right above the title, and the badges above the title
159
+ // need less room: 2.25rem under the bar, as a page's title sits under
160
+ // the site's top bar there.
162
161
  `@media (max-width: 860px) {
163
162
  ${R} .introduction-section {
164
163
  padding-top: 2.25rem;
165
164
  }
166
165
  }
167
166
  ` +
168
- `${CONTAINER_QUERY} references-container (min-width: 901px) {
167
+ `@container references-container (min-width: 901px) {
169
168
  ${R} .section-container {
170
169
  padding-inline: 1.5rem;
171
170
  }
@@ -1491,12 +1491,71 @@ const components = {
1491
1491
  .wd-toc-col:has(.wd-example-host:not(:empty)) {
1492
1492
  width: 340px;
1493
1493
  }
1494
+ /* A flex column of the visible height, so a docked request/response
1495
+ example is held to it and scrolls its code inside its own frame
1496
+ (below) rather than the whole column scrolling - the tab strip and
1497
+ copy button stay in view. `height`, not only max-height: the examples
1498
+ share the column out of a definite height (flex-basis 0 below), which
1499
+ an auto-height column would collapse to nothing. It adds no page
1500
+ height - docking is desktop-only, where the sidebar column is already
1501
+ this tall (Sidebar.astro). The column's own overflow-y is left as the
1502
+ fallback for what can't shrink: a Panel's content, or several
1503
+ examples' tab strips that don't fit together. The [hidden] rule is
1504
+ needed because display: flex would otherwise beat the attribute
1505
+ undock() sets, leaving the empty host's padding above the table of
1506
+ contents. */
1494
1507
  .wd-example-host {
1495
1508
  position: sticky;
1496
1509
  top: var(--wd-topbar-offset, 5rem);
1497
- max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
1510
+ height: calc(100vh - var(--wd-topbar-offset, 5rem));
1498
1511
  overflow-y: auto;
1499
1512
  padding: 1.5rem 0 1.5rem 0.5rem;
1513
+ display: flex;
1514
+ flex-direction: column;
1515
+ }
1516
+ .wd-example-host[hidden] {
1517
+ display: none;
1518
+ }
1519
+ /* Docked RequestExample/ResponseExample panels split the column evenly
1520
+ (flex 1 1 0), each capped at its own content's height (max-height:
1521
+ max-content) - so a short response keeps its full size and a long
1522
+ request takes the rest; two long ones get half each. Inside a panel,
1523
+ the shown block's <pre> is the part that gives way: the chain down
1524
+ to it (the .wd-codegroup, the shown .wd-code-block) is a flex column
1525
+ with min-height: 0, so the height limit reaches the <pre>, and the
1526
+ tab strip, dropdown, title bar and expand button keep their size. A
1527
+ Panel (.wd-panel) isn't in this chain: it keeps its content's height,
1528
+ and the column scrolls. A hidden tab's inline display: none still
1529
+ beats the display: flex here. */
1530
+ .wd-example-host > .wd-request-example,
1531
+ .wd-example-host > .wd-response-example {
1532
+ display: flex;
1533
+ flex-direction: column;
1534
+ flex: 1 1 0;
1535
+ max-height: max-content;
1536
+ min-height: 0;
1537
+ }
1538
+ .wd-example-host > .wd-example-panel > .wd-codegroup,
1539
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block {
1540
+ display: flex;
1541
+ flex-direction: column;
1542
+ flex: 0 1 auto;
1543
+ min-height: 0;
1544
+ }
1545
+ .wd-example-host > .wd-panel,
1546
+ .wd-example-host > .wd-example-panel > .wd-codegroup > :not(.wd-code-block),
1547
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > :not(pre) {
1548
+ flex: none;
1549
+ }
1550
+ .wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > pre.astro-code {
1551
+ flex: 0 1 auto;
1552
+ min-height: 0;
1553
+ }
1554
+ /* In :where() so it stays weaker than an `expandable` block's collapsed
1555
+ overflow-y: hidden (components.css) - a collapsed block is clipped
1556
+ with its "Show more" button, as anywhere else. */
1557
+ :where(.wd-example-host > .wd-example-panel > .wd-codegroup > .wd-code-block > pre.astro-code) {
1558
+ overflow-y: auto;
1500
1559
  }
1501
1560
  /* Spacing between multiple docked panels (e.g. Request above
1502
1561
  Response) is this wrapper's own job only once docked - inline
@@ -29,6 +29,20 @@
29
29
  ../../ is the package's folder. */
30
30
  @source not "../../node_modules";
31
31
 
32
+ /* Nor the package's modules that never become a page's markup: the
33
+ build's own Node code (src/cli, bin) and src/lib, whose modules make
34
+ pages, styles and data but give no element one of Tailwind's classes.
35
+ A word in one of them - in a comment, a message, a string of CSS - made
36
+ a rule for it in every site's stylesheet (gerador/13 and 14).
37
+ scripts/tailwind-sources.test.js holds the list of rules the package's
38
+ files make, and fails on a new one. */
39
+ @source not "../lib";
40
+ @source not "../cli";
41
+ @source not "../../bin";
42
+ /* Kept, so no site's stylesheet changes: every one has had this rule
43
+ since a word in src/cli made it. */
44
+ @source inline("isolate");
45
+
32
46
  /* Tailwind's `dark:` variant follows the site's own theme toggle
33
47
  ([data-theme="dark"] on <html>, set by BaseLayout.astro), not the OS
34
48
  setting it defaults to - otherwise Mintlify-style light/dark image