@ktjs/ts-plugin 0.1.5 → 0.1.7

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/README.md CHANGED
@@ -8,10 +8,11 @@ TypeScript language service plugin for KT.js `k-for` scope variables in TSX.
8
8
  - Suppresses TS2304 (`Cannot find name ...`) for aliases declared by `k-for`.
9
9
  - Infers alias types from iterable/indexed sources (for example `k-for="item in users"` makes `item` resolve to `users[number]`).
10
10
  - Provides hover type info and member completions for inferred aliases.
11
+ - Supports hover type info inside `k-for` expression strings (`item in users`) for alias/source identifiers.
12
+ - Adds `k-for` inline semantic highlighting in string expressions (for example alias/keyword/source in `k-for="item in list"`).
11
13
  - Supports Vue-like syntax:
12
14
  - `k-for="item in list"`
13
15
  - `k-for="(item, i) in list"`
14
- - `k-for="(value, key, i) in mapLike"`
15
16
 
16
17
  ## Install
17
18
 
package/dist/index.js CHANGED
@@ -4,6 +4,8 @@ const completion_1 = require("./completion");
4
4
  const constants_1 = require("./constants");
5
5
  const config_1 = require("./config");
6
6
  const identifiers_1 = require("./identifiers");
7
+ const kfor_highlighting_1 = require("./kfor-highlighting");
8
+ const quickinfo_1 = require("./quickinfo");
7
9
  const scope_analysis_1 = require("./scope-analysis");
8
10
  const type_resolution_1 = require("./type-resolution");
9
11
  function init(modules) {
@@ -38,6 +40,28 @@ function init(modules) {
38
40
  return !(0, scope_analysis_1.isSuppressed)(diagnostic.start, name, analysis.scopes);
39
41
  });
40
42
  };
43
+ proxy.getEncodedSemanticClassifications = (fileName, span, format) => {
44
+ const classifications = languageService.getEncodedSemanticClassifications(fileName, span, format);
45
+ if (!(0, config_1.isJsxLikeFile)(fileName)) {
46
+ return classifications;
47
+ }
48
+ const sourceFile = languageService.getProgram()?.getSourceFile(fileName);
49
+ if (!sourceFile) {
50
+ return classifications;
51
+ }
52
+ return (0, kfor_highlighting_1.addKForSemanticClassifications)(classifications, sourceFile, span, format, ts, config);
53
+ };
54
+ proxy.getEncodedSyntacticClassifications = (fileName, span) => {
55
+ const classifications = languageService.getEncodedSyntacticClassifications(fileName, span);
56
+ if (!(0, config_1.isJsxLikeFile)(fileName)) {
57
+ return classifications;
58
+ }
59
+ const sourceFile = languageService.getProgram()?.getSourceFile(fileName);
60
+ if (!sourceFile) {
61
+ return classifications;
62
+ }
63
+ return (0, kfor_highlighting_1.addKForSyntacticClassifications)(classifications, sourceFile, span, ts, config);
64
+ };
41
65
  proxy.getQuickInfoAtPosition = (fileName, position) => {
42
66
  const quickInfo = languageService.getQuickInfoAtPosition(fileName, position);
43
67
  if (!(0, config_1.isJsxLikeFile)(fileName)) {
@@ -47,25 +71,8 @@ function init(modules) {
47
71
  if (!analysis) {
48
72
  return quickInfo;
49
73
  }
50
- const identifier = (0, ast_1.findIdentifierAtPosition)(analysis.sourceFile, position, ts);
51
- if (!identifier) {
52
- return quickInfo;
53
- }
54
- const bindings = (0, scope_analysis_1.collectBindingsAtPosition)(position, analysis.scopes);
55
- const binding = bindings.get(identifier.text);
56
- if (!binding) {
57
- return quickInfo;
58
- }
59
- const typeText = (0, type_resolution_1.formatTypeList)(binding.types, analysis.checker, identifier, ts);
60
- return {
61
- kind: ts.ScriptElementKind.localVariableElement,
62
- kindModifiers: '',
63
- textSpan: {
64
- start: identifier.getStart(analysis.sourceFile),
65
- length: identifier.getWidth(analysis.sourceFile),
66
- },
67
- displayParts: [{ text: `(k-for) ${binding.name}: ${typeText}`, kind: 'text' }],
68
- };
74
+ const pluginQuickInfo = (0, quickinfo_1.getKForQuickInfoAtPosition)(analysis, position, ts, config);
75
+ return pluginQuickInfo || quickInfo;
69
76
  };
70
77
  proxy.getCompletionsAtPosition = (fileName, position, options, formattingSettings) => {
71
78
  const completions = languageService.getCompletionsAtPosition(fileName, position, options, formattingSettings);
@@ -0,0 +1,4 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ import type { ResolvedConfig } from './types';
3
+ export declare function addKForSemanticClassifications(base: tsModule.Classifications, sourceFile: tsModule.SourceFile, span: tsModule.TextSpan, format: tsModule.SemanticClassificationFormat | undefined, ts: typeof tsModule, config: ResolvedConfig): tsModule.Classifications;
4
+ export declare function addKForSyntacticClassifications(base: tsModule.Classifications, sourceFile: tsModule.SourceFile, span: tsModule.TextSpan, ts: typeof tsModule, config: ResolvedConfig): tsModule.Classifications;
@@ -0,0 +1,407 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addKForSemanticClassifications = addKForSemanticClassifications;
4
+ exports.addKForSyntacticClassifications = addKForSyntacticClassifications;
5
+ const jsx_attributes_1 = require("./jsx-attributes");
6
+ const kfor_parser_1 = require("./kfor-parser");
7
+ const identifiers_1 = require("./identifiers");
8
+ const TOKEN_TYPE_VARIABLE = 7;
9
+ const TOKEN_TYPE_TYPE = 5;
10
+ const TOKEN_MODIFIER_READONLY = 1 << 3;
11
+ const TOKEN_MODIFIER_LOCAL = 1 << 5;
12
+ const TOKEN_ENCODING_TYPE_OFFSET = 8;
13
+ const IDENTIFIER_PATTERN = /[A-Za-z_$][A-Za-z0-9_$]*/g;
14
+ const KEYWORD_DELIMITER_PATTERN = /\s+(in|of)\s+/;
15
+ function addKForSemanticClassifications(base, sourceFile, span, format, ts, config) {
16
+ const tokens = collectHighlightTokens(sourceFile, ts, config, span);
17
+ if (tokens.length === 0) {
18
+ return base;
19
+ }
20
+ const semanticSpans = buildSemanticSpans(tokens, format, ts);
21
+ if (semanticSpans.length === 0) {
22
+ return base;
23
+ }
24
+ return mergeClassifications(base, semanticSpans, false);
25
+ }
26
+ function addKForSyntacticClassifications(base, sourceFile, span, ts, config) {
27
+ const tokens = collectHighlightTokens(sourceFile, ts, config, span);
28
+ if (tokens.length === 0) {
29
+ return base;
30
+ }
31
+ const keywordSpans = buildSyntacticKeywordSpans(tokens, ts);
32
+ if (keywordSpans.length === 0) {
33
+ return base;
34
+ }
35
+ return mergeClassifications(base, keywordSpans, true);
36
+ }
37
+ function collectHighlightTokens(sourceFile, ts, config, span) {
38
+ const tokens = [];
39
+ const spanStart = span.start;
40
+ const spanEnd = span.start + span.length;
41
+ const visit = (node) => {
42
+ let opening;
43
+ if (ts.isJsxElement(node)) {
44
+ opening = node.openingElement;
45
+ }
46
+ else if (ts.isJsxSelfClosingElement(node)) {
47
+ opening = node;
48
+ }
49
+ if (opening) {
50
+ const attr = (0, jsx_attributes_1.getJsxAttribute)(opening, config.forAttr, ts);
51
+ if (attr) {
52
+ const parsed = parseKForAttributeTokens(attr, sourceFile, ts, config.allowOfKeyword);
53
+ for (let i = 0; i < parsed.length; i++) {
54
+ const token = parsed[i];
55
+ const tokenStart = token.start;
56
+ const tokenEnd = token.start + token.length;
57
+ if (tokenEnd <= spanStart || tokenStart >= spanEnd) {
58
+ continue;
59
+ }
60
+ const clippedStart = Math.max(tokenStart, spanStart);
61
+ const clippedEnd = Math.min(tokenEnd, spanEnd);
62
+ if (clippedEnd > clippedStart) {
63
+ tokens.push({
64
+ start: clippedStart,
65
+ length: clippedEnd - clippedStart,
66
+ kind: token.kind,
67
+ });
68
+ }
69
+ }
70
+ }
71
+ }
72
+ ts.forEachChild(node, visit);
73
+ };
74
+ visit(sourceFile);
75
+ return uniqueTokens(tokens);
76
+ }
77
+ function parseKForAttributeTokens(attr, sourceFile, ts, allowOfKeyword) {
78
+ const content = getAttributeRawContent(attr, sourceFile, ts);
79
+ if (!content) {
80
+ return [];
81
+ }
82
+ const raw = content.text;
83
+ const rawOffset = content.start;
84
+ const value = raw.trim();
85
+ if (!value) {
86
+ return [];
87
+ }
88
+ const parsed = (0, kfor_parser_1.parseKForExpression)(value, allowOfKeyword);
89
+ if (!parsed) {
90
+ return [];
91
+ }
92
+ const trimStart = raw.length - raw.trimStart().length;
93
+ const delimiterMatch = KEYWORD_DELIMITER_PATTERN.exec(value);
94
+ if (!delimiterMatch) {
95
+ return [];
96
+ }
97
+ const keyword = delimiterMatch[1];
98
+ const keywordOffsetInDelimiter = delimiterMatch[0].indexOf(keyword);
99
+ const leftSegment = value.slice(0, delimiterMatch.index);
100
+ const rightSegment = value.slice(delimiterMatch.index + delimiterMatch[0].length);
101
+ const leftLeading = leftSegment.length - leftSegment.trimStart().length;
102
+ const leftTrimmed = leftSegment.trim();
103
+ let aliasText = leftTrimmed;
104
+ let aliasTextStartInRaw = trimStart + leftLeading;
105
+ if (leftTrimmed.startsWith('(') && leftTrimmed.endsWith(')')) {
106
+ aliasText = leftTrimmed.slice(1, -1);
107
+ aliasTextStartInRaw += 1;
108
+ }
109
+ const rightLeading = rightSegment.length - rightSegment.trimStart().length;
110
+ const sourceText = rightSegment.trim();
111
+ const sourceTextStartInRaw = trimStart + delimiterMatch.index + delimiterMatch[0].length + rightLeading;
112
+ const keywordStartInRaw = trimStart + delimiterMatch.index + keywordOffsetInDelimiter;
113
+ const tokens = [];
114
+ const aliasTokens = collectAliasTokens(aliasText, aliasTextStartInRaw, parsed.aliases);
115
+ for (let i = 0; i < aliasTokens.length; i++) {
116
+ tokens.push({
117
+ start: rawOffset + aliasTokens[i].start,
118
+ length: aliasTokens[i].length,
119
+ kind: 'alias',
120
+ });
121
+ }
122
+ tokens.push({
123
+ start: rawOffset + keywordStartInRaw,
124
+ length: keyword.length,
125
+ kind: 'keyword',
126
+ });
127
+ const sourceTokens = collectSourceTokens(sourceText, sourceTextStartInRaw, ts);
128
+ for (let i = 0; i < sourceTokens.length; i++) {
129
+ tokens.push({
130
+ start: rawOffset + sourceTokens[i].start,
131
+ length: sourceTokens[i].length,
132
+ kind: 'source',
133
+ });
134
+ }
135
+ return tokens;
136
+ }
137
+ function collectAliasTokens(aliasText, baseStart, aliases) {
138
+ const result = [];
139
+ const allowed = new Set(aliases);
140
+ let match;
141
+ IDENTIFIER_PATTERN.lastIndex = 0;
142
+ while ((match = IDENTIFIER_PATTERN.exec(aliasText))) {
143
+ const name = match[0];
144
+ if (!allowed.has(name) || !(0, identifiers_1.isValidIdentifier)(name)) {
145
+ continue;
146
+ }
147
+ result.push({
148
+ start: baseStart + match.index,
149
+ length: name.length,
150
+ kind: 'alias',
151
+ });
152
+ }
153
+ return result;
154
+ }
155
+ function collectSourceTokens(sourceText, baseStart, ts) {
156
+ const tokens = collectSourceTokensWithAst(sourceText, baseStart, ts);
157
+ if (tokens.length > 0) {
158
+ return tokens;
159
+ }
160
+ const fallback = [];
161
+ let match;
162
+ IDENTIFIER_PATTERN.lastIndex = 0;
163
+ while ((match = IDENTIFIER_PATTERN.exec(sourceText))) {
164
+ const name = match[0];
165
+ if (!(0, identifiers_1.isValidIdentifier)(name)) {
166
+ continue;
167
+ }
168
+ fallback.push({
169
+ start: baseStart + match.index,
170
+ length: name.length,
171
+ kind: 'source',
172
+ });
173
+ }
174
+ return fallback;
175
+ }
176
+ function collectSourceTokensWithAst(sourceText, baseStart, ts) {
177
+ const snippet = `(${sourceText});`;
178
+ const tempSourceFile = ts.createSourceFile('__k_for_highlight.ts', snippet, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
179
+ if (tempSourceFile.statements.length === 0) {
180
+ return [];
181
+ }
182
+ const statement = tempSourceFile.statements[0];
183
+ if (!ts.isExpressionStatement(statement)) {
184
+ return [];
185
+ }
186
+ const result = [];
187
+ const visit = (node) => {
188
+ if (ts.isIdentifier(node) && (0, identifiers_1.isValidIdentifier)(node.text)) {
189
+ const start = node.getStart(tempSourceFile) - 1;
190
+ const end = start + node.getWidth(tempSourceFile);
191
+ if (start >= 0 && end <= sourceText.length) {
192
+ result.push({
193
+ start: baseStart + start,
194
+ length: end - start,
195
+ kind: 'source',
196
+ });
197
+ }
198
+ }
199
+ ts.forEachChild(node, visit);
200
+ };
201
+ visit(statement.expression);
202
+ return result;
203
+ }
204
+ function getAttributeRawContent(attr, sourceFile, ts) {
205
+ const initializer = attr.initializer;
206
+ if (!initializer) {
207
+ return undefined;
208
+ }
209
+ if (ts.isStringLiteral(initializer)) {
210
+ const quotedText = initializer.getText(sourceFile);
211
+ if (quotedText.length < 2) {
212
+ return undefined;
213
+ }
214
+ return {
215
+ start: initializer.getStart(sourceFile) + 1,
216
+ text: quotedText.slice(1, -1),
217
+ };
218
+ }
219
+ const expression = (0, jsx_attributes_1.getAttributeExpression)(attr, ts);
220
+ if (!expression || !ts.isStringLiteralLike(expression)) {
221
+ return undefined;
222
+ }
223
+ const quotedText = expression.getText(sourceFile);
224
+ if (quotedText.length < 2) {
225
+ return undefined;
226
+ }
227
+ return {
228
+ start: expression.getStart(sourceFile) + 1,
229
+ text: quotedText.slice(1, -1),
230
+ };
231
+ }
232
+ function buildSemanticSpans(tokens, format, ts) {
233
+ const spans = [];
234
+ if (format === ts.SemanticClassificationFormat.TwentyTwenty) {
235
+ for (let i = 0; i < tokens.length; i++) {
236
+ const token = tokens[i];
237
+ spans.push({
238
+ start: token.start,
239
+ length: token.length,
240
+ classification: token.kind === 'alias'
241
+ ? encodeSemantic2020(TOKEN_TYPE_VARIABLE, TOKEN_MODIFIER_READONLY | TOKEN_MODIFIER_LOCAL)
242
+ : token.kind === 'keyword'
243
+ ? encodeSemantic2020(TOKEN_TYPE_TYPE, 0)
244
+ : encodeSemantic2020(TOKEN_TYPE_VARIABLE, 0),
245
+ });
246
+ }
247
+ return spans;
248
+ }
249
+ for (let i = 0; i < tokens.length; i++) {
250
+ const token = tokens[i];
251
+ spans.push({
252
+ start: token.start,
253
+ length: token.length,
254
+ classification: token.kind === 'keyword' ? ts.ClassificationType.keyword : ts.ClassificationType.identifier,
255
+ });
256
+ }
257
+ return spans;
258
+ }
259
+ function buildSyntacticKeywordSpans(tokens, ts) {
260
+ const spans = [];
261
+ for (let i = 0; i < tokens.length; i++) {
262
+ const token = tokens[i];
263
+ if (token.kind !== 'keyword') {
264
+ continue;
265
+ }
266
+ spans.push({
267
+ start: token.start,
268
+ length: token.length,
269
+ classification: ts.ClassificationType.keyword,
270
+ });
271
+ }
272
+ return spans;
273
+ }
274
+ function encodeSemantic2020(typeIndex, modifiers) {
275
+ return ((typeIndex + 1) << TOKEN_ENCODING_TYPE_OFFSET) + modifiers;
276
+ }
277
+ function mergeClassifications(base, overlays, replaceOverlaps) {
278
+ if (overlays.length === 0) {
279
+ return base;
280
+ }
281
+ const baseSpans = decodeSpans(base.spans);
282
+ const extraSpans = normalizeSpans(overlays);
283
+ if (extraSpans.length === 0) {
284
+ return base;
285
+ }
286
+ const merged = replaceOverlaps
287
+ ? [...removeOverlayOverlaps(baseSpans, extraSpans), ...extraSpans]
288
+ : [...baseSpans, ...extraSpans];
289
+ const normalized = normalizeSpans(merged);
290
+ return {
291
+ spans: encodeSpans(normalized),
292
+ endOfLineState: base.endOfLineState,
293
+ };
294
+ }
295
+ function removeOverlayOverlaps(baseSpans, overlays) {
296
+ const result = [];
297
+ for (let i = 0; i < baseSpans.length; i++) {
298
+ let segments = [baseSpans[i]];
299
+ for (let j = 0; j < overlays.length; j++) {
300
+ const overlay = overlays[j];
301
+ const nextSegments = [];
302
+ for (let k = 0; k < segments.length; k++) {
303
+ const segment = segments[k];
304
+ const segmentStart = segment.start;
305
+ const segmentEnd = segment.start + segment.length;
306
+ const overlayStart = overlay.start;
307
+ const overlayEnd = overlay.start + overlay.length;
308
+ if (overlayEnd <= segmentStart || overlayStart >= segmentEnd) {
309
+ nextSegments.push(segment);
310
+ continue;
311
+ }
312
+ if (segmentStart < overlayStart) {
313
+ nextSegments.push({
314
+ start: segmentStart,
315
+ length: overlayStart - segmentStart,
316
+ classification: segment.classification,
317
+ });
318
+ }
319
+ if (overlayEnd < segmentEnd) {
320
+ nextSegments.push({
321
+ start: overlayEnd,
322
+ length: segmentEnd - overlayEnd,
323
+ classification: segment.classification,
324
+ });
325
+ }
326
+ }
327
+ segments = nextSegments;
328
+ if (segments.length === 0) {
329
+ break;
330
+ }
331
+ }
332
+ for (let j = 0; j < segments.length; j++) {
333
+ result.push(segments[j]);
334
+ }
335
+ }
336
+ return result;
337
+ }
338
+ function decodeSpans(spans) {
339
+ const decoded = [];
340
+ for (let i = 0; i + 2 < spans.length; i += 3) {
341
+ const start = spans[i];
342
+ const length = spans[i + 1];
343
+ const classification = spans[i + 2];
344
+ if (length <= 0) {
345
+ continue;
346
+ }
347
+ decoded.push({ start, length, classification });
348
+ }
349
+ return decoded;
350
+ }
351
+ function encodeSpans(spans) {
352
+ const encoded = [];
353
+ for (let i = 0; i < spans.length; i++) {
354
+ const span = spans[i];
355
+ encoded.push(span.start, span.length, span.classification);
356
+ }
357
+ return encoded;
358
+ }
359
+ function normalizeSpans(spans) {
360
+ if (spans.length === 0) {
361
+ return [];
362
+ }
363
+ const sorted = spans
364
+ .filter((span) => span.length > 0)
365
+ .slice()
366
+ .sort((left, right) => {
367
+ if (left.start !== right.start) {
368
+ return left.start - right.start;
369
+ }
370
+ if (left.length !== right.length) {
371
+ return left.length - right.length;
372
+ }
373
+ return left.classification - right.classification;
374
+ });
375
+ const normalized = [];
376
+ for (let i = 0; i < sorted.length; i++) {
377
+ const span = sorted[i];
378
+ const previous = normalized[normalized.length - 1];
379
+ if (previous &&
380
+ previous.start === span.start &&
381
+ previous.length === span.length &&
382
+ previous.classification === span.classification) {
383
+ continue;
384
+ }
385
+ normalized.push(span);
386
+ }
387
+ return normalized;
388
+ }
389
+ function uniqueTokens(tokens) {
390
+ if (tokens.length === 0) {
391
+ return [];
392
+ }
393
+ const map = new Map();
394
+ for (let i = 0; i < tokens.length; i++) {
395
+ const token = tokens[i];
396
+ const key = `${token.start}:${token.length}:${token.kind}`;
397
+ if (!map.has(key)) {
398
+ map.set(key, token);
399
+ }
400
+ }
401
+ return Array.from(map.values()).sort((left, right) => {
402
+ if (left.start !== right.start) {
403
+ return left.start - right.start;
404
+ }
405
+ return left.length - right.length;
406
+ });
407
+ }
@@ -0,0 +1,3 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ import type { FileAnalysis, ResolvedConfig } from './types';
3
+ export declare function getKForQuickInfoAtPosition(analysis: FileAnalysis, position: number, ts: typeof tsModule, config: ResolvedConfig): tsModule.QuickInfo | undefined;
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getKForQuickInfoAtPosition = getKForQuickInfoAtPosition;
4
+ const ast_1 = require("./ast");
5
+ const completion_1 = require("./completion");
6
+ const jsx_attributes_1 = require("./jsx-attributes");
7
+ const identifiers_1 = require("./identifiers");
8
+ const kfor_parser_1 = require("./kfor-parser");
9
+ const scope_analysis_1 = require("./scope-analysis");
10
+ const type_resolution_1 = require("./type-resolution");
11
+ const IDENTIFIER_PATTERN = /[A-Za-z_$][A-Za-z0-9_$]*/g;
12
+ const KEYWORD_DELIMITER_PATTERN = /\s+(in|of)\s+/;
13
+ function getKForQuickInfoAtPosition(analysis, position, ts, config) {
14
+ const stringQuickInfo = getKForStringQuickInfo(analysis, position, ts, config);
15
+ if (stringQuickInfo) {
16
+ return stringQuickInfo;
17
+ }
18
+ const identifier = (0, ast_1.findIdentifierAtPosition)(analysis.sourceFile, position, ts);
19
+ if (!identifier) {
20
+ return undefined;
21
+ }
22
+ const bindings = (0, scope_analysis_1.collectBindingsAtPosition)(position, analysis.scopes);
23
+ if (bindings.size === 0) {
24
+ return undefined;
25
+ }
26
+ const aliasBinding = bindings.get(identifier.text);
27
+ if (aliasBinding) {
28
+ return createQuickInfo(identifier, `(k-for) ${aliasBinding.name}`, aliasBinding.types, analysis.checker, ts);
29
+ }
30
+ const memberTypes = resolveMemberQuickInfoTypes(identifier, bindings, analysis.sourceFile, analysis.checker, ts);
31
+ if (memberTypes.length > 0) {
32
+ return createQuickInfo(identifier, `(k-for) ${identifier.text}`, memberTypes, analysis.checker, ts);
33
+ }
34
+ return undefined;
35
+ }
36
+ function getKForStringQuickInfo(analysis, position, ts, config) {
37
+ const context = findKForStringContextAtPosition(analysis.sourceFile, position, ts, config);
38
+ if (!context) {
39
+ return undefined;
40
+ }
41
+ if (context.token.kind === 'alias') {
42
+ const bindings = (0, scope_analysis_1.resolveBindingsForForAttribute)(context.opening, context.attr, analysis.checker, config, ts);
43
+ for (let i = 0; i < bindings.length; i++) {
44
+ const binding = bindings[i];
45
+ if (binding.name === context.token.text) {
46
+ return createQuickInfoForSpan(context.token.start, context.token.length, `(k-for) ${binding.name}`, binding.types, analysis.checker, context.opening, ts);
47
+ }
48
+ }
49
+ return undefined;
50
+ }
51
+ if (context.token.kind === 'source') {
52
+ const expression = getSourceExpressionForToken(context, ts);
53
+ if (!expression) {
54
+ return undefined;
55
+ }
56
+ const types = (0, type_resolution_1.resolveExpressionTypesFromText)(expression, {
57
+ checker: analysis.checker,
58
+ ts,
59
+ scopeNode: context.opening,
60
+ });
61
+ if (types.length === 0) {
62
+ return undefined;
63
+ }
64
+ return createQuickInfoForSpan(context.token.start, context.token.length, `(k-for source) ${context.token.text}`, types, analysis.checker, context.opening, ts);
65
+ }
66
+ return undefined;
67
+ }
68
+ function resolveMemberQuickInfoTypes(identifier, bindings, sourceFile, checker, ts) {
69
+ const parent = identifier.parent;
70
+ let expressionText;
71
+ if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) {
72
+ expressionText = parent.getText(sourceFile);
73
+ }
74
+ else if (ts.isElementAccessExpression(parent) && parent.argumentExpression === identifier) {
75
+ expressionText = parent.getText(sourceFile);
76
+ }
77
+ if (!expressionText) {
78
+ return [];
79
+ }
80
+ return (0, type_resolution_1.resolveExpressionTypesFromText)(expressionText, {
81
+ checker,
82
+ ts,
83
+ scopeNode: identifier,
84
+ localBindings: (0, completion_1.createBindingTypeMap)(bindings),
85
+ });
86
+ }
87
+ function findKForStringContextAtPosition(sourceFile, position, ts, config) {
88
+ let found;
89
+ const visit = (node) => {
90
+ if (found) {
91
+ return;
92
+ }
93
+ let opening;
94
+ if (ts.isJsxElement(node)) {
95
+ opening = node.openingElement;
96
+ }
97
+ else if (ts.isJsxSelfClosingElement(node)) {
98
+ opening = node;
99
+ }
100
+ if (opening) {
101
+ const attr = (0, jsx_attributes_1.getJsxAttribute)(opening, config.forAttr, ts);
102
+ if (attr) {
103
+ const tokenContext = findTokenInForAttribute(attr, opening, sourceFile, position, ts, config.allowOfKeyword);
104
+ if (tokenContext) {
105
+ found = tokenContext;
106
+ return;
107
+ }
108
+ }
109
+ }
110
+ ts.forEachChild(node, visit);
111
+ };
112
+ visit(sourceFile);
113
+ return found;
114
+ }
115
+ function findTokenInForAttribute(attr, opening, sourceFile, position, ts, allowOfKeyword) {
116
+ const content = getAttributeRawContent(attr, sourceFile, ts);
117
+ if (!content) {
118
+ return undefined;
119
+ }
120
+ const raw = content.text;
121
+ const rawStart = content.start;
122
+ if (position < rawStart || position >= rawStart + raw.length) {
123
+ return undefined;
124
+ }
125
+ const value = raw.trim();
126
+ if (!value) {
127
+ return undefined;
128
+ }
129
+ const parsed = (0, kfor_parser_1.parseKForExpression)(value, allowOfKeyword);
130
+ if (!parsed) {
131
+ return undefined;
132
+ }
133
+ const delimiterMatch = KEYWORD_DELIMITER_PATTERN.exec(value);
134
+ if (!delimiterMatch) {
135
+ return undefined;
136
+ }
137
+ const trimStart = raw.length - raw.trimStart().length;
138
+ const keyword = delimiterMatch[1];
139
+ const keywordOffsetInDelimiter = delimiterMatch[0].indexOf(keyword);
140
+ const leftSegment = value.slice(0, delimiterMatch.index);
141
+ const rightSegment = value.slice(delimiterMatch.index + delimiterMatch[0].length);
142
+ const leftLeading = leftSegment.length - leftSegment.trimStart().length;
143
+ const leftTrimmed = leftSegment.trim();
144
+ let aliasText = leftTrimmed;
145
+ let aliasStartInRaw = trimStart + leftLeading;
146
+ if (leftTrimmed.startsWith('(') && leftTrimmed.endsWith(')')) {
147
+ aliasText = leftTrimmed.slice(1, -1);
148
+ aliasStartInRaw += 1;
149
+ }
150
+ const rightLeading = rightSegment.length - rightSegment.trimStart().length;
151
+ const sourceText = rightSegment.trim();
152
+ const sourceStartInRaw = trimStart + delimiterMatch.index + delimiterMatch[0].length + rightLeading;
153
+ const aliasTokens = collectAliasTokens(aliasText, aliasStartInRaw, parsed.aliases, rawStart);
154
+ const sourceTokens = collectSourceTokens(sourceText, sourceStartInRaw, rawStart, ts);
155
+ const keywordToken = {
156
+ kind: 'keyword',
157
+ text: keyword,
158
+ start: rawStart + trimStart + delimiterMatch.index + keywordOffsetInDelimiter,
159
+ length: keyword.length,
160
+ };
161
+ const allTokens = [...aliasTokens, keywordToken, ...sourceTokens];
162
+ for (let i = 0; i < allTokens.length; i++) {
163
+ const token = allTokens[i];
164
+ if (position >= token.start && position < token.start + token.length) {
165
+ return {
166
+ opening,
167
+ attr,
168
+ sourceText,
169
+ sourceStart: rawStart + sourceStartInRaw,
170
+ token,
171
+ };
172
+ }
173
+ }
174
+ return undefined;
175
+ }
176
+ function collectAliasTokens(aliasText, aliasStartInRaw, aliases, rawStart) {
177
+ const result = [];
178
+ const allowed = new Set(aliases);
179
+ let match;
180
+ IDENTIFIER_PATTERN.lastIndex = 0;
181
+ while ((match = IDENTIFIER_PATTERN.exec(aliasText))) {
182
+ const name = match[0];
183
+ if (!allowed.has(name) || !(0, identifiers_1.isValidIdentifier)(name)) {
184
+ continue;
185
+ }
186
+ result.push({
187
+ kind: 'alias',
188
+ text: name,
189
+ start: rawStart + aliasStartInRaw + match.index,
190
+ length: name.length,
191
+ });
192
+ }
193
+ return result;
194
+ }
195
+ function collectSourceTokens(sourceText, sourceStartInRaw, rawStart, ts) {
196
+ const tokens = collectSourceTokensWithAst(sourceText, sourceStartInRaw, rawStart, ts);
197
+ if (tokens.length > 0) {
198
+ return tokens;
199
+ }
200
+ const result = [];
201
+ let match;
202
+ IDENTIFIER_PATTERN.lastIndex = 0;
203
+ while ((match = IDENTIFIER_PATTERN.exec(sourceText))) {
204
+ const name = match[0];
205
+ if (!(0, identifiers_1.isValidIdentifier)(name)) {
206
+ continue;
207
+ }
208
+ result.push({
209
+ kind: 'source',
210
+ text: name,
211
+ start: rawStart + sourceStartInRaw + match.index,
212
+ length: name.length,
213
+ });
214
+ }
215
+ return result;
216
+ }
217
+ function collectSourceTokensWithAst(sourceText, sourceStartInRaw, rawStart, ts) {
218
+ const snippet = `(${sourceText});`;
219
+ const tempSourceFile = ts.createSourceFile('__k_for_quickinfo.ts', snippet, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
220
+ if (tempSourceFile.statements.length === 0) {
221
+ return [];
222
+ }
223
+ const statement = tempSourceFile.statements[0];
224
+ if (!ts.isExpressionStatement(statement)) {
225
+ return [];
226
+ }
227
+ const tokens = [];
228
+ const visit = (node) => {
229
+ if (ts.isIdentifier(node) && (0, identifiers_1.isValidIdentifier)(node.text)) {
230
+ const start = node.getStart(tempSourceFile) - 1;
231
+ const length = node.getWidth(tempSourceFile);
232
+ if (start >= 0 && start + length <= sourceText.length) {
233
+ tokens.push({
234
+ kind: 'source',
235
+ text: node.text,
236
+ start: rawStart + sourceStartInRaw + start,
237
+ length,
238
+ });
239
+ }
240
+ }
241
+ ts.forEachChild(node, visit);
242
+ };
243
+ visit(statement.expression);
244
+ return uniqueSourceTokens(tokens);
245
+ }
246
+ function uniqueSourceTokens(tokens) {
247
+ const map = new Map();
248
+ for (let i = 0; i < tokens.length; i++) {
249
+ const token = tokens[i];
250
+ const key = `${token.start}:${token.length}:${token.text}`;
251
+ if (!map.has(key)) {
252
+ map.set(key, token);
253
+ }
254
+ }
255
+ return Array.from(map.values()).sort((left, right) => left.start - right.start);
256
+ }
257
+ function getSourceExpressionForToken(context, ts) {
258
+ const relativeStart = context.token.start - context.sourceStart;
259
+ if (relativeStart < 0 || relativeStart >= context.sourceText.length) {
260
+ return undefined;
261
+ }
262
+ const snippet = `(${context.sourceText});`;
263
+ const tempSourceFile = ts.createSourceFile('__k_for_quickinfo_resolve.ts', snippet, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
264
+ const lookupPosition = relativeStart + 1;
265
+ const identifier = (0, ast_1.findIdentifierAtPosition)(tempSourceFile, lookupPosition, ts);
266
+ if (!identifier) {
267
+ return context.token.text;
268
+ }
269
+ if (ts.isPropertyAccessExpression(identifier.parent) && identifier.parent.name === identifier) {
270
+ return identifier.parent.getText(tempSourceFile);
271
+ }
272
+ if (ts.isElementAccessExpression(identifier.parent) && identifier.parent.argumentExpression === identifier) {
273
+ return identifier.parent.getText(tempSourceFile);
274
+ }
275
+ return identifier.getText(tempSourceFile);
276
+ }
277
+ function getAttributeRawContent(attr, sourceFile, ts) {
278
+ const initializer = attr.initializer;
279
+ if (!initializer) {
280
+ return undefined;
281
+ }
282
+ if (ts.isStringLiteral(initializer)) {
283
+ const quotedText = initializer.getText(sourceFile);
284
+ if (quotedText.length < 2) {
285
+ return undefined;
286
+ }
287
+ return {
288
+ start: initializer.getStart(sourceFile) + 1,
289
+ text: quotedText.slice(1, -1),
290
+ };
291
+ }
292
+ const expression = (0, jsx_attributes_1.getAttributeExpression)(attr, ts);
293
+ if (!expression || !ts.isStringLiteralLike(expression)) {
294
+ return undefined;
295
+ }
296
+ const quotedText = expression.getText(sourceFile);
297
+ if (quotedText.length < 2) {
298
+ return undefined;
299
+ }
300
+ return {
301
+ start: expression.getStart(sourceFile) + 1,
302
+ text: quotedText.slice(1, -1),
303
+ };
304
+ }
305
+ function createQuickInfo(identifier, label, types, checker, ts) {
306
+ if (types.length === 0) {
307
+ return undefined;
308
+ }
309
+ return createQuickInfoForSpan(identifier.getStart(), identifier.getWidth(), label, types, checker, identifier, ts);
310
+ }
311
+ function createQuickInfoForSpan(start, length, label, types, checker, scopeNode, ts) {
312
+ return {
313
+ kind: ts.ScriptElementKind.localVariableElement,
314
+ kindModifiers: '',
315
+ textSpan: { start, length },
316
+ displayParts: [{ text: `${label}: ${(0, type_resolution_1.formatTypeList)(types, checker, scopeNode, ts)}`, kind: 'text' }],
317
+ };
318
+ }
@@ -1,5 +1,6 @@
1
1
  import type tsModule from 'typescript/lib/tsserverlibrary';
2
- import type { FileAnalysis, KForBinding, KForScope, ResolvedConfig } from './types';
2
+ import type { FileAnalysis, JsxOpeningLikeElement, KForBinding, KForScope, ResolvedConfig } from './types';
3
3
  export declare function getFileAnalysis(fileName: string, languageService: tsModule.LanguageService, ts: typeof tsModule, config: ResolvedConfig): FileAnalysis | undefined;
4
4
  export declare function isSuppressed(position: number, diagnosticName: string, scopes: KForScope[]): boolean;
5
5
  export declare function collectBindingsAtPosition(position: number, scopes: KForScope[]): Map<string, KForBinding>;
6
+ export declare function resolveBindingsForForAttribute(opening: JsxOpeningLikeElement, forAttr: tsModule.JsxAttribute, checker: tsModule.TypeChecker, config: ResolvedConfig, ts: typeof tsModule): KForBinding[];
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getFileAnalysis = getFileAnalysis;
4
4
  exports.isSuppressed = isSuppressed;
5
5
  exports.collectBindingsAtPosition = collectBindingsAtPosition;
6
+ exports.resolveBindingsForForAttribute = resolveBindingsForForAttribute;
6
7
  const jsx_attributes_1 = require("./jsx-attributes");
7
8
  const kfor_parser_1 = require("./kfor-parser");
8
9
  const identifiers_1 = require("./identifiers");
@@ -53,6 +54,9 @@ function collectBindingsAtPosition(position, scopes) {
53
54
  }
54
55
  return bindings;
55
56
  }
57
+ function resolveBindingsForForAttribute(opening, forAttr, checker, config, ts) {
58
+ return resolveScopeBindings(opening, forAttr, checker, config, ts);
59
+ }
56
60
  function collectKForScopes(sourceFile, checker, ts, config) {
57
61
  const scopes = [];
58
62
  const visit = (node) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ktjs/ts-plugin",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "TypeScript language service plugin for kt.js k-for scope names in TSX.",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/index.js",