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
15 changes: 13 additions & 2 deletions docs/lib/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,19 @@ export function imagePath(slugs: string[]): { segments: string[]; url: string }
return { segments, url: `${docsImageRoute}/${segments.join('/')}` };
}

/** "Edit this page" link: imported pages name their own source. */
/**
* Folders of content/docs that scripts/import-platform.mjs writes (they are
* git-ignored), mapped to where this repo keeps the pages copied into them.
* Pages imported from the platform repo carry their own editUrl.
*/
export const COPIED_CONTENT: Record<string, string> = {
'self-host/': 'docs/content/self-host-site/',
};

/** "Edit this page" link: imported pages name their own source; copied pages point at the file they are copied from. */
export function editUrl(pagePath: string, override?: string): string {
if (override) return override;
return `https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/${gitConfig.contentDir}/${pagePath}`;
const prefix = Object.keys(COPIED_CONTENT).find((p) => pagePath.startsWith(p));
const file = prefix ? `${COPIED_CONTENT[prefix]}${pagePath.slice(prefix.length)}` : `${gitConfig.contentDir}/${pagePath}`;
return `https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/${file}`;
}
2 changes: 1 addition & 1 deletion docs/platform.lock.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"repo": "CoderHelm/coderhelm-platform",
"ref": "15a0414820fba184b1d6f0b7e1e7b20536b42f83"
"ref": "f561451743e38d138d632be3214b770556ff224d"
}
1 change: 1 addition & 0 deletions docs/published-pages.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
"/self-host/install/",
"/self-host/integrations/",
"/self-host/knowledge-sources/",
"/self-host/microsoft-okta-sign-in/",
"/self-host/migrate/",
"/self-host/model-providers/",
"/self-host/moving-from-hosted/",
Expand Down
6 changes: 5 additions & 1 deletion docs/scripts/check-links.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { files, idsIn, resolvePath } from './lib/out.mjs';
import { files, idsIn, isUnresolvedRelative, resolvePath } from './lib/out.mjs';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(ROOT, 'out');
Expand All @@ -24,6 +24,10 @@ function check(from, href) {
// The site's own absolute links, read as paths; a host that only starts
// with the same letters (docs.coderhelm.com.other) is someone else's.
if (href === SITE || ['/', '?', '#'].some((c) => href.startsWith(SITE + c))) href = href.slice(SITE.length) || '/';
if (isUnresolvedRelative(href)) {
checked++;
return broken.push(`${path.relative(OUT, from)} links to ${href} (a relative link: the docs turn a link into a page address only when it names an existing page's file, and pages are served with and without a trailing slash, so this one breaks)`);
}
if (!href.startsWith('/') && !href.startsWith('#')) return;
if (href.startsWith('//')) return;
checked++;
Expand Down
34 changes: 34 additions & 0 deletions docs/scripts/edit-url.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// "Edit this page" (lib/shared.ts) points at a file in a repository, never at
// a page the import writes into a git-ignored folder. One page of each kind.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { editUrl } from '../lib/shared.ts';
import { convertGuide } from './import-platform.mjs';

const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const PREFIX = 'https://github.com/CoderHelm/coderhelm/blob/main/';

/** The repository path an edit link names, which git must track. */
function tracked(url) {
assert.ok(url.startsWith(PREFIX), url);
const file = url.slice(PREFIX.length);
execFileSync('git', ['ls-files', '--error-unmatch', file], { cwd: REPO, stdio: 'pipe' });
return file;
}

test('a page written in this repo links to itself', () => {
assert.equal(tracked(editUrl('getting-started/index.mdx')), 'docs/content/docs/getting-started/index.mdx');
});

test("the site's own self-host page links to the file it is copied from", () => {
assert.equal(tracked(editUrl('self-host/aws-account.mdx')), 'docs/content/self-host-site/aws-account.mdx');
});

test('a guide imported from the platform links to the platform repo', () => {
const page = convertGuide('# Backups\n\nKeep a copy.\n', 'docs/self-host/backups.md', '0'.repeat(40));
const own = page.match(/\neditUrl: "([^"]+)"\n/)[1];
assert.equal(editUrl('self-host/backups.md', own), 'https://github.com/CoderHelm/coderhelm-platform/blob/main/docs/self-host/backups.md');
});
73 changes: 71 additions & 2 deletions docs/scripts/import-platform.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,69 @@ export const APP_PAGE_RENAMES = { uninstall: 'uninstall-details' };
export function importedName(name) {
return APP_PAGE_RENAMES[name] ?? name;
}

/**
* A link from one guide to another, as the imported page needs it. `fromDir`
* and `target` are relative to docs/self-host. The docs resolve a link to a
* page only when it names the page's file with `./` or `../`, so a bare
* `faq.md` gains `./`. A guide imported under another name (APP_PAGE_RENAMES)
* is linked by that name; at the top level, a link without a #heading lands
* on the app page that kept the address, as the sidebar does.
*/
export function guideLink(fromDir, target, hash) {
const frag = hash ? `#${hash}` : '';
const ext = path.posix.extname(target);
const base = path.posix.basename(target, ext);
const targetDir = path.posix.dirname(target);
let file = target;
if (/^\.mdx?$/i.test(ext) && Object.hasOwn(APP_PAGE_RENAMES, base)) {
if (targetDir === '.' && !hash) return `/self-host/${base}/`;
file = path.posix.join(targetDir, `${APP_PAGE_RENAMES[base]}${ext}`);
}
let rel = path.posix.relative(fromDir || '.', file) || path.posix.basename(file);
if (!rel.startsWith('../')) rel = `./${rel}`;
return `${rel}${frag}`;
}

/** The app pages under app/self-host (each folder with a page), by name. */
export function selfHostAppPages(dir = path.join(ROOT, 'app/self-host')) {
Comment thread
coderhelm[bot] marked this conversation as resolved.
Resolved
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'page.tsx'))).map((e) => e.name);
}

/**
* Links in the imported self-host pages that lead nowhere: a relative link to
* a file that was not imported (renamed or missing), or a /self-host/ link to
* neither an imported page nor an app page. `dir` is content/docs/self-host.
*/
export function guideLinkProblems(dir, appPages = selfHostAppPages()) {
const problems = [];
const exists = (p) => [p, `${p}.md`, `${p}.mdx`, path.join(p, 'index.md'), path.join(p, 'index.mdx')].some((c) => fs.existsSync(c) && fs.statSync(c).isFile());
const walk = (d) => {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const file = path.join(d, e.name);
if (e.isDirectory()) { walk(file); continue; }
if (!/\.mdx?$/i.test(e.name)) continue;
const text = fs.readFileSync(file, 'utf8').replace(/```[\s\S]*?```/g, '');
for (const m of text.matchAll(/\]\(([^)\s]+)\)/g)) {
const target = m[1].split('#')[0];
if (!target || /^(https?:|mailto:)/.test(target)) continue;
let ok;
if (target.startsWith('/self-host')) {
const sub = target.replace(/^\/self-host\/?/, '').replace(/\/$/, '');
ok = sub === '' || appPages.includes(sub) || exists(path.join(dir, sub));
} else if (target.startsWith('/')) {
continue;
} else {
ok = /^\.\.?\//.test(target) && exists(path.resolve(path.dirname(file), target.replace(/\.mdx?$/i, '')));
}
if (!ok) problems.push(`${path.relative(dir, file)}: ${m[1]}`);
}
}
};
if (fs.existsSync(dir)) walk(dir);
return problems;
}
/**
* Self-hosting pages that belong to this site rather than to the platform:
* the install guide's own pages, such as what its Launch Stack does in the
Expand Down Expand Up @@ -173,6 +236,10 @@ function importSelfHost(platform) {
fs.writeFileSync(path.join(out, rel, 'meta.json'), JSON.stringify({ ...(metaTitle ? { title: metaTitle } : {}), pages: [...lead, ...pages] }, null, 2) + '\n');
};
walk(src, '');
const broken = guideLinkProblems(out);
if (broken.length) {
throw new Error(`Self-host pages link to pages that don't exist (a guide renamed, removed or linked without ./):\n ${broken.join('\n ')}`);
}
return { imported };
}

Expand Down Expand Up @@ -222,10 +289,12 @@ export function convertGuide(raw, srcPath, ref) {
}
const dir = path.posix.dirname(srcPath);
body = body.replace(/(\]\()([^)\s]+)(\))/g, (all, a, target, b) => {
if (/^(https?:|mailto:|#)/.test(target)) return all;
if (/^(https?:|mailto:|#|\/)/.test(target)) return all;
const [file, hash] = target.split('#');
const resolved = path.posix.normalize(path.posix.join(dir, file));
if (resolved.startsWith(`${SELF_HOST_SRC}/`) || resolved === SELF_HOST_SRC) return all;
if (resolved.startsWith(`${SELF_HOST_SRC}/`) || resolved === SELF_HOST_SRC) {
return `${a}${guideLink(path.posix.relative(SELF_HOST_SRC, dir), path.posix.relative(SELF_HOST_SRC, resolved), hash)}${b}`;
}
return `${a}${REPO_URL}/blob/${ref}/${resolved}${hash ? `#${hash}` : ''}${b}`;
});
const lines = [
Expand Down
55 changes: 54 additions & 1 deletion docs/scripts/import-platform.test.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { INSTALL_GUIDE_LINK, UNINSTALL_GUIDE_LINK, importedName, convertGuide, guideOrder, groupByDate, releaseNotes, selfHostLead, sitePages, sortByOrder, stableTags } from './import-platform.mjs';
import { INSTALL_GUIDE_LINK, UNINSTALL_GUIDE_LINK, importedName, convertGuide, guideLink, guideLinkProblems, selfHostAppPages, guideOrder, groupByDate, releaseNotes, selfHostLead, sitePages, sortByOrder, stableTags } from './import-platform.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import os from 'node:os';

const REF = '0123456789abcdef0123456789abcdef01234567';

Expand Down Expand Up @@ -118,3 +119,55 @@ test('only stable self-host releases are listed, never the beta builds', () => {
];
assert.deepEqual(stableTags(tags).map((t) => t.name), ['v0.8.111', 'v0.8.98']);
});

test('links to a renamed guide follow the rename: to its heading on the imported page, else to the app page that kept the address', () => {
const out = convertGuide('# A\n\nSee [keep](./uninstall.md#keep-the-data), [remove](./uninstall.md) and [faq](./faq.md).\n', 'docs/self-host/backups.md', REF);
assert.match(out, /\[keep\]\(\.\/uninstall-details\.md#keep-the-data\)/);
assert.match(out, /\[remove\]\(\/self-host\/uninstall\/\)/);
assert.match(out, /\[faq\]\(\.\/faq\.md\)/);
// Every rename is followed, not only today's one.
for (const [from, to] of Object.entries({ uninstall: 'uninstall-details' })) {
assert.equal(guideLink('', `${from}.md`, 'x'), `./${to}.md#x`);
assert.equal(guideLink('', `${from}.md`), `/self-host/${from}/`);
}
});

test('a bare link to another guide gains ./ so the docs resolve it to the page', () => {
const out = convertGuide('# A\n\nSee [security](security.md#the-reader-update) and [bedrock](bedrock.md).\n', 'docs/self-host/integrations.md', REF);
assert.match(out, /\[security\]\(\.\/security\.md#the-reader-update\)/);
assert.match(out, /\[bedrock\]\(\.\/bedrock\.md\)/);
assert.equal(guideLink('sub', 'faq.md'), '../faq.md');
assert.equal(guideLink('sub', 'sub/b.md'), './b.md');
});

test('the import fails on a link to a renamed, missing or bare page, and passes once each is fixed', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'self-host-'));
try {
fs.writeFileSync(path.join(dir, 'faq.md'), 'x');
fs.writeFileSync(path.join(dir, 'uninstall-details.md'), 'x');
// What the import wrote before renames were followed: each of these was a 404 on the site.
fs.writeFileSync(path.join(dir, 'backups.md'), 'See [a](./uninstall.md#keep), [b](security.md), [c](./gone.md) and [d](/self-host/nowhere/).\n');
assert.deepEqual(guideLinkProblems(dir, ['install', 'uninstall']), [
'backups.md: ./uninstall.md#keep',
'backups.md: security.md',
'backups.md: ./gone.md',
'backups.md: /self-host/nowhere/',
]);
fs.writeFileSync(path.join(dir, 'backups.md'), 'See [a](./uninstall-details.md#keep), [b](./faq.md), [c](/self-host/uninstall/), [d](/self-host/faq/) and [e](https://example.com).\n\n```\n[not a link](./gone.md)\n```\n');
assert.deepEqual(guideLinkProblems(dir, ['install', 'uninstall']), []);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});

test('the app pages a guide may link to are the folders under app/self-host', () => {
const pages = selfHostAppPages();
assert.ok(pages.includes('install') && pages.includes('uninstall'), pages.join(','));
for (const name of Object.keys({ uninstall: 1 })) assert.ok(pages.includes(name), `the renamed guide ${name} has an app page`);
});

test('check:links reports a link the docs left relative', async () => {
const { isUnresolvedRelative } = await import('./lib/out.mjs');
for (const href of ['./uninstall.md', './uninstall.md#keep', 'security.md', '../faq.md']) assert.ok(isUnresolvedRelative(href), href);
for (const href of ['/self-host/faq/', '#top', 'https://example.com', 'mailto:a@example.com', '?q=1']) assert.ok(!isUnresolvedRelative(href), href);
});
9 changes: 9 additions & 0 deletions docs/scripts/lib/out.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ export function resolvePath(outDir, urlPath) {
return candidates.find((c) => fs.existsSync(c) && fs.statSync(c).isFile()) ?? null;
}

/**
* A link in a shipped page that is still relative (`./uninstall.md`, `faq.md`):
* the docs left it as written because it named no page they know, and it
* resolves differently on /a/b and /a/b/, so it is broken on at least one.
*/
export function isUnresolvedRelative(href) {
return href !== '' && !/^([a-z][a-z0-9+.-]*:|\/|#|\?)/i.test(href);
}

/** Ids in an HTML file, for checking #fragments. */
export function idsIn(html) {
return new Set([...html.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]));
Expand Down
Loading