railyard/apps/ritgram/web/utils/extractUrls.ts
caelum0x f80b04ae0f feat(ritgram): move GitGram app into railyard as Ritgram, next to Rithub
Moved later/gitgram-ai/gitgram/ to apps/ritgram/ (fresh history; full history stays in caelum0x/gitgram).
AITimeMachine stays separate in later/gitgram-ai per the Rithub master plan.
Logs, pid files and env files are ignored; GPL-3.0 mobile/proximity noted in THIRD_PARTY_NOTICES.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 04:18:46 +03:00

47 lines
1.3 KiB
TypeScript

/**
* Extracts bare http(s) URLs from free text.
*
* Used by RichContent to detect external links worth turning into an inline
* embed player or a link-preview card. Only the first few unique URLs are
* surfaced to keep the feed light. Trailing punctuation commonly adjacent to a
* URL in prose (`,`, `.`, `)`, etc.) is trimmed off.
*/
const URL_PATTERN = /\bhttps?:\/\/[^\s<>()]+/gi
const TRAILING_PUNCTUATION = /[.,!?;:'")\]]+$/
export interface ExtractUrlsOptions {
/** Maximum number of unique URLs to return (default 3). */
limit?: number
}
export function extractUrls(text: string, options: ExtractUrlsOptions = {}): string[] {
const limit = options.limit ?? 3
if (!text) return []
const seen = new Set<string>()
const result: string[] = []
const matches = text.match(URL_PATTERN)
if (!matches) return result
for (const raw of matches) {
const cleaned = raw.replace(TRAILING_PUNCTUATION, '')
if (!cleaned || seen.has(cleaned)) continue
// Validate it's a real, well-formed URL before surfacing it.
try {
const u = new URL(cleaned)
if (u.protocol !== 'http:' && u.protocol !== 'https:') continue
} catch {
continue
}
seen.add(cleaned)
result.push(cleaned)
if (result.length >= limit) break
}
return result
}