@ktjs/ts-plugin 0.1.4 → 0.1.5

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,6 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ import type { JsxOpeningLikeElement } from './types';
3
+ export declare function getScopeName(opening: JsxOpeningLikeElement, attrName: string, fallback: string, ts: typeof tsModule): string;
4
+ export declare function getJsxAttribute(opening: tsModule.JsxOpeningElement | tsModule.JsxSelfClosingElement, attrName: string, ts: typeof tsModule): tsModule.JsxAttribute | undefined;
5
+ export declare function getAttributeText(attr: tsModule.JsxAttribute | undefined, ts: typeof tsModule, allowIdentifier?: boolean): string | undefined;
6
+ export declare function getAttributeExpression(attr: tsModule.JsxAttribute | undefined, ts: typeof tsModule): tsModule.Expression | undefined;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getScopeName = getScopeName;
4
+ exports.getJsxAttribute = getJsxAttribute;
5
+ exports.getAttributeText = getAttributeText;
6
+ exports.getAttributeExpression = getAttributeExpression;
7
+ const identifiers_1 = require("./identifiers");
8
+ function getScopeName(opening, attrName, fallback, ts) {
9
+ const attr = getJsxAttribute(opening, attrName, ts);
10
+ const raw = getAttributeText(attr, ts, true);
11
+ if (raw && (0, identifiers_1.isValidIdentifier)(raw)) {
12
+ return raw;
13
+ }
14
+ return fallback;
15
+ }
16
+ function getJsxAttribute(opening, attrName, ts) {
17
+ const attrs = opening.attributes.properties;
18
+ for (let i = 0; i < attrs.length; i++) {
19
+ const attr = attrs[i];
20
+ if (!ts.isJsxAttribute(attr)) {
21
+ continue;
22
+ }
23
+ if (getAttributeName(attr.name) === attrName) {
24
+ return attr;
25
+ }
26
+ }
27
+ return undefined;
28
+ }
29
+ function getAttributeText(attr, ts, allowIdentifier = false) {
30
+ if (!attr || !attr.initializer) {
31
+ return undefined;
32
+ }
33
+ if (ts.isStringLiteral(attr.initializer)) {
34
+ return attr.initializer.text;
35
+ }
36
+ if (!ts.isJsxExpression(attr.initializer) || !attr.initializer.expression) {
37
+ return undefined;
38
+ }
39
+ const expr = attr.initializer.expression;
40
+ if (ts.isStringLiteralLike(expr)) {
41
+ return expr.text;
42
+ }
43
+ if (allowIdentifier && ts.isIdentifier(expr)) {
44
+ return expr.text;
45
+ }
46
+ return undefined;
47
+ }
48
+ function getAttributeExpression(attr, ts) {
49
+ if (!attr?.initializer || !ts.isJsxExpression(attr.initializer) || !attr.initializer.expression) {
50
+ return undefined;
51
+ }
52
+ return attr.initializer.expression;
53
+ }
54
+ function getAttributeName(name) {
55
+ if ('text' in name) {
56
+ return String(name.text);
57
+ }
58
+ return name.getText();
59
+ }
@@ -0,0 +1,2 @@
1
+ import type { ParsedKForExpression } from './types';
2
+ export declare function parseKForExpression(raw: string, allowOfKeyword: boolean): ParsedKForExpression | null;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseKForExpression = parseKForExpression;
4
+ const constants_1 = require("./constants");
5
+ const identifiers_1 = require("./identifiers");
6
+ function parseKForExpression(raw, allowOfKeyword) {
7
+ const value = raw.trim();
8
+ if (!value) {
9
+ return null;
10
+ }
11
+ const tupleMatch = constants_1.KFOR_TUPLE_PATTERN.exec(value);
12
+ if (tupleMatch) {
13
+ const keyword = tupleMatch[4];
14
+ const source = tupleMatch[5]?.trim();
15
+ if ((!allowOfKeyword && keyword === 'of') || !source) {
16
+ return null;
17
+ }
18
+ return {
19
+ aliases: (0, identifiers_1.uniqueIdentifiers)([tupleMatch[1], tupleMatch[2], tupleMatch[3]].filter(Boolean)),
20
+ source,
21
+ };
22
+ }
23
+ const singleMatch = constants_1.KFOR_SINGLE_PATTERN.exec(value);
24
+ if (singleMatch) {
25
+ const keyword = singleMatch[2];
26
+ const source = singleMatch[3]?.trim();
27
+ if ((!allowOfKeyword && keyword === 'of') || !source) {
28
+ return null;
29
+ }
30
+ return {
31
+ aliases: (0, identifiers_1.uniqueIdentifiers)([singleMatch[1]]),
32
+ source,
33
+ };
34
+ }
35
+ return null;
36
+ }
@@ -0,0 +1,5 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ import type { FileAnalysis, KForBinding, KForScope, ResolvedConfig } from './types';
3
+ export declare function getFileAnalysis(fileName: string, languageService: tsModule.LanguageService, ts: typeof tsModule, config: ResolvedConfig): FileAnalysis | undefined;
4
+ export declare function isSuppressed(position: number, diagnosticName: string, scopes: KForScope[]): boolean;
5
+ export declare function collectBindingsAtPosition(position: number, scopes: KForScope[]): Map<string, KForBinding>;
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFileAnalysis = getFileAnalysis;
4
+ exports.isSuppressed = isSuppressed;
5
+ exports.collectBindingsAtPosition = collectBindingsAtPosition;
6
+ const jsx_attributes_1 = require("./jsx-attributes");
7
+ const kfor_parser_1 = require("./kfor-parser");
8
+ const identifiers_1 = require("./identifiers");
9
+ const type_resolution_1 = require("./type-resolution");
10
+ function getFileAnalysis(fileName, languageService, ts, config) {
11
+ const program = languageService.getProgram();
12
+ if (!program) {
13
+ return undefined;
14
+ }
15
+ const sourceFile = program.getSourceFile(fileName);
16
+ if (!sourceFile) {
17
+ return undefined;
18
+ }
19
+ const checker = program.getTypeChecker();
20
+ const scopes = collectKForScopes(sourceFile, checker, ts, config);
21
+ if (scopes.length === 0) {
22
+ return undefined;
23
+ }
24
+ return { sourceFile, checker, scopes };
25
+ }
26
+ function isSuppressed(position, diagnosticName, scopes) {
27
+ for (let i = scopes.length - 1; i >= 0; i--) {
28
+ const scope = scopes[i];
29
+ if (position < scope.start || position >= scope.end) {
30
+ continue;
31
+ }
32
+ for (let j = 0; j < scope.bindings.length; j++) {
33
+ if (scope.bindings[j].name === diagnosticName) {
34
+ return true;
35
+ }
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+ function collectBindingsAtPosition(position, scopes) {
41
+ const bindings = new Map();
42
+ for (let i = scopes.length - 1; i >= 0; i--) {
43
+ const scope = scopes[i];
44
+ if (position < scope.start || position >= scope.end) {
45
+ continue;
46
+ }
47
+ for (let j = 0; j < scope.bindings.length; j++) {
48
+ const binding = scope.bindings[j];
49
+ if (!bindings.has(binding.name)) {
50
+ bindings.set(binding.name, binding);
51
+ }
52
+ }
53
+ }
54
+ return bindings;
55
+ }
56
+ function collectKForScopes(sourceFile, checker, ts, config) {
57
+ const scopes = [];
58
+ const visit = (node) => {
59
+ if (ts.isJsxElement(node)) {
60
+ const forAttr = (0, jsx_attributes_1.getJsxAttribute)(node.openingElement, config.forAttr, ts);
61
+ if (forAttr) {
62
+ const bindings = resolveScopeBindings(node.openingElement, forAttr, checker, config, ts);
63
+ const start = node.openingElement.end;
64
+ const end = node.closingElement.getStart(sourceFile);
65
+ if (start < end && bindings.length > 0) {
66
+ scopes.push({ start, end, bindings });
67
+ }
68
+ }
69
+ }
70
+ ts.forEachChild(node, visit);
71
+ };
72
+ visit(sourceFile);
73
+ return scopes;
74
+ }
75
+ function resolveScopeBindings(opening, forAttr, checker, config, ts) {
76
+ const forExpression = (0, jsx_attributes_1.getAttributeText)(forAttr, ts);
77
+ if (forExpression !== undefined) {
78
+ const parsed = (0, kfor_parser_1.parseKForExpression)(forExpression, config.allowOfKeyword);
79
+ if (parsed) {
80
+ const sourceTypes = (0, type_resolution_1.resolveExpressionTypesFromText)(parsed.source, {
81
+ checker,
82
+ ts,
83
+ scopeNode: opening,
84
+ });
85
+ return createBindings(parsed.aliases, sourceTypes, checker, opening, ts);
86
+ }
87
+ }
88
+ const itemName = (0, jsx_attributes_1.getScopeName)(opening, config.itemAttr, config.itemName, ts);
89
+ const indexName = (0, jsx_attributes_1.getScopeName)(opening, config.indexAttr, config.indexName, ts);
90
+ const aliases = (0, identifiers_1.uniqueIdentifiers)([itemName, indexName]);
91
+ const sourceTypes = getLegacyForSourceTypes(forAttr, checker, ts);
92
+ return createBindings(aliases, sourceTypes, checker, opening, ts);
93
+ }
94
+ function createBindings(names, sourceTypes, checker, scopeNode, ts) {
95
+ if (names.length === 0) {
96
+ return [];
97
+ }
98
+ const inferred = inferBindingTypes(sourceTypes, names.length, checker, scopeNode, ts);
99
+ const bindings = [];
100
+ for (let i = 0; i < names.length; i++) {
101
+ bindings.push({
102
+ name: names[i],
103
+ types: inferred[i] || [],
104
+ });
105
+ }
106
+ return bindings;
107
+ }
108
+ function inferBindingTypes(sourceTypes, bindingCount, checker, scopeNode, ts) {
109
+ const slots = Array.from({ length: bindingCount }, () => []);
110
+ const candidates = expandUnionTypes(sourceTypes, ts);
111
+ for (let i = 0; i < candidates.length; i++) {
112
+ const sourceType = checker.getApparentType(candidates[i]);
113
+ const elementType = checker.getIndexTypeOfType(sourceType, ts.IndexKind.Number);
114
+ const stringValueType = elementType ? undefined : checker.getIndexTypeOfType(sourceType, ts.IndexKind.String);
115
+ const valueTypes = elementType ? [elementType] : stringValueType ? [stringValueType] : [];
116
+ if (valueTypes.length === 0) {
117
+ continue;
118
+ }
119
+ slots[0].push(...valueTypes);
120
+ if (bindingCount > 1) {
121
+ slots[1].push(elementType ? checker.getNumberType() : checker.getStringType());
122
+ }
123
+ if (bindingCount > 2) {
124
+ slots[2].push(checker.getNumberType());
125
+ }
126
+ }
127
+ for (let i = 0; i < slots.length; i++) {
128
+ slots[i] = (0, type_resolution_1.uniqueTypes)(slots[i], checker, scopeNode, ts);
129
+ }
130
+ return slots;
131
+ }
132
+ function expandUnionTypes(types, ts) {
133
+ const result = [];
134
+ for (let i = 0; i < types.length; i++) {
135
+ const type = types[i];
136
+ if (type.flags & ts.TypeFlags.Union) {
137
+ const union = type;
138
+ result.push(...union.types);
139
+ continue;
140
+ }
141
+ result.push(type);
142
+ }
143
+ return result;
144
+ }
145
+ function getLegacyForSourceTypes(forAttr, checker, ts) {
146
+ const expression = (0, jsx_attributes_1.getAttributeExpression)(forAttr, ts);
147
+ if (!expression || ts.isStringLiteralLike(expression)) {
148
+ return [];
149
+ }
150
+ return [checker.getTypeAtLocation(expression)];
151
+ }
@@ -0,0 +1,5 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ import type { TypeResolutionContext } from './types';
3
+ export declare function resolveExpressionTypesFromText(raw: string, context: TypeResolutionContext): tsModule.Type[];
4
+ export declare function formatTypeList(types: tsModule.Type[], checker: tsModule.TypeChecker, scopeNode: tsModule.Node, ts: typeof tsModule): string;
5
+ export declare function uniqueTypes(types: tsModule.Type[], checker: tsModule.TypeChecker, scopeNode: tsModule.Node, ts: typeof tsModule): tsModule.Type[];
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveExpressionTypesFromText = resolveExpressionTypesFromText;
4
+ exports.formatTypeList = formatTypeList;
5
+ exports.uniqueTypes = uniqueTypes;
6
+ function resolveExpressionTypesFromText(raw, context) {
7
+ const value = raw.trim();
8
+ if (!value) {
9
+ return [];
10
+ }
11
+ const sourceFile = context.ts.createSourceFile('__k_for_expression.ts', `(${value});`, context.ts.ScriptTarget.Latest, true, context.ts.ScriptKind.TS);
12
+ if (sourceFile.statements.length === 0) {
13
+ return [];
14
+ }
15
+ const statement = sourceFile.statements[0];
16
+ if (!context.ts.isExpressionStatement(statement)) {
17
+ return [];
18
+ }
19
+ const types = resolveExpressionTypes(statement.expression, context);
20
+ return uniqueTypes(types, context.checker, context.scopeNode, context.ts);
21
+ }
22
+ function formatTypeList(types, checker, scopeNode, ts) {
23
+ if (types.length === 0) {
24
+ return 'any';
25
+ }
26
+ const texts = new Set();
27
+ for (let i = 0; i < types.length; i++) {
28
+ texts.add(checker.typeToString(types[i], scopeNode, ts.TypeFormatFlags.NoTruncation));
29
+ }
30
+ return Array.from(texts).join(' | ');
31
+ }
32
+ function uniqueTypes(types, checker, scopeNode, ts) {
33
+ const seen = new Set();
34
+ const result = [];
35
+ for (let i = 0; i < types.length; i++) {
36
+ const type = types[i];
37
+ const text = checker.typeToString(type, scopeNode, ts.TypeFormatFlags.NoTruncation);
38
+ if (seen.has(text)) {
39
+ continue;
40
+ }
41
+ seen.add(text);
42
+ result.push(type);
43
+ }
44
+ return result;
45
+ }
46
+ function resolveExpressionTypes(expr, context) {
47
+ const ts = context.ts;
48
+ const target = unwrapExpression(expr, ts);
49
+ if (ts.isIdentifier(target)) {
50
+ return resolveIdentifierTypes(target.text, context);
51
+ }
52
+ if (ts.isPropertyAccessExpression(target)) {
53
+ const objectTypes = resolveExpressionTypes(target.expression, context);
54
+ return resolvePropertyTypes(objectTypes, target.name.text, context, false);
55
+ }
56
+ if (ts.isElementAccessExpression(target)) {
57
+ const objectTypes = resolveExpressionTypes(target.expression, context);
58
+ const argument = target.argumentExpression;
59
+ if (!argument) {
60
+ return [];
61
+ }
62
+ if (ts.isStringLiteralLike(argument)) {
63
+ return resolvePropertyTypes(objectTypes, argument.text, context, true);
64
+ }
65
+ if (ts.isNumericLiteral(argument)) {
66
+ return resolveNumericElementTypes(objectTypes, Number(argument.text), context);
67
+ }
68
+ return resolveIndexedTypes(objectTypes, context);
69
+ }
70
+ if (ts.isCallExpression(target)) {
71
+ const calleeTypes = resolveExpressionTypes(target.expression, context);
72
+ const result = [];
73
+ for (let i = 0; i < calleeTypes.length; i++) {
74
+ const signatures = context.checker.getSignaturesOfType(calleeTypes[i], ts.SignatureKind.Call);
75
+ for (let j = 0; j < signatures.length; j++) {
76
+ result.push(context.checker.getReturnTypeOfSignature(signatures[j]));
77
+ }
78
+ }
79
+ return uniqueTypes(result, context.checker, context.scopeNode, ts);
80
+ }
81
+ if (ts.isConditionalExpression(target)) {
82
+ const whenTrue = resolveExpressionTypes(target.whenTrue, context);
83
+ const whenFalse = resolveExpressionTypes(target.whenFalse, context);
84
+ return uniqueTypes([...whenTrue, ...whenFalse], context.checker, context.scopeNode, ts);
85
+ }
86
+ if (ts.isBinaryExpression(target) &&
87
+ (target.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
88
+ target.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
89
+ target.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)) {
90
+ const left = resolveExpressionTypes(target.left, context);
91
+ const right = resolveExpressionTypes(target.right, context);
92
+ return uniqueTypes([...left, ...right], context.checker, context.scopeNode, ts);
93
+ }
94
+ return [];
95
+ }
96
+ function unwrapExpression(expr, ts) {
97
+ let current = expr;
98
+ while (true) {
99
+ if (ts.isParenthesizedExpression(current)) {
100
+ current = current.expression;
101
+ continue;
102
+ }
103
+ if (ts.isAsExpression(current) || ts.isTypeAssertionExpression(current) || ts.isSatisfiesExpression(current)) {
104
+ current = current.expression;
105
+ continue;
106
+ }
107
+ if (ts.isNonNullExpression(current)) {
108
+ current = current.expression;
109
+ continue;
110
+ }
111
+ return current;
112
+ }
113
+ }
114
+ function resolveIdentifierTypes(name, context) {
115
+ const localTypes = context.localBindings?.get(name);
116
+ if (localTypes && localTypes.length > 0) {
117
+ return [...localTypes];
118
+ }
119
+ const symbol = resolveSymbolInScope(name, context);
120
+ if (!symbol) {
121
+ return [];
122
+ }
123
+ return [context.checker.getTypeOfSymbolAtLocation(symbol, context.scopeNode)];
124
+ }
125
+ function resolveSymbolInScope(name, context) {
126
+ const symbols = context.checker.getSymbolsInScope(context.scopeNode, context.ts.SymbolFlags.Value | context.ts.SymbolFlags.Alias);
127
+ for (let i = 0; i < symbols.length; i++) {
128
+ const symbol = symbols[i];
129
+ if (symbol.getName() !== name) {
130
+ continue;
131
+ }
132
+ if (symbol.flags & context.ts.SymbolFlags.Alias) {
133
+ const aliased = context.checker.getAliasedSymbol(symbol);
134
+ if (aliased.flags & context.ts.SymbolFlags.Value) {
135
+ return aliased;
136
+ }
137
+ continue;
138
+ }
139
+ if (symbol.flags & context.ts.SymbolFlags.Value) {
140
+ return symbol;
141
+ }
142
+ }
143
+ return undefined;
144
+ }
145
+ function resolvePropertyTypes(objectTypes, propertyName, context, allowStringIndexFallback) {
146
+ const result = [];
147
+ for (let i = 0; i < objectTypes.length; i++) {
148
+ const targetType = context.checker.getApparentType(objectTypes[i]);
149
+ const property = context.checker.getPropertyOfType(targetType, propertyName);
150
+ if (property) {
151
+ result.push(context.checker.getTypeOfSymbolAtLocation(property, context.scopeNode));
152
+ continue;
153
+ }
154
+ if (allowStringIndexFallback) {
155
+ const stringIndexType = context.checker.getIndexTypeOfType(targetType, context.ts.IndexKind.String);
156
+ if (stringIndexType) {
157
+ result.push(stringIndexType);
158
+ }
159
+ }
160
+ }
161
+ return uniqueTypes(result, context.checker, context.scopeNode, context.ts);
162
+ }
163
+ function resolveNumericElementTypes(objectTypes, index, context) {
164
+ const result = [];
165
+ const indexName = String(index);
166
+ for (let i = 0; i < objectTypes.length; i++) {
167
+ const targetType = context.checker.getApparentType(objectTypes[i]);
168
+ const property = context.checker.getPropertyOfType(targetType, indexName);
169
+ if (property) {
170
+ result.push(context.checker.getTypeOfSymbolAtLocation(property, context.scopeNode));
171
+ }
172
+ const numericIndexType = context.checker.getIndexTypeOfType(targetType, context.ts.IndexKind.Number);
173
+ if (numericIndexType) {
174
+ result.push(numericIndexType);
175
+ }
176
+ }
177
+ return uniqueTypes(result, context.checker, context.scopeNode, context.ts);
178
+ }
179
+ function resolveIndexedTypes(objectTypes, context) {
180
+ const result = [];
181
+ for (let i = 0; i < objectTypes.length; i++) {
182
+ const targetType = context.checker.getApparentType(objectTypes[i]);
183
+ const stringIndexType = context.checker.getIndexTypeOfType(targetType, context.ts.IndexKind.String);
184
+ if (stringIndexType) {
185
+ result.push(stringIndexType);
186
+ }
187
+ const numericIndexType = context.checker.getIndexTypeOfType(targetType, context.ts.IndexKind.Number);
188
+ if (numericIndexType) {
189
+ result.push(numericIndexType);
190
+ }
191
+ }
192
+ return uniqueTypes(result, context.checker, context.scopeNode, context.ts);
193
+ }
@@ -0,0 +1,46 @@
1
+ import type tsModule from 'typescript/lib/tsserverlibrary';
2
+ export interface KForPluginConfig {
3
+ forAttr?: string;
4
+ itemAttr?: string;
5
+ indexAttr?: string;
6
+ itemName?: string;
7
+ indexName?: string;
8
+ allowOfKeyword?: boolean;
9
+ }
10
+ export interface ResolvedConfig {
11
+ forAttr: string;
12
+ itemAttr: string;
13
+ indexAttr: string;
14
+ itemName: string;
15
+ indexName: string;
16
+ allowOfKeyword: boolean;
17
+ }
18
+ export interface KForBinding {
19
+ name: string;
20
+ types: tsModule.Type[];
21
+ }
22
+ export interface KForScope {
23
+ start: number;
24
+ end: number;
25
+ bindings: KForBinding[];
26
+ }
27
+ export interface ParsedKForExpression {
28
+ aliases: string[];
29
+ source: string;
30
+ }
31
+ export interface TypeResolutionContext {
32
+ checker: tsModule.TypeChecker;
33
+ ts: typeof tsModule;
34
+ scopeNode: tsModule.Node;
35
+ localBindings?: ReadonlyMap<string, readonly tsModule.Type[]>;
36
+ }
37
+ export interface MemberCompletionContext {
38
+ receiver: string;
39
+ prefix: string;
40
+ }
41
+ export interface FileAnalysis {
42
+ sourceFile: tsModule.SourceFile;
43
+ checker: tsModule.TypeChecker;
44
+ scopes: KForScope[];
45
+ }
46
+ export type JsxOpeningLikeElement = tsModule.JsxOpeningElement | tsModule.JsxSelfClosingElement;
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ktjs/ts-plugin",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
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",
@@ -39,4 +39,4 @@
39
39
  "scripts": {
40
40
  "build": "tsc -p tsconfig.json"
41
41
  }
42
- }
42
+ }