-
Notifications
You must be signed in to change notification settings - Fork 498
/
Copy pathenforce-ui-strings-as-const.ts
69 lines (60 loc) · 2.14 KB
/
enforce-ui-strings-as-const.ts
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
// Copyright 2025 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Rule to check ES import usage
* @author Ergün Erdoğmuş
*/
import {createRule} from './utils/ruleCreator.ts';
export default createRule({
name: 'enforce-ui-strings-as-const',
meta: {
type: 'suggestion',
messages: {
invalidUIStringsObject: 'Add `as const` to UIStrings constant object.',
},
docs: {
description: 'Enforce `as const` for UIStrings constant objects.',
category: 'Best Practices',
},
fixable: 'code',
schema: [], // no options
},
defaultOptions: [],
create: function(context) {
return {
VariableDeclaration(node) {
if (node.kind !== 'const') {
return;
}
// We only care about the declaration `const UIStrings = {}`
// and there can't be multiple declarations while defining it.
if (node.declarations.length !== 1) {
return;
}
const declaration = node.declarations[0];
const declarationId = declaration.id;
const declarationInit = declaration.init;
// We look for `startsWith` because we want to capture other variations as well
// such as `UIStringsNotTranslate` from the AIAssistancePanel.
const isIdentifierUIStrings = declarationId.type === 'Identifier' && declarationId.name.startsWith('UIStrings');
const isObjectExpressionWithoutAsConst = declarationInit?.type === 'ObjectExpression';
if (!isIdentifierUIStrings || !isObjectExpressionWithoutAsConst) {
return;
}
// If we reached here, it's a `const UIStrings... = {}` without `as const`.
context.report({
node: declaration, // Report on the whole declaration for context
messageId: 'invalidUIStringsObject',
fix: fixer => {
const objectEnd = declarationInit.range[1];
return fixer.insertTextAfterRange(
[objectEnd - 1, objectEnd],
' as const',
);
},
});
},
};
},
});