@writedocs/generator 0.17.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 +38 -4
- package/package.json +4 -1
- package/src/cli/build.js +3 -2
- package/src/cli/generate-api-pages.js +94 -3
- package/src/cli/run-pagefind.js +47 -15
- package/src/cli/write-redirects-file.js +5 -3
- 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/lib/config-schema.js +17 -3
- package/src/lib/config-schema.ts +16 -2
- package/src/lib/config.ts +17 -2
- package/src/lib/json-schema-descriptions.js +2 -0
- package/src/lib/moved-api-pages.js +16 -1
- package/src/lib/openapi-render.ts +5 -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 +80 -9
- package/src/scripts/scalar-reference.ts +151 -0
- package/src/scripts/scalar-try-it.ts +145 -0
- package/writedocs.schema.json +21 -1
package/astro.config.mjs
CHANGED
|
@@ -45,6 +45,9 @@ import { rehypeBasePath } from './src/lib/rehype-base-path.js';
|
|
|
45
45
|
import { gitLastModified, newestDate } from './src/lib/last-modified.js';
|
|
46
46
|
import { readSpecPaths } from './src/lib/project-files.js';
|
|
47
47
|
import { protectedPages } from './src/lib/protected-sections.js';
|
|
48
|
+
import { SCALAR_TRY_IT_ALIAS, SCALAR_OPTIMIZED_DEPS, scalarTryItComponent } from './src/lib/scalar-try-it-alias.js';
|
|
49
|
+
import { SCALAR_REFERENCE_ALIAS, SCALAR_REFERENCE_OPTIMIZED_DEPS, scalarReferenceComponent } from './src/lib/scalar-reference-alias.js';
|
|
50
|
+
import { readScalarReferences, scalarOperationTargets } from './src/lib/scalar-reference.js';
|
|
48
51
|
import { fileIdForPath } from './src/lib/pages.js';
|
|
49
52
|
import {
|
|
50
53
|
loadDocsConfig,
|
|
@@ -83,6 +86,9 @@ const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0,
|
|
|
83
86
|
// with how every other consumer of it in this codebase behaves - no
|
|
84
87
|
// special-casing needed.
|
|
85
88
|
const docsConfig = loadDocsConfig(contentDir);
|
|
89
|
+
// Whether an OpenAPI group shows Scalar's reference: generate-api-pages.js
|
|
90
|
+
// has listed it by now (it runs before Astro).
|
|
91
|
+
const usesScalarReference = readScalarReferences(contentDir).length > 0;
|
|
86
92
|
// resolveCodeblockTheme() is the single source of truth for the
|
|
87
93
|
// github-light/github-dark fallback - also used by ApiReferencePanel.astro
|
|
88
94
|
// for its own separate <Code/> usages (which don't inherit
|
|
@@ -171,6 +177,9 @@ function collectNoindexIds(rootContentDir) {
|
|
|
171
177
|
// A protected page (lib/protected-sections.js) is noindex, whatever its
|
|
172
178
|
// frontmatter says - and never listed in a public file.
|
|
173
179
|
const protectedRules = protectedPages(docsConfig.navigation);
|
|
180
|
+
// The operation pages of a Scalar group are noindex too - the reference is
|
|
181
|
+
// the page to index (lib/scalar-reference.js).
|
|
182
|
+
const scalarOperations = scalarOperationTargets(readScalarReferences(rootContentDir));
|
|
174
183
|
|
|
175
184
|
for (const relativeId of findAllPages(rootContentDir)) {
|
|
176
185
|
const file = path.join(rootContentDir, relativeId);
|
|
@@ -188,8 +197,8 @@ function collectNoindexIds(rootContentDir) {
|
|
|
188
197
|
// canonical URL is another address (the sitemap lists canonical ones).
|
|
189
198
|
const canonical = data?.seo?.canonical ?? data?.canonical;
|
|
190
199
|
const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
|
|
191
|
-
const
|
|
192
|
-
if (!
|
|
200
|
+
const alwaysNoindex = protectedRules.has(fileIdForPath(relativeId)) || scalarOperations.has(fileIdForPath(relativeId));
|
|
201
|
+
if (!alwaysNoindex && !frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
|
|
193
202
|
ids.add(pageId);
|
|
194
203
|
}
|
|
195
204
|
// Generated OpenAPI stub pages always set an explicit `slug` (see
|
|
@@ -203,7 +212,8 @@ function collectNoindexIds(rootContentDir) {
|
|
|
203
212
|
// A generated API page changes when a spec does. Which spec it came
|
|
204
213
|
// from isn't recorded on the page, so it gets the newest of them.
|
|
205
214
|
if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
|
|
206
|
-
|
|
215
|
+
const generatedId = normalizeEntryId(data?.slug ?? '');
|
|
216
|
+
if ((frontmatterNoindex(data) || protectedRules.has(generatedId) || scalarOperations.has(generatedId)) && data.slug) ids.add(generatedId);
|
|
207
217
|
}
|
|
208
218
|
if (!rootIsPage) ids.add('index');
|
|
209
219
|
// Folder addresses with no page of their own redirect to one under them
|
|
@@ -575,8 +585,17 @@ export default defineConfig({
|
|
|
575
585
|
// as it is, and its CommonJS dependencies failed in the browser ("dayjs
|
|
576
586
|
// ... does not provide an export named 'default'"): diagrams stayed as
|
|
577
587
|
// text in dev, while builds were fine. Naming it here prepares it always.
|
|
588
|
+
// Scalar's "Try it" (api.playground "scalar") too: found only on the first
|
|
589
|
+
// click's import(), it made Vite optimize it then and reload the page,
|
|
590
|
+
// which lost the click. Only for a site that uses it - the others don't
|
|
591
|
+
// pay for preparing it. Scalar's API reference (an OpenAPI group's
|
|
592
|
+
// `renderer: "scalar"`) the same way, on its page's first load.
|
|
578
593
|
optimizeDeps: {
|
|
579
|
-
include: [
|
|
594
|
+
include: [
|
|
595
|
+
'mermaid',
|
|
596
|
+
...(docsConfig.api.playground === 'scalar' ? SCALAR_OPTIMIZED_DEPS : []),
|
|
597
|
+
...(usesScalarReference ? SCALAR_REFERENCE_OPTIMIZED_DEPS : []),
|
|
598
|
+
],
|
|
580
599
|
},
|
|
581
600
|
resolve: {
|
|
582
601
|
alias: [
|
|
@@ -607,6 +626,21 @@ export default defineConfig({
|
|
|
607
626
|
find: 'writedocs/components',
|
|
608
627
|
replacement: path.join(packageRoot, 'packages/components/src/index.ts'),
|
|
609
628
|
},
|
|
629
|
+
// Scalar's "Try it" (ApiReferencePanel.astro): the real component
|
|
630
|
+
// only when writedocs.json asks for it (or in dev) - otherwise an
|
|
631
|
+
// empty one, so Scalar isn't bundled into a site that doesn't use it
|
|
632
|
+
// (lib/scalar-try-it-alias.js).
|
|
633
|
+
{
|
|
634
|
+
find: SCALAR_TRY_IT_ALIAS,
|
|
635
|
+
replacement: scalarTryItComponent({ playground: docsConfig.api.playground, command: process.env.WRITEDOCS_COMMAND, packageRoot }),
|
|
636
|
+
},
|
|
637
|
+
// Scalar's API reference ([...slug].astro), the page of an OpenAPI
|
|
638
|
+
// group with `renderer: "scalar"`: the real component only when a
|
|
639
|
+
// group asks for it (or in dev) - lib/scalar-reference-alias.js.
|
|
640
|
+
{
|
|
641
|
+
find: SCALAR_REFERENCE_ALIAS,
|
|
642
|
+
replacement: scalarReferenceComponent({ scalar: usesScalarReference, command: process.env.WRITEDOCS_COMMAND, packageRoot }),
|
|
643
|
+
},
|
|
610
644
|
],
|
|
611
645
|
},
|
|
612
646
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@writedocs/generator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -69,6 +69,9 @@
|
|
|
69
69
|
"@iconify-json/tabler": "1.2.38",
|
|
70
70
|
"@mdx-js/mdx": "3.1.1",
|
|
71
71
|
"@resvg/resvg-wasm": "2.6.2",
|
|
72
|
+
"@scalar/api-client": "3.25.0",
|
|
73
|
+
"@scalar/api-reference": "1.78.0",
|
|
74
|
+
"@scalar/workspace-store": "0.71.0",
|
|
72
75
|
"@shikijs/transformers": "4.4.3",
|
|
73
76
|
"@tailwindcss/vite": "4.3.3",
|
|
74
77
|
"astro": "7.2.9",
|
package/src/cli/build.js
CHANGED
|
@@ -195,8 +195,9 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
|
|
|
195
195
|
// ever produce client-side meta-refresh pages (see write-redirects-file.js)
|
|
196
196
|
// - this turns those into real instant edge redirects on hosts that read
|
|
197
197
|
// a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
|
|
198
|
-
// A folder redirect
|
|
199
|
-
//
|
|
198
|
+
// A folder redirect, or a generated API page's old address
|
|
199
|
+
// (lib/moved-api-pages.js), that leads to a protected page stays a page,
|
|
200
|
+
// behind its rule - not an edge redirect anyone can follow.
|
|
200
201
|
const protectedRoutes = fs.existsSync(accessFile) ? JSON.parse(fs.readFileSync(accessFile, 'utf8')) : [];
|
|
201
202
|
const protectedFolders = new Set(protectedRoutes.map((route) => `/${route.slug}/`));
|
|
202
203
|
writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath, protectedFolders });
|
|
@@ -8,8 +8,10 @@ import { findAllPages } from '../lib/pages.js';
|
|
|
8
8
|
import { projectIgnore } from '../lib/project-ignore.js';
|
|
9
9
|
import { readConfigText } from '../lib/config-file.js';
|
|
10
10
|
import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
|
|
11
|
-
import { operationMetaDescription } from '../lib/meta-description.js';
|
|
11
|
+
import { operationMetaDescription, plainLine, truncateAtWord } from '../lib/meta-description.js';
|
|
12
12
|
import { movedApiPagesFile, untaggedRedirects } from '../lib/moved-api-pages.js';
|
|
13
|
+
import { scalarReferencesFile, scalarDocumentFile } from '../lib/scalar-reference.js';
|
|
14
|
+
import { scalarOperationAnchor } from '../lib/scalar-anchors.js';
|
|
13
15
|
import { canonicalPath } from '../lib/canonical-path.js';
|
|
14
16
|
|
|
15
17
|
|
|
@@ -158,6 +160,21 @@ function resolveSecurity(operation, spec) {
|
|
|
158
160
|
.filter((s) => s.type);
|
|
159
161
|
}
|
|
160
162
|
|
|
163
|
+
/** The operation's security requirements as the spec wrote them (each entry
|
|
164
|
+
* an alternative, its keys required together, with their scopes) and the
|
|
165
|
+
* schemes they name, under their own names - what an OpenAPI document needs
|
|
166
|
+
* to say the same thing again (lib/scalar-document.js). `security` above
|
|
167
|
+
* flattens both into one list for writedocs' own playground. */
|
|
168
|
+
function securityAsWritten(operation, spec) {
|
|
169
|
+
const requirements = operation.security ?? spec.security ?? [];
|
|
170
|
+
const schemes = spec.components?.securitySchemes ?? {};
|
|
171
|
+
const named = {};
|
|
172
|
+
for (const req of requirements) {
|
|
173
|
+
for (const name of Object.keys(req)) if (schemes[name]?.type) named[name] = schemes[name];
|
|
174
|
+
}
|
|
175
|
+
return { securityRequirements: requirements, securitySchemes: named };
|
|
176
|
+
}
|
|
177
|
+
|
|
161
178
|
function buildOperations(spec) {
|
|
162
179
|
const operations = [];
|
|
163
180
|
for (const [urlPath, pathItem] of Object.entries(spec.paths ?? {})) {
|
|
@@ -177,6 +194,7 @@ function buildOperations(spec) {
|
|
|
177
194
|
responses: operation.responses ?? {},
|
|
178
195
|
servers: operation.servers ?? spec.servers ?? [],
|
|
179
196
|
security: resolveSecurity(operation, spec),
|
|
197
|
+
...securityAsWritten(operation, spec),
|
|
180
198
|
});
|
|
181
199
|
}
|
|
182
200
|
}
|
|
@@ -224,7 +242,7 @@ async function dereferenceSpec(specPath, sources) {
|
|
|
224
242
|
* in the same writedocs.json never collide with each other on disk, exactly
|
|
225
243
|
* as they won't collide in the URL space either (both keyed off the
|
|
226
244
|
* same `path` value). Nothing is written here - see writeGeneratedFiles(). */
|
|
227
|
-
async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources }) {
|
|
245
|
+
async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources, references, pageIds }) {
|
|
228
246
|
const pathPrefix = normalizePathPrefix(group.openapi.path);
|
|
229
247
|
const specPath = path.resolve(contentDir, group.openapi.src);
|
|
230
248
|
if (!fs.existsSync(specPath)) {
|
|
@@ -233,6 +251,21 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
|
|
|
233
251
|
`(resolved to ${specPath}), which doesn't exist`
|
|
234
252
|
);
|
|
235
253
|
}
|
|
254
|
+
// Scalar's reference (lib/scalar-reference.js) is a page of its own, at the
|
|
255
|
+
// group's path - which then can't be the site's root, nor a page's.
|
|
256
|
+
const scalar = group.openapi.renderer === 'scalar';
|
|
257
|
+
if (scalar && !pathPrefix) {
|
|
258
|
+
throw new Error(
|
|
259
|
+
`[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" and openapi.path "${group.openapi.path}" - ` +
|
|
260
|
+
'the reference is a page at that path, so give it one of its own, like "/api".'
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (scalar && pageIds.has(pathPrefix)) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
`[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" - its reference is the page at /${pathPrefix}/, ` +
|
|
266
|
+
'and a page of the project is already there. Move that page or give the group another openapi.path.'
|
|
267
|
+
);
|
|
268
|
+
}
|
|
236
269
|
|
|
237
270
|
const spec = await dereferenceSpec(specPath, sources);
|
|
238
271
|
const operations = buildOperations(spec);
|
|
@@ -241,6 +274,7 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
|
|
|
241
274
|
|
|
242
275
|
const manifest = [];
|
|
243
276
|
const untagged = [];
|
|
277
|
+
const referenceOperations = [];
|
|
244
278
|
for (const operation of operations) {
|
|
245
279
|
const key = operationKey(operation.method, operation.path);
|
|
246
280
|
const overrideSlug = overrides.get(key);
|
|
@@ -282,6 +316,7 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
|
|
|
282
316
|
moves.slugs.add(slug);
|
|
283
317
|
|
|
284
318
|
manifest.push({ slug, method: operation.method, path: operation.path, tags: operation.tags, title, generated });
|
|
319
|
+
if (scalar) referenceOperations.push({ slug, method: operation.method, path: operation.path, title, anchor: scalarOperationAnchor(operation) });
|
|
285
320
|
|
|
286
321
|
const opFile = path.join(openapiOutDir, 'operations', operationFileName(operation.method, operation.path));
|
|
287
322
|
files.set(opFile, operationJson(operation));
|
|
@@ -289,6 +324,17 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
|
|
|
289
324
|
|
|
290
325
|
files.set(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
291
326
|
if (untagged.length) moves.untagged.push({ pathPrefix, moved: untagged });
|
|
327
|
+
if (scalar) {
|
|
328
|
+
const title = spec.info?.title?.trim() || group.group;
|
|
329
|
+
// The spec as its author wrote it, in one document: $refs inside it stay
|
|
330
|
+
// (Scalar resolves them, and the page stays the spec's size), $refs to
|
|
331
|
+
// other files are brought in - the reader's browser can't fetch those.
|
|
332
|
+
const document = await new SwaggerParser().bundle(specPath);
|
|
333
|
+
files.set(scalarDocumentFile(contentDir, pathPrefix), JSON.stringify(document));
|
|
334
|
+
files.set(path.join(generatedDocsDir, `${pathPrefix}.mdx`), referencePage({ title, spec, slug: pathPrefix, operations: referenceOperations }));
|
|
335
|
+
moves.slugs.add(pathPrefix);
|
|
336
|
+
references.push({ group: group.group, slug: pathPrefix, title, operations: referenceOperations });
|
|
337
|
+
}
|
|
292
338
|
summary.groups.push({ group: group.group, src: group.openapi.src, operations: operations.length });
|
|
293
339
|
}
|
|
294
340
|
|
|
@@ -389,9 +435,14 @@ export async function planApiPages({ contentDir, drafts }) {
|
|
|
389
435
|
// Absolute path -> content: everything the two folders will hold.
|
|
390
436
|
const files = new Map();
|
|
391
437
|
const sources = new Set();
|
|
438
|
+
// Groups shown as Scalar's reference (lib/scalar-reference.js), and the
|
|
439
|
+
// addresses of the project's own pages - a reference can't take one.
|
|
440
|
+
const references = [];
|
|
441
|
+
const pageIds = groups.some((g) => g.openapi.renderer === 'scalar') ? projectPageIds(contentDir, drafts) : new Set();
|
|
392
442
|
for (const group of groups) {
|
|
393
|
-
await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources });
|
|
443
|
+
await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources, references, pageIds });
|
|
394
444
|
}
|
|
445
|
+
if (references.length) files.set(scalarReferencesFile(contentDir), JSON.stringify(references, null, 2));
|
|
395
446
|
const moved = moves.untagged.flatMap(({ pathPrefix, moved: list }) => untaggedRedirects(pathPrefix, list, moves.slugs));
|
|
396
447
|
if (moved.length) files.set(movedApiPagesFile(contentDir), JSON.stringify(moved, null, 2));
|
|
397
448
|
|
|
@@ -408,6 +459,46 @@ export async function planApiPages({ contentDir, drafts }) {
|
|
|
408
459
|
return { summary, files, roots };
|
|
409
460
|
}
|
|
410
461
|
|
|
462
|
+
/** The addresses (file ids) of the project's own pages: its path without the
|
|
463
|
+
* extension or a trailing /index, or its frontmatter `slug`. */
|
|
464
|
+
function projectPageIds(contentDir, drafts) {
|
|
465
|
+
const ids = new Set();
|
|
466
|
+
for (const rel of findAllPages(contentDir, { drafts })) {
|
|
467
|
+
ids.add(rel.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
|
|
468
|
+
try {
|
|
469
|
+
const { data } = matter(fs.readFileSync(path.join(contentDir, rel), 'utf-8'));
|
|
470
|
+
if (typeof data?.slug === 'string') ids.add(data.slug.replace(/^\/+|\/+$/g, ''));
|
|
471
|
+
} catch {}
|
|
472
|
+
}
|
|
473
|
+
return ids;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Text for a Markdown link's label inside MDX: what MDX or Markdown would
|
|
477
|
+
* read as syntax is escaped. */
|
|
478
|
+
function markdownText(text) {
|
|
479
|
+
return String(text).replace(/[\\`*_[\]{}<>|#]/g, (c) => `\\${c}`);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** The reference page of a Scalar group: its title, the spec's description
|
|
483
|
+
* as the search-engine one, and a list of the operations linking to their
|
|
484
|
+
* own pages - not shown (the page shows Scalar's reference), but what its
|
|
485
|
+
* .md copy and llms-full.txt carry. */
|
|
486
|
+
function referencePage({ title, spec, slug, operations }) {
|
|
487
|
+
const description = truncateAtWord(plainLine(spec.info?.description)) || `The ${title} reference.`;
|
|
488
|
+
const lines = operations.map((op) => `- [${markdownText(op.title)}](/${op.slug}/) - \`${op.method} ${op.path.replace(/`/g, '')}\``);
|
|
489
|
+
return [
|
|
490
|
+
'---',
|
|
491
|
+
`title: ${JSON.stringify(title)}`,
|
|
492
|
+
`slug: ${JSON.stringify(slug)}`,
|
|
493
|
+
'seo:',
|
|
494
|
+
` description: ${JSON.stringify(description)}`,
|
|
495
|
+
'---',
|
|
496
|
+
'',
|
|
497
|
+
...lines,
|
|
498
|
+
'',
|
|
499
|
+
].join('\n');
|
|
500
|
+
}
|
|
501
|
+
|
|
411
502
|
function listFiles(dir) {
|
|
412
503
|
let entries;
|
|
413
504
|
try {
|
package/src/cli/run-pagefind.js
CHANGED
|
@@ -66,6 +66,11 @@ function resolvePagefindBin(packageRoot) {
|
|
|
66
66
|
* dist/.writedocs/access.json (lib/protected-sections.js).
|
|
67
67
|
*/
|
|
68
68
|
export async function runPagefind(siteDir, { packageRoot }) {
|
|
69
|
+
// With a hidden or protected space, or a page whose result leads elsewhere
|
|
70
|
+
// - the operation page of a Scalar group, whose result is its operation in
|
|
71
|
+
// the reference (lib/scalar-reference.js) - the indexes are written by
|
|
72
|
+
// Pagefind's Node API, which takes a result's address; the CLI only knows
|
|
73
|
+
// files. Without either, the CLI indexes the site, as ever.
|
|
69
74
|
const groups = searchSpaces(siteDir);
|
|
70
75
|
if (groups) {
|
|
71
76
|
await indexBySpace(siteDir, packageRoot, groups);
|
|
@@ -80,16 +85,20 @@ export async function runPagefind(siteDir, { packageRoot }) {
|
|
|
80
85
|
// lib/protected-sections.js).
|
|
81
86
|
const SPACE = /data-wd-search-space="([^"]+)"/;
|
|
82
87
|
const SEARCH_PUBLIC = /data-wd-search-public="true"/;
|
|
88
|
+
const SEARCH_URL = /data-wd-search-url="([^"]+)"/;
|
|
83
89
|
|
|
84
90
|
/** The site's pages by search space - `{ public, spaces }` - or null when
|
|
85
|
-
* no page is in a hidden or protected space
|
|
86
|
-
* as ever).
|
|
91
|
+
* no page is in a hidden or protected space and none has a result address
|
|
92
|
+
* of its own (the whole site is one index, as ever).
|
|
87
93
|
* Only pages Pagefind would index: those with a data-pagefind-body. A
|
|
88
|
-
* page is `{ rel }`, its path in the site with forward slashes
|
|
94
|
+
* page is `{ rel }`, its path in the site with forward slashes, and `url`
|
|
95
|
+
* when its result is to lead elsewhere (data-wd-search-url, an address in
|
|
96
|
+
* the site: [...slug].astro writes it on a Scalar group's operation pages).
|
|
89
97
|
* Exported for scripts/search-spaces.test.js. */
|
|
90
98
|
export function searchSpaces(siteDir) {
|
|
91
99
|
const publicPages = [];
|
|
92
100
|
const spaces = new Map();
|
|
101
|
+
let ownUrls = false;
|
|
93
102
|
const walk = (dir) => {
|
|
94
103
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
95
104
|
const full = path.join(dir, entry.name);
|
|
@@ -105,6 +114,11 @@ export function searchSpaces(siteDir) {
|
|
|
105
114
|
// content here ran the CLI out of memory on a site with 1.7 GiB of
|
|
106
115
|
// HTML - and most sites have no hidden space, so none of it was used.
|
|
107
116
|
const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
|
|
117
|
+
const url = SEARCH_URL.exec(content)?.[1];
|
|
118
|
+
if (url) {
|
|
119
|
+
page.url = decodeAttribute(url);
|
|
120
|
+
ownUrls = true;
|
|
121
|
+
}
|
|
108
122
|
const space = SPACE.exec(content)?.[1];
|
|
109
123
|
if (!space) {
|
|
110
124
|
publicPages.push(page);
|
|
@@ -117,7 +131,12 @@ export function searchSpaces(siteDir) {
|
|
|
117
131
|
}
|
|
118
132
|
};
|
|
119
133
|
walk(siteDir);
|
|
120
|
-
return spaces.size ? { public: publicPages, spaces } : null;
|
|
134
|
+
return spaces.size || ownUrls ? { public: publicPages, spaces } : null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** An attribute's value as written by Astro, unescaped. */
|
|
138
|
+
function decodeAttribute(value) {
|
|
139
|
+
return value.replace(/&(quot|#34|#39|lt|gt|amp);/g, (_, name) => ({ quot: '"', '#34': '"', '#39': "'", lt: '<', gt: '>', amp: '&' })[name]);
|
|
121
140
|
}
|
|
122
141
|
|
|
123
142
|
/** One index for the public pages (dist/pagefind/) and one per hidden or
|
|
@@ -126,18 +145,11 @@ export function searchSpaces(siteDir) {
|
|
|
126
145
|
* pages, plus the public ones when it sets `searchPublic`. A protected
|
|
127
146
|
* space holds one access rule's pages only (searchSpaceOf() in
|
|
128
147
|
* lib/protected-sections.js), so its folder is behind that rule.
|
|
129
|
-
* src/scripts/search.ts loads the index of the page's space.
|
|
148
|
+
* src/scripts/search.ts loads the index of the page's space. A site with no
|
|
149
|
+
* space but pages with their own result address gets the public index
|
|
150
|
+
* alone, written the same way. */
|
|
130
151
|
async function indexBySpace(siteDir, packageRoot, groups) {
|
|
131
|
-
const pagefind = await
|
|
132
|
-
const check = (result, what) => {
|
|
133
|
-
if (result.errors?.length) throw new Error(`pagefind (${what}): ${result.errors.join('; ')}`);
|
|
134
|
-
return result;
|
|
135
|
-
};
|
|
136
|
-
const write = async (pages, outputPath, what) => {
|
|
137
|
-
const { index } = check(await pagefind.createIndex({}), what);
|
|
138
|
-
for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8') }), `${what}: ${page.rel}`);
|
|
139
|
-
check(await index.writeFiles({ outputPath }), what);
|
|
140
|
-
};
|
|
152
|
+
const { pagefind, write } = await nodeIndexer(siteDir, packageRoot);
|
|
141
153
|
try {
|
|
142
154
|
await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
|
|
143
155
|
for (const [id, space] of groups.spaces) {
|
|
@@ -149,6 +161,26 @@ async function indexBySpace(siteDir, packageRoot, groups) {
|
|
|
149
161
|
}
|
|
150
162
|
}
|
|
151
163
|
|
|
164
|
+
/** Pagefind's Node API, and a function writing one index of `pages`: each
|
|
165
|
+
* added by its file (Pagefind makes its address from the path, as the CLI
|
|
166
|
+
* does) or, with a `url`, at that address. */
|
|
167
|
+
async function nodeIndexer(siteDir, packageRoot) {
|
|
168
|
+
const pagefind = await import(pathToFileURL(path.join(findPagefindDir(packageRoot), 'lib', 'index.js')).href);
|
|
169
|
+
const check = (result, what) => {
|
|
170
|
+
if (result.errors?.length) throw new Error(`pagefind (${what}): ${result.errors.join('; ')}`);
|
|
171
|
+
return result;
|
|
172
|
+
};
|
|
173
|
+
const write = async (pages, outputPath, what) => {
|
|
174
|
+
const { index } = check(await pagefind.createIndex({}), what);
|
|
175
|
+
for (const page of pages) {
|
|
176
|
+
const content = fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8');
|
|
177
|
+
check(await index.addHTMLFile(page.url ? { url: page.url, content } : { sourcePath: page.rel, content }), `${what}: ${page.rel}`);
|
|
178
|
+
}
|
|
179
|
+
check(await index.writeFiles({ outputPath }), what);
|
|
180
|
+
};
|
|
181
|
+
return { pagefind, write };
|
|
182
|
+
}
|
|
183
|
+
|
|
152
184
|
function indexWholeSite(siteDir, packageRoot) {
|
|
153
185
|
const bin = resolvePagefindBin(packageRoot);
|
|
154
186
|
return new Promise((resolve, reject) => {
|
|
@@ -41,9 +41,10 @@ import { withBase } from '../lib/base-path.js';
|
|
|
41
41
|
// the rules name, source and destination - the host matches the full path
|
|
42
42
|
// it was asked for - and adds `/ -> /docs/` for whoever opens the root of
|
|
43
43
|
// the address directly.
|
|
44
|
-
/** `protectedFolders` -
|
|
45
|
-
*
|
|
46
|
-
*
|
|
44
|
+
/** `protectedFolders` - the protected addresses ("/partners/"), among them
|
|
45
|
+
* every folder redirect and moved API page (lib/moved-api-pages.js) that
|
|
46
|
+
* leads to a protected page (lib/protected-sections.js): their redirects
|
|
47
|
+
* are left out here, so each stays a page behind the page's access rule. */
|
|
47
48
|
export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, basePath = '', protectedFolders = new Set() } = {}) {
|
|
48
49
|
const writedocsJson = JSON.parse(readConfigText(contentDir));
|
|
49
50
|
const redirects = writedocsJson.redirects ?? [];
|
|
@@ -71,6 +72,7 @@ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, base
|
|
|
71
72
|
// as requested.
|
|
72
73
|
for (const { source, destination } of readMovedApiPages(contentDir)) {
|
|
73
74
|
if (redirects.some((r) => r.source.replace(/\/+$/, '') === source)) continue;
|
|
75
|
+
if (protectedFolders.has(`${source}/`)) continue;
|
|
74
76
|
lines.push(`${at(source)} ${at(destination)} 301`, `${at(source)}/ ${at(destination)} 301`);
|
|
75
77
|
}
|
|
76
78
|
|
|
@@ -18,6 +18,10 @@ import {
|
|
|
18
18
|
import { parseOpenApiRef } from '../lib/openapi-ref.js';
|
|
19
19
|
import { loadDocsConfig, resolveCodeblockTheme } from '../lib/config';
|
|
20
20
|
import ApiLangSelect from './ApiLangSelect.astro';
|
|
21
|
+
// ScalarTryIt.astro when writedocs.json asks for Scalar, an empty component
|
|
22
|
+
// otherwise - an alias, so Scalar isn't bundled into other sites
|
|
23
|
+
// (lib/scalar-try-it-alias.js).
|
|
24
|
+
import ScalarTryIt from 'writedocs/scalar-try-it';
|
|
21
25
|
|
|
22
26
|
interface Props {
|
|
23
27
|
operation: string;
|
|
@@ -64,6 +68,11 @@ const SNIPPET_THEMES = resolveCodeblockTheme(docsConfig);
|
|
|
64
68
|
// Whether the Send button in the Try-it modal routes its request through
|
|
65
69
|
// writedocs' CORS proxy - see PROXY_BASE_URL in the <script> below.
|
|
66
70
|
const proxyEnabled = docsConfig.api.proxy;
|
|
71
|
+
// writedocs.json's `api.playground`: "scalar" makes the Try button open
|
|
72
|
+
// Scalar's API client (ScalarTryIt.astro) instead of the modal below, which
|
|
73
|
+
// isn't rendered then. The button gets another data-role, so this file's own
|
|
74
|
+
// script (unchanged) never binds it.
|
|
75
|
+
const scalarPlayground = docsConfig.api.playground === 'scalar';
|
|
67
76
|
|
|
68
77
|
// "METHOD /path", or Mintlify's "spec.json METHOD /path" - see lib/openapi-ref.js.
|
|
69
78
|
const ref = parseOpenApiRef(operation);
|
|
@@ -162,14 +171,14 @@ const paramsJson = JSON.stringify(op?.parameters ?? []);
|
|
|
162
171
|
const securityJson = JSON.stringify(op?.security ?? []);
|
|
163
172
|
---
|
|
164
173
|
|
|
165
|
-
{op && (
|
|
174
|
+
{op && (<Fragment>
|
|
166
175
|
<div class="wd-api-panel" data-api-panel data-method={op.method} data-path={op.path}>
|
|
167
176
|
<div class="wd-api-card">
|
|
168
177
|
<div class="wd-api-card-head">
|
|
169
178
|
<span class="wd-api-card-label">Request</span>
|
|
170
179
|
<div class="wd-api-card-actions">
|
|
171
180
|
<ApiLangSelect options={langOptions} rolePrefix="lang" ariaLabel="Language" />
|
|
172
|
-
<button type="button" class="wd-api-try-inline" data-role=
|
|
181
|
+
<button type="button" class="wd-api-try-inline" data-role={scalarPlayground ? 'open-scalar' : 'open-modal'}>
|
|
173
182
|
Try <span class="wd-api-try-icon" aria-hidden="true">▸</span>
|
|
174
183
|
</button>
|
|
175
184
|
</div>
|
|
@@ -219,6 +228,9 @@ const securityJson = JSON.stringify(op?.security ?? []);
|
|
|
219
228
|
)}
|
|
220
229
|
</div>
|
|
221
230
|
|
|
231
|
+
{scalarPlayground && <ScalarTryIt op={op} proxy={proxyEnabled} title={docsConfig.name} />}
|
|
232
|
+
|
|
233
|
+
{!scalarPlayground && (
|
|
222
234
|
<div class="wd-api-modal-overlay" data-role="modal-overlay" hidden>
|
|
223
235
|
<div class="wd-api-modal" role="dialog" aria-modal="true" aria-label="Try it">
|
|
224
236
|
<div class="wd-api-modal-head">
|
|
@@ -410,7 +422,8 @@ const securityJson = JSON.stringify(op?.security ?? []);
|
|
|
410
422
|
</div>
|
|
411
423
|
</div>
|
|
412
424
|
</div>
|
|
413
|
-
)}
|
|
425
|
+
)}
|
|
426
|
+
</Fragment>)}
|
|
414
427
|
|
|
415
428
|
<style is:global>
|
|
416
429
|
/* Widens the shared .wd-toc-col (defined in BaseLayout.astro) only on
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
---
|
|
2
|
+
// The page of an OpenAPI group with `openapi.renderer: "scalar"`: Scalar's
|
|
3
|
+
// API reference, inside the site's layout - [...slug].astro renders it in
|
|
4
|
+
// place of the page's content, through the `writedocs/scalar-reference`
|
|
5
|
+
// alias (lib/scalar-reference-alias.js).
|
|
6
|
+
//
|
|
7
|
+
// What the page carries: the group's spec, bundled (generate-api-pages.js,
|
|
8
|
+
// lib/scalar-reference.js), in a <script type="application/json"> - inside
|
|
9
|
+
// the page and never a file of its own, so a group in a protected section
|
|
10
|
+
// stays behind the section's rule - and the small script below, which
|
|
11
|
+
// import()s Scalar (src/scripts/scalar-reference.ts) and mounts it.
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import { jsonForScript } from '../lib/scalar-document.js';
|
|
14
|
+
import { scalarDocumentFile } from '../lib/scalar-reference.js';
|
|
15
|
+
import { SCALAR_REFERENCE_CLASS } from '../lib/scalar-theme.js';
|
|
16
|
+
|
|
17
|
+
interface Props {
|
|
18
|
+
contentDir: string;
|
|
19
|
+
/** The reference's address, without slashes ("api"). */
|
|
20
|
+
slug: string;
|
|
21
|
+
/** writedocs.json's `api.proxy`. */
|
|
22
|
+
proxy: boolean;
|
|
23
|
+
/** Whether readers may download the spec: not in a protected section. */
|
|
24
|
+
download: boolean;
|
|
25
|
+
}
|
|
26
|
+
const { contentDir, slug, proxy, download } = Astro.props as Props;
|
|
27
|
+
const json = jsonForScript(JSON.parse(fs.readFileSync(scalarDocumentFile(contentDir, slug), 'utf-8')));
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
<div class={SCALAR_REFERENCE_CLASS} data-wd-scalar-reference data-proxy={String(proxy)} data-download={String(download)}>
|
|
31
|
+
<script type="application/json" is:inline data-wd-scalar-reference-document set:html={json} />
|
|
32
|
+
<div class="wd-scalar-reference-mount"></div>
|
|
33
|
+
<p class="wd-scalar-reference-loading" data-pagefind-ignore>Loading the API reference…</p>
|
|
34
|
+
<noscript>
|
|
35
|
+
<p class="wd-scalar-reference-loading">The API reference needs JavaScript. Every operation also has a page of its own:</p>
|
|
36
|
+
<div class="wd-scalar-reference-list" data-pagefind-ignore><slot /></div>
|
|
37
|
+
</noscript>
|
|
38
|
+
</div>
|
|
39
|
+
|
|
40
|
+
<script>
|
|
41
|
+
// Mounts the reference when the page loads - and again after a
|
|
42
|
+
// client-side navigation back to it.
|
|
43
|
+
async function initScalarReference() {
|
|
44
|
+
const root = document.querySelector<HTMLElement>('[data-wd-scalar-reference]');
|
|
45
|
+
const source = root?.querySelector<HTMLScriptElement>('script[data-wd-scalar-reference-document]');
|
|
46
|
+
const mount = root?.querySelector<HTMLElement>('.wd-scalar-reference-mount');
|
|
47
|
+
if (!root || !source || !mount || root.dataset.wdInit) return;
|
|
48
|
+
root.dataset.wdInit = 'true';
|
|
49
|
+
try {
|
|
50
|
+
const { mountReference } = await import('../scripts/scalar-reference');
|
|
51
|
+
mountReference({
|
|
52
|
+
el: mount,
|
|
53
|
+
document: JSON.parse(source.textContent ?? '{}'),
|
|
54
|
+
proxy: root.dataset.proxy === 'true',
|
|
55
|
+
download: root.dataset.download === 'true',
|
|
56
|
+
});
|
|
57
|
+
root.querySelector('.wd-scalar-reference-loading')?.remove();
|
|
58
|
+
} catch (err) {
|
|
59
|
+
console.error('[writedocs] Could not open the API reference.', err);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
initScalarReference();
|
|
63
|
+
document.addEventListener('astro:page-load', initScalarReference);
|
|
64
|
+
</script>
|
|
65
|
+
|
|
66
|
+
<style is:global>
|
|
67
|
+
/* Only in a build with a Scalar reference (this component isn't imported
|
|
68
|
+
otherwise - lib/scalar-reference-alias.js). */
|
|
69
|
+
.wd-scalar-reference {
|
|
70
|
+
width: 100%;
|
|
71
|
+
min-width: 0;
|
|
72
|
+
}
|
|
73
|
+
.wd-scalar-reference-loading {
|
|
74
|
+
padding: 1.5rem;
|
|
75
|
+
color: var(--wd-text-muted);
|
|
76
|
+
}
|
|
77
|
+
.wd-scalar-reference-list {
|
|
78
|
+
padding: 0 1.5rem 2rem;
|
|
79
|
+
}
|
|
80
|
+
</style>
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
---
|
|
2
|
+
// The "Try it" of an API page with writedocs.json `api.playground: "scalar"`
|
|
3
|
+
// - rendered by ApiReferencePanel.astro in place of writedocs' own modal.
|
|
4
|
+
//
|
|
5
|
+
// What the page carries: the operation as an OpenAPI document
|
|
6
|
+
// (lib/scalar-document.js) in a <script type="application/json">, and the
|
|
7
|
+
// small script below. Scalar itself (src/scripts/scalar-try-it.ts, with Vue
|
|
8
|
+
// and its CSS) is import()ed on the first click of the panel's Try button,
|
|
9
|
+
// so a page nobody clicks Try it on downloads none of it. The document is
|
|
10
|
+
// in the page, not a file of its own: it's served with the page, and on a
|
|
11
|
+
// page of a protected section (`access`) stays behind the same rule.
|
|
12
|
+
import { scalarDocument, jsonForScript } from '../lib/scalar-document.js';
|
|
13
|
+
import type { OpenApiOperation } from '../lib/openapi-render';
|
|
14
|
+
|
|
15
|
+
interface Props {
|
|
16
|
+
op: OpenApiOperation;
|
|
17
|
+
proxy: boolean;
|
|
18
|
+
title: string;
|
|
19
|
+
}
|
|
20
|
+
const { op, proxy, title } = Astro.props as Props;
|
|
21
|
+
const json = jsonForScript(scalarDocument(op, { title }));
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
<script type="application/json" is:inline data-wd-scalar-document data-method={op.method} data-path={op.path} data-proxy={String(proxy)} set:html={json} />
|
|
25
|
+
|
|
26
|
+
<script>
|
|
27
|
+
// The Try button (data-role="open-scalar", in ApiReferencePanel.astro)
|
|
28
|
+
// loads Scalar on its first click and opens it on this page's operation.
|
|
29
|
+
function initScalarTryIt(root: ParentNode) {
|
|
30
|
+
root.querySelectorAll<HTMLButtonElement>('[data-role="open-scalar"]').forEach((button) => {
|
|
31
|
+
if (button.dataset.wdInit) return;
|
|
32
|
+
button.dataset.wdInit = 'true';
|
|
33
|
+
button.addEventListener('click', async () => {
|
|
34
|
+
const source = document.querySelector<HTMLScriptElement>('script[data-wd-scalar-document]');
|
|
35
|
+
if (!source || button.getAttribute('aria-busy') === 'true') return;
|
|
36
|
+
button.setAttribute('aria-busy', 'true');
|
|
37
|
+
// The first click downloads the client (~1 MB): on a slow connection
|
|
38
|
+
// that's seconds, so the button says so - only if it takes a moment,
|
|
39
|
+
// so an already-loaded client doesn't flash it.
|
|
40
|
+
const label = button.innerHTML;
|
|
41
|
+
const loading = setTimeout(() => {
|
|
42
|
+
button.textContent = 'Loading…';
|
|
43
|
+
}, 150);
|
|
44
|
+
try {
|
|
45
|
+
const { openTryIt } = await import('../scripts/scalar-try-it');
|
|
46
|
+
const method = source.dataset.method ?? 'GET';
|
|
47
|
+
const path = source.dataset.path ?? '/';
|
|
48
|
+
await openTryIt({
|
|
49
|
+
document: JSON.parse(source.textContent ?? '{}'),
|
|
50
|
+
method,
|
|
51
|
+
path,
|
|
52
|
+
proxy: source.dataset.proxy === 'true',
|
|
53
|
+
key: `${location.pathname} ${method} ${path}`,
|
|
54
|
+
});
|
|
55
|
+
} catch (err) {
|
|
56
|
+
console.error('[writedocs] Could not open Try it.', err);
|
|
57
|
+
} finally {
|
|
58
|
+
clearTimeout(loading);
|
|
59
|
+
button.innerHTML = label;
|
|
60
|
+
button.removeAttribute('aria-busy');
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
initScalarTryIt(document);
|
|
66
|
+
document.addEventListener('astro:page-load', () => initScalarTryIt(document));
|
|
67
|
+
</script>
|
|
68
|
+
|
|
69
|
+
<style is:global>
|
|
70
|
+
/* Only in a build with Scalar's Try it (this component isn't imported
|
|
71
|
+
otherwise - lib/scalar-try-it-alias.js). */
|
|
72
|
+
.wd-api-try-inline[aria-busy='true'] {
|
|
73
|
+
cursor: progress;
|
|
74
|
+
opacity: 0.75;
|
|
75
|
+
}
|
|
76
|
+
</style>
|