@dxos/eslint-plugin-rules 0.8.4-main.69d29f4 → 0.8.4-main.6fa680abb7

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.
package/docs/README.md CHANGED
@@ -1,7 +1,5 @@
1
1
  # @dxos/eslint-plugin-rules
2
2
 
3
-
4
-
5
3
  ## Dependency Graph
6
4
 
7
5
  ```mermaid
@@ -28,4 +26,4 @@ linkStyle default stroke:#333,stroke-width:1px
28
26
  ## Dependencies
29
27
 
30
28
  | Module | Direct |
31
- |---|---|
29
+ | ------ | ------ |
package/index.js CHANGED
@@ -5,6 +5,8 @@
5
5
  import comment from './rules/comment.js';
6
6
  import effectSubpathImports from './rules/effect-subpath-imports.js';
7
7
  import header from './rules/header.js';
8
+ import importAsNamespace from './rules/import-as-namespace.js';
9
+ import noBareDotImports from './rules/no-bare-dot-imports.js';
8
10
  import noEffectRunPromise from './rules/no-effect-run-promise.js';
9
11
  import noEmptyPromiseCatch from './rules/no-empty-promise-catch.js';
10
12
  import fs from 'node:fs';
@@ -21,6 +23,8 @@ const plugin = {
21
23
  comment,
22
24
  'effect-subpath-imports': effectSubpathImports,
23
25
  header,
26
+ 'import-as-namespace': importAsNamespace,
27
+ 'no-bare-dot-imports': noBareDotImports,
24
28
  'no-effect-run-promise': noEffectRunPromise,
25
29
  'no-empty-promise-catch': noEmptyPromiseCatch,
26
30
  },
@@ -32,6 +36,8 @@ const plugin = {
32
36
  rules: {
33
37
  'dxos-plugin/effect-subpath-imports': 'error',
34
38
  'dxos-plugin/header': 'error',
39
+ 'dxos-plugin/import-as-namespace': 'error',
40
+ 'dxos-plugin/no-bare-dot-imports': 'error',
35
41
  'dxos-plugin/no-effect-run-promise': 'error',
36
42
  'dxos-plugin/no-empty-promise-catch': 'error',
37
43
  // TODO(dmaretskyi): Turned off due to large number of errors and no auto-fix.
package/moon.yml CHANGED
@@ -1,2 +1,2 @@
1
- type: library
1
+ layer: library
2
2
  language: typescript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/eslint-plugin-rules",
3
- "version": "0.8.4-main.69d29f4",
3
+ "version": "0.8.4-main.6fa680abb7",
4
4
  "homepage": "https://dxos.org",
5
5
  "bugs": "https://github.com/dxos/dxos/issues",
6
6
  "repository": {
@@ -4,9 +4,23 @@
4
4
 
5
5
  import { createRequire } from 'node:module';
6
6
 
7
-
8
7
  const EXCLUDED_EFFECT_PACKAGES = ['@effect/vitest'];
9
8
 
9
+ /**
10
+ * Map of Effect base-package exports that come from a subpath (not a direct segment).
11
+ * Used when resolving imports like `import { pipe } from 'effect'` → effect/Function.
12
+ */
13
+ const EFFECT_EXPORT_TO_SUBPATH = {
14
+ pipe: 'Function',
15
+ flow: 'Function',
16
+ };
17
+
18
+ /**
19
+ * Subpaths that allow named imports (e.g. `import { pipe, flow } from 'effect/Function'`).
20
+ * Other subpaths still require namespace imports.
21
+ */
22
+ const NAMED_IMPORT_ALLOWED_SUBPATHS = new Set(['Function']);
23
+
10
24
  /**
11
25
  * ESLint rule to transform combined imports from 'effect' and '@effect/*'
12
26
  * into subpath imports except for the EXCLUDED_EFFECT_PACKAGES.
@@ -59,6 +73,15 @@ export default {
59
73
  return exported.has(segment);
60
74
  };
61
75
 
76
+ const resolveExportToSegment = (pkgName, exportName) => {
77
+ if (isValidSubpath(pkgName, exportName)) return exportName;
78
+ if (pkgName === 'effect' && EFFECT_EXPORT_TO_SUBPATH[exportName]) {
79
+ const segment = EFFECT_EXPORT_TO_SUBPATH[exportName];
80
+ return isValidSubpath(pkgName, segment) ? segment : null;
81
+ }
82
+ return null;
83
+ };
84
+
62
85
  const isEffectPackage = (source) => {
63
86
  return source === 'effect' || source.startsWith('effect/') || source.startsWith('@effect/');
64
87
  };
@@ -66,7 +89,7 @@ export default {
66
89
  const shouldSkipEffectPackage = (basePackage) => {
67
90
  return EXCLUDED_EFFECT_PACKAGES.includes(basePackage);
68
91
  };
69
-
92
+
70
93
  /**
71
94
  * Get the base package name from a source string.
72
95
  * @param {string} source - The source string to get the base package name from.
@@ -91,11 +114,13 @@ export default {
91
114
  const basePackage = getBasePackage(source);
92
115
  if (shouldSkipEffectPackage(basePackage)) return;
93
116
 
94
- // If it's a subpath import (e.g., 'effect/Schema'), enforce namespace import only.
117
+ // If it's a subpath import (e.g., 'effect/Schema'), enforce namespace import except for allowed subpaths.
95
118
  if (source.startsWith(basePackage + '/')) {
119
+ const segment = source.slice(basePackage.length + 1);
120
+ const allowsNamed = NAMED_IMPORT_ALLOWED_SUBPATHS.has(segment);
96
121
  const isNamespaceOnly =
97
122
  node.specifiers.length === 1 && node.specifiers[0].type === 'ImportNamespaceSpecifier';
98
- if (!isNamespaceOnly) {
123
+ if (!allowsNamed && !isNamespaceOnly) {
99
124
  context.report({
100
125
  node,
101
126
  message: 'Use namespace import for Effect subpaths',
@@ -129,18 +154,22 @@ export default {
129
154
  else regularImports.push(entry);
130
155
  }
131
156
 
132
- // Partition into resolvable vs unresolved specifiers.
157
+ // Partition into resolvable vs unresolved specifiers (resolved entries include segment for fix).
133
158
  const resolvedType = [];
134
159
  const unresolvedType = [];
135
160
  const resolvedRegular = [];
136
161
  const unresolvedRegular = [];
137
162
 
138
- typeImports.forEach((s) =>
139
- isValidSubpath(packageName, s.imported) ? resolvedType.push(s) : unresolvedType.push(s),
140
- );
141
- regularImports.forEach((s) =>
142
- isValidSubpath(packageName, s.imported) ? resolvedRegular.push(s) : unresolvedRegular.push(s),
143
- );
163
+ typeImports.forEach((spec) => {
164
+ const segment = resolveExportToSegment(packageName, spec.imported);
165
+ if (segment) resolvedType.push({ ...spec, segment });
166
+ else unresolvedType.push(spec);
167
+ });
168
+ regularImports.forEach((spec) => {
169
+ const segment = resolveExportToSegment(packageName, spec.imported);
170
+ if (segment) resolvedRegular.push({ ...spec, segment });
171
+ else unresolvedRegular.push(spec);
172
+ });
144
173
 
145
174
  const unresolved = [...unresolvedType, ...unresolvedRegular].map(({ imported }) => imported);
146
175
 
@@ -160,27 +189,55 @@ export default {
160
189
  return null;
161
190
  }
162
191
 
163
- // Prefer regular (value) imports over type imports on duplicates.
164
- const seenResolved = new Set(); // key: `${alias}|${segment}`
165
-
166
- // First, emit value imports and record keys.
167
- resolvedRegular.forEach(({ imported, local }) => {
168
- const alias = imported !== local ? local : imported;
169
- const key = `${alias}|${imported}`;
170
- if (seenResolved.has(key)) return;
171
- seenResolved.add(key);
172
- imports.push(`import * as ${alias} from '${packageName}/${imported}';`);
192
+ // Group resolved imports by segment.
193
+ const bySegment = new Map(); // segment -> { regular: [...], type: [...] }
194
+ resolvedRegular.forEach((entry) => {
195
+ const seg = entry.segment;
196
+ let group = bySegment.get(seg);
197
+ if (!group) {
198
+ group = { regular: [], type: [] };
199
+ bySegment.set(seg, group);
200
+ }
201
+ group.regular.push(entry);
173
202
  });
174
-
175
- // Then, emit type imports only if a value import for the same alias/segment was not emitted.
176
- resolvedType.forEach(({ imported, local }) => {
177
- const alias = imported !== local ? local : imported;
178
- const key = `${alias}|${imported}`;
179
- if (seenResolved.has(key)) return; // skip type if value exists
180
- seenResolved.add(key);
181
- imports.push(`import type * as ${alias} from '${packageName}/${imported}';`);
203
+ resolvedType.forEach((entry) => {
204
+ const seg = entry.segment;
205
+ let group = bySegment.get(seg);
206
+ if (!group) {
207
+ group = { regular: [], type: [] };
208
+ bySegment.set(seg, group);
209
+ }
210
+ group.type.push(entry);
182
211
  });
183
212
 
213
+ for (const [segment, group] of bySegment) {
214
+ const useNamed = NAMED_IMPORT_ALLOWED_SUBPATHS.has(segment);
215
+ const merged = [...group.regular];
216
+ for (const t of group.type) {
217
+ if (!group.regular.some((r) => r.local === t.local)) merged.push(t);
218
+ }
219
+ if (useNamed && merged.length > 0) {
220
+ const specParts = merged.map(({ imported, local }) =>
221
+ imported !== local ? `${imported} as ${local}` : imported,
222
+ );
223
+ imports.push(`import { ${specParts.join(', ')} } from '${packageName}/${segment}';`);
224
+ } else {
225
+ const seen = new Set();
226
+ for (const { imported, local } of merged) {
227
+ const alias = imported !== local ? local : imported;
228
+ if (seen.has(alias)) continue;
229
+ seen.add(alias);
230
+ const isTypeOnly =
231
+ group.type.some((t) => t.imported === imported) &&
232
+ !group.regular.some((r) => r.imported === imported);
233
+ const importStr = isTypeOnly
234
+ ? `import type * as ${alias} from '${packageName}/${segment}';`
235
+ : `import * as ${alias} from '${packageName}/${segment}';`;
236
+ imports.push(importStr);
237
+ }
238
+ }
239
+ }
240
+
184
241
  // If there are unresolved, keep them in a single base import.
185
242
  if (unresolvedType.length || unresolvedRegular.length) {
186
243
  // Prefer value over type for the same local alias when both are present.
@@ -0,0 +1,271 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ const DIRECTIVE_TEXT = '@import-as-namespace';
9
+ const DIRECTIVE_LINE_REGEX = /^\s*\/\/\s*@import-as-namespace\s*$/m;
10
+ const PASCAL_CASE_REGEX = /^[A-Z][a-zA-Z0-9]*$/;
11
+ const TS_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
12
+
13
+ /**
14
+ * ESLint rule to enforce namespace imports for modules annotated with `// @import-as-namespace`.
15
+ *
16
+ * When a module contains the `// @import-as-namespace` directive comment, this rule enforces:
17
+ * - The module filename is PascalCase (e.g. `LanguageModel.ts`).
18
+ * - All imports of the module use namespace form: `import * as LanguageModel from './LanguageModel'`.
19
+ * - The namespace name matches the filename (without extension), or has a `Module` suffix.
20
+ * - Re-exports use namespace form: `export * as LanguageModel from './LanguageModel'`.
21
+ *
22
+ * The `Module` suffix is allowed as an escape hatch when the expected namespace name conflicts
23
+ * with a local declaration in the importing file (e.g., `import * as ObjModule from './Obj'`
24
+ * when the file also exports its own `Obj` interface).
25
+ *
26
+ * @example
27
+ * // In LanguageModel.ts:
28
+ * // @import-as-namespace
29
+ * export const foo = 1;
30
+ *
31
+ * // ❌ Bad (in another file):
32
+ * import { foo } from './LanguageModel';
33
+ * export { foo } from './LanguageModel';
34
+ * export * from './LanguageModel';
35
+ *
36
+ * // ✅ Good:
37
+ * import * as LanguageModel from './LanguageModel';
38
+ * import * as LanguageModelModule from './LanguageModel'; // Also allowed when needed
39
+ * export * as LanguageModel from './LanguageModel';
40
+ */
41
+ export default {
42
+ meta: {
43
+ type: 'problem',
44
+ docs: {
45
+ description: 'enforce namespace imports for modules marked with @import-as-namespace',
46
+ },
47
+ fixable: 'code',
48
+ schema: [],
49
+ messages: {
50
+ filenameMustBePascalCase:
51
+ 'Module marked with @import-as-namespace must have a PascalCase filename. Got: "{{filename}}".',
52
+ mustUseNamespaceImport:
53
+ 'Module "{{source}}" is marked @import-as-namespace. Use: `import * as {{namespace}} from \'{{source}}\'`.',
54
+ namespaceMustMatchFilename: 'Namespace import name "{{actual}}" must match filename "{{expected}}".',
55
+ mustUseNamespaceReexport:
56
+ 'Module "{{source}}" is marked @import-as-namespace. Use: `export * as {{namespace}} from \'{{source}}\'`.',
57
+ },
58
+ },
59
+ create: (context) => {
60
+ const directiveCache = new Map();
61
+
62
+ const fileHasDirective = (filePath) => {
63
+ if (directiveCache.has(filePath)) {
64
+ return directiveCache.get(filePath);
65
+ }
66
+ try {
67
+ const content = fs.readFileSync(filePath, 'utf8');
68
+ const result = DIRECTIVE_LINE_REGEX.test(content);
69
+ directiveCache.set(filePath, result);
70
+ return result;
71
+ } catch {
72
+ directiveCache.set(filePath, false);
73
+ return false;
74
+ }
75
+ };
76
+
77
+ const resolveRelativeImport = (source, currentFile) => {
78
+ if (!source.startsWith('.')) {
79
+ return null;
80
+ }
81
+ const dir = path.dirname(currentFile);
82
+ const resolved = path.resolve(dir, source);
83
+ for (const ext of TS_EXTENSIONS) {
84
+ const filePath = resolved + ext;
85
+ if (fs.existsSync(filePath)) {
86
+ return filePath;
87
+ }
88
+ }
89
+ for (const ext of TS_EXTENSIONS) {
90
+ const filePath = path.join(resolved, 'index' + ext);
91
+ if (fs.existsSync(filePath)) {
92
+ return filePath;
93
+ }
94
+ }
95
+ return null;
96
+ };
97
+
98
+ const namespaceFromSource = (source) => {
99
+ const parts = source.split('/');
100
+ const last = parts[parts.length - 1];
101
+ return last.replace(/\.\w+$/, '');
102
+ };
103
+
104
+ const buildImportFix = (fixer, node, source, expectedNamespace, context) => {
105
+ const fixes = [];
106
+ const importKeyword = node.importKind === 'type' ? 'import type' : 'import';
107
+ fixes.push(fixer.replaceText(node, `${importKeyword} * as ${expectedNamespace} from '${source}';`));
108
+
109
+ try {
110
+ const declaredVars = context.sourceCode.getDeclaredVariables(node);
111
+ for (const variable of declaredVars) {
112
+ for (const ref of variable.references) {
113
+ if (ref.identifier.range[0] >= node.range[0] && ref.identifier.range[1] <= node.range[1]) {
114
+ continue;
115
+ }
116
+ fixes.push(fixer.replaceText(ref.identifier, `${expectedNamespace}.${variable.name}`));
117
+ }
118
+ }
119
+ } catch {
120
+ // Scope analysis unavailable; fix import declaration only.
121
+ }
122
+
123
+ return fixes;
124
+ };
125
+
126
+ return {
127
+ Program: (node) => {
128
+ const comments = context.sourceCode.getAllComments();
129
+ const hasDirective = comments.some(
130
+ (comment) => comment.type === 'Line' && comment.value.trim() === DIRECTIVE_TEXT,
131
+ );
132
+ if (!hasDirective) {
133
+ return;
134
+ }
135
+ const filename = path.basename(context.getFilename());
136
+ const stem = filename.replace(/\.\w+$/, '');
137
+ if (!PASCAL_CASE_REGEX.test(stem)) {
138
+ context.report({
139
+ node,
140
+ messageId: 'filenameMustBePascalCase',
141
+ data: { filename },
142
+ });
143
+ }
144
+ },
145
+
146
+ ImportDeclaration: (node) => {
147
+ const source = String(node.source.value);
148
+ if (!source.startsWith('.')) {
149
+ return;
150
+ }
151
+ if (!node.specifiers || node.specifiers.length === 0) {
152
+ return;
153
+ }
154
+
155
+ const currentFile = context.getFilename();
156
+ const resolved = resolveRelativeImport(source, currentFile);
157
+ if (!resolved) {
158
+ return;
159
+ }
160
+ if (!fileHasDirective(resolved)) {
161
+ return;
162
+ }
163
+
164
+ const expectedNamespace = namespaceFromSource(source);
165
+
166
+ const isNamespaceImport =
167
+ node.specifiers.length === 1 && node.specifiers[0].type === 'ImportNamespaceSpecifier';
168
+
169
+ if (!isNamespaceImport) {
170
+ context.report({
171
+ node,
172
+ messageId: 'mustUseNamespaceImport',
173
+ data: { source, namespace: expectedNamespace },
174
+ fix: (fixer) => buildImportFix(fixer, node, source, expectedNamespace, context),
175
+ });
176
+ return;
177
+ }
178
+
179
+ const actual = node.specifiers[0].local.name;
180
+ const allowedNames = [expectedNamespace, expectedNamespace + 'Module'];
181
+ if (!allowedNames.includes(actual)) {
182
+ context.report({
183
+ node,
184
+ messageId: 'namespaceMustMatchFilename',
185
+ data: { actual, expected: expectedNamespace },
186
+ fix: (fixer) => {
187
+ const importKeyword = node.importKind === 'type' ? 'import type' : 'import';
188
+ return fixer.replaceText(node, `${importKeyword} * as ${expectedNamespace} from '${source}';`);
189
+ },
190
+ });
191
+ }
192
+ },
193
+
194
+ ExportNamedDeclaration: (node) => {
195
+ if (!node.source) {
196
+ return;
197
+ }
198
+ const source = String(node.source.value);
199
+ if (!source.startsWith('.')) {
200
+ return;
201
+ }
202
+
203
+ const currentFile = context.getFilename();
204
+ const resolved = resolveRelativeImport(source, currentFile);
205
+ if (!resolved) {
206
+ return;
207
+ }
208
+ if (!fileHasDirective(resolved)) {
209
+ return;
210
+ }
211
+
212
+ const expectedNamespace = namespaceFromSource(source);
213
+ const exportKeyword = node.exportKind === 'type' ? 'export type' : 'export';
214
+ context.report({
215
+ node,
216
+ messageId: 'mustUseNamespaceReexport',
217
+ data: { source, namespace: expectedNamespace },
218
+ fix: (fixer) => {
219
+ return fixer.replaceText(node, `${exportKeyword} * as ${expectedNamespace} from '${source}';`);
220
+ },
221
+ });
222
+ },
223
+
224
+ ExportAllDeclaration: (node) => {
225
+ if (!node.source) {
226
+ return;
227
+ }
228
+ const source = String(node.source.value);
229
+ if (!source.startsWith('.')) {
230
+ return;
231
+ }
232
+
233
+ const currentFile = context.getFilename();
234
+ const resolved = resolveRelativeImport(source, currentFile);
235
+ if (!resolved) {
236
+ return;
237
+ }
238
+ if (!fileHasDirective(resolved)) {
239
+ return;
240
+ }
241
+
242
+ const expectedNamespace = namespaceFromSource(source);
243
+
244
+ if (node.exported) {
245
+ const actual = node.exported.name;
246
+ const allowedNames = [expectedNamespace, expectedNamespace + 'Module'];
247
+ if (!allowedNames.includes(actual)) {
248
+ context.report({
249
+ node,
250
+ messageId: 'namespaceMustMatchFilename',
251
+ data: { actual, expected: expectedNamespace },
252
+ fix: (fixer) => {
253
+ return fixer.replaceText(node, `export * as ${expectedNamespace} from '${source}';`);
254
+ },
255
+ });
256
+ }
257
+ return;
258
+ }
259
+
260
+ context.report({
261
+ node,
262
+ messageId: 'mustUseNamespaceReexport',
263
+ data: { source, namespace: expectedNamespace },
264
+ fix: (fixer) => {
265
+ return fixer.replaceText(node, `export * as ${expectedNamespace} from '${source}';`);
266
+ },
267
+ });
268
+ },
269
+ };
270
+ },
271
+ };
@@ -0,0 +1,55 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ /**
6
+ * ESLint rule to prevent bare "." or ".." imports.
7
+ * These imports are ambiguous as they don't explicitly show which file is being imported.
8
+ *
9
+ * @example
10
+ * // ❌ Bad
11
+ * import { foo } from '.';
12
+ * import { bar } from '..';
13
+ *
14
+ * // ✅ Good
15
+ * import { foo } from './index';
16
+ * import { bar } from '../index';
17
+ */
18
+ export default {
19
+ meta: {
20
+ type: 'problem',
21
+ docs: {
22
+ description: 'disallow bare "." or ".." in import paths',
23
+ category: 'Best Practices',
24
+ recommended: true,
25
+ },
26
+ fixable: 'code',
27
+ schema: [],
28
+ messages: {
29
+ bareDotImport: 'Use explicit path instead of bare "{{source}}". Consider "{{suggestion}}" instead.',
30
+ },
31
+ },
32
+ create: (context) => {
33
+ return {
34
+ ImportDeclaration: (node) => {
35
+ const source = node.source.value;
36
+
37
+ // Check if the import is exactly "." or ".."
38
+ if (source === '.' || source === '..') {
39
+ context.report({
40
+ node: node.source,
41
+ messageId: 'bareDotImport',
42
+ data: {
43
+ source,
44
+ suggestion: source === '.' ? './index' : '../index',
45
+ },
46
+ fix: (fixer) => {
47
+ const newSource = source === '.' ? './index' : '../index';
48
+ return fixer.replaceText(node.source, `'${newSource}'`);
49
+ },
50
+ });
51
+ }
52
+ },
53
+ };
54
+ },
55
+ };