typescript-svelte-plugin 0.3.0 → 0.3.3

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.
@@ -0,0 +1,10 @@
1
+ export interface Configuration {
2
+ enable: boolean;
3
+ }
4
+ export declare class ConfigManager {
5
+ private emitter;
6
+ private config;
7
+ onConfigurationChanged(listener: (config: Configuration) => void): void;
8
+ updateConfigFromPluginConfig(config: Configuration): void;
9
+ getConfig(): Configuration;
10
+ }
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConfigManager = void 0;
4
+ const events_1 = require("events");
5
+ const configurationEventName = 'configuration-changed';
6
+ class ConfigManager {
7
+ constructor() {
8
+ this.emitter = new events_1.EventEmitter();
9
+ this.config = {
10
+ enable: true
11
+ };
12
+ }
13
+ onConfigurationChanged(listener) {
14
+ this.emitter.on(configurationEventName, listener);
15
+ }
16
+ updateConfigFromPluginConfig(config) {
17
+ this.config = {
18
+ ...this.config,
19
+ ...config
20
+ };
21
+ this.emitter.emit(configurationEventName, config);
22
+ }
23
+ getConfig() {
24
+ return this.config;
25
+ }
26
+ }
27
+ exports.ConfigManager = ConfigManager;
@@ -1,8 +1,5 @@
1
1
  import type ts from 'typescript/lib/tsserverlibrary';
2
2
  declare function init(modules: {
3
3
  typescript: typeof ts;
4
- }): {
5
- create: (info: ts.server.PluginCreateInfo) => ts.LanguageService;
6
- getExternalFiles: (project: ts.server.ConfiguredProject) => string[];
7
- };
4
+ }): ts.server.PluginModule;
8
5
  export = init;
package/dist/src/index.js CHANGED
@@ -4,7 +4,11 @@ const language_service_1 = require("./language-service");
4
4
  const logger_1 = require("./logger");
5
5
  const module_loader_1 = require("./module-loader");
6
6
  const svelte_snapshots_1 = require("./svelte-snapshots");
7
+ const config_manager_1 = require("./config-manager");
8
+ const project_svelte_files_1 = require("./project-svelte-files");
9
+ const utils_1 = require("./utils");
7
10
  function init(modules) {
11
+ const configManager = new config_manager_1.ConfigManager();
8
12
  function create(info) {
9
13
  var _a, _b, _c, _d;
10
14
  const logger = new logger_1.Logger(info.project.projectService.logger);
@@ -12,17 +16,47 @@ function init(modules) {
12
16
  logger.log('Detected that this is not a Svelte project, abort patching TypeScript');
13
17
  return info.languageService;
14
18
  }
15
- logger.log('Starting Svelte plugin');
16
- // If someone knows a better/more performant way to get svelteOptions,
17
- // please tell us :)
18
- const svelteOptions = ((_d = (_c = (_b = (_a = info.languageServiceHost).getParsedCommandLine) === null || _b === void 0 ? void 0 : _b.call(_a, info.project.getCompilerOptions().configFilePath)) === null || _c === void 0 ? void 0 : _c.raw) === null || _d === void 0 ? void 0 : _d.svelteOptions) || { namespace: 'svelteHTML' };
19
+ if ((0, language_service_1.isPatched)(info.languageService)) {
20
+ logger.log('Already patched. Checking tsconfig updates.');
21
+ (_a = project_svelte_files_1.ProjectSvelteFilesManager.getInstance(info.project.getProjectName())) === null || _a === void 0 ? void 0 : _a.updateProjectConfig(info.languageServiceHost);
22
+ return info.languageService;
23
+ }
24
+ configManager.updateConfigFromPluginConfig(info.config);
25
+ if (configManager.getConfig().enable) {
26
+ logger.log('Starting Svelte plugin');
27
+ }
28
+ else {
29
+ logger.log('Svelte plugin disabled');
30
+ logger.log(info.config);
31
+ }
32
+ // This call the ConfiguredProject.getParsedCommandLine
33
+ // where it'll try to load the cached version of the parsedCommandLine
34
+ const parsedCommandLine = (_c = (_b = info.languageServiceHost).getParsedCommandLine) === null || _c === void 0 ? void 0 : _c.call(_b, (0, utils_1.getConfigPathForProject)(info.project));
35
+ const svelteOptions = ((_d = parsedCommandLine === null || parsedCommandLine === void 0 ? void 0 : parsedCommandLine.raw) === null || _d === void 0 ? void 0 : _d.svelteOptions) || { namespace: 'svelteHTML' };
19
36
  logger.log('svelteOptions:', svelteOptions);
20
- const snapshotManager = new svelte_snapshots_1.SvelteSnapshotManager(modules.typescript, info.project.projectService, svelteOptions, logger);
21
- (0, module_loader_1.patchModuleLoader)(logger, snapshotManager, modules.typescript, info.languageServiceHost, info.project);
22
- return (0, language_service_1.decorateLanguageService)(info.languageService, snapshotManager, logger);
37
+ logger.debug(parsedCommandLine === null || parsedCommandLine === void 0 ? void 0 : parsedCommandLine.wildcardDirectories);
38
+ const snapshotManager = new svelte_snapshots_1.SvelteSnapshotManager(modules.typescript, info.project.projectService, svelteOptions, logger, configManager);
39
+ const projectSvelteFilesManager = parsedCommandLine
40
+ ? new project_svelte_files_1.ProjectSvelteFilesManager(modules.typescript, info.project, info.serverHost, snapshotManager, parsedCommandLine, configManager)
41
+ : undefined;
42
+ (0, module_loader_1.patchModuleLoader)(logger, snapshotManager, modules.typescript, info.languageServiceHost, info.project, configManager);
43
+ configManager.onConfigurationChanged(() => {
44
+ // enabling/disabling the plugin means TS has to recompute stuff
45
+ info.languageService.cleanupSemanticCache();
46
+ info.project.markAsDirty();
47
+ // updateGraph checks for new root files
48
+ // if there's no tsconfig there isn't root files to check
49
+ if (projectSvelteFilesManager) {
50
+ info.project.updateGraph();
51
+ }
52
+ });
53
+ return decorateLanguageServiceDispose((0, language_service_1.decorateLanguageService)(info.languageService, snapshotManager, logger, configManager), projectSvelteFilesManager !== null && projectSvelteFilesManager !== void 0 ? projectSvelteFilesManager : {
54
+ dispose() { }
55
+ });
23
56
  }
24
57
  function getExternalFiles(project) {
25
- if (!isSvelteProject(project.getCompilerOptions())) {
58
+ var _a, _b;
59
+ if (!isSvelteProject(project.getCompilerOptions()) || !configManager.getConfig().enable) {
26
60
  return [];
27
61
  }
28
62
  // Needed so the ambient definitions are known inside the tsx files
@@ -32,7 +66,8 @@ function init(modules) {
32
66
  './svelte-jsx.d.ts',
33
67
  './svelte-native-jsx.d.ts'
34
68
  ].map((f) => modules.typescript.sys.resolvePath((0, path_1.resolve)(svelteTsPath, f)));
35
- return svelteTsxFiles;
69
+ // let ts know project svelte files to do its optimization
70
+ return svelteTsxFiles.concat((_b = (_a = project_svelte_files_1.ProjectSvelteFilesManager.getInstance(project.getProjectName())) === null || _a === void 0 ? void 0 : _a.getFiles()) !== null && _b !== void 0 ? _b : []);
36
71
  }
37
72
  function isSvelteProject(compilerOptions) {
38
73
  // Add more checks like "no Svelte file found" or "no config file found"?
@@ -46,6 +81,17 @@ function init(modules) {
46
81
  return false;
47
82
  }
48
83
  }
49
- return { create, getExternalFiles };
84
+ function onConfigurationChanged(config) {
85
+ configManager.updateConfigFromPluginConfig(config);
86
+ }
87
+ function decorateLanguageServiceDispose(languageService, disposable) {
88
+ const dispose = languageService.dispose;
89
+ languageService.dispose = () => {
90
+ disposable.dispose();
91
+ dispose();
92
+ };
93
+ return languageService;
94
+ }
95
+ return { create, getExternalFiles, onConfigurationChanged };
50
96
  }
51
97
  module.exports = init;
@@ -27,7 +27,16 @@ function decorateCompletions(ls, logger) {
27
27
  const getCompletionEntryDetails = ls.getCompletionEntryDetails;
28
28
  ls.getCompletionEntryDetails = (fileName, position, entryName, formatOptions, source, preferences, data) => {
29
29
  const details = getCompletionEntryDetails(fileName, position, entryName, formatOptions, source, preferences, data);
30
- if (details || !(0, utils_1.isSvelteFilePath)(source || '')) {
30
+ if (details) {
31
+ if ((0, utils_1.isSvelteFilePath)(source || '')) {
32
+ logger.debug('TS found Svelte Component import completion details');
33
+ return (0, utils_1.replaceDeep)(details, componentPostfix, '');
34
+ }
35
+ else {
36
+ return details;
37
+ }
38
+ }
39
+ if (!(0, utils_1.isSvelteFilePath)(source || '')) {
31
40
  return details;
32
41
  }
33
42
  // In the completion list we removed the component postfix. Internally,
@@ -14,7 +14,10 @@ function _decorateFindReferences(ls, snapshotManager, logger) {
14
14
  return references === null || references === void 0 ? void 0 : references.map((reference) => {
15
15
  const snapshot = snapshotManager.get(reference.definition.fileName);
16
16
  if (!(0, utils_1.isSvelteFilePath)(reference.definition.fileName) || !snapshot) {
17
- return reference;
17
+ return {
18
+ ...reference,
19
+ references: mapReferences(reference.references, snapshotManager, logger)
20
+ };
18
21
  }
19
22
  const textSpan = snapshot.getOriginalTextSpan(reference.definition.textSpan);
20
23
  if (!textSpan) {
@@ -1,4 +1,6 @@
1
1
  import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { ConfigManager } from '../config-manager';
2
3
  import { Logger } from '../logger';
3
4
  import { SvelteSnapshotManager } from '../svelte-snapshots';
4
- export declare function decorateLanguageService(ls: ts.LanguageService, snapshotManager: SvelteSnapshotManager, logger: Logger): ts.LanguageService;
5
+ export declare function isPatched(ls: ts.LanguageService): boolean;
6
+ export declare function decorateLanguageService(ls: ts.LanguageService, snapshotManager: SvelteSnapshotManager, logger: Logger, configManager: ConfigManager): ts.LanguageService;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decorateLanguageService = void 0;
3
+ exports.decorateLanguageService = exports.isPatched = void 0;
4
4
  const utils_1 = require("../utils");
5
5
  const completions_1 = require("./completions");
6
6
  const definition_1 = require("./definition");
@@ -8,7 +8,21 @@ const diagnostics_1 = require("./diagnostics");
8
8
  const find_references_1 = require("./find-references");
9
9
  const implementation_1 = require("./implementation");
10
10
  const rename_1 = require("./rename");
11
- function decorateLanguageService(ls, snapshotManager, logger) {
11
+ const update_imports_1 = require("./update-imports");
12
+ const sveltePluginPatchSymbol = Symbol('sveltePluginPatchSymbol');
13
+ function isPatched(ls) {
14
+ return ls[sveltePluginPatchSymbol] === true;
15
+ }
16
+ exports.isPatched = isPatched;
17
+ function decorateLanguageService(ls, snapshotManager, logger, configManager) {
18
+ // Decorate using a proxy so we can dynamically enable/disable method
19
+ // patches depending on the enabled state of our config
20
+ const proxy = new Proxy(ls, createProxyHandler(configManager));
21
+ decorateLanguageServiceInner(proxy, snapshotManager, logger);
22
+ return proxy;
23
+ }
24
+ exports.decorateLanguageService = decorateLanguageService;
25
+ function decorateLanguageServiceInner(ls, snapshotManager, logger) {
12
26
  patchLineColumnOffset(ls, snapshotManager);
13
27
  (0, rename_1.decorateRename)(ls, snapshotManager, logger);
14
28
  (0, diagnostics_1.decorateDiagnostics)(ls, logger);
@@ -16,9 +30,29 @@ function decorateLanguageService(ls, snapshotManager, logger) {
16
30
  (0, completions_1.decorateCompletions)(ls, logger);
17
31
  (0, definition_1.decorateGetDefinition)(ls, snapshotManager, logger);
18
32
  (0, implementation_1.decorateGetImplementation)(ls, snapshotManager, logger);
33
+ (0, update_imports_1.decorateUpdateImports)(ls, snapshotManager, logger);
19
34
  return ls;
20
35
  }
21
- exports.decorateLanguageService = decorateLanguageService;
36
+ function createProxyHandler(configManager) {
37
+ const decorated = {};
38
+ return {
39
+ get(target, p) {
40
+ var _a;
41
+ // always return patch symbol whether the plugin is enabled or not
42
+ if (p === sveltePluginPatchSymbol) {
43
+ return true;
44
+ }
45
+ if (!configManager.getConfig().enable || p === 'dispose') {
46
+ return target[p];
47
+ }
48
+ return ((_a = decorated[p]) !== null && _a !== void 0 ? _a : target[p]);
49
+ },
50
+ set(_, p, value) {
51
+ decorated[p] = value;
52
+ return true;
53
+ }
54
+ };
55
+ }
22
56
  function patchLineColumnOffset(ls, snapshotManager) {
23
57
  if (!ls.toLineColumnOffset) {
24
58
  return;
@@ -0,0 +1,4 @@
1
+ import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { Logger } from '../logger';
3
+ import { SvelteSnapshotManager } from '../svelte-snapshots';
4
+ export declare function decorateUpdateImports(ls: ts.LanguageService, snapshotManager: SvelteSnapshotManager, logger: Logger): void;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decorateUpdateImports = void 0;
4
+ const utils_1 = require("../utils");
5
+ function decorateUpdateImports(ls, snapshotManager, logger) {
6
+ const getEditsForFileRename = ls.getEditsForFileRename;
7
+ ls.getEditsForFileRename = (oldFilePath, newFilePath, formatOptions, preferences) => {
8
+ const renameLocations = getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences);
9
+ // If a file move/rename of a TS/JS file results a Svelte file change,
10
+ // the Svelte extension will notice that, too, and adjusts the same imports.
11
+ // This results in duplicate adjustments or race conditions with conflicting text spans
12
+ // which can break imports in some cases.
13
+ // Therefore don't do any updates of Svelte files and and also no updates of mixed TS files
14
+ // and let the Svelte extension handle that.
15
+ return renameLocations === null || renameLocations === void 0 ? void 0 : renameLocations.filter((renameLocation) => {
16
+ return (!(0, utils_1.isSvelteFilePath)(renameLocation.fileName) &&
17
+ !renameLocation.textChanges.some((change) => change.newText.endsWith('.svelte')));
18
+ });
19
+ };
20
+ }
21
+ exports.decorateUpdateImports = decorateUpdateImports;
@@ -1,4 +1,5 @@
1
1
  import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { ConfigManager } from './config-manager';
2
3
  import { Logger } from './logger';
3
4
  import { SvelteSnapshotManager } from './svelte-snapshots';
4
5
  /**
@@ -10,4 +11,4 @@ import { SvelteSnapshotManager } from './svelte-snapshots';
10
11
  * so it assumes it's a normal typescript file and searches for files like `../Component.svelte.ts`, which is wrong.
11
12
  * In order to fix this, we need to wrap typescript's module resolution and reroute all `.svelte.ts` file lookups to .svelte.
12
13
  */
13
- export declare function patchModuleLoader(logger: Logger, snapshotManager: SvelteSnapshotManager, typescript: typeof ts, lsHost: ts.LanguageServiceHost, project: ts.server.Project): void;
14
+ export declare function patchModuleLoader(logger: Logger, snapshotManager: SvelteSnapshotManager, typescript: typeof ts, lsHost: ts.LanguageServiceHost, project: ts.server.Project, configManager: ConfigManager): void;
@@ -36,6 +36,9 @@ class ModuleResolutionCache {
36
36
  }
37
37
  });
38
38
  }
39
+ clear() {
40
+ this.cache.clear();
41
+ }
39
42
  getKey(moduleName, containingFile) {
40
43
  return containingFile + ':::' + (0, utils_1.ensureRealSvelteFilePath)(moduleName);
41
44
  }
@@ -49,7 +52,7 @@ class ModuleResolutionCache {
49
52
  * so it assumes it's a normal typescript file and searches for files like `../Component.svelte.ts`, which is wrong.
50
53
  * In order to fix this, we need to wrap typescript's module resolution and reroute all `.svelte.ts` file lookups to .svelte.
51
54
  */
52
- function patchModuleLoader(logger, snapshotManager, typescript, lsHost, project) {
55
+ function patchModuleLoader(logger, snapshotManager, typescript, lsHost, project, configManager) {
53
56
  var _a;
54
57
  const svelteSys = (0, svelte_sys_1.createSvelteSys)(logger);
55
58
  const moduleCache = new ModuleResolutionCache();
@@ -61,6 +64,9 @@ function patchModuleLoader(logger, snapshotManager, typescript, lsHost, project)
61
64
  moduleCache.delete(info.fileName);
62
65
  return origRemoveFile(info, fileExists, detachFromProject);
63
66
  };
67
+ configManager.onConfigurationChanged(() => {
68
+ moduleCache.clear();
69
+ });
64
70
  function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, compilerOptions) {
65
71
  logger.log('Resolving modules names for ' + containingFile);
66
72
  // Try resolving all module names with the original method first.
@@ -68,6 +74,9 @@ function patchModuleLoader(logger, snapshotManager, typescript, lsHost, project)
68
74
  // Svelte file and if so, are resolved, too. This way we can defer
69
75
  // all module resolving logic except for Svelte files to TypeScript.
70
76
  const resolved = (origResolveModuleNames === null || origResolveModuleNames === void 0 ? void 0 : origResolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, compilerOptions)) || Array.from(Array(moduleNames.length));
77
+ if (!configManager.getConfig().enable) {
78
+ return resolved;
79
+ }
71
80
  return resolved.map((moduleName, idx) => {
72
81
  const fileName = moduleNames[idx];
73
82
  if (moduleName || !(0, utils_1.ensureRealSvelteFilePath)(fileName).endsWith('.svelte')) {
@@ -0,0 +1,35 @@
1
+ import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { ConfigManager } from './config-manager';
3
+ import { SvelteSnapshotManager } from './svelte-snapshots';
4
+ export interface TsFilesSpec {
5
+ include?: readonly string[];
6
+ exclude?: readonly string[];
7
+ }
8
+ export declare class ProjectSvelteFilesManager {
9
+ private readonly typescript;
10
+ private readonly project;
11
+ private readonly serverHost;
12
+ private readonly snapshotManager;
13
+ private parsedCommandLine;
14
+ private files;
15
+ private directoryWatchers;
16
+ private static instances;
17
+ static getInstance(projectName: string): ProjectSvelteFilesManager | undefined;
18
+ constructor(typescript: typeof ts, project: ts.server.Project, serverHost: ts.server.ServerHost, snapshotManager: SvelteSnapshotManager, parsedCommandLine: ts.ParsedCommandLine, configManager: ConfigManager);
19
+ updateProjectConfig(serviceHost: ts.LanguageServiceHost): void;
20
+ getFiles(): string[];
21
+ /**
22
+ * Create directory watcher for include and exclude
23
+ * The watcher in tsserver doesn't support svelte file
24
+ * It won't add new created svelte file to root
25
+ */
26
+ private setupWatchers;
27
+ private watcherCallback;
28
+ private updateProjectSvelteFiles;
29
+ private addFileToProject;
30
+ private readProjectSvelteFilesFromFs;
31
+ private onConfigChanged;
32
+ private removeFileFromProject;
33
+ private disposeWatchersAndFiles;
34
+ dispose(): void;
35
+ }
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProjectSvelteFilesManager = void 0;
4
+ const utils_1 = require("./utils");
5
+ class ProjectSvelteFilesManager {
6
+ constructor(typescript, project, serverHost, snapshotManager, parsedCommandLine, configManager) {
7
+ this.typescript = typescript;
8
+ this.project = project;
9
+ this.serverHost = serverHost;
10
+ this.snapshotManager = snapshotManager;
11
+ this.parsedCommandLine = parsedCommandLine;
12
+ this.files = new Set();
13
+ this.directoryWatchers = new Set();
14
+ if (configManager.getConfig().enable) {
15
+ this.setupWatchers();
16
+ this.updateProjectSvelteFiles();
17
+ }
18
+ configManager.onConfigurationChanged(this.onConfigChanged.bind(this));
19
+ ProjectSvelteFilesManager.instances.set(project.getProjectName(), this);
20
+ }
21
+ static getInstance(projectName) {
22
+ return this.instances.get(projectName);
23
+ }
24
+ updateProjectConfig(serviceHost) {
25
+ var _a;
26
+ const parsedCommandLine = (_a = serviceHost.getParsedCommandLine) === null || _a === void 0 ? void 0 : _a.call(serviceHost, (0, utils_1.getConfigPathForProject)(this.project));
27
+ if (!parsedCommandLine) {
28
+ return;
29
+ }
30
+ this.disposeWatchersAndFiles();
31
+ this.parsedCommandLine = parsedCommandLine;
32
+ this.setupWatchers();
33
+ this.updateProjectSvelteFiles();
34
+ }
35
+ getFiles() {
36
+ return Array.from(this.files);
37
+ }
38
+ /**
39
+ * Create directory watcher for include and exclude
40
+ * The watcher in tsserver doesn't support svelte file
41
+ * It won't add new created svelte file to root
42
+ */
43
+ setupWatchers() {
44
+ for (const directory in this.parsedCommandLine.wildcardDirectories) {
45
+ if (!Object.prototype.hasOwnProperty.call(this.parsedCommandLine.wildcardDirectories, directory)) {
46
+ continue;
47
+ }
48
+ const watchDirectoryFlags = this.parsedCommandLine.wildcardDirectories[directory];
49
+ const watcher = this.serverHost.watchDirectory(directory, this.watcherCallback.bind(this), watchDirectoryFlags === this.typescript.WatchDirectoryFlags.Recursive, this.parsedCommandLine.watchOptions);
50
+ this.directoryWatchers.add(watcher);
51
+ }
52
+ }
53
+ watcherCallback(fileName) {
54
+ if (!(0, utils_1.isSvelteFilePath)(fileName)) {
55
+ return;
56
+ }
57
+ // We can't just add the file to the project directly, because
58
+ // - the casing of fileName is different
59
+ // - we don't know whether the file was added or deleted
60
+ this.updateProjectSvelteFiles();
61
+ }
62
+ updateProjectSvelteFiles() {
63
+ const fileNamesAfter = this.readProjectSvelteFilesFromFs();
64
+ const removedFiles = new Set(...this.files);
65
+ const newFiles = fileNamesAfter.filter((fileName) => {
66
+ const has = this.files.has(fileName);
67
+ if (has) {
68
+ removedFiles.delete(fileName);
69
+ }
70
+ return !has;
71
+ });
72
+ for (const newFile of newFiles) {
73
+ this.addFileToProject(newFile);
74
+ this.files.add(newFile);
75
+ }
76
+ for (const removedFile of removedFiles) {
77
+ this.removeFileFromProject(removedFile, false);
78
+ this.files.delete(removedFile);
79
+ }
80
+ }
81
+ addFileToProject(newFile) {
82
+ this.snapshotManager.create(newFile);
83
+ const snapshot = this.project.projectService.getScriptInfo(newFile);
84
+ if (snapshot) {
85
+ this.project.addRoot(snapshot);
86
+ }
87
+ }
88
+ readProjectSvelteFilesFromFs() {
89
+ const fileSpec = this.parsedCommandLine.raw;
90
+ const { include, exclude } = fileSpec;
91
+ if ((include === null || include === void 0 ? void 0 : include.length) === 0) {
92
+ return [];
93
+ }
94
+ return this.typescript.sys
95
+ .readDirectory(this.project.getCurrentDirectory() || process.cwd(), ['.svelte'], exclude, include)
96
+ .map(this.typescript.server.toNormalizedPath);
97
+ }
98
+ onConfigChanged(config) {
99
+ this.disposeWatchersAndFiles();
100
+ if (config.enable) {
101
+ this.setupWatchers();
102
+ this.updateProjectSvelteFiles();
103
+ }
104
+ }
105
+ removeFileFromProject(file, exists = true) {
106
+ const info = this.project.getScriptInfo(file);
107
+ if (info) {
108
+ this.project.removeFile(info, exists, true);
109
+ }
110
+ }
111
+ disposeWatchersAndFiles() {
112
+ this.directoryWatchers.forEach((watcher) => watcher.close());
113
+ this.directoryWatchers.clear();
114
+ this.files.forEach((file) => this.removeFileFromProject(file));
115
+ this.files.clear();
116
+ }
117
+ dispose() {
118
+ this.disposeWatchersAndFiles();
119
+ ProjectSvelteFilesManager.instances.delete(this.project.getProjectName());
120
+ }
121
+ }
122
+ exports.ProjectSvelteFilesManager = ProjectSvelteFilesManager;
123
+ ProjectSvelteFilesManager.instances = new Map();
@@ -1,4 +1,5 @@
1
1
  import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { ConfigManager } from './config-manager';
2
3
  import { Logger } from './logger';
3
4
  import { SourceMapper } from './source-mapper';
4
5
  export declare class SvelteSnapshot {
@@ -38,10 +39,11 @@ export declare class SvelteSnapshotManager {
38
39
  private projectService;
39
40
  private svelteOptions;
40
41
  private logger;
42
+ private configManager;
41
43
  private snapshots;
42
44
  constructor(typescript: typeof ts, projectService: ts.server.ProjectService, svelteOptions: {
43
45
  namespace: string;
44
- }, logger: Logger);
46
+ }, logger: Logger, configManager: ConfigManager);
45
47
  get(fileName: string): SvelteSnapshot | undefined;
46
48
  create(fileName: string): SvelteSnapshot | undefined;
47
49
  private patchProjectServiceReadFile;
@@ -189,11 +189,12 @@ class SvelteSnapshot {
189
189
  }
190
190
  exports.SvelteSnapshot = SvelteSnapshot;
191
191
  class SvelteSnapshotManager {
192
- constructor(typescript, projectService, svelteOptions, logger) {
192
+ constructor(typescript, projectService, svelteOptions, logger, configManager) {
193
193
  this.typescript = typescript;
194
194
  this.projectService = projectService;
195
195
  this.svelteOptions = svelteOptions;
196
196
  this.logger = logger;
197
+ this.configManager = configManager;
197
198
  this.snapshots = new Map();
198
199
  this.patchProjectServiceReadFile();
199
200
  }
@@ -228,7 +229,27 @@ class SvelteSnapshotManager {
228
229
  patchProjectServiceReadFile() {
229
230
  const readFile = this.projectService.host.readFile;
230
231
  this.projectService.host.readFile = (path) => {
231
- if ((0, utils_1.isSvelteFilePath)(path)) {
232
+ // The following (very hacky) first two checks make sure that the ambient module definitions
233
+ // that tell TS "every import ending with .svelte is a valid module" are removed.
234
+ // They exist in svelte2tsx and svelte to make sure that people don't
235
+ // get errors in their TS files when importing Svelte files and not using our TS plugin.
236
+ // If someone wants to get back the behavior they can add an ambient module definition
237
+ // on their own.
238
+ const normalizedPath = path.replace(/\\/g, '/');
239
+ if (normalizedPath.endsWith('node_modules/svelte/types/runtime/ambient.d.ts')) {
240
+ return '';
241
+ }
242
+ else if (normalizedPath.endsWith('svelte2tsx/svelte-shims.d.ts')) {
243
+ let originalText = readFile(path) || '';
244
+ if (!originalText.includes('// -- start svelte-ls-remove --')) {
245
+ return originalText; // uses an older version of svelte2tsx
246
+ }
247
+ originalText =
248
+ originalText.substring(0, originalText.indexOf('// -- start svelte-ls-remove --')) +
249
+ originalText.substring(originalText.indexOf('// -- end svelte-ls-remove --'));
250
+ return originalText;
251
+ }
252
+ else if ((0, utils_1.isSvelteFilePath)(path) && this.configManager.getConfig().enable) {
232
253
  this.logger.debug('Read Svelte file:', path);
233
254
  const svelteCode = readFile(path) || '';
234
255
  try {
@@ -250,8 +271,11 @@ class SvelteSnapshotManager {
250
271
  return result.code;
251
272
  }
252
273
  catch (e) {
253
- this.logger.log('Error loading Svelte file:', path);
274
+ this.logger.log('Error loading Svelte file:', path, ' Using fallback.');
254
275
  this.logger.debug('Error:', e);
276
+ // Return something either way, else "X is not a module" errors will appear
277
+ // in the TS files that use this file.
278
+ return 'export default class extends Svelte2TsxComponent<any,any,any> {}';
255
279
  }
256
280
  }
257
281
  else {
@@ -1,3 +1,4 @@
1
+ import type ts from 'typescript/lib/tsserverlibrary';
1
2
  export declare function isSvelteFilePath(filePath: string): boolean;
2
3
  export declare function isVirtualSvelteFilePath(filePath: string): boolean;
3
4
  export declare function toRealSvelteFilePath(filePath: string): string;
@@ -17,3 +18,4 @@ export declare function isNoTextSpanInGeneratedCode(text: string, span: ts.TextS
17
18
  * Replace all occurrences of a string within an object with another string,
18
19
  */
19
20
  export declare function replaceDeep<T extends Record<string, any>>(obj: T, searchStr: string | RegExp, replacementStr: string): T;
21
+ export declare function getConfigPathForProject(project: ts.server.Project): ts.server.NormalizedPath;
package/dist/src/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.replaceDeep = exports.isNoTextSpanInGeneratedCode = exports.isInGeneratedCode = exports.isNotNullOrUndefined = exports.ensureRealSvelteFilePath = exports.toRealSvelteFilePath = exports.isVirtualSvelteFilePath = exports.isSvelteFilePath = void 0;
3
+ exports.getConfigPathForProject = exports.replaceDeep = exports.isNoTextSpanInGeneratedCode = exports.isInGeneratedCode = exports.isNotNullOrUndefined = exports.ensureRealSvelteFilePath = exports.toRealSvelteFilePath = exports.isVirtualSvelteFilePath = exports.isSvelteFilePath = void 0;
4
4
  function isSvelteFilePath(filePath) {
5
5
  return filePath.endsWith('.svelte');
6
6
  }
@@ -63,3 +63,8 @@ function replaceDeep(obj, searchStr, replacementStr) {
63
63
  }
64
64
  }
65
65
  exports.replaceDeep = replaceDeep;
66
+ function getConfigPathForProject(project) {
67
+ var _a;
68
+ return ((_a = project.canonicalConfigFilePath) !== null && _a !== void 0 ? _a : project.getCompilerOptions().configFilePath);
69
+ }
70
+ exports.getConfigPathForProject = getConfigPathForProject;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-svelte-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.3.3",
4
4
  "description": "A TypeScript Plugin providing Svelte intellisense",
5
5
  "main": "dist/src/index.js",
6
6
  "scripts": {