flow-parser 0.322.0 → 0.324.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.
@@ -1,313 +0,0 @@
1
- 'use strict';
2
-
3
- const assert = require('assert');
4
- const {
5
- hasNewline,
6
- addLeadingComment,
7
- addDanglingComment,
8
- addTrailingComment
9
- } = require('../common/util.js');
10
- const childNodesCache = new WeakMap();
11
- function getSortedChildNodes(node, options, resultArray) {
12
- if (!node) {
13
- return;
14
- }
15
- const {
16
- printer,
17
- locStart,
18
- locEnd
19
- } = options;
20
- if (resultArray) {
21
- if (printer.canAttachComment && printer.canAttachComment(node)) {
22
- let i;
23
- for (i = resultArray.length - 1; i >= 0; --i) {
24
- if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
25
- break;
26
- }
27
- }
28
- resultArray.splice(i + 1, 0, node);
29
- return;
30
- }
31
- } else if (childNodesCache.has(node)) {
32
- return childNodesCache.get(node);
33
- }
34
- const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === 'object' && Object.entries(node).filter(([key]) => key !== 'enclosingNode' && key !== 'precedingNode' && key !== 'followingNode' && key !== 'tokens' && key !== 'comments' && key !== 'parent').map(([, value]) => value);
35
- if (!childNodes) {
36
- return;
37
- }
38
- if (!resultArray) {
39
- resultArray = [];
40
- childNodesCache.set(node, resultArray);
41
- }
42
- for (const childNode of childNodes) {
43
- getSortedChildNodes(childNode, options, resultArray);
44
- }
45
- return resultArray;
46
- }
47
- function decorateComment(node, comment, options, enclosingNode) {
48
- const {
49
- locStart,
50
- locEnd
51
- } = options;
52
- const commentStart = locStart(comment);
53
- const commentEnd = locEnd(comment);
54
- const childNodes = getSortedChildNodes(node, options);
55
- let precedingNode;
56
- let followingNode;
57
- let left = 0;
58
- let right = childNodes.length;
59
- while (left < right) {
60
- const middle = left + right >> 1;
61
- const child = childNodes[middle];
62
- const start = locStart(child);
63
- const end = locEnd(child);
64
- if (start <= commentStart && commentEnd <= end) {
65
- return decorateComment(child, comment, options, child);
66
- }
67
- if (end <= commentStart) {
68
- precedingNode = child;
69
- left = middle + 1;
70
- continue;
71
- }
72
- if (commentEnd <= start) {
73
- followingNode = child;
74
- right = middle;
75
- continue;
76
- }
77
- throw new Error('Comment location overlaps with node location');
78
- }
79
- if (enclosingNode && enclosingNode.type === 'TemplateLiteral') {
80
- const {
81
- quasis
82
- } = enclosingNode;
83
- const commentIndex = findExpressionIndexForComment(quasis, comment, options);
84
- if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
85
- precedingNode = null;
86
- }
87
- if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
88
- followingNode = null;
89
- }
90
- }
91
- return {
92
- enclosingNode,
93
- precedingNode,
94
- followingNode
95
- };
96
- }
97
- const returnFalse = () => false;
98
- function attach(comments, ast, text, options) {
99
- if (!Array.isArray(comments)) {
100
- return;
101
- }
102
- const tiesToBreak = [];
103
- const {
104
- locStart,
105
- locEnd,
106
- printer: {
107
- handleComments = {}
108
- }
109
- } = options;
110
- const {
111
- avoidAstMutation,
112
- ownLine: handleOwnLineComment = returnFalse,
113
- endOfLine: handleEndOfLineComment = returnFalse,
114
- remaining: handleRemainingComment = returnFalse
115
- } = handleComments;
116
- const decoratedComments = comments.map((comment, index) => ({
117
- ...decorateComment(ast, comment, options),
118
- comment,
119
- text,
120
- options,
121
- ast,
122
- isLastComment: comments.length - 1 === index
123
- }));
124
- for (const [index, context] of decoratedComments.entries()) {
125
- const {
126
- comment,
127
- precedingNode,
128
- enclosingNode,
129
- followingNode,
130
- text,
131
- options,
132
- ast,
133
- isLastComment
134
- } = context;
135
- if (options.parser === 'json' || options.parser === 'json5' || options.parser === '__js_expression' || options.parser === '__vue_expression') {
136
- if (locStart(comment) - locStart(ast) <= 0) {
137
- addLeadingComment(ast, comment);
138
- continue;
139
- }
140
- if (locEnd(comment) - locEnd(ast) >= 0) {
141
- addTrailingComment(ast, comment);
142
- continue;
143
- }
144
- }
145
- let args;
146
- if (avoidAstMutation) {
147
- args = [context];
148
- } else {
149
- comment.enclosingNode = enclosingNode;
150
- comment.precedingNode = precedingNode;
151
- comment.followingNode = followingNode;
152
- args = [comment, text, options, ast, isLastComment];
153
- }
154
- if (isOwnLineComment(text, options, decoratedComments, index)) {
155
- comment.placement = 'ownLine';
156
- if (handleOwnLineComment(...args)) {} else if (followingNode) {
157
- addLeadingComment(followingNode, comment);
158
- } else if (precedingNode) {
159
- addTrailingComment(precedingNode, comment);
160
- } else if (enclosingNode) {
161
- addDanglingComment(enclosingNode, comment);
162
- } else {
163
- addDanglingComment(ast, comment);
164
- }
165
- } else if (isEndOfLineComment(text, options, decoratedComments, index)) {
166
- comment.placement = 'endOfLine';
167
- if (handleEndOfLineComment(...args)) {} else if (precedingNode) {
168
- addTrailingComment(precedingNode, comment);
169
- } else if (followingNode) {
170
- addLeadingComment(followingNode, comment);
171
- } else if (enclosingNode) {
172
- addDanglingComment(enclosingNode, comment);
173
- } else {
174
- addDanglingComment(ast, comment);
175
- }
176
- } else {
177
- comment.placement = 'remaining';
178
- if (handleRemainingComment(...args)) {} else if (precedingNode && followingNode) {
179
- const tieCount = tiesToBreak.length;
180
- if (tieCount > 0) {
181
- const lastTie = tiesToBreak[tieCount - 1];
182
- if (lastTie.followingNode !== followingNode) {
183
- breakTies(tiesToBreak, text, options);
184
- }
185
- }
186
- tiesToBreak.push(context);
187
- } else if (precedingNode) {
188
- addTrailingComment(precedingNode, comment);
189
- } else if (followingNode) {
190
- addLeadingComment(followingNode, comment);
191
- } else if (enclosingNode) {
192
- addDanglingComment(enclosingNode, comment);
193
- } else {
194
- addDanglingComment(ast, comment);
195
- }
196
- }
197
- }
198
- breakTies(tiesToBreak, text, options);
199
- if (!avoidAstMutation) {
200
- for (const comment of comments) {
201
- delete comment.precedingNode;
202
- delete comment.enclosingNode;
203
- delete comment.followingNode;
204
- }
205
- }
206
- }
207
- const isAllEmptyAndNoLineBreak = text => !/[\S\n\u2028\u2029]/.test(text);
208
- function isOwnLineComment(text, options, decoratedComments, commentIndex) {
209
- const {
210
- comment,
211
- precedingNode
212
- } = decoratedComments[commentIndex];
213
- const {
214
- locStart,
215
- locEnd
216
- } = options;
217
- let start = locStart(comment);
218
- if (precedingNode) {
219
- for (let index = commentIndex - 1; index >= 0; index--) {
220
- const {
221
- comment,
222
- precedingNode: currentCommentPrecedingNode
223
- } = decoratedComments[index];
224
- if (currentCommentPrecedingNode !== precedingNode || !isAllEmptyAndNoLineBreak(text.slice(locEnd(comment), start))) {
225
- break;
226
- }
227
- start = locStart(comment);
228
- }
229
- }
230
- return hasNewline(text, start, {
231
- backwards: true
232
- });
233
- }
234
- function isEndOfLineComment(text, options, decoratedComments, commentIndex) {
235
- const {
236
- comment,
237
- followingNode
238
- } = decoratedComments[commentIndex];
239
- const {
240
- locStart,
241
- locEnd
242
- } = options;
243
- let end = locEnd(comment);
244
- if (followingNode) {
245
- for (let index = commentIndex + 1; index < decoratedComments.length; index++) {
246
- const {
247
- comment,
248
- followingNode: currentCommentFollowingNode
249
- } = decoratedComments[index];
250
- if (currentCommentFollowingNode !== followingNode || !isAllEmptyAndNoLineBreak(text.slice(end, locStart(comment)))) {
251
- break;
252
- }
253
- end = locEnd(comment);
254
- }
255
- }
256
- return hasNewline(text, end);
257
- }
258
- function breakTies(tiesToBreak, text, options) {
259
- const tieCount = tiesToBreak.length;
260
- if (tieCount === 0) {
261
- return;
262
- }
263
- const {
264
- precedingNode,
265
- followingNode,
266
- enclosingNode
267
- } = tiesToBreak[0];
268
- const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
269
- let gapEndPos = options.locStart(followingNode);
270
- let indexOfFirstLeadingComment;
271
- for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
272
- const {
273
- comment,
274
- precedingNode: currentCommentPrecedingNode,
275
- followingNode: currentCommentFollowingNode
276
- } = tiesToBreak[indexOfFirstLeadingComment - 1];
277
- assert.strictEqual(currentCommentPrecedingNode, precedingNode);
278
- assert.strictEqual(currentCommentFollowingNode, followingNode);
279
- const gap = text.slice(options.locEnd(comment), gapEndPos);
280
- if (gapRegExp.test(gap)) {
281
- gapEndPos = options.locStart(comment);
282
- } else {
283
- break;
284
- }
285
- }
286
- for (const [i, {
287
- comment
288
- }] of tiesToBreak.entries()) {
289
- if (i < indexOfFirstLeadingComment) {
290
- addTrailingComment(precedingNode, comment);
291
- } else {
292
- addLeadingComment(followingNode, comment);
293
- }
294
- }
295
- for (const node of [precedingNode, followingNode]) {
296
- if (node.comments && node.comments.length > 1) {
297
- node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
298
- }
299
- }
300
- tiesToBreak.length = 0;
301
- }
302
- function findExpressionIndexForComment(quasis, comment, options) {
303
- const startPos = options.locStart(comment) - 1;
304
- for (let i = 1; i < quasis.length; ++i) {
305
- if (startPos < options.locStart(quasis[i])) {
306
- return i - 1;
307
- }
308
- }
309
- return 0;
310
- }
311
- module.exports = {
312
- attach
313
- };
@@ -1,4 +0,0 @@
1
- 'use strict';
2
-
3
- const getLast = arr => arr[arr.length - 1];
4
- module.exports = getLast;
@@ -1 +0,0 @@
1
- 'use strict';
@@ -1,24 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict-local
8
- * @format
9
- */
10
-
11
- /*
12
- * Minimal type-only stub for `DetachedNode<T>` and `MaybeDetachedNode<T>`.
13
- * Upstream hermes-transform's `src/detachedNode.js` defines these as part of
14
- * its broader detached-AST authoring surface used by node-builders. The
15
- * vendored `print()` only needs the structural types for its public API
16
- * signature; everything is type-erased at runtime by Babel's
17
- * flow-strip-types pass. By keeping a local stub we avoid pulling in the
18
- * full hermes-transform detached-node machinery.
19
- */
20
-
21
- 'use strict';
22
-
23
- export type DetachedNode<+T> = T;
24
- export type MaybeDetachedNode<+T> = T | DetachedNode<T>;
@@ -1,52 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.print = print;
7
- var _mutateESTreeASTForPrettier = _interopRequireDefault(require("../../utils/mutateESTreeASTForPrettier"));
8
- var prettier = _interopRequireWildcard(require("prettier"));
9
- var _comments = require("./comments/comments");
10
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
12
- async function print(ast, originalCode, prettierOptions = {}, visitorKeys) {
13
- const program = ast;
14
- if (program.body.length === 0) {
15
- var _program$docblock;
16
- const docblockComment = (_program$docblock = program.docblock) == null ? void 0 : _program$docblock.comment;
17
- if (docblockComment != null) {
18
- return '/*' + docblockComment.value + '*/\n';
19
- }
20
- return '';
21
- }
22
- const codeForPrinting = (0, _comments.mutateESTreeASTCommentsForPrettier)(program, originalCode);
23
- (0, _mutateESTreeASTForPrettier.default)(program, visitorKeys);
24
- let pluginParserName = 'flow';
25
- let pluginParser;
26
- let pluginPrinter;
27
- try {
28
- const prettierHermesPlugin = await Promise.resolve().then(() => _interopRequireWildcard(require('prettier-plugin-hermes-parser')));
29
- pluginParser = prettierHermesPlugin.parsers.hermes;
30
- pluginPrinter = prettierHermesPlugin.printers;
31
- pluginParserName = 'hermes';
32
- } catch {
33
- const prettierFlowPlugin = require('prettier/plugins/flow');
34
- pluginParser = prettierFlowPlugin.parsers.flow;
35
- }
36
- return prettier.format(codeForPrinting, {
37
- ...prettierOptions,
38
- parser: pluginParserName,
39
- requirePragma: false,
40
- plugins: [{
41
- parsers: {
42
- [pluginParserName]: {
43
- ...pluginParser,
44
- parse() {
45
- return program;
46
- }
47
- }
48
- },
49
- printers: pluginPrinter
50
- }]
51
- });
52
- }
@@ -1,87 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict-local
8
- * @format
9
- */
10
-
11
- 'use strict';
12
-
13
- import type {MaybeDetachedNode} from './detachedNodeTypes';
14
- import type {Program} from 'flow-estree';
15
-
16
- import mutateESTreeASTForPrettier from '../../utils/mutateESTreeASTForPrettier';
17
- import * as prettier from 'prettier';
18
- import {mutateESTreeASTCommentsForPrettier} from './comments/comments';
19
- import type {VisitorKeysType} from '../../traverse/getVisitorKeys';
20
-
21
- export async function print(
22
- ast: MaybeDetachedNode<Program>,
23
- originalCode: string,
24
- prettierOptions: {...} = {},
25
- visitorKeys?: ?VisitorKeysType,
26
- ): Promise<string> {
27
- // $FlowExpectedError[incompatible-type] This is now safe to access.
28
- const program: Program = ast;
29
-
30
- // If the AST body is empty, we can skip the cost of prettier by returning a static string of the contents.
31
- if (program.body.length === 0) {
32
- // If the program had a docblock comment, we need to create the string manually.
33
- const docblockComment = program.docblock?.comment;
34
- if (docblockComment != null) {
35
- return '/*' + docblockComment.value + '*/\n';
36
- }
37
-
38
- return '';
39
- }
40
-
41
- // Cleanup the comments from the AST and generate the "orginal" code needed for prettier.
42
- const codeForPrinting = mutateESTreeASTCommentsForPrettier(
43
- program,
44
- originalCode,
45
- );
46
-
47
- // Fix up the AST to match what prettier expects.
48
- mutateESTreeASTForPrettier(program, visitorKeys);
49
-
50
- let pluginParserName = 'flow';
51
- let pluginParser;
52
- let pluginPrinter;
53
- try {
54
- // Use prettier-plugin-hermes-parser if we can. It has latest Flow syntax support.
55
- // $FlowExpectedError[untyped-import]
56
- const prettierHermesPlugin = await import('prettier-plugin-hermes-parser');
57
- pluginParser = prettierHermesPlugin.parsers.hermes;
58
- pluginPrinter = prettierHermesPlugin.printers;
59
- pluginParserName = 'hermes';
60
- } catch {
61
- const prettierFlowPlugin = require('prettier/plugins/flow');
62
- pluginParser = prettierFlowPlugin.parsers.flow;
63
- }
64
-
65
- return prettier.format(
66
- codeForPrinting,
67
- // $FlowExpectedError[incompatible-exact] - we don't want to create a dependency on the prettier types
68
- {
69
- ...prettierOptions,
70
- parser: pluginParserName,
71
- requirePragma: false,
72
- plugins: [
73
- {
74
- parsers: {
75
- [pluginParserName]: {
76
- ...pluginParser,
77
- parse() {
78
- return program;
79
- },
80
- },
81
- },
82
- printers: pluginPrinter,
83
- },
84
- ],
85
- },
86
- );
87
- }