eslint-plugin-lube 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +283 -0
  2. package/LICENSE +21 -0
  3. package/README.md +123 -9
  4. package/docs/ascii-order.md +81 -0
  5. package/docs/prefer-type-tag.md +45 -0
  6. package/docs/pretty-imports.md +70 -59
  7. package/docs/pretty-jsdoc-casting.md +31 -23
  8. package/docs/pretty-sequence.md +129 -117
  9. package/docs/pretty-ternary.md +55 -0
  10. package/docs/svelte-naming-convention.md +59 -46
  11. package/package.json +60 -38
  12. package/src/index.js +308 -0
  13. package/src/rules/ascii-order.js +1032 -0
  14. package/src/rules/prefer-type-tag.js +165 -0
  15. package/src/rules/pretty-imports.js +188 -0
  16. package/src/rules/pretty-jsdoc-casting.js +325 -0
  17. package/src/rules/pretty-sequence.js +562 -0
  18. package/src/rules/pretty-ternary.js +255 -0
  19. package/src/rules/svelte-naming-convention.js +1062 -0
  20. package/src/utils/fix_recorder.js +50 -0
  21. package/src/utils/keep_body_comments.js +53 -0
  22. package/src/utils/keep_comments.js +103 -0
  23. package/src/utils/keep_line_breaks.js +58 -0
  24. package/src/utils/skip_hole_commas.js +34 -0
  25. package/src/utils/skip_optional_patterns.js +29 -0
  26. package/src/utils/skip_unchanged_fixes.js +37 -0
  27. package/src/utils/source_text.js +476 -0
  28. package/src/utils/split_declarations.js +75 -0
  29. package/src/utils/text_width.js +9 -0
  30. package/types/index.d.ts +27 -13
  31. package/types/index.d.ts.map +1 -1
  32. package/index.js +0 -126
  33. package/private.d.ts +0 -168
  34. package/rules/pretty-imports.js +0 -147
  35. package/rules/pretty-jsdoc-casting.js +0 -236
  36. package/rules/pretty-sequence.js +0 -441
  37. package/rules/svelte-naming-convention.js +0 -361
  38. package/test/pretty-imports/ExportNamedDeclaration.js +0 -123
  39. package/test/pretty-imports/ImportDeclaration.js +0 -125
  40. package/test/pretty-imports.js +0 -20
  41. package/test/pretty-jsdoc-casting/case_by_expression.js +0 -289
  42. package/test/pretty-jsdoc-casting/various_situations.js +0 -111
  43. package/test/pretty-jsdoc-casting.js +0 -22
  44. package/test/pretty-sequence/case_by_node_type.js +0 -360
  45. package/test/pretty-sequence/case_by_option.js +0 -142
  46. package/test/pretty-sequence/various_situations.js +0 -204
  47. package/test/pretty-sequence.js +0 -23
  48. package/test/svelte-naming-convention/basic_snake_case.js +0 -67
  49. package/test/svelte-naming-convention/case_by_identifier.js +0 -1394
  50. package/test/svelte-naming-convention/snake_case_with_symbols.js +0 -67
  51. package/test/svelte-naming-convention.js +0 -25
  52. package/tsconfig.json +0 -21
  53. package/types/rules/pretty-imports.d.ts +0 -3
  54. package/types/rules/pretty-imports.d.ts.map +0 -1
  55. package/types/rules/pretty-jsdoc-casting.d.ts +0 -3
  56. package/types/rules/pretty-jsdoc-casting.d.ts.map +0 -1
  57. package/types/rules/pretty-sequence.d.ts +0 -3
  58. package/types/rules/pretty-sequence.d.ts.map +0 -1
  59. package/types/rules/svelte-naming-convention.d.ts +0 -3
  60. package/types/rules/svelte-naming-convention.d.ts.map +0 -1
  61. package/types/test/pretty-imports/ExportNamedDeclaration.d.ts +0 -2
  62. package/types/test/pretty-imports/ExportNamedDeclaration.d.ts.map +0 -1
  63. package/types/test/pretty-imports/ImportDeclaration.d.ts +0 -2
  64. package/types/test/pretty-imports/ImportDeclaration.d.ts.map +0 -1
  65. package/types/test/pretty-imports.d.ts +0 -2
  66. package/types/test/pretty-imports.d.ts.map +0 -1
  67. package/types/test/pretty-jsdoc-casting/case_by_expression.d.ts +0 -2
  68. package/types/test/pretty-jsdoc-casting/case_by_expression.d.ts.map +0 -1
  69. package/types/test/pretty-jsdoc-casting/various_situations.d.ts +0 -2
  70. package/types/test/pretty-jsdoc-casting/various_situations.d.ts.map +0 -1
  71. package/types/test/pretty-jsdoc-casting.d.ts +0 -2
  72. package/types/test/pretty-jsdoc-casting.d.ts.map +0 -1
  73. package/types/test/pretty-sequence/case_by_node_type.d.ts +0 -2
  74. package/types/test/pretty-sequence/case_by_node_type.d.ts.map +0 -1
  75. package/types/test/pretty-sequence/case_by_option.d.ts +0 -2
  76. package/types/test/pretty-sequence/case_by_option.d.ts.map +0 -1
  77. package/types/test/pretty-sequence/various_situations.d.ts +0 -2
  78. package/types/test/pretty-sequence/various_situations.d.ts.map +0 -1
  79. package/types/test/pretty-sequence.d.ts +0 -2
  80. package/types/test/pretty-sequence.d.ts.map +0 -1
  81. package/types/test/svelte-naming-convention/basic_snake_case.d.ts +0 -2
  82. package/types/test/svelte-naming-convention/basic_snake_case.d.ts.map +0 -1
  83. package/types/test/svelte-naming-convention/case_by_identifier.d.ts +0 -2
  84. package/types/test/svelte-naming-convention/case_by_identifier.d.ts.map +0 -1
  85. package/types/test/svelte-naming-convention/snake_case_with_symbols.d.ts +0 -2
  86. package/types/test/svelte-naming-convention/snake_case_with_symbols.d.ts.map +0 -1
  87. package/types/test/svelte-naming-convention.d.ts +0 -2
  88. package/types/test/svelte-naming-convention.d.ts.map +0 -1
@@ -0,0 +1,1032 @@
1
+ import { create_source_text } from "../utils/source_text.js"
2
+ const not_static = Symbol("not static")
3
+ const portable_flags_regex = /^[gimsuy]*$/
4
+ const regexp_group_name_regex = /\(\?<([^!=>]+)>/g
5
+ const regexp_modifier_regex = /\(\?[-A-Za-z]/
6
+ const constant_globals = new Set(
7
+ [ "Infinity", "NaN", "undefined" ]
8
+ )
9
+ const pass_through_parents = new Set(
10
+ [
11
+ "ArrayExpression",
12
+ "ConditionalExpression",
13
+ "JSXExpressionContainer",
14
+ "LogicalExpression",
15
+ "SequenceExpression"
16
+ ]
17
+ )
18
+ const test_functions = new Set([ "describe", "it", "test" ])
19
+ const type_wrappers = new Set(
20
+ [
21
+ "TSAsExpression",
22
+ "TSNonNullExpression",
23
+ "TSSatisfiesExpression",
24
+ "TSTypeAssertion"
25
+ ]
26
+ )
27
+ const safe_constructors = new Set(
28
+ [
29
+ "Array",
30
+ "ArrayBuffer",
31
+ "BigInt64Array",
32
+ "BigUint64Array",
33
+ "DataView",
34
+ "Date",
35
+ "Error",
36
+ "EvalError",
37
+ "Float32Array",
38
+ "Float64Array",
39
+ "Int16Array",
40
+ "Int32Array",
41
+ "Int8Array",
42
+ "Map",
43
+ "RangeError",
44
+ "ReferenceError",
45
+ "RegExp",
46
+ "Set",
47
+ "SyntaxError",
48
+ "TypeError",
49
+ "URIError",
50
+ "URL",
51
+ "Uint16Array",
52
+ "Uint32Array",
53
+ "Uint8Array",
54
+ "Uint8ClampedArray",
55
+ "WeakMap",
56
+ "WeakSet"
57
+ ]
58
+ )
59
+ const closers = new Set([ ")", "]", "}" ])
60
+ const member_separators = new Set([ ",", ";" ])
61
+ const shebang_types = new Set([ "Hashbang", "Shebang" ])
62
+ /**
63
+ * @param {import("../../private.js").OrderEntry} a
64
+ * @param {import("../../private.js").OrderEntry} b
65
+ * @returns {number}
66
+ */
67
+ function compare(a, b) {
68
+ const rank = (a.rank ?? 1) - (b.rank ?? 1)
69
+ if (rank) {
70
+ return rank
71
+ }
72
+ return a.name < b.name
73
+ ? -1
74
+ : a.name > b.name
75
+ ? 1
76
+ : 0
77
+ }
78
+ /**
79
+ * @param {import("../../private.js").Comment[]} comments
80
+ * @param {number} line
81
+ * @returns {number}
82
+ */
83
+ function count_same_line(comments, line) {
84
+ let count = 0
85
+ for (const comment of comments) {
86
+ if (comment.loc.start.line != line) {
87
+ break
88
+ }
89
+ line = comment.loc.end.line
90
+ count++
91
+ }
92
+ return count
93
+ }
94
+ /**
95
+ * @param {import("eslint").Rule.RuleContext} context
96
+ */
97
+ function create_reorder(context) {
98
+ const source_code = context.sourceCode
99
+ const source = create_source_text(source_code)
100
+ const text = source.text
101
+ /**
102
+ * @param {import("../../private.js").OrderEntry} entry
103
+ * @param {import("../../private.js").OrderLayout} layout
104
+ * @param {((node: import("../../private.js").OrderNode) => number)=} get_level
105
+ * @returns {import("../../private.js").OrderItem | undefined}
106
+ */
107
+ function get_item(entry, layout, get_level) {
108
+ const first_token = /** @type {import("eslint").AST.Token} */(source_code.getFirstToken(
109
+ /** @type {import("estree").Node} */(entry.first)/**/
110
+ ))/**/
111
+ const before = source_code.getTokenBefore(first_token)
112
+ const leading = /** @type {import("../../private.js").Comment[]} */(source_code.getCommentsBefore(first_token))/**/.filter(
113
+ comment => !shebang_types.has(comment.type)
114
+ )
115
+ const head = before ? count_same_line(leading, before.loc.end.line) : 0
116
+ const start = leading[head]?.range[0] ?? first_token.range[0]
117
+ let last_token = /** @type {import("eslint").AST.Token} */(source_code.getLastToken(
118
+ /** @type {import("estree").Node} */(entry.last)/**/
119
+ ))/**/
120
+ /** @type {import("eslint").AST.Token | null} */
121
+ let separator = null
122
+ if (layout == "member" && member_separators.has(last_token.value)) {
123
+ separator = last_token
124
+ last_token = /** @type {import("eslint").AST.Token} */(source_code.getTokenBefore(last_token))/**/
125
+ } else if (layout == "sequence") {
126
+ const next = source_code.getTokenAfter(last_token)
127
+ if (next?.value == ",") {
128
+ separator = next
129
+ }
130
+ }
131
+ const inner = /** @type {import("../../private.js").Comment[]} */(source_code.getCommentsAfter(last_token))/**/
132
+ let code_end = last_token.range[1]
133
+ let line = last_token.loc.end.line
134
+ /** @type {import("../../private.js").Comment[]} */
135
+ let tail
136
+ if (separator) {
137
+ if (inner.some(
138
+ comment => comment.type == "Line"
139
+ )) {
140
+ return undefined
141
+ }
142
+ code_end = inner[inner.length - 1]?.range[1] ?? code_end
143
+ line = separator.loc.end.line
144
+ tail = /** @type {import("../../private.js").Comment[]} */(source_code.getCommentsAfter(separator))/**/
145
+ } else {
146
+ let index = 0
147
+ for (let comment = inner[0]; comment?.type == "Block" && comment.range[0] == code_end; comment = inner[++index]) {
148
+ code_end = comment.range[1]
149
+ line = comment.loc.end.line
150
+ }
151
+ tail = inner.slice(index)
152
+ }
153
+ const sep_end = separator ? separator.range[1] : code_end
154
+ const tail_count = count_same_line(tail, line)
155
+ const last_comment = tail[tail_count - 1]
156
+ const after = last_comment ? last_comment.range[1] : sep_end
157
+ let next = after
158
+ while (text[next] == " " || text[next] == "\t") {
159
+ next++
160
+ }
161
+ let previous = start
162
+ while (text[previous - 1] == " " || text[previous - 1] == "\t") {
163
+ previous--
164
+ }
165
+ const declaration = entry.last.type == "ExportNamedDeclaration"
166
+ ? entry.last.declaration
167
+ : entry.last
168
+ return {
169
+ after,
170
+ break_after: next == text.length || text[next] == "\n" || text[next] == "\r",
171
+ break_before: previous == 0 || text[previous - 1] == "\n" || text[previous - 1] == "\r",
172
+ closes: closers.has(text[next] ?? ""),
173
+ code_end,
174
+ entry,
175
+ head: head > 0,
176
+ header: !before && leading.length > 0,
177
+ leading: start < first_token.range[0],
178
+ level: get_level ? get_level(entry.first) : 0,
179
+ semicolon: last_token.value == ";",
180
+ sep_end,
181
+ start,
182
+ tail_line: last_comment?.type == "Line",
183
+ tail_start: tail[0] && last_comment ? tail[0].range[0] : after,
184
+ terminated: last_token.value == ";" || declaration?.type == "FunctionDeclaration"
185
+ }
186
+ }
187
+ /**
188
+ * @param {import("../../private.js").OrderEntry[]} entries
189
+ * @param {import("../../private.js").OrderLayout} layout
190
+ * @param {import("../../private.js").OrderEntry} reported
191
+ * @param {((node: import("../../private.js").OrderNode) => number)=} get_level
192
+ * @returns {{ range: [number, number], text: string } | import("../../private.js").OrderItem | null}
193
+ */
194
+ function get_replacement(entries, layout, reported, get_level) {
195
+ /** @type {import("../../private.js").OrderItem[]} */
196
+ const items = []
197
+ for (const entry of entries) {
198
+ const item = get_item(entry, layout, get_level)
199
+ if (!item) {
200
+ return null
201
+ }
202
+ items.push(item)
203
+ }
204
+ const sorted = items.slice().sort(
205
+ (a, b) => compare(a.entry, b.entry)
206
+ )
207
+ const blocker = find_blocker(items, sorted, reported)
208
+ if (blocker) {
209
+ return blocker
210
+ }
211
+ const last_index = items.length - 1
212
+ let result = ""
213
+ for (let i = 0; i <= last_index; i++) {
214
+ const slot = /** @type {import("../../private.js").OrderItem} */(items[i])/**/
215
+ const item = /** @type {import("../../private.js").OrderItem} */(sorted[i])/**/
216
+ const has_tail = item.tail_start < item.after
217
+ if (
218
+ item.leading && !slot.break_before
219
+ || i == 0 && slot.head && !slot.break_before
220
+ || slot.header && item != slot
221
+ || slot.tail_start < slot.after && !slot.break_after && (i < last_index || !slot.closes)
222
+ || has_tail && !slot.break_after && (i < last_index || item.tail_line)
223
+ || layout == "statement" && i < last_index && !item.terminated && !slot.break_after
224
+ ) {
225
+ return null
226
+ }
227
+ result += source.render(item.start, item.code_end) + source.render(slot.code_end, slot.sep_end)
228
+ if (has_tail) {
229
+ result += " " + source.render(item.tail_start, item.after)
230
+ }
231
+ if (i < last_index) {
232
+ result += source.render(
233
+ slot.after,
234
+ /** @type {import("../../private.js").OrderItem} */(items[i + 1])/**/.start
235
+ )
236
+ }
237
+ }
238
+ const first = /** @type {import("../../private.js").OrderItem} */(items[0])/**/
239
+ const last = /** @type {import("../../private.js").OrderItem} */(items[last_index])/**/
240
+ if (last.semicolon && !(/** @type {import("../../private.js").OrderItem} */(sorted[last_index])/**/).semicolon) {
241
+ return null
242
+ }
243
+ source.edit(first.start, last.after, result)
244
+ return {
245
+ range: [ first.start, last.after ],
246
+ text: result
247
+ }
248
+ }
249
+ /**
250
+ * @param {import("../../private.js").OrderNode} node
251
+ * @returns {string}
252
+ */
253
+ function get_snippet(node) {
254
+ const value = node.type == "Property"
255
+ ? node.computed && node.key.type != "Literal"
256
+ ? node.key
257
+ : node.value
258
+ : node
259
+ const snippet = source_code.getText(
260
+ /** @type {import("estree").Node} */(value)/**/
261
+ ).replace(/\s+/g, " ")
262
+ return snippet.length > 30 ? snippet.slice(0, 29) + "…" : snippet
263
+ }
264
+ /**
265
+ * @param {import("../../private.js").OrderEntry[]} entries
266
+ * @param {string} message_id
267
+ * @param {import("../../private.js").OrderLayout} layout
268
+ * @param {((node: import("../../private.js").OrderNode) => number)=} get_level
269
+ * @returns {void}
270
+ */
271
+ function verify(
272
+ entries,
273
+ message_id,
274
+ layout,
275
+ get_level
276
+ ) {
277
+ const index = entries.findIndex(
278
+ (entry, i) => i > 0 && compare(
279
+ /** @type {import("../../private.js").OrderEntry} */(entries[i - 1])/**/,
280
+ entry
281
+ ) > 0
282
+ )
283
+ const entry = entries[index]
284
+ const previous = entries[index - 1]
285
+ if (!entry || !previous) {
286
+ return
287
+ }
288
+ const replacement = get_replacement(entries, layout, entry, get_level)
289
+ const fix = replacement && "range" in replacement ? replacement : null
290
+ const blocker = replacement && "entry" in replacement ? replacement : null
291
+ context.report(
292
+ {
293
+ data: {
294
+ name: entry.name,
295
+ previous: previous.name,
296
+ reason: fix
297
+ ? ""
298
+ : blocker
299
+ ? "; it is not fixed automatically because moving `" + get_snippet(blocker.entry.first) + "` could change the order of side effects, so reorder it by hand"
300
+ : "; it is not fixed automatically because a comment or statement next to it would end up in the wrong place, so reorder it by hand"
301
+ },
302
+ fix: fix && (
303
+ fixer => fixer.replaceTextRange(fix.range, fix.text)
304
+ ),
305
+ messageId: message_id,
306
+ node: entry.report
307
+ }
308
+ )
309
+ }
310
+ return { verify }
311
+ }
312
+ /**
313
+ * @param {import("../../private.js").OrderItem[]} items
314
+ * @param {import("../../private.js").OrderItem[]} sorted
315
+ * @param {import("../../private.js").OrderEntry} reported
316
+ * @returns {import("../../private.js").OrderItem | undefined}
317
+ */
318
+ function find_blocker(items, sorted, reported) {
319
+ const positions = new Map(
320
+ sorted.map((item, i) => [ item, i ])
321
+ )
322
+ const blockers = items.filter(
323
+ (a, i) => a.level > 1 && items.some(
324
+ (b, j) => b.level && i != j && i < j != /** @type {number} */(positions.get(a))/**/ < /** @type {number} */(positions.get(b))/**/
325
+ )
326
+ )
327
+ return blockers.find(
328
+ blocker => blocker.entry == reported
329
+ ) ?? blockers[0]
330
+ }
331
+ /**
332
+ * @param {import("../../private.js").OrderNode} node
333
+ * @returns {string | undefined}
334
+ */
335
+ function get_name(node) {
336
+ switch (node.type) {
337
+ case "Identifier":
338
+ return node.name
339
+ case "Literal":
340
+ return String(node.value)
341
+ case "TemplateLiteral":
342
+ return node.expressions.length
343
+ ? undefined
344
+ : /** @type {import("estree").TemplateElement} */(node.quasis[0])/**/.value.cooked ?? undefined
345
+ }
346
+ return undefined
347
+ }
348
+ /**
349
+ * @param {unknown} value
350
+ * @returns {boolean}
351
+ */
352
+ function is_large(value) {
353
+ if (typeof value == "object" && value) {
354
+ return !Array.isArray(value) && Object.values(value).some(
355
+ property => typeof property == "object" && property || is_large(property)
356
+ )
357
+ }
358
+ return Number(value) > 65536
359
+ }
360
+ /**
361
+ * @param {unknown[]} args
362
+ * @returns {boolean}
363
+ */
364
+ function is_portable_regexp(args) {
365
+ const [ pattern, flags ] = args
366
+ const source = pattern instanceof RegExp ? pattern.source : pattern
367
+ const flag_text = flags === undefined && pattern instanceof RegExp ? pattern.flags : flags
368
+ if (typeof source != "string" && source !== undefined || typeof flag_text != "string" && flag_text !== undefined) {
369
+ return false
370
+ }
371
+ if (flag_text && !portable_flags_regex.test(flag_text) || source && regexp_modifier_regex.test(source)) {
372
+ return false
373
+ }
374
+ /** @type {Set<string>} */
375
+ const names = new Set()
376
+ for (const match of source?.matchAll(regexp_group_name_regex) ?? []) {
377
+ const name = /** @type {string} */(match[1])/**/
378
+ if (names.has(name)) {
379
+ return false
380
+ }
381
+ names.add(name)
382
+ }
383
+ return true
384
+ }
385
+ /**
386
+ * @param {import("../../private.js").OrderNode} parent
387
+ * @param {import("../../private.js").OrderNode} child
388
+ * @returns {boolean}
389
+ */
390
+ function passes_through(parent, child) {
391
+ switch (parent.type) {
392
+ case "BinaryExpression":
393
+ return parent.operator == "===" || parent.operator == "!=="
394
+ case "Property":
395
+ return parent.value == child
396
+ case "UnaryExpression":
397
+ return parent.operator == "!" || parent.operator == "typeof" || parent.operator == "void"
398
+ }
399
+ return pass_through_parents.has(parent.type)
400
+ }
401
+ /** @type {import("eslint").Rule.RuleModule} */
402
+ export default {
403
+ create(context) {
404
+ /** @type {import("../../private.js").RuleOptions["ascii-order"]} */
405
+ const option = context.options[0]
406
+ const check_declarations = option?.checkDeclarations ?? true
407
+ const check_imports = option?.checkImports ?? true
408
+ const check_keys = option?.checkKeys ?? true
409
+ const check_names = option?.checkNames ?? true
410
+ const check_tests = option?.checkTests ?? true
411
+ const visitor_keys = context.sourceCode.visitorKeys
412
+ const { verify } = create_reorder(context)
413
+ /** @type {Set<string | undefined>} */
414
+ const default_exports = new Set()
415
+ /** @type {Parameters<typeof verify>[]} */
416
+ const pending = []
417
+ /**
418
+ * @param {import("../../private.js").OrderNode} node
419
+ * @returns {number}
420
+ */
421
+ function classify(node) {
422
+ switch (node.type) {
423
+ case "ArrowFunctionExpression":
424
+ case "FunctionExpression":
425
+ return 0
426
+ case "AssignmentExpression":
427
+ case "AwaitExpression":
428
+ case "CallExpression":
429
+ case "ClassExpression":
430
+ case "ImportExpression":
431
+ case "TaggedTemplateExpression":
432
+ case "UpdateExpression":
433
+ case "YieldExpression":
434
+ return 2
435
+ case "Identifier":
436
+ return is_constant_reference(node) ? 0 : 1
437
+ case "ThisExpression":
438
+ return 1
439
+ case "NewExpression":
440
+ return is_safe_construction(node) ? 1 : 2
441
+ case "Property":
442
+ return node.computed
443
+ ? Math.max(
444
+ classify(node.key),
445
+ classify(node.value)
446
+ )
447
+ : classify(node.value)
448
+ case "TSAsExpression":
449
+ case "TSNonNullExpression":
450
+ case "TSSatisfiesExpression":
451
+ case "TSTypeAssertion":
452
+ return classify(node.expression)
453
+ case "UnaryExpression":
454
+ if (node.operator == "delete") {
455
+ return 2
456
+ }
457
+ break
458
+ }
459
+ let level = 0
460
+ some_child(
461
+ node,
462
+ child => {
463
+ level = Math.max(level, classify(child))
464
+ return level == 2
465
+ }
466
+ )
467
+ return level
468
+ }
469
+ /**
470
+ * @param {import("../../private.js").OrderNode} node
471
+ * @returns {number}
472
+ */
473
+ function classify_pattern(node) {
474
+ return node.type == "MemberExpression" || node.type == "AssignmentPattern" && classify(node.right) || some_child(
475
+ node,
476
+ child => classify_pattern(child) == 2
477
+ )
478
+ ? 2
479
+ : 1
480
+ }
481
+ /**
482
+ * @param {import("estree").Program} program
483
+ * @returns {void}
484
+ */
485
+ function collect_default_exports(program) {
486
+ for (const statement of program.body) {
487
+ if (statement.type == "ExportDefaultDeclaration" && statement.declaration.type == "Identifier") {
488
+ default_exports.add(statement.declaration.name)
489
+ } else if (statement.type == "ExportNamedDeclaration" && !statement.source) {
490
+ for (const specifier of statement.specifiers) {
491
+ if (get_name(specifier.exported) == "default") {
492
+ default_exports.add(get_name(specifier.local))
493
+ }
494
+ }
495
+ }
496
+ }
497
+ }
498
+ /**
499
+ * @param {import("../../private.js").OrderNode | null} node
500
+ * @param {string[]} names
501
+ * @returns {string[]}
502
+ */
503
+ function collect_targets(node, names) {
504
+ switch (node?.type) {
505
+ case "ArrayPattern":
506
+ for (const element of node.elements) {
507
+ collect_targets(element, names)
508
+ }
509
+ break
510
+ case "AssignmentPattern":
511
+ collect_targets(node.left, names)
512
+ break
513
+ case "Identifier":
514
+ names.push(node.name)
515
+ break
516
+ case "ObjectPattern":
517
+ for (const property of node.properties) {
518
+ collect_targets(property, names)
519
+ }
520
+ break
521
+ case "Property":
522
+ collect_targets(node.value, names)
523
+ break
524
+ case "RestElement":
525
+ collect_targets(node.argument, names)
526
+ break
527
+ }
528
+ return names
529
+ }
530
+ /**
531
+ * @param {import("estree").NewExpression} node
532
+ * @returns {unknown}
533
+ */
534
+ function construct(node) {
535
+ const callee = node.callee
536
+ if (callee.type != "Identifier" || !safe_constructors.has(callee.name) || !is_global(callee)) {
537
+ return not_static
538
+ }
539
+ const args = node.arguments.map(static_value)
540
+ if (
541
+ args.includes(not_static)
542
+ || (callee.name.includes("Array") || callee.name == "DataView") && args.some(is_large)
543
+ || callee.name == "RegExp" && !is_portable_regexp(args)
544
+ ) {
545
+ return not_static
546
+ }
547
+ try {
548
+ return new (/** @type {new (...values: unknown[]) => unknown} */(/** @type {Record<string, unknown>} */(/** @type {unknown} */(globalThis))/**/[callee.name])/**/)(...args)
549
+ } catch {
550
+ return not_static
551
+ }
552
+ }
553
+ /**
554
+ * @param {Parameters<typeof verify>} check
555
+ * @returns {void}
556
+ */
557
+ function defer(...check) {
558
+ pending.push(check)
559
+ }
560
+ /**
561
+ * @param {import("../../private.js").OrderNode} node
562
+ * @returns {number}
563
+ */
564
+ function get_condition_rank(node) {
565
+ const name = get_key_name(node)
566
+ return name == "types"
567
+ ? 0
568
+ : name == "default"
569
+ ? 2
570
+ : 1
571
+ }
572
+ /**
573
+ * @param {import("../../private.js").OrderNode} statement
574
+ * @returns {import("estree").Identifier | null | undefined}
575
+ */
576
+ function get_function_id(statement) {
577
+ const node = statement.type == "ExportNamedDeclaration" ? statement.declaration : statement
578
+ return node?.type == "FunctionDeclaration" || node?.type == "TSDeclareFunction"
579
+ ? node.id
580
+ : undefined
581
+ }
582
+ /**
583
+ * @param {import("../../private.js").OrderNode} statement
584
+ * @returns {import("estree").Literal | undefined}
585
+ */
586
+ function get_import_source(statement) {
587
+ return statement.type == "ImportDeclaration" && statement.specifiers.length
588
+ ? statement.source
589
+ : undefined
590
+ }
591
+ /**
592
+ * @param {import("../../private.js").OrderNode} node
593
+ * @returns {string | undefined}
594
+ */
595
+ function get_key_name(node) {
596
+ const type = node.type
597
+ if (type != "Property" && type != "TSMethodSignature" && type != "TSPropertySignature") {
598
+ return undefined
599
+ }
600
+ return node.computed && node.key.type != "Literal" ? undefined : get_name(node.key)
601
+ }
602
+ /**
603
+ * @param {import("../../private.js").OrderNode} node
604
+ * @returns {string | undefined}
605
+ */
606
+ function get_specifier_name(node) {
607
+ if (node.type == "ImportSpecifier") {
608
+ return get_name(node.imported)
609
+ }
610
+ return node.type == "ExportSpecifier" ? get_name(node.local) : undefined
611
+ }
612
+ /**
613
+ * @param {import("../../private.js").OrderNode} statement
614
+ * @returns {import("estree").Literal | import("estree").TemplateLiteral | undefined}
615
+ */
616
+ function get_test_title(statement) {
617
+ const call = statement.type == "ExpressionStatement" ? statement.expression : undefined
618
+ if (call?.type != "CallExpression") {
619
+ return undefined
620
+ }
621
+ let callee = call.callee
622
+ while (callee.type == "MemberExpression" && !callee.computed) {
623
+ callee = callee.object
624
+ }
625
+ const title = call.arguments[0]
626
+ if (callee.type != "Identifier" || !test_functions.has(callee.name)) {
627
+ return undefined
628
+ }
629
+ return title?.type == "Literal" && typeof title.value == "string" || title?.type == "TemplateLiteral"
630
+ ? title
631
+ : undefined
632
+ }
633
+ /**
634
+ * @param {import("estree").Identifier} node
635
+ * @returns {boolean}
636
+ */
637
+ function is_constant_binding(node) {
638
+ const scope = context.sourceCode.getScope(node)
639
+ const variable = scope.references.find(
640
+ reference => reference.identifier == node
641
+ )?.resolved
642
+ if (!variable?.defs.length) {
643
+ return constant_globals.has(node.name) && is_global(node)
644
+ }
645
+ if (variable.defs.length > 1) {
646
+ return false
647
+ }
648
+ const def = /** @type {import("eslint").Scope.Definition} */(variable.defs[0])/**/
649
+ switch (def.type) {
650
+ case "ClassName":
651
+ return variable.references.every(
652
+ reference => !reference.isWrite()
653
+ ) && is_initialized_before(node, scope, variable, def.node)
654
+ case "FunctionName":
655
+ return variable.references.every(
656
+ reference => !reference.isWrite()
657
+ )
658
+ case "ImportBinding":
659
+ return def.node.type == "ImportNamespaceSpecifier"
660
+ case "Variable":
661
+ return def.parent.kind == "const" && is_initialized_before(node, scope, variable, def.node)
662
+ }
663
+ return false
664
+ }
665
+ /**
666
+ * @param {import("estree").Identifier} node
667
+ * @returns {boolean}
668
+ */
669
+ function is_constant_reference(node) {
670
+ /** @type {import("../../private.js").OrderNode} */
671
+ let child = node
672
+ /** @type {import("../../private.js").OrderNode | null} */
673
+ let parent = /** @type {import("eslint").Rule.Node} */(node)/**/.parent
674
+ while (parent && type_wrappers.has(parent.type)) {
675
+ child = parent
676
+ parent = /** @type {import("eslint").Rule.Node} */(/** @type {unknown} */(parent))/**/.parent
677
+ }
678
+ return !!parent && passes_through(parent, child) && is_constant_binding(node)
679
+ }
680
+ /**
681
+ * @param {import("estree").Identifier} node
682
+ * @returns {boolean}
683
+ */
684
+ function is_global(node) {
685
+ let scope = context.sourceCode.getScope(node)
686
+ while (scope.upper && !scope.set.has(node.name)) {
687
+ scope = scope.upper
688
+ }
689
+ return !scope.set.get(node.name)?.defs.length
690
+ }
691
+ /**
692
+ * @param {import("estree").Identifier} node
693
+ * @param {import("eslint").Scope.Scope} scope
694
+ * @param {import("eslint").Scope.Variable} variable
695
+ * @param {import("estree").Node} declaration
696
+ * @returns {boolean}
697
+ */
698
+ function is_initialized_before(node, scope, variable, declaration) {
699
+ const parent = /** @type {import("eslint").Rule.Node} */(declaration)/**/.parent
700
+ if (
701
+ parent?.type == "SwitchCase"
702
+ || parent?.parent?.type == "SwitchCase"
703
+ || /** @type {[number, number]} */(node.range)/**/[0] < /** @type {[number, number]} */(declaration.range)/**/[1]
704
+ ) {
705
+ return false
706
+ }
707
+ for (let current = /** @type {import("eslint").Scope.Scope | null} */(scope)/**/; current && current != variable.scope; current = current.upper) {
708
+ if (current.block.type == "FunctionDeclaration") {
709
+ return false
710
+ }
711
+ }
712
+ return true
713
+ }
714
+ /**
715
+ * @param {import("../../private.js").OrderNode} node
716
+ * @returns {boolean}
717
+ */
718
+ function is_package_condition(node) {
719
+ if (!/(?:^|[/\\])package\.json$/.test(context.filename)) {
720
+ return false
721
+ }
722
+ let parent = /** @type {import("eslint").Rule.Node} */(node)/**/.parent
723
+ while (parent && parent.type != "Program") {
724
+ const name = get_key_name(parent)
725
+ if (name == "exports" || name == "imports") {
726
+ return true
727
+ }
728
+ parent = parent.parent
729
+ }
730
+ return false
731
+ }
732
+ /**
733
+ * @param {import("estree").NewExpression} node
734
+ * @returns {boolean}
735
+ */
736
+ function is_safe_construction(node) {
737
+ return construct(node) !== not_static
738
+ }
739
+ /**
740
+ * @param {import("../../private.js").OrderNode} node
741
+ * @param {(child: import("../../private.js").OrderNode) => boolean} predicate
742
+ * @returns {boolean}
743
+ */
744
+ function some_child(node, predicate) {
745
+ for (const key of visitor_keys[node.type] ?? []) {
746
+ const value = /** @type {Record<string, import("../../private.js").OrderNode | import("../../private.js").OrderNode[] | null | undefined>} */(/** @type {unknown} */(node))/**/[key]
747
+ for (const child of Array.isArray(value) ? value : [ value ]) {
748
+ if (child?.type && predicate(child)) {
749
+ return true
750
+ }
751
+ }
752
+ }
753
+ return false
754
+ }
755
+ /**
756
+ * @param {import("../../private.js").OrderNode} node
757
+ * @returns {unknown}
758
+ */
759
+ function static_value(node) {
760
+ switch (node.type) {
761
+ case "ArrayExpression": {
762
+ const values = node.elements.map(
763
+ element => element ? static_value(element) : undefined
764
+ )
765
+ return values.includes(not_static) ? not_static : values
766
+ }
767
+ case "Identifier":
768
+ return constant_globals.has(node.name) && is_global(node)
769
+ ? /** @type {Record<string, unknown>} */(/** @type {unknown} */(globalThis))/**/[node.name]
770
+ : not_static
771
+ case "Literal":
772
+ return "regex" in node && node.value === null ? not_static : node.value
773
+ case "NewExpression":
774
+ return construct(node)
775
+ case "ObjectExpression": {
776
+ /** @type {Record<string, unknown>} */
777
+ const object = {}
778
+ for (const property of node.properties) {
779
+ if (property.type != "Property" || property.kind != "init" || property.computed || property.shorthand) {
780
+ return not_static
781
+ }
782
+ const value = static_value(property.value)
783
+ if (value === not_static) {
784
+ return not_static
785
+ }
786
+ object[String(get_name(property.key))] = value
787
+ }
788
+ return object
789
+ }
790
+ case "TSAsExpression":
791
+ case "TSSatisfiesExpression":
792
+ return static_value(node.expression)
793
+ case "TemplateLiteral":
794
+ return node.expressions.length ? not_static : node.quasis[0]?.value.cooked
795
+ case "UnaryExpression":
796
+ return node.operator == "-" && node.argument.type == "Literal"
797
+ ? -(/** @type {number} */(node.argument.value)/**/)
798
+ : not_static
799
+ }
800
+ return not_static
801
+ }
802
+ /**
803
+ * @param {import("../../private.js").OrderNode[]} nodes
804
+ * @param {(node: import("../../private.js").OrderNode) => string | undefined} get_node_name
805
+ * @param {"conditions" | "keys" | "names"} message_id
806
+ * @param {import("../../private.js").OrderLayout} layout
807
+ * @param {((node: import("../../private.js").OrderNode) => number)=} get_level
808
+ * @param {((node: import("../../private.js").OrderNode) => number)=} get_rank
809
+ * @returns {void}
810
+ */
811
+ function verify_nodes(
812
+ nodes,
813
+ get_node_name,
814
+ message_id,
815
+ layout,
816
+ get_level,
817
+ get_rank
818
+ ) {
819
+ /** @type {import("../../private.js").OrderEntry[]} */
820
+ let entries = []
821
+ for (const node of [ ...nodes, null ]) {
822
+ const name = node && get_node_name(node)
823
+ if (name != null) {
824
+ entries.push(
825
+ {
826
+ first: /** @type {import("../../private.js").OrderNode} */(node)/**/,
827
+ last: /** @type {import("../../private.js").OrderNode} */(node)/**/,
828
+ name,
829
+ rank: get_rank?.(
830
+ /** @type {import("../../private.js").OrderNode} */(node)/**/
831
+ ),
832
+ report: (/** @type {import("../../private.js").OrderNode & { key?: import("../../private.js").OrderNode }} */(node)/**/).key ?? /** @type {import("../../private.js").OrderNode} */(node)/**/
833
+ }
834
+ )
835
+ } else {
836
+ if (entries.length > 1) {
837
+ defer(
838
+ entries,
839
+ message_id,
840
+ layout,
841
+ get_level
842
+ )
843
+ }
844
+ entries = []
845
+ }
846
+ }
847
+ }
848
+ /**
849
+ * @param {import("../../private.js").OrderNode & { type: "BlockStatement" | "Program" | "StaticBlock" | "TSModuleBlock" }} node
850
+ * @returns {void}
851
+ */
852
+ function verify_statements(node) {
853
+ if (!check_declarations && !check_imports && !check_tests) {
854
+ return
855
+ }
856
+ /** @type {import("../../private.js").OrderEntry[]} */
857
+ let entries = []
858
+ /** @type {"declarations" | "imports" | "tests" | undefined} */
859
+ let kind
860
+ for (const statement of [ ...node.body, null ]) {
861
+ let id = statement && check_declarations ? get_function_id(statement) : undefined
862
+ if (node.type == "Program" && default_exports.has(id?.name)) {
863
+ id = undefined
864
+ }
865
+ const source = statement && check_imports ? get_import_source(statement) : undefined
866
+ const title = statement && check_tests && !id ? get_test_title(statement) : undefined
867
+ const report = id ?? source ?? title
868
+ const name = report && get_name(report)
869
+ const next_kind = name == null
870
+ ? undefined
871
+ : id
872
+ ? "declarations"
873
+ : source
874
+ ? "imports"
875
+ : "tests"
876
+ const last = entries[entries.length - 1]
877
+ if (id && last && kind == next_kind && last.name == name) {
878
+ last.last = /** @type {import("../../private.js").OrderNode} */(statement)/**/
879
+ continue
880
+ }
881
+ if (kind != next_kind) {
882
+ if (kind && entries.length > 1) {
883
+ defer(entries, kind, "statement")
884
+ }
885
+ entries = []
886
+ kind = next_kind
887
+ }
888
+ if (name != null) {
889
+ entries.push(
890
+ {
891
+ first: /** @type {import("../../private.js").OrderNode} */(statement)/**/,
892
+ last: /** @type {import("../../private.js").OrderNode} */(statement)/**/,
893
+ name,
894
+ report: /** @type {import("../../private.js").OrderNode} */(report)/**/
895
+ }
896
+ )
897
+ }
898
+ }
899
+ }
900
+ /** @type {import("../../private.js").OrderRuleListener} */
901
+ const listener = {
902
+ BlockStatement: verify_statements,
903
+ ExportNamedDeclaration: node => {
904
+ if (check_names) {
905
+ verify_nodes(
906
+ node.specifiers,
907
+ get_specifier_name,
908
+ "names",
909
+ "sequence"
910
+ )
911
+ }
912
+ },
913
+ ImportDeclaration: node => {
914
+ if (check_names) {
915
+ verify_nodes(
916
+ node.specifiers,
917
+ get_specifier_name,
918
+ "names",
919
+ "sequence"
920
+ )
921
+ }
922
+ },
923
+ ObjectExpression: node => {
924
+ if (!check_keys) {
925
+ return
926
+ }
927
+ const condition = is_package_condition(node)
928
+ verify_nodes(
929
+ node.properties,
930
+ get_key_name,
931
+ condition ? "conditions" : "keys",
932
+ "sequence",
933
+ classify,
934
+ condition ? get_condition_rank : undefined
935
+ )
936
+ },
937
+ ObjectPattern: node => {
938
+ if (check_keys) {
939
+ /** @type {Map<import("../../private.js").OrderNode, string[]>} */
940
+ const targets = new Map()
941
+ /** @type {Set<string>} */
942
+ const seen = new Set()
943
+ /** @type {Set<string>} */
944
+ const repeated = new Set()
945
+ for (const property of node.properties) {
946
+ const names = collect_targets(property, [])
947
+ for (const name of new Set(names)) {
948
+ if (seen.has(name)) {
949
+ repeated.add(name)
950
+ }
951
+ seen.add(name)
952
+ }
953
+ targets.set(property, names)
954
+ }
955
+ verify_nodes(
956
+ node.properties,
957
+ get_key_name,
958
+ "keys",
959
+ "sequence",
960
+ property => targets.get(property)?.some(name => repeated.has(name))
961
+ ? 2
962
+ : classify_pattern(property)
963
+ )
964
+ }
965
+ },
966
+ Program: node => {
967
+ collect_default_exports(node)
968
+ verify_statements(node)
969
+ },
970
+ "Program:exit": () => {
971
+ for (let i = pending.length - 1; i >= 0; i--) {
972
+ verify(
973
+ .../** @type {Parameters<typeof verify>} */(pending[i])/**/
974
+ )
975
+ }
976
+ },
977
+ StaticBlock: verify_statements,
978
+ TSInterfaceBody: node => {
979
+ if (check_keys) {
980
+ verify_nodes(
981
+ node.body,
982
+ get_key_name,
983
+ "keys",
984
+ "member"
985
+ )
986
+ }
987
+ },
988
+ TSModuleBlock: verify_statements,
989
+ TSTypeLiteral: node => {
990
+ if (check_keys) {
991
+ verify_nodes(
992
+ node.members,
993
+ get_key_name,
994
+ "keys",
995
+ "member"
996
+ )
997
+ }
998
+ }
999
+ }
1000
+ return /** @type {import("eslint").Rule.RuleListener} */(/** @type {unknown} */(listener))/**/
1001
+ },
1002
+ meta: {
1003
+ docs: {
1004
+ description: "Enforces ASCII order of import statements, import and export names, object keys, function declarations and test cases.",
1005
+ recommended: true,
1006
+ url: "https://github.com/artxe/lube-series/blob/master/packages/eslint-plugin-lube/docs/ascii-order.md"
1007
+ },
1008
+ fixable: "code",
1009
+ messages: {
1010
+ conditions: "Move condition \"{{name}}\" before \"{{previous}}\" to keep \"types\" first, \"default\" last and the others in ASCII order{{reason}}",
1011
+ declarations: "Move function \"{{name}}\" before \"{{previous}}\" to keep functions in ASCII order{{reason}}",
1012
+ imports: "Move the import of \"{{name}}\" before \"{{previous}}\" to keep imports in ASCII order{{reason}}",
1013
+ keys: "Move key \"{{name}}\" before \"{{previous}}\" to keep keys in ASCII order{{reason}}",
1014
+ names: "Move \"{{name}}\" before \"{{previous}}\" to keep names in ASCII order{{reason}}",
1015
+ tests: "Move test \"{{name}}\" before \"{{previous}}\" to keep tests in ASCII order{{reason}}"
1016
+ },
1017
+ schema: [
1018
+ {
1019
+ additionalProperties: false,
1020
+ properties: {
1021
+ checkDeclarations: { default: true, type: "boolean" },
1022
+ checkImports: { default: true, type: "boolean" },
1023
+ checkKeys: { default: true, type: "boolean" },
1024
+ checkNames: { default: true, type: "boolean" },
1025
+ checkTests: { default: true, type: "boolean" }
1026
+ },
1027
+ type: "object"
1028
+ }
1029
+ ],
1030
+ type: "suggestion"
1031
+ }
1032
+ }