forked from leo-buneev/eslint-plugin-sort-keys-fix
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort-keys.js
484 lines (426 loc) · 14.1 KB
/
sort-keys.js
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
/**
* @fileoverview Rule to require object keys to be sorted
* @author Toru Nagashima
*/
'use strict'
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const astUtils = require('./utils/ast-utils'),
naturalCompare = require('natural-compare')
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/** @typedef {import('../shared/types').ExclusifyUnion<import('estree').Node>} ASTNode */
/** @typedef {import('../shared/types').ExclusifyUnion<ASTNode['key']>} ASTPropKeyNode */
/**
* @typedef Override
* @property {string} [message] Message
* @property {string[]} order Property Order
* @property {string[]} [properties] Name of parent property to apply this override to. If omitted, the object's keys
* must be a total subset of the properties defined in order
*/
/**
* @typedef Options
* @property {boolean} [caseSensitive] Use case sensitive sorting
* @property {boolean} [natural] Use natural sorting
* @property {number} [minKeys] Minimum Keys
* @property {'first' | 'last' | 'ignore'} [allCaps] All Caps option
* @property {Override[]} [overrides] Overrides options
*/
/** @typedef {(a: string, b: string) => boolean | null} IsValidOrder */
/**
* @typedef Stack
* @property {Stack | null} upper
* @property {import('estree').Property & import('eslint').Rule.NodeParentExtension | null} prevNode
* @property {boolean} prevBlankLine
* @property {string | null} prevName
* @property {number} numKeys
* @property {string} parentName
* @property {Override} override
* @property {IsValidOrder} isValidOrder
*/
/**
* Combinatorial combination fn
* @template T
* @param {T[]} arr items
* @param {number} minLength minimum length
* @returns {T[][]} combinations
*/
function combination(arr, minLength) {
/** @type {T[][]} */
const initialValue = []
return arr
.reduce((out, item) => [...out, [item], ...out.map(c => [...c, item])], initialValue)
.filter(c => c.length >= minLength)
}
/**
* Gets the property name of the given `Property` node.
*
* - If the property's key is an `Identifier` node, this returns the key's name
* whether it's a computed property or not.
* - If the property has a static name, this returns the static name.
* - Otherwise, this returns null.
* @param {ASTNode} node The `Property` node to get.
* @returns {string|null} The property name or null.
* @private
*/
function getPropertyName(node) {
const staticName = astUtils.getStaticPropertyName(node)
if (staticName !== null) {
return staticName
}
/** @type {ASTPropKeyNode | undefined} */
const key = node.key
return (key && key.name) || null
}
/**
* test blank lines
* @param {import('eslint').Rule.RuleContext} context context
* @param {import('eslint').Rule.Node} node node
* @param {import('eslint').Rule.Node} prevNode prevNode
* @returns {boolean} if there is a blank line between the prevNode and current node
*/
function hasBlankLineBetweenNodes(context, node, prevNode) {
const sourceCode = context.getSourceCode()
// Get tokens between current node and previous node
const tokens = prevNode && sourceCode.getTokensBetween(prevNode, node, { includeComments: true })
if (!tokens) {
return false
}
let previousToken
// check blank line between tokens
for (const token of tokens) {
if (previousToken && token.loc.start.line - previousToken.loc.end.line > 1) {
return true
}
previousToken = token
}
// check blank line between the current node and the last token
if (node.loc.start.line - tokens[tokens.length - 1].loc.end.line > 1) {
return true
}
// check blank line between the first token and the previous node
if (tokens[0].loc.start.line - prevNode.loc.end.line > 1) {
return true
}
}
/**
* Function to check that 2 names are proper all caps order
* @param {string} a first value
* @param {string} b second value
* @returns {boolean | null} if the values are in valid order; null if both are all caps or not all caps
* @private
*/
function isValidAllCapsTest(a, b) {
const aIsAllCaps = a === a.toUpperCase()
const bIsAllCaps = b === b.toUpperCase()
return aIsAllCaps === bIsAllCaps ? null : aIsAllCaps && !bIsAllCaps
}
/**
* Functions which check that the given 2 names are in specific order.
*
* Postfix `I` is meant insensitive.
* Postfix `N` is meant natural.
* @type {Record<`${'asc'|'desc'}${''|'I'}${''|'N'}`, IsValidOrder>}
* @private
*/
// @ts-ignore
const isValidOrders = {
asc(a, b) {
return a <= b
},
ascI(a, b) {
return a.toLowerCase() <= b.toLowerCase()
},
ascN(a, b) {
return naturalCompare(a, b) <= 0
},
ascIN(a, b) {
return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0
},
}
Object.keys(isValidOrders).forEach(asc => {
const desc = `desc${asc.slice(3)}`
isValidOrders[desc] = Object.defineProperty((a, b) => isValidOrders[asc](b, a), 'name', { value: desc })
})
/**
* Customize
* @param {(a: any, b: any) => boolean} base isValid checker
* @param {string[]} [order] order of properties
* @returns {(a: any, b: any) => boolean} new comparator
*/
function customizeOrder(base, order) {
if (!order) {
return base
}
return (a, b) => {
const aIndex = order.indexOf(a)
const bIndex = order.indexOf(b)
if (aIndex >= 0) {
if (bIndex >= 0) {
return aIndex <= bIndex
}
return true
}
return bIndex < 0 && base(a, b)
}
}
/**
* create fixer
* @param {import('eslint').Rule.RuleContext} context context
* @param {import('eslint').Rule.Node} node node
* @param {import('eslint').Rule.Node} prevNode prevNode
* @returns {import('eslint').Rule.ReportFixer} fixer
*/
function createFixer(context, node, prevNode) {
return function fix(fixer) {
const fixes = []
const sourceCode = context.getSourceCode()
/**
* Move Property
* @param {import('eslint').Rule.Node} fromNode From Node
* @param {import('eslint').Rule.Node} toNode To Node
* @returns {void}
*/
function moveProperty(fromNode, toNode) {
const prevText = sourceCode.getText(fromNode)
const thisComments = sourceCode.getCommentsBefore(fromNode)
for (const thisComment of thisComments) {
fixes.push(fixer.insertTextBefore(toNode, `${sourceCode.getText(thisComment)}\n`))
fixes.push(fixer.remove(thisComment))
}
fixes.push(fixer.replaceText(toNode, prevText))
}
moveProperty(node, prevNode)
moveProperty(prevNode, node)
return fixes
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
fixable: 'code',
docs: {
description: 'require object keys to be sorted',
category: 'Stylistic Issues',
recommended: false,
url: 'https://github.com/forivall/eslint-plugin-sort-keys-plus',
},
schema: [
{
enum: ['asc', 'desc'],
},
{
type: 'object',
properties: {
caseSensitive: {
type: 'boolean',
default: true,
},
natural: {
type: 'boolean',
default: false,
},
minKeys: {
type: 'integer',
minimum: 2,
default: 2,
},
allowLineSeparatedGroups: {
type: 'boolean',
default: false,
},
allCaps: {
enum: ['first', 'last', 'ignore'],
default: 'ignore',
},
overrides: {
type: 'array',
items: {
type: 'object',
required: ['order'],
properties: {
message: { type: 'string' },
order: {
type: 'array',
minLength: 1,
items: {
type: 'string',
},
},
properties: {
type: 'array',
minLength: 1,
items: { type: 'string' },
},
},
},
default: [],
},
},
additionalProperties: false,
},
],
messages: {
sortKeys:
"Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'.",
},
},
create(context) {
// Parse options.
/** @type {'asc' | 'desc'} */
const order = context.options[0] || 'asc'
/** @type {Options | undefined} */
const options = context.options[1]
const insensitive = options && options.caseSensitive === false
const natural = options && options.natural
const minKeys = (options && options.minKeys) || 2
const allowLineSeparatedGroups = (options && options.allowLineSeparatedGroups) || false
const allCaps = (options && options.allCaps) || 'ignore'
/** @type {Override[]} */
const overrides = (options && options.overrides) || []
/** @type {Map<string | undefined, Override>} */
const propOverrides = new Map(
overrides.flatMap(item => (item.properties ? item.properties.map(property => [property, item]) : [])),
)
/** @type {Map<string, Override>} */
const otherOverrides = new Map()
overrides.forEach(override => {
if (override.properties) {
return
}
const sorted = override.order.concat().sort()
combination(sorted, minKeys).forEach(combo => {
const key = combo.join()
const existing = otherOverrides.get(key)
if (!existing || override.order.length < existing.order.length) {
otherOverrides.set(key, override)
}
})
})
const isValidOrderBase = isValidOrders[`${order}${insensitive ? 'I' : ''}${natural ? 'N' : ''}`]
/** @type {IsValidOrder} */
const isValidOrderAllCaps =
// eslint-disable-next-line no-nested-ternary
allCaps === 'ignore' ? () => null : allCaps === 'last' ? (a, b) => isValidAllCapsTest(b, a) : isValidAllCapsTest
/**
* The stack to save the previous property's name for each object literals.
* @type {Stack | null}
*/
let stack = null
/**
* Spread element parser
* @param {import('estree').SpreadElement & import('eslint').Rule.NodeParentExtension} node AST Node
* @returns {void}
*/
function SpreadElement(node) {
if (node.parent.type === 'ObjectExpression') {
stack.prevName = null
stack.prevNode = null
}
}
return {
ExperimentalSpreadProperty: SpreadElement,
ObjectExpression(node) {
/** @type {ASTNode} */
const parent = node.parent
let parentName
let override
if (parent.type === 'Property' && !parent.computed) {
/** @type {ASTPropKeyNode} */
const parentKey = parent.key
parentName = typeof parentKey.value === 'string' ? parentKey.value : parentKey.name
override = propOverrides.get(parentName)
}
if (!override && otherOverrides.size > 0) {
const key = node.properties
.map(getPropertyName)
.filter(name => name !== null)
.sort()
.join()
override = otherOverrides.get(key)
}
stack = {
upper: stack,
prevNode: null,
prevBlankLine: false,
prevName: null,
numKeys: node.properties.length,
parentName,
override,
isValidOrder: customizeOrder(isValidOrderBase, override && override.order),
}
},
'ObjectExpression:exit'() {
stack = stack.upper
},
SpreadElement,
Property(node) {
if (node.parent.type === 'ObjectPattern') {
return
}
const prevNode = stack.prevNode
const prevName = stack.prevName
const numKeys = stack.numKeys
const thisName = getPropertyName(node)
const isBlankLineBetweenNodes =
stack.prevBlankLine || (allowLineSeparatedGroups && hasBlankLineBetweenNodes(context, node, prevNode))
stack.prevNode = node
if (thisName !== null) {
stack.prevName = thisName
}
if (allowLineSeparatedGroups && isBlankLineBetweenNodes) {
stack.prevBlankLine = thisName === null
return
}
if (prevName === null || thisName === null || numKeys < minKeys) {
return
}
const isValidAllCaps = isValidOrderAllCaps(prevName, thisName)
if (isValidAllCaps) {
return
}
if (isValidAllCaps === false) {
context.report({
node,
loc: node.key.loc,
message: `Expected all caps keys to be first. '{{thisName}}' should be before '{{prevName}}'.`,
data: {
thisName,
prevName,
},
fix: createFixer(context, node, prevNode),
})
return
}
if (!stack.isValidOrder(prevName, thisName)) {
const isOverride =
stack.override &&
(stack.override.order.indexOf(prevName) >= 0 || stack.override.order.indexOf(thisName) >= 0)
const messageStart = isOverride
? stack.override.message || 'Expected object keys of {{parentName}} to be in custom order.'
: 'Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order.'
context.report({
node,
loc: node.key.loc,
message: `${messageStart} '{{thisName}}' should be before '{{prevName}}'.`,
data: {
parentName: stack.parentName,
thisName,
prevName,
order,
insensitive: insensitive ? 'insensitive ' : '',
natural: natural ? 'natural ' : '',
},
fix: createFixer(context, node, prevNode),
})
}
},
}
},
}