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
72 changes: 62 additions & 10 deletions api/lesson.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { representation, quality, problem } = require('../lib/agent-http');
const { lessonDocumentSeo, seoTitleFor } = require('../lib/lesson-document');
const { cardTags, cardUrl, lessonCard } = require('../lib/og-cards');
const { readTranslationResult: readTranslationFromSource, TRANSLATION_LANGUAGES, isIndexedLanguage, translationsOf, lessonUrl, NATIVE_NAMES, RTL_LANGUAGES, OG_LOCALES } = require('../lib/lesson-translations');
const { phaseHubPath, phaseLabel } = require('../lib/hub-routes');
const { phaseHubPath, phaseLabel, lessonCleanPath } = require('../lib/hub-routes');

const REPO_ROOT = path.join(__dirname, '..');
const ORIGIN = 'https://aiengineeringfromscratch.com';
Expand All @@ -16,6 +16,9 @@ const FALLBACK_END = '<!-- AIFS:LESSON-FALLBACK:END -->';
const HUBS_START = '<!-- AIFS:LESSON-HUBS:START -->';
const HUBS_END = '<!-- AIFS:LESSON-HUBS:END -->';
const LESSON_QUERY_NAMES = new Set(['path', 'track', 'fromTrack', 'learningPath', 'lang', 'ttsTest', 'legacy']);
const CLEAN_QUERY_NAMES = ['cleanPhase', 'cleanLesson'];
const CLEAN_SEGMENT = /^[a-z0-9][a-z0-9-]*$/;
const cleanLessonIndexes = new WeakMap();
const LEARNING_PATH_ALIASES = Object.freeze({
'mcp-engineering': 'model-context-protocol',
});
Expand Down Expand Up @@ -122,6 +125,43 @@ function hasQuery(req, name) {
return queryNames(req).has(name);
}

function requestPathname(req) {
try {
return new URL(req.url || '/', 'http://localhost').pathname;
} catch (_) {
return '';
}
}

function cleanRequestPath(req) {
const pathname = requestPathname(req);
if (pathname === '/lesson' || pathname === '/lesson.html') return '';
const direct = /^\/learn\/([a-z0-9][a-z0-9-]*)\/([a-z0-9][a-z0-9-]*)$/.exec(pathname);
if (direct) return pathname;
const phase = queryValue(req, 'cleanPhase');
const lesson = queryValue(req, 'cleanLesson');
return CLEAN_SEGMENT.test(phase) && CLEAN_SEGMENT.test(lesson) ? `/learn/${phase}/${lesson}` : '';
}

function lessonPathForCleanPath(manifest, cleanPath) {
let index = cleanLessonIndexes.get(manifest);
if (!index) {
index = new Map();
for (const lessonPath of Object.keys(manifest.lessons)) {
const clean = lessonCleanPath(lessonPath);
if (clean && !index.has(clean)) index.set(clean, lessonPath);
}
cleanLessonIndexes.set(manifest, index);
}
return index.get(cleanPath) || '';
}

function withoutCleanNames(query) {
const params = new URLSearchParams(query);
for (const name of CLEAN_QUERY_NAMES) params.delete(name);
return params.toString();
}

function validLessonPath(value) {
if (!value || value.includes('..') || value.includes('\\') || value.includes('\0')) return false;
return /^(?:phases\/[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*|certifications\/[a-z0-9][a-z0-9-]*\/lessons\/[a-z0-9][a-z0-9-]*)$/.test(value);
Expand Down Expand Up @@ -284,11 +324,13 @@ function lessonHead(entry, page) {

function lessonHref(ref, contextParams) {
const params = new URLSearchParams();
params.set('path', ref.path);
const cleanPath = lessonCleanPath(ref.path);
if (!cleanPath) params.set('path', ref.path);
for (const name of ['track', 'fromTrack', 'learningPath', 'lang']) {
if (contextParams && contextParams[name]) params.set(name, contextParams[name]);
}
return `/lesson?${params.toString().replace(/&/g, '&amp;')}`;
const query = params.toString().replace(/&/g, '&amp;');
return `${cleanPath || '/lesson'}${query ? `?${query}` : ''}`;
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
}

function readEnglishMarkdown(assets, lessonPath) {
Expand Down Expand Up @@ -414,15 +456,17 @@ function send(res, method, status, body, cacheControl, type = 'text/html') {
res.end(method === 'HEAD' ? '' : payload);
}

function normalizedLessonLocation(req, lessonPath, entry, assets) {
function normalizedLessonLocation(req, lessonPath, entry, assets, cleanRequest) {
const params = new URLSearchParams();
const cleanPath = lessonCleanPath(lessonPath);
const certificationLesson = /^certifications\/[a-z0-9][a-z0-9-]*\/lessons\//.test(lessonPath);
const navigationByTrack = entry.navigationByTrack && typeof entry.navigationByTrack === 'object'
? entry.navigationByTrack
: {};
let needsRedirect = hasQuery(req, 'legacy') || Array.from(queryNames(req)).some(function (name) {
return !LESSON_QUERY_NAMES.has(name);
return !LESSON_QUERY_NAMES.has(name) && !(cleanRequest && CLEAN_QUERY_NAMES.includes(name));
});
if (cleanPath && !cleanRequest) needsRedirect = true;
params.set('path', lessonPath);

if (certificationLesson && hasQuery(req, 'track')) {
Expand Down Expand Up @@ -480,13 +524,18 @@ function normalizedLessonLocation(req, lessonPath, entry, assets) {
}
}

const context = new URLSearchParams(params);
context.delete('path');
const contextQuery = context.toString();
const requestQuery = rawUrlQuery(req);
if (requestQuery !== null && requestQuery !== params.toString()) {
if (cleanRequest) {
if (requestQuery !== null && withoutCleanNames(requestQuery) !== contextQuery) needsRedirect = true;
} else if (requestQuery !== null && requestQuery !== params.toString()) {
needsRedirect = true;
}

return {
location: `/lesson?${params.toString()}`,
location: cleanPath ? `${cleanPath}${contextQuery ? `?${contextQuery}` : ''}` : `/lesson?${params.toString()}`,
needsRedirect,
params,
};
Expand Down Expand Up @@ -522,8 +571,9 @@ function createHandler(options) {
return;
}

const lessonPath = queryValue(req, 'path');
if (!validLessonPath(lessonPath)) {
const cleanRequest = cleanRequestPath(req);
const queryPath = queryValue(req, 'path');
if (!cleanRequest && !validLessonPath(queryPath)) {
send(res, method, 404, errorPage('Lesson not found', 'This lesson path does not exist. Use the catalog, sitemap, or agent curriculum index to continue.'), 'no-store');
return;
}
Expand All @@ -533,14 +583,15 @@ function createHandler(options) {
const manifest = assets && assets.manifest;
if (typeof template !== 'string') throw new Error('template-shape');
if (!manifest || !manifest.lessons || typeof manifest.lessons !== 'object') throw new Error('manifest-shape');
const lessonPath = cleanRequest ? lessonPathForCleanPath(manifest, cleanRequest) : queryPath;
const entry = Object.prototype.hasOwnProperty.call(manifest.lessons, lessonPath)
? manifest.lessons[lessonPath]
: null;
if (!entry || entry.path !== lessonPath || !entry.title) {
send(res, method, 404, errorPage('Lesson not found', 'This lesson path is not part of the current curriculum. Use the catalog, sitemap, or agent curriculum index to continue.'), 'no-store');
return;
}
const normalized = normalizedLessonLocation(req, lessonPath, entry, assets);
const normalized = normalizedLessonLocation(req, lessonPath, entry, assets, Boolean(cleanRequest));
if (normalized.needsRedirect) {
res.setHeader('Location', normalized.location);
send(res, method, 308, '', PAGE_CACHE);
Expand Down Expand Up @@ -571,6 +622,7 @@ function createHandler(options) {
let html = replaceMarkedRegion(localizedTemplate(template, servedLang), SEO_START, SEO_END, lessonHead(entry, page));
html = replaceMarkedRegion(html, FALLBACK_START, FALLBACK_END, lessonFallback(entry, lessonPath, contextParams, page, body));
html = replaceMarkedRegion(html, HUBS_START, HUBS_END, lessonHubLinks(entry, page, assets.lessonTerms, assets.cheatsheets, assets.practice));
if (cleanRequest) html = html.replace('<head>', `<head>\n <base href="/">\n <meta name="aifs-lesson-path" content="${escapeHtml(lessonPath)}">`);
res.setHeader('Vary', 'Accept, Accept-Encoding');
res.setHeader('Content-Language', servedLang);
send(res, method, 200, html, cacheControl);
Expand Down
7 changes: 6 additions & 1 deletion lib/hub-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ function phaseHubPath(lessonPath) {
return match ? phasePath(phaseSlug(match[1])) : '';
}

function lessonCleanPath(lessonPath) {
const match = /^phases\/([a-z0-9][a-z0-9-]*)\/([a-z0-9][a-z0-9-]*)$/.exec(lessonPath || '');
return match ? `/learn/${phaseSlug(match[1])}/${phaseSlug(match[2])}` : '';
}

function phaseLabel(id, name) {
return `Phase ${String(id).padStart(2, '0')}: ${name}`;
}
Expand All @@ -30,4 +35,4 @@ function glossaryLookupKey(value) {
.replace(/\s+/g, ' ');
}

module.exports = { phaseSlug, phasePath, phaseHubPath, phaseLabel, termPath, glossaryLookupKey };
module.exports = { phaseSlug, phasePath, phaseHubPath, lessonCleanPath, phaseLabel, termPath, glossaryLookupKey };
6 changes: 5 additions & 1 deletion lib/lesson-translations.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const registry = require('../languages.json');
const { readBounded } = require('./read-bounded');
const { lessonCleanPath } = require('./hub-routes');

const ORIGIN = 'https://aiengineeringfromscratch.com';
const REPOSITORY = 'rohitg00/ai-engineering-from-scratch';
Expand Down Expand Up @@ -38,7 +39,10 @@ function lessonPathFromCacheKey(key) {
}

function lessonUrl(lessonPath, lang) {
return `${ORIGIN}/lesson?path=${encodeURIComponent(lessonPath)}${lang && lang !== 'en' ? `&lang=${encodeURIComponent(lang)}` : ''}`;
const language = lang && lang !== 'en' ? `lang=${encodeURIComponent(lang)}` : '';
const clean = lessonCleanPath(lessonPath);
if (clean) return `${ORIGIN}${clean}${language ? `?${language}` : ''}`;
return `${ORIGIN}/lesson?path=${encodeURIComponent(lessonPath)}${language ? `&${language}` : ''}`;
}

function canTranslate(lang, lessonPath) {
Expand Down
6 changes: 5 additions & 1 deletion lib/og-cards.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const { normalizeWhitespace } = require('./lesson-document');
const { lessonCleanPath } = require('./hub-routes');

const ORIGIN = 'https://aiengineeringfromscratch.com';
const BRAND = 'Open source · MIT';
Expand Down Expand Up @@ -96,7 +97,10 @@ function lessonCard(entry, lang = 'en') {
: `Lesson ${match.slice(1).join('.')} · ${context.phaseName || 'AI Engineering from Scratch'}`;
const languages = String(context.languages || '').split(',').map(normalizeWhitespace).filter(value => value && value !== '—').join(', ');
const meta = translated ? `Translation · ${lang}` : certification ? INDEPENDENT : [context.type, languages].filter(Boolean).join(' · ');
return card(label, meta, entry.title, summary(entry.title, entry.description), `/lesson?path=${entry.path}${translated ? `&lang=${lang}` : ''}`);
const cleanPath = lessonCleanPath(entry.path);
const language = translated ? `lang=${lang}` : '';
const page = cleanPath ? `${cleanPath}${language ? `?${language}` : ''}` : `/lesson?path=${entry.path}${language ? `&${language}` : ''}`;
return card(label, meta, entry.title, summary(entry.title, entry.description), page);
}

function trackCard(entry) {
Expand Down
6 changes: 5 additions & 1 deletion scripts/build_book.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,14 @@ def phase_title(phase):
return read_h1(PHASES / phase / "README.md") or slug_to_title(phase.split("-", 1)[-1])


def strip_number(name):
return re.sub(r"^\d+-", "", name)


def urls_for(phase, lesson):
rel = f"phases/{phase}/{lesson}"
return {
"web": f"{SITE}/lesson?path={rel}",
"web": f"{SITE}/learn/{strip_number(phase)}/{strip_number(lesson)}",
"code": f"{REPO}/tree/main/{rel}/code",
"repo": f"{REPO}/tree/main/{rel}",
}
Expand Down
4 changes: 2 additions & 2 deletions scripts/test_agent_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,12 @@ test('MCP rejects malformed requests, unsafe origins, unsupported transport and


test('resource and MCP read lesson translations only for allowlisted languages', async () => {
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X lesson', url: 'https://aiengineeringfromscratch.com/lesson?path=phases%2F01-a%2F01-x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X lesson', url: 'https://aiengineeringfromscratch.com/learn/a/x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const read = path => (path === entry.path ? entry : null);
const fetched = [];
const readTranslation = (lang, lessonPath) => { fetched.push(`${lang}:${lessonPath}`); return Promise.resolve(lang === 'hi' ? '# एक्स\n' : null); };
const translated = await readTranslatedResource(entry.path, 'hi', { read, readTranslation });
assert.deepEqual(translated, { ...entry, lang: 'hi', url: entry.url + '&lang=hi', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/translations/i18n/hi/phases/01-a/01-x/docs/hi.md', markdown: '# एक्स\n' });
assert.deepEqual(translated, { ...entry, lang: 'hi', url: entry.url + '?lang=hi', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/translations/i18n/hi/phases/01-a/01-x/docs/hi.md', markdown: '# एक्स\n' });
assert.equal(await readTranslatedResource(entry.path, 'en', { read, readTranslation }), entry);
assert.equal(await readTranslatedResource(entry.path, 'ar', { read, readTranslation }), null);
assert.equal(await readTranslatedResource('missing', 'hi', { read, readTranslation }), null);
Expand Down
16 changes: 12 additions & 4 deletions scripts/test_agent_readiness.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,15 @@ def check_refs(value):
assert all(entry["path"] == lesson_path for lesson_path, entry in lessons.items())
assert all(
entry["canonicalUrl"].startswith(
"https://aiengineeringfromscratch.com/lesson?path="
"https://aiengineeringfromscratch.com/learn/"
if entry["context"]["kind"] == "course"
else "https://aiengineeringfromscratch.com/lesson?path=certifications"
)
and "/lesson.html?" not in entry["canonicalUrl"]
for entry in lessons.values()
)
course_urls = [entry["canonicalUrl"] for entry in lessons.values() if entry["context"]["kind"] == "course"]
assert len(set(course_urls)) == len(course_urls), "two course lessons share one clean URL"

certification_manifest = json.loads((SITE / "certification-seo.json").read_text(encoding="utf-8"))
tracks = certification_manifest["tracks"]
Expand All @@ -201,12 +205,16 @@ def check_refs(value):
)

sitemap = (SITE / "sitemap.xml").read_text(encoding="utf-8")
assert sitemap.count("/lesson?path=") == len(lessons)
sitemap_lessons = {
sitemap_locs = set(re.findall(r"<loc>([^<]+)</loc>", sitemap))
assert all(entry["canonicalUrl"] in sitemap_locs for entry in lessons.values())
assert len(re.findall(r"<loc>https://aiengineeringfromscratch\.com/learn/[a-z0-9-]+/[a-z0-9-]+</loc>", sitemap)) == len(course_urls)
sitemap_certification_lessons = {
unquote(value)
for value in re.findall(r"/lesson\?path=([^<&]+)", sitemap)
}
assert sitemap_lessons == set(lessons)
assert sitemap_certification_lessons == {
lesson_path for lesson_path, entry in lessons.items() if entry["context"]["kind"] != "course"
}
assert sitemap.count("/certification?id=") == len(tracks)
assert "/lesson.html?" not in sitemap
assert "/certification.html?" not in sitemap
Expand Down
7 changes: 5 additions & 2 deletions scripts/test_agent_wire.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ test('served routing preserves HTML, negotiates every navigation page, and recov
for (const route of ['/llms.txt','/developer.md','/sitemap.xml','/style.css?v=old','/header.js?v=old','/projects-data.js']) {
const response = await fetch(base + route); assert.equal(response.status,200,route); assert.ok((await response.text()).length > 50);
}
const lesson = '/lesson?path=phases%2F00-setup-and-tooling%2F01-dev-environment';
const lesson = '/learn/setup-and-tooling/dev-environment';
assert.equal((await fetch(base + lesson)).status,200);
const legacy = await fetch(base + lesson.replace('/lesson?','/lesson.html?'), { redirect:'manual' }); assert.equal(legacy.status,308); assert.match(legacy.headers.get('location'),/^\/lesson\?/);
const legacyQuery = '?path=phases%2F00-setup-and-tooling%2F01-dev-environment';
for (const legacyRoute of ['/lesson','/lesson.html']) {
const legacy = await fetch(base + legacyRoute + legacyQuery, { redirect:'manual' }); assert.equal(legacy.status,308); assert.equal(legacy.headers.get('location'),lesson);
}
const json = await fetch(base + '/api/v1/catalog?q=attention&limit=1'); assert.equal(json.status,200); const catalog = await json.json();
const source = await fetch(base + '/api/v1/resource?path=' + encodeURIComponent(catalog.items[0].path)); assert.ok((await source.json()).markdown);
const duplicate = await fetch(base + '/api/v1/catalog?limit=1&limit=2'); assert.equal(duplicate.status,400);
Expand Down
Loading
Loading