Debian Codegraph @

packages/babel-generator/src/index.ts

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 import SourceMap from "./source-map";
2 import Printer from "./printer";
3 import type * as t from "@babel/types";
4 import type { Opts as jsescOptions } from "jsesc";
5 import type { Format } from "./printer";
6 import type {
7 RecordAndTuplePluginOptions,
8 PipelineOperatorPluginOptions,
9 } from "@babel/parser";
10 import type { DecodedSourceMap, Mapping } from "@jridgewell/gen-mapping";
11
12 /**
13 * Babel's code generator, turns an ast into code, maintaining sourcemaps,
14 * user preferences, and valid output.
15 */
16
17 class Generator extends Printer {
18 constructor(
19 ast: t.Node,
20 opts: GeneratorOptions = {},
21 code: string | { [filename: string]: string },
22 ) {
23 const format = normalizeOptions(code, opts);
24 const map = opts.sourceMaps ? new SourceMap(opts, code) : null;
25 super(format, map);
26
27 this.ast = ast;
28 }
29
30 ast: t.Node;
31
32 /**
33 * Generate code and sourcemap from ast.
34 *
35 * Appends comments that weren't attached to any node to the end of the generated output.
36 */
37
38 generate() {
39 return super.generate(this.ast);
40 }
41 }
42
43 /**
44 * Normalize generator options, setting defaults.
45 *
46 * - Detects code indentation.
47 * - If `opts.compact = "auto"` and the code is over 500KB, `compact` will be set to `true`.
48 */
49
50 function normalizeOptions(
51 code: string | { [filename: string]: string },
52 opts: GeneratorOptions,
53 ): Format {
54 const format: Format = {
55 auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
56 auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
57 shouldPrintComment: opts.shouldPrintComment,
58 retainLines: opts.retainLines,
59 retainFunctionParens: opts.retainFunctionParens,
60 comments: opts.comments == null || opts.comments,
61 compact: opts.compact,
62 minified: opts.minified,
63 concise: opts.concise,
64 indent: {
65 adjustMultilineComment: true,
66 style: " ",
67 },
68 jsescOption: {
69 quotes: "double",
70 wrap: true,
71 minimal: process.env.BABEL_8_BREAKING ? true : false,
72 ...opts.jsescOption,
73 },
74 recordAndTupleSyntaxType: opts.recordAndTupleSyntaxType,
75 topicToken: opts.topicToken,
76 };
77
78 if (!process.env.BABEL_8_BREAKING) {
79 format.decoratorsBeforeExport = !!opts.decoratorsBeforeExport;
80 format.jsonCompatibleStrings = opts.jsonCompatibleStrings;
81 }
82
83 if (format.minified) {
84 format.compact = true;
85
86 format.shouldPrintComment =
87 format.shouldPrintComment || (() => format.comments);
88 } else {
89 format.shouldPrintComment =
90 format.shouldPrintComment ||
91 (value =>
92 format.comments ||
93 value.includes("@license") ||
94 value.includes("@preserve"));
95 }
96
97 if (format.compact === "auto") {
•98 format.compact = typeof code === "string" && code.length > 500_000; // 500KB
99
100 if (format.compact) {
101 console.error(
102 "[BABEL] Note: The code generator has deoptimised the styling of " +
103 `${opts.filename} as it exceeds the max of ${"500KB"}.`,
104 );
105 }
106 }
107
108 if (format.compact) {
109 format.indent.adjustMultilineComment = false;
110 }
111
112 const { auxiliaryCommentBefore, auxiliaryCommentAfter, shouldPrintComment } =
113 format;
114
115 if (auxiliaryCommentBefore && !shouldPrintComment(auxiliaryCommentBefore)) {
116 format.auxiliaryCommentBefore = undefined;
117 }
118 if (auxiliaryCommentAfter && !shouldPrintComment(auxiliaryCommentAfter)) {
119 format.auxiliaryCommentAfter = undefined;
120 }
121
122 return format;
123 }
124
125 export interface GeneratorOptions {
126 /**
127 * Optional string to add as a block comment at the start of the output file.
128 */
129 auxiliaryCommentBefore?: string;
130
131 /**
132 * Optional string to add as a block comment at the end of the output file.
133 */
134 auxiliaryCommentAfter?: string;
135
136 /**
137 * Function that takes a comment (as a string) and returns true if the comment should be included in the output.
138 * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment
139 * contains `@preserve` or `@license`.
140 */
141 shouldPrintComment?(comment: string): boolean;
142
143 /**
144 * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces).
145 * Defaults to `false`.
146 */
147 retainLines?: boolean;
148
149 /**
150 * Retain parens around function expressions (could be used to change engine parsing behavior)
151 * Defaults to `false`.
152 */
153 retainFunctionParens?: boolean;
154
155 /**
156 * Should comments be included in output? Defaults to `true`.
157 */
158 comments?: boolean;
159
160 /**
161 * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`.
162 */
163 compact?: boolean | "auto";
164
165 /**
166 * Should the output be minified. Defaults to `false`.
167 */
168 minified?: boolean;
169
170 /**
171 * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`.
172 */
173 concise?: boolean;
174
175 /**
176 * Used in warning messages
177 */
178 filename?: string;
179
180 /**
181 * Enable generating source maps. Defaults to `false`.
182 */
183 sourceMaps?: boolean;
184
185 /**
186 * A root for all relative URLs in the source map.
187 */
188 sourceRoot?: string;
189
190 /**
191 * The filename for the source code (i.e. the code in the `code` argument).
192 * This will only be used if `code` is a string.
193 */
194 sourceFileName?: string;
195
196 /**
197 * Set to true to run jsesc with "json": true to print "\u00A9" vs. "©";
198 * @deprecated use `jsescOptions: { json: true }` instead
199 */
200 jsonCompatibleStrings?: boolean;
201
202 /**
203 * Set to true to enable support for experimental decorators syntax before module exports.
204 * Defaults to `false`.
205 * @deprecated Removed in Babel 8
206 */
207 decoratorsBeforeExport?: boolean;
208
209 /**
210 * Options for outputting jsesc representation.
211 */
212 jsescOption?: jsescOptions;
213
214 /**
215 * For use with the recordAndTuple token.
216 */
217 recordAndTupleSyntaxType?: RecordAndTuplePluginOptions["syntaxType"];
218 /**
219 * For use with the Hack-style pipe operator.
220 * Changes what token is used for pipe bodies’ topic references.
221 */
222 topicToken?: PipelineOperatorPluginOptions["topicToken"];
223 }
224
225 export interface GeneratorResult {
226 code: string;
227 map: {
228 version: number;
229 sources: readonly string[];
230 names: readonly string[];
231 sourceRoot?: string;
232 sourcesContent?: readonly string[];
233 mappings: string;
234 file?: string;
235 } | null;
236 decodedMap: DecodedSourceMap | undefined;
237 rawMappings: Mapping[] | undefined;
238 }
239
240 /**
241 * We originally exported the Generator class above, but to make it extra clear that it is a private API,
242 * we have moved that to an internal class instance and simplified the interface to the two public methods
243 * that we wish to support.
244 */
245
246 export class CodeGenerator {
247 private _generator: Generator;
248 constructor(ast: t.Node, opts?: GeneratorOptions, code?: string) {
249 this._generator = new Generator(ast, opts, code);
250 }
251 generate(): GeneratorResult {
252 return this._generator.generate();
253 }
254 }
255
256 /**
257 * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output.
258 * @param ast - the abstract syntax tree from which to generate output code.
259 * @param opts - used for specifying options for code generation.
260 * @param code - the original source code, used for source maps.
261 * @returns - an object containing the output code and source map.
262 */
263 export default function generate(
264 ast: t.Node,
265 opts?: GeneratorOptions,
266 code?: string | { [filename: string]: string },
267 ) {
268 const gen = new Generator(ast, opts, code);
269 return gen.generate();
270 }