|
| 1 | +import { LiquidCheckDefinition, Severity, SourceCodeType } from '../../types'; |
| 2 | + |
| 3 | +export const InvalidComparisonSyntax: LiquidCheckDefinition = { |
| 4 | + meta: { |
| 5 | + code: 'InvalidComparisonSyntax', |
| 6 | + name: 'Invalid syntax after comparison operator', |
| 7 | + docs: { |
| 8 | + description: 'Ensures comparison operators in Liquid if statements follow valid syntax', |
| 9 | + recommended: true, |
| 10 | + url: 'https://shopify.dev/docs/storefronts/themes/tools/theme-check/checks/invalid-comparison', |
| 11 | + }, |
| 12 | + type: SourceCodeType.LiquidHtml, |
| 13 | + severity: Severity.ERROR, |
| 14 | + schema: {}, |
| 15 | + targets: [], |
| 16 | + }, |
| 17 | + |
| 18 | + create(context) { |
| 19 | + return { |
| 20 | + async LiquidTag(node) { |
| 21 | + if (node.name !== 'if' && node.name !== 'elsif' && node.name !== 'unless') { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + const markup = node.markup.toString(); |
| 26 | + |
| 27 | + const regex = |
| 28 | + /(>=|<=|>|<|==|!=)\s+([^\s]+)\s+([^\s]+)(?!\s+(and|or|%}|contains|startswith|endswith))/g; |
| 29 | + |
| 30 | + let match; |
| 31 | + while ((match = regex.exec(markup)) !== null) { |
| 32 | + const invalidToken = match[3]; |
| 33 | + |
| 34 | + if (!isValidComparisonConnector(invalidToken)) { |
| 35 | + const invalidTokenOffset = match.index + match[0].lastIndexOf(invalidToken); |
| 36 | + |
| 37 | + const markupStart = node.position.start + node.name.length + 3; |
| 38 | + const startIndex = markupStart + invalidTokenOffset + 1; |
| 39 | + const endIndex = startIndex + invalidToken.length; |
| 40 | + |
| 41 | + context.report({ |
| 42 | + message: `Invalid token '${invalidToken}' after comparison`, |
| 43 | + startIndex, |
| 44 | + endIndex, |
| 45 | + suggest: [ |
| 46 | + { |
| 47 | + message: `Remove '${invalidToken}'`, |
| 48 | + fix: (corrector) => { |
| 49 | + corrector.remove(startIndex, endIndex + 1); |
| 50 | + }, |
| 51 | + }, |
| 52 | + ], |
| 53 | + }); |
| 54 | + } |
| 55 | + } |
| 56 | + }, |
| 57 | + }; |
| 58 | + }, |
| 59 | +}; |
| 60 | + |
| 61 | +function isValidComparisonConnector(token: string): boolean { |
| 62 | + const validConnectors = ['and', 'or', '%}', 'contains', 'startswith', 'endswith']; |
| 63 | + return validConnectors.some((connector) => token.includes(connector)); |
| 64 | +} |
0 commit comments