(code: string, id: string, port: number)
| 10 | } |
| 11 | |
| 12 | export function enhanceConsoleLog(code: string, id: string, port: number) { |
| 13 | const filePath = id.split('?')[0]! |
| 14 | const location = filePath.replace(normalizePath(process.cwd()), '') |
| 15 | |
| 16 | try { |
| 17 | const result = parseSync(filePath, code, { |
| 18 | sourceType: 'module', |
| 19 | lang: 'tsx', |
| 20 | }) |
| 21 | if (result.errors.length > 0) return |
| 22 | |
| 23 | const offsetToLoc = createLocMapper(code) |
| 24 | const s = new MagicString(code) |
| 25 | |
| 26 | walk(result.program, (node) => { |
| 27 | if (node.type !== 'CallExpression') return |
| 28 | |
| 29 | const callee = node.callee |
| 30 | if ( |
| 31 | callee.type === 'MemberExpression' && |
| 32 | !callee.computed && |
| 33 | callee.object.type === 'Identifier' && |
| 34 | callee.object.name === 'console' && |
| 35 | callee.property.type === 'Identifier' && |
| 36 | (callee.property.name === 'log' || callee.property.name === 'error') |
| 37 | ) { |
| 38 | const loc = offsetToLoc(node.start) |
| 39 | const [lineNumber, column] = [loc.line, loc.column] |
| 40 | const finalPath = `${location}:${lineNumber}:${column + 1}` |
| 41 | const logMessage = `${chalk.magenta('LOG')} ${chalk.blueBright(`${finalPath}`)}\n → ` |
| 42 | |
| 43 | const serverLogMessage = `["${escapeForStringLiteral(logMessage)}"]` |
| 44 | const browserLogMessage = `["%c${'LOG'}%c %c${`Go to Source: http://localhost:${port}/__tsd/open-source?source=${encodeURIComponent(finalPath)}`}%c \\n \\u2192 ","color:#A0A","color:#FFF","color:#55F","color:#FFF"]` |
| 45 | |
| 46 | const spreadStr = `...(typeof window === "undefined" ? ${serverLogMessage} : ${browserLogMessage}), ` |
| 47 | |
| 48 | // Find the opening '(' of the call by scanning forward from callee end |
| 49 | let parenOffset = callee.end |
| 50 | while (parenOffset < code.length && code[parenOffset] !== '(') { |
| 51 | parenOffset++ |
| 52 | } |
| 53 | // Insert right after '(' |
| 54 | s.appendRight(parenOffset + 1, spreadStr) |
| 55 | } |
| 56 | }) |
| 57 | |
| 58 | if (!s.hasChanged()) return |
| 59 | |
| 60 | return { |
| 61 | code: s.toString(), |
| 62 | map: s.generateMap({ |
| 63 | source: filePath, |
| 64 | file: id, |
| 65 | includeContent: true, |
| 66 | }), |
| 67 | } |
| 68 | } catch (e) { |
| 69 | return |
no test coverage detected