@tslite/services 0.0.0-stage → 1.13.0

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.
Files changed (176) hide show
  1. package/LICENSE +55 -0
  2. package/NOTICE +13 -0
  3. package/dist/_namespaces/edit.d.ts +8 -0
  4. package/dist/_namespaces/edit.js +11 -0
  5. package/dist/_namespaces/ts.Completions.StringCompletions.d.ts +1 -0
  6. package/dist/_namespaces/ts.Completions.StringCompletions.js +2 -0
  7. package/dist/_namespaces/ts.Completions.d.ts +2 -0
  8. package/dist/_namespaces/ts.Completions.js +3 -0
  9. package/dist/_namespaces/ts.FindAllReferences.d.ts +2 -0
  10. package/dist/_namespaces/ts.FindAllReferences.js +3 -0
  11. package/dist/_namespaces/ts.GoToDefinition.d.ts +1 -0
  12. package/dist/_namespaces/ts.GoToDefinition.js +2 -0
  13. package/dist/_namespaces/ts.NavigationBar.d.ts +1 -0
  14. package/dist/_namespaces/ts.NavigationBar.js +2 -0
  15. package/dist/_namespaces/ts.OrganizeImports.d.ts +1 -0
  16. package/dist/_namespaces/ts.OrganizeImports.js +2 -0
  17. package/dist/_namespaces/ts.OutliningElementsCollector.d.ts +1 -0
  18. package/dist/_namespaces/ts.OutliningElementsCollector.js +2 -0
  19. package/dist/_namespaces/ts.Rename.d.ts +1 -0
  20. package/dist/_namespaces/ts.Rename.js +2 -0
  21. package/dist/_namespaces/ts.SignatureHelp.d.ts +1 -0
  22. package/dist/_namespaces/ts.SignatureHelp.js +2 -0
  23. package/dist/_namespaces/ts.SmartSelectionRange.d.ts +1 -0
  24. package/dist/_namespaces/ts.SmartSelectionRange.js +2 -0
  25. package/dist/_namespaces/ts.SymbolDisplay.d.ts +1 -0
  26. package/dist/_namespaces/ts.SymbolDisplay.js +2 -0
  27. package/dist/_namespaces/ts.codefix.d.ts +26 -0
  28. package/dist/_namespaces/ts.codefix.js +27 -0
  29. package/dist/_namespaces/ts.d.ts +17 -0
  30. package/dist/_namespaces/ts.formatting.d.ts +7 -0
  31. package/dist/_namespaces/ts.formatting.js +8 -0
  32. package/dist/_namespaces/ts.js +20 -0
  33. package/dist/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.d.ts +1 -0
  34. package/dist/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.js +2 -0
  35. package/dist/_namespaces/ts.refactor.convertParamsToDestructuredObject.d.ts +1 -0
  36. package/dist/_namespaces/ts.refactor.convertParamsToDestructuredObject.js +2 -0
  37. package/dist/_namespaces/ts.refactor.convertStringOrTemplateLiteral.d.ts +1 -0
  38. package/dist/_namespaces/ts.refactor.convertStringOrTemplateLiteral.js +2 -0
  39. package/dist/_namespaces/ts.refactor.d.ts +9 -0
  40. package/dist/_namespaces/ts.refactor.extractSymbol.d.ts +1 -0
  41. package/dist/_namespaces/ts.refactor.extractSymbol.js +2 -0
  42. package/dist/_namespaces/ts.refactor.js +10 -0
  43. package/dist/_namespaces/ts.textChanges.d.ts +1 -0
  44. package/dist/_namespaces/ts.textChanges.js +2 -0
  45. package/dist/classifier.d.ts +5 -0
  46. package/dist/classifier.js +439 -0
  47. package/dist/codeFixProvider.d.ts +13 -0
  48. package/dist/codeFixProvider.js +84 -0
  49. package/dist/codefixes/addConvertToUnknownForNonOverlappingTypes.d.ts +1 -0
  50. package/dist/codefixes/addConvertToUnknownForNonOverlappingTypes.js +21 -0
  51. package/dist/codefixes/addEmptyExportDeclaration.d.ts +1 -0
  52. package/dist/codefixes/addEmptyExportDeclaration.js +17 -0
  53. package/dist/codefixes/addMissingAsync.d.ts +1 -0
  54. package/dist/codefixes/addMissingAsync.js +75 -0
  55. package/dist/codefixes/addMissingAwait.d.ts +1 -0
  56. package/dist/codefixes/addMissingAwait.js +236 -0
  57. package/dist/codefixes/addMissingConst.d.ts +1 -0
  58. package/dist/codefixes/addMissingConst.js +91 -0
  59. package/dist/codefixes/addNameToNamelessParameter.d.ts +1 -0
  60. package/dist/codefixes/addNameToNamelessParameter.js +29 -0
  61. package/dist/codefixes/convertConstToLet.d.ts +1 -0
  62. package/dist/codefixes/convertConstToLet.js +30 -0
  63. package/dist/codefixes/convertToAsyncFunction.d.ts +1 -0
  64. package/dist/codefixes/convertToAsyncFunction.js +495 -0
  65. package/dist/codefixes/convertToMappedObjectType.d.ts +1 -0
  66. package/dist/codefixes/convertToMappedObjectType.js +48 -0
  67. package/dist/codefixes/correctQualifiedNameToIndexedAccessType.d.ts +1 -0
  68. package/dist/codefixes/correctQualifiedNameToIndexedAccessType.js +33 -0
  69. package/dist/codefixes/fixAddModuleReferTypeMissingTypeof.d.ts +1 -0
  70. package/dist/codefixes/fixAddModuleReferTypeMissingTypeof.js +27 -0
  71. package/dist/codefixes/fixAwaitInSyncFunction.d.ts +1 -0
  72. package/dist/codefixes/fixAwaitInSyncFunction.js +69 -0
  73. package/dist/codefixes/fixExpectedComma.d.ts +1 -0
  74. package/dist/codefixes/fixExpectedComma.js +35 -0
  75. package/dist/codefixes/fixInvalidJsxCharacters.d.ts +1 -0
  76. package/dist/codefixes/fixInvalidJsxCharacters.js +41 -0
  77. package/dist/codefixes/fixMissingCallParentheses.d.ts +1 -0
  78. package/dist/codefixes/fixMissingCallParentheses.js +42 -0
  79. package/dist/codefixes/fixSpelling.d.ts +1 -0
  80. package/dist/codefixes/fixSpelling.js +94 -0
  81. package/dist/codefixes/fixUnreachableCode.d.ts +1 -0
  82. package/dist/codefixes/fixUnreachableCode.js +65 -0
  83. package/dist/codefixes/fixUnusedIdentifier.d.ts +1 -0
  84. package/dist/codefixes/fixUnusedIdentifier.js +224 -0
  85. package/dist/codefixes/helpers.d.ts +8 -0
  86. package/dist/codefixes/helpers.js +53 -0
  87. package/dist/codefixes/importFixes.d.ts +14 -0
  88. package/dist/codefixes/importFixes.js +441 -0
  89. package/dist/codefixes/inferFromUsage.d.ts +1 -0
  90. package/dist/codefixes/inferFromUsage.js +742 -0
  91. package/dist/codefixes/removeUnnecessaryAwait.d.ts +1 -0
  92. package/dist/codefixes/removeUnnecessaryAwait.js +41 -0
  93. package/dist/codefixes/returnValueCorrect.d.ts +1 -0
  94. package/dist/codefixes/returnValueCorrect.js +132 -0
  95. package/dist/codefixes/splitTypeOnlyImport.d.ts +1 -0
  96. package/dist/codefixes/splitTypeOnlyImport.js +32 -0
  97. package/dist/codefixes/useBigintLiteral.d.ts +1 -0
  98. package/dist/codefixes/useBigintLiteral.js +29 -0
  99. package/dist/completions.d.ts +83 -0
  100. package/dist/completions.js +1720 -0
  101. package/dist/documentHighlights.d.ts +8 -0
  102. package/dist/documentHighlights.js +367 -0
  103. package/dist/documentRegistry.d.ts +36 -0
  104. package/dist/documentRegistry.js +63 -0
  105. package/dist/editingServices.d.ts +1 -0
  106. package/dist/editingServices.js +4 -0
  107. package/dist/findAllReferences.d.ts +113 -0
  108. package/dist/findAllReferences.js +1366 -0
  109. package/dist/formatting/formatting.d.ts +26 -0
  110. package/dist/formatting/formatting.js +1021 -0
  111. package/dist/formatting/formattingContext.d.ts +34 -0
  112. package/dist/formatting/formattingContext.js +78 -0
  113. package/dist/formatting/formattingScanner.d.ts +14 -0
  114. package/dist/formatting/formattingScanner.js +228 -0
  115. package/dist/formatting/rule.d.ts +31 -0
  116. package/dist/formatting/rule.js +22 -0
  117. package/dist/formatting/rules.d.ts +7 -0
  118. package/dist/formatting/rules.js +610 -0
  119. package/dist/formatting/rulesMap.d.ts +5 -0
  120. package/dist/formatting/rulesMap.js +127 -0
  121. package/dist/formatting/smartIndenter.d.ts +44 -0
  122. package/dist/formatting/smartIndenter.js +518 -0
  123. package/dist/getEditsForFileRename.d.ts +6 -0
  124. package/dist/getEditsForFileRename.js +86 -0
  125. package/dist/goToDefinition.d.ts +8 -0
  126. package/dist/goToDefinition.js +246 -0
  127. package/dist/importTracker.d.ts +50 -0
  128. package/dist/importTracker.js +422 -0
  129. package/dist/index.d.ts +1 -0
  130. package/dist/index.js +3 -0
  131. package/dist/navigationBar.d.ts +3 -0
  132. package/dist/navigationBar.js +549 -0
  133. package/dist/organizeImports.d.ts +18 -0
  134. package/dist/organizeImports.js +290 -0
  135. package/dist/outliningElementsCollector.d.ts +2 -0
  136. package/dist/outliningElementsCollector.js +261 -0
  137. package/dist/refactorProvider.d.ts +5 -0
  138. package/dist/refactorProvider.js +16 -0
  139. package/dist/refactors/addOrRemoveBracesToArrowFunction.d.ts +1 -0
  140. package/dist/refactors/addOrRemoveBracesToArrowFunction.js +86 -0
  141. package/dist/refactors/convertExport.d.ts +1 -0
  142. package/dist/refactors/convertExport.js +126 -0
  143. package/dist/refactors/convertImport.d.ts +1 -0
  144. package/dist/refactors/convertImport.js +116 -0
  145. package/dist/refactors/convertParamsToDestructuredObject.d.ts +1 -0
  146. package/dist/refactors/convertParamsToDestructuredObject.js +282 -0
  147. package/dist/refactors/convertStringOrTemplateLiteral.d.ts +1 -0
  148. package/dist/refactors/convertStringOrTemplateLiteral.js +148 -0
  149. package/dist/refactors/extractSymbol.d.ts +60 -0
  150. package/dist/refactors/extractSymbol.js +1281 -0
  151. package/dist/refactors/extractType.d.ts +1 -0
  152. package/dist/refactors/extractType.js +102 -0
  153. package/dist/refactors/moveToNewFile.d.ts +1 -0
  154. package/dist/refactors/moveToNewFile.js +477 -0
  155. package/dist/rename.d.ts +2 -0
  156. package/dist/rename.js +100 -0
  157. package/dist/services.d.ts +48 -0
  158. package/dist/services.js +1480 -0
  159. package/dist/signatureHelp.d.ts +8 -0
  160. package/dist/signatureHelp.js +414 -0
  161. package/dist/smartSelection.d.ts +2 -0
  162. package/dist/smartSelection.js +243 -0
  163. package/dist/stringCompletions.d.ts +4 -0
  164. package/dist/stringCompletions.js +220 -0
  165. package/dist/suggestionDiagnostics.d.ts +6 -0
  166. package/dist/suggestionDiagnostics.js +92 -0
  167. package/dist/symbolDisplay.d.ts +16 -0
  168. package/dist/symbolDisplay.js +400 -0
  169. package/dist/textChanges.d.ts +161 -0
  170. package/dist/textChanges.js +1163 -0
  171. package/dist/types.d.ts +908 -0
  172. package/dist/types.js +263 -0
  173. package/dist/utilities.d.ts +283 -0
  174. package/dist/utilities.js +1981 -0
  175. package/package.json +45 -3
  176. package/README.md +0 -3
@@ -0,0 +1,243 @@
1
+ // Modificado de microsoft/TypeScript v3.9.10, src/services/smartSelection.ts: o namespace virou módulo ES, com os imports explícitos.
2
+ import { Debug, SyntaxKind, compact, contains, createNode, createTextSpanFromBounds, findIndex, getTouchingPropertyName, isBindingElement, isBlock, isImportDeclaration, isMappedTypeNode, isParameter, isPropertySignature, isSourceFile, isStringLiteral, isSyntaxList, isTemplateHead, isTemplateLiteral, isTemplateMiddleOrTemplateTail, isTemplateSpan, isTemplateTail, isVariableDeclaration, isVariableDeclarationList, isVariableStatement, last, positionsAreOnSameLine, textSpanIntersectsWithPosition, textSpansEqual, } from "./_namespaces/ts.js";
3
+ export function getSmartSelectionRange(pos, sourceFile) {
4
+ let selectionRange = {
5
+ textSpan: createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd())
6
+ };
7
+ let parentNode = sourceFile;
8
+ outer: while (true) {
9
+ const children = getSelectionChildren(parentNode);
10
+ if (!children.length)
11
+ break;
12
+ for (let i = 0; i < children.length; i++) {
13
+ const prevNode = children[i - 1];
14
+ const node = children[i];
15
+ const nextNode = children[i + 1];
16
+ if (node.getStart(sourceFile) > pos) {
17
+ break outer;
18
+ }
19
+ if (positionShouldSnapToNode(sourceFile, pos, node)) {
20
+ // 1. Blocks are effectively redundant with SyntaxLists.
21
+ // 2. TemplateSpans, along with the SyntaxLists containing them, are a somewhat unintuitive grouping
22
+ // of things that should be considered independently.
23
+ // 3. A VariableStatement’s children are just a VaraiableDeclarationList and a semicolon.
24
+ // 4. A lone VariableDeclaration in a VaraibleDeclaration feels redundant with the VariableStatement.
25
+ //
26
+ // Dive in without pushing a selection range.
27
+ if (isBlock(node)
28
+ || isTemplateSpan(node) || isTemplateHead(node) || isTemplateTail(node)
29
+ || prevNode && isTemplateHead(prevNode)
30
+ || isVariableDeclarationList(node) && isVariableStatement(parentNode)
31
+ || isSyntaxList(node) && isVariableDeclarationList(parentNode)
32
+ || isVariableDeclaration(node) && isSyntaxList(parentNode) && children.length === 1) {
33
+ parentNode = node;
34
+ break;
35
+ }
36
+ // Synthesize a stop for '${ ... }' since '${' and '}' actually belong to siblings.
37
+ if (isTemplateSpan(parentNode) && nextNode && isTemplateMiddleOrTemplateTail(nextNode)) {
38
+ const start = node.getFullStart() - "${".length;
39
+ const end = nextNode.getStart() + "}".length;
40
+ pushSelectionRange(start, end);
41
+ }
42
+ // Blocks with braces, brackets, parens, or JSX tags on separate lines should be
43
+ // selected from open to close, including whitespace but not including the braces/etc. themselves.
44
+ const isBetweenMultiLineBookends = isSyntaxList(node)
45
+ && isListOpener(prevNode)
46
+ && isListCloser(nextNode)
47
+ && !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
48
+ const start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
49
+ const end = isBetweenMultiLineBookends ? nextNode.getStart() : node.getEnd();
50
+ // Na tag, também o trecho do nó com o comentário JSDoc dele (CK-03).
51
+ pushSelectionRange(start, end);
52
+ // String literals should have a stop both inside and outside their quotes.
53
+ if (isStringLiteral(node) || isTemplateLiteral(node)) {
54
+ pushSelectionRange(start + 1, end - 1);
55
+ }
56
+ parentNode = node;
57
+ break;
58
+ }
59
+ // If we made it to the end of the for loop, we’re done.
60
+ // In practice, I’ve only seen this happen at the very end
61
+ // of a SourceFile.
62
+ if (i === children.length - 1) {
63
+ break outer;
64
+ }
65
+ }
66
+ }
67
+ return selectionRange;
68
+ function pushSelectionRange(start, end) {
69
+ // Skip empty ranges
70
+ if (start !== end) {
71
+ const textSpan = createTextSpanFromBounds(start, end);
72
+ if (!selectionRange || (
73
+ // Skip ranges that are identical to the parent
74
+ !textSpansEqual(textSpan, selectionRange.textSpan) &&
75
+ // Skip ranges that don’t contain the original position
76
+ textSpanIntersectsWithPosition(textSpan, pos))) {
77
+ selectionRange = { textSpan, ...selectionRange && { parent: selectionRange } };
78
+ }
79
+ }
80
+ }
81
+ }
82
+ /**
83
+ * Like `ts.positionBelongsToNode`, except positions immediately after nodes
84
+ * count too, unless that position belongs to the next node. In effect, makes
85
+ * selections able to snap to preceding tokens when the cursor is on the tail
86
+ * end of them with only whitespace ahead.
87
+ * @param sourceFile The source file containing the nodes.
88
+ * @param pos The position to check.
89
+ * @param node The candidate node to snap to.
90
+ */
91
+ function positionShouldSnapToNode(sourceFile, pos, node) {
92
+ // Can’t use 'ts.positionBelongsToNode()' here because it cleverly accounts
93
+ // for missing nodes, which can’t really be considered when deciding what
94
+ // to select.
95
+ Debug.assert(node.pos <= pos);
96
+ if (pos < node.end) {
97
+ return true;
98
+ }
99
+ const nodeEnd = node.getEnd();
100
+ if (nodeEnd === pos) {
101
+ return getTouchingPropertyName(sourceFile, pos).pos < node.end;
102
+ }
103
+ return false;
104
+ }
105
+ // Na tag, também o `import =` (CK-03).
106
+ const isImport = isImportDeclaration;
107
+ /**
108
+ * Gets the children of a node to be considered for selection ranging,
109
+ * transforming them into an artificial tree according to their intuitive
110
+ * grouping where no grouping actually exists in the parse tree. For example,
111
+ * top-level imports are grouped into their own SyntaxList so they can be
112
+ * selected all together, even though in the AST they’re just siblings of each
113
+ * other as well as of other top-level statements and declarations.
114
+ */
115
+ function getSelectionChildren(node) {
116
+ // Group top-level imports
117
+ if (isSourceFile(node)) {
118
+ return groupChildren(node.getChildAt(0).getChildren(), isImport);
119
+ }
120
+ // Mapped types _look_ like ObjectTypes with a single member,
121
+ // but in fact don’t contain a SyntaxList or a node containing
122
+ // the “key/value” pair like ObjectTypes do, but it seems intuitive
123
+ // that the selection would snap to those points. The philosophy
124
+ // of choosing a selection range is not so much about what the
125
+ // syntax currently _is_ as what the syntax might easily become
126
+ // if the user is making a selection; e.g., we synthesize a selection
127
+ // around the “key/value” pair not because there’s a node there, but
128
+ // because it allows the mapped type to become an object type with a
129
+ // few keystrokes.
130
+ if (isMappedTypeNode(node)) {
131
+ const [openBraceToken, ...children] = node.getChildren();
132
+ const closeBraceToken = Debug.checkDefined(children.pop());
133
+ Debug.assertEqual(openBraceToken.kind, SyntaxKind.OpenBraceToken);
134
+ Debug.assertEqual(closeBraceToken.kind, SyntaxKind.CloseBraceToken);
135
+ // Group `-/+readonly` and `-/+?`
136
+ const groupedWithPlusMinusTokens = groupChildren(children, child => child === node.readonlyToken || child.kind === SyntaxKind.ReadonlyKeyword ||
137
+ child === node.questionToken || child.kind === SyntaxKind.QuestionToken);
138
+ // Group type parameter with surrounding brackets
139
+ const groupedWithBrackets = groupChildren(groupedWithPlusMinusTokens, ({ kind }) => kind === SyntaxKind.OpenBracketToken ||
140
+ kind === SyntaxKind.TypeParameter ||
141
+ kind === SyntaxKind.CloseBracketToken);
142
+ return [
143
+ openBraceToken,
144
+ // Pivot on `:`
145
+ createSyntaxList(splitChildren(groupedWithBrackets, ({ kind }) => kind === SyntaxKind.ColonToken)),
146
+ closeBraceToken,
147
+ ];
148
+ }
149
+ // Group modifiers and property name, then pivot on `:`.
150
+ if (isPropertySignature(node)) {
151
+ const children = groupChildren(node.getChildren(), child => child === node.name || contains(node.modifiers, child));
152
+ return splitChildren(children, ({ kind }) => kind === SyntaxKind.ColonToken);
153
+ }
154
+ // Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`.
155
+ if (isParameter(node)) {
156
+ const groupedDotDotDotAndName = groupChildren(node.getChildren(), child => child === node.dotDotDotToken || child === node.name);
157
+ const groupedWithQuestionToken = groupChildren(groupedDotDotDotAndName, child => child === groupedDotDotDotAndName[0] || child === node.questionToken);
158
+ return splitChildren(groupedWithQuestionToken, ({ kind }) => kind === SyntaxKind.EqualsToken);
159
+ }
160
+ // Pivot on '='
161
+ if (isBindingElement(node)) {
162
+ return splitChildren(node.getChildren(), ({ kind }) => kind === SyntaxKind.EqualsToken);
163
+ }
164
+ return node.getChildren();
165
+ }
166
+ /**
167
+ * Groups sibling nodes together into their own SyntaxList if they
168
+ * a) are adjacent, AND b) match a predicate function.
169
+ */
170
+ function groupChildren(children, groupOn) {
171
+ const result = [];
172
+ let group;
173
+ for (const child of children) {
174
+ if (groupOn(child)) {
175
+ group = group || [];
176
+ group.push(child);
177
+ }
178
+ else {
179
+ if (group) {
180
+ result.push(createSyntaxList(group));
181
+ group = undefined;
182
+ }
183
+ result.push(child);
184
+ }
185
+ }
186
+ if (group) {
187
+ result.push(createSyntaxList(group));
188
+ }
189
+ return result;
190
+ }
191
+ /**
192
+ * Splits sibling nodes into up to four partitions:
193
+ * 1) everything left of the first node matched by `pivotOn`,
194
+ * 2) the first node matched by `pivotOn`,
195
+ * 3) everything right of the first node matched by `pivotOn`,
196
+ * 4) a trailing semicolon, if `separateTrailingSemicolon` is enabled.
197
+ * The left and right groups, if not empty, will each be grouped into their own containing SyntaxList.
198
+ * @param children The sibling nodes to split.
199
+ * @param pivotOn The predicate function to match the node to be the pivot. The first node that matches
200
+ * the predicate will be used; any others that may match will be included into the right-hand group.
201
+ * @param separateTrailingSemicolon If the last token is a semicolon, it will be returned as a separate
202
+ * child rather than be included in the right-hand group.
203
+ */
204
+ function splitChildren(children, pivotOn, separateTrailingSemicolon = true) {
205
+ if (children.length < 2) {
206
+ return children;
207
+ }
208
+ const splitTokenIndex = findIndex(children, pivotOn);
209
+ if (splitTokenIndex === -1) {
210
+ return children;
211
+ }
212
+ const leftChildren = children.slice(0, splitTokenIndex);
213
+ const splitToken = children[splitTokenIndex];
214
+ const lastToken = last(children);
215
+ const separateLastToken = separateTrailingSemicolon && lastToken.kind === SyntaxKind.SemicolonToken;
216
+ const rightChildren = children.slice(splitTokenIndex + 1, separateLastToken ? children.length - 1 : undefined);
217
+ const result = compact([
218
+ leftChildren.length ? createSyntaxList(leftChildren) : undefined,
219
+ splitToken,
220
+ rightChildren.length ? createSyntaxList(rightChildren) : undefined,
221
+ ]);
222
+ return separateLastToken ? result.concat(lastToken) : result;
223
+ }
224
+ function createSyntaxList(children) {
225
+ Debug.assertGreaterThanOrEqual(children.length, 1);
226
+ const syntaxList = createNode(SyntaxKind.SyntaxList, children[0].pos, last(children).end);
227
+ syntaxList._children = children;
228
+ return syntaxList;
229
+ }
230
+ function isListOpener(token) {
231
+ const kind = token && token.kind;
232
+ return kind === SyntaxKind.OpenBraceToken
233
+ || kind === SyntaxKind.OpenBracketToken
234
+ || kind === SyntaxKind.OpenParenToken
235
+ || kind === SyntaxKind.JsxOpeningElement;
236
+ }
237
+ function isListCloser(token) {
238
+ const kind = token && token.kind;
239
+ return kind === SyntaxKind.CloseBraceToken
240
+ || kind === SyntaxKind.CloseBracketToken
241
+ || kind === SyntaxKind.CloseParenToken
242
+ || kind === SyntaxKind.JsxClosingElement;
243
+ }
@@ -0,0 +1,4 @@
1
+ import type { CancellationToken, CompletionEntryDetails, CompletionInfo, LanguageServiceHost, Node, SourceFile, TypeChecker, UserPreferences } from "./_namespaces/ts.js";
2
+ import type { Log } from "./_namespaces/ts.Completions.js";
3
+ export declare function getStringLiteralCompletions(sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, _host: LanguageServiceHost, log: Log, preferences: UserPreferences): CompletionInfo | undefined;
4
+ export declare function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, _host: LanguageServiceHost, cancellationToken: CancellationToken): CompletionEntryDetails | undefined;
@@ -0,0 +1,220 @@
1
+ // Modificado de microsoft/TypeScript v3.9.10, src/services/stringCompletions.ts: o namespace virou módulo ES, com os imports explícitos.
2
+ import { Debug, Extension, ScriptTarget, SignatureHelp, SyntaxKind, TypeFlags, addToSeen, contains, createMap, createTextSpan, directorySeparator, emptyArray, find, flatMap, getContextualTypeFromParent, getReplacementSpanForContextToken, hasIndexSignature, isIdentifierText, isImportCall, isInString, isLiteralTypeNode, isObjectLiteralExpression, isRequireCall, isStringLiteral, isStringLiteralLike, isTypeReferenceNode, mapDefined, signatureHasRestParameter, skipConstraint, textPart, } from "./_namespaces/ts.js";
3
+ import { SortText, createCompletionDetails, createCompletionDetailsForSymbol, getCompletionEntriesFromSymbols, } from "./_namespaces/ts.Completions.js";
4
+ /* @internal */
5
+ export function getStringLiteralCompletions(sourceFile, position, contextToken, checker, _host, log, preferences) {
6
+ // Na tag, o caminho de uma referência `/// <reference path>` tinha completion; a Linguagem não tem a referência (CK-03).
7
+ if (isInString(sourceFile, position, contextToken)) {
8
+ if (!contextToken || !isStringLiteralLike(contextToken))
9
+ return undefined;
10
+ const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker);
11
+ return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences);
12
+ }
13
+ }
14
+ function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) {
15
+ if (completion === undefined) {
16
+ return undefined;
17
+ }
18
+ switch (completion.kind) {
19
+ case 0 /* StringLiteralCompletionKind.Paths */:
20
+ return convertPathCompletions(completion.paths);
21
+ case 1 /* StringLiteralCompletionKind.Properties */: {
22
+ const entries = [];
23
+ getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, 4 /* CompletionKind.String */, preferences); // Target will not be used, so arbitrary
24
+ return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries };
25
+ }
26
+ case 2 /* StringLiteralCompletionKind.Types */: {
27
+ const entries = completion.types.map(type => ({
28
+ name: type.value,
29
+ kindModifiers: "" /* ScriptElementKindModifier.none */,
30
+ kind: "string" /* ScriptElementKind.string */,
31
+ sortText: "0",
32
+ replacementSpan: getReplacementSpanForContextToken(contextToken)
33
+ }));
34
+ return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries };
35
+ }
36
+ default:
37
+ return Debug.assertNever(completion);
38
+ }
39
+ }
40
+ export function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, checker, _host, cancellationToken) {
41
+ if (!contextToken || !isStringLiteralLike(contextToken))
42
+ return undefined;
43
+ const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker);
44
+ return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken);
45
+ }
46
+ function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) {
47
+ switch (completion.kind) {
48
+ case 0 /* StringLiteralCompletionKind.Paths */: {
49
+ const match = find(completion.paths, p => p.name === name);
50
+ return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]);
51
+ }
52
+ case 1 /* StringLiteralCompletionKind.Properties */: {
53
+ const match = find(completion.symbols, s => s.name === name);
54
+ return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken);
55
+ }
56
+ case 2 /* StringLiteralCompletionKind.Types */:
57
+ return find(completion.types, t => t.value === name) ? createCompletionDetails(name, "" /* ScriptElementKindModifier.none */, "type" /* ScriptElementKind.typeElement */, [textPart(name)]) : undefined;
58
+ default:
59
+ return Debug.assertNever(completion);
60
+ }
61
+ }
62
+ function convertPathCompletions(pathCompletions) {
63
+ const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment.
64
+ const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of.
65
+ const entries = pathCompletions.map(({ name, kind, span, extension }) => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span }));
66
+ return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries };
67
+ }
68
+ function kindModifiersFromExtension(extension) {
69
+ switch (extension) {
70
+ case Extension.Dts: return ".d.ts" /* ScriptElementKindModifier.dtsModifier */;
71
+ case Extension.Js: return ".js" /* ScriptElementKindModifier.jsModifier */;
72
+ case Extension.Json: return ".json" /* ScriptElementKindModifier.jsonModifier */;
73
+ case Extension.Jsx: return ".jsx" /* ScriptElementKindModifier.jsxModifier */;
74
+ case Extension.Ts: return ".ts" /* ScriptElementKindModifier.tsModifier */;
75
+ case Extension.Tsx: return ".tsx" /* ScriptElementKindModifier.tsxModifier */;
76
+ case Extension.TsBuildInfo: return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`);
77
+ case undefined: return "" /* ScriptElementKindModifier.none */;
78
+ default:
79
+ return Debug.assertNever(extension);
80
+ }
81
+ }
82
+ var StringLiteralCompletionKind;
83
+ (function (StringLiteralCompletionKind) {
84
+ StringLiteralCompletionKind[StringLiteralCompletionKind["Paths"] = 0] = "Paths";
85
+ StringLiteralCompletionKind[StringLiteralCompletionKind["Properties"] = 1] = "Properties";
86
+ StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types";
87
+ })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {}));
88
+ function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker) {
89
+ const { parent } = node;
90
+ switch (parent.kind) {
91
+ case SyntaxKind.LiteralType:
92
+ switch (parent.parent.kind) {
93
+ case SyntaxKind.TypeReference:
94
+ return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false };
95
+ case SyntaxKind.IndexedAccessType:
96
+ // Get all apparent property names
97
+ // i.e. interface Foo {
98
+ // foo: string;
99
+ // bar: string;
100
+ // }
101
+ // let x: Foo["/*completion position*/"]
102
+ return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType));
103
+ case SyntaxKind.ImportType:
104
+ return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node) };
105
+ case SyntaxKind.UnionType: {
106
+ if (!isTypeReferenceNode(parent.parent.parent))
107
+ return undefined;
108
+ const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent);
109
+ const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(t => !contains(alreadyUsedTypes, t.value));
110
+ return { kind: 2 /* StringLiteralCompletionKind.Types */, types, isNewIdentifier: false };
111
+ }
112
+ default:
113
+ return undefined;
114
+ }
115
+ case SyntaxKind.PropertyAssignment:
116
+ if (isObjectLiteralExpression(parent.parent) && parent.name === node) {
117
+ // Get quoted name of properties of the object literal expression
118
+ // i.e. interface ConfigFiles {
119
+ // 'jspm:dev': string
120
+ // }
121
+ // let files: ConfigFiles = {
122
+ // '/*completion position*/'
123
+ // }
124
+ //
125
+ // function foo(c: ConfigFiles) {}
126
+ // foo({
127
+ // '/*completion position*/'
128
+ // });
129
+ return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent));
130
+ }
131
+ return fromContextualType();
132
+ case SyntaxKind.ElementAccessExpression: {
133
+ const { expression, argumentExpression } = parent;
134
+ if (node === argumentExpression) {
135
+ // Get all names of properties on the expression
136
+ // i.e. interface A {
137
+ // 'prop1': string
138
+ // }
139
+ // let a: A;
140
+ // a['/*completion position*/']
141
+ return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression));
142
+ }
143
+ return undefined;
144
+ }
145
+ case SyntaxKind.CallExpression:
146
+ if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) {
147
+ const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile);
148
+ // Get string literal completions from specialized signatures of the target
149
+ // i.e. declare function f(a: 'A');
150
+ // f("/*completion position*/")
151
+ return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType();
152
+ }
153
+ // falls through (is `require("")` or `import("")`)
154
+ case SyntaxKind.ImportDeclaration:
155
+ case SyntaxKind.ExportDeclaration:
156
+ // O caminho de um módulo: import * as ns from "/*completion position*/";
157
+ // var y = require("/*completion position*/");
158
+ // export * from "/*completion position*/";
159
+ return { kind: 0 /* StringLiteralCompletionKind.Paths */, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node) };
160
+ default:
161
+ return fromContextualType();
162
+ }
163
+ function fromContextualType() {
164
+ // Get completion for string literal from string literal type
165
+ // i.e. var x: "hi" | "hello" = "/*completion position*/"
166
+ return { kind: 2 /* StringLiteralCompletionKind.Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false };
167
+ }
168
+ }
169
+ function getAlreadyUsedTypesInStringLiteralUnion(union, current) {
170
+ return mapDefined(union.types, type => type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined);
171
+ }
172
+ function getStringLiteralCompletionsFromSignature(argumentInfo, checker) {
173
+ let isNewIdentifier = false;
174
+ const uniques = createMap();
175
+ const candidates = [];
176
+ checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
177
+ const types = flatMap(candidates, candidate => {
178
+ if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length)
179
+ return;
180
+ const type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
181
+ isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String);
182
+ return getStringLiteralTypes(type, uniques);
183
+ });
184
+ return { kind: 2 /* StringLiteralCompletionKind.Types */, types, isNewIdentifier };
185
+ }
186
+ function stringLiteralCompletionsFromProperties(type) {
187
+ return type && {
188
+ kind: 1 /* StringLiteralCompletionKind.Properties */,
189
+ // Na tag, sem o `#private` (CK-02).
190
+ symbols: type.getApparentProperties(),
191
+ hasIndexSignature: hasIndexSignature(type)
192
+ };
193
+ }
194
+ function getStringLiteralTypes(type, uniques = createMap()) {
195
+ if (!type)
196
+ return emptyArray;
197
+ type = skipConstraint(type);
198
+ // Na tag, o literal de string de um membro de enum ficava de fora (CK-02).
199
+ return type.isUnion() ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) :
200
+ type.isStringLiteral() && addToSeen(uniques, type.value) ? [type] : emptyArray;
201
+ }
202
+ function addReplacementSpans(text, textStart, names) {
203
+ const span = getDirectoryFragmentTextSpan(text, textStart);
204
+ return names.map(({ name, kind, extension }) => ({ name, kind, extension, span }));
205
+ }
206
+ /**
207
+ * O completion do caminho de um módulo. Na tag, ele lia o disco do host: os diretórios relativos, o `baseUrl` e o
208
+ * `paths`, os módulos ambientes, os pacotes de tipos e o `node_modules`. O host da Linguagem não lê disco (CK-47), e a
209
+ * resolução de um import é dele (CK-46): a lista sai vazia, como a da tag com um host que não lê diretório.
210
+ */
211
+ function getStringLiteralCompletionsFromModuleNames(sourceFile, node) {
212
+ return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, emptyArray);
213
+ }
214
+ function getDirectoryFragmentTextSpan(text, textStart) {
215
+ const index = Math.max(text.lastIndexOf(directorySeparator), text.lastIndexOf("\\"));
216
+ const offset = index !== -1 ? index + 1 : 0;
217
+ // If the range is an identifier, span is unnecessary.
218
+ const length = text.length - offset;
219
+ return length === 0 || isIdentifierText(text.substr(offset, length), ScriptTarget.ESNext) ? undefined : createTextSpan(textStart + offset, length);
220
+ }
@@ -0,0 +1,6 @@
1
+ import type { CallExpression, CancellationToken, CheckResult, DiagnosticWithLocation, Node, ReturnStatement, SourceFile } from "./_namespaces/ts.js";
2
+ export declare function computeSuggestionDiagnostics(sourceFile: SourceFile, program: CheckResult, cancellationToken: CancellationToken): DiagnosticWithLocation[];
3
+ export declare function isReturnStatementWithFixablePromiseHandler(node: Node): node is ReturnStatement & {
4
+ expression: CallExpression;
5
+ };
6
+ export declare function isFixablePromiseHandler(node: Node): boolean;
@@ -0,0 +1,92 @@
1
+ // Modificado de microsoft/TypeScript v3.9.10, src/services/suggestionDiagnostics.ts: o namespace virou módulo ES, com os imports explícitos.
2
+ import { Diagnostics, SyntaxKind, addRange, createDiagnosticForNode, createMap, forEachReturnStatement, hasPropertyAccessExpressionWithName, isAsyncFunction, isBlock, isCallExpression, isFunctionLikeDeclaration, isIdentifier, isPropertyAccessExpression, isReturnStatement, isVariableDeclaration, some, } from "./_namespaces/ts.js";
3
+ const visitedNestedConvertibleFunctions = createMap();
4
+ export function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) {
5
+ program.getSemanticDiagnostics(sourceFile, cancellationToken);
6
+ const diags = [];
7
+ const checker = program.getTypeChecker();
8
+ visitedNestedConvertibleFunctions.clear();
9
+ check(sourceFile);
10
+ addRange(diags, sourceFile.bindSuggestionDiagnostics);
11
+ addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken));
12
+ return diags.sort((d1, d2) => d1.start - d2.start);
13
+ function check(node) {
14
+ // Na tag, também a sugestão de converter o `const x = require("…")` de topo num import (o TS80005): o `require` é
15
+ // CommonJS (CK-03), e o nome não se acha na Linguagem (CK-68).
16
+ if (isFunctionLikeDeclaration(node)) {
17
+ addConvertToAsyncFunctionDiagnostics(node, checker, diags);
18
+ }
19
+ node.forEachChild(check);
20
+ }
21
+ }
22
+ function addConvertToAsyncFunctionDiagnostics(node, checker, diags) {
23
+ // A função se confere antes do mapa, para os callbacks aninhados mais fundo também se conferirem.
24
+ if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) {
25
+ diags.push(createDiagnosticForNode(!node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function));
26
+ }
27
+ }
28
+ function isConvertibleFunction(node, checker) {
29
+ return !isAsyncFunction(node) &&
30
+ node.body &&
31
+ isBlock(node.body) &&
32
+ hasReturnStatementWithPromiseHandler(node.body) &&
33
+ returnsPromise(node, checker);
34
+ }
35
+ function returnsPromise(node, checker) {
36
+ const functionType = checker.getTypeAtLocation(node);
37
+ const callSignatures = checker.getSignaturesOfType(functionType);
38
+ const returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined;
39
+ return !!returnType && !!checker.getPromisedTypeOfPromise(returnType);
40
+ }
41
+ function hasReturnStatementWithPromiseHandler(body) {
42
+ return !!forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler);
43
+ }
44
+ export function isReturnStatementWithFixablePromiseHandler(node) {
45
+ return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression);
46
+ }
47
+ // Acompanha o `transformExpression` do code fix que converte para async (`convertToAsyncFunction.ts`).
48
+ export function isFixablePromiseHandler(node) {
49
+ // a chamada de fora existe e é um handler de promise
50
+ if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) {
51
+ return false;
52
+ }
53
+ // e cada chamada encadeada é válida
54
+ let currentNode = node.expression;
55
+ while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) {
56
+ if (isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) {
57
+ return false;
58
+ }
59
+ currentNode = currentNode.expression;
60
+ }
61
+ return true;
62
+ }
63
+ function isPromiseHandler(node) {
64
+ return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) ||
65
+ hasPropertyAccessExpressionWithName(node, "catch"));
66
+ }
67
+ function hasSupportedNumberOfArguments(node) {
68
+ if (node.arguments.length > 2)
69
+ return false;
70
+ if (node.arguments.length < 2)
71
+ return true;
72
+ return some(node.arguments, arg => {
73
+ return arg.kind === SyntaxKind.NullKeyword ||
74
+ isIdentifier(arg) && arg.text === "undefined";
75
+ });
76
+ }
77
+ // Acompanha o `getTransformationBody` do code fix que converte para async (`convertToAsyncFunction.ts`).
78
+ function isFixablePromiseArgument(arg) {
79
+ switch (arg.kind) {
80
+ case SyntaxKind.ArrowFunction:
81
+ visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true);
82
+ // falls through
83
+ case SyntaxKind.NullKeyword:
84
+ case SyntaxKind.Identifier: // o `undefined` é um identificador
85
+ return true;
86
+ default:
87
+ return false;
88
+ }
89
+ }
90
+ function getKeyFromNode(exp) {
91
+ return `${exp.pos.toString()}:${exp.end.toString()}`;
92
+ }
@@ -0,0 +1,16 @@
1
+ import { ScriptElementKind, SemanticMeaning } from "./_namespaces/ts.js";
2
+ import type { JSDocTagInfo, Node, SourceFile, Symbol, SymbolDisplayPart, TypeChecker } from "./_namespaces/ts.js";
3
+ export declare function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind;
4
+ export declare function getSymbolModifiers(symbol: Symbol): string;
5
+ interface SymbolDisplayPartsDocumentationAndSymbolKind {
6
+ displayParts: SymbolDisplayPart[];
7
+ documentation: SymbolDisplayPart[];
8
+ symbolKind: ScriptElementKind;
9
+ tags: JSDocTagInfo[] | undefined;
10
+ }
11
+ /**
12
+ * O texto do símbolo no ponto (`displayParts`), o tipo de símbolo e a documentação. A documentação e as tags vinham do
13
+ * JSDoc, que a cópia não tem (CK-03): saem vazias.
14
+ */
15
+ export declare function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: TypeChecker, symbol: Symbol, sourceFile: SourceFile, enclosingDeclaration: Node | undefined, location: Node, semanticMeaning?: SemanticMeaning, alias?: Symbol): SymbolDisplayPartsDocumentationAndSymbolKind;
16
+ export {};