-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathreadme.ts
More file actions
461 lines (414 loc) · 14.3 KB
/
readme.ts
File metadata and controls
461 lines (414 loc) · 14.3 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import { marked, type Tokens } from 'marked'
import sanitizeHtml from 'sanitize-html'
import { hasProtocol } from 'ufo'
import type { ReadmeResponse, TocItem } from '#shared/types/readme'
import { convertBlobOrFileToRawUrl, type RepositoryInfo } from '#shared/utils/git-providers'
import { highlightCodeSync } from './shiki'
import { convertToEmoji } from '#shared/utils/emoji'
/**
* Playground provider configuration
*/
interface PlaygroundProvider {
id: string // Provider identifier
name: string
domains: string[] // Associated domains
icon?: string // Provider icon name
}
/**
* Known playground/demo providers
*/
const PLAYGROUND_PROVIDERS: PlaygroundProvider[] = [
{
id: 'stackblitz',
name: 'StackBlitz',
domains: ['stackblitz.com', 'stackblitz.io'],
icon: 'stackblitz',
},
{
id: 'codesandbox',
name: 'CodeSandbox',
domains: ['codesandbox.io', 'githubbox.com', 'csb.app'],
icon: 'codesandbox',
},
{
id: 'codepen',
name: 'CodePen',
domains: ['codepen.io'],
icon: 'codepen',
},
{
id: 'jsfiddle',
name: 'JSFiddle',
domains: ['jsfiddle.net'],
icon: 'jsfiddle',
},
{
id: 'replit',
name: 'Replit',
domains: ['repl.it', 'replit.com'],
icon: 'replit',
},
{
id: 'gitpod',
name: 'Gitpod',
domains: ['gitpod.io'],
icon: 'gitpod',
},
{
id: 'vue-playground',
name: 'Vue Playground',
domains: ['play.vuejs.org', 'sfc.vuejs.org'],
icon: 'vue',
},
{
id: 'nuxt-new',
name: 'Nuxt Starter',
domains: ['nuxt.new'],
icon: 'nuxt',
},
{
id: 'vite-new',
name: 'Vite Starter',
domains: ['vite.new'],
icon: 'vite',
},
]
/**
* Check if a URL is a playground link and return provider info
*/
function matchPlaygroundProvider(url: string): PlaygroundProvider | null {
try {
const parsed = new URL(url)
const hostname = parsed.hostname.toLowerCase()
for (const provider of PLAYGROUND_PROVIDERS) {
for (const domain of provider.domains) {
if (hostname === domain || hostname.endsWith(`.${domain}`)) {
return provider
}
}
}
} catch {
// Invalid URL
}
return null
}
// only allow h3-h6 since we shift README headings down by 2 levels
// (page h1 = package name, h2 = "Readme" section, so README h1 → h3)
const ALLOWED_TAGS = [
'h3',
'h4',
'h5',
'h6',
'p',
'br',
'hr',
'ul',
'ol',
'li',
'blockquote',
'pre',
'code',
'a',
'strong',
'em',
'del',
's',
'table',
'thead',
'tbody',
'tr',
'th',
'td',
'img',
'picture',
'source',
'details',
'summary',
'div',
'span',
'sup',
'sub',
'kbd',
'mark',
'button',
]
const ALLOWED_ATTR: Record<string, string[]> = {
'*': ['id'], // Allow id on all tags
'a': ['href', 'title', 'target', 'rel'],
'img': ['src', 'alt', 'title', 'width', 'height', 'align'],
'source': ['src', 'srcset', 'type', 'media'],
'button': ['class', 'title', 'type', 'aria-label', 'data-copy'],
'th': ['colspan', 'rowspan', 'align'],
'td': ['colspan', 'rowspan', 'align'],
'h3': ['data-level', 'align'],
'h4': ['data-level', 'align'],
'h5': ['data-level', 'align'],
'h6': ['data-level', 'align'],
'blockquote': ['data-callout'],
'details': ['open'],
'code': ['class'],
'pre': ['class', 'style'],
'span': ['class', 'style'],
'div': ['class', 'style', 'align'],
'p': ['align'],
}
// GitHub-style callout types
// Format: > [!NOTE], > [!TIP], > [!IMPORTANT], > [!WARNING], > [!CAUTION]
/**
* Generate a GitHub-style slug from heading text.
* - Convert to lowercase
* - Remove HTML tags
* - Replace spaces with hyphens
* - Remove special characters (keep alphanumeric, hyphens, underscores)
* - Collapse multiple hyphens
*/
function slugify(text: string): string {
return text
.replace(/<[^>]*>/g, '') // Strip HTML tags
.toLowerCase()
.trim()
.replace(/\s+/g, '-') // Spaces to hyphens
.replace(/[^\w\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff-]/g, '') // Keep alphanumeric, CJK, hyphens
.replace(/-+/g, '-') // Collapse multiple hyphens
.replace(/^-|-$/g, '') // Trim leading/trailing hyphens
}
/**
* Resolve a relative URL to an absolute URL.
* If repository info is available, resolve to provider's raw file URLs.
* For markdown files (.md), use blob URLs so they render properly.
* Otherwise, fall back to jsdelivr CDN (except for .md files which are left unchanged).
*/
function resolveUrl(url: string, packageName: string, repoInfo?: RepositoryInfo): string {
if (!url) return url
if (url.startsWith('#')) {
// Prefix anchor links to match heading IDs (avoids collision with page IDs)
return `#user-content-${url.slice(1)}`
}
if (hasProtocol(url, { acceptRelative: true })) {
try {
const parsed = new URL(url, 'https://example.com')
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return url
}
} catch {
// Invalid URL, fall through to resolve as relative
}
// return protocol-relative URLs (//example.com) as-is
if (url.startsWith('//')) {
return url
}
// for non-HTTP protocols (javascript:, data:, etc.), don't return, treat as relative
}
// Check if this is a markdown file link
const isMarkdownFile = /\.md$/i.test(url.split('?')[0]?.split('#')[0] ?? '')
// Use provider's URL base when repository info is available
// This handles assets that exist in the repo but not in the npm tarball
if (repoInfo?.rawBaseUrl) {
// Normalize the relative path (remove leading ./)
let relativePath = url.replace(/^\.\//, '')
// If package is in a subdirectory, resolve relative paths from there
// e.g., for packages/ai with ./assets/hero.gif → packages/ai/assets/hero.gif
// but for ../../.github/assets/banner.jpg → resolve relative to subdirectory
if (repoInfo.directory) {
// Split directory into parts for relative path resolution
const dirParts = repoInfo.directory.split('/').filter(Boolean)
// Handle ../ navigation
while (relativePath.startsWith('../')) {
relativePath = relativePath.slice(3)
dirParts.pop()
}
// Reconstruct the path
if (dirParts.length > 0) {
relativePath = `${dirParts.join('/')}/${relativePath}`
}
}
// For markdown files, use blob URL so they render on the provider's site
// For other files, use raw URL for direct access
const baseUrl = isMarkdownFile ? repoInfo.blobBaseUrl : repoInfo.rawBaseUrl
return `${baseUrl}/${relativePath}`
}
// For markdown files without repo info, leave unchanged (like npm does)
// This avoids 404s from jsdelivr which doesn't render markdown
if (isMarkdownFile) {
return url
}
// Fallback: relative URLs → jsdelivr CDN (may 404 if asset not in npm tarball)
return `https://cdn.jsdelivr.net/npm/${packageName}/${url.replace(/^\.\//, '')}`
}
// Convert blob/src URLs to raw URLs for images across all providers
// e.g. https://github.com/nuxt/nuxt/blob/main/.github/assets/banner.svg
// → https://github.com/nuxt/nuxt/raw/main/.github/assets/banner.svg
function resolveImageUrl(url: string, packageName: string, repoInfo?: RepositoryInfo): string {
const resolved = resolveUrl(url, packageName, repoInfo)
if (repoInfo?.provider) {
return convertBlobOrFileToRawUrl(resolved, repoInfo.provider)
}
return resolved
}
// Helper to prefix id attributes with 'user-content-'
function prefixId(tagName: string, attribs: sanitizeHtml.Attributes) {
if (attribs.id && !attribs.id.startsWith('user-content-')) {
attribs.id = `user-content-${attribs.id}`
}
return { tagName, attribs }
}
export async function renderReadmeHtml(
content: string,
packageName: string,
repoInfo?: RepositoryInfo,
): Promise<ReadmeResponse> {
if (!content) return { html: '', playgroundLinks: [], toc: [] }
const shiki = await getShikiHighlighter()
const renderer = new marked.Renderer()
// Collect playground links during parsing
const collectedLinks: PlaygroundLink[] = []
const seenUrls = new Set<string>()
// Collect table of contents items during parsing
const toc: TocItem[] = []
// Track used heading slugs to handle duplicates (GitHub-style: foo, foo-1, foo-2)
const usedSlugs = new Map<string, number>()
// Track heading hierarchy to ensure sequential order for accessibility
// Page h1 = package name, h2 = "Readme" section heading
// So README starts at h3, and we ensure no levels are skipped
// Visual styling preserved via data-level attribute (original depth)
let lastSemanticLevel = 2 // Start after h2 (the "Readme" section heading)
renderer.heading = function ({ tokens, depth }: Tokens.Heading) {
// Calculate the target semantic level based on document structure
// Start at h3 (since page h1 + section h2 already exist)
// But ensure we never skip levels - can only go down by 1 or stay same/go up
let semanticLevel: number
if (depth === 1) {
// README h1 always becomes h3
semanticLevel = 3
} else {
// For deeper levels, ensure sequential order
// Don't allow jumping more than 1 level deeper than previous
const maxAllowed = Math.min(lastSemanticLevel + 1, 6)
semanticLevel = Math.min(depth + 2, maxAllowed)
}
lastSemanticLevel = semanticLevel
const text = this.parser.parseInline(tokens)
// Generate GitHub-style slug for anchor links
let slug = slugify(text)
if (!slug) slug = 'heading' // Fallback for empty headings
// Handle duplicate slugs (GitHub-style: foo, foo-1, foo-2)
const count = usedSlugs.get(slug) ?? 0
usedSlugs.set(slug, count + 1)
const uniqueSlug = count === 0 ? slug : `${slug}-${count}`
// Prefix with 'user-content-' to avoid collisions with page IDs
// (e.g., #install, #dependencies, #versions are used by the package page)
const id = `user-content-${uniqueSlug}`
// Collect TOC item with plain text (HTML stripped)
const plainText = text.replace(/<[^>]*>/g, '').trim()
if (plainText) {
toc.push({ text: plainText, id, depth })
}
return `<h${semanticLevel} id="${id}" data-level="${depth}">${text}</h${semanticLevel}>\n`
}
// Syntax highlighting for code blocks (uses shared highlighter)
renderer.code = ({ text, lang }: Tokens.Code) => {
const html = highlightCodeSync(shiki, text, lang || 'text')
// Add copy button
return `<div class="readme-code-block" >
<button type="button" class="readme-copy-button" aria-label="Copy code" check-icon="i-carbon:checkmark" copy-icon="i-carbon:copy" data-copy>
<span class="i-carbon:copy" aria-hidden="true"></span>
<span class="sr-only">Copy code</span>
</button>
${html}
</div>`
}
// Resolve image URLs (with GitHub blob → raw conversion)
renderer.image = ({ href, title, text }: Tokens.Image) => {
const resolvedHref = resolveImageUrl(href, packageName, repoInfo)
const titleAttr = title ? ` title="${title}"` : ''
const altAttr = text ? ` alt="${text}"` : ''
return `<img src="${resolvedHref}"${altAttr}${titleAttr}>`
}
// Resolve link URLs, add security attributes, and collect playground links
renderer.link = function ({ href, title, tokens }: Tokens.Link) {
const resolvedHref = resolveUrl(href, packageName, repoInfo)
const text = this.parser.parseInline(tokens)
const titleAttr = title ? ` title="${title}"` : ''
const isExternal = resolvedHref.startsWith('http://') || resolvedHref.startsWith('https://')
const relAttr = isExternal ? ' rel="nofollow noreferrer noopener"' : ''
const targetAttr = isExternal ? ' target="_blank"' : ''
// Check if this is a playground link
const provider = matchPlaygroundProvider(resolvedHref)
if (provider && !seenUrls.has(resolvedHref)) {
seenUrls.add(resolvedHref)
// Extract label from link text (strip HTML tags for plain text)
const plainText = text.replace(/<[^>]*>/g, '').trim()
collectedLinks.push({
url: resolvedHref,
provider: provider.id,
providerName: provider.name,
label: plainText || title || provider.name,
})
}
return `<a href="${resolvedHref}"${titleAttr}${relAttr}${targetAttr}>${text}</a>`
}
// GitHub-style callouts: > [!NOTE], > [!TIP], etc.
renderer.blockquote = function ({ tokens }: Tokens.Blockquote) {
const body = this.parser.parse(tokens)
const calloutMatch = body.match(/^<p>\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:<br>)?\s*/i)
if (calloutMatch?.[1]) {
const calloutType = calloutMatch[1].toLowerCase()
const cleanedBody = body.replace(calloutMatch[0], '<p>')
return `<blockquote data-callout="${calloutType}">${cleanedBody}</blockquote>\n`
}
return `<blockquote>${body}</blockquote>\n`
}
marked.setOptions({ renderer })
const rawHtml = marked.parse(content) as string
const sanitized = sanitizeHtml(rawHtml, {
allowedTags: ALLOWED_TAGS,
allowedAttributes: ALLOWED_ATTR,
allowedSchemes: ['http', 'https', 'mailto'],
// Transform img src URLs (GitHub blob → raw, relative → GitHub raw)
transformTags: {
img: (tagName, attribs) => {
if (attribs.src) {
attribs.src = resolveImageUrl(attribs.src, packageName, repoInfo)
}
return { tagName, attribs }
},
source: (tagName, attribs) => {
if (attribs.src) {
attribs.src = resolveImageUrl(attribs.src, packageName, repoInfo)
}
if (attribs.srcset) {
attribs.srcset = attribs.srcset
.split(',')
.map(entry => {
const parts = entry.trim().split(/\s+/)
const url = parts[0]
if (!url) return entry.trim()
const descriptor = parts[1]
const resolvedUrl = resolveImageUrl(url, packageName, repoInfo)
return descriptor ? `${resolvedUrl} ${descriptor}` : resolvedUrl
})
.join(', ')
}
return { tagName, attribs }
},
a: (tagName, attribs) => {
// Add security attributes for external links
if (attribs.href && hasProtocol(attribs.href, { acceptRelative: true })) {
attribs.rel = 'nofollow noreferrer noopener'
attribs.target = '_blank'
}
return { tagName, attribs }
},
div: prefixId,
p: prefixId,
span: prefixId,
section: prefixId,
article: prefixId,
},
})
return {
html: convertToEmoji(sanitized),
playgroundLinks: collectedLinks,
toc,
}
}