-
-
Notifications
You must be signed in to change notification settings - Fork 11.7k
Added stateless llms.txt service with dependency injection #28042
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5cb24e7
Add stateless llms.txt service with dependency injection
ErisDS 13fa3ac
Switched llms.txt gating from config flag to private labs flag
ErisDS 3e8de86
Updated config API snapshot for llmsTxt labs flag
ErisDS 25da3f5
Address review feedback and fix CI OOM
ErisDS b1c92c9
Replaced broad .md regex route with scoped entry router suffix
ErisDS a37c654
Added llmsTxt toggle to Labs private features UI
ErisDS 32c4aa1
Added structured logging and Sentry reporting to llms handler
ErisDS f395ff5
Removed commentsThreads and commentsPinning from private features
ErisDS f2f933d
Fixed URL resolution to include tags and authors for permalink templates
ErisDS 84ba915
Return 403 with markdown body for non-public .md requests
ErisDS 9cd67af
Improved per-entry markdown metadata with full tags and content type
ErisDS 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 |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| const logging = require('@tryghost/logging'); | ||
| const sentry = require('../../../shared/sentry'); | ||
| const urlUtils = require('../../../shared/url-utils'); | ||
|
|
||
| const LLMS_LOG_KEY = '[llms]'; | ||
|
|
||
| function createLlmsHandler({llmsService, config, settingsCache}) { | ||
| function handleDisabledLlmsRequest(req, res, next) { | ||
| if (settingsCache.get('is_private')) { | ||
| return next(); | ||
| } | ||
|
|
||
| return res.redirect(302, urlUtils.urlFor({relativeUrl: '/'})); | ||
| } | ||
|
|
||
| function setLlmsHeaders(res) { | ||
| res.set({ | ||
| 'Cache-Control': `public, max-age=${config.get('caching:llms:maxAge')}`, | ||
| 'Content-Type': 'text/plain; charset=utf-8' | ||
| }); | ||
| } | ||
|
|
||
| async function serveLlms(req, res, next, format) { | ||
| try { | ||
| if (!llmsService.isEnabled()) { | ||
| return handleDisabledLlmsRequest(req, res, next); | ||
| } | ||
|
|
||
| const content = format === 'full' | ||
| ? await llmsService.getLlmsFullTxt() | ||
| : await llmsService.getLlmsTxt(); | ||
|
|
||
| if (!content) { | ||
| return next(); | ||
| } | ||
|
|
||
| setLlmsHeaders(res); | ||
| return res.send(content); | ||
| } catch (err) { | ||
| const eventName = `llms.serve_${format}`; | ||
| const eventDetails = {route: req.path}; | ||
|
|
||
| logging.error({ | ||
| system: {event: eventName, ...eventDetails}, | ||
| err | ||
| }, `${LLMS_LOG_KEY} ${err.message}`); | ||
|
|
||
| sentry.captureException(err, { | ||
| tags: {source: eventName}, | ||
| extra: eventDetails | ||
| }); | ||
|
|
||
| return next(err); | ||
| } | ||
| } | ||
|
|
||
| function mountLlmsRoutes(siteApp) { | ||
| siteApp.get('/llms.txt', (req, res, next) => serveLlms(req, res, next, 'index')); | ||
| siteApp.get('/llms-full.txt', (req, res, next) => serveLlms(req, res, next, 'full')); | ||
| siteApp.get('/.well-known/llms.txt', (req, res, next) => serveLlms(req, res, next, 'index')); | ||
| siteApp.get('/.well-known/llms-full.txt', (req, res, next) => serveLlms(req, res, next, 'full')); | ||
| } | ||
|
|
||
| return {mountLlmsRoutes}; | ||
| } | ||
|
|
||
| module.exports = {createLlmsHandler}; |
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,180 @@ | ||
| const {NodeHtmlMarkdown} = require('node-html-markdown'); | ||
| const htmlToPlaintext = require('@tryghost/html-to-plaintext'); | ||
|
|
||
| const MAX_DESCRIPTION_LENGTH = 300; | ||
|
|
||
| const nhm = new NodeHtmlMarkdown({ | ||
| bulletMarker: '-', | ||
| codeFence: '```', | ||
| emDelimiter: '*', | ||
| strongDelimiter: '**' | ||
| }); | ||
|
|
||
| function collapseWhitespace(value) { | ||
| return (value || '').replace(/\s+/g, ' ').trim(); | ||
| } | ||
|
|
||
| function truncateDescription(value, maxLength = MAX_DESCRIPTION_LENGTH) { | ||
| const collapsed = collapseWhitespace(value); | ||
|
|
||
| if (!collapsed || collapsed.length <= maxLength) { | ||
| return collapsed; | ||
| } | ||
|
|
||
| return `${collapsed.slice(0, maxLength - 1).trimEnd()}…`; | ||
| } | ||
|
|
||
| function getMarkdownPath(pathname) { | ||
| if (!pathname || pathname === '/') { | ||
| return '/index.md'; | ||
| } | ||
|
|
||
| const normalizedPath = pathname.endsWith('/') ? pathname.slice(0, -1) : pathname; | ||
| return `${normalizedPath}.md`; | ||
| } | ||
|
|
||
| function getMarkdownUrl(url) { | ||
| const parsedUrl = new URL(url); | ||
| parsedUrl.pathname = getMarkdownPath(parsedUrl.pathname); | ||
| return parsedUrl.toString(); | ||
| } | ||
|
|
||
| function getResourcePathFromMarkdownPath(pathname) { | ||
| if (!pathname || !pathname.endsWith('.md')) { | ||
| return null; | ||
| } | ||
|
|
||
| const stripped = pathname.slice(0, -3); | ||
|
|
||
| if (!stripped || stripped === '/index') { | ||
| return '/'; | ||
| } | ||
|
|
||
| return stripped.endsWith('/') ? stripped : `${stripped}/`; | ||
| } | ||
|
|
||
| function getAcceptedMarkdownContentType(req) { | ||
| const acceptHeader = (req.get('Accept') || '').toLowerCase(); | ||
|
|
||
| if (!acceptHeader.includes('text/markdown') && !acceptHeader.includes('text/plain')) { | ||
| return null; | ||
| } | ||
|
|
||
| const preferredType = req.accepts(['text/markdown', 'text/plain', 'text/html']); | ||
|
|
||
| if (!preferredType || preferredType === 'text/html') { | ||
| return null; | ||
| } | ||
|
|
||
| return preferredType; | ||
| } | ||
|
|
||
| function markdownFromHtml(html) { | ||
| const markdown = nhm.translate(html || '').trim(); | ||
|
|
||
| if (!markdown) { | ||
| return null; | ||
| } | ||
|
|
||
| return markdown.replace(/\n{3,}/g, '\n\n'); | ||
| } | ||
|
|
||
| function formatIsoDate(value) { | ||
| if (!value) { | ||
| return null; | ||
| } | ||
|
|
||
| const date = new Date(value); | ||
|
|
||
| if (isNaN(date.getTime())) { | ||
| return null; | ||
| } | ||
|
|
||
| return date.toISOString(); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| function getPrimaryAuthorName(entry) { | ||
| if (entry.primary_author?.name) { | ||
| return entry.primary_author.name; | ||
| } | ||
|
|
||
| if (Array.isArray(entry.authors) && entry.authors[0]?.name) { | ||
| return entry.authors[0].name; | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| function getTagNames(entry) { | ||
| if (Array.isArray(entry.tags) && entry.tags.length) { | ||
| return entry.tags.map(t => t.name).filter(Boolean); | ||
| } | ||
|
|
||
| if (entry.primary_tag?.name) { | ||
| return [entry.primary_tag.name]; | ||
| } | ||
|
|
||
| return []; | ||
| } | ||
|
|
||
| function renderEntryMarkdownBody(entry) { | ||
| const markdown = markdownFromHtml(entry.html); | ||
|
|
||
| if (markdown) { | ||
| return markdown; | ||
| } | ||
|
|
||
| if (entry.plaintext) { | ||
| return collapseWhitespace(entry.plaintext); | ||
| } | ||
|
|
||
| return collapseWhitespace(htmlToPlaintext.excerpt(entry.html || '')); | ||
| } | ||
|
|
||
| function renderEntryMarkdown(entry, {llmsIndexUrl}) { | ||
| const tags = getTagNames(entry); | ||
| const metadata = [ | ||
| entry.url ? `- URL: ${entry.url}` : null, | ||
| entry.type ? `- Type: ${entry.type}` : null, | ||
| formatIsoDate(entry.published_at) ? `- Published: ${formatIsoDate(entry.published_at)}` : null, | ||
| formatIsoDate(entry.updated_at) ? `- Updated: ${formatIsoDate(entry.updated_at)}` : null, | ||
| collapseWhitespace(entry.custom_excerpt) ? `- Description: ${collapseWhitespace(entry.custom_excerpt)}` : null, | ||
| getPrimaryAuthorName(entry) ? `- Author: ${getPrimaryAuthorName(entry)}` : null, | ||
| tags.length ? `- Tags: ${tags.join(', ')}` : null | ||
| ].filter(Boolean); | ||
|
|
||
| const body = renderEntryMarkdownBody(entry) || '_No content available._'; | ||
| const lines = [ | ||
| '> ## Content Index', | ||
| `> Fetch the complete content index at: ${llmsIndexUrl}`, | ||
| '> Use this file to discover other available public pages before exploring further.', | ||
| '', | ||
| `# ${entry.title || 'Untitled'}` | ||
| ]; | ||
|
|
||
| if (metadata.length) { | ||
| lines.push(...metadata, ''); | ||
| } else { | ||
| lines.push(''); | ||
| } | ||
|
|
||
| lines.push(body); | ||
|
|
||
| return lines.join('\n'); | ||
| } | ||
|
|
||
| module.exports = { | ||
| MAX_DESCRIPTION_LENGTH, | ||
| collapseWhitespace, | ||
| formatIsoDate, | ||
| getAcceptedMarkdownContentType, | ||
| getMarkdownPath, | ||
| getMarkdownUrl, | ||
| getPrimaryAuthorName, | ||
| getTagNames, | ||
| getResourcePathFromMarkdownPath, | ||
| markdownFromHtml, | ||
| renderEntryMarkdown, | ||
| renderEntryMarkdownBody, | ||
| truncateDescription | ||
| }; | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.