typescript-plugin-scoped-imports 0.1.1 → 0.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2 - 2026-02-15
4
+
5
+ - Refactor: split plugin internals into `utils/` modules and keep `src/index.ts` focused on tsserver interceptor orchestration.
6
+ - Internal API: adopted parameter-signature convention (`3+` args use typed object params, `1-2` args stay positional) across touched utilities and wiring.
7
+ - Tests: added and expanded unit coverage for module resolution, text change parsing edge cases, and path/scope normalization behavior.
8
+ - Behavior: no public API changes and no scope-rule changes (`parent + descendientes` remains intact).
9
+
3
10
  ## 0.1.1 - 2026-02-13
4
11
 
5
12
  - Fix: alias/private scope validation now resolves canonical module paths, preventing false positives with repeated folder names (e.g. `ScopeTrap`).
package/README.md CHANGED
@@ -1,84 +1,97 @@
1
- # TypeScript Plugin: Scoped Imports
1
+ # typescript-plugin-scoped-imports
2
2
 
3
- TypeScript Language Server plugin para controlar auto-imports basado en el scope del archivo.
3
+ TypeScript Language Service plugin that filters auto-imports from private folders (`__private__`) based on file scope.
4
4
 
5
- ## Estado actual
5
+ ## What it does
6
6
 
7
- Regla validada en esta fase:
7
+ When TypeScript proposes imports (completions, quick fixes, refactors), this plugin blocks imports from `__private__` when the current file is out of scope.
8
8
 
9
- - `__private__` es accesible desde su carpeta padre y subdirectorios.
10
- - Fuera de ese subtree, el plugin bloquea sugerencias y fixes que introduzcan imports privados.
9
+ Current scope rule:
11
10
 
12
- ## Instalacion (workspace)
11
+ - Allowed: parent directory of `__private__` and descendants
12
+ - Blocked: any file outside that subtree
13
+
14
+ ## Installation
13
15
 
14
16
  ```bash
15
- pnpm install
16
- pnpm run build
17
+ npm i -D typescript
18
+ npm i typescript-plugin-scoped-imports
17
19
  ```
18
20
 
19
- Requiere Node.js 20 o superior.
20
-
21
- ## Configuracion
21
+ ## Configuration
22
22
 
23
- En tu `tsconfig.json`:
23
+ In `tsconfig.json`:
24
24
 
25
25
  ```json
26
26
  {
27
27
  "compilerOptions": {
28
28
  "plugins": [
29
29
  {
30
- "name": "typescript-plugin-scoped-imports"
30
+ "name": "typescript-plugin-scoped-imports",
31
+ "debug": false
31
32
  }
32
33
  ]
33
34
  }
34
35
  }
35
36
  ```
36
37
 
37
- Convencion: el plugin considera privados los paths que contengan la carpeta `__private__`.
38
+ `debug` is optional. Set it to `true` to enable verbose plugin debug logs.
39
+
40
+ ## Quick example
41
+
42
+ Structure:
43
+
44
+ ```text
45
+ src/components/gallery/__private__/Item.ts
46
+ src/components/gallery/silbing/nephew/InScope.ts
47
+ src/views/Home.ts
48
+ ```
49
+
50
+ - In `InScope.ts`: importing `Item` from `__private__` is allowed
51
+ - In `Home.ts`: importing `Item` from `__private__` is blocked
52
+
53
+ ## VS Code
54
+
55
+ If you use only the npm plugin, VS Code may require using the workspace TypeScript version to load it.
56
+
57
+ To avoid that, use the wrapper extension:
58
+
59
+ - `packages/typescript-plugin-scoped-imports-vscode`
60
+ - Marketplace: https://marketplace.visualstudio.com/items?itemName=nicovio.typescript-plugin-scoped-imports-vscode
38
61
 
39
- ## Matriz de validacion
62
+ ## Compatibility
40
63
 
41
- La suite automatizada vive en:
64
+ - Node.js: `>=20`
65
+ - TypeScript: `>=4.0.0`
66
+
67
+ ## Troubleshooting
68
+
69
+ If it does not load:
70
+
71
+ 1. Open `TypeScript: Open TS Server log`.
72
+ 2. Look for `PLUGIN LOADING: typescript-plugin-scoped-imports`.
73
+ 3. If missing, check:
74
+ - plugin is installed in the project
75
+ - `tsconfig.json` includes it under `compilerOptions.plugins`
76
+
77
+ ## Known limitations
78
+
79
+ - Privacy convention is based on folder name `__private__`
80
+ - No custom private-pattern configuration yet
81
+
82
+ ## Automated validation
83
+
84
+ Main integration coverage lives in:
42
85
 
43
86
  - `packages/typescript-plugin-scoped-imports/__tests__/integration/tsserver.scoped-imports.spec.ts`
44
87
 
45
- | Caso | Esperado | Resultado |
46
- | --- | --- | --- |
47
- | Carga del plugin en tsserver | Debe loguear `PLUGIN LOADING` | Automatizado |
48
- | Path completion out-of-scope (`Home.tsx` + `@/components/gallery/`) | No sugerir `__private__` | Automatizado |
49
- | Path completion in-scope padre (`ParentComponent.tsx` + `./`) | Sugerir `__private__` | Automatizado |
50
- | Path completion in-scope descendiente (`silbing/index.tsx` + `../`) | Sugerir `__private__` | Automatizado |
51
- | Path completion out-of-scope lateral (`UtilsComponent.tsx` + `../gallery/`) | No sugerir `__private__` | Automatizado |
52
- | CodeFix missing import out-of-scope (`Home.tsx`) | No proponer imports privados | Automatizado |
53
- | CodeFix missing import in-scope padre (`ParentComponent.tsx`) | Proponer import privado valido | Automatizado |
54
- | CodeFix missing import in-scope descendiente (`silbing/nephew/index.tsx`) | Proponer import privado valido | Automatizado |
55
- | Combined fix out-of-scope (`fixMissingImport`) | Sin cambios con `__private__` | Automatizado |
56
- | Combined fix in-scope (`fixMissingImport`) | Con cambios privados validos | Automatizado |
57
- | `getCompletionEntryDetails` bloqueado | Respuesta vacia y log de bloqueo | Automatizado |
58
- | `getEditsForRefactor` smoke | No romper flujo ni introducir `__private__` fuera de scope | Automatizado |
59
- | Riesgo alias por nombre repetido (`views/gallery/ScopeTrap.tsx`) | No filtrar incorrectamente por coincidencia de nombre | Automatizado |
60
-
61
- ## Ejecutar validacion automatizada
62
-
63
- Desde la raiz del workspace:
88
+ Run:
64
89
 
65
90
  ```bash
66
91
  pnpm run build
67
92
  pnpm run test
68
93
  ```
69
94
 
70
- ## Gaps detectados (priorizados)
71
-
72
- No hay gaps abiertos de severidad alta/media en la matriz actual.
73
-
74
- ## Uso en proyecto de prueba
75
-
76
- Ver `examples/test-project/` en la raiz del workspace para un ejemplo de consumo real.
77
-
78
- ## Roadmap
95
+ ## Changelog
79
96
 
80
- - [x] Fase 1: POC y validacion de carga
81
- - [x] Validacion integral de casos de completions y codefixes
82
- - [ ] Fase 2: Reglas contextuales adicionales
83
- - [ ] Fase 3: Configuracion flexible
84
- - [ ] Fase 4: Distribucion y documentacion completa
97
+ See `CHANGELOG.md`.
@@ -0,0 +1,4 @@
1
+ export declare const PRIVATE_FOLDER = "__private__";
2
+ export declare const PRIVATE_SEGMENT = "/__private__/";
3
+ export declare const PRIVATE_SEGMENT_START = "/__private__";
4
+ export declare const PRIVATE_IMPORT_PATTERN: RegExp;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PRIVATE_IMPORT_PATTERN = exports.PRIVATE_SEGMENT_START = exports.PRIVATE_SEGMENT = exports.PRIVATE_FOLDER = void 0;
4
+ exports.PRIVATE_FOLDER = "__private__";
5
+ exports.PRIVATE_SEGMENT = `/${exports.PRIVATE_FOLDER}/`;
6
+ exports.PRIVATE_SEGMENT_START = `/${exports.PRIVATE_FOLDER}`;
7
+ const PRIVATE_FOLDER_REGEX = exports.PRIVATE_FOLDER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8
+ exports.PRIVATE_IMPORT_PATTERN = new RegExp(`from\\s+["']([^"']*${PRIVATE_FOLDER_REGEX}[^"']*)["']`, "g");
package/dist/index.js CHANGED
@@ -1,31 +1,21 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- const node_path_1 = __importDefault(require("node:path"));
6
- const PRIVATE_FOLDER = "__private__";
7
- const PRIVATE_SEGMENT = `/${PRIVATE_FOLDER}/`;
8
- const PRIVATE_SEGMENT_START = `/${PRIVATE_FOLDER}`;
9
- const PRIVATE_FOLDER_REGEX = PRIVATE_FOLDER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10
- const PRIVATE_IMPORT_PATTERN = new RegExp(`from\\s+["']([^"']*${PRIVATE_FOLDER_REGEX}[^"']*)["']`, "g");
2
+ const constants_1 = require("./constants");
3
+ const completion_1 = require("./utils/completion");
4
+ const logging_1 = require("./utils/logging");
5
+ const moduleResolution_1 = require("./utils/moduleResolution");
6
+ const privateScope_1 = require("./utils/privateScope");
7
+ const textChanges_1 = require("./utils/textChanges");
11
8
  function init(modules) {
12
9
  function create(info) {
13
- info.project.projectService.logger.info("===================================");
14
- info.project.projectService.logger.info("PLUGIN LOADING: typescript-plugin-scoped-imports");
15
- info.project.projectService.logger.info("===================================");
10
+ const config = (info.config ?? {});
11
+ const { logInfo, logDebug } = (0, logging_1.createPluginLogger)(info.project.projectService.logger, config);
12
+ logInfo("===================================");
13
+ logInfo("PLUGIN LOADING: typescript-plugin-scoped-imports");
14
+ logInfo("===================================");
16
15
  try {
17
- const config = info.config || {};
18
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Config loaded - ${JSON.stringify(config)}`);
16
+ logInfo(`typescript-plugin-scoped-imports: Config loaded - ${JSON.stringify(config)}`);
19
17
  const tsApi = modules.typescript;
20
- function normalizePath(value) {
21
- return value.replace(/\\/g, "/");
22
- }
23
- function toDirectoryPath(value) {
24
- return value.endsWith("/") ? value : `${value}/`;
25
- }
26
- function toPosixAbsolute(value) {
27
- return normalizePath(node_path_1.default.resolve(value));
28
- }
18
+ const oldLS = info.languageService;
29
19
  function getCompilerOptions() {
30
20
  const programOptions = oldLS.getProgram()?.getCompilerOptions();
31
21
  if (programOptions) {
@@ -33,374 +23,157 @@ function init(modules) {
33
23
  }
34
24
  return info.project.getCompilerOptions();
35
25
  }
36
- function getProjectBaseDir(compilerOptions) {
37
- const baseDir = compilerOptions.baseUrl
38
- ? node_path_1.default.resolve(info.project.getCurrentDirectory(), compilerOptions.baseUrl)
39
- : info.project.getCurrentDirectory();
40
- return toPosixAbsolute(baseDir);
41
- }
42
- function buildPathPatternRegex(pattern) {
43
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
44
- const wildcardRegex = escaped.replace(/\*/g, "(.*)");
45
- return new RegExp(`^${wildcardRegex}$`);
46
- }
47
- function tryResolveWithPathsMapping(modulePath, compilerOptions) {
48
- const paths = compilerOptions.paths;
49
- if (!paths) {
50
- return null;
51
- }
52
- const baseDir = getProjectBaseDir(compilerOptions);
53
- for (const [pattern, targets] of Object.entries(paths)) {
54
- const matcher = buildPathPatternRegex(pattern);
55
- const match = modulePath.match(matcher);
56
- if (!match) {
57
- continue;
58
- }
59
- const captures = match.slice(1);
60
- for (const target of targets) {
61
- let captureIndex = 0;
62
- const replaced = target.replace(/\*/g, () => {
63
- const value = captures[captureIndex] ?? "";
64
- captureIndex += 1;
65
- return value;
66
- });
67
- const absolute = node_path_1.default.isAbsolute(replaced)
68
- ? toPosixAbsolute(replaced)
69
- : toPosixAbsolute(node_path_1.default.join(baseDir, replaced));
70
- return absolute;
71
- }
72
- }
73
- return null;
74
- }
75
- function resolveImportPathToAbsolute(importPath, currentFile) {
76
- const normalizedImportPath = normalizePath(importPath);
77
- const normalizedCurrentFile = normalizePath(currentFile);
78
- if (normalizedImportPath.startsWith(".")) {
79
- const currentDir = node_path_1.default.dirname(normalizedCurrentFile);
80
- return toPosixAbsolute(node_path_1.default.resolve(currentDir, normalizedImportPath));
81
- }
82
- if (normalizedImportPath.startsWith("/")) {
83
- return toPosixAbsolute(normalizedImportPath);
84
- }
85
- const compilerOptions = getCompilerOptions();
86
- const host = {
87
- fileExists: tsApi.sys.fileExists,
88
- readFile: tsApi.sys.readFile,
89
- directoryExists: tsApi.sys.directoryExists,
90
- getDirectories: tsApi.sys.getDirectories,
91
- realpath: tsApi.sys.realpath,
92
- };
93
- const resolved = tsApi.resolveModuleName(normalizedImportPath, normalizedCurrentFile, compilerOptions, host).resolvedModule?.resolvedFileName;
94
- if (resolved) {
95
- return normalizePath(resolved);
96
- }
97
- return tryResolveWithPathsMapping(normalizedImportPath, compilerOptions);
98
- }
99
- function getPrivateParentDirectory(importPath, currentFile) {
100
- const resolvedImportPath = resolveImportPathToAbsolute(importPath, currentFile);
101
- if (!resolvedImportPath) {
102
- return null;
103
- }
104
- const privateSegmentIndex = resolvedImportPath.indexOf(PRIVATE_SEGMENT_START);
105
- if (privateSegmentIndex === -1) {
106
- return null;
107
- }
108
- return toDirectoryPath(resolvedImportPath.substring(0, privateSegmentIndex + 1));
109
- }
110
- // Helper: Check if a file can access a __private__ folder
111
- // Rule: A file can access __private__ only if it's in the "scope" of that __private__ folder
112
- // The scope is: the parent directory of __private__ and all its subdirectories
113
- function isPrivateImportAllowed(importPath, currentFile) {
114
- const normalizedImportPath = normalizePath(importPath);
115
- const normalizedCurrentFile = normalizePath(currentFile);
116
- // DEBUG: Log all calls to understand what TypeScript sends
117
- info.project.projectService.logger.info(`[DEBUG isPrivateImportAllowed] importPath="${normalizedImportPath}" currentFile="${normalizedCurrentFile}"`);
118
- // If import doesn't contain __private__, allow
119
- if (!normalizedImportPath.includes(PRIVATE_FOLDER)) {
120
- return true;
121
- }
122
- // Case 1: Current file is inside __private__ - allow all
123
- if (normalizedCurrentFile.includes(PRIVATE_SEGMENT)) {
124
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING (file inside ${PRIVATE_FOLDER}): ${normalizedCurrentFile}`);
26
+ const resolveImportPath = (importPath, currentFile) => {
27
+ return (0, moduleResolution_1.resolveImportPathToAbsolute)({
28
+ tsApi,
29
+ importPath,
30
+ currentFile,
31
+ compilerOptions: getCompilerOptions(),
32
+ currentDirectory: info.project.getCurrentDirectory(),
33
+ });
34
+ };
35
+ const isPrivateImportAllowedForFile = (importPath, currentFile) => {
36
+ return (0, privateScope_1.isPrivateImportAllowed)({
37
+ importPath,
38
+ currentFile,
39
+ resolveImportPathToAbsolute: resolveImportPath,
40
+ logging: {
41
+ logInfo,
42
+ logDebug,
43
+ },
44
+ });
45
+ };
46
+ function shouldAllowChanges(params) {
47
+ const { changes, currentFile, blockedLogMessage } = params;
48
+ if (!(0, textChanges_1.containsPrivateImport)(changes)) {
125
49
  return true;
126
50
  }
127
- const privateParentDir = getPrivateParentDirectory(normalizedImportPath, normalizedCurrentFile);
128
- if (!privateParentDir) {
129
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING import (cannot resolve private parent): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
51
+ if ((0, textChanges_1.hasBlockedPrivateImports)({
52
+ changes,
53
+ currentFile,
54
+ isPrivateImportAllowed: isPrivateImportAllowedForFile,
55
+ })) {
56
+ logInfo(blockedLogMessage);
130
57
  return false;
131
58
  }
132
- const currentFileDir = toDirectoryPath(node_path_1.default.dirname(normalizedCurrentFile));
133
- if (currentFileDir.startsWith(privateParentDir)) {
134
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING import (in scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
135
- return true;
136
- }
137
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING import (out of scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
138
- return false;
139
- }
140
- // Helper: Extract import paths containing __private__ from text changes
141
- function extractPrivateImportPaths(changes) {
142
- const paths = [];
143
- const importPattern = new RegExp(PRIVATE_IMPORT_PATTERN.source, PRIVATE_IMPORT_PATTERN.flags);
144
- for (const change of changes) {
145
- for (const textChange of change.textChanges || []) {
146
- const newText = textChange.newText;
147
- if (!newText)
148
- continue;
149
- // Reset regex state
150
- importPattern.lastIndex = 0;
151
- let match = importPattern.exec(newText);
152
- while (match !== null) {
153
- paths.push(match[1]);
154
- match = importPattern.exec(newText);
155
- }
156
- }
157
- }
158
- return paths;
159
- }
160
- // Helper: Check if changes contain blocked private imports for a given file
161
- function hasBlockedPrivateImports(changes, currentFile) {
162
- const privatePaths = extractPrivateImportPaths(changes);
163
- return privatePaths.some((path) => !isPrivateImportAllowed(path, currentFile));
164
- }
165
- // Helper: Simple check if changes contain any __private__ import
166
- function containsPrivateImport(changes) {
167
- return changes.some((change) => change.textChanges?.some((textChange) => {
168
- const newText = textChange.newText;
169
- return newText?.includes(PRIVATE_FOLDER) ?? false;
170
- }));
59
+ return true;
171
60
  }
172
- // Create language service proxy
173
61
  const proxy = Object.create(null);
174
62
  const proxyObject = proxy;
175
- const oldLS = info.languageService;
176
- // Copy all methods from original LS
177
- for (const k in oldLS) {
178
- const key = k;
179
- const x = oldLS[key];
180
- if (typeof x === "function") {
181
- proxyObject[k] = (...args) => x.apply(oldLS, args);
63
+ for (const key in oldLS) {
64
+ const serviceKey = key;
65
+ const serviceMember = oldLS[serviceKey];
66
+ if (typeof serviceMember === "function") {
67
+ proxyObject[key] = (...args) => serviceMember.apply(oldLS, args);
182
68
  }
183
69
  else {
184
- proxyObject[k] = x;
185
- }
186
- }
187
- // Helper: Extract the import path being typed at the given position
188
- function getImportPathAtPosition(fileName, position) {
189
- try {
190
- const program = oldLS.getProgram();
191
- if (!program)
192
- return null;
193
- const sourceFile = program.getSourceFile(fileName);
194
- if (!sourceFile)
195
- return null;
196
- const text = sourceFile.getFullText();
197
- // Find the string literal containing the position
198
- // Look backwards from position to find the opening quote
199
- let start = position - 1;
200
- while (start >= 0 && text[start] !== '"' && text[start] !== "'") {
201
- start--;
202
- }
203
- if (start < 0)
204
- return null;
205
- const quote = text[start];
206
- // Extract the path from after the quote to the position
207
- const path = text.substring(start + 1, position);
208
- return path;
209
- }
210
- catch {
211
- return null;
70
+ proxyObject[key] = serviceMember;
212
71
  }
213
72
  }
214
- // Helper: Check if a typed path prefix allows access to __private__
215
- function isPathPrefixValidForPrivate(pathPrefix, currentFile) {
216
- const normalizedPath = pathPrefix.replace(/\\/g, "/");
217
- if (!normalizedPath) {
218
- return false;
219
- }
220
- let basePath = normalizedPath;
221
- if (basePath === ".") {
222
- basePath = "./";
223
- }
224
- else if (basePath === "..") {
225
- basePath = "../";
226
- }
227
- if (!basePath.endsWith("/")) {
228
- basePath += "/";
229
- }
230
- const candidateImportPath = `${basePath}${PRIVATE_FOLDER}`;
231
- return isPrivateImportAllowed(candidateImportPath, currentFile);
232
- }
233
- // Intercept getCompletionsAtPosition
234
73
  proxy.getCompletionsAtPosition = (fileName, position, options) => {
235
74
  const prior = oldLS.getCompletionsAtPosition(fileName, position, options);
236
75
  if (!prior) {
237
76
  return prior;
238
77
  }
239
- info.project.projectService.logger.info(`[DEBUG getCompletionsAtPosition] fileName="${fileName}" entries=${prior.entries.length}`);
240
- const originalCount = prior.entries.length;
241
- // Get the path being typed (for directory completion validation)
242
- const typedPath = getImportPathAtPosition(fileName, position);
243
- info.project.projectService.logger.info(`[DEBUG] typedPath="${typedPath}"`);
244
- // Log entries that contain __private__ for debugging
78
+ logDebug(`[DEBUG getCompletionsAtPosition] fileName="${fileName}" entries=${prior.entries.length.toString()}`);
79
+ const typedPath = (0, completion_1.getImportPathAtPosition)({
80
+ languageService: oldLS,
81
+ fileName,
82
+ position,
83
+ });
84
+ logDebug(`[DEBUG] typedPath="${typedPath}"`);
245
85
  for (const entry of prior.entries) {
246
- if (entry.name?.includes(PRIVATE_FOLDER) ||
247
- entry.source?.includes(PRIVATE_FOLDER) ||
248
- entry.sourceDisplay?.some((p) => p.text.includes(PRIVATE_FOLDER))) {
249
- info.project.projectService.logger.info(`[DEBUG entry] name="${entry.name}" source="${entry.source}" kind="${entry.kind}" sourceDisplay="${entry.sourceDisplay?.map((p) => p.text).join("")}"`);
86
+ if (entry.name?.includes(constants_1.PRIVATE_FOLDER) ||
87
+ entry.source?.includes(constants_1.PRIVATE_FOLDER) ||
88
+ entry.sourceDisplay?.some((part) => part.text.includes(constants_1.PRIVATE_FOLDER))) {
89
+ logDebug(`[DEBUG entry] name="${entry.name}" source="${entry.source}" kind="${entry.kind}" sourceDisplay="${entry.sourceDisplay?.map((part) => part.text).join("")}"`);
250
90
  }
251
91
  }
252
- // Find blocked names (from __private__ sources that are not allowed)
253
92
  const blockedNames = new Set();
254
93
  for (const entry of prior.entries) {
255
94
  const source = entry.source;
256
- if (source?.includes(PRIVATE_FOLDER)) {
257
- if (!isPrivateImportAllowed(source, fileName)) {
258
- blockedNames.add(entry.name);
259
- }
95
+ if (source?.includes(constants_1.PRIVATE_FOLDER) &&
96
+ !isPrivateImportAllowedForFile(source, fileName)) {
97
+ blockedNames.add(entry.name);
260
98
  }
261
99
  }
262
- // Filter entries
263
- const filteredEntries = prior.entries.filter((entry) => {
264
- // Handle entries with __private__ in the name (usually directory suggestions)
265
- if (entry.name?.toLowerCase().includes(PRIVATE_FOLDER)) {
266
- // If there's a source, use isPrivateImportAllowed
267
- if (entry.source) {
268
- return isPrivateImportAllowed(entry.source, fileName);
269
- }
270
- // No source - this is a directory suggestion in path completion
271
- if (entry.kind === "directory") {
272
- // Check if the typed path allows access to __private__
273
- if (typedPath !== null &&
274
- isPathPrefixValidForPrivate(typedPath, fileName)) {
275
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ALLOWING ${PRIVATE_FOLDER} directory (valid path: "${typedPath}")`);
276
- return true;
277
- }
278
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING ${PRIVATE_FOLDER} directory (invalid path: "${typedPath}")`);
279
- return false;
280
- }
281
- // For other kinds without source, block
282
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING entry by name (no source): ${entry.name}`);
283
- return false;
284
- }
285
- // Block directories that match blocked import sources
286
- if (entry.kind === "directory" && blockedNames.has(entry.name)) {
287
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING directory: ${entry.name}`);
288
- return false;
289
- }
290
- // If no source, check other fields for __private__
291
- if (!entry.source) {
292
- const entryText = (entry.name +
293
- (entry.insertText || "") +
294
- (entry.sourceDisplay?.map((p) => p.text).join("") || "") +
295
- JSON.stringify(entry.data || {})).toLowerCase();
296
- if (entryText.includes(PRIVATE_FOLDER)) {
297
- // Try to extract a path from sourceDisplay to validate
298
- const sourceDisplayText = entry.sourceDisplay?.map((p) => p.text).join("") || "";
299
- if (sourceDisplayText.includes(PRIVATE_FOLDER)) {
300
- // Use sourceDisplay as the import path for validation
301
- return isPrivateImportAllowed(sourceDisplayText, fileName);
302
- }
303
- // Can't determine scope, block to be safe
304
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING entry without source: ${entry.name} (${entryText})`);
305
- return false;
306
- }
307
- return true;
308
- }
309
- // Check source path
310
- const source = entry.source;
311
- if (source?.includes(PRIVATE_FOLDER)) {
312
- return isPrivateImportAllowed(source, fileName);
313
- }
314
- return true;
315
- });
316
- const filteredCount = filteredEntries.length;
317
- if (originalCount !== filteredCount) {
318
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${originalCount - filteredCount} completions (${originalCount} -> ${filteredCount})`);
100
+ const filteredEntries = prior.entries.filter((entry) => (0, completion_1.shouldAllowCompletionEntry)({
101
+ entry,
102
+ typedPath,
103
+ fileName,
104
+ blockedNames,
105
+ isPrivateImportAllowed: isPrivateImportAllowedForFile,
106
+ logInfo,
107
+ }));
108
+ if (prior.entries.length !== filteredEntries.length) {
109
+ logInfo(`typescript-plugin-scoped-imports: Filtered ${(prior.entries.length - filteredEntries.length).toString()} completions (${prior.entries.length.toString()} -> ${filteredEntries.length.toString()})`);
319
110
  }
320
111
  return {
321
112
  ...prior,
322
113
  entries: filteredEntries,
323
114
  };
324
115
  };
325
- // Intercept getCompletionEntryDetails
326
116
  proxy.getCompletionEntryDetails = (fileName, position, entryName, formatOptions, source, preferences, data) => {
327
- if (source?.includes(PRIVATE_FOLDER)) {
328
- if (!isPrivateImportAllowed(source, fileName)) {
329
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING completion details for source: ${source}`);
330
- return undefined;
331
- }
117
+ if (source?.includes(constants_1.PRIVATE_FOLDER) &&
118
+ !isPrivateImportAllowedForFile(source, fileName)) {
119
+ logInfo(`typescript-plugin-scoped-imports: BLOCKING completion details for source: ${source}`);
120
+ return undefined;
332
121
  }
333
122
  return oldLS.getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data);
334
123
  };
335
- // Intercept getCodeFixesAtPosition
336
124
  proxy.getCodeFixesAtPosition = (fileName, start, end, errorCodes, formatOptions, preferences) => {
337
125
  const fixes = oldLS.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
338
- const filteredFixes = fixes.filter((fix) => {
339
- if (containsPrivateImport(fix.changes)) {
340
- if (hasBlockedPrivateImports(fix.changes, fileName)) {
341
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: BLOCKING code fix "${fix.fixName}"`);
342
- return false;
343
- }
344
- }
345
- return true;
346
- });
126
+ const filteredFixes = fixes.filter((fix) => shouldAllowChanges({
127
+ changes: fix.changes,
128
+ currentFile: fileName,
129
+ blockedLogMessage: `typescript-plugin-scoped-imports: BLOCKING code fix "${fix.fixName}"`,
130
+ }));
347
131
  if (fixes.length !== filteredFixes.length) {
348
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${fixes.length - filteredFixes.length} code fixes`);
132
+ logInfo(`typescript-plugin-scoped-imports: Filtered ${(fixes.length - filteredFixes.length).toString()} code fixes`);
349
133
  }
350
134
  return filteredFixes;
351
135
  };
352
- // Intercept getCombinedCodeFix
353
136
  proxy.getCombinedCodeFix = (scope, fixId, formatOptions, preferences) => {
354
137
  const getCombinedCodeFix = oldLS.getCombinedCodeFix;
355
138
  const result = getCombinedCodeFix(scope, fixId, formatOptions, preferences);
356
- const fileName = scope.fileName;
357
- const filteredChanges = result.changes.filter((change) => {
358
- if (containsPrivateImport([change])) {
359
- if (hasBlockedPrivateImports([change], fileName)) {
360
- info.project.projectService.logger.info("typescript-plugin-scoped-imports: BLOCKING combined fix change");
361
- return false;
362
- }
363
- }
364
- return true;
365
- });
139
+ const filteredChanges = result.changes.filter((change) => shouldAllowChanges({
140
+ changes: [change],
141
+ currentFile: scope.fileName,
142
+ blockedLogMessage: "typescript-plugin-scoped-imports: BLOCKING combined fix change",
143
+ }));
366
144
  if (result.changes.length !== filteredChanges.length) {
367
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${result.changes.length - filteredChanges.length} combined fix changes`);
145
+ logInfo(`typescript-plugin-scoped-imports: Filtered ${(result.changes.length - filteredChanges.length).toString()} combined fix changes`);
368
146
  }
369
147
  return {
370
148
  ...result,
371
149
  changes: filteredChanges,
372
150
  };
373
151
  };
374
- // Intercept getEditsForRefactor
375
152
  proxy.getEditsForRefactor = (fileName, formatOptions, positionOrRange, refactorName, actionName, preferences, interactiveRefactorArguments) => {
376
153
  const result = oldLS.getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences, interactiveRefactorArguments);
377
154
  if (!result) {
378
155
  return result;
379
156
  }
380
- const filteredEdits = result.edits.filter((edit) => {
381
- if (containsPrivateImport([edit])) {
382
- if (hasBlockedPrivateImports([edit], fileName)) {
383
- info.project.projectService.logger.info("typescript-plugin-scoped-imports: BLOCKING refactor edit");
384
- return false;
385
- }
386
- }
387
- return true;
388
- });
157
+ const filteredEdits = result.edits.filter((edit) => shouldAllowChanges({
158
+ changes: [edit],
159
+ currentFile: fileName,
160
+ blockedLogMessage: "typescript-plugin-scoped-imports: BLOCKING refactor edit",
161
+ }));
389
162
  if (result.edits.length !== filteredEdits.length) {
390
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: Filtered ${result.edits.length - filteredEdits.length} refactor edits`);
163
+ logInfo(`typescript-plugin-scoped-imports: Filtered ${(result.edits.length - filteredEdits.length).toString()} refactor edits`);
391
164
  }
392
165
  return {
393
166
  ...result,
394
167
  edits: filteredEdits,
395
168
  };
396
169
  };
397
- info.project.projectService.logger.info("typescript-plugin-scoped-imports: Plugin proxy created successfully");
398
- info.project.projectService.logger.info("===================================");
170
+ logInfo("typescript-plugin-scoped-imports: Plugin proxy created successfully");
171
+ logInfo("===================================");
399
172
  return proxy;
400
173
  }
401
174
  catch (error) {
402
- info.project.projectService.logger.info(`typescript-plugin-scoped-imports: ERROR loading plugin: ${error}`);
403
- info.project.projectService.logger.info("===================================");
175
+ logInfo(`typescript-plugin-scoped-imports: ERROR loading plugin: ${error}`);
176
+ logInfo("===================================");
404
177
  throw error;
405
178
  }
406
179
  }
@@ -0,0 +1,22 @@
1
+ import type * as ts from "typescript/lib/tsserverlibrary";
2
+ export type GetImportPathAtPositionParams = {
3
+ languageService: ts.LanguageService;
4
+ fileName: string;
5
+ position: number;
6
+ };
7
+ export type IsPathPrefixValidForPrivateParams = {
8
+ pathPrefix: string;
9
+ currentFile: string;
10
+ isPrivateImportAllowed: (importPath: string, currentFile: string) => boolean;
11
+ };
12
+ export declare function getImportPathAtPosition(params: GetImportPathAtPositionParams): string | null;
13
+ export declare function isPathPrefixValidForPrivate(params: IsPathPrefixValidForPrivateParams): boolean;
14
+ export type CompletionDecisionOptions = {
15
+ entry: ts.CompletionEntry;
16
+ typedPath: string | null;
17
+ fileName: string;
18
+ blockedNames: ReadonlySet<string>;
19
+ isPrivateImportAllowed: (importPath: string, currentFile: string) => boolean;
20
+ logInfo: (message: string) => void;
21
+ };
22
+ export declare function shouldAllowCompletionEntry({ entry, typedPath, fileName, blockedNames, isPrivateImportAllowed, logInfo, }: CompletionDecisionOptions): boolean;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getImportPathAtPosition = getImportPathAtPosition;
4
+ exports.isPathPrefixValidForPrivate = isPathPrefixValidForPrivate;
5
+ exports.shouldAllowCompletionEntry = shouldAllowCompletionEntry;
6
+ const constants_1 = require("../constants");
7
+ const path_1 = require("./path");
8
+ function getImportPathAtPosition(params) {
9
+ const { languageService, fileName, position } = params;
10
+ try {
11
+ const program = languageService.getProgram();
12
+ if (!program) {
13
+ return null;
14
+ }
15
+ const sourceFile = program.getSourceFile(fileName);
16
+ if (!sourceFile) {
17
+ return null;
18
+ }
19
+ const text = sourceFile.getFullText();
20
+ let start = position - 1;
21
+ while (start >= 0 && text[start] !== '"' && text[start] !== "'") {
22
+ start -= 1;
23
+ }
24
+ if (start < 0) {
25
+ return null;
26
+ }
27
+ return text.substring(start + 1, position);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function isPathPrefixValidForPrivate(params) {
34
+ const { pathPrefix, currentFile, isPrivateImportAllowed } = params;
35
+ const normalizedPath = (0, path_1.normalizePath)(pathPrefix);
36
+ if (!normalizedPath) {
37
+ return false;
38
+ }
39
+ let basePath = normalizedPath;
40
+ if (basePath === ".") {
41
+ basePath = "./";
42
+ }
43
+ else if (basePath === "..") {
44
+ basePath = "../";
45
+ }
46
+ if (!basePath.endsWith("/")) {
47
+ basePath += "/";
48
+ }
49
+ const candidateImportPath = `${basePath}${constants_1.PRIVATE_FOLDER}`;
50
+ return isPrivateImportAllowed(candidateImportPath, currentFile);
51
+ }
52
+ function shouldAllowCompletionEntry({ entry, typedPath, fileName, blockedNames, isPrivateImportAllowed, logInfo, }) {
53
+ if (entry.name?.toLowerCase().includes(constants_1.PRIVATE_FOLDER)) {
54
+ if (entry.source) {
55
+ return isPrivateImportAllowed(entry.source, fileName);
56
+ }
57
+ if (entry.kind === "directory") {
58
+ if (typedPath !== null &&
59
+ isPathPrefixValidForPrivate({
60
+ pathPrefix: typedPath,
61
+ currentFile: fileName,
62
+ isPrivateImportAllowed,
63
+ })) {
64
+ logInfo(`typescript-plugin-scoped-imports: ALLOWING ${constants_1.PRIVATE_FOLDER} directory (valid path: "${typedPath}")`);
65
+ return true;
66
+ }
67
+ logInfo(`typescript-plugin-scoped-imports: BLOCKING ${constants_1.PRIVATE_FOLDER} directory (invalid path: "${typedPath}")`);
68
+ return false;
69
+ }
70
+ logInfo(`typescript-plugin-scoped-imports: BLOCKING entry by name (no source): ${entry.name}`);
71
+ return false;
72
+ }
73
+ if (entry.kind === "directory" && blockedNames.has(entry.name)) {
74
+ logInfo(`typescript-plugin-scoped-imports: BLOCKING directory: ${entry.name}`);
75
+ return false;
76
+ }
77
+ if (!entry.source) {
78
+ const sourceDisplayText = entry.sourceDisplay?.map((p) => p.text).join("") || "";
79
+ const entryText = (entry.name +
80
+ (entry.insertText || "") +
81
+ sourceDisplayText +
82
+ JSON.stringify(entry.data || {})).toLowerCase();
83
+ if (entryText.includes(constants_1.PRIVATE_FOLDER)) {
84
+ if (sourceDisplayText.includes(constants_1.PRIVATE_FOLDER)) {
85
+ return isPrivateImportAllowed(sourceDisplayText, fileName);
86
+ }
87
+ logInfo(`typescript-plugin-scoped-imports: BLOCKING entry without source: ${entry.name} (${entryText})`);
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+ if (entry.source.includes(constants_1.PRIVATE_FOLDER)) {
93
+ return isPrivateImportAllowed(entry.source, fileName);
94
+ }
95
+ return true;
96
+ }
@@ -0,0 +1,8 @@
1
+ import type * as ts from "typescript/lib/tsserverlibrary";
2
+ export type PluginConfig = {
3
+ debug?: boolean;
4
+ };
5
+ export declare function createPluginLogger(logger: ts.server.Logger, config: PluginConfig | undefined): {
6
+ logInfo: (message: string) => void;
7
+ logDebug: (message: string) => void;
8
+ };
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPluginLogger = createPluginLogger;
4
+ function createPluginLogger(logger, config) {
5
+ const debugEnabled = config?.debug === true;
6
+ const logInfo = (message) => {
7
+ logger.info(message);
8
+ };
9
+ const logDebug = (message) => {
10
+ if (debugEnabled) {
11
+ logger.info(message);
12
+ }
13
+ };
14
+ return {
15
+ logInfo,
16
+ logDebug,
17
+ };
18
+ }
@@ -0,0 +1,19 @@
1
+ import type * as ts from "typescript/lib/tsserverlibrary";
2
+ type TsApiForResolution = Pick<typeof ts, "resolveModuleName" | "sys">;
3
+ type ResolveWithPathsMappingParams = {
4
+ modulePath: string;
5
+ compilerOptions: ts.CompilerOptions;
6
+ projectBaseDir: string;
7
+ };
8
+ export type ResolveImportPathToAbsoluteParams = {
9
+ tsApi: TsApiForResolution;
10
+ importPath: string;
11
+ currentFile: string;
12
+ compilerOptions: ts.CompilerOptions;
13
+ currentDirectory: string;
14
+ };
15
+ export declare function buildPathPatternRegex(pattern: string): RegExp;
16
+ export declare function getProjectBaseDir(currentDirectory: string, compilerOptions: ts.CompilerOptions): string;
17
+ export declare function tryResolveWithPathsMapping(params: ResolveWithPathsMappingParams): string | null;
18
+ export declare function resolveImportPathToAbsolute(params: ResolveImportPathToAbsoluteParams): string | null;
19
+ export {};
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buildPathPatternRegex = buildPathPatternRegex;
7
+ exports.getProjectBaseDir = getProjectBaseDir;
8
+ exports.tryResolveWithPathsMapping = tryResolveWithPathsMapping;
9
+ exports.resolveImportPathToAbsolute = resolveImportPathToAbsolute;
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const path_1 = require("./path");
12
+ function buildPathPatternRegex(pattern) {
13
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
14
+ const wildcardRegex = escaped.replace(/\*/g, "(.*)");
15
+ return new RegExp(`^${wildcardRegex}$`);
16
+ }
17
+ function getProjectBaseDir(currentDirectory, compilerOptions) {
18
+ const baseDir = compilerOptions.baseUrl
19
+ ? node_path_1.default.resolve(currentDirectory, compilerOptions.baseUrl)
20
+ : currentDirectory;
21
+ return (0, path_1.toPosixAbsolute)(baseDir);
22
+ }
23
+ function tryResolveWithPathsMapping(params) {
24
+ const { modulePath, compilerOptions, projectBaseDir } = params;
25
+ const paths = compilerOptions.paths;
26
+ if (!paths) {
27
+ return null;
28
+ }
29
+ for (const [pattern, targets] of Object.entries(paths)) {
30
+ const matcher = buildPathPatternRegex(pattern);
31
+ const match = modulePath.match(matcher);
32
+ if (!match) {
33
+ continue;
34
+ }
35
+ const captures = match.slice(1);
36
+ for (const target of targets) {
37
+ let captureIndex = 0;
38
+ const replaced = target.replace(/\*/g, () => {
39
+ const value = captures[captureIndex] ?? "";
40
+ captureIndex += 1;
41
+ return value;
42
+ });
43
+ const absolute = node_path_1.default.isAbsolute(replaced)
44
+ ? (0, path_1.toPosixAbsolute)(replaced)
45
+ : (0, path_1.toPosixAbsolute)(node_path_1.default.join(projectBaseDir, replaced));
46
+ return absolute;
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ function resolveImportPathToAbsolute(params) {
52
+ const { tsApi, importPath, currentFile, compilerOptions, currentDirectory } = params;
53
+ const normalizedImportPath = (0, path_1.normalizePath)(importPath);
54
+ const normalizedCurrentFile = (0, path_1.normalizePath)(currentFile);
55
+ if (normalizedImportPath.startsWith(".")) {
56
+ const currentDir = node_path_1.default.dirname(normalizedCurrentFile);
57
+ return (0, path_1.toPosixAbsolute)(node_path_1.default.resolve(currentDir, normalizedImportPath));
58
+ }
59
+ if (normalizedImportPath.startsWith("/")) {
60
+ return (0, path_1.toPosixAbsolute)(normalizedImportPath);
61
+ }
62
+ const host = {
63
+ fileExists: tsApi.sys.fileExists,
64
+ readFile: tsApi.sys.readFile,
65
+ directoryExists: tsApi.sys.directoryExists,
66
+ getDirectories: tsApi.sys.getDirectories,
67
+ realpath: tsApi.sys.realpath,
68
+ };
69
+ const resolved = tsApi.resolveModuleName(normalizedImportPath, normalizedCurrentFile, compilerOptions, host).resolvedModule?.resolvedFileName;
70
+ if (resolved) {
71
+ return (0, path_1.normalizePath)(resolved);
72
+ }
73
+ const projectBaseDir = getProjectBaseDir(currentDirectory, compilerOptions);
74
+ return tryResolveWithPathsMapping({
75
+ modulePath: normalizedImportPath,
76
+ compilerOptions,
77
+ projectBaseDir,
78
+ });
79
+ }
@@ -0,0 +1,3 @@
1
+ export declare function normalizePath(value: string): string;
2
+ export declare function toDirectoryPath(value: string): string;
3
+ export declare function toPosixAbsolute(value: string): string;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.normalizePath = normalizePath;
7
+ exports.toDirectoryPath = toDirectoryPath;
8
+ exports.toPosixAbsolute = toPosixAbsolute;
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ function normalizePath(value) {
11
+ return value.replace(/\\/g, "/");
12
+ }
13
+ function toDirectoryPath(value) {
14
+ return value.endsWith("/") ? value : `${value}/`;
15
+ }
16
+ function toPosixAbsolute(value) {
17
+ return normalizePath(node_path_1.default.resolve(value));
18
+ }
@@ -0,0 +1,19 @@
1
+ type ResolveImportPath = (importPath: string, currentFile: string) => string | null;
2
+ type ScopeLogging = {
3
+ logInfo: (message: string) => void;
4
+ logDebug: (message: string) => void;
5
+ };
6
+ export type GetPrivateParentDirectoryParams = {
7
+ importPath: string;
8
+ currentFile: string;
9
+ resolveImportPathToAbsolute: ResolveImportPath;
10
+ };
11
+ export type IsPrivateImportAllowedParams = {
12
+ importPath: string;
13
+ currentFile: string;
14
+ resolveImportPathToAbsolute: ResolveImportPath;
15
+ logging: ScopeLogging;
16
+ };
17
+ export declare function getPrivateParentDirectory(params: GetPrivateParentDirectoryParams): string | null;
18
+ export declare function isPrivateImportAllowed(params: IsPrivateImportAllowedParams): boolean;
19
+ export {};
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getPrivateParentDirectory = getPrivateParentDirectory;
7
+ exports.isPrivateImportAllowed = isPrivateImportAllowed;
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const constants_1 = require("../constants");
10
+ const path_1 = require("./path");
11
+ function getPrivateParentDirectory(params) {
12
+ const { importPath, currentFile, resolveImportPathToAbsolute } = params;
13
+ const resolvedImportPath = resolveImportPathToAbsolute(importPath, currentFile);
14
+ if (!resolvedImportPath) {
15
+ return null;
16
+ }
17
+ const privateSegmentIndex = resolvedImportPath.indexOf(constants_1.PRIVATE_SEGMENT_START);
18
+ if (privateSegmentIndex === -1) {
19
+ return null;
20
+ }
21
+ return (0, path_1.toDirectoryPath)(resolvedImportPath.substring(0, privateSegmentIndex + 1));
22
+ }
23
+ function isPrivateImportAllowed(params) {
24
+ const { importPath, currentFile, resolveImportPathToAbsolute, logging } = params;
25
+ const normalizedImportPath = (0, path_1.normalizePath)(importPath);
26
+ const normalizedCurrentFile = (0, path_1.normalizePath)(currentFile);
27
+ logging.logDebug(`[DEBUG isPrivateImportAllowed] importPath="${normalizedImportPath}" currentFile="${normalizedCurrentFile}"`);
28
+ if (!normalizedImportPath.includes(constants_1.PRIVATE_FOLDER)) {
29
+ return true;
30
+ }
31
+ if (normalizedCurrentFile.includes(constants_1.PRIVATE_SEGMENT)) {
32
+ logging.logInfo(`typescript-plugin-scoped-imports: ALLOWING (file inside ${constants_1.PRIVATE_FOLDER}): ${normalizedCurrentFile}`);
33
+ return true;
34
+ }
35
+ const privateParentDir = getPrivateParentDirectory({
36
+ importPath: normalizedImportPath,
37
+ currentFile: normalizedCurrentFile,
38
+ resolveImportPathToAbsolute,
39
+ });
40
+ if (!privateParentDir) {
41
+ logging.logInfo(`typescript-plugin-scoped-imports: BLOCKING import (cannot resolve private parent): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
42
+ return false;
43
+ }
44
+ const currentFileDir = (0, path_1.toDirectoryPath)(node_path_1.default.dirname(normalizedCurrentFile));
45
+ if (currentFileDir.startsWith(privateParentDir)) {
46
+ logging.logInfo(`typescript-plugin-scoped-imports: ALLOWING import (in scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
47
+ return true;
48
+ }
49
+ logging.logInfo(`typescript-plugin-scoped-imports: BLOCKING import (out of scope): "${normalizedImportPath}" from "${normalizedCurrentFile}"`);
50
+ return false;
51
+ }
@@ -0,0 +1,9 @@
1
+ import type * as ts from "typescript/lib/tsserverlibrary";
2
+ export type HasBlockedPrivateImportsParams = {
3
+ changes: readonly ts.FileTextChanges[];
4
+ currentFile: string;
5
+ isPrivateImportAllowed: (importPath: string, currentFile: string) => boolean;
6
+ };
7
+ export declare function extractPrivateImportPaths(changes: readonly ts.FileTextChanges[]): string[];
8
+ export declare function containsPrivateImport(changes: readonly ts.FileTextChanges[]): boolean;
9
+ export declare function hasBlockedPrivateImports(params: HasBlockedPrivateImportsParams): boolean;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractPrivateImportPaths = extractPrivateImportPaths;
4
+ exports.containsPrivateImport = containsPrivateImport;
5
+ exports.hasBlockedPrivateImports = hasBlockedPrivateImports;
6
+ const constants_1 = require("../constants");
7
+ function extractPrivateImportPaths(changes) {
8
+ const paths = [];
9
+ const importPattern = new RegExp(constants_1.PRIVATE_IMPORT_PATTERN.source, constants_1.PRIVATE_IMPORT_PATTERN.flags);
10
+ for (const change of changes) {
11
+ for (const textChange of change.textChanges || []) {
12
+ const newText = textChange.newText;
13
+ if (!newText) {
14
+ continue;
15
+ }
16
+ importPattern.lastIndex = 0;
17
+ let match = importPattern.exec(newText);
18
+ while (match !== null) {
19
+ paths.push(match[1]);
20
+ match = importPattern.exec(newText);
21
+ }
22
+ }
23
+ }
24
+ return paths;
25
+ }
26
+ function containsPrivateImport(changes) {
27
+ return changes.some((change) => change.textChanges?.some((textChange) => {
28
+ const newText = textChange.newText;
29
+ return newText?.includes(constants_1.PRIVATE_FOLDER) ?? false;
30
+ }));
31
+ }
32
+ function hasBlockedPrivateImports(params) {
33
+ const { changes, currentFile, isPrivateImportAllowed } = params;
34
+ const privatePaths = extractPrivateImportPaths(changes);
35
+ return privatePaths.some((importPath) => !isPrivateImportAllowed(importPath, currentFile));
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-plugin-scoped-imports",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "TypeScript Language Server plugin para controlar auto-imports basado en scope",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",