Repository navigation
Expand file tree
/
Copy pathverify-tutorials.cjs
More file actions
247 lines (235 loc) · 15 KB
/
Copy pathverify-tutorials.cjs
File metadata and controls
247 lines (235 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {parseArgs} = require('node:util');
const {load} = require('cheerio');
const {unzipSync} = require('fflate');
const robotsParser = require('robots-parser');
const {TUTORIALS, PROJECTS, projectFiles} = require('./package-tutorials.cjs');
const {PUBLICATIONS_PATH, validatePublications} = require('../plugins/tutorial-media/publications');
const imageVideos = require('../src/data/image-tutorial-videos.json');
const pngPdfVideos = require('../src/data/png-pdf-videos.json');
const layoutVideos = require('../src/data/layout-tutorial-videos.json');
const htmlPreviewVideos = require('../src/data/html-preview-videos.json');
const SITE = path.join(__dirname, '..');
const ORIGIN = 'https://docs.phcode.dev';
const GUIDES = ['tutorials', 'tutorials/add-images', 'tutorials/link-pages',
'tutorials/share-website', 'tutorials/bootstrap', 'tutorials/run-python',
'tutorials/find-and-replace', 'tutorials/replace-in-files', 'Features/find-in-files',
'tutorials/image-text-layout', 'tutorials/edit-text-fonts'];
const BLOGS = ['how-to-convert-png-to-pdf-free-online', 'how-to-convert-png-to-pdf-without-losing-quality',
'html-preview-missing-css-images-javascript', 'how-to-add-a-favicon-in-html', 'compare-two-json-files',
'convert-markdown-to-pdf-with-page-breaks', 'open-an-html-file-in-chrome',
'test-website-on-different-screen-sizes', 'get-hex-color-from-image', 'convert-webp-to-jpg-background',
'decode-base64-text-and-images', 'change-all-caps-website-text', 'change-svg-fill-and-stroke',
'make-a-markdown-table', 'responsive-css-grid-sidebar', 'fix-trailing-comma-json',
'unix-timestamp-seconds-or-milliseconds', 'convert-word-to-markdown', 'clickable-pdf-preview-html'];
const ARTICLE_ROUTES = [...GUIDES.map(guide => '/docs/' + guide), ...BLOGS.map(slug => '/blog/' + slug)];
const WATCH_VIDEOS = [...Object.values(imageVideos), ...Object.values(pngPdfVideos), ...Object.values(layoutVideos),
...Object.values(htmlPreviewVideos)];
function videoDuration(file) {
const data = fs.readFileSync(file);
function atoms(start, end) {
const entries = [];
while (start < end) {
assert(start + 8 <= end, `Truncated MP4 atom: ${file}`);
let size = data.readUInt32BE(start);
const kind = data.toString('ascii', start + 4, start + 8);
let headerSize = 8;
if (size === 1) {
assert(start + 16 <= end, `Truncated extended MP4 atom: ${file}`);
size = Number(data.readBigUInt64BE(start + 8));
headerSize = 16;
} else if (size === 0) {
size = end - start;
}
assert(Number.isSafeInteger(size) && size >= headerSize && start + size <= end, `Invalid MP4 atom: ${file}`);
entries.push({kind, start, payload: start + headerSize, end: start + size});
start += size;
}
return entries;
}
const top = atoms(0, data.length);
const movie = top.find(atom => atom.kind === 'moov');
const media = top.find(atom => atom.kind === 'mdat');
assert(movie && media && movie.start < media.start, `MP4 is missing fast-start metadata: ${file}`);
const header = atoms(movie.payload, movie.end).find(atom => atom.kind === 'mvhd');
assert(header && header.payload < header.end, `Missing MP4 duration: ${file}`);
const value = data.subarray(header.payload, header.end);
assert(value[0] === 0 || value[0] === 1, `Unsupported MP4 timing version: ${file}`);
const extended = value[0] === 1;
assert(value.length >= (extended ? 32 : 20), `Truncated MP4 timing: ${file}`);
const timescale = value.readUInt32BE(extended ? 20 : 12);
const duration = extended ? Number(value.readBigUInt64BE(24)) : value.readUInt32BE(16);
assert(timescale > 0 && duration > 0 && Number.isSafeInteger(duration), `Invalid MP4 duration: ${file}`);
return duration / timescale;
}
function verify(build, release = false) {
build = path.resolve(build);
const pages = new Map();
const robots = robotsParser(`${ORIGIN}/robots.txt`, fs.readFileSync(path.join(build, 'robots.txt'), 'utf8'));
function page(file) {
if (!pages.has(file)) pages.set(file, load(fs.readFileSync(file, 'utf8')));
return pages.get(file);
}
function target(url, route = '/') {
const absolute = new URL(url, ORIGIN + route);
if (absolute.host !== 'docs.phcode.dev' || !['http:', 'https:'].includes(absolute.protocol)) return null;
const relative = decodeURIComponent(absolute.pathname).replace(/^\/+/, '');
const candidates = [`${relative.replace(/\/+$/, '')}.html`, relative, path.join(relative, 'index.html')]
.map(name => path.resolve(build, name));
const file = candidates.find(candidate => {
const within = path.relative(build, candidate);
return within !== '..' && !within.startsWith(`..${path.sep}`) && !path.isAbsolute(within) &&
fs.existsSync(candidate) && fs.statSync(candidate).isFile();
});
assert(file, `Missing local target: ${absolute.href}`);
assert(robots.isAllowed(absolute.href, 'Googlebot') === true, `Crawler blocked: ${absolute.href}`);
if (absolute.hash && path.extname(file) === '.html') {
const document = page(file);
const ids = document('[id]').map((_, element) => document(element).attr('id')).get();
assert(ids.includes(decodeURIComponent(absolute.hash.slice(1))), `Missing anchor: ${absolute.href}`);
}
return file;
}
const sitemap = load(fs.readFileSync(path.join(build, 'sitemap.xml'), 'utf8'), {xmlMode: true});
const indexed = new Set(sitemap('loc').map((_, element) => sitemap(element).text()).get());
for (const route of ARTICLE_ROUTES) {
const document = page(target(route));
assert(indexed.has(ORIGIN + route), `Tutorial missing from sitemap: ${route}`);
assert.equal(document('article h1').length, 1, `Expected one tutorial title: ${route}`);
const canonicals = document('link[rel="canonical"]').map((_, element) => document(element).attr('href')).get();
assert.deepEqual(canonicals, [ORIGIN + route], `Incorrect canonical URL: ${route}`);
document('meta[name="robots"]').each((_, element) => {
assert(!/noindex/i.test(document(element).attr('content') || ''), `Tutorial marked noindex: ${route}`);
});
document('article a, article img, article source, article track').each((_, element) => {
const url = document(element).attr(element.tagName === 'a' ? 'href' : 'src');
if (url) target(url, route);
});
// Blog author avatars sit outside the Markdown article body.
const articleImages = route.startsWith('/blog/') ? 'article .markdown img' : 'article img';
document(articleImages).each((_, element) => {
const image = document(element);
assert(image.attr('alt') && image.attr('width') && image.attr('height'), `Incomplete image attributes: ${route}`);
});
}
const imagePage = page(target('/docs/tutorials/add-images'));
assert.equal(imagePage('article details').length, 5, 'Expected five image FAQs');
const captures = JSON.parse(fs.readFileSync(path.join(SITE, 'scripts/tutorial-media-manifest.json'), 'utf8'));
const publications = validatePublications(JSON.parse(fs.readFileSync(path.join(build, PUBLICATIONS_PATH), 'utf8'))).videos;
const videos = ARTICLE_ROUTES.flatMap(route => {
const document = page(target(route));
const schemas = document('script[type="application/ld+json"]').toArray()
.map(element => JSON.parse(document(element).text())).filter(schema => schema['@type'] === 'VideoObject');
assert.equal(schemas.length, document('article video').length, `Video metadata missing: ${route}`);
return schemas.map(schema => ({schema, document}));
});
assert.equal(videos.length, captures.recordings.length, 'Every recorded video must have a player and metadata');
assert.equal(new Set(videos.map(({schema}) => schema.contentUrl)).size, videos.length, 'Video sources must be distinct');
assert.equal(new Set(videos.map(({schema}) => schema.name)).size, videos.length, 'Video names must be distinct');
const captionTextBySource = new Map();
for (const {schema, document} of videos) {
const source = new URL(schema.contentUrl).pathname;
const player = document('article video').toArray().find(element => document(element).find('source').attr('src') === source);
assert(player && schema.description && schema.name, `Incomplete video metadata: ${source}`);
assert.equal(document(player).attr('poster'), new URL(schema.thumbnailUrl[0]).pathname, `Video poster mismatch: ${source}`);
assert.equal(document(player).find('track[kind="captions"]').attr('src'), new URL(schema.caption.contentUrl).pathname, `Video captions mismatch: ${source}`);
for (const url of [schema.contentUrl, schema.thumbnailUrl[0], schema.caption.contentUrl]) target(url);
const duration = videoDuration(target(source));
const durationMatch = /^PT(\d+(?:\.\d+)?)S$/.exec(schema.duration);
assert(durationMatch && Math.abs(Number(durationMatch[1]) - duration) < 0.02, `Incorrect duration: ${source}`);
const captured = captures.recordings.find(record => '/' + record.file.replace(/^static\//, '') === source);
assert(captured && Math.abs(captured.duration_seconds - duration) < 0.02, `Capture duration mismatch: ${source}`);
if (captured.duration_limit_seconds !== undefined) {
assert(Number.isFinite(captured.duration_limit_seconds) && captured.duration_limit_seconds > 0, `Invalid duration limit: ${source}`);
assert(duration < captured.duration_limit_seconds, `Video exceeds its duration limit: ${source}`);
}
assert.equal(schema.uploadDate, publications[source], `Publication date mismatch: ${source}`);
if (release) assert(schema.uploadDate, `Release video has no first-publication date: ${source}`);
const captions = fs.readFileSync(target(schema.caption.contentUrl), 'utf8').replace(/\r\n/g, '\n');
assert(captions.startsWith('WEBVTT'), `Invalid caption format: ${source}`);
const cues = [...captions.matchAll(/(\d{2}:\d{2}:\d{2}\.\d{3}) --> (\d{2}:\d{2}:\d{2}\.\d{3})\n([^\n]+)/g)];
assert(cues.length, `Missing video captions: ${source}`);
captionTextBySource.set(source, cues.map(cue => cue[3]));
const seconds = stamp => {
const [hours, minutes, value] = stamp.split(':').map(Number);
return hours * 3600 + minutes * 60 + value;
};
let previousEnd = 0;
for (const [, start, end] of cues) {
assert(previousEnd <= seconds(start) && seconds(start) < seconds(end) && seconds(end) <= duration + 0.02,
`Invalid caption timing: ${source} (${start} --> ${end})`);
previousEnd = seconds(end);
}
}
for (const video of WATCH_VIDEOS) {
const route = video.watchPath;
const document = page(target(route));
assert(indexed.has(ORIGIN + route), `Watch page missing from sitemap: ${route}`);
assert.equal(document('main h1').length, 1, `Expected one watch-page title: ${route}`);
assert.deepEqual(document('link[rel="canonical"]').map((_, el) => document(el).attr('href')).get(),
[ORIGIN + route], `Watch page must have its own canonical URL: ${route}`);
document('meta[name="robots"], meta[name="googlebot"]').each((_, el) => {
assert(!/noindex/i.test(document(el).attr('content') || ''), `Watch page marked noindex: ${route}`);
});
// A watch page must serve one player in the initial HTML, outside tabs or
// expandable sections. Google still decides whether to index the video.
assert.equal(document('video').length, 1, `Expected one video per watch page: ${route}`);
const player = document('main video');
assert.equal(player.length, 1, `Watch-page player missing from main content: ${route}`);
assert.equal(player.closest('[hidden], [role="tabpanel"], details').length, 0,
`Watch-page player requires an interaction to appear: ${route}`);
assert.equal(player.find('source').attr('src'), video.source, `Wrong watch-page recording: ${route}`);
const schemas = document('script[type="application/ld+json"]').toArray()
.map(el => JSON.parse(document(el).text())).filter(schema => schema['@type'] === 'VideoObject');
assert.equal(schemas.length, 1, `Expected one watch-page VideoObject: ${route}`);
const original = videos.find(({schema}) => new URL(schema.contentUrl).pathname === video.source);
assert(original, `Watch page has no corresponding tutorial recording: ${route}`);
assert.deepEqual(schemas[0], original.schema, `Watch-page metadata differs from its tutorial: ${route}`);
assert.equal(player.attr('poster'), new URL(schemas[0].thumbnailUrl[0]).pathname, `Watch-page poster mismatch: ${route}`);
assert.equal(player.find('track[kind="captions"]').attr('src'), video.captions, `Watch-page captions missing: ${route}`);
assert(original.document('article a').toArray().some(el => original.document(el).attr('href') === route),
`Tutorial does not link to watch page: ${route}`);
assert(document('main a').toArray().some(el => document(el).attr('href') === video.guidePath),
`Watch page does not link to its edition's tutorial: ${route}`);
target(video.guidePath);
assert.deepEqual(document('main details li').map((_, el) => document(el).text()).get(),
captionTextBySource.get(video.source), `Watch-page instructions differ from the video captions: ${route}`);
}
let indexLinks = 0;
for (const filename of ['llms.txt', 'api/llms.txt']) {
const index = fs.readFileSync(path.join(build, filename), 'utf8');
const links = [...index.matchAll(/^- \[(?:\\.|[^\\\]])*\]\(([^)]+)\)/gm)].map(match => match[1]);
assert(index.startsWith('# Phoenix Code') && links.length && links.length === new Set(links).size,
`Invalid or duplicate AI-index entries: ${filename}`);
for (const link of links) target(link);
indexLinks += links.length;
}
for (const project of PROJECTS) {
const files = projectFiles(path.join(TUTORIALS, project));
const archive = unzipSync(fs.readFileSync(path.join(build, `tutorials/${project}.zip`)));
assert.deepEqual(Object.keys(archive).sort(), Object.keys(files).map(name => `${project}/${name}`).sort(),
`Stale practice ZIP: ${project}`);
for (const [name, content] of Object.entries(files)) {
assert(Buffer.from(archive[`${project}/${name}`]).equals(content), `Stale practice file: ${project}/${name}`);
}
}
return `PASS: ${GUIDES.length} guides, ${BLOGS.length} blog posts, local links and anchors, screenshots, 5 image FAQs, ${videos.length} videos with captions, ${WATCH_VIDEOS.length} video watch pages, ${indexLinks} AI-index links, and ${PROJECTS.length} practice ZIPs.` +
(release ? ' Release publication dates are complete.' : ' Preview metadata verified.');
}
if (require.main === module) {
try {
const {values} = parseArgs({options: {
'build-dir': {type: 'string', default: path.join(SITE, 'build')},
release: {type: 'boolean', default: false},
help: {type: 'boolean', short: 'h'},
}});
console.log(values.help ? 'Usage: npm run verify:tutorials -- [--build-dir PATH] [--release]' :
verify(values['build-dir'], values.release));
} catch (error) {
console.error(`FAIL: ${error.message}`);
process.exitCode = 1;
}
}
module.exports = {verify};