hermes-transform 0.5.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -0
  3. package/dist/detachedNode.js +128 -0
  4. package/dist/detachedNode.js.flow +113 -0
  5. package/dist/generated/TransformCloneSignatures.js.flow +19 -0
  6. package/dist/generated/TransformReplaceSignatures.js.flow +943 -0
  7. package/dist/generated/node-types.js +2071 -0
  8. package/dist/generated/node-types.js.flow +3149 -0
  9. package/dist/generated/special-case-node-types.js +178 -0
  10. package/dist/generated/special-case-node-types.js.flow +248 -0
  11. package/dist/getVisitorKeys.js +35 -0
  12. package/dist/getVisitorKeys.js.flow +31 -0
  13. package/dist/index.js +41 -0
  14. package/dist/index.js.flow +15 -0
  15. package/dist/transform/Errors.js +151 -0
  16. package/dist/transform/Errors.js.flow +17 -0
  17. package/dist/transform/MutationContext.js +94 -0
  18. package/dist/transform/MutationContext.js.flow +80 -0
  19. package/dist/transform/TransformContext.js +136 -0
  20. package/dist/transform/TransformContext.js.flow +378 -0
  21. package/dist/transform/comments/comments.js +140 -0
  22. package/dist/transform/comments/comments.js.flow +145 -0
  23. package/dist/transform/comments/prettier/README.md +6 -0
  24. package/dist/transform/comments/prettier/common/util.js +365 -0
  25. package/dist/transform/comments/prettier/common/util.js.flow +349 -0
  26. package/dist/transform/comments/prettier/language-js/comments.js +777 -0
  27. package/dist/transform/comments/prettier/language-js/comments.js.flow +950 -0
  28. package/dist/transform/comments/prettier/language-js/loc.js +41 -0
  29. package/dist/transform/comments/prettier/language-js/loc.js.flow +41 -0
  30. package/dist/transform/comments/prettier/language-js/printer-estree.js +31 -0
  31. package/dist/transform/comments/prettier/language-js/printer-estree.js.flow +37 -0
  32. package/dist/transform/comments/prettier/language-js/utils.js +131 -0
  33. package/dist/transform/comments/prettier/language-js/utils.js.flow +135 -0
  34. package/dist/transform/comments/prettier/main/comments.js +513 -0
  35. package/dist/transform/comments/prettier/main/comments.js.flow +436 -0
  36. package/dist/transform/comments/prettier/utils/get-last.js +15 -0
  37. package/dist/transform/comments/prettier/utils/get-last.js.flow +14 -0
  38. package/dist/transform/getTransformedAST.js +159 -0
  39. package/dist/transform/getTransformedAST.js.flow +128 -0
  40. package/dist/transform/mutations/AddLeadingComments.js +47 -0
  41. package/dist/transform/mutations/AddLeadingComments.js.flow +49 -0
  42. package/dist/transform/mutations/AddTrailingComments.js +47 -0
  43. package/dist/transform/mutations/AddTrailingComments.js.flow +49 -0
  44. package/dist/transform/mutations/CloneCommentsTo.js +46 -0
  45. package/dist/transform/mutations/CloneCommentsTo.js.flow +51 -0
  46. package/dist/transform/mutations/InsertStatement.js +92 -0
  47. package/dist/transform/mutations/InsertStatement.js.flow +113 -0
  48. package/dist/transform/mutations/RemoveComment.js +96 -0
  49. package/dist/transform/mutations/RemoveComment.js.flow +80 -0
  50. package/dist/transform/mutations/RemoveStatement.js +61 -0
  51. package/dist/transform/mutations/RemoveStatement.js.flow +68 -0
  52. package/dist/transform/mutations/ReplaceNode.js +96 -0
  53. package/dist/transform/mutations/ReplaceNode.js.flow +113 -0
  54. package/dist/transform/mutations/ReplaceStatementWithMany.js +81 -0
  55. package/dist/transform/mutations/ReplaceStatementWithMany.js.flow +102 -0
  56. package/dist/transform/mutations/utils/arrayUtils.js +41 -0
  57. package/dist/transform/mutations/utils/arrayUtils.js.flow +35 -0
  58. package/dist/transform/mutations/utils/getStatementParent.js +147 -0
  59. package/dist/transform/mutations/utils/getStatementParent.js.flow +143 -0
  60. package/dist/transform/mutations/utils/isValidModuleDeclarationParent.js +53 -0
  61. package/dist/transform/mutations/utils/isValidModuleDeclarationParent.js.flow +50 -0
  62. package/dist/transform/transform.js +69 -0
  63. package/dist/transform/transform.js.flow +60 -0
  64. package/dist/traverse/NodeEventGenerator.js +427 -0
  65. package/dist/traverse/NodeEventGenerator.js.flow +406 -0
  66. package/dist/traverse/SafeEmitter.js +70 -0
  67. package/dist/traverse/SafeEmitter.js.flow +46 -0
  68. package/dist/traverse/SimpleTraverser.js +149 -0
  69. package/dist/traverse/SimpleTraverser.js.flow +109 -0
  70. package/dist/traverse/esquery.js +37 -0
  71. package/dist/traverse/esquery.js.flow +173 -0
  72. package/dist/traverse/traverse.js +139 -0
  73. package/dist/traverse/traverse.js.flow +149 -0
  74. package/package.json +22 -0
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its 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
+ import type {
12
+ Comment,
13
+ ESNode,
14
+ Expression,
15
+ ModuleDeclaration,
16
+ Statement,
17
+ TypeAnnotationType,
18
+ } from 'hermes-estree';
19
+ import type {DetachedNode} from '../detachedNode';
20
+ import type {TransformCloneSignatures} from '../generated/TransformCloneSignatures';
21
+ import type {TransformReplaceSignatures} from '../generated/TransformReplaceSignatures';
22
+ import type {AddLeadingCommentsMutation} from './mutations/AddLeadingComments';
23
+ import type {AddTrailingCommentsMutation} from './mutations/AddTrailingComments';
24
+ import type {CloneCommentsToMutation} from './mutations/CloneCommentsTo';
25
+ import type {InsertStatementMutation} from './mutations/InsertStatement';
26
+ import type {RemoveCommentMutation} from './mutations/RemoveComment';
27
+ import type {RemoveStatementMutation} from './mutations/RemoveStatement';
28
+ import type {ReplaceNodeMutation} from './mutations/ReplaceNode';
29
+ import type {ReplaceStatementWithManyMutation} from './mutations/ReplaceStatementWithMany';
30
+
31
+ import {deepCloneNode, shallowCloneNode} from '../detachedNode';
32
+ import {
33
+ getCommentsForNode,
34
+ isLeadingComment,
35
+ isTrailingComment,
36
+ } from './comments/comments';
37
+ import {createAddLeadingCommentsMutation} from './mutations/AddLeadingComments';
38
+ import {createAddTrailingCommentsMutation} from './mutations/AddTrailingComments';
39
+ import {createCloneCommentsToMutation} from './mutations/CloneCommentsTo';
40
+ import {createInsertStatementMutation} from './mutations/InsertStatement';
41
+ import {createRemoveCommentMutation} from './mutations/RemoveComment';
42
+ import {createRemoveStatementMutation} from './mutations/RemoveStatement';
43
+ import {createReplaceNodeMutation} from './mutations/ReplaceNode';
44
+ import {createReplaceStatementWithManyMutation} from './mutations/ReplaceStatementWithMany';
45
+
46
+ type Mutation = $ReadOnly<
47
+ | AddLeadingCommentsMutation
48
+ | AddTrailingCommentsMutation
49
+ | CloneCommentsToMutation
50
+ | InsertStatementMutation
51
+ | RemoveCommentMutation
52
+ | RemoveStatementMutation
53
+ | ReplaceNodeMutation
54
+ | ReplaceStatementWithManyMutation,
55
+ >;
56
+
57
+ type SingleOrArray<+T> = T | $ReadOnlyArray<T>;
58
+
59
+ type ReplaceNodeOptions = $ReadOnly<{
60
+ /**
61
+ * Moves the comments from the target node to the nodetoReplaceWith.
62
+ * Note that this does not *clone* comments, it moves them and clears out
63
+ * the target node's comments afterward.
64
+ */
65
+ keepComments?: boolean,
66
+ }>;
67
+
68
+ export type TransformContext = $ReadOnly<{
69
+ mutations: $ReadOnlyArray<Mutation>,
70
+ astWasMutated: boolean,
71
+
72
+ /**
73
+ * Shallowly clones the given node and applies the given overrides.
74
+ * !!! Be careful about using this !!!
75
+ * This does not clone children nodes. This means that if you keep
76
+ * the original node in the AST then you will have two trees in the
77
+ * AST which refer to the exact same node objects; which will lead
78
+ * to ***undefined*** behaviour.
79
+ *
80
+ * You should only use this if:
81
+ * 1) the node is a simple leaf (eg literals, identifiers, etc)
82
+ * 2) you are 100% removing the original node from the AST
83
+ *
84
+ * If you want to literally duplicate a node to place somewhere else
85
+ * in the AST, then use `deepCloneNode` instead.
86
+ */
87
+ shallowCloneNode: TransformCloneSignatures & {
88
+ // generic passthrough cases with no options
89
+ <T: ESNode>(node: T): DetachedNode<T>,
90
+ <T: ESNode>(node: ?T): DetachedNode<T> | null,
91
+ },
92
+
93
+ /**
94
+ * {@see shallowCloneNode}
95
+ */
96
+ shallowCloneArray: {
97
+ <T: ESNode>(node: $ReadOnlyArray<T>): $ReadOnlyArray<DetachedNode<T>>,
98
+ <T: ESNode>(node: ?$ReadOnlyArray<T>): ?$ReadOnlyArray<DetachedNode<T>>,
99
+ },
100
+
101
+ /**
102
+ * Deeply clones the node and all its children, then applies the
103
+ * given overrides.
104
+ * !!! Be careful about using this !!!
105
+ * Because this is a deep clone, using it high up in the AST can
106
+ * result in a lot of work being done.
107
+ */
108
+ deepCloneNode: TransformCloneSignatures & {
109
+ // generic passthrough cases with no options
110
+ <T: ESNode>(node: T): DetachedNode<T>,
111
+ <T: ESNode>(node: ?T): DetachedNode<T> | null,
112
+ },
113
+
114
+ /**
115
+ * Insert `nodeToInsert` after the `target` statement.
116
+ * The inserted nodes will be kept in the order given.
117
+ */
118
+ insertAfterStatement: (
119
+ target: ModuleDeclaration | Statement,
120
+ nodeToInsert: SingleOrArray<DetachedNode<ModuleDeclaration | Statement>>,
121
+ ) => void,
122
+
123
+ /**
124
+ * Insert `nodeToInsert` before the `target` statement.
125
+ * The inserted nodes will be kept in the order given.
126
+ */
127
+ insertBeforeStatement: (
128
+ target: ModuleDeclaration | Statement,
129
+ nodeToInsert: SingleOrArray<DetachedNode<ModuleDeclaration | Statement>>,
130
+ ) => void,
131
+
132
+ /**
133
+ * Replace the `target` node with the `nodeToReplaceWith` node.
134
+ * This simply does an in-place replacement in the AST.
135
+ */
136
+ replaceNode: {
137
+ // expressions must be replaced with other expressions
138
+ (
139
+ target: Expression,
140
+ nodeToReplaceWith: DetachedNode<Expression>,
141
+ options?: ReplaceNodeOptions,
142
+ ): void,
143
+ // module declarations must be replaced with statements or other module declarations
144
+ (
145
+ target: ModuleDeclaration,
146
+ nodeToReplaceWith: DetachedNode<ModuleDeclaration | Statement>,
147
+ options?: ReplaceNodeOptions,
148
+ ): void,
149
+ // Statement must be replaced with statements or module declarations
150
+ (
151
+ target: Statement,
152
+ nodeToReplaceWith: DetachedNode<ModuleDeclaration | Statement>,
153
+ options?: ReplaceNodeOptions,
154
+ ): void,
155
+ // Types must be replaced with types
156
+ (
157
+ target: TypeAnnotationType,
158
+ nodeToReplaceWith: DetachedNode<TypeAnnotationType>,
159
+ options?: ReplaceNodeOptions,
160
+ ): void,
161
+ } & TransformReplaceSignatures, // allow like-for-like replacements as well
162
+
163
+ /**
164
+ * Replaces the `target` node with all of the `nodesToReplaceWith` nodes.
165
+ * The nodes will be kept in the order given.
166
+ */
167
+ replaceStatementWithMany: (
168
+ target: ModuleDeclaration | Statement,
169
+ nodesToReplaceWith: $ReadOnlyArray<
170
+ DetachedNode<ModuleDeclaration | Statement>,
171
+ >,
172
+ options?: {
173
+ /**
174
+ * Moves the comments from the target node to the first node in the array.
175
+ * Note that this does not *clone* comments, it moves them and clears out
176
+ * the target node's comments afterward.
177
+ */
178
+ keepComments?: boolean,
179
+ },
180
+ ) => void,
181
+
182
+ /**
183
+ * Removes a given node from the AST.
184
+ */
185
+ removeStatement: (node: ModuleDeclaration | Statement) => void,
186
+
187
+ //
188
+ // Comment APIs
189
+ //
190
+
191
+ /**
192
+ * Gets all of the comments attached to the given node.
193
+ */
194
+ getComments: (node: ESNode) => Array<Comment>,
195
+
196
+ /**
197
+ * Gets the leading comments attached to the given node.
198
+ */
199
+ getLeadingComments: (node: ESNode) => Array<Comment>,
200
+
201
+ /**
202
+ * Gets the trailing comments attached to the given node.
203
+ */
204
+ getTrailingComments: (node: ESNode) => Array<Comment>,
205
+
206
+ /**
207
+ * Clones all of the comments from the target node to the destination node.
208
+ * As its name suggest - this will clone the comments, duplicating them
209
+ * entirely. It will not remove the comments from the target node afterward.
210
+ */
211
+ cloneCommentsTo: (
212
+ target: ESNode,
213
+ destination: ESNode | DetachedNode<ESNode>,
214
+ ) => void,
215
+
216
+ /**
217
+ * Add leading comments to the specified node.
218
+ */
219
+ addLeadingComments: (
220
+ node: ESNode | DetachedNode<ESNode>,
221
+ comments: SingleOrArray<Comment>,
222
+ ) => void,
223
+
224
+ /**
225
+ * Add trailing comments to the specified node.
226
+ */
227
+ addTrailingComments: (
228
+ node: ESNode | DetachedNode<ESNode>,
229
+ comments: SingleOrArray<Comment>,
230
+ ) => void,
231
+
232
+ /**
233
+ * Removes the specified comments
234
+ */
235
+ removeComments: (comments: SingleOrArray<Comment>) => void,
236
+ }>;
237
+
238
+ export function getTransformContext(): TransformContext {
239
+ /**
240
+ * The mutations in order of collection.
241
+ */
242
+ const mutations: Array<Mutation> = [];
243
+ function pushMutation(mutation: ?Mutation): void {
244
+ if (mutation != null) {
245
+ mutations.push(mutation);
246
+ }
247
+ }
248
+
249
+ return {
250
+ mutations,
251
+
252
+ // $FlowExpectedError[unsafe-getters-setters]
253
+ get astWasMutated(): boolean {
254
+ return mutations.length > 0;
255
+ },
256
+
257
+ // $FlowExpectedError[incompatible-exact]
258
+ shallowCloneNode: ((
259
+ node: ?ESNode,
260
+ newProps?: $ReadOnly<{...}>,
261
+ ): // $FlowExpectedError[incompatible-cast]
262
+ // $FlowExpectedError[prop-missing]
263
+ ?DetachedNode<ESNode> => {
264
+ if (node == null) {
265
+ return null;
266
+ }
267
+
268
+ return shallowCloneNode(node, newProps);
269
+ }: TransformContext['shallowCloneNode']),
270
+
271
+ shallowCloneArray: (<T: ESNode>(
272
+ nodes: ?$ReadOnlyArray<T>,
273
+ ): // $FlowExpectedError[incompatible-cast]
274
+ ?$ReadOnlyArray<DetachedNode<ESNode>> => {
275
+ if (nodes == null) {
276
+ return null;
277
+ }
278
+
279
+ return nodes.map(node => shallowCloneNode<T>(node));
280
+ }: TransformContext['shallowCloneArray']),
281
+
282
+ // $FlowExpectedError[incompatible-exact]
283
+ deepCloneNode: ((
284
+ node: ?ESNode,
285
+ newProps?: $ReadOnly<{...}>,
286
+ ): // $FlowExpectedError[incompatible-cast]
287
+ // $FlowExpectedError[prop-missing]
288
+ ?DetachedNode<ESNode> => {
289
+ if (node == null) {
290
+ return null;
291
+ }
292
+
293
+ return deepCloneNode(node, newProps);
294
+ }: TransformContext['deepCloneNode']),
295
+
296
+ insertAfterStatement: ((target, nodesToInsert): void => {
297
+ pushMutation(
298
+ createInsertStatementMutation('after', target, toArray(nodesToInsert)),
299
+ );
300
+ }: TransformContext['insertBeforeStatement']),
301
+
302
+ insertBeforeStatement: ((target, nodesToInsert): void => {
303
+ pushMutation(
304
+ createInsertStatementMutation('before', target, toArray(nodesToInsert)),
305
+ );
306
+ }: TransformContext['insertBeforeStatement']),
307
+
308
+ replaceNode: ((
309
+ target: ESNode,
310
+ nodeToReplaceWith: DetachedNode<ESNode>,
311
+ options?: $ReadOnly<{keepComments?: boolean}>,
312
+ ): void => {
313
+ pushMutation(
314
+ createReplaceNodeMutation(target, nodeToReplaceWith, options),
315
+ );
316
+ }: TransformContext['replaceNode']),
317
+
318
+ replaceStatementWithMany: ((
319
+ target,
320
+ nodesToReplaceWith,
321
+ options?: $ReadOnly<{keepComments?: boolean}>,
322
+ ): void => {
323
+ pushMutation(
324
+ createReplaceStatementWithManyMutation(
325
+ target,
326
+ nodesToReplaceWith,
327
+ options,
328
+ ),
329
+ );
330
+ }: TransformContext['replaceStatementWithMany']),
331
+
332
+ removeStatement: ((node): void => {
333
+ pushMutation(createRemoveStatementMutation(node));
334
+ }: TransformContext['removeStatement']),
335
+
336
+ //
337
+ // Comment APIs
338
+ //
339
+
340
+ getComments: ((node): Array<Comment> => {
341
+ return [...getCommentsForNode(node)];
342
+ }: TransformContext['getComments']),
343
+
344
+ getLeadingComments: ((node): Array<Comment> => {
345
+ return getCommentsForNode(node).filter(isLeadingComment);
346
+ }: TransformContext['getLeadingComments']),
347
+
348
+ getTrailingComments: ((node): Array<Comment> => {
349
+ return getCommentsForNode(node).filter(isTrailingComment);
350
+ }: TransformContext['getTrailingComments']),
351
+
352
+ cloneCommentsTo: ((target, destination): void => {
353
+ pushMutation(createCloneCommentsToMutation(target, destination));
354
+ }: TransformContext['cloneCommentsTo']),
355
+
356
+ addLeadingComments: ((node, comments): void => {
357
+ pushMutation(createAddLeadingCommentsMutation(node, toArray(comments)));
358
+ }: TransformContext['addLeadingComments']),
359
+
360
+ addTrailingComments: ((node, comments): void => {
361
+ pushMutation(createAddTrailingCommentsMutation(node, toArray(comments)));
362
+ }: TransformContext['addTrailingComments']),
363
+
364
+ removeComments: ((comments): void => {
365
+ toArray(comments).forEach(comment => {
366
+ pushMutation(createRemoveCommentMutation(comment));
367
+ });
368
+ }: TransformContext['removeComments']),
369
+ };
370
+ }
371
+
372
+ function toArray<T>(thing: SingleOrArray<T>): $ReadOnlyArray<T> {
373
+ if (Array.isArray(thing)) {
374
+ // $FlowExpectedError[incompatible-return]
375
+ return thing;
376
+ }
377
+ return [thing];
378
+ }
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.addCommentsToNode = addCommentsToNode;
7
+ exports.addLeadingComment = addLeadingComment;
8
+ exports.addTrailingComment = addTrailingComment;
9
+ exports.appendCommentToSource = appendCommentToSource;
10
+ exports.attachComments = attachComments;
11
+ exports.cloneComment = cloneComment;
12
+ exports.cloneCommentWithMarkers = cloneCommentWithMarkers;
13
+ exports.getCommentsForNode = getCommentsForNode;
14
+ exports.isLeadingComment = isLeadingComment;
15
+ exports.isTrailingComment = isTrailingComment;
16
+ exports.moveCommentsToNewNode = moveCommentsToNewNode;
17
+ exports.setCommentsOnNode = setCommentsOnNode;
18
+
19
+ var _comments = require("./prettier/main/comments");
20
+
21
+ var _loc = require("./prettier/language-js/loc");
22
+
23
+ var _printerEstree = _interopRequireDefault(require("./prettier/language-js/printer-estree"));
24
+
25
+ var _util = require("./prettier/common/util");
26
+
27
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
28
+
29
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
30
+
31
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
32
+
33
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
34
+
35
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
36
+
37
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
38
+
39
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
40
+
41
+ function attachComments(comments, ast, text) {
42
+ (0, _comments.attach)(comments, ast, text, {
43
+ locStart: _loc.locStart,
44
+ locEnd: _loc.locEnd,
45
+ printer: _printerEstree["default"]
46
+ });
47
+ }
48
+
49
+ function moveCommentsToNewNode(oldNode, newNode) {
50
+ setCommentsOnNode(newNode, getCommentsForNode(oldNode));
51
+ setCommentsOnNode(oldNode, []);
52
+ }
53
+
54
+ function setCommentsOnNode(node, comments) {
55
+ // $FlowExpectedError - this property is secretly added by prettier.
56
+ node.comments = comments;
57
+ }
58
+
59
+ function addCommentsToNode(node, comments) {
60
+ var _node$comments, _ref;
61
+
62
+ // $FlowExpectedError - this property is secretly added by prettier.
63
+ node.comments = (_node$comments = node.comments) !== null && _node$comments !== void 0 ? _node$comments : []; // $FlowExpectedError
64
+
65
+ (_ref = node.comments).push.apply(_ref, _toConsumableArray(comments));
66
+ }
67
+
68
+ function getCommentsForNode(node) {
69
+ var _node$comments2;
70
+
71
+ // $FlowExpectedError - this property is secretly added by prettier.
72
+ return (_node$comments2 = node.comments) !== null && _node$comments2 !== void 0 ? _node$comments2 : [];
73
+ }
74
+
75
+ function isLeadingComment(comment) {
76
+ // $FlowExpectedError - this property is secretly added by prettier.
77
+ return comment.leading === true;
78
+ }
79
+
80
+ function isTrailingComment(comment) {
81
+ // $FlowExpectedError - this property is secretly added by prettier.
82
+ return comment.trailing === true;
83
+ }
84
+
85
+ function addLeadingComment(node, comment) {
86
+ (0, _util.addLeadingComment)(node, comment);
87
+ }
88
+
89
+ function addTrailingComment(node, comment) {
90
+ (0, _util.addTrailingComment)(node, comment);
91
+ }
92
+
93
+ function cloneComment(comment) {
94
+ // $FlowExpectedError[incompatible-return]
95
+ return {
96
+ type: comment.type,
97
+ value: comment.value,
98
+ loc: comment.loc,
99
+ range: comment.range
100
+ };
101
+ }
102
+
103
+ function cloneCommentWithMarkers(comment) {
104
+ // $FlowExpectedError[incompatible-return]
105
+ return {
106
+ type: comment.type,
107
+ value: comment.value,
108
+ loc: comment.loc,
109
+ range: comment.range,
110
+ leading: isLeadingComment(comment),
111
+ trailing: isTrailingComment(comment)
112
+ };
113
+ }
114
+
115
+ function appendCommentToSource(code, comment) {
116
+ // prettier slices comments directly from the source code when printing
117
+ // https://github.com/prettier/prettier/blob/5f0ee39fa03532c85bd1c35291450fe7ac3667b3/src/language-js/print/comment.js#L15-L20
118
+ // this means that we need to have any appended comments directly in the
119
+ // source code or else prettier will slice nothing and bork up the transform
120
+ var commentText = comment.value;
121
+
122
+ switch (comment.type) {
123
+ case 'Block':
124
+ commentText = "/*".concat(commentText, "*/");
125
+ break;
126
+
127
+ case 'Line':
128
+ commentText = "//".concat(commentText);
129
+ break;
130
+ }
131
+
132
+ var newCode = code;
133
+ newCode += '\n';
134
+ var start = newCode.length;
135
+ newCode += commentText;
136
+ var end = newCode.length; // $FlowExpectedError[cannot-write]
137
+
138
+ comment.range = [start, end];
139
+ return newCode;
140
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its 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
+ import type {Comment, ESNode, Program} from 'hermes-estree';
12
+ import type {DetachedNode} from '../../detachedNode';
13
+
14
+ // $FlowExpectedError[untyped-import]
15
+ import {attach as untypedAttach} from './prettier/main/comments';
16
+ // $FlowExpectedError[untyped-import]
17
+ import {locEnd, locStart} from './prettier/language-js/loc';
18
+ // $FlowExpectedError[untyped-import]
19
+ import printer from './prettier/language-js/printer-estree';
20
+ import {
21
+ // $FlowExpectedError[untyped-import]
22
+ addLeadingComment as untypedAddLeadingComment,
23
+ // $FlowExpectedError[untyped-import]
24
+ addTrailingComment as untypedAddTrailingComment,
25
+ } from './prettier/common/util';
26
+
27
+ export type Options = $ReadOnly<{}>;
28
+
29
+ export function attachComments(
30
+ comments: $ReadOnlyArray<Comment>,
31
+ ast: Program,
32
+ text: string,
33
+ ): void {
34
+ untypedAttach(comments, ast, text, {
35
+ locStart,
36
+ locEnd,
37
+ printer,
38
+ });
39
+ }
40
+
41
+ export function moveCommentsToNewNode(
42
+ oldNode: ESNode,
43
+ newNode: DetachedNode<ESNode>,
44
+ ): void {
45
+ setCommentsOnNode(newNode, getCommentsForNode(oldNode));
46
+ setCommentsOnNode(oldNode, []);
47
+ }
48
+
49
+ export function setCommentsOnNode(
50
+ node: ESNode | DetachedNode<ESNode>,
51
+ comments: $ReadOnlyArray<Comment>,
52
+ ): void {
53
+ // $FlowExpectedError - this property is secretly added by prettier.
54
+ node.comments = comments;
55
+ }
56
+
57
+ export function addCommentsToNode(
58
+ node: ESNode | DetachedNode<ESNode>,
59
+ comments: $ReadOnlyArray<Comment>,
60
+ ): void {
61
+ // $FlowExpectedError - this property is secretly added by prettier.
62
+ node.comments = node.comments ?? [];
63
+ // $FlowExpectedError
64
+ (node.comments: Array<Comment>).push(...comments);
65
+ }
66
+
67
+ export function getCommentsForNode(
68
+ node: ESNode | DetachedNode<ESNode>,
69
+ ): $ReadOnlyArray<Comment> {
70
+ // $FlowExpectedError - this property is secretly added by prettier.
71
+ return node.comments ?? [];
72
+ }
73
+
74
+ export function isLeadingComment(comment: Comment): boolean {
75
+ // $FlowExpectedError - this property is secretly added by prettier.
76
+ return comment.leading === true;
77
+ }
78
+ export function isTrailingComment(comment: Comment): boolean {
79
+ // $FlowExpectedError - this property is secretly added by prettier.
80
+ return comment.trailing === true;
81
+ }
82
+
83
+ export function addLeadingComment(
84
+ node: ESNode | DetachedNode<ESNode>,
85
+ comment: Comment,
86
+ ): void {
87
+ untypedAddLeadingComment(node, comment);
88
+ }
89
+
90
+ export function addTrailingComment(
91
+ node: ESNode | DetachedNode<ESNode>,
92
+ comment: Comment,
93
+ ): void {
94
+ untypedAddTrailingComment(node, comment);
95
+ }
96
+
97
+ export function cloneComment<T: Comment>(comment: T): T {
98
+ // $FlowExpectedError[incompatible-return]
99
+ return {
100
+ type: comment.type,
101
+ value: comment.value,
102
+ loc: comment.loc,
103
+ range: comment.range,
104
+ };
105
+ }
106
+
107
+ export function cloneCommentWithMarkers<T: Comment>(comment: T): T {
108
+ // $FlowExpectedError[incompatible-return]
109
+ return {
110
+ type: comment.type,
111
+ value: comment.value,
112
+ loc: comment.loc,
113
+ range: comment.range,
114
+ leading: isLeadingComment(comment),
115
+ trailing: isTrailingComment(comment),
116
+ };
117
+ }
118
+
119
+ export function appendCommentToSource(code: string, comment: Comment): string {
120
+ // prettier slices comments directly from the source code when printing
121
+ // https://github.com/prettier/prettier/blob/5f0ee39fa03532c85bd1c35291450fe7ac3667b3/src/language-js/print/comment.js#L15-L20
122
+ // this means that we need to have any appended comments directly in the
123
+ // source code or else prettier will slice nothing and bork up the transform
124
+
125
+ let commentText = comment.value;
126
+ switch (comment.type) {
127
+ case 'Block':
128
+ commentText = `/*${commentText}*/`;
129
+ break;
130
+ case 'Line':
131
+ commentText = `//${commentText}`;
132
+ break;
133
+ }
134
+
135
+ let newCode = code;
136
+ newCode += '\n';
137
+ const start = newCode.length;
138
+ newCode += commentText;
139
+ const end = newCode.length;
140
+
141
+ // $FlowExpectedError[cannot-write]
142
+ comment.range = [start, end];
143
+
144
+ return newCode;
145
+ }
@@ -0,0 +1,6 @@
1
+ # Comment Attachment
2
+
3
+ This is a fork of prettier's comment attachment algorithm. The original license for `prettier` can be found in the `PRETTIER_LICENCE` file in the root of this package.
4
+ Specifically this fork contains the `attach` method from [`src/main/comments.js`](https://github.com/prettier/prettier/blob/894f841fbd948875fc2a47bd63f3db3dcadc5f43/src/main/comments.js#L357) and the minimum set of code required for it.
5
+
6
+ The folder structure has been maintained to make merging future updates easier.