-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathrule-utils.ts
More file actions
950 lines (818 loc) · 28.4 KB
/
rule-utils.ts
File metadata and controls
950 lines (818 loc) · 28.4 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
import {
Visitor,
Location,
Position,
hasERBOutput,
isEffectivelyStatic,
getValidatableStaticContent,
getAttributeName,
getStaticAttributeValue,
hasDynamicAttributeNameOnAttribute as hasDynamicAttributeName,
getCombinedAttributeNameString,
getAttributeValueNodes,
getAttributeValue,
forEachAttribute,
} from "@herb-tools/core"
import type {
HTMLAttributeNameNode,
HTMLAttributeNode,
HTMLElementNode,
HTMLOpenTagNode,
LexResult,
Token,
Node
} from "@herb-tools/core"
import { DEFAULT_LINT_CONTEXT } from "../types.js"
import type * as Nodes from "@herb-tools/core"
import type { UnboundLintOffense, LintContext, LintSeverity, BaseAutofixContext } from "../types.js"
export enum ControlFlowType {
CONDITIONAL,
LOOP
}
/**
* Base visitor class that provides common functionality for rule visitors
*/
export abstract class BaseRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> extends Visitor {
public readonly offenses: UnboundLintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
super()
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create an unbound lint offense (without severity).
* The Linter will bind severity based on the rule's config.
*/
protected createOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): UnboundLintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
autofixContext,
severity,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): void {
this.offenses.push(this.createOffense(message, location, autofixContext, severity))
}
}
/**
* Mixin that adds control flow tracking capabilities to rule visitors
* This allows rules to track state across different control flow structures
* like if/else branches, loops, etc.
*
* @template TAutofixContext - Type for autofix context (node + custom data)
* @template TControlFlowState - Type for state passed between onEnterControlFlow and onExitControlFlow
* @template TBranchState - Type for state passed between onEnterBranch and onExitBranch
*/
export abstract class ControlFlowTrackingVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext, TControlFlowState = any, TBranchState = any> extends BaseRuleVisitor<TAutofixContext> {
protected isInControlFlow: boolean = false
protected currentControlFlowType: ControlFlowType | null = null
/**
* Handle visiting a control flow node with proper scope management
*/
protected handleControlFlowNode(_node: Node, controlFlowType: ControlFlowType, visitChildren: () => void): void {
const wasInControlFlow = this.isInControlFlow
const previousControlFlowType = this.currentControlFlowType
this.isInControlFlow = true
this.currentControlFlowType = controlFlowType
const stateToRestore = this.onEnterControlFlow(controlFlowType, wasInControlFlow)
visitChildren()
this.onExitControlFlow(controlFlowType, wasInControlFlow, stateToRestore)
this.isInControlFlow = wasInControlFlow
this.currentControlFlowType = previousControlFlowType
}
/**
* Handle visiting a branch node (like else, when) with proper scope management
*/
protected startNewBranch(visitChildren: () => void): void {
const stateToRestore = this.onEnterBranch()
visitChildren()
this.onExitBranch(stateToRestore)
}
visitERBIfNode(node: Nodes.ERBIfNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBIfNode(node))
}
visitERBUnlessNode(node: Nodes.ERBUnlessNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBUnlessNode(node))
}
visitERBCaseNode(node: Nodes.ERBCaseNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBCaseNode(node))
}
visitERBCaseMatchNode(node: Nodes.ERBCaseMatchNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBCaseMatchNode(node))
}
visitERBWhileNode(node: Nodes.ERBWhileNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBWhileNode(node))
}
visitERBForNode(node: Nodes.ERBForNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBForNode(node))
}
visitERBUntilNode(node: Nodes.ERBUntilNode): void {
this.handleControlFlowNode(node, ControlFlowType.LOOP, () => super.visitERBUntilNode(node))
}
visitERBBlockNode(node: Nodes.ERBBlockNode): void {
this.handleControlFlowNode(node, ControlFlowType.CONDITIONAL, () => super.visitERBBlockNode(node))
}
visitERBElseNode(node: Nodes.ERBElseNode): void {
this.startNewBranch(() => super.visitERBElseNode(node))
}
visitERBWhenNode(node: Nodes.ERBWhenNode): void {
this.startNewBranch(() => super.visitERBWhenNode(node))
}
protected abstract onEnterControlFlow(controlFlowType: ControlFlowType, wasAlreadyInControlFlow: boolean): TControlFlowState
protected abstract onExitControlFlow(controlFlowType: ControlFlowType, wasAlreadyInControlFlow: boolean, stateToRestore: TControlFlowState): void
protected abstract onEnterBranch(): TBranchState
protected abstract onExitBranch(stateToRestore: TBranchState): void
}
/**
* Common HTML element categorization
*/
export const HTML_INLINE_ELEMENTS = new Set([
"a", "abbr", "acronym", "b", "bdo", "big", "br", "button", "cite", "code",
"dfn", "em", "i", "img", "input", "kbd", "label", "map", "object", "output",
"q", "samp", "script", "select", "small", "span", "strong", "sub", "sup",
"textarea", "time", "tt", "var"
])
export const HTML_BLOCK_ELEMENTS = new Set([
"address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl",
"dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2",
"h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "noscript",
"ol", "p", "pre", "section", "table", "tfoot", "ul", "video"
])
export const HTML_VOID_ELEMENTS = new Set([
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
"param", "source", "track", "wbr",
])
export const HTML_BOOLEAN_ATTRIBUTES = new Set([
"autofocus", "autoplay", "checked", "controls", "defer", "disabled", "hidden",
"loop", "multiple", "muted", "readonly", "required", "reversed", "selected",
"open", "default", "formnovalidate", "novalidate", "itemscope", "scoped",
"seamless", "allowfullscreen", "async", "compact", "declare", "nohref",
"noresize", "noshade", "nowrap", "sortable", "truespeed", "typemustmatch"
])
export const HEADING_TAGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"])
/**
* SVG elements that use camelCase naming
*/
export const SVG_CAMEL_CASE_ELEMENTS = new Set([
"animateMotion",
"animateTransform",
"clipPath",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"foreignObject",
"glyphRef",
"linearGradient",
"radialGradient",
"textPath"
])
/**
* Mapping from lowercase SVG element names to their correct camelCase versions
* Generated dynamically from SVG_CAMEL_CASE_ELEMENTS
*/
export const SVG_LOWERCASE_TO_CAMELCASE = new Map(
Array.from(SVG_CAMEL_CASE_ELEMENTS).map(element => [element.toLowerCase(), element])
)
export const VALID_ARIA_ROLES = new Set([
"banner", "complementary", "contentinfo", "form", "main", "navigation", "region", "search",
"article", "cell", "columnheader", "definition", "directory", "document", "feed", "figure",
"group", "heading", "img", "list", "listitem", "math", "none", "note", "presentation",
"row", "rowgroup", "rowheader", "separator", "table", "term", "tooltip",
"alert", "alertdialog", "button", "checkbox", "combobox", "dialog", "grid", "gridcell", "link",
"listbox", "menu", "menubar", "menuitem", "menuitemcheckbox", "menuitemradio", "option",
"progressbar", "radio", "radiogroup", "scrollbar", "searchbox", "slider", "spinbutton",
"status", "switch", "tab", "tablist", "tabpanel", "textbox", "timer", "toolbar", "tree",
"treegrid", "treeitem",
"log", "marquee"
]);
/**
* Abstract ARIA roles used to support the WAI-ARIA Roles Model.
* Authors MUST NOT use abstract roles in content.
* @see https://www.w3.org/TR/wai-aria-1.0/roles#abstract_roles
*/
export const ABSTRACT_ARIA_ROLES = new Set([
"command",
"composite",
"input",
"landmark",
"range",
"roletype",
"section",
"sectionhead",
"select",
"structure",
"widget",
"window"
]);
/**
* Parameter types for AttributeVisitorMixin methods
*/
export interface StaticAttributeStaticValueParams {
attributeName: string
attributeValue: string
attributeNode: HTMLAttributeNode
originalAttributeName: string
parentNode: HTMLOpenTagNode
}
export interface StaticAttributeDynamicValueParams {
attributeName: string
valueNodes: Node[]
attributeNode: HTMLAttributeNode
originalAttributeName: string
parentNode: HTMLOpenTagNode
combinedValue?: string | null
}
export interface DynamicAttributeStaticValueParams {
nameNodes: Node[]
attributeValue: string
attributeNode: HTMLAttributeNode
parentNode: HTMLOpenTagNode
combinedName?: string
}
export interface DynamicAttributeDynamicValueParams {
nameNodes: Node[]
valueNodes: Node[]
attributeNode: HTMLAttributeNode
parentNode: HTMLOpenTagNode
combinedName?: string
combinedValue?: string | null
}
export const ARIA_ATTRIBUTES = new Set([
'aria-activedescendant',
'aria-atomic',
'aria-autocomplete',
'aria-busy',
'aria-checked',
'aria-colcount',
'aria-colindex',
'aria-colspan',
'aria-controls',
'aria-current',
'aria-describedby',
'aria-details',
'aria-disabled',
'aria-dropeffect',
'aria-errormessage',
'aria-expanded',
'aria-flowto',
'aria-grabbed',
'aria-haspopup',
'aria-hidden',
'aria-invalid',
'aria-keyshortcuts',
'aria-label',
'aria-labelledby',
'aria-level',
'aria-live',
'aria-modal',
'aria-multiline',
'aria-multiselectable',
'aria-orientation',
'aria-owns',
'aria-placeholder',
'aria-posinset',
'aria-pressed',
'aria-readonly',
'aria-relevant',
'aria-required',
'aria-roledescription',
'aria-rowcount',
'aria-rowindex',
'aria-rowspan',
'aria-selected',
'aria-setsize',
'aria-sort',
'aria-valuemax',
'aria-valuemin',
'aria-valuenow',
'aria-valuetext',
])
/**
* Helper function to create a location at the end of the source with a 1-character range
*/
export function createEndOfFileLocation(source: string): Location {
const lines = source.split('\n')
const lastLineNumber = lines.length
const lastLine = lines[lines.length - 1]
const lastColumnNumber = lastLine.length
const startColumn = lastColumnNumber > 0 ? lastColumnNumber - 1 : 0
return Location.from(lastLineNumber, startColumn, lastLineNumber, lastColumnNumber)
}
/**
* Checks if an element is inline
*/
export function isInlineElement(tagName: string): boolean {
return HTML_INLINE_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an element is block-level
*/
export function isBlockElement(tagName: string): boolean {
return HTML_BLOCK_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an element is a void element
*/
export function isVoidElement(tagName: string): boolean {
return HTML_VOID_ELEMENTS.has(tagName.toLowerCase())
}
/**
* Checks if an attribute is a boolean attribute
*/
export function isBooleanAttribute(attributeName: string): boolean {
return HTML_BOOLEAN_ATTRIBUTES.has(attributeName.toLowerCase())
}
/**
* Attribute visitor that provides granular processing based on both
* attribute name type (static/dynamic) and value type (static/dynamic)
*
* This gives you 4 distinct methods to override:
* - checkStaticAttributeStaticValue() - name="class" value="foo"
* - checkStaticAttributeDynamicValue() - name="class" value="<%= css_class %>"
* - checkDynamicAttributeStaticValue() - name="data-<%= key %>" value="foo"
* - checkDynamicAttributeDynamicValue() - name="data-<%= key %>" value="<%= value %>"
*/
export abstract class AttributeVisitorMixin<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> extends BaseRuleVisitor<TAutofixContext> {
constructor(ruleName: string, context?: Partial<LintContext>) {
super(ruleName, context)
}
visitHTMLOpenTagNode(node: HTMLOpenTagNode): void {
this.checkAttributesOnNode(node)
super.visitHTMLOpenTagNode(node)
}
private checkAttributesOnNode(node: HTMLOpenTagNode): void {
forEachAttribute(node, (attributeNode) => {
const staticAttributeName = getAttributeName(attributeNode)
const originalAttributeName = getAttributeName(attributeNode, false) || ""
const isDynamicName = hasDynamicAttributeName(attributeNode)
const staticAttributeValue = getStaticAttributeValue(attributeNode)
const valueNodes = getAttributeValueNodes(attributeNode)
const hasOutputERB = hasERBOutput(valueNodes)
const isEffectivelyStaticValue = isEffectivelyStatic(valueNodes)
if (staticAttributeName && staticAttributeValue !== null) {
this.checkStaticAttributeStaticValue({
attributeName: staticAttributeName,
attributeValue: staticAttributeValue,
attributeNode,
originalAttributeName,
parentNode: node
})
} else if (staticAttributeName && isEffectivelyStaticValue && !hasOutputERB) {
const validatableContent = getValidatableStaticContent(valueNodes) || ""
this.checkStaticAttributeStaticValue({ attributeName: staticAttributeName, attributeValue: validatableContent, attributeNode, originalAttributeName, parentNode: node })
} else if (staticAttributeName && hasOutputERB) {
const combinedValue = getAttributeValue(attributeNode)
this.checkStaticAttributeDynamicValue({ attributeName: staticAttributeName, valueNodes, attributeNode, parentNode: node, originalAttributeName, combinedValue })
} else if (isDynamicName && staticAttributeValue !== null) {
const nameNode = attributeNode.name as HTMLAttributeNameNode
const nameNodes = nameNode.children || []
const combinedName = getCombinedAttributeNameString(attributeNode)
this.checkDynamicAttributeStaticValue({ nameNodes, attributeValue: staticAttributeValue, attributeNode, parentNode: node, combinedName })
} else if (isDynamicName) {
const nameNode = attributeNode.name as HTMLAttributeNameNode
const nameNodes = nameNode.children || []
const combinedName = getCombinedAttributeNameString(attributeNode)
const combinedValue = getAttributeValue(attributeNode)
this.checkDynamicAttributeDynamicValue({ nameNodes, valueNodes, attributeNode, parentNode: node, combinedName, combinedValue })
}
})
}
/**
* Static attribute name with static value: class="container"
*/
protected checkStaticAttributeStaticValue(_params: StaticAttributeStaticValueParams): void {
// Default implementation does nothing
}
/**
* Static attribute name with dynamic value: class="<%= css_class %>"
*/
protected checkStaticAttributeDynamicValue(_params: StaticAttributeDynamicValueParams): void {
// Default implementation does nothing
}
/**
* Dynamic attribute name with static value: data-<%= key %>="foo"
*/
protected checkDynamicAttributeStaticValue(_params: DynamicAttributeStaticValueParams): void {
// Default implementation does nothing
}
/**
* Dynamic attribute name with dynamic value: data-<%= key %>="<%= value %>"
*/
protected checkDynamicAttributeDynamicValue(_params: DynamicAttributeDynamicValueParams): void {
// Default implementation does nothing
}
}
/**
* Base lexer visitor class that provides common functionality for lexer-based rule visitors
*/
export abstract class BaseLexerRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> {
public readonly offenses: UnboundLintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create an unbound lint offense (without severity).
* The Linter will bind severity based on the rule's config.
*/
protected createOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): UnboundLintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
autofixContext,
severity,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): void {
this.offenses.push(this.createOffense(message, location, autofixContext, severity))
}
/**
* Main entry point for lexer rule visitors
* @param lexResult - The lexer result containing tokens and source
*/
visit(lexResult: LexResult): void {
this.visitTokens(lexResult.value.tokens)
}
/**
* Visit all tokens
* Override this method to implement token-level checks
*/
protected visitTokens(tokens: Token[]): void {
for (const token of tokens) {
this.visitToken(token)
}
}
/**
* Visit individual tokens
* Override this method to implement per-token checks
*/
protected visitToken(_token: Token): void {
// Default implementation does nothing
}
}
/**
* Base source visitor class that provides common functionality for source-based rule visitors
*/
export abstract class BaseSourceRuleVisitor<TAutofixContext extends BaseAutofixContext = BaseAutofixContext> {
public readonly offenses: UnboundLintOffense<TAutofixContext>[] = []
protected ruleName: string
protected context: LintContext
constructor(ruleName: string, context?: Partial<LintContext>) {
this.ruleName = ruleName
this.context = { ...DEFAULT_LINT_CONTEXT, ...context }
}
/**
* Helper method to create an unbound lint offense (without severity).
* The Linter will bind severity based on the rule's config.
*/
protected createOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): UnboundLintOffense<TAutofixContext> {
return {
rule: this.ruleName,
code: this.ruleName,
source: "Herb Linter",
message,
location,
autofixContext,
severity,
}
}
/**
* Helper method to add an offense to the offenses array
*/
protected addOffense(message: string, location: Location, autofixContext?: TAutofixContext, severity?: LintSeverity): void {
this.offenses.push(this.createOffense(message, location, autofixContext, severity))
}
/**
* Main entry point for source rule visitors
* @param source - The raw source code
*/
visit(source: string): void {
this.visitSource(source)
}
/**
* Visit the source code directly
* Override this method to implement source-level checks
*/
protected abstract visitSource(source: string): void
}
/**
* Autofix utilities for applying string replacements
*/
/**
* Checks if two locations are equal
* @param a - First location
* @param b - Second location
* @returns true if locations are equal
*/
export function locationsEqual(a: Location, b: Location): boolean {
return a.start.line === b.start.line &&
a.start.column === b.start.column &&
a.end.line === b.end.line &&
a.end.column === b.end.column
}
/**
* Finds a node in the AST that has a specific location
* Uses direct recursive traversal for reliability
* @param root - The root node to search from
* @param location - The location to match
* @param predicate - Optional predicate function to filter nodes (e.g., isERBNode)
* @returns The matching node or null if not found
*/
export function findNodeByLocation(root: Node, location: Location, predicate?: (node: Node) => boolean): any {
const visited = new Set<any>()
function search(node: any): any {
if (!node || visited.has(node)) return null
visited.add(node)
if (node.location && locationsEqual(node.location, location)) {
if (!predicate || predicate(node)) {
return node
}
}
const propsToCheck = ['tag_opening', 'tag_closing', 'tag_name', 'name', 'equals', 'value', 'content']
for (const prop of propsToCheck) {
if (node[prop]?.location && locationsEqual(node[prop].location, location)) {
if (!predicate || predicate(node)) {
return node
}
}
}
if (typeof node.compactChildNodes === 'function') {
for (const child of node.compactChildNodes()) {
const found = search(child)
if (found) return found
}
} else {
if (node.children && Array.isArray(node.children)) {
for (const child of node.children) {
const found = search(child)
if (found) return found
}
}
if (node.body && Array.isArray(node.body)) {
for (const child of node.body) {
const found = search(child)
if (found) return found
}
}
}
return null
}
return search(root)
}
/**
* AST Navigation Utilities
* These utilities help navigate the AST tree for complex autofix operations
*/
/**
* Finds the parent node of a given child node in the AST
* @param root - The root node to search from (typically the document node)
* @param target - The child node to find the parent of
* @returns The parent node, or null if not found
*
* @example
* const parent = findParent(result.value, offense.autofixContext.node)
* if (parent?.type === "AST_HTML_ELEMENT_NODE") {
* // Modify parent...
* }
*/
export function findParent(root: Node, target: Node): Node | null {
let parentNode: Node | null = null
const search = (node: Node, _parent: Node | null = null): void => {
if (parentNode) return
const nodeAny = node as any
if (nodeAny.children) {
for (const child of nodeAny.children) {
if (child === target) {
parentNode = node
return
}
}
}
const propsToCheck = ['open_tag', 'close_tag', 'body', 'name', 'value']
for (const prop of propsToCheck) {
const value = (node as any)[prop]
if (value === target) {
parentNode = node
return
}
if (Array.isArray(value) && value.includes(target)) {
parentNode = node
return
}
}
if (nodeAny.children) {
for (const child of nodeAny.children) {
search(child, node)
if (parentNode) return
}
}
for (const prop of propsToCheck) {
const value = (node as any)[prop]
if (Array.isArray(value)) {
for (const item of value) {
if (item && typeof item === 'object' && 'type' in item) {
search(item, node)
if (parentNode) return
}
}
} else if (value && typeof value === 'object' && 'type' in value) {
search(value, node)
if (parentNode) return
}
}
}
search(root)
return parentNode
}
export const DOCUMENT_ONLY_TAG_NAMES = new Set<string>([
"html"
])
export const HTML_ONLY_TAG_NAMES = new Set<string>([
"head", "body"
])
export const HEAD_ONLY_TAG_NAMES = new Set<string>([
"base",
"title",
"style",
"meta",
"link",
])
export const HEAD_AND_BODY_TAG_NAMES = new Set<string>([
"script",
"noscript",
"template",
])
export function isDocumentOnlyTag(tagName: string): boolean {
return DOCUMENT_ONLY_TAG_NAMES.has(tagName.toLowerCase())
}
export function isHtmlOnlyTag(tagName: string): boolean {
return HTML_ONLY_TAG_NAMES.has(tagName.toLowerCase())
}
export function isHeadOnlyTag(tagName: string): boolean {
return HEAD_ONLY_TAG_NAMES.has(tagName.toLowerCase())
}
export function isHeadAndBodyTag(tagName: string): boolean {
return HEAD_AND_BODY_TAG_NAMES.has(tagName.toLowerCase())
}
export function isBodyOnlyTag(tagName: string): boolean {
const tag = tagName.toLowerCase()
return (
!isDocumentOnlyTag(tag) &&
!isHtmlOnlyTag(tag) &&
!isHeadOnlyTag(tag) &&
!isHeadAndBodyTag(tag)
)
}
export function isBodyTag(tagName: string): boolean {
const tag = tagName.toLowerCase()
return (
!isDocumentOnlyTag(tag) &&
!isHtmlOnlyTag(tag) &&
(isBodyOnlyTag(tag) || isHeadAndBodyTag(tag))
)
}
export function isHeadTag(tagName: string): boolean {
const tag = tagName.toLowerCase()
return (
!isDocumentOnlyTag(tag) &&
!isHtmlOnlyTag(tag) &&
(isHeadOnlyTag(tag) || isHeadAndBodyTag(tag))
)
}
/**
* Converts a character offset in a source string to a Position (line, column).
* Lines are 1-based, columns are 0-based.
*/
export function positionFromOffset(source: string, offset: number): Position {
let line = 1
let column = 0
let currentOffset = 0
for (let i = 0; i < source.length && currentOffset < offset; i++) {
const char = source[i]
currentOffset++
if (char === "\n") {
line++
column = 0
} else {
column++
}
}
return new Position(line, column)
}
/**
* Creates a Location from a source string, a start offset, and a length.
*/
export function locationFromOffset(source: string, startOffset: number, length: number): Location {
const start = positionFromOffset(source, startOffset)
const end = positionFromOffset(source, startOffset + length)
return Location.from(start.line, start.column, end.line, end.column)
}
/**
* Checks if a position (line, column) is within a node's location range.
* @param node - The node to check
* @param line - Line number (1-based)
* @param column - Column number (0-based)
* @returns true if the position is within the node's location
*/
function isPositionInNode(node: Node, line: number, column: number): boolean {
if (!node.location) return false
const { start, end } = node.location
if (line < start.line) return false
if (line === start.line && column < start.column) return false
if (line > end.line) return false
if (line === end.line && column >= end.column) return false
return true
}
/**
* Finds a node in the AST that contains a specific position.
* Returns the deepest (most specific) node that matches the position and optional predicate.
*
* @param root - The root node to search from
* @param line - Line number (1-based)
* @param column - Column number (0-based)
* @param predicate - Optional predicate function to filter nodes
* @returns The matching node or null if not found
*/
export function findNodeAtPosition(root: Node, line: number, column: number, predicate?: (node: Node) => boolean): Node | null {
let bestMatch: Node | null = null
const visited = new Set<Node>()
function search(node: Node): void {
if (!node || visited.has(node)) return
visited.add(node)
if (isPositionInNode(node, line, column)) {
if (!predicate || predicate(node)) {
if (!bestMatch || isMoreSpecific(node, bestMatch)) {
bestMatch = node
}
}
}
const nodeAny = node as any
if (typeof nodeAny.compactChildNodes === 'function') {
for (const child of nodeAny.compactChildNodes()) {
search(child)
}
} else {
if (nodeAny.children && Array.isArray(nodeAny.children)) {
for (const child of nodeAny.children) {
if (child) search(child)
}
}
if (nodeAny.body && Array.isArray(nodeAny.body)) {
for (const child of nodeAny.body) {
if (child) search(child)
}
}
}
}
function isMoreSpecific(nodeA: Node, nodeB: Node): boolean {
if (!nodeA.location || !nodeB.location) return false
const aStart = nodeA.location.start
const aEnd = nodeA.location.end
const bStart = nodeB.location.start
const bEnd = nodeB.location.end
const startsAtOrAfter = aStart.line > bStart.line || (aStart.line === bStart.line && aStart.column >= bStart.column)
const endsAtOrBefore = aEnd.line < bEnd.line || (aEnd.line === bEnd.line && aEnd.column <= bEnd.column)
return startsAtOrAfter && endsAtOrBefore
}
search(root)
return bestMatch
}