typescript-svelte-plugin 0.3.18 → 0.3.19

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/dist/src/index.js CHANGED
@@ -121,15 +121,7 @@ function init(modules) {
121
121
  }
122
122
  function isSvelteProject(compilerOptions) {
123
123
  // Add more checks like "no Svelte file found" or "no config file found"?
124
- try {
125
- const isSvelteProject = typeof compilerOptions.configFilePath !== 'string' ||
126
- require.resolve('svelte', { paths: [compilerOptions.configFilePath] });
127
- return isSvelteProject;
128
- }
129
- catch (e) {
130
- // If require.resolve fails, we end up here
131
- return false;
132
- }
124
+ return (0, utils_1.hasNodeModule)(compilerOptions, 'svelte');
133
125
  }
134
126
  function onConfigurationChanged(config) {
135
127
  configManager.updateConfigFromPluginConfig(config);
@@ -37,7 +37,9 @@ function decorateCompletions(ls, info, ts, logger) {
37
37
  const node = source && (0, utils_1.findNodeAtPosition)(source, position);
38
38
  if (node && (0, utils_1.isTopLevelExport)(ts, node, source)) {
39
39
  return {
40
- entries: Object.entries(sveltekit_1.kitExports).map(([key, value]) => ({
40
+ entries: Object.entries(sveltekit_1.kitExports)
41
+ .filter(([, value]) => (0, sveltekit_1.isKitRouteExportAllowedIn)((0, path_1.basename)(fileName), value))
42
+ .map(([key, value]) => ({
41
43
  kind: ts.ScriptElementKind.constElement,
42
44
  name: key,
43
45
  labelDetails: {
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.decorateDiagnostics = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const svelte2tsx_1 = require("svelte2tsx");
4
9
  const utils_1 = require("../utils");
5
10
  const sveltekit_1 = require("./sveltekit");
6
11
  function decorateDiagnostics(ls, info, typescript, logger) {
@@ -46,6 +51,7 @@ function decorateSuggestionDiagnostics(ls, info, typescript, logger) {
46
51
  };
47
52
  }
48
53
  function getKitDiagnostics(methodName, fileName, info, ts, logger) {
54
+ var _a, _b;
49
55
  const result = (0, sveltekit_1.getVirtualLS)(fileName, info, ts, logger);
50
56
  if (!result)
51
57
  return;
@@ -59,10 +65,7 @@ function getKitDiagnostics(methodName, fileName, info, ts, logger) {
59
65
  const mapped = toOriginalPos(diagnostic.start);
60
66
  if (mapped.inGenerated) {
61
67
  // If not "Cannot find module './$types' .." then filter out
62
- if (diagnostic.code !== 2307) {
63
- continue;
64
- }
65
- else {
68
+ if (diagnostic.code === 2307) {
66
69
  diagnostic = {
67
70
  ...diagnostic,
68
71
  // adjust length so it doesn't spill over to the next line
@@ -70,10 +73,33 @@ function getKitDiagnostics(methodName, fileName, info, ts, logger) {
70
73
  messageText: typeof diagnostic.messageText === 'string' &&
71
74
  diagnostic.messageText.includes('./$types')
72
75
  ? diagnostic.messageText +
73
- ` (this likely means that SvelteKit's type generation didn't run yet)`
76
+ ` (this likely means that SvelteKit's type generation didn't run yet - try running it by executing 'npm run dev' or 'npm run build')`
77
+ : diagnostic.messageText
78
+ };
79
+ }
80
+ else if (diagnostic.code === 2694) {
81
+ diagnostic = {
82
+ ...diagnostic,
83
+ // adjust length so it doesn't spill over to the next line
84
+ length: 1,
85
+ messageText: typeof diagnostic.messageText === 'string' &&
86
+ diagnostic.messageText.includes('/$types')
87
+ ? diagnostic.messageText +
88
+ ` (this likely means that SvelteKit's generated types are out of date - try rerunning it by executing 'npm run dev' or 'npm run build')`
74
89
  : diagnostic.messageText
75
90
  };
76
91
  }
92
+ else if (diagnostic.code === 2355) {
93
+ // A function whose declared type is neither 'void' nor 'any' must return a value
94
+ diagnostic = {
95
+ ...diagnostic,
96
+ // adjust length so it doesn't spill over to the next line
97
+ length: 1
98
+ };
99
+ }
100
+ else {
101
+ continue;
102
+ }
77
103
  }
78
104
  diagnostic = {
79
105
  ...diagnostic,
@@ -81,6 +107,30 @@ function getKitDiagnostics(methodName, fileName, info, ts, logger) {
81
107
  };
82
108
  diagnostics.push(diagnostic);
83
109
  }
110
+ if (methodName === 'getSemanticDiagnostics') {
111
+ // We're in a Svelte file - check top level exports
112
+ // We're using the original file to have the correct position without mapping
113
+ const source = (_a = info.languageService.getProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFile(fileName);
114
+ const basename = path_1.default.basename(fileName);
115
+ const validExports = Object.keys(sveltekit_1.kitExports).filter((key) => (0, sveltekit_1.isKitRouteExportAllowedIn)(basename, sveltekit_1.kitExports[key]));
116
+ if (source && basename.startsWith('+')) {
117
+ const exports = svelte2tsx_1.internalHelpers.findExports(source, /* irrelevant */ false);
118
+ for (const exportName of exports.keys()) {
119
+ if (!validExports.includes(exportName) && !exportName.startsWith('_')) {
120
+ const node = exports.get(exportName).node;
121
+ const identifier = (_b = (0, utils_1.findIdentifier)(ts, node)) !== null && _b !== void 0 ? _b : node;
122
+ diagnostics.push({
123
+ file: source,
124
+ start: identifier.getStart(),
125
+ length: identifier.getEnd() - identifier.getStart(),
126
+ messageText: `Invalid export '${exportName}' (valid exports are ${validExports.join(', ')}, or anything with a '_' prefix)`,
127
+ category: ts.DiagnosticCategory.Error,
128
+ code: 71001 // arbitrary
129
+ });
130
+ }
131
+ }
132
+ }
133
+ }
84
134
  // @ts-ignore TS doesn't get the return type right
85
135
  return diagnostics;
86
136
  }
@@ -9,6 +9,7 @@ const diagnostics_1 = require("./diagnostics");
9
9
  const find_references_1 = require("./find-references");
10
10
  const hover_1 = require("./hover");
11
11
  const implementation_1 = require("./implementation");
12
+ const inlay_hints_1 = require("./inlay-hints");
12
13
  const rename_1 = require("./rename");
13
14
  const update_imports_1 = require("./update-imports");
14
15
  const sveltePluginPatchSymbol = Symbol('sveltePluginPatchSymbol');
@@ -35,6 +36,7 @@ function decorateLanguageServiceInner(ls, snapshotManager, logger, info, typescr
35
36
  (0, update_imports_1.decorateUpdateImports)(ls, snapshotManager, logger);
36
37
  (0, call_hierarchy_1.decorateCallHierarchy)(ls, snapshotManager, typescript);
37
38
  (0, hover_1.decorateHover)(ls, info, typescript, logger);
39
+ (0, inlay_hints_1.decorateInlayHints)(ls, info, typescript, logger);
38
40
  return ls;
39
41
  }
40
42
  function createProxyHandler(configManager) {
@@ -0,0 +1,5 @@
1
+ import type ts from 'typescript/lib/tsserverlibrary';
2
+ import { Logger } from '../logger';
3
+ type _ts = typeof ts;
4
+ export declare function decorateInlayHints(ls: ts.LanguageService, info: ts.server.PluginCreateInfo, ts: _ts, logger: Logger): void;
5
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decorateInlayHints = void 0;
4
+ const sveltekit_1 = require("./sveltekit");
5
+ function decorateInlayHints(ls, info, ts, logger) {
6
+ const provideInlayHints = ls.provideInlayHints;
7
+ ls.provideInlayHints = (fileName, span, preferences) => {
8
+ const result = (0, sveltekit_1.getVirtualLS)(fileName, info, ts);
9
+ if (!result) {
10
+ return provideInlayHints(fileName, span, preferences);
11
+ }
12
+ const { languageService, toVirtualPos, toOriginalPos } = result;
13
+ return languageService
14
+ .provideInlayHints(fileName, {
15
+ start: toVirtualPos(span.start),
16
+ length: span.length
17
+ }, preferences)
18
+ .map((hint) => ({
19
+ ...hint,
20
+ position: toOriginalPos(hint.position).pos
21
+ }));
22
+ };
23
+ }
24
+ exports.decorateInlayHints = decorateInlayHints;
25
+ //# sourceMappingURL=inlay-hints.js.map
@@ -1,135 +1,20 @@
1
1
  import type ts from 'typescript/lib/tsserverlibrary';
2
2
  import { Logger } from '../logger';
3
+ import { InternalHelpers } from 'svelte2tsx';
3
4
  type _ts = typeof ts;
4
- interface KitSnapshot {
5
- file: ts.IScriptSnapshot;
6
- version: string;
7
- addedCode: Array<{
8
- generatedPos: number;
9
- originalPos: number;
10
- length: number;
11
- total: number;
12
- inserted: string;
13
- }>;
14
- }
15
- export declare const kitExports: {
16
- prerender: {
17
- displayParts: {
18
- text: string;
19
- kind: string;
20
- }[];
21
- documentation: {
22
- text: string;
23
- kind: string;
24
- }[];
25
- };
26
- ssr: {
27
- displayParts: {
28
- text: string;
29
- kind: string;
30
- }[];
31
- documentation: {
32
- text: string;
33
- kind: string;
34
- }[];
35
- };
36
- csr: {
37
- displayParts: {
38
- text: string;
39
- kind: string;
40
- }[];
41
- documentation: {
42
- text: string;
43
- kind: string;
44
- }[];
45
- };
46
- trailingSlash: {
47
- displayParts: {
48
- text: string;
49
- kind: string;
50
- }[];
51
- documentation: {
52
- text: string;
53
- kind: string;
54
- }[];
55
- };
56
- config: {
57
- displayParts: {
58
- text: string;
59
- kind: string;
60
- }[];
61
- documentation: {
62
- text: string;
63
- kind: string;
64
- }[];
65
- };
66
- actions: {
67
- displayParts: {
68
- text: string;
69
- kind: string;
70
- }[];
71
- documentation: {
72
- text: string;
73
- kind: string;
74
- }[];
75
- };
76
- load: {
77
- displayParts: {
78
- text: string;
79
- kind: string;
80
- }[];
81
- documentation: {
82
- text: string;
83
- kind: string;
84
- }[];
85
- };
86
- };
87
- export declare function getProxiedLanguageService(info: ts.server.PluginCreateInfo, ts: _ts, logger?: Logger): {
88
- languageService: ts.LanguageService;
89
- languageServiceHost: ts.LanguageServiceHost & {
90
- getKitScriptSnapshotIfUpToDate: (fileName: string) => KitSnapshot | undefined;
91
- upsertKitFile: (fileName: string) => void;
92
- };
93
- } | {
94
- languageService: ts.LanguageService;
95
- languageServiceHost: {
96
- files: Record<string, KitSnapshot>;
97
- log(): void;
98
- trace(): void;
99
- error(): void;
100
- getCompilationSettings(): ts.CompilerOptions;
101
- getScriptIsOpen(): boolean;
102
- getCurrentDirectory(): string;
103
- getDefaultLibFileName(o: any): string;
104
- resolveModuleNames: ((...args: any[]) => (ts.ResolvedModule | undefined)[]) | undefined;
105
- resolveModuleNameLiterals: ((...args: any[]) => readonly ts.ResolvedModuleWithFailedLookupLocations[]) | undefined;
106
- getScriptVersion(fileName: string): string;
107
- getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined;
108
- getScriptFileNames(): string[];
109
- getKitScriptSnapshotIfUpToDate(fileName: string): KitSnapshot | undefined;
110
- upsertKitFile(fileName: string): KitSnapshot | undefined;
111
- readFile(fileName: string): string | undefined;
112
- fileExists(fileName: string): boolean;
113
- };
114
- };
5
+ export declare const kitExports: Record<string, {
6
+ displayParts: ts.SymbolDisplayPart[];
7
+ documentation: ts.SymbolDisplayPart[];
8
+ allowedIn: Array<'server' | 'universal' | 'layout' | 'page' | 'api'>;
9
+ }>;
10
+ export declare function isKitRouteExportAllowedIn(basename: string, kitExport: typeof kitExports[keyof typeof kitExports]): boolean;
115
11
  export declare function getVirtualLS(fileName: string, info: ts.server.PluginCreateInfo, ts: _ts, logger?: Logger): {
116
12
  languageService: ts.LanguageService;
117
- addedCode: {
118
- generatedPos: number;
119
- originalPos: number;
120
- length: number;
121
- total: number;
122
- inserted: string;
123
- }[];
13
+ addedCode: InternalHelpers.AddedCode[];
124
14
  toVirtualPos: (pos: number) => number;
125
15
  toOriginalPos: (pos: number) => {
126
16
  pos: number;
127
17
  inGenerated: boolean;
128
18
  };
129
19
  } | undefined;
130
- export declare function toVirtualPos(pos: number, addedCode: KitSnapshot['addedCode']): number;
131
- export declare function toOriginalPos(pos: number, addedCode: KitSnapshot['addedCode']): {
132
- pos: number;
133
- inGenerated: boolean;
134
- };
135
20
  export {};
@@ -1,13 +1,116 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
4
24
  };
5
25
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.toOriginalPos = exports.toVirtualPos = exports.getVirtualLS = exports.getProxiedLanguageService = exports.kitExports = void 0;
7
- const path_1 = __importDefault(require("path"));
26
+ exports.getVirtualLS = exports.isKitRouteExportAllowedIn = exports.kitExports = void 0;
27
+ const utils_1 = require("../utils");
28
+ const svelte2tsx_1 = require("svelte2tsx");
8
29
  const cache = new WeakMap();
30
+ function createApiExport(name) {
31
+ return {
32
+ allowedIn: ['api', 'server'],
33
+ displayParts: [
34
+ {
35
+ text: 'export',
36
+ kind: 'keyword'
37
+ },
38
+ {
39
+ text: ' ',
40
+ kind: 'space'
41
+ },
42
+ {
43
+ text: 'async',
44
+ kind: 'keyword'
45
+ },
46
+ {
47
+ text: ' ',
48
+ kind: 'space'
49
+ },
50
+ {
51
+ text: 'function',
52
+ kind: 'keyword'
53
+ },
54
+ {
55
+ text: ' ',
56
+ kind: 'space'
57
+ },
58
+ {
59
+ text: name,
60
+ kind: 'localName'
61
+ },
62
+ {
63
+ text: '(',
64
+ kind: 'punctuation'
65
+ },
66
+ {
67
+ text: 'event',
68
+ kind: 'parameterName'
69
+ },
70
+ {
71
+ text: ': ',
72
+ kind: 'punctuation'
73
+ },
74
+ {
75
+ text: 'RequestEvent',
76
+ kind: 'interfaceName'
77
+ },
78
+ {
79
+ text: ')',
80
+ kind: 'punctuation'
81
+ },
82
+ {
83
+ text: ': ',
84
+ kind: 'punctuation'
85
+ },
86
+ {
87
+ text: 'Promise',
88
+ kind: 'keyword'
89
+ },
90
+ {
91
+ text: '<',
92
+ kind: 'punctuation'
93
+ },
94
+ {
95
+ text: 'Response',
96
+ kind: 'interfaceName'
97
+ },
98
+ {
99
+ text: '>',
100
+ kind: 'punctuation'
101
+ }
102
+ ],
103
+ documentation: [
104
+ {
105
+ text: `Handles ${name} requests. More info: https://kit.svelte.dev/docs/routing#server`,
106
+ kind: 'text'
107
+ }
108
+ ]
109
+ };
110
+ }
9
111
  exports.kitExports = {
10
112
  prerender: {
113
+ allowedIn: ['layout', 'page', 'api', 'server', 'universal'],
11
114
  displayParts: [
12
115
  {
13
116
  text: 'const',
@@ -46,6 +149,7 @@ exports.kitExports = {
46
149
  ]
47
150
  },
48
151
  ssr: {
152
+ allowedIn: ['layout', 'page', 'server', 'universal'],
49
153
  displayParts: [
50
154
  {
51
155
  text: 'const',
@@ -76,6 +180,7 @@ exports.kitExports = {
76
180
  ]
77
181
  },
78
182
  csr: {
183
+ allowedIn: ['layout', 'page', 'server', 'universal'],
79
184
  displayParts: [
80
185
  {
81
186
  text: 'const',
@@ -106,6 +211,7 @@ exports.kitExports = {
106
211
  ]
107
212
  },
108
213
  trailingSlash: {
214
+ allowedIn: ['layout', 'page', 'api', 'server', 'universal'],
109
215
  displayParts: [
110
216
  {
111
217
  text: 'const',
@@ -136,6 +242,7 @@ exports.kitExports = {
136
242
  ]
137
243
  },
138
244
  config: {
245
+ allowedIn: ['layout', 'page', 'api', 'server', 'universal'],
139
246
  displayParts: [
140
247
  {
141
248
  text: 'const',
@@ -168,6 +275,7 @@ exports.kitExports = {
168
275
  ]
169
276
  },
170
277
  actions: {
278
+ allowedIn: ['page', 'server'],
171
279
  displayParts: [
172
280
  {
173
281
  text: 'const',
@@ -199,6 +307,7 @@ exports.kitExports = {
199
307
  ]
200
308
  },
201
309
  load: {
310
+ allowedIn: ['layout', 'page', 'server', 'universal'],
202
311
  displayParts: [
203
312
  {
204
313
  text: 'export',
@@ -267,17 +376,97 @@ exports.kitExports = {
267
376
  kind: 'text'
268
377
  }
269
378
  ]
379
+ },
380
+ GET: createApiExport('GET'),
381
+ POST: createApiExport('POST'),
382
+ PUT: createApiExport('PUT'),
383
+ PATCH: createApiExport('PATCH'),
384
+ DELETE: createApiExport('DELETE'),
385
+ OPTIONS: createApiExport('OPTIONS'),
386
+ // param matching
387
+ match: {
388
+ allowedIn: [],
389
+ displayParts: [],
390
+ documentation: [
391
+ {
392
+ text: `A parameter matcher. ` +
393
+ `More info: https://kit.svelte.dev/docs/advanced-routing#matching`,
394
+ kind: 'text'
395
+ }
396
+ ]
397
+ },
398
+ // hooks
399
+ handle: {
400
+ allowedIn: [],
401
+ displayParts: [],
402
+ documentation: [
403
+ {
404
+ text: `The handle hook runs every time the SvelteKit server receives a request and determines the response. ` +
405
+ `It receives an 'event' object representing the request and a function called 'resolve', which renders the route and generates a Response. ` +
406
+ `This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). ` +
407
+ `More info: https://kit.svelte.dev/docs/hooks#server-hooks-handle`,
408
+ kind: 'text'
409
+ }
410
+ ]
411
+ },
412
+ handleFetch: {
413
+ allowedIn: [],
414
+ displayParts: [],
415
+ documentation: [
416
+ {
417
+ text: `The handleFetch hook allows you to modify (or replace) a 'fetch' request that happens inside a 'load' function that runs on the server (or during pre-rendering). ` +
418
+ `More info: https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch`,
419
+ kind: 'text'
420
+ }
421
+ ]
422
+ },
423
+ handleError: {
424
+ allowedIn: [],
425
+ displayParts: [],
426
+ documentation: [
427
+ {
428
+ text: `The handleError hook runs when an unexpected error is thrown while responding to a request. ` +
429
+ `If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. ` +
430
+ `Make sure that this function _never_ throws an error. ` +
431
+ `More info: https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror`,
432
+ kind: 'text'
433
+ }
434
+ ]
270
435
  }
271
436
  };
437
+ function isKitRouteExportAllowedIn(basename, kitExport) {
438
+ if (!basename.startsWith('+')) {
439
+ return false;
440
+ }
441
+ const allowedIn = kitExport.allowedIn;
442
+ return ((basename.includes('layout')
443
+ ? allowedIn.includes('layout')
444
+ : basename.includes('+server')
445
+ ? allowedIn.includes('api')
446
+ : allowedIn.includes('page')) &&
447
+ (basename.includes('server')
448
+ ? allowedIn.includes('server')
449
+ : allowedIn.includes('universal')));
450
+ }
451
+ exports.isKitRouteExportAllowedIn = isKitRouteExportAllowedIn;
272
452
  function getProxiedLanguageService(info, ts, logger) {
273
453
  const cachedProxiedLanguageService = cache.get(info);
274
- if (cachedProxiedLanguageService) {
275
- return cachedProxiedLanguageService;
454
+ if (cachedProxiedLanguageService !== undefined) {
455
+ return cachedProxiedLanguageService !== null && cachedProxiedLanguageService !== void 0 ? cachedProxiedLanguageService : undefined;
456
+ }
457
+ if (!(0, utils_1.hasNodeModule)(info.project.getCompilerOptions(), '@sveltejs/kit')) {
458
+ // Not a SvelteKit project, do nothing
459
+ cache.set(info, null);
460
+ return;
276
461
  }
277
462
  const originalLanguageServiceHost = info.languageServiceHost;
278
463
  class ProxiedLanguageServiceHost {
279
464
  constructor() {
465
+ var _a;
280
466
  this.files = {};
467
+ this.paramsPath = 'src/params';
468
+ this.serverHooksPath = 'src/hooks.server';
469
+ this.clientHooksPath = 'src/hooks.client';
281
470
  this.resolveModuleNames = originalLanguageServiceHost.resolveModuleNames
282
471
  ? (...args) => {
283
472
  return originalLanguageServiceHost.resolveModuleNames(
@@ -292,6 +481,37 @@ function getProxiedLanguageService(info, ts, logger) {
292
481
  ...args);
293
482
  }
294
483
  : undefined;
484
+ // needed for path auto completions
485
+ this.readDirectory = originalLanguageServiceHost.readDirectory
486
+ ? (...args) => {
487
+ return originalLanguageServiceHost.readDirectory(
488
+ // @ts-ignore
489
+ ...args);
490
+ }
491
+ : undefined;
492
+ const configPath = info.project.getCurrentDirectory() + '/svelte.config.js';
493
+ (_a = configPath, Promise.resolve().then(() => __importStar(require(_a)))).then((module) => {
494
+ const config = module.default;
495
+ if (config.kit && config.kit.files) {
496
+ if (config.kit.files.params) {
497
+ this.paramsPath = config.kit.files.params;
498
+ }
499
+ if (config.kit.files.hooks) {
500
+ this.serverHooksPath || (this.serverHooksPath = config.kit.files.hooks.server);
501
+ this.clientHooksPath || (this.clientHooksPath = config.kit.files.hooks.client);
502
+ }
503
+ // We could be more sophisticated with only removing the files that are actually
504
+ // wrong but this is good enough given how rare it is that this setting is used
505
+ Object.keys(this.files)
506
+ .filter((name) => {
507
+ return !name.includes('src/hooks') && !name.includes('src/params');
508
+ })
509
+ .forEach((name) => {
510
+ delete this.files[name];
511
+ });
512
+ }
513
+ })
514
+ .catch(() => { });
295
515
  }
296
516
  log() { }
297
517
  trace() { }
@@ -299,9 +519,6 @@ function getProxiedLanguageService(info, ts, logger) {
299
519
  getCompilationSettings() {
300
520
  return originalLanguageServiceHost.getCompilationSettings();
301
521
  }
302
- getScriptIsOpen() {
303
- return true;
304
- }
305
522
  getCurrentDirectory() {
306
523
  return originalLanguageServiceHost.getCurrentDirectory();
307
524
  }
@@ -337,101 +554,15 @@ function getProxiedLanguageService(info, ts, logger) {
337
554
  return this.files[fileName];
338
555
  }
339
556
  upsertKitFile(fileName) {
340
- var _a;
341
- const basename = path_1.default.basename(fileName);
342
- if (!kitPageFiles.has(basename))
557
+ const result = svelte2tsx_1.internalHelpers.upsertKitFile(fileName, {
558
+ clientHooksPath: this.clientHooksPath,
559
+ paramsPath: this.paramsPath,
560
+ serverHooksPath: this.serverHooksPath
561
+ }, () => { var _a; return (_a = info.languageService.getProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFile(fileName); });
562
+ if (!result) {
343
563
  return;
344
- const source = (_a = info.languageService.getProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFile(fileName);
345
- if (!source)
346
- return;
347
- const addedCode = [];
348
- const insert = (pos, inserted) => {
349
- var _a, _b, _c, _d;
350
- const insertionIdx = addedCode.findIndex((c) => c.generatedPos > pos);
351
- if (insertionIdx >= 0) {
352
- for (let i = insertionIdx; i < addedCode.length; i++) {
353
- addedCode[i].generatedPos += inserted.length;
354
- addedCode[i].total += inserted.length;
355
- }
356
- const prevTotal = (_b = (_a = addedCode[insertionIdx - 1]) === null || _a === void 0 ? void 0 : _a.total) !== null && _b !== void 0 ? _b : 0;
357
- addedCode.splice(insertionIdx, 0, {
358
- generatedPos: pos + prevTotal,
359
- originalPos: pos,
360
- length: inserted.length,
361
- inserted,
362
- total: prevTotal + inserted.length
363
- });
364
- }
365
- else {
366
- const prevTotal = (_d = (_c = addedCode[addedCode.length - 1]) === null || _c === void 0 ? void 0 : _c.total) !== null && _d !== void 0 ? _d : 0;
367
- addedCode.push({
368
- generatedPos: pos + prevTotal,
369
- originalPos: pos,
370
- length: inserted.length,
371
- inserted,
372
- total: prevTotal + inserted.length
373
- });
374
- }
375
- };
376
- const isTsFile = basename.endsWith('.ts');
377
- const exports = findExports(ts, source, isTsFile);
378
- // add type to load function if not explicitly typed
379
- const load = exports.get('load');
380
- if ((load === null || load === void 0 ? void 0 : load.type) === 'function' &&
381
- load.node.parameters.length === 1 &&
382
- !load.hasTypeDefinition) {
383
- const pos = load.node.parameters[0].getEnd();
384
- const inserted = `: import('./$types').${basename.includes('layout') ? 'Layout' : 'Page'}${basename.includes('server') ? 'Server' : ''}LoadEvent`;
385
- insert(pos, inserted);
386
- }
387
- // add type to actions variable if not explicitly typed
388
- const actions = exports.get('actions');
389
- if ((actions === null || actions === void 0 ? void 0 : actions.type) === 'var' && !actions.hasTypeDefinition && actions.node.initializer) {
390
- const pos = actions.node.initializer.getEnd();
391
- const inserted = ` satisfies import('./$types').Actions`;
392
- insert(pos, inserted);
393
- }
394
- // add type to prerender variable if not explicitly typed
395
- const prerender = exports.get('prerender');
396
- if ((prerender === null || prerender === void 0 ? void 0 : prerender.type) === 'var' &&
397
- !prerender.hasTypeDefinition &&
398
- prerender.node.initializer) {
399
- const pos = prerender.node.name.getEnd();
400
- const inserted = ` : import('@sveltejs/kit').PrerenderOption`;
401
- insert(pos, inserted);
402
- }
403
- // add type to trailingSlash variable if not explicitly typed
404
- const trailingSlash = exports.get('trailingSlash');
405
- if ((trailingSlash === null || trailingSlash === void 0 ? void 0 : trailingSlash.type) === 'var' &&
406
- !trailingSlash.hasTypeDefinition &&
407
- trailingSlash.node.initializer) {
408
- const pos = trailingSlash.node.name.getEnd();
409
- const inserted = ` : 'never' | 'always' | 'ignore'`; // TODO this should be exported from kit
410
- insert(pos, inserted);
411
- }
412
- // add type to ssr variable if not explicitly typed
413
- const ssr = exports.get('ssr');
414
- if ((ssr === null || ssr === void 0 ? void 0 : ssr.type) === 'var' && !ssr.hasTypeDefinition && ssr.node.initializer) {
415
- const pos = ssr.node.name.getEnd();
416
- const inserted = ` : boolean`;
417
- insert(pos, inserted);
418
- }
419
- // add type to csr variable if not explicitly typed
420
- const csr = exports.get('csr');
421
- if ((csr === null || csr === void 0 ? void 0 : csr.type) === 'var' && !csr.hasTypeDefinition && csr.node.initializer) {
422
- const pos = csr.node.name.getEnd();
423
- const inserted = ` : boolean`;
424
- insert(pos, inserted);
425
- }
426
- // construct generated text from internal text and addedCode array
427
- const originalText = source.getFullText();
428
- let pos = 0;
429
- let text = '';
430
- for (const added of addedCode) {
431
- text += originalText.slice(pos, added.originalPos) + added.inserted;
432
- pos = added.originalPos;
433
564
  }
434
- text += originalText.slice(pos);
565
+ const { text, addedCode } = result;
435
566
  const snap = ts.ScriptSnapshot.fromString(text);
436
567
  snap.getChangeRange = (_) => undefined;
437
568
  this.files[fileName] = {
@@ -452,116 +583,52 @@ function getProxiedLanguageService(info, ts, logger) {
452
583
  originalLanguageServiceHost.fileExists(fileName));
453
584
  }
454
585
  }
586
+ // Ideally we'd create a full Proxy of the language service, but that seems to have cache issues
587
+ // with diagnostics, which makes positions go out of sync.
455
588
  const languageServiceHost = new ProxiedLanguageServiceHost();
456
- const languageService = ts.createLanguageService(languageServiceHost, ts.createDocumentRegistry());
589
+ const languageService = ts.createLanguageService(languageServiceHost, createProxyRegistry(ts, originalLanguageServiceHost, languageServiceHost));
457
590
  cache.set(info, { languageService, languageServiceHost });
458
591
  return {
459
592
  languageService,
460
593
  languageServiceHost
461
594
  };
462
595
  }
463
- exports.getProxiedLanguageService = getProxiedLanguageService;
464
- const kitPageFiles = new Set([
465
- '+page.ts',
466
- '+page.js',
467
- '+layout.ts',
468
- '+layout.js',
469
- '+page.server.ts',
470
- '+page.server.js',
471
- '+layout.server.ts',
472
- '+layout.server.js'
473
- ]);
596
+ function createProxyRegistry(ts, originalLanguageServiceHost, options) {
597
+ // Don't destructure options param, as the value may be mutated through a svelte.config.js later
598
+ const registry = ts.createDocumentRegistry();
599
+ const originalRegistry = originalLanguageServiceHost.documentRegistry;
600
+ const proxyRegistry = {
601
+ ...originalRegistry,
602
+ acquireDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions) {
603
+ if (svelte2tsx_1.internalHelpers.isKitFile(fileName, options)) {
604
+ return registry.acquireDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions);
605
+ }
606
+ return originalRegistry.acquireDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions);
607
+ },
608
+ updateDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions) {
609
+ if (svelte2tsx_1.internalHelpers.isKitFile(fileName, options)) {
610
+ return registry.updateDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions);
611
+ }
612
+ return originalRegistry.updateDocumentWithKey(fileName, tsPath, compilationSettingsOrHost, key, scriptSnapshot, version, scriptKind, sourceFileOptions);
613
+ }
614
+ };
615
+ return proxyRegistry;
616
+ }
474
617
  function getVirtualLS(fileName, info, ts, logger) {
475
618
  var _a;
476
619
  const proxy = getProxiedLanguageService(info, ts, logger);
620
+ if (!proxy) {
621
+ return;
622
+ }
477
623
  const result = (_a = proxy.languageServiceHost.getKitScriptSnapshotIfUpToDate(fileName)) !== null && _a !== void 0 ? _a : proxy.languageServiceHost.upsertKitFile(fileName);
478
624
  if (result) {
479
625
  return {
480
626
  languageService: proxy.languageService,
481
627
  addedCode: result.addedCode,
482
- toVirtualPos: (pos) => toVirtualPos(pos, result.addedCode),
483
- toOriginalPos: (pos) => toOriginalPos(pos, result.addedCode)
628
+ toVirtualPos: (pos) => svelte2tsx_1.internalHelpers.toVirtualPos(pos, result.addedCode),
629
+ toOriginalPos: (pos) => svelte2tsx_1.internalHelpers.toOriginalPos(pos, result.addedCode)
484
630
  };
485
631
  }
486
632
  }
487
633
  exports.getVirtualLS = getVirtualLS;
488
- function toVirtualPos(pos, addedCode) {
489
- let total = 0;
490
- for (const added of addedCode) {
491
- if (pos < added.originalPos)
492
- break;
493
- total += added.length;
494
- }
495
- return pos + total;
496
- }
497
- exports.toVirtualPos = toVirtualPos;
498
- function toOriginalPos(pos, addedCode) {
499
- let total = 0;
500
- let idx = 0;
501
- for (; idx < addedCode.length; idx++) {
502
- const added = addedCode[idx];
503
- if (pos < added.generatedPos)
504
- break;
505
- total += added.length;
506
- }
507
- if (idx > 0) {
508
- const prev = addedCode[idx - 1];
509
- // If pos is in the middle of an added range, return the start of the addition
510
- if (pos > prev.generatedPos && pos < prev.generatedPos + prev.length) {
511
- return { pos: prev.originalPos, inGenerated: true };
512
- }
513
- }
514
- return { pos: pos - total, inGenerated: false };
515
- }
516
- exports.toOriginalPos = toOriginalPos;
517
- /**
518
- * Finds the top level const/let/function exports of a source file.
519
- */
520
- function findExports(ts, source, isTsFile) {
521
- var _a, _b, _c, _d, _e;
522
- const exports = new Map();
523
- // TODO handle indirect exports?
524
- for (const statement of source.statements) {
525
- if (ts.isFunctionDeclaration(statement) &&
526
- statement.name &&
527
- ((_b = (_a = ts.getModifiers(statement)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.kind) === ts.SyntaxKind.ExportKeyword) {
528
- // export function x ...
529
- exports.set(statement.name.text, {
530
- type: 'function',
531
- node: statement,
532
- hasTypeDefinition: !!((_c = statement.parameters[0]) === null || _c === void 0 ? void 0 : _c.type) ||
533
- (!isTsFile &&
534
- (!!ts.getJSDocType(statement) ||
535
- (statement.parameters[0] &&
536
- !!ts.getJSDocParameterTags(statement.parameters[0]).length)))
537
- });
538
- }
539
- if (ts.isVariableStatement(statement) &&
540
- statement.declarationList.declarations.length === 1 &&
541
- ((_e = (_d = ts.getModifiers(statement)) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.kind) === ts.SyntaxKind.ExportKeyword) {
542
- // export const x = ...
543
- const declaration = statement.declarationList.declarations[0];
544
- const hasTypeDefinition = !!declaration.type ||
545
- (!isTsFile && !!ts.getJSDocType(declaration)) ||
546
- (!!declaration.initializer && ts.isSatisfiesExpression(declaration.initializer));
547
- if (declaration.initializer &&
548
- (ts.isFunctionExpression(declaration.initializer) ||
549
- ts.isArrowFunction(declaration.initializer))) {
550
- exports.set(declaration.name.getText(), {
551
- type: 'function',
552
- node: declaration.initializer,
553
- hasTypeDefinition
554
- });
555
- }
556
- else {
557
- exports.set(declaration.name.getText(), {
558
- type: 'var',
559
- node: declaration,
560
- hasTypeDefinition
561
- });
562
- }
563
- }
564
- }
565
- return exports;
566
- }
567
634
  //# sourceMappingURL=sveltekit.js.map
@@ -43,4 +43,6 @@ export declare function isTopLevelExport(ts: _ts, node: ts.Node, source: ts.Sour
43
43
  export declare function isGeneratedSvelteComponentName(className: string): boolean;
44
44
  export declare function offsetOfGeneratedComponentExport(snapshot: SvelteSnapshot): number;
45
45
  export declare function gatherDescendants<T extends ts.Node>(node: ts.Node, predicate: NodePredicate | NodeTypePredicate<T>, dest?: T[]): T[];
46
+ export declare function findIdentifier(ts: _ts, node: ts.Node): ts.Identifier | undefined;
47
+ export declare function hasNodeModule(compilerOptions: ts.CompilerOptions, module: string): string | boolean;
46
48
  export {};
package/dist/src/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.gatherDescendants = exports.offsetOfGeneratedComponentExport = exports.isGeneratedSvelteComponentName = exports.isTopLevelExport = exports.findNodeAtPosition = exports.findNodeAtSpan = exports.get$storeOffsetOf$storeDeclaration = exports.isStoreVariableIn$storeDeclaration = exports.getConfigPathForProject = exports.replaceDeep = exports.isNoTextSpanInGeneratedCode = exports.isInGeneratedCode = exports.isNotNullOrUndefined = exports.ensureRealSvelteFilePath = exports.toRealSvelteFilePath = exports.isVirtualSvelteFilePath = exports.isSvelteFilePath = void 0;
3
+ exports.hasNodeModule = exports.findIdentifier = exports.gatherDescendants = exports.offsetOfGeneratedComponentExport = exports.isGeneratedSvelteComponentName = exports.isTopLevelExport = exports.findNodeAtPosition = exports.findNodeAtSpan = exports.get$storeOffsetOf$storeDeclaration = exports.isStoreVariableIn$storeDeclaration = 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
  }
@@ -170,4 +170,35 @@ function gatherDescendants(node, predicate, dest = []) {
170
170
  return dest;
171
171
  }
172
172
  exports.gatherDescendants = gatherDescendants;
173
+ function findIdentifier(ts, node) {
174
+ if (ts.isIdentifier(node)) {
175
+ return node;
176
+ }
177
+ if (ts.isFunctionDeclaration(node)) {
178
+ return node.name;
179
+ }
180
+ while (node) {
181
+ if (ts.isIdentifier(node)) {
182
+ return node;
183
+ }
184
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
185
+ return node.name;
186
+ }
187
+ node = node.parent;
188
+ }
189
+ }
190
+ exports.findIdentifier = findIdentifier;
191
+ function hasNodeModule(compilerOptions, module) {
192
+ try {
193
+ const hasModule = typeof compilerOptions.configFilePath !== 'string' ||
194
+ require.resolve(module, { paths: [compilerOptions.configFilePath] });
195
+ return hasModule;
196
+ }
197
+ catch (e) {
198
+ // If require.resolve fails, we end up here, which can be either because the package is not found,
199
+ // or (in case of things like SvelteKit) the package is found but the package.json is not exported.
200
+ return (e === null || e === void 0 ? void 0 : e.code) === 'ERR_PACKAGE_PATH_NOT_EXPORTED';
201
+ }
202
+ }
203
+ exports.hasNodeModule = hasNodeModule;
173
204
  //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typescript-svelte-plugin",
3
- "version": "0.3.18",
3
+ "version": "0.3.19",
4
4
  "description": "A TypeScript Plugin providing Svelte intellisense",
5
5
  "main": "dist/src/index.js",
6
6
  "scripts": {
@@ -24,6 +24,6 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@jridgewell/sourcemap-codec": "^1.4.14",
27
- "svelte2tsx": "~0.6.0"
27
+ "svelte2tsx": "~0.6.4"
28
28
  }
29
29
  }