Branchwell

PulseCanvas / website / scripts / indexnow.mjs

1#!/usr/bin/env node
2// Tells IndexNow which pages changed in this deploy, so Bing (and the assistants that
3// search through it, such as Copilot and ChatGPT) re-read them within minutes instead of days.
4//
5// It runs at the end of a Vercel or Cloudflare Pages build. For every URL in the built sitemap it compares the
6// page's words (title, description, structured data and visible text) with the page that is
7// live right now, and submits only the pages that differ, plus pages that were added or removed.
8// With --lastmod it also writes <lastmod> into the built sitemap: today for a changed page,
9// otherwise the date the live sitemap (or the committed one) already shows.
10//
11// Production deploys submit. Preview deploys only print what they would submit.
12// Local builds do nothing. It never fails a build.
13//
14// Usage: node indexnow.mjs <built sitemap> <built html dir> [more dirs...] [--lastmod]
15// The key below is public by design: IndexNow checks it against /<key>.txt on the site.
16import { existsSync, readFileSync, writeFileSync } from 'node:fs';
17import { join } from 'node:path';
18
19const KEY = '66365049776433ceca35572e03fca658';
20const ENDPOINT = process.env.INDEXNOW_ENDPOINT || 'https://api.indexnow.org/indexnow';
21// Vercel sets VERCEL_ENV; a Cloudflare Pages build of main is production, any other branch a preview.
22const cfBranch = process.env.CF_PAGES ? process.env.CF_PAGES_BRANCH : process.env.WORKERS_CI ? process.env.WORKERS_CI_BRANCH : null;
23const mode = process.env.VERCEL_ENV || (cfBranch == null ? undefined : cfBranch === 'main' ? 'production' : 'preview'); // production | preview | undefined (local)
24
25const args = process.argv.slice(2);
26const withLastmod = args.includes('--lastmod');
27const [sitemapFile, ...dirs] = args.filter((arg) => arg !== '--lastmod');
28
29const locs = (xml) => [...xml.matchAll(/<url>([\s\S]*?)<\/url>/g)].map(([, entry]) => ({
30 loc: (entry.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1],
31 lastmod: (entry.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1],
32})).filter((entry) => entry.loc);
33
34// What a page says, without markup, scripts or asset file names, so a rebuild alone is not a change.
35// The robots tag is left out: preview builds set noindex, and a noindex page is not in the sitemap anyway.
36export const words = (html) => {
37 const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || '';
38 const meta = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag)
39 .filter((tag) => /(?:name|property)=["'](?:description|og:title|og:description)["']/i.test(tag))
40 .map((tag) => (tag.match(/content=(?:"([^"]*)"|'([^']*)')/i) || []).slice(1).find(Boolean) || '');
41 const data = [...html.matchAll(/<script[^>]*application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)].map(([, json]) => json);
42 const text = html
43 .replace(/<(script|style|noscript|template)\b[\s\S]*?<\/\1>/gi, ' ')
44 .replace(/<!--[\s\S]*?-->/g, ' ')
45 .replace(/<[^>]+>/g, ' ');
46 return [title, ...meta, ...data, text].join(' ').replace(/&nbsp;|&#160;/g, ' ').replace(/\s+/g, ' ').trim();
47};
48
49const builtPage = (url) => {
50 const path = decodeURIComponent(new URL(url).pathname).replace(/\/+$/, '');
51 for (const dir of dirs) {
52 for (const file of path ? [`${path}.html`, `${path}/index.html`] : ['/index.html']) {
53 if (existsSync(join(dir, file))) return readFileSync(join(dir, file), 'utf8');
54 }
55 }
56 return null;
57};
58
59const get = async (url) => {
60 const target = process.env.INDEXNOW_TEST_ORIGIN ? url.replace(/^https?:\/\/[^/]+/, process.env.INDEXNOW_TEST_ORIGIN) : url;
61 const response = await fetch(target, { signal: AbortSignal.timeout(10000), headers: { 'user-agent': 'indexnow-build-check' } });
62 return { status: response.status, body: response.status === 200 ? await response.text() : '' };
63};
64
65async function main() {
66 if (!mode || !sitemapFile || !existsSync(sitemapFile)) return;
67 const xml = readFileSync(sitemapFile, 'utf8');
68 const pages = locs(xml);
69 if (!pages.length) return;
70 const origin = new URL(pages[0].loc).origin;
71
72 const liveSitemap = await get(`${origin}/sitemap.xml`).catch(() => ({ status: 0, body: '' }));
73 const live = new Map(locs(liveSitemap.body).map((entry) => [entry.loc, entry.lastmod]));
74
75 const changed = [];
76 const skipped = [];
77 for (let start = 0; start < pages.length; start += 8) {
78 await Promise.all(pages.slice(start, start + 8).map(async ({ loc }) => {
79 const built = builtPage(loc);
80 if (built === null) return skipped.push(`${loc} (not built as a file)`);
81 const now = await get(loc).catch(() => null);
82 if (now && now.status === 404) return changed.push(loc); // new page
83 if (!now || now.status !== 200) return skipped.push(`${loc} (live page did not load)`);
84 if (words(built) !== words(now.body)) changed.push(loc);
85 }));
86 }
87 // A page that left the sitemap is submitted too, so it drops out of the index.
88 const removed = liveSitemap.status === 200 ? [...live.keys()].filter((loc) => !pages.some((page) => page.loc === loc)) : [];
89
90 if (withLastmod) {
91 const today = new Date().toISOString().slice(0, 10);
92 const dated = xml.replace(/<url>([\s\S]*?)<\/url>/g, (entry, inner) => {
93 const loc = (inner.match(/<loc>\s*([^<\s]+)\s*<\/loc>/) || [])[1];
94 const committed = (inner.match(/<lastmod>\s*([^<\s]+)\s*<\/lastmod>/) || [])[1];
95 const date = changed.includes(loc) ? today : live.get(loc) || committed;
96 const bare = inner.replace(/\s*<lastmod>[\s\S]*?<\/lastmod>/, '');
97 return `<url>${date ? bare.replace(/<\/loc>/, `</loc><lastmod>${date}</lastmod>`) : bare}</url>`;
98 });
99 writeFileSync(sitemapFile, dated);
100 }
101
102 const urlList = [...changed, ...removed];
103 for (const note of skipped) console.log(`IndexNow: skipped ${note}`);
104 if (!urlList.length) return console.log(`IndexNow: no page changed (${pages.length} checked).`);
105 console.log(`IndexNow: ${urlList.length} of ${pages.length} page(s) changed:\n ${urlList.join('\n ')}`);
106 if (mode !== 'production') return console.log('IndexNow: preview build, nothing submitted.');
107
108 const host = new URL(origin).host;
109 const response = await fetch(ENDPOINT, {
110 method: 'POST',
111 signal: AbortSignal.timeout(10000),
112 headers: { 'content-type': 'application/json; charset=utf-8' },
113 body: JSON.stringify({ host, key: KEY, keyLocation: `${origin}/${KEY}.txt`, urlList }),
114 });
115 console.log(`IndexNow: submitted, HTTP ${response.status}.`);
116}
117
118main().catch((error) => console.log(`IndexNow: skipped (${error.message}).`));