Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/lib/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ export const frontmatterSchema = pageSchema.extend({
editUrl: z.string().url().optional(),
/** Written by a build script; the edit link goes to the script's source. */
generated: z.boolean().optional(),
/** Imported pages: the file they come from (repo/path) and the commit it was read at. */
source: z.string().optional(),
sourceCommit: z.string().optional(),
});

const docs = defineDocs({
Expand Down
8 changes: 8 additions & 0 deletions docs/scripts/check-output.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
// - sitemap.xml lists every page; robots.txt points at it
// - the plugin manifest schema and the bundled validator are published
// - a 404 page exists
// - no page shows raw source syntax as text: an MDX comment, a component
// tag printed instead of rendered, an escaped brace or entity (and the
// Markdown twins carry none of it outside code)
// - every page ever published (published-pages.json) is still a page or
// has a redirect (redirects.json), and new pages are recorded

Expand All @@ -16,6 +19,7 @@ import { fileURLToPath } from 'node:url';
import { files } from './lib/out.mjs';
import { checkMoves, exportedPages, readMoves } from './lib/moves.mjs';
import { proseProblems } from './lib/prose.mjs';
import { markdownProse, rawSyntax, visibleText } from './lib/raw-syntax.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(ROOT, 'out');
Expand Down Expand Up @@ -57,6 +61,9 @@ for (const segs of pages) {
need(!/<\/?Diagram\b/.test(twin), `/${md}: a <Diagram> tag was not turned into text`);
// Imported and generated pages follow the same rules as written ones.
for (const p of proseProblems(twin, { allow: PROSE_ALLOW.filter((a) => twinOf(a.file) === md) })) need(false, `/${md}:${p.line}: ${p.rule}: ${p.text}`);
// Component tags stay in the twins on purpose (they read as structure);
// a comment, an escaped brace or a double-escaped entity never should.
for (const r of rawSyntax(markdownProse(twin)).filter((f) => f.rule !== 'jsx-tag')) need(false, `/${md}: raw ${r.rule} in the text: ${r.text}`);
}
if (llms) need(llms.includes(`(${SITE}/${md})`), `llms.txt: no link to /${md}`);
if (sitemap) need(sitemap.includes(`<loc>${SITE}${url === '/' ? '/' : `${url}/`}</loc>`) || sitemap.includes(`<loc>${SITE}${url}</loc>`), `sitemap.xml: no ${url}`);
Expand All @@ -65,6 +72,7 @@ for (const segs of pages) {
const html = read(path.join(...(segs.length ? segs : ['.']), 'index.html'));
need(html && /<meta property="og:image" content="[^"]+\/og\//.test(html), `${url}: no og:image meta`);
need(html && html.includes('text/markdown'), `${url}: no Markdown alternate link`);
if (html) for (const r of rawSyntax(visibleText(html))) need(false, `${url}: raw ${r.rule} shows on the page: ${r.text}`);
}

const schemaText = read('schema/plugin-manifest.v1.json');
Expand Down
5 changes: 4 additions & 1 deletion docs/scripts/import-platform.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,12 @@ export function convertGuide(raw, srcPath, ref) {
`title: ${yamlString(front.title)}`,
...(front.description ? [`description: ${yamlString(front.description)}`] : []),
`editUrl: ${yamlString(`${REPO_URL}/blob/main/${srcPath}`)}`,
// Where the page comes from, as data. These files are Markdown, not MDX,
// so a {/* comment */} in the body would print on the page as text.
`source: ${yamlString(`${lock.repo}/${srcPath}`)}`,
`sourceCommit: ${yamlString(ref)}`,
'---',
'',
`{/* Imported from ${lock.repo}/${srcPath} at ${ref.slice(0, 12)}. Edit it there. */}`,
'',
];
// Arrows in prose become words, as on every other page (scripts/lib/prose.mjs).
Expand Down
11 changes: 10 additions & 1 deletion docs/scripts/import-platform.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const REF = '0123456789abcdef0123456789abcdef01234567';

test('a guide gets frontmatter from its first heading and paragraph, and an edit link to the platform repo', () => {
const out = convertGuide('# Install on AWS\n\nDeploy CoderHelm into **your** account in one command.\n\n## Steps\n', 'docs/self-host/install.md', REF);
assert.match(out, /^---\ntitle: "Install on AWS"\ndescription: "Deploy CoderHelm into your account in one command."\neditUrl: "https:\/\/github.com\/CoderHelm\/coderhelm-platform\/blob\/main\/docs\/self-host\/install.md"\n---/);
assert.match(out, /^---\ntitle: "Install on AWS"\ndescription: "Deploy CoderHelm into your account in one command."\neditUrl: "https:\/\/github.com\/CoderHelm\/coderhelm-platform\/blob\/main\/docs\/self-host\/install.md"\nsource: "CoderHelm\/coderhelm-platform\/docs\/self-host\/install.md"\nsourceCommit: "[0-9a-f]{40}"\n---\n\n/);
assert.ok(!out.includes('# Install on AWS'), 'the H1 becomes the page title, not a second heading');
assert.match(out, /## Steps/);
});
Expand All @@ -30,3 +30,12 @@ test('guides are listed by their order front matter, the rest by name', () => {
const order = new Map([['quick-start', 1], ['faq', 13], ['requirements', 2]]);
assert.deepEqual(sortByOrder(['faq', 'zeta', 'quick-start', 'alpha', 'requirements'], order), ['quick-start', 'requirements', 'faq', 'alpha', 'zeta']);
});

test('where a guide comes from is front matter, never a comment in the body (Markdown would print it)', () => {
const out = convertGuide('# Backups\n\nKeep a copy.\n', 'docs/self-host/backups.md', REF);
assert.match(out, /\nsource: "CoderHelm\/coderhelm-platform\/docs\/self-host\/backups.md"\n/);
assert.match(out, new RegExp(`\\nsourceCommit: "${REF}"\\n`));
const body = out.slice(out.indexOf('\n---\n', 4) + 5);
assert.ok(!/\{\/\*|<!--/.test(body), `no comment in the body:\n${body}`);
assert.match(body, /^\nKeep a copy\./);
});
48 changes: 48 additions & 0 deletions docs/scripts/lib/raw-syntax.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Finds source syntax that leaked onto a built page as visible text: an MDX
// comment, a component tag that was printed instead of rendered, an escaped
// brace, an admonition marker, or an HTML entity that was escaped twice.
// Code blocks and inline code are left out: showing syntax there is the point.

const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };

const decode = (s) =>
s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, e) => {
if (e[0] === '#') return String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1)));
return ENTITIES[e.toLowerCase()] ?? all;
});

/** The text a reader sees in an HTML document, without scripts, styles and code. */
export function visibleText(html) {
const body = html.match(/<body[^>]*>([\s\S]*)<\/body>/i)?.[1] ?? html;
return decode(
body
.replace(/<(script|style|template|noscript|svg)\b[\s\S]*?<\/\1>/gi, ' ')
.replace(/<(pre|code|kbd|samp)\b[\s\S]*?<\/\1>/gi, ' ')
.replace(/<[^>]+>/g, ' '),
).replace(/[ \t\r\n]+/g, ' ');
}

/** Markdown with fenced code blocks and inline code removed. */
export function markdownProse(md) {
return md.replace(/^(```|~~~)[\s\S]*?^\1[^\n]*$/gm, ' ').replace(/`[^`\n]*`/g, ' ');
}

const COMPONENTS = 'Callout|Cards?|Tabs?|Steps?|Accordions?|Files?|Folder|TypeTable|Diagram|Badge|Paths?|Tiles?|include';

export const RULES = [
{ rule: 'mdx-comment', re: /\{\/\*|\*\/\}/ },
{ rule: 'jsx-tag', re: new RegExp(`</?(?:${COMPONENTS})\\b[^<>]*>?`) },
{ rule: 'escaped-brace', re: /\\[{}]/ },
{ rule: 'admonition', re: /(?:^|\s):::\s*\w*|\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]/ },
{ rule: 'html-entity', re: /&(?:#x[0-9a-f]+|#\d+|[a-z]{2,8});/i },
];

/** Raw syntax in already-extracted text; each finding with some context around it. */
export function rawSyntax(text) {
const found = [];
for (const { rule, re } of RULES) {
const m = text.match(re);
if (m) found.push({ rule, text: text.slice(Math.max(0, m.index - 40), m.index + m[0].length + 40).trim() });
}
return found;
}
33 changes: 33 additions & 0 deletions docs/scripts/raw-syntax.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { markdownProse, rawSyntax, visibleText } from './lib/raw-syntax.mjs';

const rules = (text) => rawSyntax(text).map((f) => f.rule);

test('an MDX comment printed on a page is caught', () => {
const html = '<html><body><h1>Backups</h1><p>{/* Imported from x at abc. Edit it there. */}</p></body></html>';
assert.deepEqual(rules(visibleText(html)), ['mdx-comment']);
});

test('a component printed as text is caught, escaped or not', () => {
assert.deepEqual(rules(visibleText('<body><p>&lt;Callout type="warn"&gt;Careful&lt;/Callout&gt;</p></body>')), ['jsx-tag']);
assert.deepEqual(rules(visibleText('<body><p>&#x3C;Steps></p></body>')), ['jsx-tag']);
});

test('escaped braces, admonition markers and double-escaped entities are caught', () => {
assert.deepEqual(rules(visibleText('<body><p>Set \\{name\\}</p></body>')), ['escaped-brace']);
assert.deepEqual(rules(visibleText('<body><p>:::warning Do not</p></body>')), ['admonition']);
assert.deepEqual(rules(visibleText('<body><blockquote>[!NOTE] Read this</blockquote></body>')), ['admonition']);
assert.deepEqual(rules(visibleText('<body><p>a &amp;amp; b</p></body>')), ['html-entity']);
});

test('syntax inside code, scripts and styles is not visible text', () => {
const html = '<body><pre><code>{/* fine */} &lt;Callout&gt;</code></pre><p>Use <code>&lt;Tabs&gt;</code> here &amp; there.</p><script>self.__next_f.push("{/*")</script><style>a::after{content:"*/}"}</style></body>';
assert.deepEqual(rules(visibleText(html)), []);
});

test('Markdown twins are checked outside fenced and inline code', () => {
const md = '# A\n\nUse `{/* x */}` like this:\n\n```mdx\n<Callout>hi</Callout>\n```\n\nDone.\n';
assert.deepEqual(rules(markdownProse(md)), []);
assert.deepEqual(rules(markdownProse('# A\n\n{/* Imported from x. */}\n\nBody.\n')), ['mdx-comment']);
});
Loading