-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
common.ts
336 lines (310 loc) · 8.45 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import type { AttributeToken, TagToken, Token } from 'pug-lexer';
import type { Logger } from '../logger';
import type { PugFramework } from '../options/pug-framework';
/**
* Returns the previous tag token if there was one.
*
* @param tokens The token array.
* @param index The current index within the token array..
* @returns Previous tag token if there was one.
*/
export function previousTagToken(
tokens: ReadonlyArray<Token>,
index: number,
): TagToken | undefined {
for (let i: number = index - 1; i >= 0; i--) {
const token: Token | undefined = tokens[i];
if (!token) {
return;
}
if (token.type === 'tag') {
return token;
}
}
return;
}
/**
* Returns the previous attribute token between the current token and the last occurrence of a `start-attributes` token.
*
* @param tokens A reference to the whole token array.
* @param index The current index on which the cursor is in the token array.
* @returns Previous attribute token if there was one.
*/
export function previousNormalAttributeToken(
tokens: ReadonlyArray<Token>,
index: number,
): AttributeToken | undefined {
for (let i: number = index - 1; i > 0; i--) {
const token: Token | undefined = tokens[i];
if (!token || token.type === 'start-attributes') {
return;
}
if (
token.type === 'attribute' &&
token.name !== 'class' &&
token.name !== 'id'
) {
return token;
}
}
return;
}
/**
* Returns the previous type attribute token or undefined if no attribute is present.
*
* @param tokens A reference to the whole token array.
* @param index The current index on which the cursor is in the token array.
* @returns Previous attribute token if there was one.
*/
export function previousTypeAttributeToken(
tokens: ReadonlyArray<Token>,
index: number,
): AttributeToken | undefined {
for (let i: number = index - 1; i > 0; i--) {
const token: Token | undefined = tokens[i];
if (!token || token.type === 'start-attributes' || token.type === 'tag') {
return;
}
if (token.type === 'attribute' && token.name === 'type') {
return token;
}
}
return;
}
/**
* Unwraps line feeds from a given value.
*
* @param value The value to unwrap.
* @returns The unwrapped result.
*/
export function unwrapLineFeeds(value: string): string {
return value.includes('\n')
? value
.split('\n')
.map((part) => part.trim())
.map((part) => (part[0] === '.' ? '' : ' ') + part)
.join('')
.trim()
: value;
}
/**
* Indicates whether the attribute is a `style` normal attribute.
*
* ---
*
* Example style tag:
* ```
* span(style="color: red")
* ```
*
* In this case `name` is `style` and `val` is `"color: red"`.
*
* ---
*
* @param name Name of tag attribute.
* @param val Value of `style` tag attribute.
* @returns Whether it's a style attribute that is quoted or not.
*/
export function isStyleAttribute(name: string, val: string): boolean {
return name === 'style' && isQuoted(val);
}
/**
* Indicates whether the value is surrounded by the `start` and `end` parameters.
*
* @param val Value of a tag attribute.
* @param start The left hand side of the wrapping.
* @param end The right hand side of the wrapping.
* @param offset The offset from left and right where to search from.
* @returns Whether the value is wrapped with start and end from the offset or not.
*/
export function isWrappedWith(
val: string,
start: string,
end: string,
offset: number = 0,
): boolean {
return (
val.startsWith(start, offset) && val.endsWith(end, val.length - offset)
);
}
/**
* Indicates whether the value is surrounded by quotes.
*
* ---
*
* Example with double quotes:
* ```
* a(href="#")
* ```
*
* In this case `val` is `"#"`.
*
* ---
*
* Example with single quotes:
* ```
* a(href='#')
* ```
*
* In this case `val` is `'#'`.
*
* ---
*
* Example with no quotes:
* ```
* - const route = '#';
* a(href=route)
* ```
*
* In this case `val` is `route`.
*
* ---
*
* Special cases:
* ```
* a(href='/' + '#')
* a(href="/" + "#")
* ```
*
* These cases should not be treated as quoted.
*
* ---
*
* @param val Value of tag attribute.
* @returns Whether the value is quoted or not.
*/
export function isQuoted(val: string): boolean {
if (/^(["'`])(.*)\1$/.test(val)) {
// Regex for checking if there are any unescaped quotations.
const regex: RegExp = new RegExp(`${val[0]}(?<!\\\\${val[0]})`);
return !regex.test(val.slice(1, -1));
}
return false;
}
/**
* Detects whether the given value is a single line interpolation or not.
*
* @param val The value to check.
* @returns `true` if it's a single line interpolation, otherwise `false`.
*/
export function isSingleLineWithInterpolation(val: string): boolean {
return /^`[\S\s]*`$/.test(val) && val.includes('${');
}
/**
* Detects whether the given value is a multiline interpolation or not.
*
* @param val The value to check.
* @returns `true` if it's a multiline interpolation, otherwise `false`.
*/
export function isMultilineInterpolation(val: string): boolean {
return /^`[\S\s]*`$/m.test(val) && val.includes('\n');
}
/**
* Encloses code in brackets and possibly spaces.
*
* @param bracketSpacing Specifies whether or not to insert spaces before and after the code.
* @param code Code that is enclosed in brackets.
* @param param2 Brackets.
* @param param2."0" Opening brackets.
* @param param2."1" Closing brackets.
* @returns The handled string.
*/
export function handleBracketSpacing(
bracketSpacing: boolean,
code: string,
[opening, closing] = ['{{', '}}'],
): string {
return bracketSpacing
? `${opening} ${code} ${closing}`
: `${opening}${code}${closing}`;
}
/**
* Bakes a string.
*
* @param rawContent The raw string.
* @param enclosingQuote Enclosing quote.
* @param unescapeUnnecessaryEscapes Whether to unescape unnecessary escapes or not. Default: `false`.
* @returns The baked string.
* @see [copied from Prettier common util](https://github.com/prettier/prettier/blob/master/src/common/util.js#L647)
*/
export function makeString(
rawContent: string,
enclosingQuote: "'" | '"',
unescapeUnnecessaryEscapes: boolean = false,
): string {
const otherQuote: "'" | '"' = enclosingQuote === '"' ? "'" : '"';
const newContent: string = rawContent.replaceAll(
/\\([\S\s])|(["'])/g,
(match, escaped: "'" | '"', quote: "'" | '"') => {
if (escaped === otherQuote) {
return escaped;
}
if (quote === enclosingQuote) {
return `\\${quote}`;
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (quote) {
return quote;
}
return unescapeUnnecessaryEscapes &&
/^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped)
? escaped
: `\\${escaped}`;
},
);
return enclosingQuote + newContent + enclosingQuote;
}
/**
* See [issue #9](https://github.com/prettier/plugin-pug/issues/9) for more details.
*
* @param code Code that is checked.
* @param quotes Quotes.
* @param otherQuotes Opposite of quotes.
* @param logger A logger.
* @returns Whether dangerous quote combinations where detected or not.
*/
export function detectDangerousQuoteCombination(
code: string,
quotes: "'" | '"',
otherQuotes: "'" | '"',
logger: Logger,
): boolean {
// Index of primary quote
const q1: number = code.indexOf(quotes);
// Index of secondary (other) quote
const q2: number = code.indexOf(otherQuotes);
// Index of backtick
const qb: number = code.indexOf('`');
// eslint-disable-next-line unicorn/consistent-existence-index-check
if (q1 >= 0 && q2 >= 0 && q2 > q1 && (qb < 0 || q1 < qb)) {
logger.log({ code, quotes, otherQuotes, q1, q2, qb });
return true;
}
return false;
}
/**
* Try to detect used framework within the project by reading `process.env.npm_package_*`.
*
* @returns PugFramework.
*/
export function detectFramework(): PugFramework {
try {
const npmPackages: string[] = Object.keys(process.env)
.filter((key) => key.startsWith('npm_package_'))
.filter((key) => /(dev)?[Dd]ependencies_+/.test(key));
if (
npmPackages.some(
(pack) => pack.includes('vue') && !pack.includes('vuepress'),
)
) {
return 'vue';
} else if (npmPackages.some((pack) => pack.includes('svelte'))) {
return 'svelte';
} else if (npmPackages.some((pack) => pack.includes('angular'))) {
return 'angular';
}
} catch {
return 'auto';
}
return 'auto';
}