@dloizides/frontend-devtools 1.0.1 → 1.0.2

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 (46) hide show
  1. package/dist/eslint/index.d.mts +77 -0
  2. package/dist/eslint/index.d.ts +77 -0
  3. package/dist/eslint/index.js +2000 -0
  4. package/dist/eslint/index.js.map +1 -0
  5. package/dist/eslint/index.mjs +1990 -0
  6. package/dist/eslint/index.mjs.map +1 -0
  7. package/dist/index.d.mts +71 -0
  8. package/dist/index.d.ts +71 -0
  9. package/dist/index.js +2029 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/index.mjs +2017 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/package.json +6 -1
  14. package/.eslintrc.js +0 -34
  15. package/jest.config.js +0 -24
  16. package/publish.ps1 +0 -107
  17. package/src/eslint/index.ts +0 -16
  18. package/src/eslint/legacy.ts +0 -44
  19. package/src/eslint/plugin.test.ts +0 -60
  20. package/src/eslint/plugin.ts +0 -87
  21. package/src/eslint/rules.behaviour.test.ts +0 -86
  22. package/src/eslint/rules.d.ts +0 -16
  23. package/src/eslint/types.ts +0 -27
  24. package/src/i18n/initI18n.test.ts +0 -101
  25. package/src/i18n/initI18n.ts +0 -109
  26. package/src/index.ts +0 -31
  27. package/src/rules/enforce-function-style.js +0 -278
  28. package/src/rules/enforce-module-structure.js +0 -323
  29. package/src/rules/enforce-route-preload.js +0 -288
  30. package/src/rules/enforce-test-colocation.js +0 -82
  31. package/src/rules/enum-file-isolation.js +0 -149
  32. package/src/rules/i18n-interpolation.js +0 -185
  33. package/src/rules/i18n-param-names.js +0 -119
  34. package/src/rules/no-barrel-companion-file.js +0 -142
  35. package/src/rules/no-duplicate-nav-prefix.js +0 -107
  36. package/src/rules/no-duplicate-shared-patterns.js +0 -166
  37. package/src/rules/no-generated-models-barrel-value-import.js +0 -70
  38. package/src/rules/no-null-check.js +0 -171
  39. package/src/rules/no-optional-undefined.js +0 -99
  40. package/src/rules/no-product-imports-in-shared.js +0 -164
  41. package/src/rules/prefer-const-enum.js +0 -127
  42. package/src/rules/require-stable-hook-args.js +0 -372
  43. package/src/rules/smart-max-lines.js +0 -344
  44. package/tsconfig.json +0 -25
  45. package/tsconfig.test.json +0 -11
  46. package/tsup.config.ts +0 -14
@@ -1,288 +0,0 @@
1
- /**
2
- * Custom ESLint Plugin: Enforce Route Page Preloading
3
- *
4
- * Runs on a preloader file (e.g., src/config/routePreloader.ts) and ensures
5
- * every Expo Router route page in the configured directory has a matching
6
- * dynamic import() expression. This prevents developers from adding new
7
- * route pages without preloading them, which would cause slower navigation.
8
- *
9
- * Reports:
10
- * - missingPreload: route page file has no matching import() in the preloader
11
- * - stalePreload: import path does not match any route page file
12
- * - noImportsFound: preloader file has no dynamic import() expressions at all
13
- */
14
-
15
- import fs from 'fs';
16
- import path from 'path';
17
-
18
- /**
19
- * Recursively discover route page files in the given directory.
20
- *
21
- * A file qualifies as a route page if:
22
- * - It is a .tsx file
23
- * - It is NOT a _layout.tsx file
24
- * - It is NOT inside an excluded directory (e.g., __tests__)
25
- * - If it lives in a directory that already has an index.tsx, only index.tsx
26
- * itself counts (sibling .tsx files are sub-components, not route entries)
27
- * - Direct .tsx files whose name does NOT start with _ are also route pages
28
- */
29
- function discoverRoutePages(baseDir, options) {
30
- const {
31
- excludeFiles = ['_layout.tsx'],
32
- excludeDirs = ['__tests__'],
33
- rootIndexIsRedirect = true,
34
- } = options;
35
-
36
- const routePages = [];
37
-
38
- function walk(dir, relativePrefix) {
39
- let entries;
40
- try {
41
- entries = fs.readdirSync(dir, { withFileTypes: true });
42
- } catch {
43
- return;
44
- }
45
-
46
- for (const entry of entries) {
47
- const fullPath = path.join(dir, entry.name);
48
- const relativePath = path.join(relativePrefix, entry.name);
49
-
50
- if (entry.isDirectory()) {
51
- // Skip excluded directories
52
- if (excludeDirs.includes(entry.name)) continue;
53
-
54
- walk(fullPath, relativePath);
55
- continue;
56
- }
57
-
58
- // Only consider .tsx files
59
- if (!entry.name.endsWith('.tsx')) continue;
60
-
61
- // Skip excluded file names
62
- if (excludeFiles.includes(entry.name)) continue;
63
-
64
- // Skip files starting with _ (e.g., _layout.tsx already excluded above,
65
- // but also any other underscore-prefixed files)
66
- if (entry.name.startsWith('_')) continue;
67
-
68
- // Skip root index if configured as redirect
69
- const normalizedRelative = relativePath.replace(/\\/g, '/');
70
- if (rootIndexIsRedirect && normalizedRelative === 'index.tsx') continue;
71
-
72
- // Strip .tsx extension for the normalized path
73
- const withoutExt = normalizedRelative.replace(/\.tsx$/, '');
74
- routePages.push(withoutExt);
75
- }
76
- }
77
-
78
- walk(baseDir, '');
79
- return routePages;
80
- }
81
-
82
- /**
83
- * Recursively collect all ImportExpression source paths within an AST subtree.
84
- */
85
- function collectImportPaths(node) {
86
- const paths = [];
87
-
88
- function walk(n) {
89
- if (!n || typeof n !== 'object') return;
90
-
91
- if (n.type === 'ImportExpression' && n.source?.type === 'Literal')
92
- paths.push({ value: n.source.value, node: n });
93
-
94
- for (const key of Object.keys(n)) {
95
- if (key === 'parent') continue;
96
- const child = n[key];
97
- if (Array.isArray(child))
98
- child.forEach(walk);
99
- else if (child?.type)
100
- walk(child);
101
- }
102
- }
103
-
104
- walk(node);
105
- return paths;
106
- }
107
-
108
- /**
109
- * Resolve a relative import path to an absolute normalized form,
110
- * then strip the project root prefix to get a project-relative path.
111
- */
112
- function resolveImportToProjectRelative(importPath, fileDir, projectRoot) {
113
- // Resolve relative to the file being linted
114
- const absoluteResolved = path.resolve(fileDir, importPath);
115
- // Make it relative to the project root
116
- const projectRelative = path.relative(projectRoot, absoluteResolved);
117
- // Normalize to forward slashes
118
- return projectRelative.replace(/\\/g, '/');
119
- }
120
-
121
- const enforceRoutePreloadRule = {
122
- meta: {
123
- type: 'problem',
124
- docs: {
125
- description:
126
- 'Ensure every route page in the configured directory has a matching dynamic import() in the preloader file',
127
- category: 'Best Practices',
128
- recommended: true,
129
- },
130
- schema: [
131
- {
132
- type: 'object',
133
- properties: {
134
- routeDir: {
135
- type: 'string',
136
- description:
137
- 'Directory to scan for route pages, relative to project root',
138
- default: 'app/(protected)',
139
- },
140
- excludeFiles: {
141
- type: 'array',
142
- items: { type: 'string' },
143
- description: 'Filename patterns to skip',
144
- default: ['_layout.tsx'],
145
- },
146
- excludeDirs: {
147
- type: 'array',
148
- items: { type: 'string' },
149
- description: 'Directory names to skip',
150
- default: ['__tests__'],
151
- },
152
- rootIndexIsRedirect: {
153
- type: 'boolean',
154
- description:
155
- 'Whether the root index.tsx in routeDir is just a redirect and should be skipped',
156
- default: true,
157
- },
158
- },
159
- additionalProperties: false,
160
- },
161
- ],
162
- messages: {
163
- missingPreload:
164
- 'Route page "{{routeFile}}" is not preloaded. Add: import(\'{{importPath}}\').catch(() => undefined);',
165
- stalePreload:
166
- 'Preload import "{{importPath}}" does not match any route page in {{routeDir}}/. Remove it or add the corresponding route page.',
167
- noImportsFound:
168
- 'Preloader file has no dynamic import() expressions. Add imports for all route pages in {{routeDir}}/.',
169
- },
170
- },
171
-
172
- create(context) {
173
- const options = context.options[0] ?? {};
174
- const routeDir = options.routeDir ?? 'app/(protected)';
175
- const excludeFiles = options.excludeFiles ?? ['_layout.tsx'];
176
- const excludeDirs = options.excludeDirs ?? ['__tests__'];
177
- const rootIndexIsRedirect = options.rootIndexIsRedirect ?? true;
178
-
179
- // Determine project root (directory containing eslint.config.mjs)
180
- const cwd = context.cwd ?? context.getCwd?.() ?? process.cwd();
181
- const projectRoot = cwd;
182
-
183
- // Determine the directory of the file being linted
184
- const filename = context.filename ?? context.getFilename?.();
185
- const fileDir = path.dirname(filename);
186
-
187
- // Discover all route page files
188
- const routeDirAbsolute = path.resolve(projectRoot, routeDir);
189
- const routePages = discoverRoutePages(routeDirAbsolute, {
190
- excludeFiles,
191
- excludeDirs,
192
- rootIndexIsRedirect,
193
- });
194
-
195
- // Build the set of expected normalized paths: "app/(protected)/tenants/index"
196
- const expectedRouteSet = new Set(
197
- routePages.map((rp) => `${routeDir}/${rp}`.replace(/\\/g, '/')),
198
- );
199
-
200
- // Collected during traversal
201
- const importExpressions = []; // { resolvedPath: string, rawPath: string, node: ASTNode }
202
-
203
- return {
204
- // Collect all dynamic import() expressions in the file
205
- ImportExpression(node) {
206
- if (node.source?.type !== 'Literal') return;
207
- const rawPath = node.source.value;
208
- const resolvedPath = resolveImportToProjectRelative(
209
- rawPath,
210
- fileDir,
211
- projectRoot,
212
- );
213
- importExpressions.push({ resolvedPath, rawPath, node });
214
- },
215
-
216
- 'Program:exit'(programNode) {
217
- // If no route pages were discovered, nothing to check
218
- if (expectedRouteSet.size === 0) return;
219
-
220
- // If preloader has zero imports, report a single error
221
- if (importExpressions.length === 0) {
222
- context.report({
223
- node: programNode,
224
- messageId: 'noImportsFound',
225
- data: { routeDir },
226
- });
227
- return;
228
- }
229
-
230
- // Build set of resolved import paths (normalized)
231
- const importedPaths = new Set(
232
- importExpressions.map((i) => i.resolvedPath),
233
- );
234
-
235
- // Check for missing preloads: route pages not covered by any import
236
- for (const routePath of expectedRouteSet) {
237
- if (!importedPaths.has(routePath)) {
238
- // Compute the relative import path from the preloader file to the route
239
- const routeAbsolute = path.resolve(projectRoot, `${routePath}.tsx`);
240
- let relativePath = path.relative(fileDir, routeAbsolute);
241
- // Normalize to forward slashes
242
- relativePath = relativePath.replace(/\\/g, '/');
243
- // Ensure it starts with ./
244
- if (!relativePath.startsWith('.'))
245
- relativePath = `./${relativePath}`;
246
- // Strip .tsx extension
247
- relativePath = relativePath.replace(/\.tsx$/, '');
248
-
249
- context.report({
250
- node: programNode,
251
- messageId: 'missingPreload',
252
- data: {
253
- routeFile: routePath,
254
- importPath: relativePath,
255
- },
256
- });
257
- }
258
- }
259
-
260
- // Check for stale preloads: imports that don't match any route page
261
- for (const { resolvedPath, rawPath, node } of importExpressions) {
262
- // Only flag imports that point into the routeDir
263
- const normalizedRouteDir = routeDir.replace(/\\/g, '/');
264
- if (!resolvedPath.startsWith(normalizedRouteDir)) continue;
265
-
266
- if (!expectedRouteSet.has(resolvedPath))
267
- context.report({
268
- node,
269
- messageId: 'stalePreload',
270
- data: {
271
- importPath: rawPath,
272
- routeDir,
273
- },
274
- });
275
- }
276
- },
277
- };
278
- },
279
- };
280
-
281
- /**
282
- * Export the plugin
283
- */
284
- export default {
285
- rules: {
286
- 'enforce-route-preload': enforceRoutePreloadRule,
287
- },
288
- };
@@ -1,82 +0,0 @@
1
- /**
2
- * Custom ESLint Plugin: Enforce Test Colocation
3
- *
4
- * Flags test files that live in __tests__/ directories instead of being
5
- * co-located next to the source file they test.
6
- *
7
- * Co-located tests are easier to find, easier to maintain, and make it
8
- * obvious which files have test coverage at a glance.
9
- *
10
- * Examples:
11
- * BAD: DataGrid/__tests__/useGridCallbacks.test.ts
12
- * GOOD: DataGrid/hooks/useGridCallbacks.test.ts (next to source)
13
- *
14
- * BAD: lib/api/errors/__tests__/apiError.test.ts
15
- * GOOD: lib/api/errors/apiError.test.ts (next to source)
16
- *
17
- * OK: hooks/useGridCallbacks.test.ts (already co-located)
18
- */
19
-
20
- import { dirname, basename, sep, posix } from 'path';
21
-
22
- const enforceTestColocationRule = {
23
- meta: {
24
- type: 'suggestion',
25
- docs: {
26
- description:
27
- 'Test files should be co-located next to their source file, ' +
28
- 'not placed in a __tests__/ directory.',
29
- category: 'Best Practices',
30
- recommended: true,
31
- },
32
- schema: [],
33
- messages: {
34
- testInTestsDir:
35
- 'Test file "{{fileName}}" is inside a __tests__/ directory. ' +
36
- 'Move it next to its source file for co-location. ' +
37
- 'Suggested: {{suggestedPath}}',
38
- },
39
- },
40
-
41
- create(context) {
42
- return {
43
- Program() {
44
- const filePath = context.filename || context.getFilename();
45
- if (!filePath) return;
46
-
47
- const fileName = basename(filePath);
48
-
49
- // Only check test files
50
- if (!fileName.endsWith('.test.ts') && !fileName.endsWith('.test.tsx'))
51
- return;
52
-
53
- // Normalize path separators for consistent checking
54
- const normalized = filePath.split(sep).join(posix.sep);
55
-
56
- // Check if the file is inside a __tests__/ directory
57
- if (!normalized.includes('/__tests__/')) return;
58
-
59
- // Build the suggested co-located path:
60
- // __tests__/foo.test.ts → ../foo.test.ts (next to source)
61
- const dir = dirname(filePath);
62
- const parentDir = dirname(dir);
63
- const parentDirName = basename(parentDir);
64
-
65
- context.report({
66
- loc: { line: 1, column: 0 },
67
- messageId: 'testInTestsDir',
68
- data: {
69
- fileName,
70
- suggestedPath: `${parentDirName}/${fileName}`,
71
- },
72
- });
73
- },
74
- };
75
- },
76
- };
77
-
78
- export default {
79
- rules: {
80
- 'enforce-test-colocation': enforceTestColocationRule,
81
- },
82
- };
@@ -1,149 +0,0 @@
1
- /**
2
- * Custom ESLint Plugin: Enum File Isolation
3
- *
4
- * Flags exported enums in files that also contain unrelated exports.
5
- * Enums should live in dedicated files (e.g., status.enum.ts or status.ts).
6
- *
7
- * Related helpers (functions/variables/types that reference the enum name)
8
- * are allowed in the same file as the enum.
9
- *
10
- * Examples:
11
- * FLAGGED - enum mixed with unrelated exports:
12
- * export const enum ExportType { Csv = 'csv', Excel = 'excel' }
13
- * export interface TableColumn { ... } // Unrelated to ExportType
14
- *
15
- * FLAGGED - multiple exported enums in one file:
16
- * export const enum ErrorActionType { ... }
17
- * export const enum ErrorSeverity { ... }
18
- *
19
- * NOT FLAGGED - enum with related helpers:
20
- * export const enum MenuStatus { Active = 'active', Inactive = 'inactive' }
21
- * export const menuStatusToLabel = (s: MenuStatus): string => { ... }
22
- */
23
-
24
- const enumFileIsolationRule = {
25
- meta: {
26
- type: 'suggestion',
27
- docs: {
28
- description:
29
- 'Exported enums should live in dedicated files. Only related helpers may share the file.',
30
- category: 'Best Practices',
31
- recommended: true,
32
- },
33
- schema: [],
34
- messages: {
35
- multipleEnums:
36
- 'File contains multiple exported enums ({{enumNames}}). Each enum should have its own dedicated file.',
37
- unrelatedExports:
38
- 'Exported enum "{{enumName}}" is in a file with unrelated exports. Move the enum to a dedicated file (e.g., {{suggestedFile}}) or move unrelated exports elsewhere.',
39
- },
40
- },
41
-
42
- create(context) {
43
- const exportedEnums = [];
44
- const otherExportNodes = [];
45
-
46
- /**
47
- * Collect exported enum declarations.
48
- */
49
- function collectExportedEnum(node) {
50
- // ExportNamedDeclaration > TSEnumDeclaration
51
- if (
52
- node.type === 'ExportNamedDeclaration' &&
53
- node.declaration &&
54
- node.declaration.type === 'TSEnumDeclaration'
55
- ) {
56
- exportedEnums.push({
57
- name: node.declaration.id.name,
58
- node: node.declaration.id,
59
- });
60
- return true;
61
- }
62
- return false;
63
- }
64
-
65
- /**
66
- * Collect non-enum exported declarations.
67
- */
68
- function collectOtherExport(node) {
69
- if (node.type !== 'ExportNamedDeclaration') return;
70
- // Skip if it's an enum (already collected)
71
- if (
72
- node.declaration &&
73
- node.declaration.type === 'TSEnumDeclaration'
74
- )
75
- return;
76
-
77
- otherExportNodes.push(node);
78
- }
79
-
80
- /**
81
- * Check if a source text references an enum name using word boundary.
82
- */
83
- function referencesEnum(sourceText, enumName) {
84
- const regex = new RegExp(`\\b${enumName}\\b`);
85
- return regex.test(sourceText);
86
- }
87
-
88
- return {
89
- ExportNamedDeclaration(node) {
90
- if (!collectExportedEnum(node)) collectOtherExport(node);
91
- },
92
-
93
- 'Program:exit'() {
94
- // No exported enums -> nothing to check
95
- if (exportedEnums.length === 0) return;
96
-
97
- const sourceCode = context.sourceCode || context.getSourceCode();
98
-
99
- // Check for multiple exported enums in the same file
100
- if (exportedEnums.length > 1) {
101
- const enumNames = exportedEnums
102
- .map((e) => e.name)
103
- .join(', ');
104
- for (const enumInfo of exportedEnums) {
105
- context.report({
106
- node: enumInfo.node,
107
- messageId: 'multipleEnums',
108
- data: { enumNames },
109
- });
110
- }
111
- return;
112
- }
113
-
114
- // Single enum - check if other exports are related
115
- const enumName = exportedEnums[0].name;
116
- const enumNode = exportedEnums[0].node;
117
-
118
- // If no other exports, the file is fine
119
- if (otherExportNodes.length === 0) return;
120
-
121
- // Check each other export to see if it references the enum
122
- const unrelatedExports = otherExportNodes.filter((node) => {
123
- const text = sourceCode.getText(node);
124
- return !referencesEnum(text, enumName);
125
- });
126
-
127
- if (unrelatedExports.length > 0) {
128
- // Convert PascalCase to kebab-case for suggested filename
129
- const suggestedFile = enumName
130
- .replace(/([a-z])([A-Z])/g, '$1-$2')
131
- .toLowerCase()
132
- .concat('.ts');
133
-
134
- context.report({
135
- node: enumNode,
136
- messageId: 'unrelatedExports',
137
- data: { enumName, suggestedFile },
138
- });
139
- }
140
- },
141
- };
142
- },
143
- };
144
-
145
- export default {
146
- rules: {
147
- 'enum-file-isolation': enumFileIsolationRule,
148
- },
149
- };
@@ -1,185 +0,0 @@
1
- /**
2
- * Custom ESLint Plugin: i18n Interpolation Placeholder Enforcement
3
- *
4
- * Ensures translation JSON files only use standardized placeholders:
5
- * {{p1}}, {{p2}}, {{p3}} (compatible with the FM() helper).
6
- *
7
- * Detects and autofixes:
8
- * - Non-standard double-brace placeholders: {{message}} → {{p1}}
9
- * - Single-brace placeholders: {p1} → {{p1}}
10
- * - Placeholders exceeding the 3-param FM() limit (error only, no autofix)
11
- */
12
-
13
- const DOUBLE_BRACE_REGEX = /\{\{(\w+)\}\}/g;
14
- const SINGLE_BRACE_REGEX = /(?<!\{)\{(\w+)\}(?!\})/g;
15
- const ALLOWED_NAMES = new Set(['p1', 'p2', 'p3']);
16
- const MAX_POSITIONAL_PARAMS = 3;
17
-
18
- const rule = {
19
- meta: {
20
- type: 'problem',
21
- docs: {
22
- description:
23
- 'Enforce {{p1}}/{{p2}}/{{p3}} interpolation placeholders in translation JSON files',
24
- },
25
- fixable: 'code',
26
- schema: [],
27
- messages: {
28
- nonStandardPlaceholder:
29
- 'Non-standard placeholder "{{placeholder}}" found. Use {{p1}}/{{p2}}/{{p3}} instead.',
30
- singleBracePlaceholder:
31
- 'Single-brace placeholder "{{{placeholder}}}" found. Use double braces: {{{{{fixedName}}}}}.',
32
- tooManyPlaceholders:
33
- 'Translation has {{count}} unique placeholders but FM() only supports 3. Refactor the translation string.',
34
- },
35
- },
36
-
37
- create(context) {
38
- return {
39
- JSONLiteral(node) {
40
- if (typeof node.value !== 'string') return;
41
-
42
- const raw = node.value;
43
-
44
- // Collect all non-standard double-brace placeholders
45
- const doubleBraceMatches = [];
46
- let match;
47
- while ((match = DOUBLE_BRACE_REGEX.exec(raw)) !== null) {
48
- if (!ALLOWED_NAMES.has(match[1]))
49
- doubleBraceMatches.push({ name: match[1], index: match.index });
50
- }
51
-
52
- // Collect single-brace placeholders (any name)
53
- const singleBraceMatches = [];
54
- while ((match = SINGLE_BRACE_REGEX.exec(raw)) !== null)
55
- singleBraceMatches.push({ name: match[1], index: match.index });
56
-
57
- const hasDoubleBraceIssues = doubleBraceMatches.length > 0;
58
- const hasSingleBraceIssues = singleBraceMatches.length > 0;
59
-
60
- if (!hasDoubleBraceIssues && !hasSingleBraceIssues) return;
61
-
62
- // Build ordered mapping of unique placeholder names → p1/p2/p3
63
- const seenNames = [];
64
- const allMatches = [...doubleBraceMatches, ...singleBraceMatches].sort(
65
- (a, b) => a.index - b.index,
66
- );
67
-
68
- for (const m of allMatches) {
69
- if (!seenNames.includes(m.name) && !ALLOWED_NAMES.has(m.name))
70
- seenNames.push(m.name);
71
- }
72
-
73
- // Check if too many unique placeholders
74
- // Count existing valid ones too
75
- const existingValid = new Set();
76
- let m2;
77
- const tempRegex = /\{\{(\w+)\}\}/g;
78
- while ((m2 = tempRegex.exec(raw)) !== null) {
79
- if (ALLOWED_NAMES.has(m2[1])) existingValid.add(m2[1]);
80
- }
81
-
82
- // Also count single-brace valid ones
83
- const tempSingleRegex = /(?<!\{)\{(\w+)\}(?!\})/g;
84
- while ((m2 = tempSingleRegex.exec(raw)) !== null) {
85
- if (ALLOWED_NAMES.has(m2[1])) existingValid.add(m2[1]);
86
- }
87
-
88
- const totalUnique = seenNames.length + existingValid.size;
89
-
90
- if (totalUnique > MAX_POSITIONAL_PARAMS) {
91
- context.report({
92
- node,
93
- messageId: 'tooManyPlaceholders',
94
- data: { count: String(totalUnique) },
95
- });
96
- return;
97
- }
98
-
99
- // Determine the next available positional name
100
- const usedPositional = new Set(existingValid);
101
- const nameMap = {};
102
- const positionalNames = ['p1', 'p2', 'p3'];
103
- let nextIdx = 0;
104
-
105
- // Skip already-used positional names
106
- for (const name of seenNames) {
107
- while (
108
- nextIdx < positionalNames.length &&
109
- usedPositional.has(positionalNames[nextIdx])
110
- )
111
- nextIdx++;
112
-
113
- if (nextIdx < positionalNames.length) {
114
- nameMap[name] = positionalNames[nextIdx];
115
- usedPositional.add(positionalNames[nextIdx]);
116
- nextIdx++;
117
- }
118
- }
119
-
120
- // Report and fix double-brace non-standard placeholders
121
- if (hasDoubleBraceIssues) {
122
- const fixedValue = raw.replace(DOUBLE_BRACE_REGEX, (full, name) => {
123
- if (ALLOWED_NAMES.has(name)) return full;
124
- const replacement = nameMap[name];
125
- return replacement !== undefined ? `{{${replacement}}}` : full;
126
- });
127
-
128
- context.report({
129
- node,
130
- messageId: 'nonStandardPlaceholder',
131
- data: { placeholder: doubleBraceMatches[0].name },
132
- fix(fixer) {
133
- let finalValue = fixedValue;
134
-
135
- // Also fix single-brace issues in the same pass
136
- if (hasSingleBraceIssues)
137
- finalValue = finalValue.replace(
138
- SINGLE_BRACE_REGEX,
139
- (full, name) => {
140
- if (ALLOWED_NAMES.has(name)) return `{{${name}}}`;
141
- const replacement = nameMap[name];
142
- return replacement !== undefined
143
- ? `{{${replacement}}}`
144
- : `{{${name}}}`;
145
- },
146
- );
147
-
148
- return fixer.replaceText(node, JSON.stringify(finalValue));
149
- },
150
- });
151
- } else if (hasSingleBraceIssues) {
152
- // Only single-brace issues
153
- const fixedValue = raw.replace(SINGLE_BRACE_REGEX, (full, name) => {
154
- if (ALLOWED_NAMES.has(name)) return `{{${name}}}`;
155
- const replacement = nameMap[name];
156
- return replacement !== undefined
157
- ? `{{${replacement}}}`
158
- : `{{${name}}}`;
159
- });
160
-
161
- context.report({
162
- node,
163
- messageId: 'singleBracePlaceholder',
164
- data: {
165
- placeholder: singleBraceMatches[0].name,
166
- fixedName: ALLOWED_NAMES.has(singleBraceMatches[0].name)
167
- ? singleBraceMatches[0].name
168
- : nameMap[singleBraceMatches[0].name] ??
169
- singleBraceMatches[0].name,
170
- },
171
- fix(fixer) {
172
- return fixer.replaceText(node, JSON.stringify(fixedValue));
173
- },
174
- });
175
- }
176
- },
177
- };
178
- },
179
- };
180
-
181
- export default {
182
- rules: {
183
- 'i18n-interpolation': rule,
184
- },
185
- };