@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.
- package/astro.config.mjs +43 -3
- package/package.json +4 -1
- package/src/cli/build.js +39 -3
- package/src/cli/dev.js +16 -0
- package/src/cli/generate-api-pages.js +94 -3
- package/src/cli/run-pagefind.js +67 -22
- package/src/cli/write-redirects-file.js +7 -1
- package/src/components/ApiReferencePanel.astro +16 -3
- package/src/components/NoScalarReference.astro +6 -0
- package/src/components/NoScalarTryIt.astro +5 -0
- package/src/components/ScalarReference.astro +80 -0
- package/src/components/ScalarTryIt.astro +76 -0
- package/src/layout/BaseLayout.astro +7 -0
- package/src/layout/components/LockMark.astro +28 -0
- package/src/layout/components/MobileMenu.astro +4 -0
- package/src/layout/components/Sidebar.astro +3 -2
- package/src/layout/components/TopBar.astro +9 -0
- package/src/lib/config-schema.js +58 -6
- package/src/lib/config-schema.ts +75 -8
- package/src/lib/config.ts +40 -13
- package/src/lib/content-check.js +18 -3
- package/src/lib/json-schema-descriptions.js +5 -1
- package/src/lib/llms-index.ts +5 -0
- package/src/lib/mcp-index.ts +5 -1
- package/src/lib/moved-api-pages.js +16 -1
- package/src/lib/openapi-render.ts +5 -0
- package/src/lib/protected-sections.js +238 -0
- package/src/lib/scalar-anchors.js +56 -0
- package/src/lib/scalar-document.js +63 -0
- package/src/lib/scalar-fetch.js +89 -0
- package/src/lib/scalar-reference-alias.js +32 -0
- package/src/lib/scalar-reference.js +105 -0
- package/src/lib/scalar-theme.js +175 -0
- package/src/lib/scalar-try-it-alias.js +31 -0
- package/src/pages/[...slug].astro +133 -23
- package/src/pages/llms-full.txt.ts +4 -0
- package/src/pages/og/[...slug].png.ts +11 -2
- package/src/scripts/scalar-reference.ts +151 -0
- package/src/scripts/scalar-try-it.ts +145 -0
- package/writedocs.schema.json +476 -71
|
@@ -74,11 +74,25 @@ import Visibility from "../../packages/components/src/components/Visibility.astr
|
|
|
74
74
|
import { Tree, FileTree, Color, GitHub } from "../../packages/components/src/components/compound";
|
|
75
75
|
import ApiPlayground from "../components/ApiPlayground.astro";
|
|
76
76
|
import ApiReferencePanel from "../components/ApiReferencePanel.astro";
|
|
77
|
+
// Scalar's API reference, the page of an OpenAPI group with `renderer:
|
|
78
|
+
// "scalar"` - through an alias, so a site without one doesn't bundle Scalar
|
|
79
|
+
// (lib/scalar-reference-alias.js).
|
|
80
|
+
import ScalarReference from "writedocs/scalar-reference";
|
|
81
|
+
import {
|
|
82
|
+
readScalarReferences,
|
|
83
|
+
scalarReferenceAt,
|
|
84
|
+
sidebarListsOnly,
|
|
85
|
+
scalarOperationTargets,
|
|
86
|
+
scalarRedirectScript,
|
|
87
|
+
} from "../lib/scalar-reference.js";
|
|
77
88
|
import { searchScope, sectionTrail, ALL_SCOPES } from "../lib/search-scope.js";
|
|
78
89
|
import { selectorPlacements } from "../lib/selector-placement.js";
|
|
79
90
|
import { spaceOf } from "../lib/hidden-sections.js";
|
|
91
|
+
import { protectedPages, searchSpaceOf } from "../lib/protected-sections.js";
|
|
92
|
+
import { isNoindex } from "../lib/seo-tags.js";
|
|
80
93
|
import { navigationPageOrder } from "../lib/pages.js";
|
|
81
94
|
import { folderRedirects } from "../lib/folder-redirects.js";
|
|
95
|
+
import { readMovedApiPages, protectedMovedApiPages } from "../lib/moved-api-pages.js";
|
|
82
96
|
import { DRAFT_BANNER_HTML } from "../lib/drafts.js";
|
|
83
97
|
import { oncePerBuild } from "../lib/build-memo.js";
|
|
84
98
|
// writedocs.json's `basePath` - the addresses below stay site addresses
|
|
@@ -184,17 +198,20 @@ export async function getStaticPaths() {
|
|
|
184
198
|
// a real, directly-linkable page (an in-progress draft, an unlisted
|
|
185
199
|
// landing page, etc.).
|
|
186
200
|
const claimedFileIds = new Set<string>();
|
|
201
|
+
// The operation pages of a Scalar group (lib/scalar-reference.js) aren't in
|
|
202
|
+
// the sidebar either.
|
|
203
|
+
const scalarOperations = scalarOperationTargets(readScalarReferences(contentDir));
|
|
187
204
|
|
|
188
205
|
const pageRoutes = sections.flatMap((section, sectionIndex) => {
|
|
189
206
|
const flatNav = flattenNav(section.pages);
|
|
190
207
|
// Prev/next skip pages that aren't in the sidebar (frontmatter
|
|
191
|
-
// `hidden
|
|
192
|
-
// link) - the reader should land on the
|
|
193
|
-
// have clicked in the sidebar. Inlined for
|
|
194
|
-
// error branch below.
|
|
208
|
+
// `hidden`, a Scalar group's operation pages) or aren't pages at all
|
|
209
|
+
// (frontmatter `url`, an external link) - the reader should land on the
|
|
210
|
+
// next page they could also have clicked in the sidebar. Inlined for
|
|
211
|
+
// the same reason as the error branch below.
|
|
195
212
|
const isPaginationStop = (slug: string) => {
|
|
196
213
|
const data = entryByFileId.get(slug)?.data;
|
|
197
|
-
return Boolean(data) && !data!.hidden && !data!.url;
|
|
214
|
+
return Boolean(data) && !data!.hidden && !data!.url && !scalarOperations.has(slug);
|
|
198
215
|
};
|
|
199
216
|
return flatNav.map((navEntry, i) => {
|
|
200
217
|
const entry = entryByFileId.get(navEntry.slug);
|
|
@@ -263,7 +280,7 @@ export async function getStaticPaths() {
|
|
|
263
280
|
const next =
|
|
264
281
|
flattenNav(landing.pages).find((e) => {
|
|
265
282
|
const data = entryByFileId.get(e.slug)?.data;
|
|
266
|
-
return Boolean(data) && !data!.hidden && !data!.url;
|
|
283
|
+
return Boolean(data) && !data!.hidden && !data!.url && !scalarOperations.has(e.slug);
|
|
267
284
|
}) ?? null;
|
|
268
285
|
const urlSlug = normalizeEntryId(entry.id);
|
|
269
286
|
if (entry.data.url) {
|
|
@@ -303,8 +320,12 @@ export async function getStaticPaths() {
|
|
|
303
320
|
// (`/docs/creator/`) redirect to the first page under them
|
|
304
321
|
// (lib/folder-redirects.js). Preferred in the reader's order: navigation
|
|
305
322
|
// order, public sections before hidden ones, pages outside the
|
|
306
|
-
// navigation
|
|
323
|
+
// navigation after them - and protected pages (lib/protected-sections.js)
|
|
324
|
+
// last, so a folder with any page anyone can read leads to one.
|
|
307
325
|
const slugOf = (route: { params: { slug?: string } }) => route.params.slug ?? "index";
|
|
326
|
+
const protectedRules = protectedPages(config.navigation);
|
|
327
|
+
const ruleOfRoute = (route: { props: { entry?: DocsEntry } }) =>
|
|
328
|
+
route.props.entry ? (protectedRules.get(fileIdForEntry(contentDir, packageRoot, route.props.entry)) ?? null) : null;
|
|
308
329
|
const inHiddenSection = sections.map((section) => spaceOf(section.path) !== null);
|
|
309
330
|
const contentRoutes = pageRoutes.filter((route) => !("redirectTo" in route.props));
|
|
310
331
|
// An item's own page counts where the navigation names it: before the
|
|
@@ -325,25 +346,48 @@ export async function getStaticPaths() {
|
|
|
325
346
|
...contentRoutes,
|
|
326
347
|
...landingRoutes.filter((route) => !("redirectTo" in route.props)),
|
|
327
348
|
] as ContentRoute[];
|
|
349
|
+
const isProtected = (route: ContentRoute) => ruleOfRoute(route) !== null;
|
|
328
350
|
const folderTargets = [
|
|
329
351
|
...navContent
|
|
330
|
-
.filter((route) => !inHiddenItem(route))
|
|
352
|
+
.filter((route) => !inHiddenItem(route) && !isProtected(route))
|
|
331
353
|
.sort((a, b) => orderOf(a) - orderOf(b))
|
|
332
354
|
.map(slugOf),
|
|
333
355
|
...navContent
|
|
334
|
-
.filter(inHiddenItem)
|
|
356
|
+
.filter((route) => inHiddenItem(route) && !isProtected(route))
|
|
335
357
|
.sort((a, b) => orderOf(a) - orderOf(b))
|
|
336
358
|
.map(slugOf),
|
|
337
359
|
...hiddenRoutes.map(slugOf),
|
|
360
|
+
...navContent
|
|
361
|
+
.filter(isProtected)
|
|
362
|
+
.sort((a, b) => orderOf(a) - orderOf(b))
|
|
363
|
+
.map(slugOf),
|
|
338
364
|
];
|
|
339
365
|
const takenAddresses = new Set([
|
|
340
366
|
...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
|
|
341
367
|
...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
|
|
342
368
|
]);
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
369
|
+
// The protected addresses, `{ slug, rule }`: the pages, and a folder
|
|
370
|
+
// redirect that leads to one - its folder has no other page, and the
|
|
371
|
+
// redirect page names the page, so it's behind the same rule.
|
|
372
|
+
const protectedRoutes = navContent.flatMap((route) => {
|
|
373
|
+
const rule = ruleOfRoute(route);
|
|
374
|
+
return rule ? [{ slug: slugOf(route), rule }] : [];
|
|
375
|
+
});
|
|
376
|
+
const ruleBySlug = new Map(protectedRoutes.map((route) => [route.slug, route.rule]));
|
|
377
|
+
const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => {
|
|
378
|
+
const rule = ruleBySlug.get(target);
|
|
379
|
+
if (rule) protectedRoutes.push({ slug: folder, rule });
|
|
380
|
+
return { params: { slug: folder }, props: { redirectTo: `/${target}/`, temporary: true } };
|
|
381
|
+
});
|
|
382
|
+
// The old addresses of generated API pages (lib/moved-api-pages.js - the
|
|
383
|
+
// redirect pages are astro.config.mjs's): one that leads to a protected
|
|
384
|
+
// page is behind the same rule, and kept out of `_redirects`.
|
|
385
|
+
protectedRoutes.push(...protectedMovedApiPages(readMovedApiPages(contentDir), (slug) => ruleBySlug.get(slug) ?? null));
|
|
386
|
+
// `writedocs build` names a file here; the build makes
|
|
387
|
+
// dist/.writedocs/access.json from it (lib/protected-sections.js,
|
|
388
|
+
// src/cli/build.js) - the og route hands its list over the same way.
|
|
389
|
+
const accessFile = process.env.WRITEDOCS_ACCESS_FILE;
|
|
390
|
+
if (accessFile) fs.writeFileSync(accessFile, JSON.stringify(protectedRoutes));
|
|
347
391
|
|
|
348
392
|
return [...rootRedirect, ...pageRoutes, ...landingRoutes, ...hiddenRoutes, ...folderRoutes];
|
|
349
393
|
}
|
|
@@ -462,9 +506,17 @@ const { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId } = await
|
|
|
462
506
|
const titleForSlug = (slug: string) => titleByFileId.get(slug) ?? slug;
|
|
463
507
|
const navTitleForSlug = (slug: string) => navTitleByFileId.get(slug) ?? slug;
|
|
464
508
|
const methodForSlug = (slug: string) => methodByFileId.get(slug) ?? null;
|
|
509
|
+
// The operation pages of the site's Scalar groups (lib/scalar-reference.js):
|
|
510
|
+
// left out of the sidebar like a `hidden` page, noindex, and each sends its
|
|
511
|
+
// reader to its operation in the reference.
|
|
512
|
+
const scalarReferences = oncePerBuild("slug:scalar-references", () => readScalarReferences(contentDir));
|
|
513
|
+
const scalarTargets = oncePerBuild("slug:scalar-targets", () => scalarOperationTargets(scalarReferences));
|
|
465
514
|
// Frontmatter that changes how a page appears in navigation (hidden, url,
|
|
466
515
|
// icon, tag, deprecated) - see buildNavTree() in lib/config.ts.
|
|
467
|
-
const navMetaForSlug = (slug: string) =>
|
|
516
|
+
const navMetaForSlug = (slug: string) => {
|
|
517
|
+
const data = entryByFileId.get(slug)?.data;
|
|
518
|
+
return data && scalarTargets.has(slug) ? { ...data, hidden: true } : data;
|
|
519
|
+
};
|
|
468
520
|
const hrefForSlug = (slug: string) => {
|
|
469
521
|
const raw = entryByFileId.get(slug)?.id ?? slug;
|
|
470
522
|
const effective = normalizeEntryId(raw);
|
|
@@ -475,6 +527,9 @@ const hrefForSlug = (slug: string) => {
|
|
|
475
527
|
// and what every "is this the active page" comparison below needs, since
|
|
476
528
|
// navTree/globalDropdowns are built from writedocs.json's file-id space.
|
|
477
529
|
const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
|
|
530
|
+
// The access rule the page is behind, or null (lib/protected-sections.js).
|
|
531
|
+
const protectedRules = oncePerBuild("slug:protected", () => protectedPages(config.navigation));
|
|
532
|
+
const pageRule = protectedRules.get(currentFileId) ?? null;
|
|
478
533
|
// A section's tree doesn't depend on which of its pages is open (NavTree.astro
|
|
479
534
|
// marks the current one), so it's built once per section in a build.
|
|
480
535
|
const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () =>
|
|
@@ -514,9 +569,10 @@ const pageSearchScope = isHidden ? { key: ALL_SCOPES, label: "" } : searchScope(
|
|
|
514
569
|
const pageSectionTrail = [entry.data.draft ? "Draft" : "", isHidden ? "" : sectionTrail(activeSection.path, breadcrumbs)]
|
|
515
570
|
.filter(Boolean)
|
|
516
571
|
.join(" · ");
|
|
517
|
-
// A page under a hidden navigation item searches its own
|
|
518
|
-
// site's (lib/hidden-sections.js,
|
|
519
|
-
|
|
572
|
+
// A page under a hidden or a protected navigation item searches its own
|
|
573
|
+
// index, not the site's (lib/hidden-sections.js, lib/protected-sections.js,
|
|
574
|
+
// cli/run-pagefind.js) - a protected page by its rule.
|
|
575
|
+
const pageSearchSpace = isHidden ? null : searchSpaceOf(activeSection.path, pageRule);
|
|
520
576
|
const languageSegment = isHidden ? undefined : activeSection.path.find((segment) => segment.kind === "language");
|
|
521
577
|
const pageLang = languageSegment
|
|
522
578
|
? (languageSegment.items[languageSegment.index] as { language: string }).language
|
|
@@ -536,6 +592,20 @@ const globalDropdowns = buildGlobalDropdowns(
|
|
|
536
592
|
// than recomputing it, since it already encodes the same
|
|
537
593
|
// frontmatter-slug-override-aware routing logic.
|
|
538
594
|
const pageSeo = mergeSeo(config.seo, entry.data.seo);
|
|
595
|
+
// A protected page (lib/protected-sections.js) is never indexed, whatever
|
|
596
|
+
// its own `seo` says - a `robots` that allows indexing gives way.
|
|
597
|
+
if (pageRule) {
|
|
598
|
+
if (!isNoindex(pageSeo)) pageSeo.robots = undefined;
|
|
599
|
+
pageSeo.noindex = true;
|
|
600
|
+
}
|
|
601
|
+
// An operation page of a Scalar group: the reference is the page to index,
|
|
602
|
+
// and the one the reader is sent to - by the script in <head>, and by search
|
|
603
|
+
// (data-wd-search-url below, cli/run-pagefind.js).
|
|
604
|
+
const scalarTarget = scalarTargets.get(currentFileId) ?? null;
|
|
605
|
+
if (scalarTarget) {
|
|
606
|
+
if (!isNoindex(pageSeo)) pageSeo.robots = undefined;
|
|
607
|
+
pageSeo.noindex = true;
|
|
608
|
+
}
|
|
539
609
|
// A page with no picture of its own for link previews gets the generated
|
|
540
610
|
// card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
|
|
541
611
|
if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
|
|
@@ -544,10 +614,14 @@ const currentPath = hrefForSlug(currentFileId);
|
|
|
544
614
|
// lib/item-pages.js) - a hidden page belongs to no language level.
|
|
545
615
|
const alternates = isHidden
|
|
546
616
|
? []
|
|
547
|
-
: languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined)
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
617
|
+
: languageAlternates(activeSection.path, currentFileId, activeSection.pages, landing !== undefined)
|
|
618
|
+
// Not a protected page in another language: a search engine can't
|
|
619
|
+
// read it (a protected page itself lists none - it's noindex).
|
|
620
|
+
.filter((a) => !protectedRules.has(a.slug))
|
|
621
|
+
.map((a) => ({
|
|
622
|
+
lang: a.lang,
|
|
623
|
+
href: hrefForSlug(a.slug),
|
|
624
|
+
}));
|
|
551
625
|
// The trail for the page's structured data (lib/json-ld.js): home, the
|
|
552
626
|
// groups above the page that have a page of their own, the page.
|
|
553
627
|
const structuredTrail = [
|
|
@@ -575,7 +649,18 @@ const landingWithoutSidebar =
|
|
|
575
649
|
landing !== undefined &&
|
|
576
650
|
flattenNav(landing.pages).length === 0 &&
|
|
577
651
|
!selectorPlacements(selectors, { sidebar: true }).includes("sidebar");
|
|
578
|
-
|
|
652
|
+
// The page of Scalar's API reference (an OpenAPI group with `renderer:
|
|
653
|
+
// "scalar"` - lib/scalar-reference.js): no table of contents, and the site's
|
|
654
|
+
// sidebar only when it lists more than this page - otherwise Scalar's own
|
|
655
|
+
// sidebar, with the API's operations, stands where it would be.
|
|
656
|
+
const scalarReference = scalarReferenceAt(scalarReferences, currentFileId);
|
|
657
|
+
const pageMode = scalarReference
|
|
658
|
+
? sidebarListsOnly(navTree, currentFileId)
|
|
659
|
+
? "frame"
|
|
660
|
+
: "wide"
|
|
661
|
+
: (isHidden || landingWithoutSidebar) && entry.data.mode === "default"
|
|
662
|
+
? "frame"
|
|
663
|
+
: entry.data.mode;
|
|
579
664
|
const showSidebar = pageMode === "default" || pageMode === "wide";
|
|
580
665
|
// Products inside a tab or dropdown switch at the top of the sidebar, not in
|
|
581
666
|
// the top bar (lib/selector-placement.js - TopBar.astro applies the same rule).
|
|
@@ -663,6 +748,7 @@ const components = {
|
|
|
663
748
|
alternates={alternates}
|
|
664
749
|
breadcrumbs={structuredTrail}
|
|
665
750
|
isApi={Boolean(entry.data.openapi)}
|
|
751
|
+
headScript={scalarTarget ? scalarRedirectScript(siteHref(scalarTarget.href)) : undefined}
|
|
666
752
|
>
|
|
667
753
|
{
|
|
668
754
|
showSidebar && (
|
|
@@ -676,7 +762,29 @@ const components = {
|
|
|
676
762
|
)
|
|
677
763
|
}
|
|
678
764
|
{
|
|
679
|
-
|
|
765
|
+
scalarReference ? (
|
|
766
|
+
// Scalar's reference, the width of the main column. Search finds the
|
|
767
|
+
// page by its title; the operations are found on their own pages
|
|
768
|
+
// (lib/scalar-reference.js). Its list of them is for a reader without
|
|
769
|
+
// JavaScript.
|
|
770
|
+
<div class="wd-canvas" data-pagefind-body>
|
|
771
|
+
<span hidden data-pagefind-meta="title">{entry.data.title}</span>
|
|
772
|
+
<ScalarReference contentDir={contentDir} slug={scalarReference.slug} proxy={config.api.proxy} download={!pageRule}>
|
|
773
|
+
<Content components={components} />
|
|
774
|
+
</ScalarReference>
|
|
775
|
+
<div
|
|
776
|
+
hidden
|
|
777
|
+
data-markdown-ignore
|
|
778
|
+
data-wd-search-scope={pageSearchScope.key}
|
|
779
|
+
data-wd-search-scope-label={pageSearchScope.label}
|
|
780
|
+
data-wd-search-space={pageSearchSpace?.id}
|
|
781
|
+
data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined}
|
|
782
|
+
data-pagefind-filter={`scope:${pageSearchScope.key}`}
|
|
783
|
+
>
|
|
784
|
+
{pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
|
|
785
|
+
</div>
|
|
786
|
+
</div>
|
|
787
|
+
) : isCanvasMode ? (
|
|
680
788
|
// 'custom' and 'blank' both get this treatment: no auto <h1>, no
|
|
681
789
|
// prev/next nav, none of .wd-article's own prose max-width/padding -
|
|
682
790
|
// just the page's own MDX/component content, edge to edge. Still gets
|
|
@@ -695,6 +803,7 @@ const components = {
|
|
|
695
803
|
data-wd-search-scope-label={pageSearchScope.label}
|
|
696
804
|
data-wd-search-space={pageSearchSpace?.id}
|
|
697
805
|
data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined}
|
|
806
|
+
data-wd-search-url={scalarTarget?.href}
|
|
698
807
|
data-pagefind-filter={`scope:${pageSearchScope.key}`}
|
|
699
808
|
>
|
|
700
809
|
{pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
|
|
@@ -739,6 +848,7 @@ const components = {
|
|
|
739
848
|
data-wd-search-scope-label={pageSearchScope.label}
|
|
740
849
|
data-wd-search-space={pageSearchSpace?.id}
|
|
741
850
|
data-wd-search-public={pageSearchSpace?.searchPublic ? "true" : undefined}
|
|
851
|
+
data-wd-search-url={scalarTarget?.href}
|
|
742
852
|
data-pagefind-filter={`scope:${pageSearchScope.key}`}
|
|
743
853
|
>
|
|
744
854
|
{pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
|
|
@@ -7,6 +7,7 @@ import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
|
|
|
7
7
|
import { pageMarkdown } from '../lib/openapi-markdown';
|
|
8
8
|
import { orderByNavigation } from '../lib/llms.js';
|
|
9
9
|
import { readProjectText } from '../lib/config-file.js';
|
|
10
|
+
import { protectedPages } from '../lib/protected-sections.js';
|
|
10
11
|
|
|
11
12
|
// The "everything, concatenated" half of the llms.txt pair - see
|
|
12
13
|
// llms.txt.ts (right next to this file) for the lightweight index half,
|
|
@@ -47,10 +48,13 @@ export const GET: APIRoute = async () => {
|
|
|
47
48
|
]);
|
|
48
49
|
const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
|
|
49
50
|
|
|
51
|
+
const protectedRules = protectedPages(config.navigation);
|
|
50
52
|
const unordered = entries
|
|
51
53
|
// Same noindex exclusion llms.txt.ts applies to its own listing -
|
|
52
54
|
// see that file's comment.
|
|
53
55
|
.filter((entry) => !entry.data.seo?.noindex)
|
|
56
|
+
// Same for a protected page (lib/protected-sections.js).
|
|
57
|
+
.filter((entry) => !protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry)))
|
|
54
58
|
// Same `url` exclusion as llms.txt.ts - a redirect, not a page.
|
|
55
59
|
.filter((entry) => !entry.data.url)
|
|
56
60
|
.map((entry: DocsEntry) => {
|
|
@@ -2,7 +2,8 @@ import { getCollection, type CollectionEntry } from 'astro:content';
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import type { APIRoute } from 'astro';
|
|
5
|
-
import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
|
|
5
|
+
import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo, fileIdForEntry } from '../../lib/config';
|
|
6
|
+
import { protectedPages } from '../../lib/protected-sections.js';
|
|
6
7
|
import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
|
|
7
8
|
import { ogImagePng } from '../../lib/og-image.js';
|
|
8
9
|
import { ogCardSet, ogCardOptions } from '../../lib/og-cards.js';
|
|
@@ -36,9 +37,17 @@ export async function getStaticPaths() {
|
|
|
36
37
|
]);
|
|
37
38
|
const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
|
|
38
39
|
|
|
40
|
+
// A protected page (lib/protected-sections.js) is noindex, and a noindex
|
|
41
|
+
// page gets no card - its link preview is the sign-in page's anyway.
|
|
42
|
+
const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
|
|
43
|
+
const protectedRules = protectedPages(config.navigation);
|
|
39
44
|
const set = ogCardSet(
|
|
40
45
|
config,
|
|
41
|
-
entries.map((entry) =>
|
|
46
|
+
entries.map((entry) => {
|
|
47
|
+
const seo = mergeSeo(config.seo, entry.data.seo);
|
|
48
|
+
if (protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry))) seo.noindex = true;
|
|
49
|
+
return { id: normalizeEntryId(entry.id), data: entry.data, seo };
|
|
50
|
+
}),
|
|
42
51
|
contentDir
|
|
43
52
|
);
|
|
44
53
|
const listFile = process.env.WRITEDOCS_OG_CARDS_FILE;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Scalar's API reference, the page of an OpenAPI group with
|
|
2
|
+
// `openapi.renderer: "scalar"`. ScalarReference.astro's page script
|
|
3
|
+
// import()s this module when the page loads; Vite puts it - Scalar, Vue and
|
|
4
|
+
// Scalar's CSS with it - in chunks of their own under _astro/, from the
|
|
5
|
+
// generator's own node_modules (never a CDN), loaded by this page only.
|
|
6
|
+
//
|
|
7
|
+
// - The document: the group's spec, bundled, from the JSON the page carries
|
|
8
|
+
// (ScalarReference.astro) - nothing is fetched.
|
|
9
|
+
// - Requests from its Try it: through tryItFetch() (lib/scalar-fetch.js), the
|
|
10
|
+
// rules of writedocs' playground and of the API pages' Scalar Try it -
|
|
11
|
+
// straight to the API, then writedocs' proxy when `api.proxy` allows;
|
|
12
|
+
// never Scalar's proxy (no proxyUrl; its client opens as a modal, which
|
|
13
|
+
// then uses none).
|
|
14
|
+
// - Off: Scalar's AI agent ("Ask AI" - on by default on localhost), its
|
|
15
|
+
// developer tools (and their "Deploy API"/"Generate SDK"), telemetry, its
|
|
16
|
+
// fonts from fonts.scalar.com, its own search (the site's is the search),
|
|
17
|
+
// its dark-mode toggle (the site's theme decides), and - in a protected
|
|
18
|
+
// section - the spec download.
|
|
19
|
+
// - Anchors: Scalar's tag and operation slugs come from
|
|
20
|
+
// lib/scalar-anchors.js, the functions the build used to send each
|
|
21
|
+
// operation's page and search result to its section.
|
|
22
|
+
// - The look: Scalar's CSS plus the site's tokens on the reference's element
|
|
23
|
+
// (lib/scalar-theme.js). Scalar puts .light-mode/.dark-mode on <body>; it
|
|
24
|
+
// follows <html data-theme> here.
|
|
25
|
+
// - Credentials: Scalar keeps what a reader types in memory (`persistAuth`
|
|
26
|
+
// would write it to localStorage - off). Like writedocs' playground they're
|
|
27
|
+
// kept for the visit and forgotten with the tab: copied to sessionStorage
|
|
28
|
+
// when the reader leaves the page and given back as Scalar's
|
|
29
|
+
// `authentication` when it opens again - under the key the API pages'
|
|
30
|
+
// Scalar Try it uses, by scheme name.
|
|
31
|
+
// - One reference per page: Astro's client-side navigation replaces the
|
|
32
|
+
// body, so it's destroyed before each swap.
|
|
33
|
+
import scalarCss from '@scalar/api-reference/style.css?inline';
|
|
34
|
+
import { createApiReference } from '@scalar/api-reference';
|
|
35
|
+
import { tryItFetch } from '../lib/scalar-fetch.js';
|
|
36
|
+
import { scalarReferenceThemeCss } from '../lib/scalar-theme.js';
|
|
37
|
+
import { scalarTagSlug, scalarOperationSlug } from '../lib/scalar-anchors.js';
|
|
38
|
+
|
|
39
|
+
export interface ReferenceRequest {
|
|
40
|
+
/** The element to mount in. */
|
|
41
|
+
el: HTMLElement;
|
|
42
|
+
/** The group's spec. */
|
|
43
|
+
document: Record<string, unknown>;
|
|
44
|
+
/** writedocs.json's `api.proxy`. */
|
|
45
|
+
proxy: boolean;
|
|
46
|
+
/** Whether the reader may download the spec - not in a protected section. */
|
|
47
|
+
download: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const STYLE_ID = 'wd-scalar-reference-style';
|
|
51
|
+
const AUTH_STORAGE_KEY = 'wd-scalar-auth';
|
|
52
|
+
|
|
53
|
+
type Instance = ReturnType<typeof createApiReference>;
|
|
54
|
+
type AuthAccess = { export: () => Record<string, { secrets?: Record<string, Record<string, unknown>> }> };
|
|
55
|
+
let current: { instance: Instance; observer: MutationObserver; saveAuth: () => void } | null = null;
|
|
56
|
+
|
|
57
|
+
function ensureStyles() {
|
|
58
|
+
if (document.getElementById(STYLE_ID)) return;
|
|
59
|
+
const style = document.createElement('style');
|
|
60
|
+
style.id = STYLE_ID;
|
|
61
|
+
style.textContent = `${scalarCss}\n${scalarReferenceThemeCss()}`;
|
|
62
|
+
document.head.appendChild(style);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const isDark = () => document.documentElement.dataset.theme === 'dark';
|
|
66
|
+
function applyTheme() {
|
|
67
|
+
document.body.classList.toggle('dark-mode', isDark());
|
|
68
|
+
document.body.classList.toggle('light-mode', !isDark());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
type SavedAuth = Record<string, Record<string, unknown>>;
|
|
72
|
+
function readAuth(): SavedAuth {
|
|
73
|
+
try {
|
|
74
|
+
const parsed = JSON.parse(sessionStorage.getItem(AUTH_STORAGE_KEY) ?? '{}');
|
|
75
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
76
|
+
} catch {
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function writeAuth(all: SavedAuth) {
|
|
81
|
+
try {
|
|
82
|
+
sessionStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(all));
|
|
83
|
+
} catch {
|
|
84
|
+
// storage unavailable - credentials just won't carry to the next visit of the page
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function unmount() {
|
|
89
|
+
if (!current) return;
|
|
90
|
+
current.saveAuth();
|
|
91
|
+
current.observer.disconnect();
|
|
92
|
+
current.instance.destroy();
|
|
93
|
+
current = null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Mounts Scalar's reference in `request.el`. */
|
|
97
|
+
export function mountReference(request: ReferenceRequest) {
|
|
98
|
+
unmount();
|
|
99
|
+
ensureStyles();
|
|
100
|
+
applyTheme();
|
|
101
|
+
const observer = new MutationObserver(applyTheme);
|
|
102
|
+
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
|
103
|
+
|
|
104
|
+
// Scalar's read-only view of what the reader typed, from a plugin's onInit.
|
|
105
|
+
let auth: AuthAccess | null = null;
|
|
106
|
+
const saveAuth = () => {
|
|
107
|
+
if (!auth) return;
|
|
108
|
+
const all = readAuth();
|
|
109
|
+
for (const documentAuth of Object.values(auth.export() ?? {})) {
|
|
110
|
+
for (const [name, secrets] of Object.entries(documentAuth?.secrets ?? {})) all[name] = secrets;
|
|
111
|
+
}
|
|
112
|
+
writeAuth(all);
|
|
113
|
+
};
|
|
114
|
+
const authPlugin = () => ({
|
|
115
|
+
name: 'writedocs-session-auth',
|
|
116
|
+
extensions: [],
|
|
117
|
+
hooks: {
|
|
118
|
+
onInit: ({ auth: access }: { auth: AuthAccess }) => {
|
|
119
|
+
auth = access;
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const instance = createApiReference(request.el, {
|
|
125
|
+
content: request.document,
|
|
126
|
+
customFetch: tryItFetch({ proxy: request.proxy }),
|
|
127
|
+
persistAuth: false,
|
|
128
|
+
authentication: { securitySchemes: readAuth() },
|
|
129
|
+
agent: { disabled: true },
|
|
130
|
+
mcp: { disabled: true },
|
|
131
|
+
showDeveloperTools: 'never',
|
|
132
|
+
telemetry: false,
|
|
133
|
+
withDefaultFonts: false,
|
|
134
|
+
hideSearch: true,
|
|
135
|
+
hideDarkModeToggle: true,
|
|
136
|
+
forceDarkModeState: isDark() ? 'dark' : 'light',
|
|
137
|
+
documentDownloadType: request.download ? 'both' : 'none',
|
|
138
|
+
generateTagSlug: scalarTagSlug,
|
|
139
|
+
generateOperationSlug: scalarOperationSlug,
|
|
140
|
+
plugins: [authPlugin],
|
|
141
|
+
} as never);
|
|
142
|
+
current = { instance, observer, saveAuth };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Leaving the page (a reload, another site, the tab closing - then
|
|
146
|
+
// sessionStorage goes with it) or hiding it: what the reader typed is kept.
|
|
147
|
+
addEventListener('pagehide', () => current?.saveAuth());
|
|
148
|
+
document.addEventListener('visibilitychange', () => {
|
|
149
|
+
if (document.visibilityState === 'hidden') current?.saveAuth();
|
|
150
|
+
});
|
|
151
|
+
document.addEventListener('astro:before-swap', unmount);
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Scalar's API client as the "Try it" of an API page (writedocs.json
|
|
2
|
+
// `api.playground: "scalar"`). Nothing here is on a page until a reader
|
|
3
|
+
// clicks Try it: ScalarTryIt.astro's page script import()s this module on
|
|
4
|
+
// that click, and Vite puts it - Scalar, Vue and Scalar's CSS with it - in
|
|
5
|
+
// chunks of their own under _astro/, from the generator's own node_modules
|
|
6
|
+
// (never a CDN).
|
|
7
|
+
//
|
|
8
|
+
// - The OpenAPI document is the page's own operation, from the JSON
|
|
9
|
+
// ScalarTryIt.astro wrote into the page (lib/scalar-document.js).
|
|
10
|
+
// - Requests: through tryItFetch() (lib/scalar-fetch.js) - straight to the
|
|
11
|
+
// API, then writedocs' proxy when `api.proxy` allows; never Scalar's proxy
|
|
12
|
+
// (no proxyUrl is given, and in its modal Scalar then uses none).
|
|
13
|
+
// - The look: Scalar's CSS plus the site's tokens mapped onto Scalar's
|
|
14
|
+
// variables (lib/scalar-theme.js), in a <style> added on the first open
|
|
15
|
+
// (and again after a page swap drops it); the host's .light-mode /
|
|
16
|
+
// .dark-mode class follows <html data-theme> while the modal is open.
|
|
17
|
+
// - Credentials: Scalar keeps what a reader types in memory. To carry it
|
|
18
|
+
// across the pages of one visit like writedocs' own playground does
|
|
19
|
+
// (sessionStorage - forgotten when the tab closes), each change is copied
|
|
20
|
+
// to sessionStorage and replayed into the next page's client.
|
|
21
|
+
// - One client per page: Astro's client-side navigation replaces the body,
|
|
22
|
+
// so the client is unmounted before each swap and made again on the next
|
|
23
|
+
// page's first click.
|
|
24
|
+
import scalarCss from '@scalar/api-client/style.css?inline';
|
|
25
|
+
import { createApiClientModal } from '@scalar/api-client/modal';
|
|
26
|
+
import { createWorkspaceStore } from '@scalar/workspace-store/client';
|
|
27
|
+
import { createWorkspaceEventBus } from '@scalar/workspace-store/events';
|
|
28
|
+
import { tryItFetch } from '../lib/scalar-fetch.js';
|
|
29
|
+
import { scalarThemeCss, SCALAR_HOST_CLASS } from '../lib/scalar-theme.js';
|
|
30
|
+
|
|
31
|
+
export interface TryItRequest {
|
|
32
|
+
/** The page's operation as an OpenAPI document (lib/scalar-document.js). */
|
|
33
|
+
document: Record<string, unknown>;
|
|
34
|
+
method: string;
|
|
35
|
+
path: string;
|
|
36
|
+
/** writedocs.json's `api.proxy`. */
|
|
37
|
+
proxy: boolean;
|
|
38
|
+
/** Identifies the page's client: a new page, or another operation, gets a new one. */
|
|
39
|
+
key: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const STYLE_ID = 'wd-scalar-style';
|
|
43
|
+
const AUTH_STORAGE_KEY = 'wd-scalar-auth';
|
|
44
|
+
|
|
45
|
+
type Modal = ReturnType<typeof createApiClientModal>;
|
|
46
|
+
let current: { key: string; host: HTMLElement; modal: Modal; observer: MutationObserver } | null = null;
|
|
47
|
+
|
|
48
|
+
function ensureStyles() {
|
|
49
|
+
if (document.getElementById(STYLE_ID)) return;
|
|
50
|
+
const style = document.createElement('style');
|
|
51
|
+
style.id = STYLE_ID;
|
|
52
|
+
style.textContent = `${scalarCss}\n${scalarThemeCss()}`;
|
|
53
|
+
document.head.appendChild(style);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function applyTheme(host: HTMLElement) {
|
|
57
|
+
const dark = document.documentElement.dataset.theme === 'dark';
|
|
58
|
+
host.classList.toggle('dark-mode', dark);
|
|
59
|
+
host.classList.toggle('light-mode', !dark);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type SavedAuth = Record<string, Record<string, unknown>>;
|
|
63
|
+
function readAuth(): SavedAuth {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(sessionStorage.getItem(AUTH_STORAGE_KEY) ?? '{}');
|
|
66
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
67
|
+
} catch {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function writeAuth(all: SavedAuth) {
|
|
72
|
+
try {
|
|
73
|
+
sessionStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(all));
|
|
74
|
+
} catch {
|
|
75
|
+
// storage unavailable - credentials just won't carry across pages
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function merged(base: unknown, patch: unknown): unknown {
|
|
79
|
+
if (!base || typeof base !== 'object' || !patch || typeof patch !== 'object' || Array.isArray(patch)) return patch;
|
|
80
|
+
const out: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
|
81
|
+
for (const [k, v] of Object.entries(patch as Record<string, unknown>)) out[k] = merged(out[k], v);
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function unmount() {
|
|
86
|
+
if (!current) return;
|
|
87
|
+
current.observer.disconnect();
|
|
88
|
+
current.modal.app.unmount();
|
|
89
|
+
current.host.remove();
|
|
90
|
+
current = null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function create(request: TryItRequest): Promise<Modal> {
|
|
94
|
+
const host = document.createElement('div');
|
|
95
|
+
host.className = SCALAR_HOST_CLASS;
|
|
96
|
+
host.dataset.wdScalar = request.key;
|
|
97
|
+
applyTheme(host);
|
|
98
|
+
document.body.appendChild(host);
|
|
99
|
+
const observer = new MutationObserver(() => applyTheme(host));
|
|
100
|
+
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
|
101
|
+
|
|
102
|
+
const workspaceStore = createWorkspaceStore();
|
|
103
|
+
await workspaceStore.addDocument({ name: 'default', document: request.document });
|
|
104
|
+
const eventBus = createWorkspaceEventBus({ debug: false });
|
|
105
|
+
const modal = createApiClientModal({
|
|
106
|
+
el: host,
|
|
107
|
+
eventBus,
|
|
108
|
+
workspaceStore,
|
|
109
|
+
options: {
|
|
110
|
+
// No proxyUrl: Scalar's modal then sends straight to the API, and
|
|
111
|
+
// customFetch decides the rest.
|
|
112
|
+
customFetch: tryItFetch({ proxy: request.proxy }),
|
|
113
|
+
hideClientButton: true,
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
// Credentials typed on an earlier page of this visit, then every change.
|
|
118
|
+
const schemes = (request.document.components as { securitySchemes?: Record<string, unknown> } | undefined)?.securitySchemes ?? {};
|
|
119
|
+
for (const [name, payload] of Object.entries(readAuth())) {
|
|
120
|
+
if (name in schemes) eventBus.emit('auth:update:security-scheme-secrets', { name, payload, overwrite: true } as never);
|
|
121
|
+
}
|
|
122
|
+
eventBus.on('auth:update:security-scheme-secrets', (({ name, payload, overwrite }: { name: string; payload: Record<string, unknown>; overwrite?: boolean }) => {
|
|
123
|
+
const all = readAuth();
|
|
124
|
+
all[name] = (overwrite ? payload : merged(all[name], payload)) as Record<string, unknown>;
|
|
125
|
+
writeAuth(all);
|
|
126
|
+
}) as never);
|
|
127
|
+
eventBus.on('auth:clear:security-scheme-secrets', (({ name }: { name: string }) => {
|
|
128
|
+
const all = readAuth();
|
|
129
|
+
delete all[name];
|
|
130
|
+
writeAuth(all);
|
|
131
|
+
}) as never);
|
|
132
|
+
|
|
133
|
+
current = { key: request.key, host, modal, observer };
|
|
134
|
+
return modal;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Opens Scalar's client on the page's operation. */
|
|
138
|
+
export async function openTryIt(request: TryItRequest) {
|
|
139
|
+
ensureStyles();
|
|
140
|
+
if (current && (current.key !== request.key || !current.host.isConnected)) unmount();
|
|
141
|
+
const modal = current?.modal ?? (await create(request));
|
|
142
|
+
modal.open({ path: request.path, method: request.method.toLowerCase() as never });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
document.addEventListener('astro:before-swap', unmount);
|