Debian Codegraph @

packages/babel-highlight/src/index.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /// <reference path="../../../lib/third-party-libs.d.ts" />
2
3 import type { Token as JSToken, JSXToken } from "js-tokens";
4 import jsTokens from "js-tokens";
5
6 import {
7 isStrictReservedWord,
8 isKeyword,
9 } from "@babel/helper-validator-identifier";
10 import Chalk from "chalk";
11
12 type ChalkClass = ReturnType<typeof getChalk>;
13
14 /**
15 * Names that are always allowed as identifiers, but also appear as keywords
16 * within certain syntactic productions.
17 *
18 * https://tc39.es/ecma262/#sec-keywords-and-reserved-words
19 *
20 * `target` has been omitted since it is very likely going to be a false
21 * positive.
22 */
23 const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
24
25 type InternalTokenType =
26 | "keyword"
27 | "capitalized"
28 | "jsxIdentifier"
29 | "punctuator"
30 | "number"
31 | "string"
32 | "regex"
33 | "comment"
34 | "invalid";
35
36 type Token = {
37 type: InternalTokenType | "uncolored";
38 value: string;
39 };
40 /**
41 * Chalk styles for token types.
42 */
43 function getDefs(chalk: ChalkClass): Record<InternalTokenType, ChalkClass> {
44 return {
45 keyword: chalk.cyan,
46 capitalized: chalk.yellow,
47 jsxIdentifier: chalk.yellow,
48 punctuator: chalk.yellow,
49 number: chalk.magenta,
50 string: chalk.green,
51 regex: chalk.magenta,
52 comment: chalk.grey,
53 invalid: chalk.white.bgRed.bold,
54 };
55 }
56
57 /**
58 * RegExp to test for newlines in terminal.
59 */
60 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
61
62 /**
63 * RegExp to test for the three types of brackets.
64 */
65 const BRACKET = /^[()[\]{}]$/;
66
67 let tokenize: (
68 text: string,
69 ) => Generator<{ type: InternalTokenType | "uncolored"; value: string }>;
70
71 if (process.env.BABEL_8_BREAKING) {
72 /**
73 * Get the type of token, specifying punctuator type.
74 */
75 const getTokenType = function (
76 token: JSToken | JSXToken,
77 ): InternalTokenType | "uncolored" {
78 if (token.type === "IdentifierName") {
79 if (
80 isKeyword(token.value) ||
81 isStrictReservedWord(token.value, true) ||
82 sometimesKeywords.has(token.value)
83 ) {
84 return "keyword";
85 }
86
87 if (token.value[0] !== token.value[0].toLowerCase()) {
88 return "capitalized";
89 }
90 }
91
92 if (token.type === "Punctuator" && BRACKET.test(token.value)) {
93 return "uncolored";
94 }
95
96 if (token.type === "Invalid" && token.value === "@") {
97 return "punctuator";
98 }
99
100 switch (token.type) {
101 case "NumericLiteral":
102 return "number";
103
104 case "StringLiteral":
105 case "JSXString":
106 case "NoSubstitutionTemplate":
107 return "string";
108
109 case "RegularExpressionLiteral":
110 return "regex";
111
112 case "Punctuator":
113 case "JSXPunctuator":
114 return "punctuator";
115
116 case "MultiLineComment":
117 case "SingleLineComment":
118 return "comment";
119
120 case "Invalid":
121 case "JSXInvalid":
122 return "invalid";
123
124 case "JSXIdentifier":
125 return "jsxIdentifier";
126
127 default:
128 return "uncolored";
129 }
130 };
131
132 /**
133 * Turn a string of JS into an array of objects.
134 */
135 tokenize = function* (text: string): Generator<Token> {
136 for (const token of jsTokens(text, { jsx: true })) {
137 switch (token.type) {
138 case "TemplateHead":
139 yield { type: "string", value: token.value.slice(0, -2) };
140 yield { type: "punctuator", value: "${" };
141 break;
142
143 case "TemplateMiddle":
144 yield { type: "punctuator", value: "}" };
145 yield { type: "string", value: token.value.slice(1, -2) };
146 yield { type: "punctuator", value: "${" };
147 break;
148
149 case "TemplateTail":
150 yield { type: "punctuator", value: "}" };
151 yield { type: "string", value: token.value.slice(1) };
152 break;
153
154 default:
155 yield {
156 type: getTokenType(token),
157 value: token.value,
158 };
159 }
160 }
161 };
162 } else {
163 /**
164 * RegExp to test for what seems to be a JSX tag name.
165 */
166 const JSX_TAG = /^[a-z][\w-]*$/i;
167
168 // The token here is defined in js-tokens@4. However we don't bother
169 // typing it since the whole block will be removed in Babel 8
170 const getTokenType = function (token: any, offset: number, text: string) {
171 if (token.type === "name") {
172 if (
173 isKeyword(token.value) ||
174 isStrictReservedWord(token.value, true) ||
175 sometimesKeywords.has(token.value)
176 ) {
177 return "keyword";
178 }
179
180 if (
181 JSX_TAG.test(token.value) &&
182 (text[offset - 1] === "<" || text.slice(offset - 2, offset) == "</")
183 ) {
184 return "jsxIdentifier";
185 }
186
187 if (token.value[0] !== token.value[0].toLowerCase()) {
188 return "capitalized";
189 }
190 }
191
192 if (token.type === "punctuator" && BRACKET.test(token.value)) {
193 return "bracket";
194 }
195
196 if (
197 token.type === "invalid" &&
198 (token.value === "@" || token.value === "#")
199 ) {
200 return "punctuator";
201 }
202
203 return token.type;
204 };
205
206 tokenize = function* (text: string) {
207 let match;
208 while ((match = (jsTokens as any).default.exec(text))) {
209 const token = (jsTokens as any).matchToToken(match);
210
211 yield {
212 type: getTokenType(token, match.index, text),
213 value: token.value,
214 };
215 }
216 };
217 }
218
219 /**
220 * Highlight `text` using the token definitions in `defs`.
221 */
222 function highlightTokens(defs: Record<string, ChalkClass>, text: string) {
223 let highlighted = "";
224
225 for (const { type, value } of tokenize(text)) {
226 const colorize = defs[type];
227 if (colorize) {
228 highlighted += value
229 .split(NEWLINE)
230 .map(str => colorize(str))
231 .join("\n");
232 } else {
233 highlighted += value;
234 }
235 }
236
237 return highlighted;
238 }
239
240 /**
241 * Highlight `text` using the token definitions in `defs`.
242 */
243
244 type Options = {
245 forceColor?: boolean;
246 };
247
248 /**
249 * Whether the code should be highlighted given the passed options.
250 */
251 export function shouldHighlight(options: Options): boolean {
252 return !!Chalk.supportsColor || options.forceColor;
253 }
254
255 /**
256 * The Chalk instance that should be used given the passed options.
257 */
258 export function getChalk(options: Options) {
259 return options.forceColor
260 ? new Chalk.constructor({ enabled: true, level: 1 })
261 : Chalk;
262 }
263
264 /**
265 * Highlight `code`.
266 */
267 export default function highlight(code: string, options: Options = {}): string {
268 if (code !== "" && shouldHighlight(options)) {
269 const chalk = getChalk(options);
270 const defs = getDefs(chalk);
271 return highlightTokens(defs, code);
272 } else {
273 return code;
274 }
275 }