@writedocs/generator 0.16.0 → 0.18.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.
Files changed (40) hide show
  1. package/astro.config.mjs +43 -3
  2. package/package.json +4 -1
  3. package/src/cli/build.js +39 -3
  4. package/src/cli/dev.js +16 -0
  5. package/src/cli/generate-api-pages.js +94 -3
  6. package/src/cli/run-pagefind.js +67 -22
  7. package/src/cli/write-redirects-file.js +7 -1
  8. package/src/components/ApiReferencePanel.astro +16 -3
  9. package/src/components/NoScalarReference.astro +6 -0
  10. package/src/components/NoScalarTryIt.astro +5 -0
  11. package/src/components/ScalarReference.astro +80 -0
  12. package/src/components/ScalarTryIt.astro +76 -0
  13. package/src/layout/BaseLayout.astro +7 -0
  14. package/src/layout/components/LockMark.astro +28 -0
  15. package/src/layout/components/MobileMenu.astro +4 -0
  16. package/src/layout/components/Sidebar.astro +3 -2
  17. package/src/layout/components/TopBar.astro +9 -0
  18. package/src/lib/config-schema.js +58 -6
  19. package/src/lib/config-schema.ts +75 -8
  20. package/src/lib/config.ts +40 -13
  21. package/src/lib/content-check.js +18 -3
  22. package/src/lib/json-schema-descriptions.js +5 -1
  23. package/src/lib/llms-index.ts +5 -0
  24. package/src/lib/mcp-index.ts +5 -1
  25. package/src/lib/moved-api-pages.js +16 -1
  26. package/src/lib/openapi-render.ts +5 -0
  27. package/src/lib/protected-sections.js +238 -0
  28. package/src/lib/scalar-anchors.js +56 -0
  29. package/src/lib/scalar-document.js +63 -0
  30. package/src/lib/scalar-fetch.js +89 -0
  31. package/src/lib/scalar-reference-alias.js +32 -0
  32. package/src/lib/scalar-reference.js +105 -0
  33. package/src/lib/scalar-theme.js +175 -0
  34. package/src/lib/scalar-try-it-alias.js +31 -0
  35. package/src/pages/[...slug].astro +133 -23
  36. package/src/pages/llms-full.txt.ts +4 -0
  37. package/src/pages/og/[...slug].png.ts +11 -2
  38. package/src/scripts/scalar-reference.ts +151 -0
  39. package/src/scripts/scalar-try-it.ts +145 -0
  40. package/writedocs.schema.json +476 -71
@@ -0,0 +1,89 @@
1
+ // How a request from Scalar's "Try it" leaves the browser - the `customFetch`
2
+ // writedocs gives Scalar's API client (src/scripts/scalar-try-it.ts).
3
+ //
4
+ // Scalar's own way to reach an API that refuses browser calls is a proxy URL
5
+ // it rewrites every request to, `<proxy>?scalar_url=<url>` - by default its
6
+ // own hosted proxy.scalar.com. writedocs never uses that: Scalar gets no
7
+ // proxy URL (its modal then sends straight to the API), and this function
8
+ // applies writedocs' own rules, the ones writedocs' playground follows
9
+ // (ApiReferencePanel.astro's send handler):
10
+ //
11
+ // - the request goes straight to the API first, so a reader's key reaches
12
+ // only the API;
13
+ // - only when the browser blocks it (fetch() rejects - CORS, or the host
14
+ // can't be reached) and writedocs.json's `api.proxy` is on, the same
15
+ // request goes again through writedocs' proxy, which is cors-anywhere
16
+ // style: the target URL right after the base. The response then carries
17
+ // an `x-writedocs-proxy` header, which Scalar lists with the others;
18
+ // - not a request the browser sends without asking first (a CORS "simple"
19
+ // request) that is a POST: it may already have reached the API, and
20
+ // sending it again could run it twice;
21
+ // - a request the reader cancelled isn't sent again.
22
+ //
23
+ // Plain JavaScript (Request/Response, nothing else) so the tests can import it.
24
+
25
+ /** writedocs' CORS proxy - the same one as PROXY_BASE_URL in
26
+ * ApiReferencePanel.astro (kept there as a literal, in that page script). */
27
+ export const WRITEDOCS_PROXY_URL = 'https://proxy.writechoice.io/';
28
+
29
+ /** The header a response sent through the proxy carries, and what it says. */
30
+ export const PROXY_HEADER = 'x-writedocs-proxy';
31
+ export const PROXY_HEADER_VALUE = 'sent through the writedocs proxy - the API blocks direct browser requests (CORS)';
32
+
33
+ const METHODS_WITHOUT_BODY = new Set(['GET', 'HEAD']);
34
+ const SAFELISTED_HEADERS = new Set(['accept', 'accept-language', 'content-language', 'content-type']);
35
+ const SIMPLE_CONTENT_TYPES = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'];
36
+
37
+ /** Whether the browser sends this request without a preflight (the CORS
38
+ * spec's "simple" request): GET, HEAD or POST, and only safelisted headers,
39
+ * a Content-Type among the three a form can send. */
40
+ export function isSimpleRequest(method, headers) {
41
+ if (!['GET', 'HEAD', 'POST'].includes(method.toUpperCase())) return false;
42
+ for (const [name, value] of new Headers(headers)) {
43
+ if (!SAFELISTED_HEADERS.has(name.toLowerCase())) return false;
44
+ if (name.toLowerCase() === 'content-type' && !SIMPLE_CONTENT_TYPES.includes(value.split(';')[0].trim().toLowerCase())) return false;
45
+ }
46
+ return true;
47
+ }
48
+
49
+ /** A blocked request that mustn't be sent again: a simple POST may already
50
+ * have run on the API, the browser only kept its response from the page. */
51
+ export function mayHaveRun(method, headers) {
52
+ return method.toUpperCase() === 'POST' && isSimpleRequest(method, headers);
53
+ }
54
+
55
+ /** The fetch for Scalar's API client. `proxy`: writedocs.json's `api.proxy`.
56
+ * `fetchImpl`: the fetch to call (the browser's). */
57
+ export function tryItFetch({ proxy, fetchImpl = (...args) => globalThis.fetch(...args) }) {
58
+ return async function writedocsTryItFetch(input, init) {
59
+ const request = new Request(input, init);
60
+ // Read before the first try: sending it consumes the body.
61
+ const body = METHODS_WITHOUT_BODY.has(request.method) ? undefined : await request.clone().arrayBuffer();
62
+ try {
63
+ return await fetchImpl(request);
64
+ } catch (err) {
65
+ if (!proxy || request.signal?.aborted || err?.name === 'AbortError') throw err;
66
+ if (mayHaveRun(request.method, request.headers)) {
67
+ throw new Error('Blocked by the browser (CORS). Not retried through the writedocs proxy: this POST may already have reached the API.', { cause: err });
68
+ }
69
+ let res;
70
+ try {
71
+ res = await fetchImpl(WRITEDOCS_PROXY_URL + request.url, {
72
+ method: request.method,
73
+ headers: request.headers,
74
+ body,
75
+ signal: request.signal,
76
+ });
77
+ } catch (proxyErr) {
78
+ throw new Error('Request failed through the writedocs proxy too - the base URL may be unreachable from the internet.', { cause: proxyErr });
79
+ }
80
+ return markedAsProxied(res);
81
+ }
82
+ };
83
+ }
84
+
85
+ function markedAsProxied(res) {
86
+ const headers = new Headers(res.headers);
87
+ headers.set(PROXY_HEADER, PROXY_HEADER_VALUE);
88
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
89
+ }
@@ -0,0 +1,32 @@
1
+ // Which component the alias `writedocs/scalar-reference` (astro.config.mjs)
2
+ // resolves to - [...slug].astro imports the page of Scalar's API reference
3
+ // (an OpenAPI group with `openapi.renderer: "scalar"`) through it.
4
+ //
5
+ // Why an alias, as for the API pages' Scalar Try it
6
+ // (lib/scalar-try-it-alias.js): Astro bundles the <script> of every
7
+ // component a page imports, rendered or not, and ScalarReference.astro's
8
+ // script import()s Scalar - a plain import would put Scalar's chunks in the
9
+ // _astro/ folder of every site. Through the alias a build imports
10
+ // ScalarReference.astro only when writedocs.json has a group asking for it;
11
+ // otherwise an empty component, and the build is the same as before the
12
+ // option existed.
13
+ //
14
+ // `writedocs dev` always gets the real one: it reads writedocs.json again on
15
+ // every request, so a switch to "scalar" mid-session works without a restart.
16
+ //
17
+ // Plain JavaScript so the tests can import it.
18
+ import path from 'node:path';
19
+
20
+ export const SCALAR_REFERENCE_ALIAS = 'writedocs/scalar-reference';
21
+
22
+ /** What src/scripts/scalar-reference.ts imports from Scalar - for Vite's
23
+ * optimizeDeps in `writedocs dev` (astro.config.mjs), so its first load
24
+ * doesn't reload the page. Keep in step with its imports (the tests check). */
25
+ export const SCALAR_REFERENCE_OPTIMIZED_DEPS = ['@scalar/api-reference'];
26
+
27
+ /** The component file the alias points at. `scalar`: whether a group of
28
+ * the site shows Scalar's reference (lib/scalar-reference.js). */
29
+ export function scalarReferenceComponent({ scalar, command, packageRoot }) {
30
+ const file = scalar || command === 'dev' ? 'ScalarReference.astro' : 'NoScalarReference.astro';
31
+ return path.join(packageRoot, 'src/components', file);
32
+ }
@@ -0,0 +1,105 @@
1
+ // OpenAPI groups with `openapi.renderer: "scalar"`: Scalar's API reference on
2
+ // one page, at the group's `path`, in the site's layout.
3
+ //
4
+ // generate-api-pages.js works each one out before Astro starts and writes,
5
+ // under writedocsTempDir()/openapi/ (never published):
6
+ // - scalar.json - every such group: `{ group, slug, title, operations }`,
7
+ // `slug` the reference page's address ("api" for "/api"), and per
8
+ // operation the page writedocs still builds for it (`slug`) and its
9
+ // fragment in the reference (`anchor`, lib/scalar-anchors.js);
10
+ // - <path>/reference-document.json - the group's spec, bundled into one
11
+ // document (its own $refs kept, other files' brought in), which the
12
+ // reference page carries inside its HTML (ScalarReference.astro) - never a
13
+ // file of its own, so a group in a protected section stays behind the
14
+ // section's rule;
15
+ // - the reference page itself, generated-docs/<path>.mdx: the title, and a
16
+ // list of the operations - what its .md copy and llms-full.txt say.
17
+ //
18
+ // The per-operation pages are generated as for any OpenAPI group (search,
19
+ // llms.txt, llms-full.txt, MCP and the .md copies are made from them) and
20
+ // stay in the navigation data - so their section, access rule and search
21
+ // space don't change - but [...slug].astro keeps them out of the sidebar
22
+ // and pagination, marks them noindex, sends a reader on to their operation
23
+ // in the reference, and gives search their anchor (scalarOperationTargets()
24
+ // below).
25
+ //
26
+ // Plain JavaScript: read by the CLI, astro.config.mjs and the pages.
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
30
+
31
+ /** The list of the site's Scalar references (JSON). */
32
+ export const scalarReferencesFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'scalar.json');
33
+
34
+ /** A group's bundled spec (JSON), for its reference page. `pathPrefix`: the
35
+ * group's `openapi.path` without its slashes ("api", "v2/api"). */
36
+ export const scalarDocumentFile = (contentDir, pathPrefix) =>
37
+ path.join(writedocsTempDir(contentDir), 'openapi', ...pathPrefix.split('/'), 'reference-document.json');
38
+
39
+ /** `[{ group, slug, title, operations: [{ slug, method, path, anchor }] }]` -
40
+ * empty without any, or before generate-api-pages.js has run. */
41
+ export function readScalarReferences(contentDir) {
42
+ try {
43
+ const list = JSON.parse(fs.readFileSync(scalarReferencesFile(contentDir), 'utf-8'));
44
+ return Array.isArray(list) ? list.filter((r) => typeof r?.slug === 'string' && Array.isArray(r.operations)) : [];
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ /** The reference whose page is `slug` (a page's file id), or null. */
51
+ export function scalarReferenceAt(references, slug) {
52
+ return references.find((r) => r.slug === slug) ?? null;
53
+ }
54
+
55
+ /** The address of an operation in its reference, in the site (no basePath):
56
+ * "/api/#tag/pets/GET/pets". */
57
+ export function scalarOperationHref(reference, operation) {
58
+ return `/${reference.slug}/#${operation.anchor}`;
59
+ }
60
+
61
+ /** Whether a sidebar (buildNavTree()'s nodes) would list nothing but the
62
+ * page `slug` - the reference of an API tab, say. Its page then leaves the
63
+ * site's sidebar out, and Scalar's own (its operations) takes its place;
64
+ * otherwise the two stand side by side. */
65
+ export function sidebarListsOnly(nodes, slug) {
66
+ const entries = [];
67
+ const walk = (list) => {
68
+ for (const node of list) {
69
+ if (node.kind === 'group') {
70
+ if (node.pageSlug) entries.push(node.pageSlug);
71
+ walk(node.children ?? []);
72
+ } else {
73
+ entries.push(node.kind === 'page' ? node.slug : node.href);
74
+ }
75
+ }
76
+ };
77
+ walk(nodes);
78
+ return entries.length === 1 && entries[0] === slug;
79
+ }
80
+
81
+ /** Page (file id) -> where its reader goes instead, for every operation page
82
+ * of a Scalar group: `{ href, reference }` - `href` the address in the site
83
+ * ("/api/#tag/pets/GET/pets", no basePath), `reference` the reference's
84
+ * slug. A hand-written page that claims one of the group's operations
85
+ * (frontmatter `openapi`) is in it too: the reference shows that
86
+ * operation. */
87
+ export function scalarOperationTargets(references) {
88
+ const targets = new Map();
89
+ for (const reference of references) {
90
+ for (const operation of reference.operations) {
91
+ targets.set(operation.slug, { href: scalarOperationHref(reference, operation), reference: reference.slug });
92
+ }
93
+ }
94
+ return targets;
95
+ }
96
+
97
+ /** The script that sends a reader from an operation page to `href` (the
98
+ * address with the site's basePath): replace(), so Back skips the page.
99
+ * Only with JavaScript - Scalar's reference needs it too, so a reader
100
+ * without it stays on the operation's own page, which shows everything.
101
+ * Safe inside a <script> (no `<` left). */
102
+ export function scalarRedirectScript(href) {
103
+ const backslash = String.fromCharCode(92);
104
+ return `location.replace(${JSON.stringify(href).replace(/</g, `${backslash}u003c`)});`;
105
+ }
@@ -0,0 +1,175 @@
1
+ // The look of Scalar's "Try it" on a writedocs site: Scalar's documented
2
+ // theme variables (--scalar-*, scalar.com/products/api-references/themes),
3
+ // each set from one of the site's own tokens (--wd-*, BaseLayout.astro) -
4
+ // so the modal has the site's colors (writedocs.json `styles.colors`), its
5
+ // body font, and follows its light/dark mode as it changes: the tokens
6
+ // change under [data-theme], and src/scripts/scalar-try-it.ts swaps the
7
+ // host's .light-mode/.dark-mode class (which Scalar's own rules key off) in
8
+ // step with it.
9
+ //
10
+ // Scalar's own fonts (Inter, JetBrains Mono) come from its font CDN; they're
11
+ // never loaded here - the body font is the site's, the code font the
12
+ // system's monospace stack.
13
+ //
14
+ // Plain JavaScript so the tests can import it. A string, injected with
15
+ // Scalar's CSS when a reader first opens Try it - no page carries it before.
16
+
17
+ /** The class of the element the modal is mounted in. */
18
+ export const SCALAR_HOST_CLASS = 'wd-scalar-host';
19
+
20
+ const MONO = 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
21
+
22
+ /** Scalar variable -> its value from the site's tokens. */
23
+ export const SCALAR_THEME_VARIABLES = {
24
+ '--scalar-font': 'var(--wd-font-family-body, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)',
25
+ '--scalar-font-code': MONO,
26
+ '--scalar-background-1': 'var(--wd-background)',
27
+ '--scalar-background-2': 'var(--wd-surface)',
28
+ '--scalar-background-3': 'color-mix(in srgb, var(--wd-text) 8%, var(--wd-surface))',
29
+ '--scalar-background-4': 'color-mix(in srgb, var(--wd-text) 12%, var(--wd-surface))',
30
+ '--scalar-background-accent': 'color-mix(in srgb, var(--wd-primary) 14%, transparent)',
31
+ '--scalar-color-1': 'var(--wd-heading)',
32
+ '--scalar-color-2': 'var(--wd-text)',
33
+ '--scalar-color-3': 'var(--wd-text-muted)',
34
+ '--scalar-color-accent': 'var(--wd-primary)',
35
+ '--scalar-border-color': 'var(--wd-border)',
36
+ '--scalar-link-color': 'var(--wd-primary)',
37
+ '--scalar-link-color-hover': 'var(--wd-primary)',
38
+ '--scalar-button-1': 'var(--wd-primary)',
39
+ '--scalar-button-1-color': 'var(--wd-on-primary)',
40
+ '--scalar-button-1-hover': 'color-mix(in srgb, var(--wd-primary) 88%, var(--wd-text))',
41
+ '--scalar-sidebar-background-1': 'var(--wd-background)',
42
+ '--scalar-sidebar-color-1': 'var(--wd-heading)',
43
+ '--scalar-sidebar-color-2': 'var(--wd-text-muted)',
44
+ '--scalar-sidebar-color-active': 'var(--wd-primary)',
45
+ '--scalar-sidebar-border-color': 'var(--wd-border)',
46
+ '--scalar-sidebar-item-hover-background': 'var(--wd-surface)',
47
+ '--scalar-sidebar-item-hover-color': 'var(--wd-heading)',
48
+ '--scalar-sidebar-item-active-background': 'color-mix(in srgb, var(--wd-primary) 12%, transparent)',
49
+ '--scalar-sidebar-search-background': 'var(--wd-surface)',
50
+ '--scalar-sidebar-search-border-color': 'var(--wd-border)',
51
+ '--scalar-sidebar-search-color': 'var(--wd-text)',
52
+ };
53
+
54
+ /** The CSS: the variables on the host, in either mode - two classes, so it
55
+ * wins over Scalar's own `.light-mode`/`.dark-mode` defaults on the same
56
+ * element, whatever the order the two style sheets end up in. And the
57
+ * host's stacking level: Scalar's modal is position: fixed with no
58
+ * z-index, so without one the site's sticky top bar (z-index 10) covered
59
+ * its header. 100 is writedocs' own Try-it modal's level
60
+ * (.wd-api-modal-overlay, ApiReferencePanel.astro). */
61
+ export function scalarThemeCss() {
62
+ const body = Object.entries(SCALAR_THEME_VARIABLES)
63
+ .map(([name, value]) => ` ${name}: ${value};`)
64
+ .join('\n');
65
+ return (
66
+ `.${SCALAR_HOST_CLASS} {\n position: relative;\n z-index: 100;\n}\n` +
67
+ `.${SCALAR_HOST_CLASS}.light-mode,\n.${SCALAR_HOST_CLASS}.dark-mode {\n${body}\n}\n`
68
+ );
69
+ }
70
+
71
+ /** The element Scalar's API reference (`openapi.renderer: "scalar"`) is
72
+ * mounted in - ScalarReference.astro. */
73
+ export const SCALAR_REFERENCE_CLASS = 'wd-scalar-reference';
74
+
75
+ /** The reference's own variables, on its element too: Scalar's sidebar and
76
+ * sections take the measurements of the site's sidebar (NavTree.astro,
77
+ * Sidebar.astro) wherever Scalar has a variable for one. */
78
+ export const SCALAR_REFERENCE_VARIABLES = {
79
+ // The site's sidebar: 260px wide (.wd-sidebar-col), padded 1.5rem 1rem
80
+ // 1.5rem 0 (.wd-sidebar).
81
+ '--scalar-sidebar-width': '260px',
82
+ '--scalar-sidebar-padding': '1.5rem 1rem 1.5rem 0',
83
+ // An entry: the site's text, weight 400; hovered, the heading color on a
84
+ // 6% tint of the primary; selected, the primary on 12%, weight 500.
85
+ '--scalar-sidebar-color-2': 'var(--wd-nav-text)',
86
+ '--scalar-sidebar-font-weight': '400',
87
+ '--scalar-sidebar-font-weight-active': '500',
88
+ '--scalar-sidebar-item-hover-color': 'var(--wd-nav-title)',
89
+ '--scalar-sidebar-item-hover-background': 'color-mix(in srgb, var(--wd-primary) 6%, transparent)',
90
+ '--scalar-sidebar-item-active-background': 'color-mix(in srgb, var(--wd-primary) 12%, transparent)',
91
+ '--scalar-sidebar-color-active': 'var(--wd-primary)',
92
+ // The vertical guide beside nested entries: the site's border color (the
93
+ // selected entry's own bar is its border, below).
94
+ '--scalar-sidebar-indent-border': 'var(--wd-border)',
95
+ '--scalar-sidebar-indent-border-hover': 'var(--wd-border)',
96
+ '--scalar-sidebar-indent-border-active': 'var(--wd-border)',
97
+ };
98
+
99
+ /** Where Scalar has no variable: `[selector, declarations, why]`, every
100
+ * selector inside the reference's element, none touching the site's own
101
+ * layout. Scalar's classes they rely on are listed in
102
+ * docs/dev/docs/scalar-reference.mdx, to check when updating Scalar. No
103
+ * !important: each wins on specificity, or on coming after Scalar's CSS in
104
+ * the same <style> (src/scripts/scalar-reference.ts). */
105
+ const R = `.${SCALAR_REFERENCE_CLASS}`;
106
+ const ENTRY = `${R} a:has(> .scalar-sidebar-indent)`;
107
+ export const SCALAR_REFERENCE_RULES = [
108
+ [ENTRY, 'padding: 0.2rem 0.75rem; font-size: 0.9rem; line-height: 1.6; border-radius: 0 0.4rem 0.4rem 0; border-left: 1px solid transparent;', "a sidebar entry (Scalar's link holding its indent): the site's entry box - .wd-nav-list a"],
109
+ [`${ENTRY}:hover, ${R} a:has(> .scalar-sidebar-indent-selected)`, 'border-left-color: var(--wd-primary);', "the bar at the left of a hovered or the selected entry, as the site's"],
110
+ [`${ENTRY}:focus-visible`, 'outline: revert; outline-offset: revert;', "the keyboard focus ring: the browser's own, as on the site's links (Scalar draws its own solid one)"],
111
+ [`${ENTRY} + button`, 'right: calc(0.75rem - 4px); color: var(--wd-text-muted);', "a group's arrow: where the site's chevron is, in its color (the button has 4px of padding)"],
112
+ [`${ENTRY} + button > div, ${ENTRY} + button svg`, 'width: 10px; height: 10px;', "the arrow's size: the site's chevron's (its box too, so it sits where the chevron does)"],
113
+ [`${R} .section-header`, '--font-size: 2rem; --font-weight: 700; line-height: 1.6;', "the reference's title and each section's: the site's h1"],
114
+ [`${R} .operation-title`, '--font-size: 1.5rem; --font-weight: 700; line-height: 1.6;', "an operation's title: the site's h2"],
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
+ [`${R} .section`, 'padding-block: 2.75rem;', "the space around a section: the site's before an h2"],
117
+ [`${R} .introduction-section`, 'padding-top: 1.5rem;', "the reference's title where the site's h1 is"],
118
+ [`${R} .introduction-section .section-content`, 'position: relative;', 'so the version badges can sit above the title'],
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
+ ];
121
+
122
+ /** The reference's CSS: the same variables on its element - Scalar sets its
123
+ * own on <body>'s .light-mode/.dark-mode class (src/scripts/scalar-
124
+ * reference.ts keeps that class in step with the site's theme), and these,
125
+ * closer to every element of the reference, win - then its own variables,
126
+ * and the rules above. And where its sticky parts stop: below the site's
127
+ * top bar (--wd-topbar-offset, topbar-offset.ts), which Scalar reads as a
128
+ * custom header's height. The content's left margin is the site's article
129
+ * padding when Scalar's own container query would give it 60px. */
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('');
138
+ const declarations = (vars) =>
139
+ Object.entries(vars)
140
+ .map(([name, value]) => ` ${name}: ${value};`)
141
+ .join('\n');
142
+ const rules = SCALAR_REFERENCE_RULES.map(([selector, body]) => `${selector} {\n ${body}\n}`).join('\n');
143
+ return (
144
+ `${R} {
145
+ --scalar-custom-header-height: var(--wd-topbar-offset, 4rem);
146
+ ${declarations(SCALAR_THEME_VARIABLES)}
147
+ ${declarations(SCALAR_REFERENCE_VARIABLES)}
148
+ }
149
+ ` +
150
+ `${rules}
151
+ ` +
152
+ // Below Scalar's own breakpoint its sidebar is a menu under its bar - the
153
+ // site's own menu has no padding above its first entry either.
154
+ `@media (width < 1000px) {
155
+ ${R} {
156
+ --scalar-sidebar-padding: 0 1rem 1.5rem 0;
157
+ }
158
+ }
159
+ ` +
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.
162
+ `@media (max-width: 860px) {
163
+ ${R} .introduction-section {
164
+ padding-top: 2.25rem;
165
+ }
166
+ }
167
+ ` +
168
+ `${CONTAINER_QUERY} references-container (min-width: 901px) {
169
+ ${R} .section-container {
170
+ padding-inline: 1.5rem;
171
+ }
172
+ }
173
+ `
174
+ );
175
+ }
@@ -0,0 +1,31 @@
1
+ // Which component the alias `writedocs/scalar-try-it` (astro.config.mjs)
2
+ // resolves to - ApiReferencePanel.astro imports Scalar's "Try it" through it.
3
+ //
4
+ // Why an alias and not a plain import: Astro bundles the <script> of every
5
+ // component a page imports, rendered or not, and ScalarTryIt.astro's script
6
+ // import()s Scalar - so a plain import would put Scalar's chunks (hundreds of
7
+ // files) in the _astro/ folder of every site with an API page, Scalar or not.
8
+ // Through the alias, a build imports ScalarTryIt.astro only when
9
+ // writedocs.json asks for `api.playground: "scalar"`; otherwise an empty
10
+ // component that renders nothing, and the build is the same as before the
11
+ // option existed.
12
+ //
13
+ // `writedocs dev` always gets the real one: it reads writedocs.json again on
14
+ // every request, so a switch to "scalar" mid-session works without a restart
15
+ // (and dev writes no dist/).
16
+ //
17
+ // Plain JavaScript so the tests can import it.
18
+ import path from 'node:path';
19
+
20
+ export const SCALAR_TRY_IT_ALIAS = 'writedocs/scalar-try-it';
21
+
22
+ /** What src/scripts/scalar-try-it.ts imports from Scalar - for Vite's
23
+ * optimizeDeps in `writedocs dev` (astro.config.mjs). Keep in step with its
24
+ * imports (the tests check). */
25
+ export const SCALAR_OPTIMIZED_DEPS = ['@scalar/api-client/modal', '@scalar/workspace-store/client', '@scalar/workspace-store/events'];
26
+
27
+ /** The component file the alias points at. */
28
+ export function scalarTryItComponent({ playground, command, packageRoot }) {
29
+ const file = playground === 'scalar' || command === 'dev' ? 'ScalarTryIt.astro' : 'NoScalarTryIt.astro';
30
+ return path.join(packageRoot, 'src/components', file);
31
+ }