(expr: string, fromFile: string, context: ResolutionContext)
| 332 | * that is a whole segment stays a hole. Null for anything else. |
| 333 | */ |
| 334 | export function configHrefExpression(expr: string, fromFile: string, context: ResolutionContext): string | null { |
| 335 | const m = /^\s*([A-Za-z_$][\w$]*)((?:\s*\??\.\s*[A-Za-z_$][\w$]*)+)\s*(\((?:[^()]|\([^()]*\))*\))?\s*$/.exec(expr); |
| 336 | if (!m) return null; |
| 337 | const root = m[1]!; |
| 338 | const keys = m[2]!.split('.').map((k) => k.replace(/[?\s]/g, '')).filter(Boolean); |
| 339 | let file = fromFile; |
| 340 | let name = root; |
| 341 | const mapping = context.getImportMappings(fromFile, 'tsx').find((x) => x.localName === root) ?? |
| 342 | context.getImportMappings(fromFile, 'typescript').find((x) => x.localName === root); |
| 343 | if (mapping) { |
| 344 | const resolved = resolveImportPath(mapping.source, fromFile, 'typescript', context); |
| 345 | if (!resolved) return null; |
| 346 | file = resolved; |
| 347 | if (mapping.exportedName && mapping.exportedName !== 'default' && mapping.exportedName !== '*') name = mapping.exportedName; |
| 348 | } |
| 349 | const decl = context.getNodesInFile(file).find((n) => n.name === name && (n.kind === 'constant' || n.kind === 'variable')); |
| 350 | if (!decl) return null; |
| 351 | const lines = context.readFile(file)?.split('\n') ?? []; |
| 352 | const text = lines.slice(decl.startLine - 1, decl.endLine).join('\n'); |
| 353 | const open = text.indexOf('{', Math.max(0, text.search(new RegExp(`\\b${escapeRegExp(name)}\\b`)))); |
| 354 | if (open < 0) return null; |
| 355 | let value = readObjectValue(text, open, keys); |
| 356 | if (value === null) return null; |
| 357 | // A function's value is what it returns: `(id: string) => \`/app/…\``, `() => { return '/'; }`. |
| 358 | if (m[3] !== undefined) { |
| 359 | const body = /^(?:async\s+)?(?:\([^()]*(?:\([^()]*\)[^()]*)*\)|[A-Za-z_$][\w$]*)\s*(?::\s*[^=]+?)?=>\s*/.exec(value); |
| 360 | if (!body) return null; |
| 361 | value = value.slice(body[0].length).trim(); |
| 362 | if (value.startsWith('{')) value = /\breturn\s+([`'"][\s\S]*?[`'"])\s*;?\s*}/.exec(value)?.[1] ?? ''; |
| 363 | } |
| 364 | if (!/^[`'"]/.test(value)) return null; |
| 365 | // `/auth/login${redirectTo ? … : ''}`: a hole glued to a segment is a suffix, not a segment. |
| 366 | return value.startsWith('`') ? dropGluedTemplateHoles(value) : value; |
| 367 | } |
| 368 | |
| 369 | /** Remove each `${…}` of a template literal that is not a whole path segment. */ |
| 370 | function dropGluedTemplateHoles(template: string): string { |
no test coverage detected