@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
package/src/lib/config.ts CHANGED
@@ -3,9 +3,11 @@ import path from 'node:path';
3
3
  import { EXCLUDED_TOP_LEVEL_DIRS, navPageId, draftsIncluded, findDraftPages, fileIdForPath } from './pages.js';
4
4
  import { withoutDrafts } from './drafts.js';
5
5
  import { isHidden } from './hidden-sections.js';
6
+ import { accessOf, isLocked } from './protected-sections.js';
6
7
  import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
7
8
  import matter from 'gray-matter';
8
9
  import { writedocsTempDir } from './writedocs-temp-dir.js';
10
+ import { readScalarReferences } from './scalar-reference.js';
9
11
  import { readableTextOn } from './color.js';
10
12
  import { oncePerBuild } from './build-memo.js';
11
13
  import { normalizeBasePath, siteUrlFor, siteOriginFor } from './base-path.js';
@@ -342,10 +344,24 @@ function loadOpenApiManifest(contentDir: string, specPath: string): OpenApiManif
342
344
  * manifest is missing - generate-api-pages.js always runs before this
343
345
  * does (see src/cli/dev.js/build.js), so a missing manifest here means
344
346
  * generation hasn't happened yet rather than a user error worth
345
- * crashing the dev server over. */
346
- function expandOpenApiGroupPages(openapiRef: { src: string; path: string }, contentDir: string): NavItem[] {
347
+ * crashing the dev server over.
348
+ *
349
+ * A group with `renderer: "scalar"` is its reference page first - the page
350
+ * its sidebar shows, and the one a tab with it opens on - then every
351
+ * operation page, which [...slug].astro leaves out of the sidebar and the
352
+ * page-by-page links (lib/scalar-reference.js). They stay here so each
353
+ * keeps its section: its access rule, search space and language. */
354
+ function expandOpenApiGroupPages(
355
+ openapiRef: { src: string; path: string; renderer?: string },
356
+ contentDir: string
357
+ ): NavItem[] {
347
358
  const manifest = loadOpenApiManifest(contentDir, openapiRef.path);
348
359
  if (!manifest) return [];
360
+ if (openapiRef.renderer === 'scalar') {
361
+ const slug = openapiRef.path.replace(/^\/+|\/+$/g, '');
362
+ const reference = readScalarReferences(contentDir).find((r: { slug: string }) => r.slug === slug);
363
+ if (reference) return [reference.slug, ...manifest.map((op) => op.slug)];
364
+ }
349
365
 
350
366
  const seenTags: string[] = [];
351
367
  const byTag = new Map<string, string[]>();
@@ -850,6 +866,7 @@ export function landingSelectors(landing: Landing, hrefForSlug: (slug: string) =
850
866
  href: 'href' in child ? child.href : hrefForSlug(firstSlugOf(child as Container) ?? 'index'),
851
867
  active: false,
852
868
  dropdown: dropdownMenuOf(child as Container, hrefForSlug),
869
+ ...(isLocked(child) ? { locked: true } : {}),
853
870
  };
854
871
  }),
855
872
  });
@@ -883,24 +900,28 @@ export function resolveGlobalDropdowns(navigation: NavigationConfig): DropdownIt
883
900
  * (returns null, with nothing that tries the next one), which is a real
884
901
  * case now that any container - not just a nested dropdown - can be a
885
902
  * bare external link (e.g. a `tabs` array whose first entry is
886
- * `{ tab: "Status", href: "..." }`). */
887
- function firstSlugAmong(items: Container[]): string | null {
903
+ * `{ tab: "Status", href: "..." }`).
904
+ * `publicOnly` (the site's `/`): protected items are skipped too
905
+ * (lib/protected-sections.js) - an option's own link still leads into its
906
+ * protected children, the way choosing it in a menu would. */
907
+ function firstSlugAmong(items: Container[], publicOnly = false): string | null {
888
908
  for (const item of items) {
889
909
  // A hidden item is reached only by its address - never by default.
890
910
  if (isHidden(item)) continue;
891
- const slug = firstSlugOf(item);
911
+ if (publicOnly && accessOf(item)) continue;
912
+ const slug = firstSlugOf(item, publicOnly);
892
913
  if (slug !== null) return slug;
893
914
  }
894
915
  return null;
895
916
  }
896
917
 
897
- export function firstSlugOf(node: Container): string | null {
918
+ export function firstSlugOf(node: Container, publicOnly = false): string | null {
898
919
  // An item with a `page` of its own opens there (lib/item-pages.js).
899
920
  const own = itemPage(node);
900
921
  if (own !== null) return own;
901
922
  if ('pages' in node) return flattenNav(node.pages)[0]?.slug ?? null;
902
923
  if ('href' in node) return null;
903
- if ('tabs' in node) return firstSlugAmong(node.tabs);
924
+ if ('tabs' in node) return firstSlugAmong(node.tabs, publicOnly);
904
925
  if ('versions' in node) {
905
926
  // Try the `default`-tagged version(s) first (matching the old
906
927
  // "preferred" pick), then fall through to the rest in order - same
@@ -908,11 +929,11 @@ export function firstSlugOf(node: Container): string | null {
908
929
  // extra preference pass in front of it.
909
930
  const defaults = node.versions.filter((v) => v.default);
910
931
  const rest = node.versions.filter((v) => !v.default);
911
- return firstSlugAmong([...defaults, ...rest]);
932
+ return firstSlugAmong([...defaults, ...rest], publicOnly);
912
933
  }
913
- if ('languages' in node) return firstSlugAmong(node.languages);
914
- if ('dropdowns' in node) return firstSlugAmong(node.dropdowns);
915
- if ('products' in node) return firstSlugAmong(node.products);
934
+ if ('languages' in node) return firstSlugAmong(node.languages, publicOnly);
935
+ if ('dropdowns' in node) return firstSlugAmong(node.dropdowns, publicOnly);
936
+ if ('products' in node) return firstSlugAmong(node.products, publicOnly);
916
937
  return null;
917
938
  }
918
939
 
@@ -985,10 +1006,11 @@ export function equivalentPageIn(
985
1006
  * the navigation happens to be a page literally named "index" (the
986
1007
  * usual "docs/index.mdx is the homepage" convention). Mirrors
987
1008
  * firstSlugOf()'s per-container descent, plus the flat-array root case
988
- * firstSlugOf() alone can't handle since a bare array isn't a Container. */
1009
+ * firstSlugOf() alone can't handle since a bare array isn't a Container.
1010
+ * Never a page in a hidden or a protected item. */
989
1011
  export function firstSlugOfNavigation(navigation: NavigationConfig): string | null {
990
1012
  if (Array.isArray(navigation)) return flattenNav(navigation)[0]?.slug ?? null;
991
- return firstSlugOf(navigation as Container);
1013
+ return firstSlugOf(navigation as Container, true);
992
1014
  }
993
1015
 
994
1016
  /** Whether `slug` is reachable anywhere underneath a container, however
@@ -1048,6 +1070,9 @@ export interface SelectorOption {
1048
1070
  // On an entry with a `submenu`: the entry's own `page`, if it has one -
1049
1071
  // clicking the entry opens it. Without one, clicking opens the flyout.
1050
1072
  pageHref?: string;
1073
+ // A protected item with `lock: true` (lib/protected-sections.js): a
1074
+ // padlock beside its name, wherever it's listed (LockMark.astro).
1075
+ locked?: boolean;
1051
1076
  }
1052
1077
 
1053
1078
  export interface Selector {
@@ -1086,6 +1111,7 @@ function dropdownMenuOf(
1086
1111
  icon: iconOf(d),
1087
1112
  href: 'href' in d ? d.href : hrefForSlug(firstSlugOf(d) ?? 'index'),
1088
1113
  active,
1114
+ ...(isLocked(d) ? { locked: true } : {}),
1089
1115
  };
1090
1116
  if (depth === 1 && 'dropdowns' in d) {
1091
1117
  const submenu = dropdownMenuOf(d, hrefForSlug, active ? below : [], depth + 1);
@@ -1143,6 +1169,7 @@ export function buildSelectors(
1143
1169
  href: 'href' in item ? item.href : hrefForSlug(targetSlug),
1144
1170
  active: isActive,
1145
1171
  dropdown: dropdownMenuOf(item, hrefForSlug, isActive ? path.slice(segIndex + 1) : []),
1172
+ ...(isLocked(item) ? { locked: true } : {}),
1146
1173
  };
1147
1174
  }),
1148
1175
  };
@@ -39,6 +39,7 @@ import { pageFrontmatterSchema, createJsonLocator } from './config-schema.js';
39
39
  import { parseOpenApiRef } from './openapi-ref.js';
40
40
  import { readText } from './config-file.js';
41
41
  import { collectOpenApiGroups, operationKeys } from './openapi-spec.js';
42
+ import { usesAccess, accessOf, firstAccessPath, ACCESS_NEEDS_PLATFORM } from './protected-sections.js';
42
43
 
43
44
  /** An issue: { file, line?, message, suggestion? } - `file` relative to the
44
45
  * content directory, POSIX slashes. */
@@ -451,15 +452,29 @@ export async function checkContent(contentDir, configText) {
451
452
  }
452
453
  // Every top-level item hidden, and no home page: `/` never redirects into a
453
454
  // hidden item (lib/hidden-sections.js), so the site's address has nothing.
455
+ // Nor into a protected one (lib/protected-sections.js).
454
456
  const nav = config.navigation;
455
457
  const topKey = nav && !Array.isArray(nav) ? ['tabs', 'versions', 'languages', 'dropdowns', 'products'].find((k) => Array.isArray(nav[k])) : null;
456
- if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || 'href' in (item ?? {})) && !ids.has('index')) {
458
+ if (topKey && nav[topKey].length && nav[topKey].every((item) => item?.hidden === true || accessOf(item) || 'href' in (item ?? {})) && !ids.has('index')) {
459
+ const anyProtected = nav[topKey].some((item) => accessOf(item));
457
460
  warnings.push(
458
461
  issue(
459
462
  'writedocs.json',
460
463
  locate(['navigation', topKey])?.line,
461
- `Every item in navigation.${topKey} is hidden and there's no home page - the site's own address (/) shows "not found".`,
462
- 'Add an index.mdx at the project root for a home page, or leave one item not hidden.'
464
+ `Every item in navigation.${topKey} is hidden${anyProtected ? ' or protected' : ''} and there's no home page - the site's own address (/) shows "not found".`,
465
+ `Add an index.mdx at the project root for a home page, or leave one item not hidden${anyProtected ? ' and not protected' : ''}.`
466
+ )
467
+ );
468
+ }
469
+ // `access` is the WriteDocs platform's to enforce - anywhere else the
470
+ // pages are public (lib/protected-sections.js).
471
+ if (usesAccess(nav)) {
472
+ warnings.push(
473
+ issue(
474
+ 'writedocs.json',
475
+ locate(firstAccessPath(nav))?.line,
476
+ ACCESS_NEEDS_PLATFORM,
477
+ 'Publish the site on WriteDocs, where each access rule is set up - or, on another host, put a login in front of these pages (on Cloudflare, Cloudflare Access).'
463
478
  )
464
479
  );
465
480
  }
@@ -45,7 +45,9 @@ const CONTAINERS = {
45
45
 
46
46
  const HIDDEN = {
47
47
  hidden: 'Reachable only by its address: no tab, switcher or menu lists it, and inside it this level isn\'t shown. Its pages search only among themselves.',
48
- searchPublic: 'For a hidden item: its search also finds the site\'s public pages.',
48
+ searchPublic: 'For a hidden or protected item: its search also finds the site\'s public pages.',
49
+ access: 'The name of an access rule on the WriteDocs platform (lowercase letters, numbers and hyphens, up to 40): every page under this item is served only to readers the rule lets in. Only the platform protects them - on any other host they\'re public.',
50
+ lock: 'For a protected item (with `access`): a padlock next to its name, wherever it\'s listed.',
49
51
  page: 'A page of its own - an overview - that choosing this item opens, in place of its first page. Shown inside the item; in a sidebar too, it opens there.',
50
52
  };
51
53
 
@@ -150,6 +152,7 @@ export const DESCRIPTIONS = {
150
152
  'NavigationItem.openapi': 'Generate this group\'s pages from an OpenAPI spec - a page per operation, grouped by tag.',
151
153
  'NavigationItem.openapi.src': 'Path of the OpenAPI spec file, relative to writedocs.json.',
152
154
  'NavigationItem.openapi.path': 'URL path the generated pages go under, like "/api". Each OpenAPI group needs its own.',
155
+ 'NavigationItem.openapi.renderer': 'How readers see the group: "writedocs" (the default), a page per operation grouped by tag; or "scalar", one page at `path` with Scalar\'s API reference and its own Try it. Search, llms.txt, MCP and the .md copies still cover every operation.',
153
156
  'NavigationItem.label': 'Link text in the sidebar.',
154
157
  'NavigationItem.href': 'Where the link goes.',
155
158
  ...Object.fromEntries(containerEntries),
@@ -167,6 +170,7 @@ export const DESCRIPTIONS = {
167
170
 
168
171
  api: 'The API playground.',
169
172
  'api.proxy': 'When the browser blocks a "Try it" request (the API doesn\'t allow calls from other sites - CORS), retry it through writedocs\' proxy. Requests always go to the API directly first. Default true.',
173
+ 'api.playground': 'Which client the "Try it" button of the API pages opens: "writedocs" (the default) or "scalar" (Scalar\'s API client, loaded only when a reader clicks Try it). The API pages are the same either way; api.proxy applies to both.',
170
174
  domain: 'The site\'s address, like "docs.example.com". Turns on sitemap.xml and absolute URLs in link previews.',
171
175
  basePath: 'The path the site is served under, like "/docs" for example.com/docs - usually behind your own proxy. Every address the site makes starts with it, and the build writes the site to dist/docs/. Starts with "/", no "/" at the end; lowercase letters, digits, "-" and "_". Default: none, the site at the root.',
172
176
 
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import { loadDocsConfig, normalizeEntryId, findAllPages, resolveSiteRoot, fileIdForEntry, contextMenuOptions } from './config';
10
10
  import { buildLlmsTree, renderLlmsFiles } from './llms.js';
11
11
  import { navigationPageOrder } from './pages.js';
12
+ import { protectedPages } from './protected-sections.js';
12
13
  import { writedocsTempDir } from './writedocs-temp-dir.js';
13
14
 
14
15
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -55,11 +56,15 @@ export async function llmsIndexFiles(): Promise<Map<string, string> | null> {
55
56
  const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
56
57
 
57
58
  const pages = new Map<string, { title: string; href: string; description?: string; slug: string }>();
59
+ // Protected pages (lib/protected-sections.js) are for the readers their
60
+ // access rule lets in - never listed in a public file.
61
+ const protectedRules = protectedPages(config.navigation);
58
62
  for (const entry of entries) {
59
63
  // A page that opted out of search-engine indexing (`seo.noindex`, also
60
64
  // left out of sitemap.xml) is left out here too, and a frontmatter `url`
61
65
  // page (Mintlify's external link) has no content of its own.
62
66
  if (entry.data.seo?.noindex || entry.data.url) continue;
67
+ if (protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry))) continue;
63
68
  const slug = normalizeEntryId(entry.id);
64
69
  // The .md route when it exists ([...slug].md.ts - unless `contextMenu` is off,
65
70
  // and never for an OpenAPI page, which renders from the spec), else the
@@ -19,6 +19,7 @@ import {
19
19
  } from './config';
20
20
  import { pageMarkdown } from './openapi-markdown';
21
21
  import { orderByNavigation } from './llms.js';
22
+ import { protectedPages } from './protected-sections.js';
22
23
  import { writedocsTempDir } from './writedocs-temp-dir.js';
23
24
 
24
25
  type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
@@ -71,10 +72,13 @@ export async function mcpIndex(): Promise<McpIndex> {
71
72
  return place;
72
73
  };
73
74
 
75
+ const protectedRules = protectedPages(config.navigation);
74
76
  const docs = entries
75
77
  // Same pages llms.txt lists: not `noindex`, not a frontmatter `url`
76
- // (an external link, with no content of its own).
78
+ // (an external link, with no content of its own), not protected
79
+ // (lib/protected-sections.js).
77
80
  .filter((entry) => !entry.data.seo?.noindex && !entry.data.url)
81
+ .filter((entry) => !protectedRules.has(fileIdForEntry(contentDir, packageRoot, entry)))
78
82
  .map((entry) => {
79
83
  const slug = normalizeEntryId(entry.id);
80
84
  const fileId = fileIdForEntry(contentDir, packageRoot, entry);
@@ -8,7 +8,8 @@
8
8
  // from the specs and writes it; astro.config.mjs adds it to the site's
9
9
  // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
10
  // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
- // counts the old addresses as existing.
11
+ // counts the old addresses as existing. One that leads to a protected page
12
+ // stays out of `_redirects` (protectedMovedApiPages() below).
12
13
  //
13
14
  // Plain JavaScript: read by code that runs under plain Node.
14
15
  import fs from 'node:fs';
@@ -47,3 +48,17 @@ export function untaggedRedirects(pathPrefix, moved, taken) {
47
48
  }
48
49
  return redirects;
49
50
  }
51
+
52
+ /** The moved addresses that lead to a protected page, as `{ slug, rule }`
53
+ * (the old address without its slashes, and the page's access rule):
54
+ * [...slug].astro adds them to the protected addresses - the access map,
55
+ * dist/.writedocs/access.json - and write-redirects-file.js leaves them
56
+ * out of `_redirects`, so the redirect stays a page behind the page's rule
57
+ * instead of an edge redirect that names the protected address to anyone.
58
+ * `ruleOf(slug)`: the rule of the page at `slug`, or null. */
59
+ export function protectedMovedApiPages(moved, ruleOf) {
60
+ return moved.flatMap(({ source, destination }) => {
61
+ const rule = ruleOf(destination.replace(/^\/+|\/+$/g, ''));
62
+ return rule ? [{ slug: source.replace(/^\/+|\/+$/g, ''), rule }] : [];
63
+ });
64
+ }
@@ -117,6 +117,11 @@ export interface OpenApiOperation {
117
117
  responses: Record<string, { description?: string; content?: Record<string, { schema?: OpenApiSchema }> }>;
118
118
  servers: { url: string }[];
119
119
  security: { name: string; type: string; in?: string; scheme?: string }[];
120
+ // The same security as the spec wrote it - requirements and the schemes
121
+ // they name (generate-api-pages.js's securityAsWritten()). Read by
122
+ // lib/scalar-document.js, for Scalar's "Try it".
123
+ securityRequirements?: Record<string, string[]>[];
124
+ securitySchemes?: Record<string, Record<string, unknown>>;
120
125
  }
121
126
 
122
127
  /** Merges `allOf` members into one flat {type, properties, required}
@@ -0,0 +1,238 @@
1
+ // Protected navigation items (`"access": "<rule>"` on a tab, product,
2
+ // version, language or dropdown): every page under the item is served only
3
+ // to the readers its access rule lets in. The rule itself - a password or a
4
+ // list of emails - lives on the WriteDocs platform, never in the project:
5
+ // writedocs.json only names it. The innermost item's rule wins.
6
+ //
7
+ // What the build does with a protected page:
8
+ //
9
+ // - It's left out of everything public that lists pages or carries their
10
+ // text: sitemap.xml (astro.config.mjs), llms.txt and its child files
11
+ // (lib/llms-index.ts), llms-full.txt and mcp-index.json - and it gets
12
+ // `noindex` ([...slug].astro).
13
+ // - `/` never redirects into a protected item (firstSlugOf() in
14
+ // lib/config.ts), and a folder address leads to a public page when the
15
+ // folder has one; a folder with only protected pages under it redirects
16
+ // to one of them, and that redirect is protected too ([...slug].astro).
17
+ // - Its search is its own, like a hidden item's (lib/hidden-sections.js):
18
+ // searchSpaceOf() below gives it a space per rule, and the public search
19
+ // never finds it.
20
+ // - The build writes dist/.writedocs/access.json (accessMap() below): for
21
+ // each rule, every served path it protects. The platform reads it when it
22
+ // publishes and serves those paths only behind the rule's sign-in; the
23
+ // file itself is never served.
24
+ //
25
+ // Protection isn't visual: whether the item shows in the menus is `hidden`'s
26
+ // to say, and `lock` adds a padlock where it shows. Without the platform -
27
+ // a build hosted anywhere else - nothing is protected; `writedocs build`
28
+ // and `validate` say so (ACCESS_NEEDS_PLATFORM).
29
+ //
30
+ // Plain JavaScript, for scripts/protected-sections.test.js and the CLI.
31
+ import { CHILD_KINDS, itemPage } from './item-pages.js';
32
+ import { navPageId } from './pages.js';
33
+ import { isHidden, spaceOf } from './hidden-sections.js';
34
+
35
+ /** What `writedocs build` and `writedocs validate` say when a project uses
36
+ * `access`. */
37
+ export const ACCESS_NEEDS_PLATFORM = 'access needs the WriteDocs platform; on your own host these pages are public.';
38
+
39
+ /** What `writedocs dev` says when a project uses `access`. */
40
+ export const ACCESS_IN_DEV = 'access: nothing is protected in writedocs dev - every page opens without signing in.';
41
+
42
+ /** The access.json format's version - see docs/dev/docs/protected-sections.mdx. */
43
+ export const ACCESS_MAP_VERSION = 1;
44
+
45
+ /** Where the map goes, from the root of dist/ - outside the site's own
46
+ * folder with a `basePath`: the platform reserves /.writedocs/ and never
47
+ * serves it. */
48
+ export const ACCESS_MAP_FILE = '.writedocs/access.json';
49
+
50
+ /** A navigation item's access rule, or null. */
51
+ export function accessOf(item) {
52
+ return item && typeof item === 'object' && typeof item.access === 'string' ? item.access : null;
53
+ }
54
+
55
+ /** Whether a padlock shows on the item where it's listed. */
56
+ export function isLocked(item) {
57
+ return Boolean(accessOf(item) && item.lock === true);
58
+ }
59
+
60
+ /** The rule on a section's path - its innermost protected item's - or null. */
61
+ export function ruleOf(path = []) {
62
+ let rule = null;
63
+ for (const segment of path) rule = accessOf(segment.items[segment.index]) ?? rule;
64
+ return rule;
65
+ }
66
+
67
+ /** Each item of the navigation, with the rule that applies to it (its own or
68
+ * the closest one above it) - `global.dropdowns` aren't walked: the
69
+ * validator refuses `access` there. */
70
+ function walkItems(navigation, visit) {
71
+ const walk = (node, rule) => {
72
+ if (!node || typeof node !== 'object') return;
73
+ for (const [key] of CHILD_KINDS) {
74
+ if (!Array.isArray(node[key])) continue;
75
+ for (const item of node[key]) {
76
+ const inner = accessOf(item) ?? rule;
77
+ visit(item, inner);
78
+ walk(item, inner);
79
+ }
80
+ }
81
+ };
82
+ if (navigation && !Array.isArray(navigation)) walk(navigation, null);
83
+ }
84
+
85
+ /** Whether any item of the navigation names an access rule. */
86
+ export function usesAccess(navigation) {
87
+ let found = false;
88
+ walkItems(navigation, (item) => {
89
+ if (accessOf(item)) found = true;
90
+ });
91
+ return found;
92
+ }
93
+
94
+ /** The JSON path of the first `access` in the navigation - for a warning's
95
+ * line in writedocs.json - or null. */
96
+ export function firstAccessPath(navigation) {
97
+ const find = (node, path) => {
98
+ if (!node || typeof node !== 'object') return null;
99
+ for (const [key] of CHILD_KINDS) {
100
+ if (!Array.isArray(node[key])) continue;
101
+ for (let i = 0; i < node[key].length; i++) {
102
+ const itemPath = [...path, key, i];
103
+ if (accessOf(node[key][i])) return [...itemPath, 'access'];
104
+ const inner = find(node[key][i], itemPath);
105
+ if (inner) return inner;
106
+ }
107
+ }
108
+ return null;
109
+ };
110
+ return navigation && !Array.isArray(navigation) ? find(navigation, ['navigation']) : null;
111
+ }
112
+
113
+ /** The access rules the navigation names, in order, without repeats. */
114
+ export function accessRules(navigation) {
115
+ const rules = new Set();
116
+ walkItems(navigation, (item) => {
117
+ const rule = accessOf(item);
118
+ if (rule) rules.add(rule);
119
+ });
120
+ return [...rules];
121
+ }
122
+
123
+ /** Every protected page - Map<page id, rule> - by the id writedocs.json
124
+ * names it with (fileIdForEntry() in lib/config.ts): the pages in a
125
+ * protected item's sidebar, however deep, and its own `page`. A page listed
126
+ * under two items keeps the first rule found; a page under any rule is
127
+ * protected, wherever else it's listed. */
128
+ export function protectedPages(navigation) {
129
+ const pages = new Map();
130
+ const add = (id, rule) => {
131
+ const key = navPageId(id);
132
+ if (!pages.has(key)) pages.set(key, rule);
133
+ };
134
+ const collect = (list, rule) => {
135
+ for (const entry of list) {
136
+ if (typeof entry === 'string') add(entry, rule);
137
+ else if (entry && typeof entry === 'object' && !('href' in entry)) {
138
+ if (typeof entry.page === 'string') add(entry.page, rule);
139
+ if (Array.isArray(entry.pages)) collect(entry.pages, rule);
140
+ }
141
+ }
142
+ };
143
+ walkItems(navigation, (item, rule) => {
144
+ if (!rule) return;
145
+ const own = itemPage(item);
146
+ if (own !== null) add(own, rule);
147
+ if (Array.isArray(item.pages)) collect(item.pages, rule);
148
+ });
149
+ return pages;
150
+ }
151
+
152
+ /** The search space of a section - `{ id, searchPublic }` - or null for the
153
+ * public pages. Under a rule: one space per rule, `access.<rule>`, and,
154
+ * when the section is also inside a hidden item, one per hidden item in
155
+ * the rule, `access.<rule>.<hidden space id>` - so a hidden part keeps
156
+ * its search to itself (lib/hidden-sections.js), and a reader signed in to
157
+ * a rule never gets another rule's pages from a search. Without a rule,
158
+ * the hidden item's space, as before. `searchPublic` is the innermost
159
+ * hidden or protected item's. A "." can't be in a rule's name or a hidden
160
+ * space's id, so no two spaces share an id. `rule` defaults to the path's
161
+ * (ruleOf()); a page's own rule can be passed in. */
162
+ export function searchSpaceOf(path = [], rule = ruleOf(path)) {
163
+ const hidden = spaceOf(path);
164
+ if (!rule) return hidden;
165
+ let searchPublic = false;
166
+ for (const segment of path) {
167
+ const item = segment.items[segment.index];
168
+ if (isHidden(item) || accessOf(item)) searchPublic = item.searchPublic === true;
169
+ }
170
+ return { id: hidden ? `access.${rule}.${hidden.id}` : `access.${rule}`, searchPublic };
171
+ }
172
+
173
+ /** The rule whose pages a search space holds, or null for a public or
174
+ * hidden one. */
175
+ export function ruleOfSpace(spaceId) {
176
+ const match = /^access\.([a-z0-9-]+)(?:\.|$)/.exec(spaceId);
177
+ return match ? match[1] : null;
178
+ }
179
+
180
+ /**
181
+ * The map the platform protects a site by - what goes in
182
+ * dist/.writedocs/access.json:
183
+ *
184
+ * { "version": 1, "basePath": "/docs", "rules": { "<rule>": { "paths": [...], "prefixes": [...] } } }
185
+ *
186
+ * `paths` are exact paths as the serving sees them (the basePath in front);
187
+ * `prefixes` are folders (ending in "/") whose every file is the rule's.
188
+ * Built from:
189
+ * - `rules`: every rule writedocs.json names (accessRules()) - each one is
190
+ * in the map, even with nothing to protect (every page under it a draft),
191
+ * so the platform can tell the author a rule isn't set up;
192
+ * - `routes`: the protected addresses the build rendered, `{ slug, rule }`
193
+ * - pages, and the folder redirects that lead only to protected pages
194
+ * ([...slug].astro writes the list); slug "index" is the site's root;
195
+ * - `exists(relPath)`: whether the site folder has a file, for the copies
196
+ * made from a page - its Markdown (`<slug>.md`) and its link-preview
197
+ * image (`og/<slug>.png`);
198
+ * - `spaces`: the search spaces the build indexed (run-pagefind.js).
199
+ * Each page is listed with and without its trailing slash and as its
200
+ * index.html - every way a static host answers for it. Sorted, so the same
201
+ * site gives the same file.
202
+ */
203
+ export function accessMap({ rules: named = [], routes, spaces = [], exists = () => false, basePath = '' }) {
204
+ const rules = new Map();
205
+ const ruleEntry = (rule) => {
206
+ if (!rules.has(rule)) rules.set(rule, { paths: new Set(), prefixes: new Set() });
207
+ return rules.get(rule);
208
+ };
209
+ const at = (address) => `${basePath}${address}`;
210
+ named.forEach(ruleEntry);
211
+ for (const { slug, rule } of routes) {
212
+ const entry = ruleEntry(rule);
213
+ if (slug === 'index') {
214
+ entry.paths.add(at('/'));
215
+ if (basePath) entry.paths.add(basePath);
216
+ entry.paths.add(at('/index.html'));
217
+ } else {
218
+ entry.paths.add(at(`/${slug}/`));
219
+ entry.paths.add(at(`/${slug}`));
220
+ entry.paths.add(at(`/${slug}/index.html`));
221
+ }
222
+ for (const copy of [`${slug}.md`, `og/${slug}.png`]) {
223
+ if (exists(copy)) entry.paths.add(at(`/${copy}`));
224
+ }
225
+ }
226
+ for (const space of spaces) {
227
+ const rule = ruleOfSpace(space);
228
+ if (rule) ruleEntry(rule).prefixes.add(at(`/pagefind-spaces/${space}/`));
229
+ }
230
+ const sorted = [...rules.keys()].sort();
231
+ return {
232
+ version: ACCESS_MAP_VERSION,
233
+ basePath,
234
+ rules: Object.fromEntries(
235
+ sorted.map((rule) => [rule, { paths: [...rules.get(rule).paths].sort(), prefixes: [...rules.get(rule).prefixes].sort() }])
236
+ ),
237
+ };
238
+ }
@@ -0,0 +1,56 @@
1
+ // Where an operation is in Scalar's API reference (an OpenAPI group with
2
+ // `openapi.renderer: "scalar"`): the address fragment of its section,
3
+ // "tag/pets/GET/pets/{petId}" - "/api/#tag/pets/GET/pets/{petId}" on the page.
4
+ //
5
+ // Scalar makes these ids itself (getNavigationOptions() in
6
+ // @scalar/workspace-store): `tag/<tag slug>/<operation slug>` for an operation
7
+ // with a tag - under its first tag - and `<operation slug>` for one without,
8
+ // each behind the document's own slug, which the address leaves out for a
9
+ // page with one document. Both slugs come from functions its configuration
10
+ // can replace (`generateTagSlug`, `generateOperationSlug`), and
11
+ // src/scripts/scalar-reference.ts gives it the two below - so the anchor the
12
+ // build works out for an operation (the redirect from its page, its search
13
+ // result) is the one the reader's browser makes, by construction, and stays
14
+ // the same from build to build and Scalar version to version: it depends on
15
+ // the operation's first tag, method and path only.
16
+ //
17
+ // Plain JavaScript with no Node import: imported by the build and by the
18
+ // browser script.
19
+
20
+ const NON_WORD = /[^\p{L}\p{M}\p{N}\s_-]/gu;
21
+ const SPACES = /[\s_-]+/g;
22
+ const EDGE_HYPHENS = /^-+|-+$/g;
23
+
24
+ /** A tag name as a slug: Scalar's own slugify() (@scalar/helpers), with its
25
+ * defaults - lower case, letters, marks, digits and hyphens only, spaces
26
+ * and underscores as one hyphen, at most 255 characters read. */
27
+ export function scalarSlug(value) {
28
+ return String(value ?? '')
29
+ .slice(0, 255)
30
+ .trim()
31
+ .normalize('NFC')
32
+ .toLowerCase()
33
+ .replace(NON_WORD, '')
34
+ .replace(SPACES, '-')
35
+ .replace(EDGE_HYPHENS, '');
36
+ }
37
+
38
+ /** Scalar's `generateTagSlug` - it gets the tag object. */
39
+ export function scalarTagSlug(tag) {
40
+ return scalarSlug(tag?.name ?? '');
41
+ }
42
+
43
+ /** Scalar's `generateOperationSlug` - it gets `{ path, method, ... }`, the
44
+ * method upper case for a standard one. "GET/pets/{petId}", as Scalar's
45
+ * default writes it. */
46
+ export function scalarOperationSlug({ method, path }) {
47
+ return `${String(method).toUpperCase()}${path}`;
48
+ }
49
+
50
+ /** The operation's fragment in the reference (no "#"). `tags` as the spec
51
+ * lists them - Scalar shows the operation under each, and this is the
52
+ * first. */
53
+ export function scalarOperationAnchor({ method, path, tags = [] }) {
54
+ const operation = scalarOperationSlug({ method, path });
55
+ return tags.length ? `tag/${scalarTagSlug({ name: tags[0] })}/${operation}` : operation;
56
+ }
@@ -0,0 +1,63 @@
1
+ // What Scalar's "Try it" gets (writedocs.json `api.playground: "scalar"`):
2
+ // the OpenAPI document of one operation, built from the operation JSON the
3
+ // build already writes for the page (generate-api-pages.js) - never the
4
+ // project's spec file, and never fetched. It goes into the page itself
5
+ // (ScalarTryIt.astro), so it's exactly as public as the page: on a page of a
6
+ // protected section (`access`), behind the same rule.
7
+ //
8
+ // Plain JavaScript so the tests can import it.
9
+
10
+ const METHODS_WITHOUT_BODY = new Set(['GET', 'HEAD']);
11
+
12
+ /** One operation (the build's operation JSON) as an OpenAPI 3.1 document
13
+ * with only that operation. `title` names the document (Scalar shows it in
14
+ * its sidebar, which starts closed). Null fields are left out; schemas stay
15
+ * as the build dereferenced them - a recursive one as its `x-circular`
16
+ * stand-in. */
17
+ export function scalarDocument(op, { title } = {}) {
18
+ const operation = {};
19
+ if (op.operationId) operation.operationId = op.operationId;
20
+ if (op.summary) operation.summary = op.summary;
21
+ if (op.description) operation.description = op.description;
22
+ if (op.tags?.length) operation.tags = op.tags;
23
+ if (op.parameters?.length) operation.parameters = op.parameters;
24
+ if (op.requestBody && !METHODS_WITHOUT_BODY.has(op.method.toUpperCase())) operation.requestBody = op.requestBody;
25
+ operation.responses = op.responses && Object.keys(op.responses).length ? op.responses : { default: { description: '' } };
26
+
27
+ const { requirements, schemes } = securityOf(op);
28
+ if (requirements) operation.security = requirements;
29
+
30
+ const doc = {
31
+ openapi: '3.1.0',
32
+ info: { title: title || op.summary || `${op.method} ${op.path}`, version: '' },
33
+ paths: { [op.path]: { [op.method.toLowerCase()]: operation } },
34
+ };
35
+ if (op.servers?.length) doc.servers = op.servers;
36
+ if (Object.keys(schemes).length) doc.components = { securitySchemes: schemes };
37
+ return doc;
38
+ }
39
+
40
+ /** The operation's security requirements and schemes. Builds before this
41
+ * module existed (or a hand-made operation file) only have the flattened
42
+ * `security` list - then each scheme in it is offered on its own. */
43
+ function securityOf(op) {
44
+ if (op.securityRequirements) {
45
+ return { requirements: op.securityRequirements, schemes: op.securitySchemes ?? {} };
46
+ }
47
+ if (!op.security?.length) return { requirements: null, schemes: {} };
48
+ const schemes = {};
49
+ for (const { name, ...scheme } of op.security) {
50
+ // generate-api-pages.js's resolveSecurity() lets an apiKey scheme's own
51
+ // `name` (the header or parameter) stand for the scheme's key.
52
+ schemes[name] = scheme.type === 'apiKey' ? { ...scheme, name } : scheme;
53
+ }
54
+ return { requirements: Object.keys(schemes).map((name) => ({ [name]: [] })), schemes };
55
+ }
56
+
57
+ /** JSON for a `<script type="application/json">`: every `<` escaped, so no
58
+ * text in the spec can close the tag (`</script>`) or open a comment. The
59
+ * block is only ever read with JSON.parse(), never run. */
60
+ export function jsonForScript(value) {
61
+ const backslash = String.fromCharCode(92);
62
+ return JSON.stringify(value).replace(/</g, `${backslash}u003c`);
63
+ }