/** * @module metatext-helpers * * Helper functions for target URL parsing, markdown link extraction, * and Ahead-Of-Time (AOT) index (`index/targets.json`) management. */ import { IBGIB_SPACE_URL_PREFIX } from './metatext-constants.mjs'; import { ParsedTargetUrl, TargetAnchorRecord, TargetsIndexData, } from './metatext-types.mjs'; /** * Parses line range anchor from a URL hash (e.g. '#L12-L24', '#L12-24', '#L15'). */ export function parseLineRangeAnchor(hashOrAnchor?: string): [number, number] | undefined { if (!hashOrAnchor) { return undefined; } const clean = hashOrAnchor.replace(/^#/, '').trim(); if (!clean) { return undefined; } // Match #L12-L24 or #L12-24 const rangeMatch = clean.match(/^L?(\d+)\s*[-:]\s*L?(\d+)$/i); if (rangeMatch) { const start = parseInt(rangeMatch[1], 10); const end = parseInt(rangeMatch[2], 10); if (!isNaN(start) && !isNaN(end) && start > 0 && end >= start) { return [start, end]; } } // Match single line #L12 or #12 const singleMatch = clean.match(/^L?(\d+)$/i); if (singleMatch) { const line = parseInt(singleMatch[1], 10); if (!isNaN(line) && line > 0) { return [line, line]; } } return undefined; } /** * Parses an ibgib URL into its constituent cosmos, galaxy, branch, file path, and line range components. * Supports both https://ibgib.space/... URLs and ibgib://... protocol URIs. * * @example * parseTargetUrl('https://ibgib.space/@bill/cosmos-1/code-1/main/src/index.mts#L12-L24') * // returns { * // rawUrl: '...', * // userHandle: 'bill', * // cosmosName: 'cosmos-1', * // galaxyName: 'code-1', * // branchName: 'main', * // filePath: 'src/index.mts', * // lineRange: [12, 24], * // targetKey: 'code-1/src/index.mts' * // } */ export function parseTargetUrl(url: string): ParsedTargetUrl | undefined { if (!url || typeof url !== 'string') { return undefined; } const trimmed = url.trim(); let pathname = ''; let hash = ''; if (trimmed.startsWith(IBGIB_SPACE_URL_PREFIX)) { try { const parsed = new URL(trimmed); pathname = parsed.pathname.replace(/^\/+/, ''); hash = parsed.hash; } catch { return undefined; } } else if (trimmed.startsWith('ibgib://')) { const sansProtocol = trimmed.slice('ibgib://'.length); const hashIdx = sansProtocol.indexOf('#'); if (hashIdx >= 0) { pathname = sansProtocol.slice(0, hashIdx).replace(/^\/+/, ''); hash = sansProtocol.slice(hashIdx); } else { pathname = sansProtocol.replace(/^\/+/, ''); } } else { return undefined; } if (!pathname) { return undefined; } const segments = pathname.split('/').filter(Boolean); if (segments.length === 0) { return undefined; } let userHandle: string | undefined; let cosmosName: string | undefined; let galaxyName: string | undefined; let branchName: string | undefined; let filePathSegments: string[] = []; let currentIdx = 0; // Optional user handle segment: '@bill' if (segments[currentIdx]?.startsWith('@')) { userHandle = segments[currentIdx].slice(1); currentIdx++; } const remaining = segments.slice(currentIdx); if (remaining.length === 0) { return undefined; } // Check if the first segment is directly a galaxy identifier (e.g. 'code-1', 'metatext-1') const isFirstSegmentGalaxy = /^(code|metatext|notes|curriculum|telemetry)(-\w+)?$/i.test(remaining[0]); if (isFirstSegmentGalaxy) { galaxyName = remaining[0]; if (remaining.length >= 3) { branchName = remaining[1]; filePathSegments = remaining.slice(2); } else if (remaining.length === 2) { filePathSegments = remaining.slice(1); } else { filePathSegments = []; } } else if (remaining.length >= 4) { // Full route: cosmosName / galaxyName / branchName / path/to/file cosmosName = remaining[0]; galaxyName = remaining[1]; branchName = remaining[2]; filePathSegments = remaining.slice(3); } else if (remaining.length === 3) { // galaxyName / branchName / path/to/file galaxyName = remaining[0]; branchName = remaining[1]; filePathSegments = remaining.slice(2); } else if (remaining.length === 2) { // galaxyName / file galaxyName = remaining[0]; filePathSegments = remaining.slice(1); } else { filePathSegments = remaining; } const filePath = filePathSegments.join('/'); if (!filePath) { return undefined; } const isCommit = filePathSegments[0] === 'commit'; const commitGib = isCommit ? filePathSegments[1] : undefined; const lineRange = parseLineRangeAnchor(hash); const resolvedGalaxy = galaxyName || 'code-1'; const targetKey = `${resolvedGalaxy}/${filePath}`; return { rawUrl: trimmed, userHandle, cosmosName, galaxyName: resolvedGalaxy, branchName, filePath, lineRange, targetKey, isCommit, commitGib, }; } /** * Extracts all valid code target URLs embedded in Markdown text (both [text](url) and bare URLs). */ export function extractTargetUrlsFromMarkdown(markdownText: string): ParsedTargetUrl[] { if (!markdownText || typeof markdownText !== 'string') { return []; } const results: ParsedTargetUrl[] = []; const seenKeys = new Set(); // 1. Match Markdown link targets: [label](url) const mdLinkRegex = /\[[^\]]*\]\((https:\/\/ibgib\.space\/[^\s\)]+|ibgib:\/\/[^\s\)]+)\)/g; let match: RegExpExecArray | null; while ((match = mdLinkRegex.exec(markdownText)) !== null) { const rawUrl = match[1]; const parsed = parseTargetUrl(rawUrl); if (parsed) { const dedupeKey = `${parsed.targetKey}:${parsed.lineRange ? parsed.lineRange.join('-') : 'none'}`; if (!seenKeys.has(dedupeKey)) { seenKeys.add(dedupeKey); results.push(parsed); } } } // 2. Match bare URLs not already captured const bareUrlRegex = /(https:\/\/ibgib\.space\/[^\s\)]+|ibgib:\/\/[^\s\)]+)/g; while ((match = bareUrlRegex.exec(markdownText)) !== null) { const rawUrl = match[1]; const parsed = parseTargetUrl(rawUrl); if (parsed) { const dedupeKey = `${parsed.targetKey}:${parsed.lineRange ? parsed.lineRange.join('-') : 'none'}`; if (!seenKeys.has(dedupeKey)) { seenKeys.add(dedupeKey); results.push(parsed); } } } return results; } /** * Updates a TargetsIndexData object with target anchors parsed from a new or updated comment file. */ export function updateTargetsIndexData({ currentIndex, targetUrls, commentFilePath, author, authorKeystoneTjp, timestamp, }: { currentIndex?: TargetsIndexData | null; targetUrls: ParsedTargetUrl[]; commentFilePath: string; author?: string; authorKeystoneTjp?: string; timestamp?: string; }): TargetsIndexData { const updated: TargetsIndexData = { targets: { ...(currentIndex?.targets || {}) }, }; const recordTimestamp = timestamp || new Date().toISOString(); for (const target of targetUrls) { const key = target.targetKey; const existingList = updated.targets[key] ? [...updated.targets[key]] : []; // Check if a record already exists for this exact comment file and line range const lineRangeKey = target.lineRange ? target.lineRange.join('-') : 'none'; const existingIdx = existingList.findIndex(r => r.filePath === commentFilePath && (r.lineRange ? r.lineRange.join('-') : 'none') === lineRangeKey ); const newRecord: TargetAnchorRecord = { filePath: commentFilePath, ...(target.lineRange ? { lineRange: target.lineRange } : {}), ...(author ? { author } : {}), ...(authorKeystoneTjp ? { authorKeystoneTjp } : {}), timestamp: recordTimestamp, }; if (existingIdx >= 0) { existingList[existingIdx] = newRecord; } else { existingList.push(newRecord); } updated.targets[key] = existingList; } return updated; } /** * Retrieves all target anchor records associated with a specific file in a galaxy. * Performs fast O(1) dictionary lookup. */ export function getTargetAnchorsForFile({ indexData, filePath, galaxyName = 'code-1', }: { indexData?: TargetsIndexData | null; filePath: string; galaxyName?: string; }): TargetAnchorRecord[] { if (!indexData?.targets || !filePath) { return []; } const cleanPath = filePath.replace(/^\/+/, ''); const canonicalKey = `${galaxyName}/${cleanPath}`; // Check canonical key first if (indexData.targets[canonicalKey]) { return indexData.targets[canonicalKey]; } // Fall back to bare filePath key if present if (indexData.targets[cleanPath]) { return indexData.targets[cleanPath]; } return []; } /** * Serializes TargetsIndexData to formatted JSON string. */ export function serializeTargetsIndex(indexData: TargetsIndexData): string { return JSON.stringify(indexData, null, 2); } /** * Safely deserializes a JSON string into a TargetsIndexData object. */ export function deserializeTargetsIndex(jsonString: string): TargetsIndexData { try { if (!jsonString || typeof jsonString !== 'string') { return { targets: {} }; } const parsed = JSON.parse(jsonString); if (parsed && typeof parsed === 'object' && parsed.targets && typeof parsed.targets === 'object') { return parsed as TargetsIndexData; } return { targets: {} }; } catch { return { targets: {} }; } }