diff --git a/src/rules/sort-collections.ts b/src/rules/sort-collections.ts index a47d7a41..f24b09e3 100644 --- a/src/rules/sort-collections.ts +++ b/src/rules/sort-collections.ts @@ -29,6 +29,12 @@ export const rule = createRule({ toSort.includes(key.value) ) { const currentOrder = collection.properties; + const scripts = new Set( + currentOrder.map( + (prop) => (prop.key as AST.JSONStringLiteral).value, + ), + ); + const desiredOrder = currentOrder.slice().sort((a, b) => { let aKey = (a.key as AST.JSONStringLiteral).value; let bKey = (b.key as AST.JSONStringLiteral).value; @@ -38,18 +44,30 @@ export const rule = createRule({ } else { let modifier = 0; - if (aKey.startsWith("pre")) { + if ( + aKey.startsWith("pre") && + scripts.has(aKey.substring(3)) + ) { aKey = aKey.substring(3); modifier -= 1; - } else if (aKey.startsWith("post")) { + } else if ( + aKey.startsWith("post") && + scripts.has(aKey.substring(4)) + ) { aKey = aKey.substring(4); modifier += 1; } - if (bKey.startsWith("pre")) { + if ( + bKey.startsWith("pre") && + scripts.has(bKey.substring(3)) + ) { bKey = bKey.substring(3); modifier += 1; - } else if (bKey.startsWith("post")) { + } else if ( + bKey.startsWith("post") && + scripts.has(bKey.substring(4)) + ) { bKey = bKey.substring(4); modifier -= 1; } diff --git a/src/tests/rules/sort-collections.test.ts b/src/tests/rules/sort-collections.test.ts index 1e04ec9a..17f35567 100644 --- a/src/tests/rules/sort-collections.test.ts +++ b/src/tests/rules/sort-collections.test.ts @@ -112,5 +112,29 @@ ruleTester.run("sort-collections", rule, { filename: "not-a-package.json", options: [["devDependencies"]], }, + { + code: `{ + "scripts": { + "lint": "echo test", + "poster": "echo test" + } +}`, + }, + { + code: `{ + "scripts": { + "pretest": "echo test", + "watch": "echo test" + } +}`, + }, + { + code: `{ + "scripts": { + "postwatch": "echo test", + "pretest": "echo test" + } +}`, + }, ], });