key-spacing.js
26 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/**
* @fileoverview Rule to specify spacing of object literal keys and values
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const GraphemeSplitter = require("grapheme-splitter");
const splitter = new GraphemeSplitter();
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether a string contains a line terminator as defined in
* http://www.ecma-international.org/ecma-262/5.1/#sec-7.3
* @param {string} str String to test.
* @returns {boolean} True if str contains a line terminator.
*/
function containsLineTerminator(str) {
return astUtils.LINEBREAK_MATCHER.test(str);
}
/**
* Gets the last element of an array.
* @param {Array} arr An array.
* @returns {any} Last element of arr.
*/
function last(arr) {
return arr[arr.length - 1];
}
/**
* Checks whether a node is contained on a single line.
* @param {ASTNode} node AST Node being evaluated.
* @returns {boolean} True if the node is a single line.
*/
function isSingleLine(node) {
return (node.loc.end.line === node.loc.start.line);
}
/**
* Checks whether the properties on a single line.
* @param {ASTNode[]} properties List of Property AST nodes.
* @returns {boolean} True if all properties is on a single line.
*/
function isSingleLineProperties(properties) {
const [firstProp] = properties,
lastProp = last(properties);
return firstProp.loc.start.line === lastProp.loc.end.line;
}
/**
* Initializes a single option property from the configuration with defaults for undefined values
* @param {Object} toOptions Object to be initialized
* @param {Object} fromOptions Object to be initialized from
* @returns {Object} The object with correctly initialized options and values
*/
function initOptionProperty(toOptions, fromOptions) {
toOptions.mode = fromOptions.mode || "strict";
// Set value of beforeColon
if (typeof fromOptions.beforeColon !== "undefined") {
toOptions.beforeColon = +fromOptions.beforeColon;
} else {
toOptions.beforeColon = 0;
}
// Set value of afterColon
if (typeof fromOptions.afterColon !== "undefined") {
toOptions.afterColon = +fromOptions.afterColon;
} else {
toOptions.afterColon = 1;
}
// Set align if exists
if (typeof fromOptions.align !== "undefined") {
if (typeof fromOptions.align === "object") {
toOptions.align = fromOptions.align;
} else { // "string"
toOptions.align = {
on: fromOptions.align,
mode: toOptions.mode,
beforeColon: toOptions.beforeColon,
afterColon: toOptions.afterColon
};
}
}
return toOptions;
}
/**
* Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values
* @param {Object} toOptions Object to be initialized
* @param {Object} fromOptions Object to be initialized from
* @returns {Object} The object with correctly initialized options and values
*/
function initOptions(toOptions, fromOptions) {
if (typeof fromOptions.align === "object") {
// Initialize the alignment configuration
toOptions.align = initOptionProperty({}, fromOptions.align);
toOptions.align.on = fromOptions.align.on || "colon";
toOptions.align.mode = fromOptions.align.mode || "strict";
toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
} else { // string or undefined
toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions));
toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions));
// If alignment options are defined in multiLine, pull them out into the general align configuration
if (toOptions.multiLine.align) {
toOptions.align = {
on: toOptions.multiLine.align.on,
mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode,
beforeColon: toOptions.multiLine.align.beforeColon,
afterColon: toOptions.multiLine.align.afterColon
};
}
}
return toOptions;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "layout",
docs: {
description: "Enforce consistent spacing between keys and values in object literal properties",
recommended: false,
url: "https://eslint.org/docs/rules/key-spacing"
},
fixable: "whitespace",
schema: [{
anyOf: [
{
type: "object",
properties: {
align: {
anyOf: [
{
enum: ["colon", "value"]
},
{
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
on: {
enum: ["colon", "value"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
}
]
},
mode: {
enum: ["strict", "minimum"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
},
{
type: "object",
properties: {
singleLine: {
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
},
multiLine: {
type: "object",
properties: {
align: {
anyOf: [
{
enum: ["colon", "value"]
},
{
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
on: {
enum: ["colon", "value"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
}
]
},
mode: {
enum: ["strict", "minimum"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
}
},
additionalProperties: false
},
{
type: "object",
properties: {
singleLine: {
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
},
multiLine: {
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
},
align: {
type: "object",
properties: {
mode: {
enum: ["strict", "minimum"]
},
on: {
enum: ["colon", "value"]
},
beforeColon: {
type: "boolean"
},
afterColon: {
type: "boolean"
}
},
additionalProperties: false
}
},
additionalProperties: false
}
]
}],
messages: {
extraKey: "Extra space after {{computed}}key '{{key}}'.",
extraValue: "Extra space before value for {{computed}}key '{{key}}'.",
missingKey: "Missing space after {{computed}}key '{{key}}'.",
missingValue: "Missing space before value for {{computed}}key '{{key}}'."
}
},
create(context) {
/**
* OPTIONS
* "key-spacing": [2, {
* beforeColon: false,
* afterColon: true,
* align: "colon" // Optional, or "value"
* }
*/
const options = context.options[0] || {},
ruleOptions = initOptions({}, options),
multiLineOptions = ruleOptions.multiLine,
singleLineOptions = ruleOptions.singleLine,
alignmentOptions = ruleOptions.align || null;
const sourceCode = context.getSourceCode();
/**
* Checks whether a property is a member of the property group it follows.
* @param {ASTNode} lastMember The last Property known to be in the group.
* @param {ASTNode} candidate The next Property that might be in the group.
* @returns {boolean} True if the candidate property is part of the group.
*/
function continuesPropertyGroup(lastMember, candidate) {
const groupEndLine = lastMember.loc.start.line,
candidateStartLine = candidate.loc.start.line;
if (candidateStartLine - groupEndLine <= 1) {
return true;
}
/*
* Check that the first comment is adjacent to the end of the group, the
* last comment is adjacent to the candidate property, and that successive
* comments are adjacent to each other.
*/
const leadingComments = sourceCode.getCommentsBefore(candidate);
if (
leadingComments.length &&
leadingComments[0].loc.start.line - groupEndLine <= 1 &&
candidateStartLine - last(leadingComments).loc.end.line <= 1
) {
for (let i = 1; i < leadingComments.length; i++) {
if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) {
return false;
}
}
return true;
}
return false;
}
/**
* Determines if the given property is key-value property.
* @param {ASTNode} property Property node to check.
* @returns {boolean} Whether the property is a key-value property.
*/
function isKeyValueProperty(property) {
return !(
(property.method ||
property.shorthand ||
property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement"
);
}
/**
* Starting from the given a node (a property.key node here) looks forward
* until it finds the last token before a colon punctuator and returns it.
* @param {ASTNode} node The node to start looking from.
* @returns {ASTNode} The last token before a colon punctuator.
*/
function getLastTokenBeforeColon(node) {
const colonToken = sourceCode.getTokenAfter(node, astUtils.isColonToken);
return sourceCode.getTokenBefore(colonToken);
}
/**
* Starting from the given a node (a property.key node here) looks forward
* until it finds the colon punctuator and returns it.
* @param {ASTNode} node The node to start looking from.
* @returns {ASTNode} The colon punctuator.
*/
function getNextColon(node) {
return sourceCode.getTokenAfter(node, astUtils.isColonToken);
}
/**
* Gets an object literal property's key as the identifier name or string value.
* @param {ASTNode} property Property node whose key to retrieve.
* @returns {string} The property's key.
*/
function getKey(property) {
const key = property.key;
if (property.computed) {
return sourceCode.getText().slice(key.range[0], key.range[1]);
}
return astUtils.getStaticPropertyName(property);
}
/**
* Reports an appropriately-formatted error if spacing is incorrect on one
* side of the colon.
* @param {ASTNode} property Key-value pair in an object literal.
* @param {string} side Side being verified - either "key" or "value".
* @param {string} whitespace Actual whitespace string.
* @param {int} expected Expected whitespace length.
* @param {string} mode Value of the mode as "strict" or "minimum"
* @returns {void}
*/
function report(property, side, whitespace, expected, mode) {
const diff = whitespace.length - expected;
if ((
diff && mode === "strict" ||
diff < 0 && mode === "minimum" ||
diff > 0 && !expected && mode === "minimum") &&
!(expected && containsLineTerminator(whitespace))
) {
const nextColon = getNextColon(property.key),
tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }),
tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }),
isKeySide = side === "key",
isExtra = diff > 0,
diffAbs = Math.abs(diff),
spaces = Array(diffAbs + 1).join(" ");
const locStart = isKeySide ? tokenBeforeColon.loc.end : nextColon.loc.start;
const locEnd = isKeySide ? nextColon.loc.start : tokenAfterColon.loc.start;
const missingLoc = isKeySide ? tokenBeforeColon.loc : tokenAfterColon.loc;
const loc = isExtra ? { start: locStart, end: locEnd } : missingLoc;
let fix;
if (isExtra) {
let range;
// Remove whitespace
if (isKeySide) {
range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs];
} else {
range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]];
}
fix = function(fixer) {
return fixer.removeRange(range);
};
} else {
// Add whitespace
if (isKeySide) {
fix = function(fixer) {
return fixer.insertTextAfter(tokenBeforeColon, spaces);
};
} else {
fix = function(fixer) {
return fixer.insertTextBefore(tokenAfterColon, spaces);
};
}
}
let messageId = "";
if (isExtra) {
messageId = side === "key" ? "extraKey" : "extraValue";
} else {
messageId = side === "key" ? "missingKey" : "missingValue";
}
context.report({
node: property[side],
loc,
messageId,
data: {
computed: property.computed ? "computed " : "",
key: getKey(property)
},
fix
});
}
}
/**
* Gets the number of characters in a key, including quotes around string
* keys and braces around computed property keys.
* @param {ASTNode} property Property of on object literal.
* @returns {int} Width of the key.
*/
function getKeyWidth(property) {
const startToken = sourceCode.getFirstToken(property);
const endToken = getLastTokenBeforeColon(property.key);
return splitter.countGraphemes(sourceCode.getText().slice(startToken.range[0], endToken.range[1]));
}
/**
* Gets the whitespace around the colon in an object literal property.
* @param {ASTNode} property Property node from an object literal.
* @returns {Object} Whitespace before and after the property's colon.
*/
function getPropertyWhitespace(property) {
const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice(
property.key.range[1], property.value.range[0]
));
if (whitespace) {
return {
beforeColon: whitespace[1],
afterColon: whitespace[2]
};
}
return null;
}
/**
* Creates groups of properties.
* @param {ASTNode} node ObjectExpression node being evaluated.
* @returns {Array<ASTNode[]>} Groups of property AST node lists.
*/
function createGroups(node) {
if (node.properties.length === 1) {
return [node.properties];
}
return node.properties.reduce((groups, property) => {
const currentGroup = last(groups),
prev = last(currentGroup);
if (!prev || continuesPropertyGroup(prev, property)) {
currentGroup.push(property);
} else {
groups.push([property]);
}
return groups;
}, [
[]
]);
}
/**
* Verifies correct vertical alignment of a group of properties.
* @param {ASTNode[]} properties List of Property AST nodes.
* @returns {void}
*/
function verifyGroupAlignment(properties) {
const length = properties.length,
widths = properties.map(getKeyWidth), // Width of keys, including quotes
align = alignmentOptions.on; // "value" or "colon"
let targetWidth = Math.max(...widths),
beforeColon, afterColon, mode;
if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration.
beforeColon = alignmentOptions.beforeColon;
afterColon = alignmentOptions.afterColon;
mode = alignmentOptions.mode;
} else {
beforeColon = multiLineOptions.beforeColon;
afterColon = multiLineOptions.afterColon;
mode = alignmentOptions.mode;
}
// Conditionally include one space before or after colon
targetWidth += (align === "colon" ? beforeColon : afterColon);
for (let i = 0; i < length; i++) {
const property = properties[i];
const whitespace = getPropertyWhitespace(property);
if (whitespace) { // Object literal getters/setters lack a colon
const width = widths[i];
if (align === "value") {
report(property, "key", whitespace.beforeColon, beforeColon, mode);
report(property, "value", whitespace.afterColon, targetWidth - width, mode);
} else { // align = "colon"
report(property, "key", whitespace.beforeColon, targetWidth - width, mode);
report(property, "value", whitespace.afterColon, afterColon, mode);
}
}
}
}
/**
* Verifies spacing of property conforms to specified options.
* @param {ASTNode} node Property node being evaluated.
* @param {Object} lineOptions Configured singleLine or multiLine options
* @returns {void}
*/
function verifySpacing(node, lineOptions) {
const actual = getPropertyWhitespace(node);
if (actual) { // Object literal getters/setters lack colons
report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode);
report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode);
}
}
/**
* Verifies spacing of each property in a list.
* @param {ASTNode[]} properties List of Property AST nodes.
* @param {Object} lineOptions Configured singleLine or multiLine options
* @returns {void}
*/
function verifyListSpacing(properties, lineOptions) {
const length = properties.length;
for (let i = 0; i < length; i++) {
verifySpacing(properties[i], lineOptions);
}
}
/**
* Verifies vertical alignment, taking into account groups of properties.
* @param {ASTNode} node ObjectExpression node being evaluated.
* @returns {void}
*/
function verifyAlignment(node) {
createGroups(node).forEach(group => {
const properties = group.filter(isKeyValueProperty);
if (properties.length > 0 && isSingleLineProperties(properties)) {
verifyListSpacing(properties, multiLineOptions);
} else {
verifyGroupAlignment(properties);
}
});
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
if (alignmentOptions) { // Verify vertical alignment
return {
ObjectExpression(node) {
if (isSingleLine(node)) {
verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions);
} else {
verifyAlignment(node);
}
}
};
}
// Obey beforeColon and afterColon in each property as configured
return {
Property(node) {
verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions);
}
};
}
};