-
Notifications
You must be signed in to change notification settings - Fork 45
[WEB-4447] Generate markdown copies of each HTML file for agents #2657
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
kennethkalmer
wants to merge
2
commits into
main
Choose a base branch
from
WEB-4447-dot-html-dot-md
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+409
−15
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,11 @@ | ||
import { GatsbyNode } from 'gatsby'; | ||
import { onPostBuild as llmstxt } from './llmstxt'; | ||
import { onPostBuild as compressAssets } from './compressAssets'; | ||
import { onPostBuild as markdownOutput } from './markdownOutput'; | ||
|
||
export const onPostBuild: GatsbyNode['onPostBuild'] = async (args) => { | ||
// Run all onPostBuild functions in sequence | ||
await llmstxt(args); | ||
await markdownOutput(args); | ||
await compressAssets(args); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
import { GatsbyNode, Reporter } from 'gatsby'; | ||
import fs from 'fs/promises'; | ||
import path from 'path'; | ||
import { glob } from 'glob'; | ||
import { JSDOM, VirtualConsole } from 'jsdom'; | ||
import TurndownService from 'turndown'; | ||
|
||
const CONFIG = { | ||
htmlDir: './public', | ||
markdownDir: './public', | ||
excludePatterns: ['404.html', 'api/**/*', 'page-data/**/*', 'static/**/*', 'docs/404.html'], | ||
includeMetadata: true, | ||
}; | ||
|
||
// Selectors for elements to remove from the HTML before converting to markdown | ||
const UNWANTED_ELEMENTS_SELECTOR = | ||
'script, style, nav[role="navigation"], .header, #header, header, .footer, #footer, footer, [aria-label="breadcrumb"], aside'; | ||
|
||
// Prioritised selectors for the main content of the page, first match wins | ||
const CONTENT_SELECTORS = ['main', '[role="main"]', '.content', '#content', 'article']; | ||
|
||
const withoutTrailingSlash = (path: string) => (path === `/` ? path : path.replace(/\/$/, ``)); | ||
|
||
const cleanAttribute = (attribute: string | null) => { | ||
return attribute ? attribute.replace(/(\n+\s*)+/g, '\n') : ''; | ||
}; | ||
|
||
async function exportToMarkdown({ reporter, siteUrl }: { reporter: Reporter; siteUrl: string }) { | ||
const turndownService = new TurndownService({ | ||
headingStyle: 'atx', | ||
codeBlockStyle: 'fenced', | ||
emDelimiter: '*', | ||
}); | ||
|
||
// Remove the anchor tags from the headers | ||
turndownService.addRule('header', { | ||
filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'], | ||
replacement: (_, node) => { | ||
const level = parseInt(node.nodeName.charAt(1), 10); | ||
return `${'#'.repeat(level)} ${node.textContent}`; | ||
}, | ||
}); | ||
|
||
// Update local links to use the siteUrl | ||
turndownService.addRule('localLink', { | ||
filter: (node) => (node.nodeName === 'A' && node.getAttribute('href')?.startsWith('/')) || false, | ||
replacement: (content, node) => { | ||
// most of this replacement is taken from the turndown library directly | ||
let href = withoutTrailingSlash(siteUrl) + (node as HTMLElement).getAttribute('href'); | ||
if (href) { | ||
href = href.replace(/([()])/g, '\\$1'); | ||
} | ||
let title = cleanAttribute((node as HTMLElement).getAttribute('title')); | ||
if (title) { | ||
title = ' "' + title.replace(/"/g, '\\"') + '"'; | ||
} | ||
return '[' + content + '](' + href + title + ')'; | ||
}, | ||
}); | ||
|
||
// Find all HTML files | ||
const htmlFiles = await glob('**/*.html', { | ||
cwd: CONFIG.htmlDir, | ||
ignore: CONFIG.excludePatterns, | ||
}); | ||
|
||
reporter.info(`Found ${htmlFiles.length} HTML files to process`); | ||
|
||
for (const htmlFile of htmlFiles) { | ||
try { | ||
const fullPath = path.join(CONFIG.htmlDir, htmlFile); | ||
const htmlContent = await fs.readFile(fullPath, 'utf-8'); | ||
|
||
// Parse and clean HTML | ||
const virtualConsole = new VirtualConsole(); // Stop CSS parsing errors from polluting the console | ||
const dom = new JSDOM(htmlContent, { url: siteUrl, virtualConsole }); | ||
const document = dom.window.document; | ||
|
||
// Remove unwanted elements | ||
const unwanted = document.querySelectorAll(UNWANTED_ELEMENTS_SELECTOR); | ||
unwanted.forEach((el) => el.remove()); | ||
|
||
// Get main content | ||
let mainContent = null; | ||
|
||
for (const selector of CONTENT_SELECTORS) { | ||
mainContent = document.querySelector(selector); | ||
if (mainContent) { | ||
break; | ||
} | ||
} | ||
|
||
if (!mainContent) { | ||
mainContent = document.body; | ||
} | ||
|
||
// Convert to markdown | ||
const markdown = turndownService.turndown(mainContent.innerHTML); | ||
|
||
// Prepare final content | ||
let finalContent = ''; | ||
|
||
if (CONFIG.includeMetadata) { | ||
const title = document.querySelector('title')?.textContent?.trim() || 'Untitled'; | ||
const description = document.querySelector('meta[name="description"]')?.getAttribute('content')?.trim() || ''; | ||
const canonicalUrl = document.querySelector('link[rel="canonical"]')?.getAttribute('href') || ''; | ||
|
||
finalContent = `--- | ||
title: "${title}" | ||
url: ${canonicalUrl || `/${htmlFile.replace('.html', '').replace('/index', '')}`} | ||
generated_at: ${new Date().toISOString()} | ||
description: "${description}" | ||
--- | ||
|
||
${markdown}`; | ||
} else { | ||
finalContent = markdown; | ||
} | ||
|
||
// Append .md to the filename, remove /index.html | ||
const outputName = `${htmlFile.replace('/index.html', '')}.md`; | ||
const outputPath = path.join(CONFIG.markdownDir, outputName); | ||
|
||
// Write markdown file | ||
await fs.writeFile(outputPath, finalContent); | ||
} catch (error) { | ||
reporter.error(`✗ Error processing ${htmlFile}:`, error as Error); | ||
} | ||
} | ||
|
||
reporter.info(`Markdown export complete! ${htmlFiles.length} files processed.`); | ||
} | ||
|
||
interface QueryResult { | ||
site: { | ||
siteMetadata: { | ||
siteUrl: string; | ||
}; | ||
}; | ||
} | ||
|
||
// Run the export | ||
export const onPostBuild: GatsbyNode['onPostBuild'] = async ({ graphql, reporter }) => { | ||
const query = ` | ||
query { | ||
site { | ||
siteMetadata { | ||
siteUrl | ||
} | ||
} | ||
} | ||
`; | ||
const { data, errors } = await graphql<QueryResult>(query); | ||
|
||
if (errors) { | ||
reporter.panicOnBuild(`Error while running GraphQL query.`); | ||
throw errors; | ||
} | ||
|
||
if (!data) { | ||
reporter.panicOnBuild(`No documents found.`); | ||
throw new Error('No documents found.'); | ||
} | ||
|
||
const siteUrl = data.site.siteMetadata.siteUrl; | ||
|
||
if (!siteUrl) { | ||
reporter.panicOnBuild(`Site URL not found.`); | ||
throw new Error('Site URL not found.'); | ||
} | ||
|
||
await exportToMarkdown({ reporter, siteUrl }); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@mattheworiordan I think we need this line in #2862 as well to help nginx along