UNPKG

799 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.55.1
4 Thu, 29 Jul 2021 15:46:34 GMT - commit 97759be7eacc11c4f7e4fdb9fada077279b363f3
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13var path = require('path');
14var crypto = require('crypto');
15var fs = require('fs');
16var require$$0 = require('events');
17
18function _interopNamespaceDefaultOnly(e) {
19 return {__proto__: null, 'default': e};
20}
21
22var version$1 = "2.55.1";
23
24function ensureArray(items) {
25 if (Array.isArray(items)) {
26 return items.filter(Boolean);
27 }
28 if (items) {
29 return [items];
30 }
31 return [];
32}
33
34function getLocator$1(source, options) {
35 if (options === void 0) { options = {}; }
36 var offsetLine = options.offsetLine || 0;
37 var offsetColumn = options.offsetColumn || 0;
38 var originalLines = source.split('\n');
39 var start = 0;
40 var lineRanges = originalLines.map(function (line, i) {
41 var end = start + line.length + 1;
42 var range = { start: start, end: end, line: i };
43 start = end;
44 return range;
45 });
46 var i = 0;
47 function rangeContains(range, index) {
48 return range.start <= index && index < range.end;
49 }
50 function getLocation(range, index) {
51 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
52 }
53 function locate(search, startIndex) {
54 if (typeof search === 'string') {
55 search = source.indexOf(search, startIndex || 0);
56 }
57 var range = lineRanges[i];
58 var d = search >= range.end ? 1 : -1;
59 while (range) {
60 if (rangeContains(range, search))
61 return getLocation(range, search);
62 i += d;
63 range = lineRanges[i];
64 }
65 }
66 return locate;
67}
68function locate(source, search, options) {
69 if (typeof options === 'number') {
70 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
71 }
72 return getLocator$1(source, options)(search, options && options.startIndex);
73}
74
75function spaces(i) {
76 let result = '';
77 while (i--)
78 result += ' ';
79 return result;
80}
81function tabsToSpaces(str) {
82 return str.replace(/^\t+/, match => match.split('\t').join(' '));
83}
84function getCodeFrame(source, line, column) {
85 let lines = source.split('\n');
86 const frameStart = Math.max(0, line - 3);
87 let frameEnd = Math.min(line + 2, lines.length);
88 lines = lines.slice(frameStart, frameEnd);
89 while (!/\S/.test(lines[lines.length - 1])) {
90 lines.pop();
91 frameEnd -= 1;
92 }
93 const digits = String(frameEnd).length;
94 return lines
95 .map((str, i) => {
96 const isErrorLine = frameStart + i + 1 === line;
97 let lineNum = String(i + frameStart + 1);
98 while (lineNum.length < digits)
99 lineNum = ` ${lineNum}`;
100 if (isErrorLine) {
101 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
102 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
103 }
104 return `${lineNum}: ${tabsToSpaces(str)}`;
105 })
106 .join('\n');
107}
108
109function printQuotedStringList(list, verbs) {
110 const isSingleItem = list.length <= 1;
111 const quotedList = list.map(item => `"${item}"`);
112 let output = isSingleItem
113 ? quotedList[0]
114 : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
115 if (verbs) {
116 output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
117 }
118 return output;
119}
120
121const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
122const relativePath = /^\.?\.\//;
123function isAbsolute(path) {
124 return absolutePath.test(path);
125}
126function isRelative(path) {
127 return relativePath.test(path);
128}
129function normalize(path) {
130 if (path.indexOf('\\') == -1)
131 return path;
132 return path.replace(/\\/g, '/');
133}
134
135function getAliasName(id) {
136 const base = path.basename(id);
137 return base.substr(0, base.length - path.extname(id).length);
138}
139function relativeId(id) {
140 if (!isAbsolute(id))
141 return id;
142 return path.relative(path.resolve(), id);
143}
144function isPathFragment(name) {
145 // starting with "/", "./", "../", "C:/"
146 return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
147}
148
149function error(base) {
150 if (!(base instanceof Error))
151 base = Object.assign(new Error(base.message), base);
152 throw base;
153}
154function augmentCodeLocation(props, pos, source, id) {
155 if (typeof pos === 'object') {
156 const { line, column } = pos;
157 props.loc = { column, file: id, line };
158 }
159 else {
160 props.pos = pos;
161 const { line, column } = locate(source, pos, { offsetLine: 1 });
162 props.loc = { column, file: id, line };
163 }
164 if (props.frame === undefined) {
165 const { line, column } = props.loc;
166 props.frame = getCodeFrame(source, line, column);
167 }
168}
169var Errors;
170(function (Errors) {
171 Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
172 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
173 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
174 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
175 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
176 Errors["BAD_LOADER"] = "BAD_LOADER";
177 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
178 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
179 Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
180 Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
181 Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
182 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
183 Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
184 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
185 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
186 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
187 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
188 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
189 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
190 Errors["INVALID_OPTION"] = "INVALID_OPTION";
191 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
192 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
193 Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
194 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
195 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
196 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
197 Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
198 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
199 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
200 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
201 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
202 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
203 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
204 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
205 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
206})(Errors || (Errors = {}));
207function errAssetNotFinalisedForFileName(name) {
208 return {
209 code: Errors.ASSET_NOT_FINALISED,
210 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
211 };
212}
213function errCannotEmitFromOptionsHook() {
214 return {
215 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
216 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
217 };
218}
219function errChunkNotGeneratedForFileName(name) {
220 return {
221 code: Errors.CHUNK_NOT_GENERATED,
222 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
223 };
224}
225function errChunkInvalid({ fileName, code }, exception) {
226 const errorProps = {
227 code: Errors.CHUNK_INVALID,
228 message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
229 };
230 augmentCodeLocation(errorProps, exception.loc, code, fileName);
231 return errorProps;
232}
233function errCircularReexport(exportName, importedModule) {
234 return {
235 code: Errors.CIRCULAR_REEXPORT,
236 id: importedModule,
237 message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
238 };
239}
240function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
241 return {
242 code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
243 exporter,
244 importer,
245 message: `Export "${exportName}" of module ${relativeId(exporter)} was reexported through module ${relativeId(reexporter)} while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in ${relativeId(importer)} to point directly to the exporting module or do not use "preserveModules" to ensure these modules end up in the same chunk.`,
246 reexporter
247 };
248}
249function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
250 return {
251 code: Errors.ASSET_NOT_FOUND,
252 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
253 };
254}
255function errAssetSourceAlreadySet(name) {
256 return {
257 code: Errors.ASSET_SOURCE_ALREADY_SET,
258 message: `Unable to set the source for asset "${name}", source already set.`
259 };
260}
261function errNoAssetSourceSet(assetName) {
262 return {
263 code: Errors.ASSET_SOURCE_MISSING,
264 message: `Plugin error creating asset "${assetName}" - no asset source set.`
265 };
266}
267function errBadLoader(id) {
268 return {
269 code: Errors.BAD_LOADER,
270 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
271 };
272}
273function errDeprecation(deprecation) {
274 return {
275 code: Errors.DEPRECATED_FEATURE,
276 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
277 };
278}
279function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
280 return {
281 code: Errors.FILE_NOT_FOUND,
282 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
283 };
284}
285function errFileNameConflict(fileName) {
286 return {
287 code: Errors.FILE_NAME_CONFLICT,
288 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
289 };
290}
291function errInputHookInOutputPlugin(pluginName, hookName) {
292 return {
293 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
294 message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
295 };
296}
297function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
298 return {
299 code: Errors.INVALID_CHUNK,
300 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
301 };
302}
303function errInvalidExportOptionValue(optionValue) {
304 return {
305 code: Errors.INVALID_EXPORT_OPTION,
306 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
307 url: `https://rollupjs.org/guide/en/#outputexports`
308 };
309}
310function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
311 return {
312 code: 'INVALID_EXPORT_OPTION',
313 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
314 };
315}
316function errInternalIdCannotBeExternal(source, importer) {
317 return {
318 code: Errors.INVALID_EXTERNAL_ID,
319 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
320 };
321}
322function errInvalidOption(option, explanation) {
323 return {
324 code: Errors.INVALID_OPTION,
325 message: `Invalid value for option "${option}" - ${explanation}.`
326 };
327}
328function errInvalidRollupPhaseForAddWatchFile() {
329 return {
330 code: Errors.INVALID_ROLLUP_PHASE,
331 message: `Cannot call addWatchFile after the build has finished.`
332 };
333}
334function errInvalidRollupPhaseForChunkEmission() {
335 return {
336 code: Errors.INVALID_ROLLUP_PHASE,
337 message: `Cannot emit chunks after module loading has finished.`
338 };
339}
340function errMissingExport(exportName, importingModule, importedModule) {
341 return {
342 code: Errors.MISSING_EXPORT,
343 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
344 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
345 };
346}
347function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
348 return {
349 code: Errors.MISSING_IMPLICIT_DEPENDANT,
350 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
351 };
352}
353function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
354 return {
355 code: Errors.MISSING_IMPLICIT_DEPENDANT,
356 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
357 };
358}
359function errImplicitDependantIsNotIncluded(module) {
360 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
361 return {
362 code: Errors.MISSING_IMPLICIT_DEPENDANT,
363 message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
364 };
365}
366function errMixedExport(facadeModuleId, name) {
367 return {
368 code: Errors.MIXED_EXPORTS,
369 id: facadeModuleId,
370 message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}["default"]\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning`,
371 url: `https://rollupjs.org/guide/en/#outputexports`
372 };
373}
374function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
375 return {
376 code: Errors.NAMESPACE_CONFLICT,
377 message: `Conflicting namespaces: "${relativeId(reexportingModule.id)}" re-exports "${name}" from both "${relativeId(reexportingModule.exportsAll[name])}" and "${relativeId(additionalExportAllModule.exportsAll[name])}" (will be ignored)`,
378 name,
379 reexporter: reexportingModule.id,
380 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
381 };
382}
383function errAmbiguousExternalNamespaces(name, reexportingModule, usedExternalModule, externalModules) {
384 return {
385 code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
386 message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(externalModules.map(module => relativeId(module)))}, guessing "${relativeId(usedExternalModule)}".`,
387 name,
388 reexporter: reexportingModule,
389 sources: externalModules
390 };
391}
392function errNoTransformMapOrAstWithoutCode(pluginName) {
393 return {
394 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
395 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
396 'a "code". This will be ignored.'
397 };
398}
399function errPreferNamedExports(facadeModuleId) {
400 const file = relativeId(facadeModuleId);
401 return {
402 code: Errors.PREFER_NAMED_EXPORTS,
403 id: facadeModuleId,
404 message: `Entry module "${file}" is implicitly using "default" export mode, which means for CommonJS output that its default export is assigned to "module.exports". For many tools, such CommonJS output will not be interchangeable with the original ES module. If this is intended, explicitly set "output.exports" to either "auto" or "default", otherwise you might want to consider changing the signature of "${file}" to use named exports only.`,
405 url: `https://rollupjs.org/guide/en/#outputexports`
406 };
407}
408function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
409 return {
410 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
411 id,
412 message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
413 ? `an export named "${syntheticNamedExportsOption}"`
414 : 'a default export'} that does not reexport an unresolved named export of the same module.`
415 };
416}
417function errUnexpectedNamedImport(id, imported, isReexport) {
418 const importType = isReexport ? 'reexport' : 'import';
419 return {
420 code: Errors.UNEXPECTED_NAMED_IMPORT,
421 id,
422 message: `The named export "${imported}" was ${importType}ed from the external module ${relativeId(id)} even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
423 url: 'https://rollupjs.org/guide/en/#outputinterop'
424 };
425}
426function errUnexpectedNamespaceReexport(id) {
427 return {
428 code: Errors.UNEXPECTED_NAMED_IMPORT,
429 id,
430 message: `There was a namespace "*" reexport from the external module ${relativeId(id)} even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
431 url: 'https://rollupjs.org/guide/en/#outputinterop'
432 };
433}
434function errEntryCannotBeExternal(unresolvedId) {
435 return {
436 code: Errors.UNRESOLVED_ENTRY,
437 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
438 };
439}
440function errUnresolvedEntry(unresolvedId) {
441 return {
442 code: Errors.UNRESOLVED_ENTRY,
443 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
444 };
445}
446function errUnresolvedImport(source, importer) {
447 return {
448 code: Errors.UNRESOLVED_IMPORT,
449 message: `Could not resolve '${source}' from ${relativeId(importer)}`
450 };
451}
452function errUnresolvedImportTreatedAsExternal(source, importer) {
453 return {
454 code: Errors.UNRESOLVED_IMPORT,
455 importer: relativeId(importer),
456 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
457 source,
458 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
459 };
460}
461function errExternalSyntheticExports(source, importer) {
462 return {
463 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
464 importer: relativeId(importer),
465 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
466 source
467 };
468}
469function errFailedValidation(message) {
470 return {
471 code: Errors.VALIDATION_ERROR,
472 message
473 };
474}
475function errAlreadyClosed() {
476 return {
477 code: Errors.ALREADY_CLOSED,
478 message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
479 };
480}
481function warnDeprecation(deprecation, activeDeprecation, options) {
482 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
483}
484function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
485 if (activeDeprecation || strictDeprecations) {
486 const warning = errDeprecation(deprecation);
487 if (strictDeprecations) {
488 return error(warning);
489 }
490 warn(warning);
491 }
492}
493
494const defaultOnWarn = warning => console.warn(warning.message || warning);
495function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
496 const validOptionSet = new Set(validOptions);
497 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
498 if (unknownOptions.length > 0) {
499 warn({
500 code: 'UNKNOWN_OPTION',
501 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
502 ...validOptionSet
503 ]
504 .sort()
505 .join(', ')}`
506 });
507 }
508}
509const treeshakePresets = {
510 recommended: {
511 annotations: true,
512 correctVarValueBeforeDeclaration: false,
513 moduleSideEffects: () => true,
514 propertyReadSideEffects: true,
515 tryCatchDeoptimization: true,
516 unknownGlobalSideEffects: false
517 },
518 safest: {
519 annotations: true,
520 correctVarValueBeforeDeclaration: true,
521 moduleSideEffects: () => true,
522 propertyReadSideEffects: true,
523 tryCatchDeoptimization: true,
524 unknownGlobalSideEffects: true
525 },
526 smallest: {
527 annotations: true,
528 correctVarValueBeforeDeclaration: false,
529 moduleSideEffects: () => false,
530 propertyReadSideEffects: false,
531 tryCatchDeoptimization: false,
532 unknownGlobalSideEffects: false
533 }
534};
535
536let fsEvents;
537let fsEventsImportError;
538function loadFsEvents() {
539 return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespaceDefaultOnly(require('fsevents')); })
540 .then(namespace => {
541 fsEvents = namespace.default;
542 })
543 .catch(err => {
544 fsEventsImportError = err;
545 });
546}
547// A call to this function will be injected into the chokidar code
548function getFsEvents() {
549 if (fsEventsImportError)
550 throw fsEventsImportError;
551 return fsEvents;
552}
553
554var fseventsImporter = {
555 __proto__: null,
556 loadFsEvents: loadFsEvents,
557 getFsEvents: getFsEvents
558};
559
560var charToInteger = {};
561var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
562for (var i = 0; i < chars$1.length; i++) {
563 charToInteger[chars$1.charCodeAt(i)] = i;
564}
565function decode(mappings) {
566 var decoded = [];
567 var line = [];
568 var segment = [
569 0,
570 0,
571 0,
572 0,
573 0,
574 ];
575 var j = 0;
576 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
577 var c = mappings.charCodeAt(i);
578 if (c === 44) { // ","
579 segmentify(line, segment, j);
580 j = 0;
581 }
582 else if (c === 59) { // ";"
583 segmentify(line, segment, j);
584 j = 0;
585 decoded.push(line);
586 line = [];
587 segment[0] = 0;
588 }
589 else {
590 var integer = charToInteger[c];
591 if (integer === undefined) {
592 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
593 }
594 var hasContinuationBit = integer & 32;
595 integer &= 31;
596 value += integer << shift;
597 if (hasContinuationBit) {
598 shift += 5;
599 }
600 else {
601 var shouldNegate = value & 1;
602 value >>>= 1;
603 if (shouldNegate) {
604 value = value === 0 ? -0x80000000 : -value;
605 }
606 segment[j] += value;
607 j++;
608 value = shift = 0; // reset
609 }
610 }
611 }
612 segmentify(line, segment, j);
613 decoded.push(line);
614 return decoded;
615}
616function segmentify(line, segment, j) {
617 // This looks ugly, but we're creating specialized arrays with a specific
618 // length. This is much faster than creating a new array (which v8 expands to
619 // a capacity of 17 after pushing the first item), or slicing out a subarray
620 // (which is slow). Length 4 is assumed to be the most frequent, followed by
621 // length 5 (since not everything will have an associated name), followed by
622 // length 1 (it's probably rare for a source substring to not have an
623 // associated segment data).
624 if (j === 4)
625 line.push([segment[0], segment[1], segment[2], segment[3]]);
626 else if (j === 5)
627 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
628 else if (j === 1)
629 line.push([segment[0]]);
630}
631function encode(decoded) {
632 var sourceFileIndex = 0; // second field
633 var sourceCodeLine = 0; // third field
634 var sourceCodeColumn = 0; // fourth field
635 var nameIndex = 0; // fifth field
636 var mappings = '';
637 for (var i = 0; i < decoded.length; i++) {
638 var line = decoded[i];
639 if (i > 0)
640 mappings += ';';
641 if (line.length === 0)
642 continue;
643 var generatedCodeColumn = 0; // first field
644 var lineMappings = [];
645 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
646 var segment = line_1[_i];
647 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
648 generatedCodeColumn = segment[0];
649 if (segment.length > 1) {
650 segmentMappings +=
651 encodeInteger(segment[1] - sourceFileIndex) +
652 encodeInteger(segment[2] - sourceCodeLine) +
653 encodeInteger(segment[3] - sourceCodeColumn);
654 sourceFileIndex = segment[1];
655 sourceCodeLine = segment[2];
656 sourceCodeColumn = segment[3];
657 }
658 if (segment.length === 5) {
659 segmentMappings += encodeInteger(segment[4] - nameIndex);
660 nameIndex = segment[4];
661 }
662 lineMappings.push(segmentMappings);
663 }
664 mappings += lineMappings.join(',');
665 }
666 return mappings;
667}
668function encodeInteger(num) {
669 var result = '';
670 num = num < 0 ? (-num << 1) | 1 : num << 1;
671 do {
672 var clamped = num & 31;
673 num >>>= 5;
674 if (num > 0) {
675 clamped |= 32;
676 }
677 result += chars$1[clamped];
678 } while (num > 0);
679 return result;
680}
681
682var BitSet = function BitSet(arg) {
683 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
684};
685
686BitSet.prototype.add = function add (n) {
687 this.bits[n >> 5] |= 1 << (n & 31);
688};
689
690BitSet.prototype.has = function has (n) {
691 return !!(this.bits[n >> 5] & (1 << (n & 31)));
692};
693
694var Chunk$1 = function Chunk(start, end, content) {
695 this.start = start;
696 this.end = end;
697 this.original = content;
698
699 this.intro = '';
700 this.outro = '';
701
702 this.content = content;
703 this.storeName = false;
704 this.edited = false;
705
706 // we make these non-enumerable, for sanity while debugging
707 Object.defineProperties(this, {
708 previous: { writable: true, value: null },
709 next: { writable: true, value: null }
710 });
711};
712
713Chunk$1.prototype.appendLeft = function appendLeft (content) {
714 this.outro += content;
715};
716
717Chunk$1.prototype.appendRight = function appendRight (content) {
718 this.intro = this.intro + content;
719};
720
721Chunk$1.prototype.clone = function clone () {
722 var chunk = new Chunk$1(this.start, this.end, this.original);
723
724 chunk.intro = this.intro;
725 chunk.outro = this.outro;
726 chunk.content = this.content;
727 chunk.storeName = this.storeName;
728 chunk.edited = this.edited;
729
730 return chunk;
731};
732
733Chunk$1.prototype.contains = function contains (index) {
734 return this.start < index && index < this.end;
735};
736
737Chunk$1.prototype.eachNext = function eachNext (fn) {
738 var chunk = this;
739 while (chunk) {
740 fn(chunk);
741 chunk = chunk.next;
742 }
743};
744
745Chunk$1.prototype.eachPrevious = function eachPrevious (fn) {
746 var chunk = this;
747 while (chunk) {
748 fn(chunk);
749 chunk = chunk.previous;
750 }
751};
752
753Chunk$1.prototype.edit = function edit (content, storeName, contentOnly) {
754 this.content = content;
755 if (!contentOnly) {
756 this.intro = '';
757 this.outro = '';
758 }
759 this.storeName = storeName;
760
761 this.edited = true;
762
763 return this;
764};
765
766Chunk$1.prototype.prependLeft = function prependLeft (content) {
767 this.outro = content + this.outro;
768};
769
770Chunk$1.prototype.prependRight = function prependRight (content) {
771 this.intro = content + this.intro;
772};
773
774Chunk$1.prototype.split = function split (index) {
775 var sliceIndex = index - this.start;
776
777 var originalBefore = this.original.slice(0, sliceIndex);
778 var originalAfter = this.original.slice(sliceIndex);
779
780 this.original = originalBefore;
781
782 var newChunk = new Chunk$1(index, this.end, originalAfter);
783 newChunk.outro = this.outro;
784 this.outro = '';
785
786 this.end = index;
787
788 if (this.edited) {
789 // TODO is this block necessary?...
790 newChunk.edit('', false);
791 this.content = '';
792 } else {
793 this.content = originalBefore;
794 }
795
796 newChunk.next = this.next;
797 if (newChunk.next) { newChunk.next.previous = newChunk; }
798 newChunk.previous = this;
799 this.next = newChunk;
800
801 return newChunk;
802};
803
804Chunk$1.prototype.toString = function toString () {
805 return this.intro + this.content + this.outro;
806};
807
808Chunk$1.prototype.trimEnd = function trimEnd (rx) {
809 this.outro = this.outro.replace(rx, '');
810 if (this.outro.length) { return true; }
811
812 var trimmed = this.content.replace(rx, '');
813
814 if (trimmed.length) {
815 if (trimmed !== this.content) {
816 this.split(this.start + trimmed.length).edit('', undefined, true);
817 }
818 return true;
819
820 } else {
821 this.edit('', undefined, true);
822
823 this.intro = this.intro.replace(rx, '');
824 if (this.intro.length) { return true; }
825 }
826};
827
828Chunk$1.prototype.trimStart = function trimStart (rx) {
829 this.intro = this.intro.replace(rx, '');
830 if (this.intro.length) { return true; }
831
832 var trimmed = this.content.replace(rx, '');
833
834 if (trimmed.length) {
835 if (trimmed !== this.content) {
836 this.split(this.end - trimmed.length);
837 this.edit('', undefined, true);
838 }
839 return true;
840
841 } else {
842 this.edit('', undefined, true);
843
844 this.outro = this.outro.replace(rx, '');
845 if (this.outro.length) { return true; }
846 }
847};
848
849var btoa = function () {
850 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
851};
852if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
853 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
854} else if (typeof Buffer === 'function') {
855 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
856}
857
858var SourceMap = function SourceMap(properties) {
859 this.version = 3;
860 this.file = properties.file;
861 this.sources = properties.sources;
862 this.sourcesContent = properties.sourcesContent;
863 this.names = properties.names;
864 this.mappings = encode(properties.mappings);
865};
866
867SourceMap.prototype.toString = function toString () {
868 return JSON.stringify(this);
869};
870
871SourceMap.prototype.toUrl = function toUrl () {
872 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
873};
874
875function guessIndent(code) {
876 var lines = code.split('\n');
877
878 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
879 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
880
881 if (tabbed.length === 0 && spaced.length === 0) {
882 return null;
883 }
884
885 // More lines tabbed than spaced? Assume tabs, and
886 // default to tabs in the case of a tie (or nothing
887 // to go on)
888 if (tabbed.length >= spaced.length) {
889 return '\t';
890 }
891
892 // Otherwise, we need to guess the multiple
893 var min = spaced.reduce(function (previous, current) {
894 var numSpaces = /^ +/.exec(current)[0].length;
895 return Math.min(numSpaces, previous);
896 }, Infinity);
897
898 return new Array(min + 1).join(' ');
899}
900
901function getRelativePath(from, to) {
902 var fromParts = from.split(/[/\\]/);
903 var toParts = to.split(/[/\\]/);
904
905 fromParts.pop(); // get dirname
906
907 while (fromParts[0] === toParts[0]) {
908 fromParts.shift();
909 toParts.shift();
910 }
911
912 if (fromParts.length) {
913 var i = fromParts.length;
914 while (i--) { fromParts[i] = '..'; }
915 }
916
917 return fromParts.concat(toParts).join('/');
918}
919
920var toString$1 = Object.prototype.toString;
921
922function isObject(thing) {
923 return toString$1.call(thing) === '[object Object]';
924}
925
926function getLocator(source) {
927 var originalLines = source.split('\n');
928 var lineOffsets = [];
929
930 for (var i = 0, pos = 0; i < originalLines.length; i++) {
931 lineOffsets.push(pos);
932 pos += originalLines[i].length + 1;
933 }
934
935 return function locate(index) {
936 var i = 0;
937 var j = lineOffsets.length;
938 while (i < j) {
939 var m = (i + j) >> 1;
940 if (index < lineOffsets[m]) {
941 j = m;
942 } else {
943 i = m + 1;
944 }
945 }
946 var line = i - 1;
947 var column = index - lineOffsets[line];
948 return { line: line, column: column };
949 };
950}
951
952var Mappings = function Mappings(hires) {
953 this.hires = hires;
954 this.generatedCodeLine = 0;
955 this.generatedCodeColumn = 0;
956 this.raw = [];
957 this.rawSegments = this.raw[this.generatedCodeLine] = [];
958 this.pending = null;
959};
960
961Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
962 if (content.length) {
963 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
964 if (nameIndex >= 0) {
965 segment.push(nameIndex);
966 }
967 this.rawSegments.push(segment);
968 } else if (this.pending) {
969 this.rawSegments.push(this.pending);
970 }
971
972 this.advance(content);
973 this.pending = null;
974};
975
976Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
977 var originalCharIndex = chunk.start;
978 var first = true;
979
980 while (originalCharIndex < chunk.end) {
981 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
982 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
983 }
984
985 if (original[originalCharIndex] === '\n') {
986 loc.line += 1;
987 loc.column = 0;
988 this.generatedCodeLine += 1;
989 this.raw[this.generatedCodeLine] = this.rawSegments = [];
990 this.generatedCodeColumn = 0;
991 first = true;
992 } else {
993 loc.column += 1;
994 this.generatedCodeColumn += 1;
995 first = false;
996 }
997
998 originalCharIndex += 1;
999 }
1000
1001 this.pending = null;
1002};
1003
1004Mappings.prototype.advance = function advance (str) {
1005 if (!str) { return; }
1006
1007 var lines = str.split('\n');
1008
1009 if (lines.length > 1) {
1010 for (var i = 0; i < lines.length - 1; i++) {
1011 this.generatedCodeLine++;
1012 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1013 }
1014 this.generatedCodeColumn = 0;
1015 }
1016
1017 this.generatedCodeColumn += lines[lines.length - 1].length;
1018};
1019
1020var n = '\n';
1021
1022var warned = {
1023 insertLeft: false,
1024 insertRight: false,
1025 storeName: false
1026};
1027
1028var MagicString = function MagicString(string, options) {
1029 if ( options === void 0 ) options = {};
1030
1031 var chunk = new Chunk$1(0, string.length, string);
1032
1033 Object.defineProperties(this, {
1034 original: { writable: true, value: string },
1035 outro: { writable: true, value: '' },
1036 intro: { writable: true, value: '' },
1037 firstChunk: { writable: true, value: chunk },
1038 lastChunk: { writable: true, value: chunk },
1039 lastSearchedChunk: { writable: true, value: chunk },
1040 byStart: { writable: true, value: {} },
1041 byEnd: { writable: true, value: {} },
1042 filename: { writable: true, value: options.filename },
1043 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1044 sourcemapLocations: { writable: true, value: new BitSet() },
1045 storedNames: { writable: true, value: {} },
1046 indentStr: { writable: true, value: guessIndent(string) }
1047 });
1048
1049 this.byStart[0] = chunk;
1050 this.byEnd[string.length] = chunk;
1051};
1052
1053MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
1054 this.sourcemapLocations.add(char);
1055};
1056
1057MagicString.prototype.append = function append (content) {
1058 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1059
1060 this.outro += content;
1061 return this;
1062};
1063
1064MagicString.prototype.appendLeft = function appendLeft (index, content) {
1065 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1066
1067 this._split(index);
1068
1069 var chunk = this.byEnd[index];
1070
1071 if (chunk) {
1072 chunk.appendLeft(content);
1073 } else {
1074 this.intro += content;
1075 }
1076 return this;
1077};
1078
1079MagicString.prototype.appendRight = function appendRight (index, content) {
1080 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1081
1082 this._split(index);
1083
1084 var chunk = this.byStart[index];
1085
1086 if (chunk) {
1087 chunk.appendRight(content);
1088 } else {
1089 this.outro += content;
1090 }
1091 return this;
1092};
1093
1094MagicString.prototype.clone = function clone () {
1095 var cloned = new MagicString(this.original, { filename: this.filename });
1096
1097 var originalChunk = this.firstChunk;
1098 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1099
1100 while (originalChunk) {
1101 cloned.byStart[clonedChunk.start] = clonedChunk;
1102 cloned.byEnd[clonedChunk.end] = clonedChunk;
1103
1104 var nextOriginalChunk = originalChunk.next;
1105 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1106
1107 if (nextClonedChunk) {
1108 clonedChunk.next = nextClonedChunk;
1109 nextClonedChunk.previous = clonedChunk;
1110
1111 clonedChunk = nextClonedChunk;
1112 }
1113
1114 originalChunk = nextOriginalChunk;
1115 }
1116
1117 cloned.lastChunk = clonedChunk;
1118
1119 if (this.indentExclusionRanges) {
1120 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1121 }
1122
1123 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
1124
1125 cloned.intro = this.intro;
1126 cloned.outro = this.outro;
1127
1128 return cloned;
1129};
1130
1131MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
1132 var this$1$1 = this;
1133
1134 options = options || {};
1135
1136 var sourceIndex = 0;
1137 var names = Object.keys(this.storedNames);
1138 var mappings = new Mappings(options.hires);
1139
1140 var locate = getLocator(this.original);
1141
1142 if (this.intro) {
1143 mappings.advance(this.intro);
1144 }
1145
1146 this.firstChunk.eachNext(function (chunk) {
1147 var loc = locate(chunk.start);
1148
1149 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1150
1151 if (chunk.edited) {
1152 mappings.addEdit(
1153 sourceIndex,
1154 chunk.content,
1155 loc,
1156 chunk.storeName ? names.indexOf(chunk.original) : -1
1157 );
1158 } else {
1159 mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
1160 }
1161
1162 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1163 });
1164
1165 return {
1166 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1167 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1168 sourcesContent: options.includeContent ? [this.original] : [null],
1169 names: names,
1170 mappings: mappings.raw
1171 };
1172};
1173
1174MagicString.prototype.generateMap = function generateMap (options) {
1175 return new SourceMap(this.generateDecodedMap(options));
1176};
1177
1178MagicString.prototype.getIndentString = function getIndentString () {
1179 return this.indentStr === null ? '\t' : this.indentStr;
1180};
1181
1182MagicString.prototype.indent = function indent (indentStr, options) {
1183 var pattern = /^[^\r\n]/gm;
1184
1185 if (isObject(indentStr)) {
1186 options = indentStr;
1187 indentStr = undefined;
1188 }
1189
1190 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1191
1192 if (indentStr === '') { return this; } // noop
1193
1194 options = options || {};
1195
1196 // Process exclusion ranges
1197 var isExcluded = {};
1198
1199 if (options.exclude) {
1200 var exclusions =
1201 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1202 exclusions.forEach(function (exclusion) {
1203 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1204 isExcluded[i] = true;
1205 }
1206 });
1207 }
1208
1209 var shouldIndentNextCharacter = options.indentStart !== false;
1210 var replacer = function (match) {
1211 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
1212 shouldIndentNextCharacter = true;
1213 return match;
1214 };
1215
1216 this.intro = this.intro.replace(pattern, replacer);
1217
1218 var charIndex = 0;
1219 var chunk = this.firstChunk;
1220
1221 while (chunk) {
1222 var end = chunk.end;
1223
1224 if (chunk.edited) {
1225 if (!isExcluded[charIndex]) {
1226 chunk.content = chunk.content.replace(pattern, replacer);
1227
1228 if (chunk.content.length) {
1229 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1230 }
1231 }
1232 } else {
1233 charIndex = chunk.start;
1234
1235 while (charIndex < end) {
1236 if (!isExcluded[charIndex]) {
1237 var char = this.original[charIndex];
1238
1239 if (char === '\n') {
1240 shouldIndentNextCharacter = true;
1241 } else if (char !== '\r' && shouldIndentNextCharacter) {
1242 shouldIndentNextCharacter = false;
1243
1244 if (charIndex === chunk.start) {
1245 chunk.prependRight(indentStr);
1246 } else {
1247 this._splitChunk(chunk, charIndex);
1248 chunk = chunk.next;
1249 chunk.prependRight(indentStr);
1250 }
1251 }
1252 }
1253
1254 charIndex += 1;
1255 }
1256 }
1257
1258 charIndex = chunk.end;
1259 chunk = chunk.next;
1260 }
1261
1262 this.outro = this.outro.replace(pattern, replacer);
1263
1264 return this;
1265};
1266
1267MagicString.prototype.insert = function insert () {
1268 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1269};
1270
1271MagicString.prototype.insertLeft = function insertLeft (index, content) {
1272 if (!warned.insertLeft) {
1273 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1274 warned.insertLeft = true;
1275 }
1276
1277 return this.appendLeft(index, content);
1278};
1279
1280MagicString.prototype.insertRight = function insertRight (index, content) {
1281 if (!warned.insertRight) {
1282 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1283 warned.insertRight = true;
1284 }
1285
1286 return this.prependRight(index, content);
1287};
1288
1289MagicString.prototype.move = function move (start, end, index) {
1290 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
1291
1292 this._split(start);
1293 this._split(end);
1294 this._split(index);
1295
1296 var first = this.byStart[start];
1297 var last = this.byEnd[end];
1298
1299 var oldLeft = first.previous;
1300 var oldRight = last.next;
1301
1302 var newRight = this.byStart[index];
1303 if (!newRight && last === this.lastChunk) { return this; }
1304 var newLeft = newRight ? newRight.previous : this.lastChunk;
1305
1306 if (oldLeft) { oldLeft.next = oldRight; }
1307 if (oldRight) { oldRight.previous = oldLeft; }
1308
1309 if (newLeft) { newLeft.next = first; }
1310 if (newRight) { newRight.previous = last; }
1311
1312 if (!first.previous) { this.firstChunk = last.next; }
1313 if (!last.next) {
1314 this.lastChunk = first.previous;
1315 this.lastChunk.next = null;
1316 }
1317
1318 first.previous = newLeft;
1319 last.next = newRight || null;
1320
1321 if (!newLeft) { this.firstChunk = first; }
1322 if (!newRight) { this.lastChunk = last; }
1323 return this;
1324};
1325
1326MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
1327 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
1328
1329 while (start < 0) { start += this.original.length; }
1330 while (end < 0) { end += this.original.length; }
1331
1332 if (end > this.original.length) { throw new Error('end is out of bounds'); }
1333 if (start === end)
1334 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
1335
1336 this._split(start);
1337 this._split(end);
1338
1339 if (options === true) {
1340 if (!warned.storeName) {
1341 console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
1342 warned.storeName = true;
1343 }
1344
1345 options = { storeName: true };
1346 }
1347 var storeName = options !== undefined ? options.storeName : false;
1348 var contentOnly = options !== undefined ? options.contentOnly : false;
1349
1350 if (storeName) {
1351 var original = this.original.slice(start, end);
1352 this.storedNames[original] = true;
1353 }
1354
1355 var first = this.byStart[start];
1356 var last = this.byEnd[end];
1357
1358 if (first) {
1359 if (end > first.end && first.next !== this.byStart[first.end]) {
1360 throw new Error('Cannot overwrite across a split point');
1361 }
1362
1363 first.edit(content, storeName, contentOnly);
1364
1365 if (first !== last) {
1366 var chunk = first.next;
1367 while (chunk !== last) {
1368 chunk.edit('', false);
1369 chunk = chunk.next;
1370 }
1371
1372 chunk.edit('', false);
1373 }
1374 } else {
1375 // must be inserting at the end
1376 var newChunk = new Chunk$1(start, end, '').edit(content, storeName);
1377
1378 // TODO last chunk in the array may not be the last chunk, if it's moved...
1379 last.next = newChunk;
1380 newChunk.previous = last;
1381 }
1382 return this;
1383};
1384
1385MagicString.prototype.prepend = function prepend (content) {
1386 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1387
1388 this.intro = content + this.intro;
1389 return this;
1390};
1391
1392MagicString.prototype.prependLeft = function prependLeft (index, content) {
1393 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1394
1395 this._split(index);
1396
1397 var chunk = this.byEnd[index];
1398
1399 if (chunk) {
1400 chunk.prependLeft(content);
1401 } else {
1402 this.intro = content + this.intro;
1403 }
1404 return this;
1405};
1406
1407MagicString.prototype.prependRight = function prependRight (index, content) {
1408 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1409
1410 this._split(index);
1411
1412 var chunk = this.byStart[index];
1413
1414 if (chunk) {
1415 chunk.prependRight(content);
1416 } else {
1417 this.outro = content + this.outro;
1418 }
1419 return this;
1420};
1421
1422MagicString.prototype.remove = function remove (start, end) {
1423 while (start < 0) { start += this.original.length; }
1424 while (end < 0) { end += this.original.length; }
1425
1426 if (start === end) { return this; }
1427
1428 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
1429 if (start > end) { throw new Error('end must be greater than start'); }
1430
1431 this._split(start);
1432 this._split(end);
1433
1434 var chunk = this.byStart[start];
1435
1436 while (chunk) {
1437 chunk.intro = '';
1438 chunk.outro = '';
1439 chunk.edit('');
1440
1441 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1442 }
1443 return this;
1444};
1445
1446MagicString.prototype.lastChar = function lastChar () {
1447 if (this.outro.length)
1448 { return this.outro[this.outro.length - 1]; }
1449 var chunk = this.lastChunk;
1450 do {
1451 if (chunk.outro.length)
1452 { return chunk.outro[chunk.outro.length - 1]; }
1453 if (chunk.content.length)
1454 { return chunk.content[chunk.content.length - 1]; }
1455 if (chunk.intro.length)
1456 { return chunk.intro[chunk.intro.length - 1]; }
1457 } while (chunk = chunk.previous);
1458 if (this.intro.length)
1459 { return this.intro[this.intro.length - 1]; }
1460 return '';
1461};
1462
1463MagicString.prototype.lastLine = function lastLine () {
1464 var lineIndex = this.outro.lastIndexOf(n);
1465 if (lineIndex !== -1)
1466 { return this.outro.substr(lineIndex + 1); }
1467 var lineStr = this.outro;
1468 var chunk = this.lastChunk;
1469 do {
1470 if (chunk.outro.length > 0) {
1471 lineIndex = chunk.outro.lastIndexOf(n);
1472 if (lineIndex !== -1)
1473 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
1474 lineStr = chunk.outro + lineStr;
1475 }
1476
1477 if (chunk.content.length > 0) {
1478 lineIndex = chunk.content.lastIndexOf(n);
1479 if (lineIndex !== -1)
1480 { return chunk.content.substr(lineIndex + 1) + lineStr; }
1481 lineStr = chunk.content + lineStr;
1482 }
1483
1484 if (chunk.intro.length > 0) {
1485 lineIndex = chunk.intro.lastIndexOf(n);
1486 if (lineIndex !== -1)
1487 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
1488 lineStr = chunk.intro + lineStr;
1489 }
1490 } while (chunk = chunk.previous);
1491 lineIndex = this.intro.lastIndexOf(n);
1492 if (lineIndex !== -1)
1493 { return this.intro.substr(lineIndex + 1) + lineStr; }
1494 return this.intro + lineStr;
1495};
1496
1497MagicString.prototype.slice = function slice (start, end) {
1498 if ( start === void 0 ) start = 0;
1499 if ( end === void 0 ) end = this.original.length;
1500
1501 while (start < 0) { start += this.original.length; }
1502 while (end < 0) { end += this.original.length; }
1503
1504 var result = '';
1505
1506 // find start chunk
1507 var chunk = this.firstChunk;
1508 while (chunk && (chunk.start > start || chunk.end <= start)) {
1509 // found end chunk before start
1510 if (chunk.start < end && chunk.end >= end) {
1511 return result;
1512 }
1513
1514 chunk = chunk.next;
1515 }
1516
1517 if (chunk && chunk.edited && chunk.start !== start)
1518 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1519
1520 var startChunk = chunk;
1521 while (chunk) {
1522 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1523 result += chunk.intro;
1524 }
1525
1526 var containsEnd = chunk.start < end && chunk.end >= end;
1527 if (containsEnd && chunk.edited && chunk.end !== end)
1528 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1529
1530 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1531 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1532
1533 result += chunk.content.slice(sliceStart, sliceEnd);
1534
1535 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1536 result += chunk.outro;
1537 }
1538
1539 if (containsEnd) {
1540 break;
1541 }
1542
1543 chunk = chunk.next;
1544 }
1545
1546 return result;
1547};
1548
1549// TODO deprecate this? not really very useful
1550MagicString.prototype.snip = function snip (start, end) {
1551 var clone = this.clone();
1552 clone.remove(0, start);
1553 clone.remove(end, clone.original.length);
1554
1555 return clone;
1556};
1557
1558MagicString.prototype._split = function _split (index) {
1559 if (this.byStart[index] || this.byEnd[index]) { return; }
1560
1561 var chunk = this.lastSearchedChunk;
1562 var searchForward = index > chunk.end;
1563
1564 while (chunk) {
1565 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
1566
1567 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1568 }
1569};
1570
1571MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
1572 if (chunk.edited && chunk.content.length) {
1573 // zero-length edited chunks are a special case (overlapping replacements)
1574 var loc = getLocator(this.original)(index);
1575 throw new Error(
1576 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
1577 );
1578 }
1579
1580 var newChunk = chunk.split(index);
1581
1582 this.byEnd[index] = chunk;
1583 this.byStart[index] = newChunk;
1584 this.byEnd[newChunk.end] = newChunk;
1585
1586 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
1587
1588 this.lastSearchedChunk = chunk;
1589 return true;
1590};
1591
1592MagicString.prototype.toString = function toString () {
1593 var str = this.intro;
1594
1595 var chunk = this.firstChunk;
1596 while (chunk) {
1597 str += chunk.toString();
1598 chunk = chunk.next;
1599 }
1600
1601 return str + this.outro;
1602};
1603
1604MagicString.prototype.isEmpty = function isEmpty () {
1605 var chunk = this.firstChunk;
1606 do {
1607 if (chunk.intro.length && chunk.intro.trim() ||
1608 chunk.content.length && chunk.content.trim() ||
1609 chunk.outro.length && chunk.outro.trim())
1610 { return false; }
1611 } while (chunk = chunk.next);
1612 return true;
1613};
1614
1615MagicString.prototype.length = function length () {
1616 var chunk = this.firstChunk;
1617 var length = 0;
1618 do {
1619 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1620 } while (chunk = chunk.next);
1621 return length;
1622};
1623
1624MagicString.prototype.trimLines = function trimLines () {
1625 return this.trim('[\\r\\n]');
1626};
1627
1628MagicString.prototype.trim = function trim (charType) {
1629 return this.trimStart(charType).trimEnd(charType);
1630};
1631
1632MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
1633 var rx = new RegExp((charType || '\\s') + '+$');
1634
1635 this.outro = this.outro.replace(rx, '');
1636 if (this.outro.length) { return true; }
1637
1638 var chunk = this.lastChunk;
1639
1640 do {
1641 var end = chunk.end;
1642 var aborted = chunk.trimEnd(rx);
1643
1644 // if chunk was trimmed, we have a new lastChunk
1645 if (chunk.end !== end) {
1646 if (this.lastChunk === chunk) {
1647 this.lastChunk = chunk.next;
1648 }
1649
1650 this.byEnd[chunk.end] = chunk;
1651 this.byStart[chunk.next.start] = chunk.next;
1652 this.byEnd[chunk.next.end] = chunk.next;
1653 }
1654
1655 if (aborted) { return true; }
1656 chunk = chunk.previous;
1657 } while (chunk);
1658
1659 return false;
1660};
1661
1662MagicString.prototype.trimEnd = function trimEnd (charType) {
1663 this.trimEndAborted(charType);
1664 return this;
1665};
1666MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
1667 var rx = new RegExp('^' + (charType || '\\s') + '+');
1668
1669 this.intro = this.intro.replace(rx, '');
1670 if (this.intro.length) { return true; }
1671
1672 var chunk = this.firstChunk;
1673
1674 do {
1675 var end = chunk.end;
1676 var aborted = chunk.trimStart(rx);
1677
1678 if (chunk.end !== end) {
1679 // special case...
1680 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
1681
1682 this.byEnd[chunk.end] = chunk;
1683 this.byStart[chunk.next.start] = chunk.next;
1684 this.byEnd[chunk.next.end] = chunk.next;
1685 }
1686
1687 if (aborted) { return true; }
1688 chunk = chunk.next;
1689 } while (chunk);
1690
1691 return false;
1692};
1693
1694MagicString.prototype.trimStart = function trimStart (charType) {
1695 this.trimStartAborted(charType);
1696 return this;
1697};
1698
1699var hasOwnProp = Object.prototype.hasOwnProperty;
1700
1701var Bundle$1 = function Bundle(options) {
1702 if ( options === void 0 ) options = {};
1703
1704 this.intro = options.intro || '';
1705 this.separator = options.separator !== undefined ? options.separator : '\n';
1706 this.sources = [];
1707 this.uniqueSources = [];
1708 this.uniqueSourceIndexByFilename = {};
1709};
1710
1711Bundle$1.prototype.addSource = function addSource (source) {
1712 if (source instanceof MagicString) {
1713 return this.addSource({
1714 content: source,
1715 filename: source.filename,
1716 separator: this.separator
1717 });
1718 }
1719
1720 if (!isObject(source) || !source.content) {
1721 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1722 }
1723
1724 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1725 if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
1726 });
1727
1728 if (source.separator === undefined) {
1729 // TODO there's a bunch of this sort of thing, needs cleaning up
1730 source.separator = this.separator;
1731 }
1732
1733 if (source.filename) {
1734 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1735 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1736 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1737 } else {
1738 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1739 if (source.content.original !== uniqueSource.content) {
1740 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1741 }
1742 }
1743 }
1744
1745 this.sources.push(source);
1746 return this;
1747};
1748
1749Bundle$1.prototype.append = function append (str, options) {
1750 this.addSource({
1751 content: new MagicString(str),
1752 separator: (options && options.separator) || ''
1753 });
1754
1755 return this;
1756};
1757
1758Bundle$1.prototype.clone = function clone () {
1759 var bundle = new Bundle$1({
1760 intro: this.intro,
1761 separator: this.separator
1762 });
1763
1764 this.sources.forEach(function (source) {
1765 bundle.addSource({
1766 filename: source.filename,
1767 content: source.content.clone(),
1768 separator: source.separator
1769 });
1770 });
1771
1772 return bundle;
1773};
1774
1775Bundle$1.prototype.generateDecodedMap = function generateDecodedMap (options) {
1776 var this$1$1 = this;
1777 if ( options === void 0 ) options = {};
1778
1779 var names = [];
1780 this.sources.forEach(function (source) {
1781 Object.keys(source.content.storedNames).forEach(function (name) {
1782 if (!~names.indexOf(name)) { names.push(name); }
1783 });
1784 });
1785
1786 var mappings = new Mappings(options.hires);
1787
1788 if (this.intro) {
1789 mappings.advance(this.intro);
1790 }
1791
1792 this.sources.forEach(function (source, i) {
1793 if (i > 0) {
1794 mappings.advance(this$1$1.separator);
1795 }
1796
1797 var sourceIndex = source.filename ? this$1$1.uniqueSourceIndexByFilename[source.filename] : -1;
1798 var magicString = source.content;
1799 var locate = getLocator(magicString.original);
1800
1801 if (magicString.intro) {
1802 mappings.advance(magicString.intro);
1803 }
1804
1805 magicString.firstChunk.eachNext(function (chunk) {
1806 var loc = locate(chunk.start);
1807
1808 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1809
1810 if (source.filename) {
1811 if (chunk.edited) {
1812 mappings.addEdit(
1813 sourceIndex,
1814 chunk.content,
1815 loc,
1816 chunk.storeName ? names.indexOf(chunk.original) : -1
1817 );
1818 } else {
1819 mappings.addUneditedChunk(
1820 sourceIndex,
1821 chunk,
1822 magicString.original,
1823 loc,
1824 magicString.sourcemapLocations
1825 );
1826 }
1827 } else {
1828 mappings.advance(chunk.content);
1829 }
1830
1831 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1832 });
1833
1834 if (magicString.outro) {
1835 mappings.advance(magicString.outro);
1836 }
1837 });
1838
1839 return {
1840 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1841 sources: this.uniqueSources.map(function (source) {
1842 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1843 }),
1844 sourcesContent: this.uniqueSources.map(function (source) {
1845 return options.includeContent ? source.content : null;
1846 }),
1847 names: names,
1848 mappings: mappings.raw
1849 };
1850};
1851
1852Bundle$1.prototype.generateMap = function generateMap (options) {
1853 return new SourceMap(this.generateDecodedMap(options));
1854};
1855
1856Bundle$1.prototype.getIndentString = function getIndentString () {
1857 var indentStringCounts = {};
1858
1859 this.sources.forEach(function (source) {
1860 var indentStr = source.content.indentStr;
1861
1862 if (indentStr === null) { return; }
1863
1864 if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
1865 indentStringCounts[indentStr] += 1;
1866 });
1867
1868 return (
1869 Object.keys(indentStringCounts).sort(function (a, b) {
1870 return indentStringCounts[a] - indentStringCounts[b];
1871 })[0] || '\t'
1872 );
1873};
1874
1875Bundle$1.prototype.indent = function indent (indentStr) {
1876 var this$1$1 = this;
1877
1878 if (!arguments.length) {
1879 indentStr = this.getIndentString();
1880 }
1881
1882 if (indentStr === '') { return this; } // noop
1883
1884 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1885
1886 this.sources.forEach(function (source, i) {
1887 var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
1888 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1889
1890 source.content.indent(indentStr, {
1891 exclude: source.indentExclusionRanges,
1892 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1893 });
1894
1895 trailingNewline = source.content.lastChar() === '\n';
1896 });
1897
1898 if (this.intro) {
1899 this.intro =
1900 indentStr +
1901 this.intro.replace(/^[^\n]/gm, function (match, index) {
1902 return index > 0 ? indentStr + match : match;
1903 });
1904 }
1905
1906 return this;
1907};
1908
1909Bundle$1.prototype.prepend = function prepend (str) {
1910 this.intro = str + this.intro;
1911 return this;
1912};
1913
1914Bundle$1.prototype.toString = function toString () {
1915 var this$1$1 = this;
1916
1917 var body = this.sources
1918 .map(function (source, i) {
1919 var separator = source.separator !== undefined ? source.separator : this$1$1.separator;
1920 var str = (i > 0 ? separator : '') + source.content.toString();
1921
1922 return str;
1923 })
1924 .join('');
1925
1926 return this.intro + body;
1927};
1928
1929Bundle$1.prototype.isEmpty = function isEmpty () {
1930 if (this.intro.length && this.intro.trim())
1931 { return false; }
1932 if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
1933 { return false; }
1934 return true;
1935};
1936
1937Bundle$1.prototype.length = function length () {
1938 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1939};
1940
1941Bundle$1.prototype.trimLines = function trimLines () {
1942 return this.trim('[\\r\\n]');
1943};
1944
1945Bundle$1.prototype.trim = function trim (charType) {
1946 return this.trimStart(charType).trimEnd(charType);
1947};
1948
1949Bundle$1.prototype.trimStart = function trimStart (charType) {
1950 var rx = new RegExp('^' + (charType || '\\s') + '+');
1951 this.intro = this.intro.replace(rx, '');
1952
1953 if (!this.intro) {
1954 var source;
1955 var i = 0;
1956
1957 do {
1958 source = this.sources[i++];
1959 if (!source) {
1960 break;
1961 }
1962 } while (!source.content.trimStartAborted(charType));
1963 }
1964
1965 return this;
1966};
1967
1968Bundle$1.prototype.trimEnd = function trimEnd (charType) {
1969 var rx = new RegExp((charType || '\\s') + '+$');
1970
1971 var source;
1972 var i = this.sources.length - 1;
1973
1974 do {
1975 source = this.sources[i--];
1976 if (!source) {
1977 this.intro = this.intro.replace(rx, '');
1978 break;
1979 }
1980 } while (!source.content.trimEndAborted(charType));
1981
1982 return this;
1983};
1984
1985var MagicString$1 = MagicString;
1986
1987function relative(from, to) {
1988 const fromParts = from.split(/[/\\]/).filter(Boolean);
1989 const toParts = to.split(/[/\\]/).filter(Boolean);
1990 if (fromParts[0] === '.')
1991 fromParts.shift();
1992 if (toParts[0] === '.')
1993 toParts.shift();
1994 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1995 fromParts.shift();
1996 toParts.shift();
1997 }
1998 while (toParts[0] === '..' && fromParts.length > 0) {
1999 toParts.shift();
2000 fromParts.pop();
2001 }
2002 while (fromParts.pop()) {
2003 toParts.unshift('..');
2004 }
2005 return toParts.join('/');
2006}
2007
2008const RESERVED_NAMES = {
2009 __proto__: null,
2010 await: true,
2011 break: true,
2012 case: true,
2013 catch: true,
2014 class: true,
2015 const: true,
2016 continue: true,
2017 debugger: true,
2018 default: true,
2019 delete: true,
2020 do: true,
2021 else: true,
2022 enum: true,
2023 eval: true,
2024 export: true,
2025 extends: true,
2026 false: true,
2027 finally: true,
2028 for: true,
2029 function: true,
2030 if: true,
2031 implements: true,
2032 import: true,
2033 in: true,
2034 instanceof: true,
2035 interface: true,
2036 let: true,
2037 new: true,
2038 null: true,
2039 package: true,
2040 private: true,
2041 protected: true,
2042 public: true,
2043 return: true,
2044 static: true,
2045 super: true,
2046 switch: true,
2047 this: true,
2048 throw: true,
2049 true: true,
2050 try: true,
2051 typeof: true,
2052 undefined: true,
2053 var: true,
2054 void: true,
2055 while: true,
2056 with: true,
2057 yield: true
2058};
2059
2060function getOrCreate(map, key, init) {
2061 const existing = map.get(key);
2062 if (existing) {
2063 return existing;
2064 }
2065 const value = init();
2066 map.set(key, value);
2067 return value;
2068}
2069
2070const UnknownKey = Symbol('Unknown Key');
2071const UnknownInteger = Symbol('Unknown Integer');
2072const EMPTY_PATH = [];
2073const UNKNOWN_PATH = [UnknownKey];
2074const UNKNOWN_INTEGER_PATH = [UnknownInteger];
2075const EntitiesKey = Symbol('Entities');
2076class PathTracker {
2077 constructor() {
2078 this.entityPaths = Object.create(null, {
2079 [EntitiesKey]: { value: new Set() }
2080 });
2081 }
2082 trackEntityAtPathAndGetIfTracked(path, entity) {
2083 const trackedEntities = this.getEntities(path);
2084 if (trackedEntities.has(entity))
2085 return true;
2086 trackedEntities.add(entity);
2087 return false;
2088 }
2089 withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
2090 const trackedEntities = this.getEntities(path);
2091 if (trackedEntities.has(entity))
2092 return returnIfTracked;
2093 trackedEntities.add(entity);
2094 const result = onUntracked();
2095 trackedEntities.delete(entity);
2096 return result;
2097 }
2098 getEntities(path) {
2099 let currentPaths = this.entityPaths;
2100 for (const pathSegment of path) {
2101 currentPaths = currentPaths[pathSegment] =
2102 currentPaths[pathSegment] ||
2103 Object.create(null, { [EntitiesKey]: { value: new Set() } });
2104 }
2105 return currentPaths[EntitiesKey];
2106 }
2107}
2108const SHARED_RECURSION_TRACKER = new PathTracker();
2109class DiscriminatedPathTracker {
2110 constructor() {
2111 this.entityPaths = Object.create(null, {
2112 [EntitiesKey]: { value: new Map() }
2113 });
2114 }
2115 trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
2116 let currentPaths = this.entityPaths;
2117 for (const pathSegment of path) {
2118 currentPaths = currentPaths[pathSegment] =
2119 currentPaths[pathSegment] ||
2120 Object.create(null, { [EntitiesKey]: { value: new Map() } });
2121 }
2122 const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
2123 if (trackedEntities.has(entity))
2124 return true;
2125 trackedEntities.add(entity);
2126 return false;
2127 }
2128}
2129
2130const UnknownValue = Symbol('Unknown Value');
2131class ExpressionEntity {
2132 constructor() {
2133 this.included = false;
2134 }
2135 deoptimizePath(_path) { }
2136 deoptimizeThisOnEventAtPath(_event, _path, thisParameter, _recursionTracker) {
2137 thisParameter.deoptimizePath(UNKNOWN_PATH);
2138 }
2139 /**
2140 * If possible it returns a stringifyable literal value for this node that can be used
2141 * for inlining or comparing values.
2142 * Otherwise it should return UnknownValue.
2143 */
2144 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2145 return UnknownValue;
2146 }
2147 getReturnExpressionWhenCalledAtPath(_path, _callOptions, _recursionTracker, _origin) {
2148 return UNKNOWN_EXPRESSION;
2149 }
2150 hasEffectsWhenAccessedAtPath(_path, _context) {
2151 return true;
2152 }
2153 hasEffectsWhenAssignedAtPath(_path, _context) {
2154 return true;
2155 }
2156 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2157 return true;
2158 }
2159 include(_context, _includeChildrenRecursively) {
2160 this.included = true;
2161 }
2162 includeCallArguments(context, args) {
2163 for (const arg of args) {
2164 arg.include(context, false);
2165 }
2166 }
2167}
2168const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
2169})();
2170
2171class Variable extends ExpressionEntity {
2172 constructor(name) {
2173 super();
2174 this.name = name;
2175 this.alwaysRendered = false;
2176 this.initReached = false;
2177 this.isId = false;
2178 this.isReassigned = false;
2179 this.kind = null;
2180 this.renderBaseName = null;
2181 this.renderName = null;
2182 }
2183 /**
2184 * Binds identifiers that reference this variable to this variable.
2185 * Necessary to be able to change variable names.
2186 */
2187 addReference(_identifier) { }
2188 getBaseVariableName() {
2189 return this.renderBaseName || this.renderName || this.name;
2190 }
2191 getName() {
2192 const name = this.renderName || this.name;
2193 return this.renderBaseName
2194 ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
2195 : name;
2196 }
2197 hasEffectsWhenAccessedAtPath(path, _context) {
2198 return path.length > 0;
2199 }
2200 /**
2201 * Marks this variable as being part of the bundle, which is usually the case when one of
2202 * its identifiers becomes part of the bundle. Returns true if it has not been included
2203 * previously.
2204 * Once a variable is included, it should take care all its declarations are included.
2205 */
2206 include() {
2207 this.included = true;
2208 }
2209 markCalledFromTryStatement() { }
2210 setRenderNames(baseName, name) {
2211 this.renderBaseName = baseName;
2212 this.renderName = name;
2213 }
2214}
2215
2216class ExternalVariable extends Variable {
2217 constructor(module, name) {
2218 super(name);
2219 this.module = module;
2220 this.isNamespace = name === '*';
2221 this.referenced = false;
2222 }
2223 addReference(identifier) {
2224 this.referenced = true;
2225 if (this.name === 'default' || this.name === '*') {
2226 this.module.suggestName(identifier.name);
2227 }
2228 }
2229 hasEffectsWhenAccessedAtPath(path) {
2230 return path.length > (this.isNamespace ? 1 : 0);
2231 }
2232 include() {
2233 if (!this.included) {
2234 this.included = true;
2235 this.module.used = true;
2236 }
2237 }
2238}
2239
2240const BLANK = Object.freeze(Object.create(null));
2241const EMPTY_OBJECT = Object.freeze({});
2242const EMPTY_ARRAY = Object.freeze([]);
2243
2244const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
2245const builtins$1 = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' ');
2246const blacklisted = new Set(reservedWords$1.concat(builtins$1));
2247const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2248const startsWithDigit = (str) => /\d/.test(str[0]);
2249function isLegal(str) {
2250 if (startsWithDigit(str) || blacklisted.has(str)) {
2251 return false;
2252 }
2253 return !illegalCharacters.test(str);
2254}
2255function makeLegal(str) {
2256 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2257 if (startsWithDigit(str) || blacklisted.has(str))
2258 str = `_${str}`;
2259 return str || '_';
2260}
2261
2262class ExternalModule {
2263 constructor(options, id, hasModuleSideEffects, meta, renormalizeRenderPath) {
2264 this.options = options;
2265 this.id = id;
2266 this.renormalizeRenderPath = renormalizeRenderPath;
2267 this.defaultVariableName = '';
2268 this.dynamicImporters = [];
2269 this.importers = [];
2270 this.mostCommonSuggestion = 0;
2271 this.namespaceVariableName = '';
2272 this.reexported = false;
2273 this.renderPath = undefined;
2274 this.used = false;
2275 this.variableName = '';
2276 this.execIndex = Infinity;
2277 this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2278 this.nameSuggestions = Object.create(null);
2279 this.declarations = Object.create(null);
2280 this.exportedVariables = new Map();
2281 const { importers, dynamicImporters } = this;
2282 this.info = {
2283 ast: null,
2284 code: null,
2285 dynamicallyImportedIds: EMPTY_ARRAY,
2286 get dynamicImporters() {
2287 return dynamicImporters.sort();
2288 },
2289 hasModuleSideEffects,
2290 id,
2291 implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
2292 implicitlyLoadedBefore: EMPTY_ARRAY,
2293 importedIds: EMPTY_ARRAY,
2294 get importers() {
2295 return importers.sort();
2296 },
2297 isEntry: false,
2298 isExternal: true,
2299 meta,
2300 syntheticNamedExports: false
2301 };
2302 }
2303 getVariableForExportName(name) {
2304 let declaration = this.declarations[name];
2305 if (declaration)
2306 return declaration;
2307 this.declarations[name] = declaration = new ExternalVariable(this, name);
2308 this.exportedVariables.set(declaration, name);
2309 return declaration;
2310 }
2311 setRenderPath(options, inputBase) {
2312 this.renderPath =
2313 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2314 if (!this.renderPath) {
2315 this.renderPath = this.renormalizeRenderPath
2316 ? normalize(path.relative(inputBase, this.id))
2317 : this.id;
2318 }
2319 return this.renderPath;
2320 }
2321 suggestName(name) {
2322 if (!this.nameSuggestions[name])
2323 this.nameSuggestions[name] = 0;
2324 this.nameSuggestions[name] += 1;
2325 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2326 this.mostCommonSuggestion = this.nameSuggestions[name];
2327 this.suggestedVariableName = name;
2328 }
2329 }
2330 warnUnusedImports() {
2331 const unused = Object.keys(this.declarations).filter(name => {
2332 if (name === '*')
2333 return false;
2334 const declaration = this.declarations[name];
2335 return !declaration.included && !this.reexported && !declaration.referenced;
2336 });
2337 if (unused.length === 0)
2338 return;
2339 const importersSet = new Set();
2340 for (const name of unused) {
2341 const { importers } = this.declarations[name].module;
2342 for (const importer of importers) {
2343 importersSet.add(importer);
2344 }
2345 }
2346 const importersArray = [...importersSet];
2347 this.options.onwarn({
2348 code: 'UNUSED_EXTERNAL_IMPORT',
2349 message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
2350 names: unused,
2351 source: this.id,
2352 sources: importersArray
2353 });
2354 }
2355}
2356
2357const extractors = {
2358 ArrayPattern(names, param) {
2359 for (const element of param.elements) {
2360 if (element)
2361 extractors[element.type](names, element);
2362 }
2363 },
2364 AssignmentPattern(names, param) {
2365 extractors[param.left.type](names, param.left);
2366 },
2367 Identifier(names, param) {
2368 names.push(param.name);
2369 },
2370 MemberExpression() { },
2371 ObjectPattern(names, param) {
2372 for (const prop of param.properties) {
2373 if (prop.type === 'RestElement') {
2374 extractors.RestElement(names, prop);
2375 }
2376 else {
2377 extractors[prop.value.type](names, prop.value);
2378 }
2379 }
2380 },
2381 RestElement(names, param) {
2382 extractors[param.argument.type](names, param.argument);
2383 }
2384};
2385const extractAssignedNames = function extractAssignedNames(param) {
2386 const names = [];
2387 extractors[param.type](names, param);
2388 return names;
2389};
2390
2391const BROKEN_FLOW_NONE = 0;
2392const BROKEN_FLOW_BREAK_CONTINUE = 1;
2393const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
2394function createInclusionContext() {
2395 return {
2396 brokenFlow: BROKEN_FLOW_NONE,
2397 includedCallArguments: new Set(),
2398 includedLabels: new Set()
2399 };
2400}
2401function createHasEffectsContext() {
2402 return {
2403 accessed: new PathTracker(),
2404 assigned: new PathTracker(),
2405 brokenFlow: BROKEN_FLOW_NONE,
2406 called: new DiscriminatedPathTracker(),
2407 ignore: {
2408 breaks: false,
2409 continues: false,
2410 labels: new Set(),
2411 returnYield: false
2412 },
2413 includedLabels: new Set(),
2414 instantiated: new DiscriminatedPathTracker(),
2415 replacedVariableInits: new Map()
2416 };
2417}
2418
2419// AST walker module for Mozilla Parser API compatible trees
2420
2421function skipThrough(node, st, c) { c(node, st); }
2422function ignore(_node, _st, _c) {}
2423
2424// Node walkers.
2425
2426var base$1 = {};
2427
2428base$1.Program = base$1.BlockStatement = function (node, st, c) {
2429 for (var i = 0, list = node.body; i < list.length; i += 1)
2430 {
2431 var stmt = list[i];
2432
2433 c(stmt, st, "Statement");
2434 }
2435};
2436base$1.Statement = skipThrough;
2437base$1.EmptyStatement = ignore;
2438base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
2439 function (node, st, c) { return c(node.expression, st, "Expression"); };
2440base$1.IfStatement = function (node, st, c) {
2441 c(node.test, st, "Expression");
2442 c(node.consequent, st, "Statement");
2443 if (node.alternate) { c(node.alternate, st, "Statement"); }
2444};
2445base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
2446base$1.BreakStatement = base$1.ContinueStatement = ignore;
2447base$1.WithStatement = function (node, st, c) {
2448 c(node.object, st, "Expression");
2449 c(node.body, st, "Statement");
2450};
2451base$1.SwitchStatement = function (node, st, c) {
2452 c(node.discriminant, st, "Expression");
2453 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
2454 var cs = list$1[i$1];
2455
2456 if (cs.test) { c(cs.test, st, "Expression"); }
2457 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
2458 {
2459 var cons = list[i];
2460
2461 c(cons, st, "Statement");
2462 }
2463 }
2464};
2465base$1.SwitchCase = function (node, st, c) {
2466 if (node.test) { c(node.test, st, "Expression"); }
2467 for (var i = 0, list = node.consequent; i < list.length; i += 1)
2468 {
2469 var cons = list[i];
2470
2471 c(cons, st, "Statement");
2472 }
2473};
2474base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
2475 if (node.argument) { c(node.argument, st, "Expression"); }
2476};
2477base$1.ThrowStatement = base$1.SpreadElement =
2478 function (node, st, c) { return c(node.argument, st, "Expression"); };
2479base$1.TryStatement = function (node, st, c) {
2480 c(node.block, st, "Statement");
2481 if (node.handler) { c(node.handler, st); }
2482 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
2483};
2484base$1.CatchClause = function (node, st, c) {
2485 if (node.param) { c(node.param, st, "Pattern"); }
2486 c(node.body, st, "Statement");
2487};
2488base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
2489 c(node.test, st, "Expression");
2490 c(node.body, st, "Statement");
2491};
2492base$1.ForStatement = function (node, st, c) {
2493 if (node.init) { c(node.init, st, "ForInit"); }
2494 if (node.test) { c(node.test, st, "Expression"); }
2495 if (node.update) { c(node.update, st, "Expression"); }
2496 c(node.body, st, "Statement");
2497};
2498base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
2499 c(node.left, st, "ForInit");
2500 c(node.right, st, "Expression");
2501 c(node.body, st, "Statement");
2502};
2503base$1.ForInit = function (node, st, c) {
2504 if (node.type === "VariableDeclaration") { c(node, st); }
2505 else { c(node, st, "Expression"); }
2506};
2507base$1.DebuggerStatement = ignore;
2508
2509base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
2510base$1.VariableDeclaration = function (node, st, c) {
2511 for (var i = 0, list = node.declarations; i < list.length; i += 1)
2512 {
2513 var decl = list[i];
2514
2515 c(decl, st);
2516 }
2517};
2518base$1.VariableDeclarator = function (node, st, c) {
2519 c(node.id, st, "Pattern");
2520 if (node.init) { c(node.init, st, "Expression"); }
2521};
2522
2523base$1.Function = function (node, st, c) {
2524 if (node.id) { c(node.id, st, "Pattern"); }
2525 for (var i = 0, list = node.params; i < list.length; i += 1)
2526 {
2527 var param = list[i];
2528
2529 c(param, st, "Pattern");
2530 }
2531 c(node.body, st, node.expression ? "Expression" : "Statement");
2532};
2533
2534base$1.Pattern = function (node, st, c) {
2535 if (node.type === "Identifier")
2536 { c(node, st, "VariablePattern"); }
2537 else if (node.type === "MemberExpression")
2538 { c(node, st, "MemberPattern"); }
2539 else
2540 { c(node, st); }
2541};
2542base$1.VariablePattern = ignore;
2543base$1.MemberPattern = skipThrough;
2544base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
2545base$1.ArrayPattern = function (node, st, c) {
2546 for (var i = 0, list = node.elements; i < list.length; i += 1) {
2547 var elt = list[i];
2548
2549 if (elt) { c(elt, st, "Pattern"); }
2550 }
2551};
2552base$1.ObjectPattern = function (node, st, c) {
2553 for (var i = 0, list = node.properties; i < list.length; i += 1) {
2554 var prop = list[i];
2555
2556 if (prop.type === "Property") {
2557 if (prop.computed) { c(prop.key, st, "Expression"); }
2558 c(prop.value, st, "Pattern");
2559 } else if (prop.type === "RestElement") {
2560 c(prop.argument, st, "Pattern");
2561 }
2562 }
2563};
2564
2565base$1.Expression = skipThrough;
2566base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
2567base$1.ArrayExpression = function (node, st, c) {
2568 for (var i = 0, list = node.elements; i < list.length; i += 1) {
2569 var elt = list[i];
2570
2571 if (elt) { c(elt, st, "Expression"); }
2572 }
2573};
2574base$1.ObjectExpression = function (node, st, c) {
2575 for (var i = 0, list = node.properties; i < list.length; i += 1)
2576 {
2577 var prop = list[i];
2578
2579 c(prop, st);
2580 }
2581};
2582base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
2583base$1.SequenceExpression = function (node, st, c) {
2584 for (var i = 0, list = node.expressions; i < list.length; i += 1)
2585 {
2586 var expr = list[i];
2587
2588 c(expr, st, "Expression");
2589 }
2590};
2591base$1.TemplateLiteral = function (node, st, c) {
2592 for (var i = 0, list = node.quasis; i < list.length; i += 1)
2593 {
2594 var quasi = list[i];
2595
2596 c(quasi, st);
2597 }
2598
2599 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
2600 {
2601 var expr = list$1[i$1];
2602
2603 c(expr, st, "Expression");
2604 }
2605};
2606base$1.TemplateElement = ignore;
2607base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
2608 c(node.argument, st, "Expression");
2609};
2610base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
2611 c(node.left, st, "Expression");
2612 c(node.right, st, "Expression");
2613};
2614base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
2615 c(node.left, st, "Pattern");
2616 c(node.right, st, "Expression");
2617};
2618base$1.ConditionalExpression = function (node, st, c) {
2619 c(node.test, st, "Expression");
2620 c(node.consequent, st, "Expression");
2621 c(node.alternate, st, "Expression");
2622};
2623base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
2624 c(node.callee, st, "Expression");
2625 if (node.arguments)
2626 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
2627 {
2628 var arg = list[i];
2629
2630 c(arg, st, "Expression");
2631 } }
2632};
2633base$1.MemberExpression = function (node, st, c) {
2634 c(node.object, st, "Expression");
2635 if (node.computed) { c(node.property, st, "Expression"); }
2636};
2637base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
2638 if (node.declaration)
2639 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
2640 if (node.source) { c(node.source, st, "Expression"); }
2641};
2642base$1.ExportAllDeclaration = function (node, st, c) {
2643 if (node.exported)
2644 { c(node.exported, st); }
2645 c(node.source, st, "Expression");
2646};
2647base$1.ImportDeclaration = function (node, st, c) {
2648 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
2649 {
2650 var spec = list[i];
2651
2652 c(spec, st);
2653 }
2654 c(node.source, st, "Expression");
2655};
2656base$1.ImportExpression = function (node, st, c) {
2657 c(node.source, st, "Expression");
2658};
2659base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
2660
2661base$1.TaggedTemplateExpression = function (node, st, c) {
2662 c(node.tag, st, "Expression");
2663 c(node.quasi, st, "Expression");
2664};
2665base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
2666base$1.Class = function (node, st, c) {
2667 if (node.id) { c(node.id, st, "Pattern"); }
2668 if (node.superClass) { c(node.superClass, st, "Expression"); }
2669 c(node.body, st);
2670};
2671base$1.ClassBody = function (node, st, c) {
2672 for (var i = 0, list = node.body; i < list.length; i += 1)
2673 {
2674 var elt = list[i];
2675
2676 c(elt, st);
2677 }
2678};
2679base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
2680 if (node.computed) { c(node.key, st, "Expression"); }
2681 if (node.value) { c(node.value, st, "Expression"); }
2682};
2683
2684const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
2685const BinaryExpression$1 = 'BinaryExpression';
2686const BlockStatement$1 = 'BlockStatement';
2687const CallExpression$1 = 'CallExpression';
2688const ChainExpression$1 = 'ChainExpression';
2689const ConditionalExpression$1 = 'ConditionalExpression';
2690const ExpressionStatement$1 = 'ExpressionStatement';
2691const Identifier$1 = 'Identifier';
2692const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
2693const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
2694const LogicalExpression$1 = 'LogicalExpression';
2695const NewExpression$1 = 'NewExpression';
2696const Program$1 = 'Program';
2697const Property$1 = 'Property';
2698const ReturnStatement$1 = 'ReturnStatement';
2699const SequenceExpression$1 = 'SequenceExpression';
2700
2701// this looks ridiculous, but it prevents sourcemap tooling from mistaking
2702// this for an actual sourceMappingURL
2703let SOURCEMAPPING_URL = 'sourceMa';
2704SOURCEMAPPING_URL += 'ppingURL';
2705const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
2706const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
2707
2708// patch up acorn-walk until class-fields are officially supported
2709base$1.PropertyDefinition = function (node, st, c) {
2710 if (node.computed) {
2711 c(node.key, st, 'Expression');
2712 }
2713 if (node.value) {
2714 c(node.value, st, 'Expression');
2715 }
2716};
2717const ANNOTATION_KEY = '_rollupAnnotations';
2718const INVALID_COMMENT_KEY = '_rollupRemoved';
2719function handlePureAnnotationsOfNode(node, state, type = node.type) {
2720 const { annotations } = state;
2721 let comment = annotations[state.annotationIndex];
2722 while (comment && node.start >= comment.end) {
2723 markPureNode(node, comment, state.code);
2724 comment = annotations[++state.annotationIndex];
2725 }
2726 if (comment && comment.end <= node.end) {
2727 base$1[type](node, state, handlePureAnnotationsOfNode);
2728 while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
2729 ++state.annotationIndex;
2730 annotateNode(node, comment, false);
2731 }
2732 }
2733}
2734const neitherWithespaceNorBrackets = /[^\s(]/g;
2735const noWhitespace = /\S/g;
2736function markPureNode(node, comment, code) {
2737 const annotatedNodes = [];
2738 let invalidAnnotation;
2739 const codeInBetween = code.slice(comment.end, node.start);
2740 if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
2741 const parentStart = node.start;
2742 while (true) {
2743 annotatedNodes.push(node);
2744 switch (node.type) {
2745 case ExpressionStatement$1:
2746 case ChainExpression$1:
2747 node = node.expression;
2748 continue;
2749 case SequenceExpression$1:
2750 // if there are parentheses, the annotation would apply to the entire expression
2751 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
2752 node = node.expressions[0];
2753 continue;
2754 }
2755 invalidAnnotation = true;
2756 break;
2757 case ConditionalExpression$1:
2758 // if there are parentheses, the annotation would apply to the entire expression
2759 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
2760 node = node.test;
2761 continue;
2762 }
2763 invalidAnnotation = true;
2764 break;
2765 case LogicalExpression$1:
2766 case BinaryExpression$1:
2767 // if there are parentheses, the annotation would apply to the entire expression
2768 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
2769 node = node.left;
2770 continue;
2771 }
2772 invalidAnnotation = true;
2773 break;
2774 case CallExpression$1:
2775 case NewExpression$1:
2776 break;
2777 default:
2778 invalidAnnotation = true;
2779 }
2780 break;
2781 }
2782 }
2783 else {
2784 invalidAnnotation = true;
2785 }
2786 if (invalidAnnotation) {
2787 annotateNode(node, comment, false);
2788 }
2789 else {
2790 for (const node of annotatedNodes) {
2791 annotateNode(node, comment, true);
2792 }
2793 }
2794}
2795function doesNotMatchOutsideComment(code, forbiddenChars) {
2796 let nextMatch;
2797 while ((nextMatch = forbiddenChars.exec(code)) !== null) {
2798 if (nextMatch[0] === '/') {
2799 const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
2800 if (charCodeAfterSlash === 42 /*"*"*/) {
2801 forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
2802 continue;
2803 }
2804 else if (charCodeAfterSlash === 47 /*"/"*/) {
2805 forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
2806 continue;
2807 }
2808 }
2809 forbiddenChars.lastIndex = 0;
2810 return false;
2811 }
2812 return true;
2813}
2814const pureCommentRegex = /[@#]__PURE__/;
2815function addAnnotations(comments, esTreeAst, code) {
2816 const annotations = [];
2817 const sourceMappingComments = [];
2818 for (const comment of comments) {
2819 if (pureCommentRegex.test(comment.value)) {
2820 annotations.push(comment);
2821 }
2822 else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
2823 sourceMappingComments.push(comment);
2824 }
2825 }
2826 for (const comment of sourceMappingComments) {
2827 annotateNode(esTreeAst, comment, false);
2828 }
2829 handlePureAnnotationsOfNode(esTreeAst, {
2830 annotationIndex: 0,
2831 annotations,
2832 code
2833 });
2834}
2835function annotateNode(node, comment, valid) {
2836 const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
2837 const property = node[key];
2838 if (property) {
2839 property.push(comment);
2840 }
2841 else {
2842 node[key] = [comment];
2843 }
2844}
2845
2846const keys = {
2847 Literal: [],
2848 Program: ['body']
2849};
2850function getAndCreateKeys(esTreeNode) {
2851 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
2852 return keys[esTreeNode.type];
2853}
2854
2855const INCLUDE_PARAMETERS = 'variables';
2856class NodeBase extends ExpressionEntity {
2857 constructor(esTreeNode, parent, parentScope) {
2858 super();
2859 this.esTreeNode = esTreeNode;
2860 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
2861 this.parent = parent;
2862 this.context = parent.context;
2863 this.createScope(parentScope);
2864 this.parseNode(esTreeNode);
2865 this.initialise();
2866 this.context.magicString.addSourcemapLocation(this.start);
2867 this.context.magicString.addSourcemapLocation(this.end);
2868 }
2869 addExportedVariables(_variables, _exportNamesByVariable) { }
2870 /**
2871 * Override this to bind assignments to variables and do any initialisations that
2872 * require the scopes to be populated with variables.
2873 */
2874 bind() {
2875 for (const key of this.keys) {
2876 const value = this[key];
2877 if (value === null)
2878 continue;
2879 if (Array.isArray(value)) {
2880 for (const child of value) {
2881 if (child !== null)
2882 child.bind();
2883 }
2884 }
2885 else {
2886 value.bind();
2887 }
2888 }
2889 }
2890 /**
2891 * Override if this node should receive a different scope than the parent scope.
2892 */
2893 createScope(parentScope) {
2894 this.scope = parentScope;
2895 }
2896 hasEffects(context) {
2897 if (this.deoptimized === false)
2898 this.applyDeoptimizations();
2899 for (const key of this.keys) {
2900 const value = this[key];
2901 if (value === null)
2902 continue;
2903 if (Array.isArray(value)) {
2904 for (const child of value) {
2905 if (child !== null && child.hasEffects(context))
2906 return true;
2907 }
2908 }
2909 else if (value.hasEffects(context))
2910 return true;
2911 }
2912 return false;
2913 }
2914 include(context, includeChildrenRecursively) {
2915 if (this.deoptimized === false)
2916 this.applyDeoptimizations();
2917 this.included = true;
2918 for (const key of this.keys) {
2919 const value = this[key];
2920 if (value === null)
2921 continue;
2922 if (Array.isArray(value)) {
2923 for (const child of value) {
2924 if (child !== null)
2925 child.include(context, includeChildrenRecursively);
2926 }
2927 }
2928 else {
2929 value.include(context, includeChildrenRecursively);
2930 }
2931 }
2932 }
2933 includeAsSingleStatement(context, includeChildrenRecursively) {
2934 this.include(context, includeChildrenRecursively);
2935 }
2936 /**
2937 * Override to perform special initialisation steps after the scope is initialised
2938 */
2939 initialise() { }
2940 insertSemicolon(code) {
2941 if (code.original[this.end - 1] !== ';') {
2942 code.appendLeft(this.end, ';');
2943 }
2944 }
2945 parseNode(esTreeNode) {
2946 for (const [key, value] of Object.entries(esTreeNode)) {
2947 // That way, we can override this function to add custom initialisation and then call super.parseNode
2948 if (this.hasOwnProperty(key))
2949 continue;
2950 if (key.charCodeAt(0) === 95 /* _ */) {
2951 if (key === ANNOTATION_KEY) {
2952 this.annotations = value;
2953 }
2954 else if (key === INVALID_COMMENT_KEY) {
2955 for (const { start, end } of value)
2956 this.context.magicString.remove(start, end);
2957 }
2958 }
2959 else if (typeof value !== 'object' || value === null) {
2960 this[key] = value;
2961 }
2962 else if (Array.isArray(value)) {
2963 this[key] = [];
2964 for (const child of value) {
2965 this[key].push(child === null
2966 ? null
2967 : new (this.context.nodeConstructors[child.type] ||
2968 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
2969 }
2970 }
2971 else {
2972 this[key] = new (this.context.nodeConstructors[value.type] ||
2973 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
2974 }
2975 }
2976 }
2977 render(code, options) {
2978 for (const key of this.keys) {
2979 const value = this[key];
2980 if (value === null)
2981 continue;
2982 if (Array.isArray(value)) {
2983 for (const child of value) {
2984 if (child !== null)
2985 child.render(code, options);
2986 }
2987 }
2988 else {
2989 value.render(code, options);
2990 }
2991 }
2992 }
2993 shouldBeIncluded(context) {
2994 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
2995 }
2996 applyDeoptimizations() { }
2997}
2998
2999class ExportAllDeclaration extends NodeBase {
3000 hasEffects() {
3001 return false;
3002 }
3003 initialise() {
3004 this.context.addExport(this);
3005 }
3006 render(code, _options, nodeRenderOptions) {
3007 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
3008 }
3009}
3010ExportAllDeclaration.prototype.needsBoundaries = true;
3011
3012function treeshakeNode(node, code, start, end) {
3013 code.remove(start, end);
3014 if (node.annotations) {
3015 for (const annotation of node.annotations) {
3016 if (annotation.start < start) {
3017 code.remove(annotation.start, annotation.end);
3018 }
3019 else {
3020 return;
3021 }
3022 }
3023 }
3024}
3025function removeAnnotations(node, code) {
3026 if (!node.annotations && node.parent.type === ExpressionStatement$1) {
3027 node = node.parent;
3028 }
3029 if (node.annotations) {
3030 for (const annotation of node.annotations) {
3031 code.remove(annotation.start, annotation.end);
3032 }
3033 }
3034}
3035
3036const NO_SEMICOLON = { isNoStatement: true };
3037// This assumes there are only white-space and comments between start and the string we are looking for
3038function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
3039 let searchPos, charCodeAfterSlash;
3040 searchPos = code.indexOf(searchString, start);
3041 while (true) {
3042 start = code.indexOf('/', start);
3043 if (start === -1 || start >= searchPos)
3044 return searchPos;
3045 charCodeAfterSlash = code.charCodeAt(++start);
3046 ++start;
3047 // With our assumption, '/' always starts a comment. Determine comment type:
3048 start =
3049 charCodeAfterSlash === 47 /*"/"*/
3050 ? code.indexOf('\n', start) + 1
3051 : code.indexOf('*/', start) + 2;
3052 if (start > searchPos) {
3053 searchPos = code.indexOf(searchString, start);
3054 }
3055 }
3056}
3057const NON_WHITESPACE = /\S/g;
3058function findNonWhiteSpace(code, index) {
3059 NON_WHITESPACE.lastIndex = index;
3060 const result = NON_WHITESPACE.exec(code);
3061 return result.index;
3062}
3063// This assumes "code" only contains white-space and comments
3064// Returns position of line-comment if applicable
3065function findFirstLineBreakOutsideComment(code) {
3066 let lineBreakPos, charCodeAfterSlash, start = 0;
3067 lineBreakPos = code.indexOf('\n', start);
3068 while (true) {
3069 start = code.indexOf('/', start);
3070 if (start === -1 || start > lineBreakPos)
3071 return [lineBreakPos, lineBreakPos + 1];
3072 // With our assumption, '/' always starts a comment. Determine comment type:
3073 charCodeAfterSlash = code.charCodeAt(start + 1);
3074 if (charCodeAfterSlash === 47 /*"/"*/)
3075 return [start, lineBreakPos + 1];
3076 start = code.indexOf('*/', start + 3) + 2;
3077 if (start > lineBreakPos) {
3078 lineBreakPos = code.indexOf('\n', start);
3079 }
3080 }
3081}
3082function renderStatementList(statements, code, start, end, options) {
3083 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
3084 let nextNode = statements[0];
3085 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
3086 if (nextNodeNeedsBoundaries) {
3087 nextNodeStart =
3088 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
3089 }
3090 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
3091 currentNode = nextNode;
3092 currentNodeStart = nextNodeStart;
3093 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
3094 nextNode = statements[nextIndex];
3095 nextNodeNeedsBoundaries =
3096 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
3097 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
3098 nextNodeStart =
3099 currentNode.end +
3100 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
3101 if (currentNode.included) {
3102 currentNodeNeedsBoundaries
3103 ? currentNode.render(code, options, {
3104 end: nextNodeStart,
3105 start: currentNodeStart
3106 })
3107 : currentNode.render(code, options);
3108 }
3109 else {
3110 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
3111 }
3112 }
3113 else {
3114 currentNode.render(code, options);
3115 }
3116 }
3117}
3118// This assumes that the first character is not part of the first node
3119function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
3120 const splitUpNodes = [];
3121 let node, nextNode, nextNodeStart, contentEnd, char;
3122 let separator = start - 1;
3123 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
3124 nextNode = nodes[nextIndex];
3125 if (node !== undefined) {
3126 separator =
3127 node.end +
3128 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
3129 }
3130 nextNodeStart = contentEnd =
3131 separator +
3132 1 +
3133 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
3134 while (((char = code.original.charCodeAt(nextNodeStart)),
3135 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
3136 nextNodeStart++;
3137 if (node !== undefined) {
3138 splitUpNodes.push({
3139 contentEnd,
3140 end: nextNodeStart,
3141 node,
3142 separator,
3143 start
3144 });
3145 }
3146 node = nextNode;
3147 start = nextNodeStart;
3148 }
3149 splitUpNodes.push({
3150 contentEnd: end,
3151 end,
3152 node: node,
3153 separator: null,
3154 start
3155 });
3156 return splitUpNodes;
3157}
3158// This assumes there are only white-space and comments between start and end
3159function removeLineBreaks(code, start, end) {
3160 while (true) {
3161 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
3162 if (removeStart === -1) {
3163 break;
3164 }
3165 code.remove(start + removeStart, (start += removeEnd));
3166 }
3167}
3168
3169function getSystemExportStatement(exportedVariables, options) {
3170 const _ = options.compact ? '' : ' ';
3171 if (exportedVariables.length === 1 &&
3172 options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
3173 const variable = exportedVariables[0];
3174 return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
3175 }
3176 else {
3177 return `exports({${_}${exportedVariables
3178 .map(variable => {
3179 return options.exportNamesByVariable
3180 .get(variable)
3181 .map(exportName => `${exportName}:${_}${variable.getName()}`)
3182 .join(`,${_}`);
3183 })
3184 .join(`,${_}`)}${_}})`;
3185 }
3186}
3187function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
3188 const _ = options.compact ? '' : ' ';
3189 const s = options.compact ? '' : ';';
3190 return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
3191 .map(variable => {
3192 return options.exportNamesByVariable
3193 .get(variable)
3194 .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
3195 .join(`,${_}`);
3196 })
3197 .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
3198}
3199
3200const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
3201const base = 64;
3202function toBase64(num) {
3203 let outStr = '';
3204 do {
3205 const curDigit = num % base;
3206 num = Math.floor(num / base);
3207 outStr = chars[curDigit] + outStr;
3208 } while (num !== 0);
3209 return outStr;
3210}
3211
3212function getSafeName(baseName, usedNames) {
3213 let safeName = baseName;
3214 let count = 1;
3215 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
3216 safeName = `${baseName}$${toBase64(count++)}`;
3217 }
3218 usedNames.add(safeName);
3219 return safeName;
3220}
3221
3222const NO_ARGS = [];
3223
3224function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
3225 return Object.create(inheritedDescriptions, memberDescriptions);
3226}
3227const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
3228 getLiteralValueAtPath() {
3229 return undefined;
3230 }
3231})();
3232const returnsUnknown = {
3233 value: {
3234 callsArgs: null,
3235 returns: UNKNOWN_EXPRESSION
3236 }
3237};
3238const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
3239 getReturnExpressionWhenCalledAtPath(path) {
3240 if (path.length === 1) {
3241 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
3242 }
3243 return UNKNOWN_EXPRESSION;
3244 }
3245 hasEffectsWhenAccessedAtPath(path) {
3246 return path.length > 1;
3247 }
3248 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3249 if (path.length === 1) {
3250 return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], callOptions, context);
3251 }
3252 return true;
3253 }
3254})();
3255const returnsBoolean = {
3256 value: {
3257 callsArgs: null,
3258 returns: UNKNOWN_LITERAL_BOOLEAN
3259 }
3260};
3261const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
3262 getReturnExpressionWhenCalledAtPath(path) {
3263 if (path.length === 1) {
3264 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
3265 }
3266 return UNKNOWN_EXPRESSION;
3267 }
3268 hasEffectsWhenAccessedAtPath(path) {
3269 return path.length > 1;
3270 }
3271 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3272 if (path.length === 1) {
3273 return hasMemberEffectWhenCalled(literalNumberMembers, path[0], callOptions, context);
3274 }
3275 return true;
3276 }
3277})();
3278const returnsNumber = {
3279 value: {
3280 callsArgs: null,
3281 returns: UNKNOWN_LITERAL_NUMBER
3282 }
3283};
3284const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
3285 getReturnExpressionWhenCalledAtPath(path) {
3286 if (path.length === 1) {
3287 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
3288 }
3289 return UNKNOWN_EXPRESSION;
3290 }
3291 hasEffectsWhenAccessedAtPath(path) {
3292 return path.length > 1;
3293 }
3294 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3295 if (path.length === 1) {
3296 return hasMemberEffectWhenCalled(literalStringMembers, path[0], callOptions, context);
3297 }
3298 return true;
3299 }
3300})();
3301const returnsString = {
3302 value: {
3303 callsArgs: null,
3304 returns: UNKNOWN_LITERAL_STRING
3305 }
3306};
3307const objectMembers = assembleMemberDescriptions({
3308 hasOwnProperty: returnsBoolean,
3309 isPrototypeOf: returnsBoolean,
3310 propertyIsEnumerable: returnsBoolean,
3311 toLocaleString: returnsString,
3312 toString: returnsString,
3313 valueOf: returnsUnknown
3314});
3315const literalBooleanMembers = assembleMemberDescriptions({
3316 valueOf: returnsBoolean
3317}, objectMembers);
3318const literalNumberMembers = assembleMemberDescriptions({
3319 toExponential: returnsString,
3320 toFixed: returnsString,
3321 toLocaleString: returnsString,
3322 toPrecision: returnsString,
3323 valueOf: returnsNumber
3324}, objectMembers);
3325const literalStringMembers = assembleMemberDescriptions({
3326 charAt: returnsString,
3327 charCodeAt: returnsNumber,
3328 codePointAt: returnsNumber,
3329 concat: returnsString,
3330 endsWith: returnsBoolean,
3331 includes: returnsBoolean,
3332 indexOf: returnsNumber,
3333 lastIndexOf: returnsNumber,
3334 localeCompare: returnsNumber,
3335 match: returnsBoolean,
3336 normalize: returnsString,
3337 padEnd: returnsString,
3338 padStart: returnsString,
3339 repeat: returnsString,
3340 replace: {
3341 value: {
3342 callsArgs: [1],
3343 returns: UNKNOWN_LITERAL_STRING
3344 }
3345 },
3346 search: returnsNumber,
3347 slice: returnsString,
3348 split: returnsUnknown,
3349 startsWith: returnsBoolean,
3350 substr: returnsString,
3351 substring: returnsString,
3352 toLocaleLowerCase: returnsString,
3353 toLocaleUpperCase: returnsString,
3354 toLowerCase: returnsString,
3355 toUpperCase: returnsString,
3356 trim: returnsString,
3357 valueOf: returnsString
3358}, objectMembers);
3359function getLiteralMembersForValue(value) {
3360 switch (typeof value) {
3361 case 'boolean':
3362 return literalBooleanMembers;
3363 case 'number':
3364 return literalNumberMembers;
3365 case 'string':
3366 return literalStringMembers;
3367 default:
3368 return Object.create(null);
3369 }
3370}
3371function hasMemberEffectWhenCalled(members, memberName, callOptions, context) {
3372 if (typeof memberName !== 'string' || !members[memberName]) {
3373 return true;
3374 }
3375 if (!members[memberName].callsArgs)
3376 return false;
3377 for (const argIndex of members[memberName].callsArgs) {
3378 if (callOptions.args[argIndex] &&
3379 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
3380 args: NO_ARGS,
3381 thisParam: null,
3382 withNew: false
3383 }, context))
3384 return true;
3385 }
3386 return false;
3387}
3388function getMemberReturnExpressionWhenCalled(members, memberName) {
3389 if (typeof memberName !== 'string' || !members[memberName])
3390 return UNKNOWN_EXPRESSION;
3391 return members[memberName].returns;
3392}
3393
3394class LocalVariable extends Variable {
3395 constructor(name, declarator, init, context) {
3396 super(name);
3397 this.calledFromTryStatement = false;
3398 this.additionalInitializers = null;
3399 this.expressionsToBeDeoptimized = [];
3400 this.declarations = declarator ? [declarator] : [];
3401 this.init = init;
3402 this.deoptimizationTracker = context.deoptimizationTracker;
3403 this.module = context.module;
3404 }
3405 addDeclaration(identifier, init) {
3406 this.declarations.push(identifier);
3407 const additionalInitializers = this.markInitializersForDeoptimization();
3408 if (init !== null) {
3409 additionalInitializers.push(init);
3410 }
3411 }
3412 consolidateInitializers() {
3413 if (this.additionalInitializers !== null) {
3414 for (const initializer of this.additionalInitializers) {
3415 initializer.deoptimizePath(UNKNOWN_PATH);
3416 }
3417 this.additionalInitializers = null;
3418 }
3419 }
3420 deoptimizePath(path) {
3421 var _a, _b;
3422 if (this.isReassigned ||
3423 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
3424 return;
3425 }
3426 if (path.length === 0) {
3427 if (!this.isReassigned) {
3428 this.isReassigned = true;
3429 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
3430 this.expressionsToBeDeoptimized = [];
3431 for (const expression of expressionsToBeDeoptimized) {
3432 expression.deoptimizeCache();
3433 }
3434 (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
3435 }
3436 }
3437 else {
3438 (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
3439 }
3440 }
3441 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
3442 if (this.isReassigned || !this.init) {
3443 return thisParameter.deoptimizePath(UNKNOWN_PATH);
3444 }
3445 recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker), undefined);
3446 }
3447 getLiteralValueAtPath(path, recursionTracker, origin) {
3448 if (this.isReassigned || !this.init) {
3449 return UnknownValue;
3450 }
3451 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
3452 this.expressionsToBeDeoptimized.push(origin);
3453 return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
3454 }, UnknownValue);
3455 }
3456 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
3457 if (this.isReassigned || !this.init) {
3458 return UNKNOWN_EXPRESSION;
3459 }
3460 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
3461 this.expressionsToBeDeoptimized.push(origin);
3462 return this.init.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
3463 }, UNKNOWN_EXPRESSION);
3464 }
3465 hasEffectsWhenAccessedAtPath(path, context) {
3466 if (this.isReassigned)
3467 return true;
3468 return (this.init &&
3469 !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
3470 this.init.hasEffectsWhenAccessedAtPath(path, context));
3471 }
3472 hasEffectsWhenAssignedAtPath(path, context) {
3473 if (this.included)
3474 return true;
3475 if (path.length === 0)
3476 return false;
3477 if (this.isReassigned)
3478 return true;
3479 return (this.init &&
3480 !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
3481 this.init.hasEffectsWhenAssignedAtPath(path, context));
3482 }
3483 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3484 if (this.isReassigned)
3485 return true;
3486 return (this.init &&
3487 !(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
3488 this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
3489 }
3490 include() {
3491 if (!this.included) {
3492 this.included = true;
3493 for (const declaration of this.declarations) {
3494 // If node is a default export, it can save a tree-shaking run to include the full declaration now
3495 if (!declaration.included)
3496 declaration.include(createInclusionContext(), false);
3497 let node = declaration.parent;
3498 while (!node.included) {
3499 // We do not want to properly include parents in case they are part of a dead branch
3500 // in which case .include() might pull in more dead code
3501 node.included = true;
3502 if (node.type === Program$1)
3503 break;
3504 node = node.parent;
3505 }
3506 }
3507 }
3508 }
3509 includeCallArguments(context, args) {
3510 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
3511 for (const arg of args) {
3512 arg.include(context, false);
3513 }
3514 }
3515 else if (this.init) {
3516 context.includedCallArguments.add(this.init);
3517 this.init.includeCallArguments(context, args);
3518 context.includedCallArguments.delete(this.init);
3519 }
3520 }
3521 markCalledFromTryStatement() {
3522 this.calledFromTryStatement = true;
3523 }
3524 markInitializersForDeoptimization() {
3525 if (this.additionalInitializers === null) {
3526 this.additionalInitializers = this.init === null ? [] : [this.init];
3527 this.init = UNKNOWN_EXPRESSION;
3528 this.isReassigned = true;
3529 }
3530 return this.additionalInitializers;
3531 }
3532}
3533
3534class Scope$1 {
3535 constructor() {
3536 this.children = [];
3537 this.variables = new Map();
3538 }
3539 addDeclaration(identifier, context, init, _isHoisted) {
3540 const name = identifier.name;
3541 let variable = this.variables.get(name);
3542 if (variable) {
3543 variable.addDeclaration(identifier, init);
3544 }
3545 else {
3546 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
3547 this.variables.set(name, variable);
3548 }
3549 return variable;
3550 }
3551 contains(name) {
3552 return this.variables.has(name);
3553 }
3554 findVariable(_name) {
3555 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
3556 }
3557}
3558
3559class ChildScope extends Scope$1 {
3560 constructor(parent) {
3561 super();
3562 this.accessedOutsideVariables = new Map();
3563 this.parent = parent;
3564 parent.children.push(this);
3565 }
3566 addAccessedDynamicImport(importExpression) {
3567 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
3568 if (this.parent instanceof ChildScope) {
3569 this.parent.addAccessedDynamicImport(importExpression);
3570 }
3571 }
3572 addAccessedGlobals(globals, accessedGlobalsByScope) {
3573 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
3574 for (const name of globals) {
3575 accessedGlobals.add(name);
3576 }
3577 accessedGlobalsByScope.set(this, accessedGlobals);
3578 if (this.parent instanceof ChildScope) {
3579 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
3580 }
3581 }
3582 addNamespaceMemberAccess(name, variable) {
3583 this.accessedOutsideVariables.set(name, variable);
3584 this.parent.addNamespaceMemberAccess(name, variable);
3585 }
3586 addReturnExpression(expression) {
3587 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
3588 }
3589 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
3590 for (const variable of this.accessedOutsideVariables.values()) {
3591 if (variable.included) {
3592 usedNames.add(variable.getBaseVariableName());
3593 if (format === 'system' && exportNamesByVariable.has(variable)) {
3594 usedNames.add('exports');
3595 }
3596 }
3597 }
3598 const accessedGlobals = accessedGlobalsByScope.get(this);
3599 if (accessedGlobals) {
3600 for (const name of accessedGlobals) {
3601 usedNames.add(name);
3602 }
3603 }
3604 }
3605 contains(name) {
3606 return this.variables.has(name) || this.parent.contains(name);
3607 }
3608 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
3609 const usedNames = new Set();
3610 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
3611 if (this.accessedDynamicImports) {
3612 for (const importExpression of this.accessedDynamicImports) {
3613 if (importExpression.inlineNamespace) {
3614 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
3615 }
3616 }
3617 }
3618 for (const [name, variable] of this.variables) {
3619 if (variable.included || variable.alwaysRendered) {
3620 variable.setRenderNames(null, getSafeName(name, usedNames));
3621 }
3622 }
3623 for (const scope of this.children) {
3624 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
3625 }
3626 }
3627 findLexicalBoundary() {
3628 return this.parent.findLexicalBoundary();
3629 }
3630 findVariable(name) {
3631 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
3632 if (knownVariable) {
3633 return knownVariable;
3634 }
3635 const variable = this.parent.findVariable(name);
3636 this.accessedOutsideVariables.set(name, variable);
3637 return variable;
3638 }
3639}
3640
3641//@ts-check
3642/** @typedef { import('estree').Node} Node */
3643/** @typedef {Node | {
3644 * type: 'PropertyDefinition';
3645 * computed: boolean;
3646 * value: Node
3647 * }} NodeWithPropertyDefinition */
3648
3649/**
3650 *
3651 * @param {NodeWithPropertyDefinition} node
3652 * @param {NodeWithPropertyDefinition} parent
3653 * @returns boolean
3654 */
3655function is_reference (node, parent) {
3656 if (node.type === 'MemberExpression') {
3657 return !node.computed && is_reference(node.object, node);
3658 }
3659
3660 if (node.type === 'Identifier') {
3661 if (!parent) return true;
3662
3663 switch (parent.type) {
3664 // disregard `bar` in `foo.bar`
3665 case 'MemberExpression': return parent.computed || node === parent.object;
3666
3667 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
3668 case 'MethodDefinition': return parent.computed;
3669
3670 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
3671 case 'PropertyDefinition': return parent.computed || node === parent.value;
3672
3673 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
3674 case 'Property': return parent.computed || node === parent.value;
3675
3676 // disregard the `bar` in `export { foo as bar }` or
3677 // the foo in `import { foo as bar }`
3678 case 'ExportSpecifier':
3679 case 'ImportSpecifier': return node === parent.local;
3680
3681 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
3682 case 'LabeledStatement':
3683 case 'BreakStatement':
3684 case 'ContinueStatement': return false;
3685 default: return true;
3686 }
3687 }
3688
3689 return false;
3690}
3691
3692/* eslint sort-keys: "off" */
3693const ValueProperties = Symbol('Value Properties');
3694const PURE = { pure: true };
3695const IMPURE = { pure: false };
3696// We use shortened variables to reduce file size here
3697/* OBJECT */
3698const O = {
3699 __proto__: null,
3700 [ValueProperties]: IMPURE
3701};
3702/* PURE FUNCTION */
3703const PF = {
3704 __proto__: null,
3705 [ValueProperties]: PURE
3706};
3707/* CONSTRUCTOR */
3708const C = {
3709 __proto__: null,
3710 [ValueProperties]: IMPURE,
3711 prototype: O
3712};
3713/* PURE CONSTRUCTOR */
3714const PC = {
3715 __proto__: null,
3716 [ValueProperties]: PURE,
3717 prototype: O
3718};
3719const ARRAY_TYPE = {
3720 __proto__: null,
3721 [ValueProperties]: PURE,
3722 from: PF,
3723 of: PF,
3724 prototype: O
3725};
3726const INTL_MEMBER = {
3727 __proto__: null,
3728 [ValueProperties]: PURE,
3729 supportedLocalesOf: PC
3730};
3731const knownGlobals = {
3732 // Placeholders for global objects to avoid shape mutations
3733 global: O,
3734 globalThis: O,
3735 self: O,
3736 window: O,
3737 // Common globals
3738 __proto__: null,
3739 [ValueProperties]: IMPURE,
3740 Array: {
3741 __proto__: null,
3742 [ValueProperties]: IMPURE,
3743 from: O,
3744 isArray: PF,
3745 of: PF,
3746 prototype: O
3747 },
3748 ArrayBuffer: {
3749 __proto__: null,
3750 [ValueProperties]: PURE,
3751 isView: PF,
3752 prototype: O
3753 },
3754 Atomics: O,
3755 BigInt: C,
3756 BigInt64Array: C,
3757 BigUint64Array: C,
3758 Boolean: PC,
3759 constructor: C,
3760 DataView: PC,
3761 Date: {
3762 __proto__: null,
3763 [ValueProperties]: PURE,
3764 now: PF,
3765 parse: PF,
3766 prototype: O,
3767 UTC: PF
3768 },
3769 decodeURI: PF,
3770 decodeURIComponent: PF,
3771 encodeURI: PF,
3772 encodeURIComponent: PF,
3773 Error: PC,
3774 escape: PF,
3775 eval: O,
3776 EvalError: PC,
3777 Float32Array: ARRAY_TYPE,
3778 Float64Array: ARRAY_TYPE,
3779 Function: C,
3780 hasOwnProperty: O,
3781 Infinity: O,
3782 Int16Array: ARRAY_TYPE,
3783 Int32Array: ARRAY_TYPE,
3784 Int8Array: ARRAY_TYPE,
3785 isFinite: PF,
3786 isNaN: PF,
3787 isPrototypeOf: O,
3788 JSON: O,
3789 Map: PC,
3790 Math: {
3791 __proto__: null,
3792 [ValueProperties]: IMPURE,
3793 abs: PF,
3794 acos: PF,
3795 acosh: PF,
3796 asin: PF,
3797 asinh: PF,
3798 atan: PF,
3799 atan2: PF,
3800 atanh: PF,
3801 cbrt: PF,
3802 ceil: PF,
3803 clz32: PF,
3804 cos: PF,
3805 cosh: PF,
3806 exp: PF,
3807 expm1: PF,
3808 floor: PF,
3809 fround: PF,
3810 hypot: PF,
3811 imul: PF,
3812 log: PF,
3813 log10: PF,
3814 log1p: PF,
3815 log2: PF,
3816 max: PF,
3817 min: PF,
3818 pow: PF,
3819 random: PF,
3820 round: PF,
3821 sign: PF,
3822 sin: PF,
3823 sinh: PF,
3824 sqrt: PF,
3825 tan: PF,
3826 tanh: PF,
3827 trunc: PF
3828 },
3829 NaN: O,
3830 Number: {
3831 __proto__: null,
3832 [ValueProperties]: PURE,
3833 isFinite: PF,
3834 isInteger: PF,
3835 isNaN: PF,
3836 isSafeInteger: PF,
3837 parseFloat: PF,
3838 parseInt: PF,
3839 prototype: O
3840 },
3841 Object: {
3842 __proto__: null,
3843 [ValueProperties]: PURE,
3844 create: PF,
3845 getNotifier: PF,
3846 getOwn: PF,
3847 getOwnPropertyDescriptor: PF,
3848 getOwnPropertyNames: PF,
3849 getOwnPropertySymbols: PF,
3850 getPrototypeOf: PF,
3851 is: PF,
3852 isExtensible: PF,
3853 isFrozen: PF,
3854 isSealed: PF,
3855 keys: PF,
3856 prototype: O
3857 },
3858 parseFloat: PF,
3859 parseInt: PF,
3860 Promise: {
3861 __proto__: null,
3862 [ValueProperties]: IMPURE,
3863 all: O,
3864 prototype: O,
3865 race: O,
3866 reject: O,
3867 resolve: O
3868 },
3869 propertyIsEnumerable: O,
3870 Proxy: O,
3871 RangeError: PC,
3872 ReferenceError: PC,
3873 Reflect: O,
3874 RegExp: PC,
3875 Set: PC,
3876 SharedArrayBuffer: C,
3877 String: {
3878 __proto__: null,
3879 [ValueProperties]: PURE,
3880 fromCharCode: PF,
3881 fromCodePoint: PF,
3882 prototype: O,
3883 raw: PF
3884 },
3885 Symbol: {
3886 __proto__: null,
3887 [ValueProperties]: PURE,
3888 for: PF,
3889 keyFor: PF,
3890 prototype: O
3891 },
3892 SyntaxError: PC,
3893 toLocaleString: O,
3894 toString: O,
3895 TypeError: PC,
3896 Uint16Array: ARRAY_TYPE,
3897 Uint32Array: ARRAY_TYPE,
3898 Uint8Array: ARRAY_TYPE,
3899 Uint8ClampedArray: ARRAY_TYPE,
3900 // Technically, this is a global, but it needs special handling
3901 // undefined: ?,
3902 unescape: PF,
3903 URIError: PC,
3904 valueOf: O,
3905 WeakMap: PC,
3906 WeakSet: PC,
3907 // Additional globals shared by Node and Browser that are not strictly part of the language
3908 clearInterval: C,
3909 clearTimeout: C,
3910 console: O,
3911 Intl: {
3912 __proto__: null,
3913 [ValueProperties]: IMPURE,
3914 Collator: INTL_MEMBER,
3915 DateTimeFormat: INTL_MEMBER,
3916 ListFormat: INTL_MEMBER,
3917 NumberFormat: INTL_MEMBER,
3918 PluralRules: INTL_MEMBER,
3919 RelativeTimeFormat: INTL_MEMBER
3920 },
3921 setInterval: C,
3922 setTimeout: C,
3923 TextDecoder: C,
3924 TextEncoder: C,
3925 URL: C,
3926 URLSearchParams: C,
3927 // Browser specific globals
3928 AbortController: C,
3929 AbortSignal: C,
3930 addEventListener: O,
3931 alert: O,
3932 AnalyserNode: C,
3933 Animation: C,
3934 AnimationEvent: C,
3935 applicationCache: O,
3936 ApplicationCache: C,
3937 ApplicationCacheErrorEvent: C,
3938 atob: O,
3939 Attr: C,
3940 Audio: C,
3941 AudioBuffer: C,
3942 AudioBufferSourceNode: C,
3943 AudioContext: C,
3944 AudioDestinationNode: C,
3945 AudioListener: C,
3946 AudioNode: C,
3947 AudioParam: C,
3948 AudioProcessingEvent: C,
3949 AudioScheduledSourceNode: C,
3950 AudioWorkletNode: C,
3951 BarProp: C,
3952 BaseAudioContext: C,
3953 BatteryManager: C,
3954 BeforeUnloadEvent: C,
3955 BiquadFilterNode: C,
3956 Blob: C,
3957 BlobEvent: C,
3958 blur: O,
3959 BroadcastChannel: C,
3960 btoa: O,
3961 ByteLengthQueuingStrategy: C,
3962 Cache: C,
3963 caches: O,
3964 CacheStorage: C,
3965 cancelAnimationFrame: O,
3966 cancelIdleCallback: O,
3967 CanvasCaptureMediaStreamTrack: C,
3968 CanvasGradient: C,
3969 CanvasPattern: C,
3970 CanvasRenderingContext2D: C,
3971 ChannelMergerNode: C,
3972 ChannelSplitterNode: C,
3973 CharacterData: C,
3974 clientInformation: O,
3975 ClipboardEvent: C,
3976 close: O,
3977 closed: O,
3978 CloseEvent: C,
3979 Comment: C,
3980 CompositionEvent: C,
3981 confirm: O,
3982 ConstantSourceNode: C,
3983 ConvolverNode: C,
3984 CountQueuingStrategy: C,
3985 createImageBitmap: O,
3986 Credential: C,
3987 CredentialsContainer: C,
3988 crypto: O,
3989 Crypto: C,
3990 CryptoKey: C,
3991 CSS: C,
3992 CSSConditionRule: C,
3993 CSSFontFaceRule: C,
3994 CSSGroupingRule: C,
3995 CSSImportRule: C,
3996 CSSKeyframeRule: C,
3997 CSSKeyframesRule: C,
3998 CSSMediaRule: C,
3999 CSSNamespaceRule: C,
4000 CSSPageRule: C,
4001 CSSRule: C,
4002 CSSRuleList: C,
4003 CSSStyleDeclaration: C,
4004 CSSStyleRule: C,
4005 CSSStyleSheet: C,
4006 CSSSupportsRule: C,
4007 CustomElementRegistry: C,
4008 customElements: O,
4009 CustomEvent: C,
4010 DataTransfer: C,
4011 DataTransferItem: C,
4012 DataTransferItemList: C,
4013 defaultstatus: O,
4014 defaultStatus: O,
4015 DelayNode: C,
4016 DeviceMotionEvent: C,
4017 DeviceOrientationEvent: C,
4018 devicePixelRatio: O,
4019 dispatchEvent: O,
4020 document: O,
4021 Document: C,
4022 DocumentFragment: C,
4023 DocumentType: C,
4024 DOMError: C,
4025 DOMException: C,
4026 DOMImplementation: C,
4027 DOMMatrix: C,
4028 DOMMatrixReadOnly: C,
4029 DOMParser: C,
4030 DOMPoint: C,
4031 DOMPointReadOnly: C,
4032 DOMQuad: C,
4033 DOMRect: C,
4034 DOMRectReadOnly: C,
4035 DOMStringList: C,
4036 DOMStringMap: C,
4037 DOMTokenList: C,
4038 DragEvent: C,
4039 DynamicsCompressorNode: C,
4040 Element: C,
4041 ErrorEvent: C,
4042 Event: C,
4043 EventSource: C,
4044 EventTarget: C,
4045 external: O,
4046 fetch: O,
4047 File: C,
4048 FileList: C,
4049 FileReader: C,
4050 find: O,
4051 focus: O,
4052 FocusEvent: C,
4053 FontFace: C,
4054 FontFaceSetLoadEvent: C,
4055 FormData: C,
4056 frames: O,
4057 GainNode: C,
4058 Gamepad: C,
4059 GamepadButton: C,
4060 GamepadEvent: C,
4061 getComputedStyle: O,
4062 getSelection: O,
4063 HashChangeEvent: C,
4064 Headers: C,
4065 history: O,
4066 History: C,
4067 HTMLAllCollection: C,
4068 HTMLAnchorElement: C,
4069 HTMLAreaElement: C,
4070 HTMLAudioElement: C,
4071 HTMLBaseElement: C,
4072 HTMLBodyElement: C,
4073 HTMLBRElement: C,
4074 HTMLButtonElement: C,
4075 HTMLCanvasElement: C,
4076 HTMLCollection: C,
4077 HTMLContentElement: C,
4078 HTMLDataElement: C,
4079 HTMLDataListElement: C,
4080 HTMLDetailsElement: C,
4081 HTMLDialogElement: C,
4082 HTMLDirectoryElement: C,
4083 HTMLDivElement: C,
4084 HTMLDListElement: C,
4085 HTMLDocument: C,
4086 HTMLElement: C,
4087 HTMLEmbedElement: C,
4088 HTMLFieldSetElement: C,
4089 HTMLFontElement: C,
4090 HTMLFormControlsCollection: C,
4091 HTMLFormElement: C,
4092 HTMLFrameElement: C,
4093 HTMLFrameSetElement: C,
4094 HTMLHeadElement: C,
4095 HTMLHeadingElement: C,
4096 HTMLHRElement: C,
4097 HTMLHtmlElement: C,
4098 HTMLIFrameElement: C,
4099 HTMLImageElement: C,
4100 HTMLInputElement: C,
4101 HTMLLabelElement: C,
4102 HTMLLegendElement: C,
4103 HTMLLIElement: C,
4104 HTMLLinkElement: C,
4105 HTMLMapElement: C,
4106 HTMLMarqueeElement: C,
4107 HTMLMediaElement: C,
4108 HTMLMenuElement: C,
4109 HTMLMetaElement: C,
4110 HTMLMeterElement: C,
4111 HTMLModElement: C,
4112 HTMLObjectElement: C,
4113 HTMLOListElement: C,
4114 HTMLOptGroupElement: C,
4115 HTMLOptionElement: C,
4116 HTMLOptionsCollection: C,
4117 HTMLOutputElement: C,
4118 HTMLParagraphElement: C,
4119 HTMLParamElement: C,
4120 HTMLPictureElement: C,
4121 HTMLPreElement: C,
4122 HTMLProgressElement: C,
4123 HTMLQuoteElement: C,
4124 HTMLScriptElement: C,
4125 HTMLSelectElement: C,
4126 HTMLShadowElement: C,
4127 HTMLSlotElement: C,
4128 HTMLSourceElement: C,
4129 HTMLSpanElement: C,
4130 HTMLStyleElement: C,
4131 HTMLTableCaptionElement: C,
4132 HTMLTableCellElement: C,
4133 HTMLTableColElement: C,
4134 HTMLTableElement: C,
4135 HTMLTableRowElement: C,
4136 HTMLTableSectionElement: C,
4137 HTMLTemplateElement: C,
4138 HTMLTextAreaElement: C,
4139 HTMLTimeElement: C,
4140 HTMLTitleElement: C,
4141 HTMLTrackElement: C,
4142 HTMLUListElement: C,
4143 HTMLUnknownElement: C,
4144 HTMLVideoElement: C,
4145 IDBCursor: C,
4146 IDBCursorWithValue: C,
4147 IDBDatabase: C,
4148 IDBFactory: C,
4149 IDBIndex: C,
4150 IDBKeyRange: C,
4151 IDBObjectStore: C,
4152 IDBOpenDBRequest: C,
4153 IDBRequest: C,
4154 IDBTransaction: C,
4155 IDBVersionChangeEvent: C,
4156 IdleDeadline: C,
4157 IIRFilterNode: C,
4158 Image: C,
4159 ImageBitmap: C,
4160 ImageBitmapRenderingContext: C,
4161 ImageCapture: C,
4162 ImageData: C,
4163 indexedDB: O,
4164 innerHeight: O,
4165 innerWidth: O,
4166 InputEvent: C,
4167 IntersectionObserver: C,
4168 IntersectionObserverEntry: C,
4169 isSecureContext: O,
4170 KeyboardEvent: C,
4171 KeyframeEffect: C,
4172 length: O,
4173 localStorage: O,
4174 location: O,
4175 Location: C,
4176 locationbar: O,
4177 matchMedia: O,
4178 MediaDeviceInfo: C,
4179 MediaDevices: C,
4180 MediaElementAudioSourceNode: C,
4181 MediaEncryptedEvent: C,
4182 MediaError: C,
4183 MediaKeyMessageEvent: C,
4184 MediaKeySession: C,
4185 MediaKeyStatusMap: C,
4186 MediaKeySystemAccess: C,
4187 MediaList: C,
4188 MediaQueryList: C,
4189 MediaQueryListEvent: C,
4190 MediaRecorder: C,
4191 MediaSettingsRange: C,
4192 MediaSource: C,
4193 MediaStream: C,
4194 MediaStreamAudioDestinationNode: C,
4195 MediaStreamAudioSourceNode: C,
4196 MediaStreamEvent: C,
4197 MediaStreamTrack: C,
4198 MediaStreamTrackEvent: C,
4199 menubar: O,
4200 MessageChannel: C,
4201 MessageEvent: C,
4202 MessagePort: C,
4203 MIDIAccess: C,
4204 MIDIConnectionEvent: C,
4205 MIDIInput: C,
4206 MIDIInputMap: C,
4207 MIDIMessageEvent: C,
4208 MIDIOutput: C,
4209 MIDIOutputMap: C,
4210 MIDIPort: C,
4211 MimeType: C,
4212 MimeTypeArray: C,
4213 MouseEvent: C,
4214 moveBy: O,
4215 moveTo: O,
4216 MutationEvent: C,
4217 MutationObserver: C,
4218 MutationRecord: C,
4219 name: O,
4220 NamedNodeMap: C,
4221 NavigationPreloadManager: C,
4222 navigator: O,
4223 Navigator: C,
4224 NetworkInformation: C,
4225 Node: C,
4226 NodeFilter: O,
4227 NodeIterator: C,
4228 NodeList: C,
4229 Notification: C,
4230 OfflineAudioCompletionEvent: C,
4231 OfflineAudioContext: C,
4232 offscreenBuffering: O,
4233 OffscreenCanvas: C,
4234 open: O,
4235 openDatabase: O,
4236 Option: C,
4237 origin: O,
4238 OscillatorNode: C,
4239 outerHeight: O,
4240 outerWidth: O,
4241 PageTransitionEvent: C,
4242 pageXOffset: O,
4243 pageYOffset: O,
4244 PannerNode: C,
4245 parent: O,
4246 Path2D: C,
4247 PaymentAddress: C,
4248 PaymentRequest: C,
4249 PaymentRequestUpdateEvent: C,
4250 PaymentResponse: C,
4251 performance: O,
4252 Performance: C,
4253 PerformanceEntry: C,
4254 PerformanceLongTaskTiming: C,
4255 PerformanceMark: C,
4256 PerformanceMeasure: C,
4257 PerformanceNavigation: C,
4258 PerformanceNavigationTiming: C,
4259 PerformanceObserver: C,
4260 PerformanceObserverEntryList: C,
4261 PerformancePaintTiming: C,
4262 PerformanceResourceTiming: C,
4263 PerformanceTiming: C,
4264 PeriodicWave: C,
4265 Permissions: C,
4266 PermissionStatus: C,
4267 personalbar: O,
4268 PhotoCapabilities: C,
4269 Plugin: C,
4270 PluginArray: C,
4271 PointerEvent: C,
4272 PopStateEvent: C,
4273 postMessage: O,
4274 Presentation: C,
4275 PresentationAvailability: C,
4276 PresentationConnection: C,
4277 PresentationConnectionAvailableEvent: C,
4278 PresentationConnectionCloseEvent: C,
4279 PresentationConnectionList: C,
4280 PresentationReceiver: C,
4281 PresentationRequest: C,
4282 print: O,
4283 ProcessingInstruction: C,
4284 ProgressEvent: C,
4285 PromiseRejectionEvent: C,
4286 prompt: O,
4287 PushManager: C,
4288 PushSubscription: C,
4289 PushSubscriptionOptions: C,
4290 queueMicrotask: O,
4291 RadioNodeList: C,
4292 Range: C,
4293 ReadableStream: C,
4294 RemotePlayback: C,
4295 removeEventListener: O,
4296 Request: C,
4297 requestAnimationFrame: O,
4298 requestIdleCallback: O,
4299 resizeBy: O,
4300 ResizeObserver: C,
4301 ResizeObserverEntry: C,
4302 resizeTo: O,
4303 Response: C,
4304 RTCCertificate: C,
4305 RTCDataChannel: C,
4306 RTCDataChannelEvent: C,
4307 RTCDtlsTransport: C,
4308 RTCIceCandidate: C,
4309 RTCIceTransport: C,
4310 RTCPeerConnection: C,
4311 RTCPeerConnectionIceEvent: C,
4312 RTCRtpReceiver: C,
4313 RTCRtpSender: C,
4314 RTCSctpTransport: C,
4315 RTCSessionDescription: C,
4316 RTCStatsReport: C,
4317 RTCTrackEvent: C,
4318 screen: O,
4319 Screen: C,
4320 screenLeft: O,
4321 ScreenOrientation: C,
4322 screenTop: O,
4323 screenX: O,
4324 screenY: O,
4325 ScriptProcessorNode: C,
4326 scroll: O,
4327 scrollbars: O,
4328 scrollBy: O,
4329 scrollTo: O,
4330 scrollX: O,
4331 scrollY: O,
4332 SecurityPolicyViolationEvent: C,
4333 Selection: C,
4334 ServiceWorker: C,
4335 ServiceWorkerContainer: C,
4336 ServiceWorkerRegistration: C,
4337 sessionStorage: O,
4338 ShadowRoot: C,
4339 SharedWorker: C,
4340 SourceBuffer: C,
4341 SourceBufferList: C,
4342 speechSynthesis: O,
4343 SpeechSynthesisEvent: C,
4344 SpeechSynthesisUtterance: C,
4345 StaticRange: C,
4346 status: O,
4347 statusbar: O,
4348 StereoPannerNode: C,
4349 stop: O,
4350 Storage: C,
4351 StorageEvent: C,
4352 StorageManager: C,
4353 styleMedia: O,
4354 StyleSheet: C,
4355 StyleSheetList: C,
4356 SubtleCrypto: C,
4357 SVGAElement: C,
4358 SVGAngle: C,
4359 SVGAnimatedAngle: C,
4360 SVGAnimatedBoolean: C,
4361 SVGAnimatedEnumeration: C,
4362 SVGAnimatedInteger: C,
4363 SVGAnimatedLength: C,
4364 SVGAnimatedLengthList: C,
4365 SVGAnimatedNumber: C,
4366 SVGAnimatedNumberList: C,
4367 SVGAnimatedPreserveAspectRatio: C,
4368 SVGAnimatedRect: C,
4369 SVGAnimatedString: C,
4370 SVGAnimatedTransformList: C,
4371 SVGAnimateElement: C,
4372 SVGAnimateMotionElement: C,
4373 SVGAnimateTransformElement: C,
4374 SVGAnimationElement: C,
4375 SVGCircleElement: C,
4376 SVGClipPathElement: C,
4377 SVGComponentTransferFunctionElement: C,
4378 SVGDefsElement: C,
4379 SVGDescElement: C,
4380 SVGDiscardElement: C,
4381 SVGElement: C,
4382 SVGEllipseElement: C,
4383 SVGFEBlendElement: C,
4384 SVGFEColorMatrixElement: C,
4385 SVGFEComponentTransferElement: C,
4386 SVGFECompositeElement: C,
4387 SVGFEConvolveMatrixElement: C,
4388 SVGFEDiffuseLightingElement: C,
4389 SVGFEDisplacementMapElement: C,
4390 SVGFEDistantLightElement: C,
4391 SVGFEDropShadowElement: C,
4392 SVGFEFloodElement: C,
4393 SVGFEFuncAElement: C,
4394 SVGFEFuncBElement: C,
4395 SVGFEFuncGElement: C,
4396 SVGFEFuncRElement: C,
4397 SVGFEGaussianBlurElement: C,
4398 SVGFEImageElement: C,
4399 SVGFEMergeElement: C,
4400 SVGFEMergeNodeElement: C,
4401 SVGFEMorphologyElement: C,
4402 SVGFEOffsetElement: C,
4403 SVGFEPointLightElement: C,
4404 SVGFESpecularLightingElement: C,
4405 SVGFESpotLightElement: C,
4406 SVGFETileElement: C,
4407 SVGFETurbulenceElement: C,
4408 SVGFilterElement: C,
4409 SVGForeignObjectElement: C,
4410 SVGGElement: C,
4411 SVGGeometryElement: C,
4412 SVGGradientElement: C,
4413 SVGGraphicsElement: C,
4414 SVGImageElement: C,
4415 SVGLength: C,
4416 SVGLengthList: C,
4417 SVGLinearGradientElement: C,
4418 SVGLineElement: C,
4419 SVGMarkerElement: C,
4420 SVGMaskElement: C,
4421 SVGMatrix: C,
4422 SVGMetadataElement: C,
4423 SVGMPathElement: C,
4424 SVGNumber: C,
4425 SVGNumberList: C,
4426 SVGPathElement: C,
4427 SVGPatternElement: C,
4428 SVGPoint: C,
4429 SVGPointList: C,
4430 SVGPolygonElement: C,
4431 SVGPolylineElement: C,
4432 SVGPreserveAspectRatio: C,
4433 SVGRadialGradientElement: C,
4434 SVGRect: C,
4435 SVGRectElement: C,
4436 SVGScriptElement: C,
4437 SVGSetElement: C,
4438 SVGStopElement: C,
4439 SVGStringList: C,
4440 SVGStyleElement: C,
4441 SVGSVGElement: C,
4442 SVGSwitchElement: C,
4443 SVGSymbolElement: C,
4444 SVGTextContentElement: C,
4445 SVGTextElement: C,
4446 SVGTextPathElement: C,
4447 SVGTextPositioningElement: C,
4448 SVGTitleElement: C,
4449 SVGTransform: C,
4450 SVGTransformList: C,
4451 SVGTSpanElement: C,
4452 SVGUnitTypes: C,
4453 SVGUseElement: C,
4454 SVGViewElement: C,
4455 TaskAttributionTiming: C,
4456 Text: C,
4457 TextEvent: C,
4458 TextMetrics: C,
4459 TextTrack: C,
4460 TextTrackCue: C,
4461 TextTrackCueList: C,
4462 TextTrackList: C,
4463 TimeRanges: C,
4464 toolbar: O,
4465 top: O,
4466 Touch: C,
4467 TouchEvent: C,
4468 TouchList: C,
4469 TrackEvent: C,
4470 TransitionEvent: C,
4471 TreeWalker: C,
4472 UIEvent: C,
4473 ValidityState: C,
4474 visualViewport: O,
4475 VisualViewport: C,
4476 VTTCue: C,
4477 WaveShaperNode: C,
4478 WebAssembly: O,
4479 WebGL2RenderingContext: C,
4480 WebGLActiveInfo: C,
4481 WebGLBuffer: C,
4482 WebGLContextEvent: C,
4483 WebGLFramebuffer: C,
4484 WebGLProgram: C,
4485 WebGLQuery: C,
4486 WebGLRenderbuffer: C,
4487 WebGLRenderingContext: C,
4488 WebGLSampler: C,
4489 WebGLShader: C,
4490 WebGLShaderPrecisionFormat: C,
4491 WebGLSync: C,
4492 WebGLTexture: C,
4493 WebGLTransformFeedback: C,
4494 WebGLUniformLocation: C,
4495 WebGLVertexArrayObject: C,
4496 WebSocket: C,
4497 WheelEvent: C,
4498 Window: C,
4499 Worker: C,
4500 WritableStream: C,
4501 XMLDocument: C,
4502 XMLHttpRequest: C,
4503 XMLHttpRequestEventTarget: C,
4504 XMLHttpRequestUpload: C,
4505 XMLSerializer: C,
4506 XPathEvaluator: C,
4507 XPathExpression: C,
4508 XPathResult: C,
4509 XSLTProcessor: C
4510};
4511for (const global of ['window', 'global', 'self', 'globalThis']) {
4512 knownGlobals[global] = knownGlobals;
4513}
4514function getGlobalAtPath(path) {
4515 let currentGlobal = knownGlobals;
4516 for (const pathSegment of path) {
4517 if (typeof pathSegment !== 'string') {
4518 return null;
4519 }
4520 currentGlobal = currentGlobal[pathSegment];
4521 if (!currentGlobal) {
4522 return null;
4523 }
4524 }
4525 return currentGlobal[ValueProperties];
4526}
4527function isPureGlobal(path) {
4528 const globalAtPath = getGlobalAtPath(path);
4529 return globalAtPath !== null && globalAtPath.pure;
4530}
4531function isGlobalMember(path) {
4532 if (path.length === 1) {
4533 return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
4534 }
4535 return getGlobalAtPath(path.slice(0, -1)) !== null;
4536}
4537
4538class GlobalVariable extends Variable {
4539 constructor() {
4540 super(...arguments);
4541 this.isReassigned = true;
4542 }
4543 hasEffectsWhenAccessedAtPath(path) {
4544 return !isGlobalMember([this.name, ...path]);
4545 }
4546 hasEffectsWhenCalledAtPath(path) {
4547 return !isPureGlobal([this.name, ...path]);
4548 }
4549}
4550
4551const tdzVariableKinds = {
4552 __proto__: null,
4553 class: true,
4554 const: true,
4555 let: true,
4556 var: true
4557};
4558class Identifier extends NodeBase {
4559 constructor() {
4560 super(...arguments);
4561 this.variable = null;
4562 this.deoptimized = false;
4563 this.isTDZAccess = null;
4564 }
4565 addExportedVariables(variables, exportNamesByVariable) {
4566 if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
4567 variables.push(this.variable);
4568 }
4569 }
4570 bind() {
4571 if (this.variable === null && is_reference(this, this.parent)) {
4572 this.variable = this.scope.findVariable(this.name);
4573 this.variable.addReference(this);
4574 }
4575 }
4576 declare(kind, init) {
4577 let variable;
4578 const { treeshake } = this.context.options;
4579 switch (kind) {
4580 case 'var':
4581 variable = this.scope.addDeclaration(this, this.context, init, true);
4582 if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
4583 // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
4584 variable.markInitializersForDeoptimization();
4585 }
4586 break;
4587 case 'function':
4588 // in strict mode, functions are only hoisted within a scope but not across block scopes
4589 variable = this.scope.addDeclaration(this, this.context, init, false);
4590 break;
4591 case 'let':
4592 case 'const':
4593 case 'class':
4594 variable = this.scope.addDeclaration(this, this.context, init, false);
4595 break;
4596 case 'parameter':
4597 variable = this.scope.addParameterDeclaration(this);
4598 break;
4599 /* istanbul ignore next */
4600 default:
4601 /* istanbul ignore next */
4602 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
4603 }
4604 variable.kind = kind;
4605 return [(this.variable = variable)];
4606 }
4607 deoptimizePath(path) {
4608 if (path.length === 0 && !this.scope.contains(this.name)) {
4609 this.disallowImportReassignment();
4610 }
4611 this.variable.deoptimizePath(path);
4612 }
4613 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
4614 this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
4615 }
4616 getLiteralValueAtPath(path, recursionTracker, origin) {
4617 return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
4618 }
4619 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
4620 return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
4621 }
4622 hasEffects() {
4623 if (!this.deoptimized)
4624 this.applyDeoptimizations();
4625 if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
4626 return true;
4627 }
4628 return (this.context.options.treeshake.unknownGlobalSideEffects &&
4629 this.variable instanceof GlobalVariable &&
4630 this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
4631 }
4632 hasEffectsWhenAccessedAtPath(path, context) {
4633 return (this.variable !== null &&
4634 this.getVariableRespectingTDZ().hasEffectsWhenAccessedAtPath(path, context));
4635 }
4636 hasEffectsWhenAssignedAtPath(path, context) {
4637 return (!this.variable ||
4638 (path.length > 0
4639 ? this.getVariableRespectingTDZ()
4640 : this.variable).hasEffectsWhenAssignedAtPath(path, context));
4641 }
4642 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4643 return (!this.variable ||
4644 this.getVariableRespectingTDZ().hasEffectsWhenCalledAtPath(path, callOptions, context));
4645 }
4646 include() {
4647 if (!this.deoptimized)
4648 this.applyDeoptimizations();
4649 if (!this.included) {
4650 this.included = true;
4651 if (this.variable !== null) {
4652 this.context.includeVariableInModule(this.variable);
4653 }
4654 }
4655 }
4656 includeCallArguments(context, args) {
4657 this.getVariableRespectingTDZ().includeCallArguments(context, args);
4658 }
4659 isPossibleTDZ() {
4660 // return cached value to avoid issues with the next tree-shaking pass
4661 if (this.isTDZAccess !== null)
4662 return this.isTDZAccess;
4663 if (!(this.variable instanceof LocalVariable) ||
4664 !this.variable.kind ||
4665 !(this.variable.kind in tdzVariableKinds)) {
4666 return (this.isTDZAccess = false);
4667 }
4668 let decl_id;
4669 if (this.variable.declarations &&
4670 this.variable.declarations.length === 1 &&
4671 (decl_id = this.variable.declarations[0]) &&
4672 this.start < decl_id.start &&
4673 closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
4674 // a variable accessed before its declaration
4675 // in the same function or at top level of module
4676 return (this.isTDZAccess = true);
4677 }
4678 if (!this.variable.initReached) {
4679 // Either a const/let TDZ violation or
4680 // var use before declaration was encountered.
4681 return (this.isTDZAccess = true);
4682 }
4683 return (this.isTDZAccess = false);
4684 }
4685 markDeclarationReached() {
4686 this.variable.initReached = true;
4687 }
4688 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
4689 if (this.variable) {
4690 const name = this.variable.getName();
4691 if (name !== this.name) {
4692 code.overwrite(this.start, this.end, name, {
4693 contentOnly: true,
4694 storeName: true
4695 });
4696 if (isShorthandProperty) {
4697 code.prependRight(this.start, `${this.name}: `);
4698 }
4699 }
4700 // In strict mode, any variable named "eval" must be the actual "eval" function
4701 if (name === 'eval' &&
4702 renderedParentType === CallExpression$1 &&
4703 isCalleeOfRenderedParent) {
4704 code.appendRight(this.start, '0, ');
4705 }
4706 }
4707 }
4708 applyDeoptimizations() {
4709 this.deoptimized = true;
4710 if (this.variable !== null && this.variable instanceof LocalVariable) {
4711 this.variable.consolidateInitializers();
4712 this.context.requestTreeshakingPass();
4713 }
4714 }
4715 disallowImportReassignment() {
4716 return this.context.error({
4717 code: 'ILLEGAL_REASSIGNMENT',
4718 message: `Illegal reassignment to import '${this.name}'`
4719 }, this.start);
4720 }
4721 getVariableRespectingTDZ() {
4722 if (this.isPossibleTDZ()) {
4723 return UNKNOWN_EXPRESSION;
4724 }
4725 return this.variable;
4726 }
4727}
4728function closestParentFunctionOrProgram(node) {
4729 while (node && !/^Program|Function/.test(node.type)) {
4730 node = node.parent;
4731 }
4732 // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
4733 return node;
4734}
4735
4736const EVENT_ACCESSED = 0;
4737const EVENT_ASSIGNED = 1;
4738const EVENT_CALLED = 2;
4739
4740class MethodBase extends NodeBase {
4741 constructor() {
4742 super(...arguments);
4743 this.accessedValue = null;
4744 this.accessorCallOptions = {
4745 args: NO_ARGS,
4746 thisParam: null,
4747 withNew: false
4748 };
4749 }
4750 // As getter properties directly receive their values from fixed function
4751 // expressions, there is no known situation where a getter is deoptimized.
4752 deoptimizeCache() { }
4753 deoptimizePath(path) {
4754 this.getAccessedValue().deoptimizePath(path);
4755 }
4756 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
4757 if (event === EVENT_ACCESSED && this.kind === 'get' && path.length === 0) {
4758 return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
4759 }
4760 if (event === EVENT_ASSIGNED && this.kind === 'set' && path.length === 0) {
4761 return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
4762 }
4763 this.getAccessedValue().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
4764 }
4765 getLiteralValueAtPath(path, recursionTracker, origin) {
4766 return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
4767 }
4768 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
4769 return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
4770 }
4771 hasEffects(context) {
4772 return this.key.hasEffects(context);
4773 }
4774 hasEffectsWhenAccessedAtPath(path, context) {
4775 if (this.kind === 'get' && path.length === 0) {
4776 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
4777 }
4778 return this.getAccessedValue().hasEffectsWhenAccessedAtPath(path, context);
4779 }
4780 hasEffectsWhenAssignedAtPath(path, context) {
4781 if (this.kind === 'set') {
4782 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
4783 }
4784 return this.getAccessedValue().hasEffectsWhenAssignedAtPath(path, context);
4785 }
4786 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4787 return this.getAccessedValue().hasEffectsWhenCalledAtPath(path, callOptions, context);
4788 }
4789 getAccessedValue() {
4790 if (this.accessedValue === null) {
4791 if (this.kind === 'get') {
4792 this.accessedValue = UNKNOWN_EXPRESSION;
4793 return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, SHARED_RECURSION_TRACKER, this));
4794 }
4795 else {
4796 return (this.accessedValue = this.value);
4797 }
4798 }
4799 return this.accessedValue;
4800 }
4801}
4802
4803class MethodDefinition extends MethodBase {
4804}
4805
4806const INTEGER_REG_EXP = /^\d+$/;
4807class ObjectEntity extends ExpressionEntity {
4808 // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
4809 // and we assume there are no setters or getters
4810 constructor(properties, prototypeExpression, immutable = false) {
4811 super();
4812 this.prototypeExpression = prototypeExpression;
4813 this.immutable = immutable;
4814 this.allProperties = [];
4815 this.deoptimizedPaths = Object.create(null);
4816 this.expressionsToBeDeoptimizedByKey = Object.create(null);
4817 this.gettersByKey = Object.create(null);
4818 this.hasUnknownDeoptimizedInteger = false;
4819 this.hasUnknownDeoptimizedProperty = false;
4820 this.propertiesAndGettersByKey = Object.create(null);
4821 this.propertiesAndSettersByKey = Object.create(null);
4822 this.settersByKey = Object.create(null);
4823 this.thisParametersToBeDeoptimized = new Set();
4824 this.unknownIntegerProps = [];
4825 this.unmatchableGetters = [];
4826 this.unmatchablePropertiesAndGetters = [];
4827 this.unmatchableSetters = [];
4828 if (Array.isArray(properties)) {
4829 this.buildPropertyMaps(properties);
4830 }
4831 else {
4832 this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
4833 for (const propertiesForKey of Object.values(properties)) {
4834 this.allProperties.push(...propertiesForKey);
4835 }
4836 }
4837 }
4838 deoptimizeAllProperties() {
4839 var _a;
4840 if (this.hasUnknownDeoptimizedProperty) {
4841 return;
4842 }
4843 this.hasUnknownDeoptimizedProperty = true;
4844 for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
4845 for (const property of properties) {
4846 property.deoptimizePath(UNKNOWN_PATH);
4847 }
4848 }
4849 // While the prototype itself cannot be mutated, each property can
4850 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
4851 this.deoptimizeCachedEntities();
4852 }
4853 deoptimizeIntegerProperties() {
4854 if (this.hasUnknownDeoptimizedProperty || this.hasUnknownDeoptimizedInteger) {
4855 return;
4856 }
4857 this.hasUnknownDeoptimizedInteger = true;
4858 for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
4859 if (INTEGER_REG_EXP.test(key)) {
4860 for (const property of propertiesAndGetters) {
4861 property.deoptimizePath(UNKNOWN_PATH);
4862 }
4863 }
4864 }
4865 this.deoptimizeCachedIntegerEntities();
4866 }
4867 deoptimizePath(path) {
4868 var _a;
4869 if (this.hasUnknownDeoptimizedProperty || this.immutable)
4870 return;
4871 const key = path[0];
4872 if (path.length === 1) {
4873 if (typeof key !== 'string') {
4874 if (key === UnknownInteger) {
4875 return this.deoptimizeIntegerProperties();
4876 }
4877 return this.deoptimizeAllProperties();
4878 }
4879 if (!this.deoptimizedPaths[key]) {
4880 this.deoptimizedPaths[key] = true;
4881 // we only deoptimizeCache exact matches as in all other cases,
4882 // we do not return a literal value or return expression
4883 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
4884 if (expressionsToBeDeoptimized) {
4885 for (const expression of expressionsToBeDeoptimized) {
4886 expression.deoptimizeCache();
4887 }
4888 }
4889 }
4890 }
4891 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
4892 for (const property of typeof key === 'string'
4893 ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
4894 : this.allProperties) {
4895 property.deoptimizePath(subPath);
4896 }
4897 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [UnknownKey, UnknownKey] : path);
4898 }
4899 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
4900 var _a;
4901 const [key, ...subPath] = path;
4902 if (this.hasUnknownDeoptimizedProperty ||
4903 // single paths that are deoptimized will not become getters or setters
4904 ((event === EVENT_CALLED || path.length > 1) &&
4905 typeof key === 'string' &&
4906 this.deoptimizedPaths[key])) {
4907 thisParameter.deoptimizePath(UNKNOWN_PATH);
4908 return;
4909 }
4910 const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = event === EVENT_CALLED || path.length > 1
4911 ? [
4912 this.propertiesAndGettersByKey,
4913 this.propertiesAndGettersByKey,
4914 this.unmatchablePropertiesAndGetters
4915 ]
4916 : event === EVENT_ACCESSED
4917 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
4918 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
4919 if (typeof key === 'string') {
4920 if (propertiesForExactMatchByKey[key]) {
4921 const properties = relevantPropertiesByKey[key];
4922 if (properties) {
4923 for (const property of properties) {
4924 property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
4925 }
4926 }
4927 if (!this.immutable) {
4928 this.thisParametersToBeDeoptimized.add(thisParameter);
4929 }
4930 return;
4931 }
4932 for (const property of relevantUnmatchableProperties) {
4933 property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
4934 }
4935 if (INTEGER_REG_EXP.test(key)) {
4936 for (const property of this.unknownIntegerProps) {
4937 property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
4938 }
4939 }
4940 }
4941 else {
4942 for (const properties of Object.values(relevantPropertiesByKey).concat([
4943 relevantUnmatchableProperties
4944 ])) {
4945 for (const property of properties) {
4946 property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
4947 }
4948 }
4949 for (const property of this.unknownIntegerProps) {
4950 property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
4951 }
4952 }
4953 if (!this.immutable) {
4954 this.thisParametersToBeDeoptimized.add(thisParameter);
4955 }
4956 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
4957 }
4958 getLiteralValueAtPath(path, recursionTracker, origin) {
4959 if (path.length === 0) {
4960 return UnknownValue;
4961 }
4962 const key = path[0];
4963 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
4964 if (expressionAtPath) {
4965 return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
4966 }
4967 if (this.prototypeExpression) {
4968 return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
4969 }
4970 if (path.length === 1) {
4971 return undefined;
4972 }
4973 return UnknownValue;
4974 }
4975 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
4976 if (path.length === 0) {
4977 return UNKNOWN_EXPRESSION;
4978 }
4979 const key = path[0];
4980 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
4981 if (expressionAtPath) {
4982 return expressionAtPath.getReturnExpressionWhenCalledAtPath(path.slice(1), callOptions, recursionTracker, origin);
4983 }
4984 if (this.prototypeExpression) {
4985 return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
4986 }
4987 return UNKNOWN_EXPRESSION;
4988 }
4989 hasEffectsWhenAccessedAtPath(path, context) {
4990 const [key, ...subPath] = path;
4991 if (path.length > 1) {
4992 if (typeof key !== 'string') {
4993 return true;
4994 }
4995 const expressionAtPath = this.getMemberExpression(key);
4996 if (expressionAtPath) {
4997 return expressionAtPath.hasEffectsWhenAccessedAtPath(subPath, context);
4998 }
4999 if (this.prototypeExpression) {
5000 return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
5001 }
5002 return true;
5003 }
5004 if (this.hasUnknownDeoptimizedProperty)
5005 return true;
5006 if (typeof key === 'string') {
5007 if (this.propertiesAndGettersByKey[key]) {
5008 const getters = this.gettersByKey[key];
5009 if (getters) {
5010 for (const getter of getters) {
5011 if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
5012 return true;
5013 }
5014 }
5015 return false;
5016 }
5017 for (const getter of this.unmatchableGetters) {
5018 if (getter.hasEffectsWhenAccessedAtPath(subPath, context)) {
5019 return true;
5020 }
5021 }
5022 }
5023 else {
5024 for (const getters of Object.values(this.gettersByKey).concat([this.unmatchableGetters])) {
5025 for (const getter of getters) {
5026 if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
5027 return true;
5028 }
5029 }
5030 }
5031 if (this.prototypeExpression) {
5032 return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
5033 }
5034 return false;
5035 }
5036 hasEffectsWhenAssignedAtPath(path, context) {
5037 const [key, ...subPath] = path;
5038 if (path.length > 1) {
5039 if (typeof key !== 'string') {
5040 return true;
5041 }
5042 const expressionAtPath = this.getMemberExpression(key);
5043 if (expressionAtPath) {
5044 return expressionAtPath.hasEffectsWhenAssignedAtPath(subPath, context);
5045 }
5046 if (this.prototypeExpression) {
5047 return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
5048 }
5049 return true;
5050 }
5051 if (this.hasUnknownDeoptimizedProperty)
5052 return true;
5053 // We do not need to test for unknown properties as in that case, hasUnknownDeoptimizedProperty is true
5054 if (typeof key === 'string') {
5055 if (this.propertiesAndSettersByKey[key]) {
5056 const setters = this.settersByKey[key];
5057 if (setters) {
5058 for (const setter of setters) {
5059 if (setter.hasEffectsWhenAssignedAtPath(subPath, context))
5060 return true;
5061 }
5062 }
5063 return false;
5064 }
5065 for (const property of this.unmatchableSetters) {
5066 if (property.hasEffectsWhenAssignedAtPath(subPath, context)) {
5067 return true;
5068 }
5069 }
5070 }
5071 if (this.prototypeExpression) {
5072 return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
5073 }
5074 return false;
5075 }
5076 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5077 const key = path[0];
5078 const expressionAtPath = this.getMemberExpression(key);
5079 if (expressionAtPath) {
5080 return expressionAtPath.hasEffectsWhenCalledAtPath(path.slice(1), callOptions, context);
5081 }
5082 if (this.prototypeExpression) {
5083 return this.prototypeExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
5084 }
5085 return true;
5086 }
5087 buildPropertyMaps(properties) {
5088 const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
5089 const unmatchablePropertiesAndSetters = [];
5090 for (let index = properties.length - 1; index >= 0; index--) {
5091 const { key, kind, property } = properties[index];
5092 allProperties.push(property);
5093 if (typeof key !== 'string') {
5094 if (key === UnknownInteger) {
5095 unknownIntegerProps.push(property);
5096 continue;
5097 }
5098 if (kind === 'set')
5099 unmatchableSetters.push(property);
5100 if (kind === 'get')
5101 unmatchableGetters.push(property);
5102 if (kind !== 'get')
5103 unmatchablePropertiesAndSetters.push(property);
5104 if (kind !== 'set')
5105 unmatchablePropertiesAndGetters.push(property);
5106 }
5107 else {
5108 if (kind === 'set') {
5109 if (!propertiesAndSettersByKey[key]) {
5110 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5111 settersByKey[key] = [property, ...unmatchableSetters];
5112 }
5113 }
5114 else if (kind === 'get') {
5115 if (!propertiesAndGettersByKey[key]) {
5116 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5117 gettersByKey[key] = [property, ...unmatchableGetters];
5118 }
5119 }
5120 else {
5121 if (!propertiesAndSettersByKey[key]) {
5122 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5123 }
5124 if (!propertiesAndGettersByKey[key]) {
5125 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5126 }
5127 }
5128 }
5129 }
5130 }
5131 deoptimizeCachedEntities() {
5132 for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
5133 for (const expression of expressionsToBeDeoptimized) {
5134 expression.deoptimizeCache();
5135 }
5136 }
5137 for (const expression of this.thisParametersToBeDeoptimized) {
5138 expression.deoptimizePath(UNKNOWN_PATH);
5139 }
5140 }
5141 deoptimizeCachedIntegerEntities() {
5142 for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
5143 if (INTEGER_REG_EXP.test(key)) {
5144 for (const expression of expressionsToBeDeoptimized) {
5145 expression.deoptimizeCache();
5146 }
5147 }
5148 }
5149 for (const expression of this.thisParametersToBeDeoptimized) {
5150 expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
5151 }
5152 }
5153 getMemberExpression(key) {
5154 if (this.hasUnknownDeoptimizedProperty ||
5155 typeof key !== 'string' ||
5156 (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
5157 this.deoptimizedPaths[key]) {
5158 return UNKNOWN_EXPRESSION;
5159 }
5160 const properties = this.propertiesAndGettersByKey[key];
5161 if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
5162 return properties[0];
5163 }
5164 if (properties ||
5165 this.unmatchablePropertiesAndGetters.length > 0 ||
5166 (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
5167 return UNKNOWN_EXPRESSION;
5168 }
5169 return null;
5170 }
5171 getMemberExpressionAndTrackDeopt(key, origin) {
5172 if (typeof key !== 'string') {
5173 return UNKNOWN_EXPRESSION;
5174 }
5175 const expression = this.getMemberExpression(key);
5176 if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
5177 const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
5178 this.expressionsToBeDeoptimizedByKey[key] || []);
5179 expressionsToBeDeoptimized.push(origin);
5180 }
5181 return expression;
5182 }
5183}
5184
5185class ObjectMember extends ExpressionEntity {
5186 constructor(object, key) {
5187 super();
5188 this.object = object;
5189 this.key = key;
5190 }
5191 deoptimizePath(path) {
5192 this.object.deoptimizePath([this.key, ...path]);
5193 }
5194 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
5195 this.object.deoptimizeThisOnEventAtPath(event, [this.key, ...path], thisParameter, recursionTracker);
5196 }
5197 getLiteralValueAtPath(path, recursionTracker, origin) {
5198 return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
5199 }
5200 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
5201 return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], callOptions, recursionTracker, origin);
5202 }
5203 hasEffectsWhenAccessedAtPath(path, context) {
5204 if (path.length === 0)
5205 return false;
5206 return this.object.hasEffectsWhenAccessedAtPath([this.key, ...path], context);
5207 }
5208 hasEffectsWhenAssignedAtPath(path, context) {
5209 return this.object.hasEffectsWhenAssignedAtPath([this.key, ...path], context);
5210 }
5211 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5212 return this.object.hasEffectsWhenCalledAtPath([this.key, ...path], callOptions, context);
5213 }
5214}
5215
5216class Method extends ExpressionEntity {
5217 constructor(description) {
5218 super();
5219 this.description = description;
5220 }
5221 deoptimizeThisOnEventAtPath(event, path, thisParameter) {
5222 if (event === EVENT_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
5223 thisParameter.deoptimizePath(UNKNOWN_INTEGER_PATH);
5224 }
5225 }
5226 getReturnExpressionWhenCalledAtPath(path, callOptions) {
5227 if (path.length > 0) {
5228 return UNKNOWN_EXPRESSION;
5229 }
5230 return (this.description.returnsPrimitive ||
5231 (this.description.returns === 'self'
5232 ? callOptions.thisParam || UNKNOWN_EXPRESSION
5233 : this.description.returns()));
5234 }
5235 hasEffectsWhenAccessedAtPath(path) {
5236 return path.length > 1;
5237 }
5238 hasEffectsWhenAssignedAtPath(path) {
5239 return path.length > 0;
5240 }
5241 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5242 var _a, _b;
5243 if (path.length > 0 ||
5244 (this.description.mutatesSelfAsArray === true &&
5245 ((_a = callOptions.thisParam) === null || _a === void 0 ? void 0 : _a.hasEffectsWhenAssignedAtPath(UNKNOWN_INTEGER_PATH, context)))) {
5246 return true;
5247 }
5248 if (!this.description.callsArgs) {
5249 return false;
5250 }
5251 for (const argIndex of this.description.callsArgs) {
5252 if ((_b = callOptions.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsWhenCalledAtPath(EMPTY_PATH, {
5253 args: NO_ARGS,
5254 thisParam: null,
5255 withNew: false
5256 }, context)) {
5257 return true;
5258 }
5259 }
5260 return false;
5261 }
5262 includeCallArguments(context, args) {
5263 for (const arg of args) {
5264 arg.include(context, false);
5265 }
5266 }
5267}
5268const METHOD_RETURNS_BOOLEAN = [
5269 new Method({
5270 callsArgs: null,
5271 mutatesSelfAsArray: false,
5272 returns: null,
5273 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
5274 })
5275];
5276const METHOD_RETURNS_STRING = [
5277 new Method({
5278 callsArgs: null,
5279 mutatesSelfAsArray: false,
5280 returns: null,
5281 returnsPrimitive: UNKNOWN_LITERAL_STRING
5282 })
5283];
5284const METHOD_RETURNS_NUMBER = [
5285 new Method({
5286 callsArgs: null,
5287 mutatesSelfAsArray: false,
5288 returns: null,
5289 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5290 })
5291];
5292const METHOD_RETURNS_UNKNOWN = [
5293 new Method({
5294 callsArgs: null,
5295 mutatesSelfAsArray: false,
5296 returns: null,
5297 returnsPrimitive: UNKNOWN_EXPRESSION
5298 })
5299];
5300
5301const OBJECT_PROTOTYPE = new ObjectEntity({
5302 __proto__: null,
5303 hasOwnProperty: METHOD_RETURNS_BOOLEAN,
5304 isPrototypeOf: METHOD_RETURNS_BOOLEAN,
5305 propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
5306 toLocaleString: METHOD_RETURNS_STRING,
5307 toString: METHOD_RETURNS_STRING,
5308 valueOf: METHOD_RETURNS_UNKNOWN
5309}, null, true);
5310
5311class ClassNode extends NodeBase {
5312 constructor() {
5313 super(...arguments);
5314 this.objectEntity = null;
5315 }
5316 createScope(parentScope) {
5317 this.scope = new ChildScope(parentScope);
5318 }
5319 deoptimizeCache() {
5320 this.getObjectEntity().deoptimizeAllProperties();
5321 }
5322 deoptimizePath(path) {
5323 this.getObjectEntity().deoptimizePath(path);
5324 }
5325 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
5326 this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
5327 }
5328 getLiteralValueAtPath(path, recursionTracker, origin) {
5329 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
5330 }
5331 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
5332 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
5333 }
5334 hasEffects(context) {
5335 var _a, _b;
5336 const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
5337 (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
5338 return initEffect || super.hasEffects(context);
5339 }
5340 hasEffectsWhenAccessedAtPath(path, context) {
5341 return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
5342 }
5343 hasEffectsWhenAssignedAtPath(path, context) {
5344 return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
5345 }
5346 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5347 if (path.length === 0) {
5348 return (!callOptions.withNew ||
5349 (this.classConstructor !== null
5350 ? this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context)
5351 : this.superClass !== null &&
5352 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
5353 }
5354 else {
5355 return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
5356 }
5357 }
5358 include(context, includeChildrenRecursively) {
5359 var _a;
5360 this.included = true;
5361 (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
5362 this.body.include(context, includeChildrenRecursively);
5363 if (this.id) {
5364 this.id.markDeclarationReached();
5365 this.id.include();
5366 }
5367 }
5368 initialise() {
5369 var _a;
5370 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
5371 for (const method of this.body.body) {
5372 if (method instanceof MethodDefinition && method.kind === 'constructor') {
5373 this.classConstructor = method;
5374 return;
5375 }
5376 }
5377 this.classConstructor = null;
5378 }
5379 getObjectEntity() {
5380 if (this.objectEntity !== null) {
5381 return this.objectEntity;
5382 }
5383 const staticProperties = [];
5384 const dynamicMethods = [];
5385 for (const definition of this.body.body) {
5386 const properties = definition.static ? staticProperties : dynamicMethods;
5387 const definitionKind = definition.kind;
5388 // Note that class fields do not end up on the prototype
5389 if (properties === dynamicMethods && !definitionKind)
5390 continue;
5391 const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
5392 let key;
5393 if (definition.computed) {
5394 const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
5395 if (keyValue === UnknownValue) {
5396 properties.push({ key: UnknownKey, kind, property: definition });
5397 continue;
5398 }
5399 else {
5400 key = String(keyValue);
5401 }
5402 }
5403 else {
5404 key =
5405 definition.key instanceof Identifier
5406 ? definition.key.name
5407 : String(definition.key.value);
5408 }
5409 properties.push({ key, kind, property: definition });
5410 }
5411 staticProperties.unshift({
5412 key: 'prototype',
5413 kind: 'init',
5414 property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
5415 });
5416 return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
5417 }
5418}
5419
5420class ClassDeclaration extends ClassNode {
5421 initialise() {
5422 super.initialise();
5423 if (this.id !== null) {
5424 this.id.variable.isId = true;
5425 }
5426 }
5427 parseNode(esTreeNode) {
5428 if (esTreeNode.id !== null) {
5429 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
5430 }
5431 super.parseNode(esTreeNode);
5432 }
5433 render(code, options) {
5434 if (options.format === 'system' &&
5435 this.id &&
5436 options.exportNamesByVariable.has(this.id.variable)) {
5437 code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
5438 }
5439 super.render(code, options);
5440 }
5441}
5442
5443class ArgumentsVariable extends LocalVariable {
5444 constructor(context) {
5445 super('arguments', null, UNKNOWN_EXPRESSION, context);
5446 }
5447 hasEffectsWhenAccessedAtPath(path) {
5448 return path.length > 1;
5449 }
5450 hasEffectsWhenAssignedAtPath() {
5451 return true;
5452 }
5453 hasEffectsWhenCalledAtPath() {
5454 return true;
5455 }
5456}
5457
5458class ThisVariable extends LocalVariable {
5459 constructor(context) {
5460 super('this', null, null, context);
5461 this.deoptimizedPaths = [];
5462 this.entitiesToBeDeoptimized = new Set();
5463 this.thisDeoptimizationList = [];
5464 this.thisDeoptimizations = new DiscriminatedPathTracker();
5465 }
5466 addEntityToBeDeoptimized(entity) {
5467 for (const path of this.deoptimizedPaths) {
5468 entity.deoptimizePath(path);
5469 }
5470 for (const thisDeoptimization of this.thisDeoptimizationList) {
5471 this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
5472 }
5473 this.entitiesToBeDeoptimized.add(entity);
5474 }
5475 deoptimizePath(path) {
5476 if (path.length === 0 ||
5477 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
5478 return;
5479 }
5480 this.deoptimizedPaths.push(path);
5481 for (const entity of this.entitiesToBeDeoptimized) {
5482 entity.deoptimizePath(path);
5483 }
5484 }
5485 deoptimizeThisOnEventAtPath(event, path, thisParameter) {
5486 const thisDeoptimization = {
5487 event,
5488 path,
5489 thisParameter
5490 };
5491 if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, event, thisParameter)) {
5492 for (const entity of this.entitiesToBeDeoptimized) {
5493 this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
5494 }
5495 this.thisDeoptimizationList.push(thisDeoptimization);
5496 }
5497 }
5498 hasEffectsWhenAccessedAtPath(path, context) {
5499 return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
5500 super.hasEffectsWhenAccessedAtPath(path, context));
5501 }
5502 hasEffectsWhenAssignedAtPath(path, context) {
5503 return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
5504 super.hasEffectsWhenAssignedAtPath(path, context));
5505 }
5506 applyThisDeoptimizationEvent(entity, { event, path, thisParameter }) {
5507 entity.deoptimizeThisOnEventAtPath(event, path, thisParameter === this ? entity : thisParameter, SHARED_RECURSION_TRACKER);
5508 }
5509 getInit(context) {
5510 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
5511 }
5512}
5513
5514class SpreadElement extends NodeBase {
5515 constructor() {
5516 super(...arguments);
5517 this.deoptimized = false;
5518 }
5519 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
5520 if (path.length > 0) {
5521 this.argument.deoptimizeThisOnEventAtPath(event, [UnknownKey, ...path], thisParameter, recursionTracker);
5522 }
5523 }
5524 hasEffects(context) {
5525 if (!this.deoptimized)
5526 this.applyDeoptimizations();
5527 const { propertyReadSideEffects } = this.context.options
5528 .treeshake;
5529 return (this.argument.hasEffects(context) ||
5530 (propertyReadSideEffects &&
5531 (propertyReadSideEffects === 'always' ||
5532 this.argument.hasEffectsWhenAccessedAtPath(UNKNOWN_PATH, context))));
5533 }
5534 applyDeoptimizations() {
5535 this.deoptimized = true;
5536 // Only properties of properties of the argument could become subject to reassignment
5537 // This will also reassign the return values of iterators
5538 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
5539 this.context.requestTreeshakingPass();
5540 }
5541}
5542
5543class ParameterScope extends ChildScope {
5544 constructor(parent, context) {
5545 super(parent);
5546 this.parameters = [];
5547 this.hasRest = false;
5548 this.context = context;
5549 this.hoistedBodyVarScope = new ChildScope(this);
5550 }
5551 /**
5552 * Adds a parameter to this scope. Parameters must be added in the correct
5553 * order, e.g. from left to right.
5554 */
5555 addParameterDeclaration(identifier) {
5556 const name = identifier.name;
5557 let variable = this.hoistedBodyVarScope.variables.get(name);
5558 if (variable) {
5559 variable.addDeclaration(identifier, null);
5560 }
5561 else {
5562 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
5563 }
5564 this.variables.set(name, variable);
5565 return variable;
5566 }
5567 addParameterVariables(parameters, hasRest) {
5568 this.parameters = parameters;
5569 for (const parameterList of parameters) {
5570 for (const parameter of parameterList) {
5571 parameter.alwaysRendered = true;
5572 }
5573 }
5574 this.hasRest = hasRest;
5575 }
5576 includeCallArguments(context, args) {
5577 let calledFromTryStatement = false;
5578 let argIncluded = false;
5579 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
5580 for (const checkedArg of args) {
5581 if (checkedArg instanceof SpreadElement) {
5582 for (const arg of args) {
5583 arg.include(context, false);
5584 }
5585 break;
5586 }
5587 }
5588 for (let index = args.length - 1; index >= 0; index--) {
5589 const paramVars = this.parameters[index] || restParam;
5590 const arg = args[index];
5591 if (paramVars) {
5592 calledFromTryStatement = false;
5593 if (paramVars.length === 0) {
5594 // handle empty destructuring
5595 argIncluded = true;
5596 }
5597 else {
5598 for (const variable of paramVars) {
5599 if (variable.included) {
5600 argIncluded = true;
5601 }
5602 if (variable.calledFromTryStatement) {
5603 calledFromTryStatement = true;
5604 }
5605 }
5606 }
5607 }
5608 if (!argIncluded && arg.shouldBeIncluded(context)) {
5609 argIncluded = true;
5610 }
5611 if (argIncluded) {
5612 arg.include(context, calledFromTryStatement);
5613 }
5614 }
5615 }
5616}
5617
5618class ReturnValueScope extends ParameterScope {
5619 constructor() {
5620 super(...arguments);
5621 this.returnExpression = null;
5622 this.returnExpressions = [];
5623 }
5624 addReturnExpression(expression) {
5625 this.returnExpressions.push(expression);
5626 }
5627 getReturnExpression() {
5628 if (this.returnExpression === null)
5629 this.updateReturnExpression();
5630 return this.returnExpression;
5631 }
5632 updateReturnExpression() {
5633 if (this.returnExpressions.length === 1) {
5634 this.returnExpression = this.returnExpressions[0];
5635 }
5636 else {
5637 this.returnExpression = UNKNOWN_EXPRESSION;
5638 for (const expression of this.returnExpressions) {
5639 expression.deoptimizePath(UNKNOWN_PATH);
5640 }
5641 }
5642 }
5643}
5644
5645class FunctionScope extends ReturnValueScope {
5646 constructor(parent, context) {
5647 super(parent, context);
5648 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
5649 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
5650 }
5651 findLexicalBoundary() {
5652 return this;
5653 }
5654 includeCallArguments(context, args) {
5655 super.includeCallArguments(context, args);
5656 if (this.argumentsVariable.included) {
5657 for (const arg of args) {
5658 if (!arg.included) {
5659 arg.include(context, false);
5660 }
5661 }
5662 }
5663 }
5664}
5665
5666class RestElement extends NodeBase {
5667 constructor() {
5668 super(...arguments);
5669 this.deoptimized = false;
5670 this.declarationInit = null;
5671 }
5672 addExportedVariables(variables, exportNamesByVariable) {
5673 this.argument.addExportedVariables(variables, exportNamesByVariable);
5674 }
5675 declare(kind, init) {
5676 this.declarationInit = init;
5677 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
5678 }
5679 deoptimizePath(path) {
5680 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
5681 }
5682 hasEffectsWhenAssignedAtPath(path, context) {
5683 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
5684 }
5685 markDeclarationReached() {
5686 this.argument.markDeclarationReached();
5687 }
5688 applyDeoptimizations() {
5689 this.deoptimized = true;
5690 if (this.declarationInit !== null) {
5691 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
5692 this.context.requestTreeshakingPass();
5693 }
5694 }
5695}
5696
5697class FunctionNode extends NodeBase {
5698 constructor() {
5699 super(...arguments);
5700 this.deoptimizedReturn = false;
5701 this.isPrototypeDeoptimized = false;
5702 }
5703 createScope(parentScope) {
5704 this.scope = new FunctionScope(parentScope, this.context);
5705 }
5706 deoptimizePath(path) {
5707 if (path.length === 1) {
5708 if (path[0] === 'prototype') {
5709 this.isPrototypeDeoptimized = true;
5710 }
5711 else if (path[0] === UnknownKey) {
5712 this.isPrototypeDeoptimized = true;
5713 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
5714 // which means the return expression needs to be reassigned as well
5715 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
5716 }
5717 }
5718 }
5719 // TODO for completeness, we should also track other events here
5720 deoptimizeThisOnEventAtPath(event, path, thisParameter) {
5721 if (event === EVENT_CALLED) {
5722 if (path.length > 0) {
5723 thisParameter.deoptimizePath(UNKNOWN_PATH);
5724 }
5725 else {
5726 this.scope.thisVariable.addEntityToBeDeoptimized(thisParameter);
5727 }
5728 }
5729 }
5730 getReturnExpressionWhenCalledAtPath(path) {
5731 if (path.length !== 0) {
5732 return UNKNOWN_EXPRESSION;
5733 }
5734 if (this.async) {
5735 if (!this.deoptimizedReturn) {
5736 this.deoptimizedReturn = true;
5737 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
5738 this.context.requestTreeshakingPass();
5739 }
5740 return UNKNOWN_EXPRESSION;
5741 }
5742 return this.scope.getReturnExpression();
5743 }
5744 hasEffects() {
5745 return this.id !== null && this.id.hasEffects();
5746 }
5747 hasEffectsWhenAccessedAtPath(path) {
5748 if (path.length <= 1)
5749 return false;
5750 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
5751 }
5752 hasEffectsWhenAssignedAtPath(path) {
5753 if (path.length <= 1) {
5754 return false;
5755 }
5756 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
5757 }
5758 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5759 if (path.length > 0)
5760 return true;
5761 if (this.async) {
5762 const { propertyReadSideEffects } = this.context.options
5763 .treeshake;
5764 const returnExpression = this.scope.getReturnExpression();
5765 if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
5766 (propertyReadSideEffects &&
5767 (propertyReadSideEffects === 'always' ||
5768 returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
5769 return true;
5770 }
5771 }
5772 for (const param of this.params) {
5773 if (param.hasEffects(context))
5774 return true;
5775 }
5776 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
5777 context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew
5778 ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
5779 : UNKNOWN_EXPRESSION);
5780 const { brokenFlow, ignore } = context;
5781 context.ignore = {
5782 breaks: false,
5783 continues: false,
5784 labels: new Set(),
5785 returnYield: true
5786 };
5787 if (this.body.hasEffects(context))
5788 return true;
5789 context.brokenFlow = brokenFlow;
5790 if (thisInit) {
5791 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
5792 }
5793 else {
5794 context.replacedVariableInits.delete(this.scope.thisVariable);
5795 }
5796 context.ignore = ignore;
5797 return false;
5798 }
5799 include(context, includeChildrenRecursively) {
5800 this.included = true;
5801 if (this.id)
5802 this.id.include();
5803 const hasArguments = this.scope.argumentsVariable.included;
5804 for (const param of this.params) {
5805 if (!(param instanceof Identifier) || hasArguments) {
5806 param.include(context, includeChildrenRecursively);
5807 }
5808 }
5809 const { brokenFlow } = context;
5810 context.brokenFlow = BROKEN_FLOW_NONE;
5811 this.body.include(context, includeChildrenRecursively);
5812 context.brokenFlow = brokenFlow;
5813 }
5814 includeCallArguments(context, args) {
5815 this.scope.includeCallArguments(context, args);
5816 }
5817 initialise() {
5818 if (this.id !== null) {
5819 this.id.declare('function', this);
5820 }
5821 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
5822 this.body.addImplicitReturnExpressionToScope();
5823 }
5824 parseNode(esTreeNode) {
5825 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
5826 super.parseNode(esTreeNode);
5827 }
5828}
5829FunctionNode.prototype.preventChildBlockScope = true;
5830
5831class FunctionDeclaration extends FunctionNode {
5832 initialise() {
5833 super.initialise();
5834 if (this.id !== null) {
5835 this.id.variable.isId = true;
5836 }
5837 }
5838 parseNode(esTreeNode) {
5839 if (esTreeNode.id !== null) {
5840 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
5841 }
5842 super.parseNode(esTreeNode);
5843 }
5844}
5845
5846// The header ends at the first non-white-space after "default"
5847function getDeclarationStart(code, start) {
5848 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
5849}
5850function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
5851 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
5852 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
5853 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
5854 if (generatorStarPos === -1) {
5855 return declarationEnd;
5856 }
5857 return declarationEnd + generatorStarPos + 1;
5858}
5859class ExportDefaultDeclaration extends NodeBase {
5860 include(context, includeChildrenRecursively) {
5861 super.include(context, includeChildrenRecursively);
5862 if (includeChildrenRecursively) {
5863 this.context.includeVariableInModule(this.variable);
5864 }
5865 }
5866 initialise() {
5867 const declaration = this.declaration;
5868 this.declarationName =
5869 (declaration.id && declaration.id.name) || this.declaration.name;
5870 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
5871 this.context.addExport(this);
5872 }
5873 render(code, options, nodeRenderOptions) {
5874 const { start, end } = nodeRenderOptions;
5875 const declarationStart = getDeclarationStart(code.original, this.start);
5876 if (this.declaration instanceof FunctionDeclaration) {
5877 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
5878 }
5879 else if (this.declaration instanceof ClassDeclaration) {
5880 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
5881 }
5882 else if (this.variable.getOriginalVariable() !== this.variable) {
5883 // Remove altogether to prevent re-declaring the same variable
5884 treeshakeNode(this, code, start, end);
5885 return;
5886 }
5887 else if (this.variable.included) {
5888 this.renderVariableDeclaration(code, declarationStart, options);
5889 }
5890 else {
5891 code.remove(this.start, declarationStart);
5892 this.declaration.render(code, options, {
5893 isCalleeOfRenderedParent: false,
5894 renderedParentType: ExpressionStatement$1
5895 });
5896 if (code.original[this.end - 1] !== ';') {
5897 code.appendLeft(this.end, ';');
5898 }
5899 return;
5900 }
5901 this.declaration.render(code, options);
5902 }
5903 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
5904 const name = this.variable.getName();
5905 // Remove `export default`
5906 code.remove(this.start, declarationStart);
5907 if (needsId) {
5908 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
5909 }
5910 if (options.format === 'system' &&
5911 this.declaration instanceof ClassDeclaration &&
5912 options.exportNamesByVariable.has(this.variable)) {
5913 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
5914 }
5915 }
5916 renderVariableDeclaration(code, declarationStart, options) {
5917 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
5918 const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
5919 if (systemExportNames) {
5920 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
5921 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
5922 }
5923 else {
5924 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
5925 if (!hasTrailingSemicolon) {
5926 code.appendLeft(this.end, ';');
5927 }
5928 }
5929 }
5930}
5931ExportDefaultDeclaration.prototype.needsBoundaries = true;
5932
5933class Literal extends NodeBase {
5934 deoptimizeThisOnEventAtPath() { }
5935 getLiteralValueAtPath(path) {
5936 if (path.length > 0 ||
5937 // unknown literals can also be null but do not start with an "n"
5938 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
5939 typeof this.value === 'bigint' ||
5940 // to support shims for regular expressions
5941 this.context.code.charCodeAt(this.start) === 47) {
5942 return UnknownValue;
5943 }
5944 return this.value;
5945 }
5946 getReturnExpressionWhenCalledAtPath(path) {
5947 if (path.length !== 1)
5948 return UNKNOWN_EXPRESSION;
5949 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
5950 }
5951 hasEffectsWhenAccessedAtPath(path) {
5952 if (this.value === null) {
5953 return path.length > 0;
5954 }
5955 return path.length > 1;
5956 }
5957 hasEffectsWhenAssignedAtPath(path) {
5958 return path.length > 0;
5959 }
5960 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5961 if (path.length === 1) {
5962 return hasMemberEffectWhenCalled(this.members, path[0], callOptions, context);
5963 }
5964 return true;
5965 }
5966 initialise() {
5967 this.members = getLiteralMembersForValue(this.value);
5968 }
5969 parseNode(esTreeNode) {
5970 this.value = esTreeNode.value;
5971 this.regex = esTreeNode.regex;
5972 super.parseNode(esTreeNode);
5973 }
5974 render(code) {
5975 if (typeof this.value === 'string') {
5976 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
5977 }
5978 }
5979}
5980
5981class Program extends NodeBase {
5982 constructor() {
5983 super(...arguments);
5984 this.hasCachedEffect = false;
5985 }
5986 hasEffects(context) {
5987 // We are caching here to later more efficiently identify side-effect-free modules
5988 if (this.hasCachedEffect)
5989 return true;
5990 for (const node of this.body) {
5991 if (node.hasEffects(context)) {
5992 return (this.hasCachedEffect = true);
5993 }
5994 }
5995 return false;
5996 }
5997 include(context, includeChildrenRecursively) {
5998 this.included = true;
5999 for (const node of this.body) {
6000 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
6001 node.include(context, includeChildrenRecursively);
6002 }
6003 }
6004 }
6005 render(code, options) {
6006 if (this.body.length) {
6007 renderStatementList(this.body, code, this.start, this.end, options);
6008 }
6009 else {
6010 super.render(code, options);
6011 }
6012 }
6013}
6014
6015class TemplateLiteral extends NodeBase {
6016 getLiteralValueAtPath(path) {
6017 if (path.length > 0 || this.quasis.length !== 1) {
6018 return UnknownValue;
6019 }
6020 return this.quasis[0].value.cooked;
6021 }
6022 render(code, options) {
6023 code.indentExclusionRanges.push([this.start, this.end]);
6024 super.render(code, options);
6025 }
6026}
6027
6028function isReassignedExportsMember(variable, exportNamesByVariable) {
6029 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
6030}
6031
6032function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
6033 for (const declarator of declarations) {
6034 if (!declarator.id.included)
6035 return false;
6036 if (declarator.id.type === Identifier$1) {
6037 if (exportNamesByVariable.has(declarator.id.variable))
6038 return false;
6039 }
6040 else {
6041 const exportedVariables = [];
6042 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
6043 if (exportedVariables.length > 0)
6044 return false;
6045 }
6046 }
6047 return true;
6048}
6049class VariableDeclaration extends NodeBase {
6050 deoptimizePath() {
6051 for (const declarator of this.declarations) {
6052 declarator.deoptimizePath(EMPTY_PATH);
6053 }
6054 }
6055 hasEffectsWhenAssignedAtPath() {
6056 return false;
6057 }
6058 include(context, includeChildrenRecursively) {
6059 this.included = true;
6060 for (const declarator of this.declarations) {
6061 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
6062 declarator.include(context, includeChildrenRecursively);
6063 }
6064 }
6065 includeAsSingleStatement(context, includeChildrenRecursively) {
6066 this.included = true;
6067 for (const declarator of this.declarations) {
6068 if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
6069 declarator.include(context, includeChildrenRecursively);
6070 declarator.id.include(context, includeChildrenRecursively);
6071 }
6072 }
6073 }
6074 initialise() {
6075 for (const declarator of this.declarations) {
6076 declarator.declareDeclarator(this.kind);
6077 }
6078 }
6079 render(code, options, nodeRenderOptions = BLANK) {
6080 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
6081 for (const declarator of this.declarations) {
6082 declarator.render(code, options);
6083 }
6084 if (!nodeRenderOptions.isNoStatement &&
6085 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
6086 code.appendLeft(this.end, ';');
6087 }
6088 }
6089 else {
6090 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
6091 }
6092 }
6093 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement) {
6094 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
6095 code.remove(this.end - 1, this.end);
6096 }
6097 if (!isNoStatement) {
6098 separatorString += ';';
6099 }
6100 if (lastSeparatorPos !== null) {
6101 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
6102 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
6103 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
6104 actualContentEnd--;
6105 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
6106 actualContentEnd--;
6107 }
6108 }
6109 if (actualContentEnd === lastSeparatorPos + 1) {
6110 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
6111 }
6112 else {
6113 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
6114 code.remove(actualContentEnd, renderedContentEnd);
6115 }
6116 }
6117 else {
6118 code.appendLeft(renderedContentEnd, separatorString);
6119 }
6120 if (systemPatternExports.length > 0) {
6121 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
6122 }
6123 }
6124 renderReplacedDeclarations(code, options, { isNoStatement }) {
6125 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
6126 let actualContentEnd, renderedContentEnd;
6127 renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
6128 let lastSeparatorPos = renderedContentEnd - 1;
6129 code.remove(this.start, lastSeparatorPos);
6130 let isInDeclaration = false;
6131 let hasRenderedContent = false;
6132 let separatorString = '', leadingString, nextSeparatorString;
6133 const systemPatternExports = [];
6134 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
6135 if (!node.included) {
6136 code.remove(start, end);
6137 continue;
6138 }
6139 leadingString = '';
6140 nextSeparatorString = '';
6141 if (!node.id.included ||
6142 (node.id instanceof Identifier &&
6143 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
6144 if (hasRenderedContent) {
6145 separatorString += ';';
6146 }
6147 isInDeclaration = false;
6148 }
6149 else {
6150 if (options.format === 'system' && node.init !== null) {
6151 if (node.id.type !== Identifier$1) {
6152 node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
6153 }
6154 else {
6155 const exportNames = options.exportNamesByVariable.get(node.id.variable);
6156 if (exportNames) {
6157 const _ = options.compact ? '' : ' ';
6158 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
6159 code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
6160 ? `exports('${exportNames[0]}',${_}`
6161 : getSystemExportFunctionLeft([node.id.variable], false, options));
6162 nextSeparatorString += ')';
6163 }
6164 }
6165 }
6166 if (isInDeclaration) {
6167 separatorString += ',';
6168 }
6169 else {
6170 if (hasRenderedContent) {
6171 separatorString += ';';
6172 }
6173 leadingString += `${this.kind} `;
6174 isInDeclaration = true;
6175 }
6176 }
6177 if (renderedContentEnd === lastSeparatorPos + 1) {
6178 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
6179 }
6180 else {
6181 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
6182 code.appendLeft(renderedContentEnd, leadingString);
6183 }
6184 node.render(code, options);
6185 actualContentEnd = contentEnd;
6186 renderedContentEnd = end;
6187 hasRenderedContent = true;
6188 lastSeparatorPos = separator;
6189 separatorString = nextSeparatorString;
6190 }
6191 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement);
6192 }
6193}
6194
6195const NEW_ARRAY_PROPERTIES = [
6196 { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
6197 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6198];
6199const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
6200 new Method({
6201 callsArgs: [0],
6202 mutatesSelfAsArray: 'deopt-only',
6203 returns: null,
6204 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
6205 })
6206];
6207const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
6208 new Method({
6209 callsArgs: [0],
6210 mutatesSelfAsArray: 'deopt-only',
6211 returns: null,
6212 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6213 })
6214];
6215const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
6216 new Method({
6217 callsArgs: null,
6218 mutatesSelfAsArray: true,
6219 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6220 returnsPrimitive: null
6221 })
6222];
6223const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6224 new Method({
6225 callsArgs: null,
6226 mutatesSelfAsArray: 'deopt-only',
6227 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6228 returnsPrimitive: null
6229 })
6230];
6231const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6232 new Method({
6233 callsArgs: [0],
6234 mutatesSelfAsArray: 'deopt-only',
6235 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6236 returnsPrimitive: null
6237 })
6238];
6239const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
6240 new Method({
6241 callsArgs: null,
6242 mutatesSelfAsArray: true,
6243 returns: null,
6244 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6245 })
6246];
6247const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
6248 new Method({
6249 callsArgs: null,
6250 mutatesSelfAsArray: true,
6251 returns: null,
6252 returnsPrimitive: UNKNOWN_EXPRESSION
6253 })
6254];
6255const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
6256 new Method({
6257 callsArgs: null,
6258 mutatesSelfAsArray: 'deopt-only',
6259 returns: null,
6260 returnsPrimitive: UNKNOWN_EXPRESSION
6261 })
6262];
6263const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
6264 new Method({
6265 callsArgs: [0],
6266 mutatesSelfAsArray: 'deopt-only',
6267 returns: null,
6268 returnsPrimitive: UNKNOWN_EXPRESSION
6269 })
6270];
6271const METHOD_MUTATES_SELF_RETURNS_SELF = [
6272 new Method({
6273 callsArgs: null,
6274 mutatesSelfAsArray: true,
6275 returns: 'self',
6276 returnsPrimitive: null
6277 })
6278];
6279const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
6280 new Method({
6281 callsArgs: [0],
6282 mutatesSelfAsArray: true,
6283 returns: 'self',
6284 returnsPrimitive: null
6285 })
6286];
6287const ARRAY_PROTOTYPE = new ObjectEntity({
6288 __proto__: null,
6289 // We assume that accessors have effects as we do not track the accessed value afterwards
6290 at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
6291 concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6292 copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
6293 entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6294 every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6295 fill: METHOD_MUTATES_SELF_RETURNS_SELF,
6296 filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6297 find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6298 findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
6299 forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6300 includes: METHOD_RETURNS_BOOLEAN,
6301 indexOf: METHOD_RETURNS_NUMBER,
6302 join: METHOD_RETURNS_STRING,
6303 keys: METHOD_RETURNS_UNKNOWN,
6304 lastIndexOf: METHOD_RETURNS_NUMBER,
6305 map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6306 pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6307 push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6308 reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6309 reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6310 reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
6311 shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6312 slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6313 some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6314 sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
6315 splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
6316 unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6317 values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
6318}, OBJECT_PROTOTYPE, true);
6319
6320class ArrayExpression extends NodeBase {
6321 constructor() {
6322 super(...arguments);
6323 this.objectEntity = null;
6324 }
6325 deoptimizePath(path) {
6326 this.getObjectEntity().deoptimizePath(path);
6327 }
6328 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
6329 this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
6330 }
6331 getLiteralValueAtPath(path, recursionTracker, origin) {
6332 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
6333 }
6334 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
6335 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
6336 }
6337 hasEffectsWhenAccessedAtPath(path, context) {
6338 return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
6339 }
6340 hasEffectsWhenAssignedAtPath(path, context) {
6341 return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
6342 }
6343 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6344 return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
6345 }
6346 getObjectEntity() {
6347 if (this.objectEntity !== null) {
6348 return this.objectEntity;
6349 }
6350 const properties = [
6351 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6352 ];
6353 let hasSpread = false;
6354 for (let index = 0; index < this.elements.length; index++) {
6355 const element = this.elements[index];
6356 if (element instanceof SpreadElement || hasSpread) {
6357 if (element) {
6358 hasSpread = true;
6359 properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
6360 }
6361 }
6362 else if (!element) {
6363 properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
6364 }
6365 else {
6366 properties.push({ key: String(index), kind: 'init', property: element });
6367 }
6368 }
6369 return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
6370 }
6371}
6372
6373class ArrayPattern extends NodeBase {
6374 addExportedVariables(variables, exportNamesByVariable) {
6375 for (const element of this.elements) {
6376 if (element !== null) {
6377 element.addExportedVariables(variables, exportNamesByVariable);
6378 }
6379 }
6380 }
6381 declare(kind) {
6382 const variables = [];
6383 for (const element of this.elements) {
6384 if (element !== null) {
6385 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
6386 }
6387 }
6388 return variables;
6389 }
6390 deoptimizePath(path) {
6391 if (path.length === 0) {
6392 for (const element of this.elements) {
6393 if (element !== null) {
6394 element.deoptimizePath(path);
6395 }
6396 }
6397 }
6398 }
6399 hasEffectsWhenAssignedAtPath(path, context) {
6400 if (path.length > 0)
6401 return true;
6402 for (const element of this.elements) {
6403 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
6404 return true;
6405 }
6406 return false;
6407 }
6408 markDeclarationReached() {
6409 for (const element of this.elements) {
6410 if (element !== null) {
6411 element.markDeclarationReached();
6412 }
6413 }
6414 }
6415}
6416
6417class BlockScope extends ChildScope {
6418 addDeclaration(identifier, context, init, isHoisted) {
6419 if (isHoisted) {
6420 const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
6421 // Necessary to make sure the init is deoptimized for conditional declarations.
6422 // We cannot call deoptimizePath here.
6423 variable.markInitializersForDeoptimization();
6424 return variable;
6425 }
6426 else {
6427 return super.addDeclaration(identifier, context, init, false);
6428 }
6429 }
6430}
6431
6432class ExpressionStatement extends NodeBase {
6433 initialise() {
6434 if (this.directive &&
6435 this.directive !== 'use strict' &&
6436 this.parent.type === Program$1) {
6437 this.context.warn(
6438 // This is necessary, because either way (deleting or not) can lead to errors.
6439 {
6440 code: 'MODULE_LEVEL_DIRECTIVE',
6441 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
6442 }, this.start);
6443 }
6444 }
6445 render(code, options) {
6446 super.render(code, options);
6447 if (this.included)
6448 this.insertSemicolon(code);
6449 }
6450 shouldBeIncluded(context) {
6451 if (this.directive && this.directive !== 'use strict')
6452 return this.parent.type !== Program$1;
6453 return super.shouldBeIncluded(context);
6454 }
6455}
6456
6457class BlockStatement extends NodeBase {
6458 constructor() {
6459 super(...arguments);
6460 this.directlyIncluded = false;
6461 }
6462 addImplicitReturnExpressionToScope() {
6463 const lastStatement = this.body[this.body.length - 1];
6464 if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
6465 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
6466 }
6467 }
6468 createScope(parentScope) {
6469 this.scope = this.parent.preventChildBlockScope
6470 ? parentScope
6471 : new BlockScope(parentScope);
6472 }
6473 hasEffects(context) {
6474 if (this.deoptimizeBody)
6475 return true;
6476 for (const node of this.body) {
6477 if (node.hasEffects(context))
6478 return true;
6479 if (context.brokenFlow)
6480 break;
6481 }
6482 return false;
6483 }
6484 include(context, includeChildrenRecursively) {
6485 if (!this.deoptimizeBody || !this.directlyIncluded) {
6486 this.included = true;
6487 this.directlyIncluded = true;
6488 if (this.deoptimizeBody)
6489 includeChildrenRecursively = true;
6490 for (const node of this.body) {
6491 if (includeChildrenRecursively || node.shouldBeIncluded(context))
6492 node.include(context, includeChildrenRecursively);
6493 }
6494 }
6495 }
6496 initialise() {
6497 const firstBodyStatement = this.body[0];
6498 this.deoptimizeBody =
6499 firstBodyStatement instanceof ExpressionStatement &&
6500 firstBodyStatement.directive === 'use asm';
6501 }
6502 render(code, options) {
6503 if (this.body.length) {
6504 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
6505 }
6506 else {
6507 super.render(code, options);
6508 }
6509 }
6510}
6511
6512class ArrowFunctionExpression extends NodeBase {
6513 constructor() {
6514 super(...arguments);
6515 this.deoptimizedReturn = false;
6516 }
6517 createScope(parentScope) {
6518 this.scope = new ReturnValueScope(parentScope, this.context);
6519 }
6520 deoptimizePath(path) {
6521 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
6522 // which means the return expression needs to be reassigned
6523 if (path.length === 1 && path[0] === UnknownKey) {
6524 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6525 }
6526 }
6527 // Arrow functions do not mutate their context
6528 deoptimizeThisOnEventAtPath() { }
6529 getReturnExpressionWhenCalledAtPath(path) {
6530 if (path.length !== 0) {
6531 return UNKNOWN_EXPRESSION;
6532 }
6533 if (this.async) {
6534 if (!this.deoptimizedReturn) {
6535 this.deoptimizedReturn = true;
6536 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6537 this.context.requestTreeshakingPass();
6538 }
6539 return UNKNOWN_EXPRESSION;
6540 }
6541 return this.scope.getReturnExpression();
6542 }
6543 hasEffects() {
6544 return false;
6545 }
6546 hasEffectsWhenAccessedAtPath(path) {
6547 return path.length > 1;
6548 }
6549 hasEffectsWhenAssignedAtPath(path) {
6550 return path.length > 1;
6551 }
6552 hasEffectsWhenCalledAtPath(path, _callOptions, context) {
6553 if (path.length > 0)
6554 return true;
6555 if (this.async) {
6556 const { propertyReadSideEffects } = this.context.options
6557 .treeshake;
6558 const returnExpression = this.scope.getReturnExpression();
6559 if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
6560 (propertyReadSideEffects &&
6561 (propertyReadSideEffects === 'always' ||
6562 returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
6563 return true;
6564 }
6565 }
6566 for (const param of this.params) {
6567 if (param.hasEffects(context))
6568 return true;
6569 }
6570 const { ignore, brokenFlow } = context;
6571 context.ignore = {
6572 breaks: false,
6573 continues: false,
6574 labels: new Set(),
6575 returnYield: true
6576 };
6577 if (this.body.hasEffects(context))
6578 return true;
6579 context.ignore = ignore;
6580 context.brokenFlow = brokenFlow;
6581 return false;
6582 }
6583 include(context, includeChildrenRecursively) {
6584 this.included = true;
6585 for (const param of this.params) {
6586 if (!(param instanceof Identifier)) {
6587 param.include(context, includeChildrenRecursively);
6588 }
6589 }
6590 const { brokenFlow } = context;
6591 context.brokenFlow = BROKEN_FLOW_NONE;
6592 this.body.include(context, includeChildrenRecursively);
6593 context.brokenFlow = brokenFlow;
6594 }
6595 includeCallArguments(context, args) {
6596 this.scope.includeCallArguments(context, args);
6597 }
6598 initialise() {
6599 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
6600 if (this.body instanceof BlockStatement) {
6601 this.body.addImplicitReturnExpressionToScope();
6602 }
6603 else {
6604 this.scope.addReturnExpression(this.body);
6605 }
6606 }
6607 parseNode(esTreeNode) {
6608 if (esTreeNode.body.type === BlockStatement$1) {
6609 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
6610 }
6611 super.parseNode(esTreeNode);
6612 }
6613}
6614ArrowFunctionExpression.prototype.preventChildBlockScope = true;
6615
6616class AssignmentExpression extends NodeBase {
6617 constructor() {
6618 super(...arguments);
6619 this.deoptimized = false;
6620 }
6621 hasEffects(context) {
6622 if (!this.deoptimized)
6623 this.applyDeoptimizations();
6624 return (this.right.hasEffects(context) ||
6625 this.left.hasEffects(context) ||
6626 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
6627 }
6628 hasEffectsWhenAccessedAtPath(path, context) {
6629 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
6630 }
6631 include(context, includeChildrenRecursively) {
6632 if (!this.deoptimized)
6633 this.applyDeoptimizations();
6634 this.included = true;
6635 let hasEffectsContext;
6636 if (includeChildrenRecursively ||
6637 this.operator !== '=' ||
6638 this.left.included ||
6639 ((hasEffectsContext = createHasEffectsContext()),
6640 this.left.hasEffects(hasEffectsContext) ||
6641 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, hasEffectsContext))) {
6642 this.left.include(context, includeChildrenRecursively);
6643 }
6644 this.right.include(context, includeChildrenRecursively);
6645 }
6646 render(code, options, { preventASI, renderedParentType } = BLANK) {
6647 if (this.left.included) {
6648 this.left.render(code, options);
6649 this.right.render(code, options);
6650 }
6651 else {
6652 const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', this.left.end) + 1);
6653 code.remove(this.start, inclusionStart);
6654 if (preventASI) {
6655 removeLineBreaks(code, inclusionStart, this.right.start);
6656 }
6657 this.right.render(code, options, {
6658 renderedParentType: renderedParentType || this.parent.type
6659 });
6660 }
6661 if (options.format === 'system') {
6662 const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
6663 if (this.left.type === 'Identifier' && exportNames) {
6664 const _ = options.compact ? '' : ' ';
6665 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
6666 const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
6667 code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
6668 ? `exports('${exportNames[0]}',${_}`
6669 : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
6670 code.appendLeft(this.right.end, ')');
6671 }
6672 else {
6673 const systemPatternExports = [];
6674 this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
6675 if (systemPatternExports.length > 0) {
6676 code.prependRight(this.start, `(${getSystemExportFunctionLeft(systemPatternExports, true, options)}`);
6677 code.appendLeft(this.end, '))');
6678 }
6679 }
6680 }
6681 }
6682 applyDeoptimizations() {
6683 this.deoptimized = true;
6684 this.left.deoptimizePath(EMPTY_PATH);
6685 this.right.deoptimizePath(UNKNOWN_PATH);
6686 this.context.requestTreeshakingPass();
6687 }
6688}
6689
6690class AssignmentPattern extends NodeBase {
6691 constructor() {
6692 super(...arguments);
6693 this.deoptimized = false;
6694 }
6695 addExportedVariables(variables, exportNamesByVariable) {
6696 this.left.addExportedVariables(variables, exportNamesByVariable);
6697 }
6698 declare(kind, init) {
6699 return this.left.declare(kind, init);
6700 }
6701 deoptimizePath(path) {
6702 path.length === 0 && this.left.deoptimizePath(path);
6703 }
6704 hasEffectsWhenAssignedAtPath(path, context) {
6705 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
6706 }
6707 markDeclarationReached() {
6708 this.left.markDeclarationReached();
6709 }
6710 render(code, options, { isShorthandProperty } = BLANK) {
6711 this.left.render(code, options, { isShorthandProperty });
6712 this.right.render(code, options);
6713 }
6714 applyDeoptimizations() {
6715 this.deoptimized = true;
6716 this.left.deoptimizePath(EMPTY_PATH);
6717 this.right.deoptimizePath(UNKNOWN_PATH);
6718 this.context.requestTreeshakingPass();
6719 }
6720}
6721
6722class AwaitExpression extends NodeBase {
6723 constructor() {
6724 super(...arguments);
6725 this.deoptimized = false;
6726 }
6727 hasEffects() {
6728 if (!this.deoptimized)
6729 this.applyDeoptimizations();
6730 return true;
6731 }
6732 include(context, includeChildrenRecursively) {
6733 if (!this.deoptimized)
6734 this.applyDeoptimizations();
6735 if (!this.included) {
6736 this.included = true;
6737 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
6738 let parent = this.parent;
6739 do {
6740 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
6741 break checkTopLevelAwait;
6742 } while ((parent = parent.parent));
6743 this.context.usesTopLevelAwait = true;
6744 }
6745 }
6746 this.argument.include(context, includeChildrenRecursively);
6747 }
6748 applyDeoptimizations() {
6749 this.deoptimized = true;
6750 this.argument.deoptimizePath(UNKNOWN_PATH);
6751 this.context.requestTreeshakingPass();
6752 }
6753}
6754
6755const binaryOperators = {
6756 '!=': (left, right) => left != right,
6757 '!==': (left, right) => left !== right,
6758 '%': (left, right) => left % right,
6759 '&': (left, right) => left & right,
6760 '*': (left, right) => left * right,
6761 // At the moment, "**" will be transpiled to Math.pow
6762 '**': (left, right) => left ** right,
6763 '+': (left, right) => left + right,
6764 '-': (left, right) => left - right,
6765 '/': (left, right) => left / right,
6766 '<': (left, right) => left < right,
6767 '<<': (left, right) => left << right,
6768 '<=': (left, right) => left <= right,
6769 '==': (left, right) => left == right,
6770 '===': (left, right) => left === right,
6771 '>': (left, right) => left > right,
6772 '>=': (left, right) => left >= right,
6773 '>>': (left, right) => left >> right,
6774 '>>>': (left, right) => left >>> right,
6775 '^': (left, right) => left ^ right,
6776 in: () => UnknownValue,
6777 instanceof: () => UnknownValue,
6778 '|': (left, right) => left | right
6779};
6780class BinaryExpression extends NodeBase {
6781 deoptimizeCache() { }
6782 getLiteralValueAtPath(path, recursionTracker, origin) {
6783 if (path.length > 0)
6784 return UnknownValue;
6785 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6786 if (leftValue === UnknownValue)
6787 return UnknownValue;
6788 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6789 if (rightValue === UnknownValue)
6790 return UnknownValue;
6791 const operatorFn = binaryOperators[this.operator];
6792 if (!operatorFn)
6793 return UnknownValue;
6794 return operatorFn(leftValue, rightValue);
6795 }
6796 hasEffects(context) {
6797 // support some implicit type coercion runtime errors
6798 if (this.operator === '+' &&
6799 this.parent instanceof ExpressionStatement &&
6800 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
6801 return true;
6802 return super.hasEffects(context);
6803 }
6804 hasEffectsWhenAccessedAtPath(path) {
6805 return path.length > 1;
6806 }
6807 render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
6808 this.left.render(code, options, {
6809 renderedSurroundingElement: renderedParentType || renderedSurroundingElement
6810 });
6811 this.right.render(code, options);
6812 }
6813}
6814
6815class BreakStatement extends NodeBase {
6816 hasEffects(context) {
6817 if (this.label) {
6818 if (!context.ignore.labels.has(this.label.name))
6819 return true;
6820 context.includedLabels.add(this.label.name);
6821 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6822 }
6823 else {
6824 if (!context.ignore.breaks)
6825 return true;
6826 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6827 }
6828 return false;
6829 }
6830 include(context) {
6831 this.included = true;
6832 if (this.label) {
6833 this.label.include();
6834 context.includedLabels.add(this.label.name);
6835 }
6836 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6837 }
6838}
6839
6840// To avoid infinite recursions
6841const MAX_PATH_DEPTH = 7;
6842function getResolvablePropertyKey(memberExpression) {
6843 return memberExpression.computed
6844 ? getResolvableComputedPropertyKey(memberExpression.property)
6845 : memberExpression.property.name;
6846}
6847function getResolvableComputedPropertyKey(propertyKey) {
6848 if (propertyKey instanceof Literal) {
6849 return String(propertyKey.value);
6850 }
6851 return null;
6852}
6853function getPathIfNotComputed(memberExpression) {
6854 const nextPathKey = memberExpression.propertyKey;
6855 const object = memberExpression.object;
6856 if (typeof nextPathKey === 'string') {
6857 if (object instanceof Identifier) {
6858 return [
6859 { key: object.name, pos: object.start },
6860 { key: nextPathKey, pos: memberExpression.property.start }
6861 ];
6862 }
6863 if (object instanceof MemberExpression) {
6864 const parentPath = getPathIfNotComputed(object);
6865 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
6866 }
6867 }
6868 return null;
6869}
6870function getStringFromPath(path) {
6871 let pathString = path[0].key;
6872 for (let index = 1; index < path.length; index++) {
6873 pathString += '.' + path[index].key;
6874 }
6875 return pathString;
6876}
6877class MemberExpression extends NodeBase {
6878 constructor() {
6879 super(...arguments);
6880 this.variable = null;
6881 this.deoptimized = false;
6882 this.bound = false;
6883 this.expressionsToBeDeoptimized = [];
6884 this.replacement = null;
6885 }
6886 bind() {
6887 this.bound = true;
6888 const path = getPathIfNotComputed(this);
6889 const baseVariable = path && this.scope.findVariable(path[0].key);
6890 if (baseVariable && baseVariable.isNamespace) {
6891 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
6892 if (!resolvedVariable) {
6893 super.bind();
6894 }
6895 else if (typeof resolvedVariable === 'string') {
6896 this.replacement = resolvedVariable;
6897 }
6898 else {
6899 this.variable = resolvedVariable;
6900 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
6901 }
6902 }
6903 else {
6904 super.bind();
6905 }
6906 }
6907 deoptimizeCache() {
6908 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6909 this.expressionsToBeDeoptimized = [];
6910 this.propertyKey = UnknownKey;
6911 this.object.deoptimizePath(UNKNOWN_PATH);
6912 for (const expression of expressionsToBeDeoptimized) {
6913 expression.deoptimizeCache();
6914 }
6915 }
6916 deoptimizePath(path) {
6917 if (path.length === 0)
6918 this.disallowNamespaceReassignment();
6919 if (this.variable) {
6920 this.variable.deoptimizePath(path);
6921 }
6922 else if (!this.replacement) {
6923 if (path.length < MAX_PATH_DEPTH) {
6924 this.object.deoptimizePath([this.getPropertyKey(), ...path]);
6925 }
6926 }
6927 }
6928 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
6929 if (this.variable) {
6930 this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
6931 }
6932 else if (!this.replacement) {
6933 if (path.length < MAX_PATH_DEPTH) {
6934 this.object.deoptimizeThisOnEventAtPath(event, [this.getPropertyKey(), ...path], thisParameter, recursionTracker);
6935 }
6936 else {
6937 thisParameter.deoptimizePath(UNKNOWN_PATH);
6938 }
6939 }
6940 }
6941 getLiteralValueAtPath(path, recursionTracker, origin) {
6942 if (this.variable !== null) {
6943 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
6944 }
6945 if (this.replacement) {
6946 return UnknownValue;
6947 }
6948 this.expressionsToBeDeoptimized.push(origin);
6949 if (path.length < MAX_PATH_DEPTH) {
6950 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
6951 }
6952 return UnknownValue;
6953 }
6954 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
6955 if (this.variable !== null) {
6956 return this.variable.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
6957 }
6958 if (this.replacement) {
6959 return UNKNOWN_EXPRESSION;
6960 }
6961 this.expressionsToBeDeoptimized.push(origin);
6962 if (path.length < MAX_PATH_DEPTH) {
6963 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, recursionTracker, origin);
6964 }
6965 return UNKNOWN_EXPRESSION;
6966 }
6967 hasEffects(context) {
6968 if (!this.deoptimized)
6969 this.applyDeoptimizations();
6970 const { propertyReadSideEffects } = this.context.options
6971 .treeshake;
6972 return (this.property.hasEffects(context) ||
6973 this.object.hasEffects(context) ||
6974 // Assignments do not access the property before assigning
6975 (!(this.variable ||
6976 this.replacement ||
6977 (this.parent instanceof AssignmentExpression && this.parent.operator === '=')) &&
6978 propertyReadSideEffects &&
6979 (propertyReadSideEffects === 'always' ||
6980 this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey()], context))));
6981 }
6982 hasEffectsWhenAccessedAtPath(path, context) {
6983 if (this.variable !== null) {
6984 return this.variable.hasEffectsWhenAccessedAtPath(path, context);
6985 }
6986 if (this.replacement) {
6987 return true;
6988 }
6989 if (path.length < MAX_PATH_DEPTH) {
6990 return this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey(), ...path], context);
6991 }
6992 return true;
6993 }
6994 hasEffectsWhenAssignedAtPath(path, context) {
6995 if (this.variable !== null) {
6996 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
6997 }
6998 if (this.replacement) {
6999 return true;
7000 }
7001 if (path.length < MAX_PATH_DEPTH) {
7002 return this.object.hasEffectsWhenAssignedAtPath([this.getPropertyKey(), ...path], context);
7003 }
7004 return true;
7005 }
7006 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7007 if (this.variable !== null) {
7008 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
7009 }
7010 if (this.replacement) {
7011 return true;
7012 }
7013 if (path.length < MAX_PATH_DEPTH) {
7014 return this.object.hasEffectsWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, context);
7015 }
7016 return true;
7017 }
7018 include(context, includeChildrenRecursively) {
7019 if (!this.deoptimized)
7020 this.applyDeoptimizations();
7021 if (!this.included) {
7022 this.included = true;
7023 if (this.variable !== null) {
7024 this.context.includeVariableInModule(this.variable);
7025 }
7026 }
7027 this.object.include(context, includeChildrenRecursively);
7028 this.property.include(context, includeChildrenRecursively);
7029 }
7030 includeCallArguments(context, args) {
7031 if (this.variable) {
7032 this.variable.includeCallArguments(context, args);
7033 }
7034 else {
7035 super.includeCallArguments(context, args);
7036 }
7037 }
7038 initialise() {
7039 this.propertyKey = getResolvablePropertyKey(this);
7040 }
7041 render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
7042 if (this.variable || this.replacement) {
7043 let replacement = this.variable ? this.variable.getName() : this.replacement;
7044 if (renderedParentType && isCalleeOfRenderedParent)
7045 replacement = '0, ' + replacement;
7046 code.overwrite(this.start, this.end, replacement, {
7047 contentOnly: true,
7048 storeName: true
7049 });
7050 }
7051 else {
7052 if (renderedParentType && isCalleeOfRenderedParent) {
7053 code.appendRight(this.start, '0, ');
7054 }
7055 const surroundingElement = renderedParentType || renderedSurroundingElement;
7056 this.object.render(code, options, surroundingElement ? { renderedSurroundingElement: surroundingElement } : BLANK);
7057 this.property.render(code, options);
7058 }
7059 }
7060 applyDeoptimizations() {
7061 this.deoptimized = true;
7062 const { propertyReadSideEffects } = this.context.options
7063 .treeshake;
7064 if (
7065 // Namespaces are not bound and should not be deoptimized
7066 this.bound &&
7067 propertyReadSideEffects &&
7068 !(this.variable || this.replacement)) {
7069 // Regular Assignments do not access the property before assigning
7070 if (!(this.parent instanceof AssignmentExpression && this.parent.operator === '=')) {
7071 this.object.deoptimizeThisOnEventAtPath(EVENT_ACCESSED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
7072 }
7073 if (this.parent instanceof AssignmentExpression) {
7074 this.object.deoptimizeThisOnEventAtPath(EVENT_ASSIGNED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
7075 }
7076 this.context.requestTreeshakingPass();
7077 }
7078 }
7079 disallowNamespaceReassignment() {
7080 if (this.object instanceof Identifier) {
7081 const variable = this.scope.findVariable(this.object.name);
7082 if (variable.isNamespace) {
7083 if (this.variable) {
7084 this.context.includeVariableInModule(this.variable);
7085 }
7086 this.context.warn({
7087 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
7088 message: `Illegal reassignment to import '${this.object.name}'`
7089 }, this.start);
7090 }
7091 }
7092 }
7093 getPropertyKey() {
7094 if (this.propertyKey === null) {
7095 this.propertyKey = UnknownKey;
7096 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7097 return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
7098 }
7099 return this.propertyKey;
7100 }
7101 resolveNamespaceVariables(baseVariable, path) {
7102 if (path.length === 0)
7103 return baseVariable;
7104 if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
7105 return null;
7106 const exportName = path[0].key;
7107 const variable = baseVariable.context.traceExport(exportName);
7108 if (!variable) {
7109 const fileName = baseVariable.context.fileName;
7110 this.context.warn({
7111 code: 'MISSING_EXPORT',
7112 exporter: relativeId(fileName),
7113 importer: relativeId(this.context.fileName),
7114 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
7115 missing: exportName,
7116 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
7117 }, path[0].pos);
7118 return 'undefined';
7119 }
7120 return this.resolveNamespaceVariables(variable, path.slice(1));
7121 }
7122}
7123
7124class CallExpression extends NodeBase {
7125 constructor() {
7126 super(...arguments);
7127 this.deoptimized = false;
7128 this.deoptimizableDependentExpressions = [];
7129 this.expressionsToBeDeoptimized = new Set();
7130 this.returnExpression = null;
7131 }
7132 bind() {
7133 super.bind();
7134 if (this.callee instanceof Identifier) {
7135 const variable = this.scope.findVariable(this.callee.name);
7136 if (variable.isNamespace) {
7137 this.context.warn({
7138 code: 'CANNOT_CALL_NAMESPACE',
7139 message: `Cannot call a namespace ('${this.callee.name}')`
7140 }, this.start);
7141 }
7142 if (this.callee.name === 'eval') {
7143 this.context.warn({
7144 code: 'EVAL',
7145 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
7146 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
7147 }, this.start);
7148 }
7149 }
7150 this.callOptions = {
7151 args: this.arguments,
7152 thisParam: this.callee instanceof MemberExpression && !this.callee.variable
7153 ? this.callee.object
7154 : null,
7155 withNew: false
7156 };
7157 }
7158 deoptimizeCache() {
7159 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
7160 this.returnExpression = UNKNOWN_EXPRESSION;
7161 for (const expression of this.deoptimizableDependentExpressions) {
7162 expression.deoptimizeCache();
7163 }
7164 for (const expression of this.expressionsToBeDeoptimized) {
7165 expression.deoptimizePath(UNKNOWN_PATH);
7166 }
7167 }
7168 }
7169 deoptimizePath(path) {
7170 if (path.length === 0 ||
7171 this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
7172 return;
7173 }
7174 const returnExpression = this.getReturnExpression();
7175 if (returnExpression !== UNKNOWN_EXPRESSION) {
7176 returnExpression.deoptimizePath(path);
7177 }
7178 }
7179 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
7180 const returnExpression = this.getReturnExpression(recursionTracker);
7181 if (returnExpression === UNKNOWN_EXPRESSION) {
7182 thisParameter.deoptimizePath(UNKNOWN_PATH);
7183 }
7184 else {
7185 recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
7186 this.expressionsToBeDeoptimized.add(thisParameter);
7187 returnExpression.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
7188 }, undefined);
7189 }
7190 }
7191 getLiteralValueAtPath(path, recursionTracker, origin) {
7192 const returnExpression = this.getReturnExpression(recursionTracker);
7193 if (returnExpression === UNKNOWN_EXPRESSION) {
7194 return UnknownValue;
7195 }
7196 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
7197 this.deoptimizableDependentExpressions.push(origin);
7198 return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
7199 }, UnknownValue);
7200 }
7201 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
7202 const returnExpression = this.getReturnExpression(recursionTracker);
7203 if (this.returnExpression === UNKNOWN_EXPRESSION) {
7204 return UNKNOWN_EXPRESSION;
7205 }
7206 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
7207 this.deoptimizableDependentExpressions.push(origin);
7208 return returnExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
7209 }, UNKNOWN_EXPRESSION);
7210 }
7211 hasEffects(context) {
7212 try {
7213 for (const argument of this.arguments) {
7214 if (argument.hasEffects(context))
7215 return true;
7216 }
7217 if (this.context.options.treeshake.annotations &&
7218 this.annotations)
7219 return false;
7220 return (this.callee.hasEffects(context) ||
7221 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
7222 }
7223 finally {
7224 if (!this.deoptimized)
7225 this.applyDeoptimizations();
7226 }
7227 }
7228 hasEffectsWhenAccessedAtPath(path, context) {
7229 return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
7230 this.getReturnExpression().hasEffectsWhenAccessedAtPath(path, context));
7231 }
7232 hasEffectsWhenAssignedAtPath(path, context) {
7233 return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
7234 this.getReturnExpression().hasEffectsWhenAssignedAtPath(path, context));
7235 }
7236 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7237 return (!(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
7238 this.getReturnExpression().hasEffectsWhenCalledAtPath(path, callOptions, context));
7239 }
7240 include(context, includeChildrenRecursively) {
7241 if (!this.deoptimized)
7242 this.applyDeoptimizations();
7243 if (includeChildrenRecursively) {
7244 super.include(context, includeChildrenRecursively);
7245 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
7246 this.callee instanceof Identifier &&
7247 this.callee.variable) {
7248 this.callee.variable.markCalledFromTryStatement();
7249 }
7250 }
7251 else {
7252 this.included = true;
7253 this.callee.include(context, false);
7254 }
7255 this.callee.includeCallArguments(context, this.arguments);
7256 const returnExpression = this.getReturnExpression();
7257 if (!returnExpression.included) {
7258 returnExpression.include(context, false);
7259 }
7260 }
7261 render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
7262 const surroundingELement = renderedParentType || renderedSurroundingElement;
7263 this.callee.render(code, options, {
7264 isCalleeOfRenderedParent: true,
7265 renderedSurroundingElement: surroundingELement
7266 });
7267 if (this.arguments.length > 0) {
7268 if (this.arguments[this.arguments.length - 1].included) {
7269 for (const arg of this.arguments) {
7270 arg.render(code, options);
7271 }
7272 }
7273 else {
7274 let lastIncludedIndex = this.arguments.length - 2;
7275 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
7276 lastIncludedIndex--;
7277 }
7278 if (lastIncludedIndex >= 0) {
7279 for (let index = 0; index <= lastIncludedIndex; index++) {
7280 this.arguments[index].render(code, options);
7281 }
7282 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
7283 }
7284 else {
7285 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
7286 }
7287 }
7288 }
7289 }
7290 applyDeoptimizations() {
7291 this.deoptimized = true;
7292 const { thisParam } = this.callOptions;
7293 if (thisParam) {
7294 this.callee.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParam, SHARED_RECURSION_TRACKER);
7295 }
7296 for (const argument of this.arguments) {
7297 // This will make sure all properties of parameters behave as "unknown"
7298 argument.deoptimizePath(UNKNOWN_PATH);
7299 }
7300 this.context.requestTreeshakingPass();
7301 }
7302 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
7303 if (this.returnExpression === null) {
7304 this.returnExpression = UNKNOWN_EXPRESSION;
7305 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.callOptions, recursionTracker, this));
7306 }
7307 return this.returnExpression;
7308 }
7309}
7310
7311class CatchScope extends ParameterScope {
7312 addDeclaration(identifier, context, init, isHoisted) {
7313 const existingParameter = this.variables.get(identifier.name);
7314 if (existingParameter) {
7315 // While we still create a hoisted declaration, the initializer goes to
7316 // the parameter. Note that technically, the declaration now belongs to
7317 // two variables, which is not correct but should not cause issues.
7318 this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
7319 existingParameter.addDeclaration(identifier, init);
7320 return existingParameter;
7321 }
7322 return this.parent.addDeclaration(identifier, context, init, isHoisted);
7323 }
7324}
7325
7326class CatchClause extends NodeBase {
7327 createScope(parentScope) {
7328 this.scope = new CatchScope(parentScope, this.context);
7329 }
7330 parseNode(esTreeNode) {
7331 // Parameters need to be declared first as the logic is that initializers
7332 // of hoisted body variables are associated with parameters of the same
7333 // name instead of the variable
7334 const { param } = esTreeNode;
7335 if (param) {
7336 this.param = new (this.context.nodeConstructors[param.type] ||
7337 this.context.nodeConstructors.UnknownNode)(param, this, this.scope);
7338 this.param.declare('parameter', UNKNOWN_EXPRESSION);
7339 }
7340 super.parseNode(esTreeNode);
7341 }
7342}
7343
7344class ChainExpression extends NodeBase {
7345}
7346
7347class ClassBodyScope extends ChildScope {
7348 constructor(parent, classNode, context) {
7349 super(parent);
7350 this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
7351 this.instanceScope = new ChildScope(this);
7352 this.instanceScope.variables.set('this', new ThisVariable(context));
7353 }
7354 findLexicalBoundary() {
7355 return this;
7356 }
7357}
7358
7359class ClassBody extends NodeBase {
7360 createScope(parentScope) {
7361 this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
7362 }
7363 include(context, includeChildrenRecursively) {
7364 this.included = true;
7365 this.context.includeVariableInModule(this.scope.thisVariable);
7366 for (const definition of this.body) {
7367 definition.include(context, includeChildrenRecursively);
7368 }
7369 }
7370 parseNode(esTreeNode) {
7371 const body = (this.body = []);
7372 for (const definition of esTreeNode.body) {
7373 body.push(new this.context.nodeConstructors[definition.type](definition, this, definition.static ? this.scope : this.scope.instanceScope));
7374 }
7375 super.parseNode(esTreeNode);
7376 }
7377}
7378
7379class ClassExpression extends ClassNode {
7380 render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
7381 super.render(code, options);
7382 const surroundingElement = renderedParentType || renderedSurroundingElement;
7383 if (surroundingElement === ExpressionStatement$1) {
7384 code.appendRight(this.start, '(');
7385 code.prependLeft(this.end, ')');
7386 }
7387 }
7388}
7389
7390class MultiExpression extends ExpressionEntity {
7391 constructor(expressions) {
7392 super();
7393 this.expressions = expressions;
7394 this.included = false;
7395 }
7396 deoptimizePath(path) {
7397 for (const expression of this.expressions) {
7398 expression.deoptimizePath(path);
7399 }
7400 }
7401 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
7402 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)));
7403 }
7404 hasEffectsWhenAccessedAtPath(path, context) {
7405 for (const expression of this.expressions) {
7406 if (expression.hasEffectsWhenAccessedAtPath(path, context))
7407 return true;
7408 }
7409 return false;
7410 }
7411 hasEffectsWhenAssignedAtPath(path, context) {
7412 for (const expression of this.expressions) {
7413 if (expression.hasEffectsWhenAssignedAtPath(path, context))
7414 return true;
7415 }
7416 return false;
7417 }
7418 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7419 for (const expression of this.expressions) {
7420 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
7421 return true;
7422 }
7423 return false;
7424 }
7425 include(context, includeChildrenRecursively) {
7426 // This is only relevant to include values that do not have an AST representation,
7427 // such as UnknownArrayExpression. Thus we only need to include them once.
7428 for (const expression of this.expressions) {
7429 if (!expression.included) {
7430 expression.include(context, includeChildrenRecursively);
7431 }
7432 }
7433 }
7434}
7435
7436class ConditionalExpression extends NodeBase {
7437 constructor() {
7438 super(...arguments);
7439 this.expressionsToBeDeoptimized = [];
7440 this.isBranchResolutionAnalysed = false;
7441 this.usedBranch = null;
7442 }
7443 deoptimizeCache() {
7444 if (this.usedBranch !== null) {
7445 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
7446 this.usedBranch = null;
7447 unusedBranch.deoptimizePath(UNKNOWN_PATH);
7448 for (const expression of this.expressionsToBeDeoptimized) {
7449 expression.deoptimizeCache();
7450 }
7451 }
7452 }
7453 deoptimizePath(path) {
7454 const usedBranch = this.getUsedBranch();
7455 if (usedBranch === null) {
7456 this.consequent.deoptimizePath(path);
7457 this.alternate.deoptimizePath(path);
7458 }
7459 else {
7460 usedBranch.deoptimizePath(path);
7461 }
7462 }
7463 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
7464 this.consequent.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
7465 this.alternate.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
7466 }
7467 getLiteralValueAtPath(path, recursionTracker, origin) {
7468 const usedBranch = this.getUsedBranch();
7469 if (usedBranch === null)
7470 return UnknownValue;
7471 this.expressionsToBeDeoptimized.push(origin);
7472 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
7473 }
7474 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
7475 const usedBranch = this.getUsedBranch();
7476 if (usedBranch === null)
7477 return new MultiExpression([
7478 this.consequent.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
7479 this.alternate.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
7480 ]);
7481 this.expressionsToBeDeoptimized.push(origin);
7482 return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
7483 }
7484 hasEffects(context) {
7485 if (this.test.hasEffects(context))
7486 return true;
7487 const usedBranch = this.getUsedBranch();
7488 if (usedBranch === null) {
7489 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
7490 }
7491 return usedBranch.hasEffects(context);
7492 }
7493 hasEffectsWhenAccessedAtPath(path, context) {
7494 const usedBranch = this.getUsedBranch();
7495 if (usedBranch === null) {
7496 return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
7497 this.alternate.hasEffectsWhenAccessedAtPath(path, context));
7498 }
7499 return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
7500 }
7501 hasEffectsWhenAssignedAtPath(path, context) {
7502 const usedBranch = this.getUsedBranch();
7503 if (usedBranch === null) {
7504 return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
7505 this.alternate.hasEffectsWhenAssignedAtPath(path, context));
7506 }
7507 return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
7508 }
7509 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7510 const usedBranch = this.getUsedBranch();
7511 if (usedBranch === null) {
7512 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
7513 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
7514 }
7515 return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
7516 }
7517 include(context, includeChildrenRecursively) {
7518 this.included = true;
7519 const usedBranch = this.getUsedBranch();
7520 if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
7521 this.test.include(context, includeChildrenRecursively);
7522 this.consequent.include(context, includeChildrenRecursively);
7523 this.alternate.include(context, includeChildrenRecursively);
7524 }
7525 else {
7526 usedBranch.include(context, includeChildrenRecursively);
7527 }
7528 }
7529 includeCallArguments(context, args) {
7530 const usedBranch = this.getUsedBranch();
7531 if (usedBranch === null) {
7532 this.consequent.includeCallArguments(context, args);
7533 this.alternate.includeCallArguments(context, args);
7534 }
7535 else {
7536 usedBranch.includeCallArguments(context, args);
7537 }
7538 }
7539 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
7540 const usedBranch = this.getUsedBranch();
7541 if (!this.test.included) {
7542 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
7543 const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
7544 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
7545 : colonPos) + 1);
7546 if (preventASI) {
7547 removeLineBreaks(code, inclusionStart, usedBranch.start);
7548 }
7549 code.remove(this.start, inclusionStart);
7550 if (this.consequent.included) {
7551 code.remove(colonPos, this.end);
7552 }
7553 removeAnnotations(this, code);
7554 usedBranch.render(code, options, {
7555 isCalleeOfRenderedParent,
7556 preventASI: true,
7557 ...(renderedSurroundingElement
7558 ? { renderedSurroundingElement }
7559 : { renderedParentType: renderedParentType || this.parent.type })
7560 });
7561 }
7562 else {
7563 this.test.render(code, options, {
7564 renderedSurroundingElement: renderedParentType || renderedSurroundingElement
7565 });
7566 this.consequent.render(code, options);
7567 this.alternate.render(code, options);
7568 }
7569 }
7570 getUsedBranch() {
7571 if (this.isBranchResolutionAnalysed) {
7572 return this.usedBranch;
7573 }
7574 this.isBranchResolutionAnalysed = true;
7575 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7576 return testValue === UnknownValue
7577 ? null
7578 : (this.usedBranch = testValue ? this.consequent : this.alternate);
7579 }
7580}
7581
7582class ContinueStatement extends NodeBase {
7583 hasEffects(context) {
7584 if (this.label) {
7585 if (!context.ignore.labels.has(this.label.name))
7586 return true;
7587 context.includedLabels.add(this.label.name);
7588 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
7589 }
7590 else {
7591 if (!context.ignore.continues)
7592 return true;
7593 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
7594 }
7595 return false;
7596 }
7597 include(context) {
7598 this.included = true;
7599 if (this.label) {
7600 this.label.include();
7601 context.includedLabels.add(this.label.name);
7602 }
7603 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
7604 }
7605}
7606
7607class DoWhileStatement extends NodeBase {
7608 hasEffects(context) {
7609 if (this.test.hasEffects(context))
7610 return true;
7611 const { brokenFlow, ignore: { breaks, continues } } = context;
7612 context.ignore.breaks = true;
7613 context.ignore.continues = true;
7614 if (this.body.hasEffects(context))
7615 return true;
7616 context.ignore.breaks = breaks;
7617 context.ignore.continues = continues;
7618 context.brokenFlow = brokenFlow;
7619 return false;
7620 }
7621 include(context, includeChildrenRecursively) {
7622 this.included = true;
7623 this.test.include(context, includeChildrenRecursively);
7624 const { brokenFlow } = context;
7625 this.body.includeAsSingleStatement(context, includeChildrenRecursively);
7626 context.brokenFlow = brokenFlow;
7627 }
7628}
7629
7630class EmptyStatement extends NodeBase {
7631 hasEffects() {
7632 return false;
7633 }
7634}
7635
7636class ExportNamedDeclaration extends NodeBase {
7637 bind() {
7638 // Do not bind specifiers
7639 if (this.declaration !== null)
7640 this.declaration.bind();
7641 }
7642 hasEffects(context) {
7643 return this.declaration !== null && this.declaration.hasEffects(context);
7644 }
7645 initialise() {
7646 this.context.addExport(this);
7647 }
7648 render(code, options, nodeRenderOptions) {
7649 const { start, end } = nodeRenderOptions;
7650 if (this.declaration === null) {
7651 code.remove(start, end);
7652 }
7653 else {
7654 code.remove(this.start, this.declaration.start);
7655 this.declaration.render(code, options, { end, start });
7656 }
7657 }
7658}
7659ExportNamedDeclaration.prototype.needsBoundaries = true;
7660
7661class ExportSpecifier extends NodeBase {
7662}
7663
7664class ForInStatement extends NodeBase {
7665 constructor() {
7666 super(...arguments);
7667 this.deoptimized = false;
7668 }
7669 createScope(parentScope) {
7670 this.scope = new BlockScope(parentScope);
7671 }
7672 hasEffects(context) {
7673 if (!this.deoptimized)
7674 this.applyDeoptimizations();
7675 if ((this.left &&
7676 (this.left.hasEffects(context) ||
7677 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
7678 (this.right && this.right.hasEffects(context)))
7679 return true;
7680 const { brokenFlow, ignore: { breaks, continues } } = context;
7681 context.ignore.breaks = true;
7682 context.ignore.continues = true;
7683 if (this.body.hasEffects(context))
7684 return true;
7685 context.ignore.breaks = breaks;
7686 context.ignore.continues = continues;
7687 context.brokenFlow = brokenFlow;
7688 return false;
7689 }
7690 include(context, includeChildrenRecursively) {
7691 if (!this.deoptimized)
7692 this.applyDeoptimizations();
7693 this.included = true;
7694 this.left.include(context, includeChildrenRecursively || true);
7695 this.right.include(context, includeChildrenRecursively);
7696 const { brokenFlow } = context;
7697 this.body.includeAsSingleStatement(context, includeChildrenRecursively);
7698 context.brokenFlow = brokenFlow;
7699 }
7700 render(code, options) {
7701 this.left.render(code, options, NO_SEMICOLON);
7702 this.right.render(code, options, NO_SEMICOLON);
7703 // handle no space between "in" and the right side
7704 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
7705 code.prependLeft(this.right.start, ' ');
7706 }
7707 this.body.render(code, options);
7708 }
7709 applyDeoptimizations() {
7710 this.deoptimized = true;
7711 this.left.deoptimizePath(EMPTY_PATH);
7712 this.context.requestTreeshakingPass();
7713 }
7714}
7715
7716class ForOfStatement extends NodeBase {
7717 constructor() {
7718 super(...arguments);
7719 this.deoptimized = false;
7720 }
7721 createScope(parentScope) {
7722 this.scope = new BlockScope(parentScope);
7723 }
7724 hasEffects() {
7725 if (!this.deoptimized)
7726 this.applyDeoptimizations();
7727 // Placeholder until proper Symbol.Iterator support
7728 return true;
7729 }
7730 include(context, includeChildrenRecursively) {
7731 if (!this.deoptimized)
7732 this.applyDeoptimizations();
7733 this.included = true;
7734 this.left.include(context, includeChildrenRecursively || true);
7735 this.right.include(context, includeChildrenRecursively);
7736 const { brokenFlow } = context;
7737 this.body.includeAsSingleStatement(context, includeChildrenRecursively);
7738 context.brokenFlow = brokenFlow;
7739 }
7740 render(code, options) {
7741 this.left.render(code, options, NO_SEMICOLON);
7742 this.right.render(code, options, NO_SEMICOLON);
7743 // handle no space between "of" and the right side
7744 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
7745 code.prependLeft(this.right.start, ' ');
7746 }
7747 this.body.render(code, options);
7748 }
7749 applyDeoptimizations() {
7750 this.deoptimized = true;
7751 this.left.deoptimizePath(EMPTY_PATH);
7752 this.context.requestTreeshakingPass();
7753 }
7754}
7755
7756class ForStatement extends NodeBase {
7757 createScope(parentScope) {
7758 this.scope = new BlockScope(parentScope);
7759 }
7760 hasEffects(context) {
7761 if ((this.init && this.init.hasEffects(context)) ||
7762 (this.test && this.test.hasEffects(context)) ||
7763 (this.update && this.update.hasEffects(context)))
7764 return true;
7765 const { brokenFlow, ignore: { breaks, continues } } = context;
7766 context.ignore.breaks = true;
7767 context.ignore.continues = true;
7768 if (this.body.hasEffects(context))
7769 return true;
7770 context.ignore.breaks = breaks;
7771 context.ignore.continues = continues;
7772 context.brokenFlow = brokenFlow;
7773 return false;
7774 }
7775 include(context, includeChildrenRecursively) {
7776 this.included = true;
7777 if (this.init)
7778 this.init.includeAsSingleStatement(context, includeChildrenRecursively);
7779 if (this.test)
7780 this.test.include(context, includeChildrenRecursively);
7781 const { brokenFlow } = context;
7782 if (this.update)
7783 this.update.include(context, includeChildrenRecursively);
7784 this.body.includeAsSingleStatement(context, includeChildrenRecursively);
7785 context.brokenFlow = brokenFlow;
7786 }
7787 render(code, options) {
7788 if (this.init)
7789 this.init.render(code, options, NO_SEMICOLON);
7790 if (this.test)
7791 this.test.render(code, options, NO_SEMICOLON);
7792 if (this.update)
7793 this.update.render(code, options, NO_SEMICOLON);
7794 this.body.render(code, options);
7795 }
7796}
7797
7798class FunctionExpression extends FunctionNode {
7799 render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
7800 super.render(code, options);
7801 const surroundingElement = renderedParentType || renderedSurroundingElement;
7802 if (surroundingElement === ExpressionStatement$1) {
7803 code.appendRight(this.start, '(');
7804 code.prependLeft(this.end, ')');
7805 }
7806 }
7807}
7808
7809class TrackingScope extends BlockScope {
7810 constructor() {
7811 super(...arguments);
7812 this.hoistedDeclarations = [];
7813 }
7814 addDeclaration(identifier, context, init, isHoisted) {
7815 this.hoistedDeclarations.push(identifier);
7816 return super.addDeclaration(identifier, context, init, isHoisted);
7817 }
7818}
7819
7820const unset = Symbol('unset');
7821class IfStatement extends NodeBase {
7822 constructor() {
7823 super(...arguments);
7824 this.testValue = unset;
7825 }
7826 deoptimizeCache() {
7827 this.testValue = UnknownValue;
7828 }
7829 hasEffects(context) {
7830 if (this.test.hasEffects(context)) {
7831 return true;
7832 }
7833 const testValue = this.getTestValue();
7834 if (testValue === UnknownValue) {
7835 const { brokenFlow } = context;
7836 if (this.consequent.hasEffects(context))
7837 return true;
7838 const consequentBrokenFlow = context.brokenFlow;
7839 context.brokenFlow = brokenFlow;
7840 if (this.alternate === null)
7841 return false;
7842 if (this.alternate.hasEffects(context))
7843 return true;
7844 context.brokenFlow =
7845 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7846 return false;
7847 }
7848 return testValue
7849 ? this.consequent.hasEffects(context)
7850 : this.alternate !== null && this.alternate.hasEffects(context);
7851 }
7852 include(context, includeChildrenRecursively) {
7853 this.included = true;
7854 if (includeChildrenRecursively) {
7855 this.includeRecursively(includeChildrenRecursively, context);
7856 }
7857 else {
7858 const testValue = this.getTestValue();
7859 if (testValue === UnknownValue) {
7860 this.includeUnknownTest(context);
7861 }
7862 else {
7863 this.includeKnownTest(context, testValue);
7864 }
7865 }
7866 }
7867 parseNode(esTreeNode) {
7868 this.consequentScope = new TrackingScope(this.scope);
7869 this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
7870 this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
7871 if (esTreeNode.alternate) {
7872 this.alternateScope = new TrackingScope(this.scope);
7873 this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
7874 this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
7875 }
7876 super.parseNode(esTreeNode);
7877 }
7878 render(code, options) {
7879 // Note that unknown test values are always included
7880 const testValue = this.getTestValue();
7881 const hoistedDeclarations = [];
7882 const includesIfElse = this.test.included;
7883 const noTreeshake = !this.context.options.treeshake;
7884 if (includesIfElse) {
7885 this.test.render(code, options);
7886 }
7887 else {
7888 code.remove(this.start, this.consequent.start);
7889 }
7890 if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
7891 this.consequent.render(code, options);
7892 }
7893 else {
7894 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
7895 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
7896 }
7897 if (this.alternate) {
7898 if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
7899 if (includesIfElse) {
7900 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
7901 code.prependLeft(this.alternate.start, ' ');
7902 }
7903 }
7904 else {
7905 code.remove(this.consequent.end, this.alternate.start);
7906 }
7907 this.alternate.render(code, options);
7908 }
7909 else {
7910 if (includesIfElse && this.shouldKeepAlternateBranch()) {
7911 code.overwrite(this.alternate.start, this.end, ';');
7912 }
7913 else {
7914 code.remove(this.consequent.end, this.end);
7915 }
7916 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
7917 }
7918 }
7919 this.renderHoistedDeclarations(hoistedDeclarations, code);
7920 }
7921 getTestValue() {
7922 if (this.testValue === unset) {
7923 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
7924 }
7925 return this.testValue;
7926 }
7927 includeKnownTest(context, testValue) {
7928 if (this.test.shouldBeIncluded(context)) {
7929 this.test.include(context, false);
7930 }
7931 if (testValue && this.consequent.shouldBeIncluded(context)) {
7932 this.consequent.includeAsSingleStatement(context, false);
7933 }
7934 if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
7935 this.alternate.includeAsSingleStatement(context, false);
7936 }
7937 }
7938 includeRecursively(includeChildrenRecursively, context) {
7939 this.test.include(context, includeChildrenRecursively);
7940 this.consequent.include(context, includeChildrenRecursively);
7941 if (this.alternate !== null) {
7942 this.alternate.include(context, includeChildrenRecursively);
7943 }
7944 }
7945 includeUnknownTest(context) {
7946 this.test.include(context, false);
7947 const { brokenFlow } = context;
7948 let consequentBrokenFlow = BROKEN_FLOW_NONE;
7949 if (this.consequent.shouldBeIncluded(context)) {
7950 this.consequent.includeAsSingleStatement(context, false);
7951 consequentBrokenFlow = context.brokenFlow;
7952 context.brokenFlow = brokenFlow;
7953 }
7954 if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
7955 this.alternate.includeAsSingleStatement(context, false);
7956 context.brokenFlow =
7957 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7958 }
7959 }
7960 renderHoistedDeclarations(hoistedDeclarations, code) {
7961 const hoistedVars = [
7962 ...new Set(hoistedDeclarations.map(identifier => {
7963 const variable = identifier.variable;
7964 return variable.included ? variable.getName() : '';
7965 }))
7966 ]
7967 .filter(Boolean)
7968 .join(', ');
7969 if (hoistedVars) {
7970 const parentType = this.parent.type;
7971 const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
7972 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
7973 if (needsBraces) {
7974 code.appendLeft(this.end, ` }`);
7975 }
7976 }
7977 }
7978 shouldKeepAlternateBranch() {
7979 let currentParent = this.parent;
7980 do {
7981 if (currentParent instanceof IfStatement && currentParent.alternate) {
7982 return true;
7983 }
7984 if (currentParent instanceof BlockStatement) {
7985 return false;
7986 }
7987 currentParent = currentParent.parent;
7988 } while (currentParent);
7989 return false;
7990 }
7991}
7992
7993class ImportDeclaration extends NodeBase {
7994 // Do not bind specifiers
7995 bind() { }
7996 hasEffects() {
7997 return false;
7998 }
7999 initialise() {
8000 this.context.addImport(this);
8001 }
8002 render(code, _options, nodeRenderOptions) {
8003 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
8004 }
8005}
8006ImportDeclaration.prototype.needsBoundaries = true;
8007
8008class ImportDefaultSpecifier extends NodeBase {
8009}
8010
8011const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
8012const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
8013const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
8014const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
8015const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
8016const defaultInteropHelpersByInteropType = {
8017 auto: INTEROP_DEFAULT_VARIABLE,
8018 default: null,
8019 defaultOnly: null,
8020 esModule: null,
8021 false: null,
8022 true: INTEROP_DEFAULT_LEGACY_VARIABLE
8023};
8024function isDefaultAProperty(interopType, externalLiveBindings) {
8025 return (interopType === 'esModule' ||
8026 (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
8027}
8028const namespaceInteropHelpersByInteropType = {
8029 auto: INTEROP_NAMESPACE_VARIABLE,
8030 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
8031 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
8032 esModule: null,
8033 false: null,
8034 true: INTEROP_NAMESPACE_VARIABLE
8035};
8036function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
8037 return (isDefaultAProperty(interopType, externalLiveBindings) &&
8038 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
8039}
8040function getDefaultOnlyHelper() {
8041 return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
8042}
8043function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
8044 return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
8045 ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
8046 : '').join('');
8047}
8048const HELPER_GENERATORS = {
8049 [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
8050 `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
8051 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
8052 [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
8053 `e${_}&&${_}e.__esModule${_}?${_}` +
8054 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
8055 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
8056 `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
8057 `}${n}${n}`,
8058 [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
8059 createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
8060 `}${n}${n}`,
8061 [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
8062 (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
8063 ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
8064 : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
8065 createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
8066 `}${n}${n}`
8067};
8068function getDefaultLiveBinding(_) {
8069 return `e${_}:${_}{${_}'default':${_}e${_}}`;
8070}
8071function getDefaultStatic(_) {
8072 return `e['default']${_}:${_}e`;
8073}
8074function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
8075 return (`${i}var n${_}=${_}${namespaceToStringTag
8076 ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
8077 : 'Object.create(null)'};${n}` +
8078 `${i}if${_}(e)${_}{${n}` +
8079 `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
8080 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
8081 `${i}${t}});${n}` +
8082 `${i}}${n}` +
8083 `${i}n['default']${_}=${_}e;${n}` +
8084 `${i}return ${getFrozen('n', freeze)};${n}`);
8085}
8086function copyPropertyLiveBinding(_, n, t, i) {
8087 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
8088 `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
8089 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
8090 `${i}${t}${t}enumerable:${_}true,${n}` +
8091 `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
8092 `${i}${t}${t}${t}return e[k];${n}` +
8093 `${i}${t}${t}}${n}` +
8094 `${i}${t}});${n}` +
8095 `${i}}${n}`);
8096}
8097function copyPropertyStatic(_, n, _t, i) {
8098 return `${i}n[k]${_}=${_}e[k];${n}`;
8099}
8100function getFrozen(fragment, freeze) {
8101 return freeze ? `Object.freeze(${fragment})` : fragment;
8102}
8103const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
8104
8105class ImportExpression extends NodeBase {
8106 constructor() {
8107 super(...arguments);
8108 this.inlineNamespace = null;
8109 this.mechanism = null;
8110 this.resolution = null;
8111 }
8112 hasEffects() {
8113 return true;
8114 }
8115 include(context, includeChildrenRecursively) {
8116 if (!this.included) {
8117 this.included = true;
8118 this.context.includeDynamicImport(this);
8119 this.scope.addAccessedDynamicImport(this);
8120 }
8121 this.source.include(context, includeChildrenRecursively);
8122 }
8123 initialise() {
8124 this.context.addDynamicImport(this);
8125 }
8126 render(code, options) {
8127 if (this.inlineNamespace) {
8128 const _ = options.compact ? '' : ' ';
8129 const s = options.compact ? '' : ';';
8130 code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
8131 return;
8132 }
8133 if (this.mechanism) {
8134 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
8135 code.overwrite(this.end - 1, this.end, this.mechanism.right);
8136 }
8137 this.source.render(code, options);
8138 }
8139 renderFinalResolution(code, resolution, namespaceExportName, options) {
8140 code.overwrite(this.source.start, this.source.end, resolution);
8141 if (namespaceExportName) {
8142 const _ = options.compact ? '' : ' ';
8143 const s = options.compact ? '' : ';';
8144 code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
8145 }
8146 }
8147 setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
8148 this.resolution = resolution;
8149 const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
8150 let helper;
8151 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
8152 if (helper) {
8153 accessedGlobals.push(helper);
8154 }
8155 if (accessedGlobals.length > 0) {
8156 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
8157 }
8158 }
8159 setInternalResolution(inlineNamespace) {
8160 this.inlineNamespace = inlineNamespace;
8161 }
8162 getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
8163 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
8164 {
8165 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
8166 format: options.format,
8167 moduleId: this.context.module.id,
8168 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
8169 }
8170 ]);
8171 if (mechanism) {
8172 return { helper: null, mechanism };
8173 }
8174 switch (options.format) {
8175 case 'cjs': {
8176 const _ = options.compact ? '' : ' ';
8177 const s = options.compact ? '' : ';';
8178 const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
8179 const helper = getInteropHelper(resolution, exportMode, options.interop);
8180 return {
8181 helper,
8182 mechanism: helper
8183 ? {
8184 left: `${leftStart} /*#__PURE__*/${helper}(require(`,
8185 right: `))${s}${_}})`
8186 }
8187 : {
8188 left: `${leftStart} require(`,
8189 right: `)${s}${_}})`
8190 }
8191 };
8192 }
8193 case 'amd': {
8194 const _ = options.compact ? '' : ' ';
8195 const resolve = options.compact ? 'c' : 'resolve';
8196 const reject = options.compact ? 'e' : 'reject';
8197 const helper = getInteropHelper(resolution, exportMode, options.interop);
8198 const resolveNamespace = helper
8199 ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
8200 : resolve;
8201 return {
8202 helper,
8203 mechanism: {
8204 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
8205 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
8206 }
8207 };
8208 }
8209 case 'system':
8210 return {
8211 helper: null,
8212 mechanism: {
8213 left: 'module.import(',
8214 right: ')'
8215 }
8216 };
8217 case 'es':
8218 if (options.dynamicImportFunction) {
8219 return {
8220 helper: null,
8221 mechanism: {
8222 left: `${options.dynamicImportFunction}(`,
8223 right: ')'
8224 }
8225 };
8226 }
8227 }
8228 return { helper: null, mechanism: null };
8229 }
8230}
8231function getInteropHelper(resolution, exportMode, interop) {
8232 return exportMode === 'external'
8233 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
8234 : exportMode === 'default'
8235 ? getDefaultOnlyHelper()
8236 : null;
8237}
8238const accessedImportGlobals = {
8239 amd: ['require'],
8240 cjs: ['require'],
8241 system: ['module']
8242};
8243
8244class ImportNamespaceSpecifier extends NodeBase {
8245}
8246
8247class ImportSpecifier extends NodeBase {
8248}
8249
8250class LabeledStatement extends NodeBase {
8251 hasEffects(context) {
8252 const brokenFlow = context.brokenFlow;
8253 context.ignore.labels.add(this.label.name);
8254 if (this.body.hasEffects(context))
8255 return true;
8256 context.ignore.labels.delete(this.label.name);
8257 if (context.includedLabels.has(this.label.name)) {
8258 context.includedLabels.delete(this.label.name);
8259 context.brokenFlow = brokenFlow;
8260 }
8261 return false;
8262 }
8263 include(context, includeChildrenRecursively) {
8264 this.included = true;
8265 const brokenFlow = context.brokenFlow;
8266 this.body.include(context, includeChildrenRecursively);
8267 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
8268 this.label.include();
8269 context.includedLabels.delete(this.label.name);
8270 context.brokenFlow = brokenFlow;
8271 }
8272 }
8273 render(code, options) {
8274 if (this.label.included) {
8275 this.label.render(code, options);
8276 }
8277 else {
8278 code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
8279 }
8280 this.body.render(code, options);
8281 }
8282}
8283
8284class LogicalExpression extends NodeBase {
8285 constructor() {
8286 super(...arguments);
8287 // We collect deoptimization information if usedBranch !== null
8288 this.expressionsToBeDeoptimized = [];
8289 this.isBranchResolutionAnalysed = false;
8290 this.usedBranch = null;
8291 }
8292 deoptimizeCache() {
8293 if (this.usedBranch !== null) {
8294 const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
8295 this.usedBranch = null;
8296 unusedBranch.deoptimizePath(UNKNOWN_PATH);
8297 for (const expression of this.expressionsToBeDeoptimized) {
8298 expression.deoptimizeCache();
8299 }
8300 }
8301 }
8302 deoptimizePath(path) {
8303 const usedBranch = this.getUsedBranch();
8304 if (usedBranch === null) {
8305 this.left.deoptimizePath(path);
8306 this.right.deoptimizePath(path);
8307 }
8308 else {
8309 usedBranch.deoptimizePath(path);
8310 }
8311 }
8312 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
8313 this.left.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
8314 this.right.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
8315 }
8316 getLiteralValueAtPath(path, recursionTracker, origin) {
8317 const usedBranch = this.getUsedBranch();
8318 if (usedBranch === null)
8319 return UnknownValue;
8320 this.expressionsToBeDeoptimized.push(origin);
8321 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
8322 }
8323 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
8324 const usedBranch = this.getUsedBranch();
8325 if (usedBranch === null)
8326 return new MultiExpression([
8327 this.left.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
8328 this.right.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
8329 ]);
8330 this.expressionsToBeDeoptimized.push(origin);
8331 return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
8332 }
8333 hasEffects(context) {
8334 if (this.left.hasEffects(context)) {
8335 return true;
8336 }
8337 if (this.getUsedBranch() !== this.left) {
8338 return this.right.hasEffects(context);
8339 }
8340 return false;
8341 }
8342 hasEffectsWhenAccessedAtPath(path, context) {
8343 const usedBranch = this.getUsedBranch();
8344 if (usedBranch === null) {
8345 return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
8346 this.right.hasEffectsWhenAccessedAtPath(path, context));
8347 }
8348 return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
8349 }
8350 hasEffectsWhenAssignedAtPath(path, context) {
8351 const usedBranch = this.getUsedBranch();
8352 if (usedBranch === null) {
8353 return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
8354 this.right.hasEffectsWhenAssignedAtPath(path, context));
8355 }
8356 return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
8357 }
8358 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8359 const usedBranch = this.getUsedBranch();
8360 if (usedBranch === null) {
8361 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
8362 this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
8363 }
8364 return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
8365 }
8366 include(context, includeChildrenRecursively) {
8367 this.included = true;
8368 const usedBranch = this.getUsedBranch();
8369 if (includeChildrenRecursively ||
8370 (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
8371 usedBranch === null) {
8372 this.left.include(context, includeChildrenRecursively);
8373 this.right.include(context, includeChildrenRecursively);
8374 }
8375 else {
8376 usedBranch.include(context, includeChildrenRecursively);
8377 }
8378 }
8379 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
8380 if (!this.left.included || !this.right.included) {
8381 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
8382 if (this.right.included) {
8383 const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
8384 code.remove(this.start, removePos);
8385 if (preventASI) {
8386 removeLineBreaks(code, removePos, this.right.start);
8387 }
8388 }
8389 else {
8390 code.remove(operatorPos, this.end);
8391 }
8392 removeAnnotations(this, code);
8393 this.getUsedBranch().render(code, options, {
8394 isCalleeOfRenderedParent,
8395 preventASI,
8396 ...(renderedSurroundingElement
8397 ? { renderedSurroundingElement }
8398 : { renderedParentType: renderedParentType || this.parent.type })
8399 });
8400 }
8401 else {
8402 this.left.render(code, options, {
8403 preventASI,
8404 renderedSurroundingElement: renderedParentType || renderedSurroundingElement
8405 });
8406 this.right.render(code, options);
8407 }
8408 }
8409 getUsedBranch() {
8410 if (!this.isBranchResolutionAnalysed) {
8411 this.isBranchResolutionAnalysed = true;
8412 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8413 if (leftValue === UnknownValue) {
8414 return null;
8415 }
8416 else {
8417 this.usedBranch =
8418 (this.operator === '||' && leftValue) ||
8419 (this.operator === '&&' && !leftValue) ||
8420 (this.operator === '??' && leftValue != null)
8421 ? this.left
8422 : this.right;
8423 }
8424 }
8425 return this.usedBranch;
8426 }
8427}
8428
8429const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
8430const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
8431const FILE_PREFIX = 'ROLLUP_FILE_URL_';
8432class MetaProperty extends NodeBase {
8433 addAccessedGlobals(format, accessedGlobalsByScope) {
8434 const metaProperty = this.metaProperty;
8435 const accessedGlobals = (metaProperty &&
8436 (metaProperty.startsWith(FILE_PREFIX) ||
8437 metaProperty.startsWith(ASSET_PREFIX) ||
8438 metaProperty.startsWith(CHUNK_PREFIX))
8439 ? accessedFileUrlGlobals
8440 : accessedMetaUrlGlobals)[format];
8441 if (accessedGlobals.length > 0) {
8442 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
8443 }
8444 }
8445 getReferencedFileName(outputPluginDriver) {
8446 const metaProperty = this.metaProperty;
8447 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
8448 return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
8449 }
8450 return null;
8451 }
8452 hasEffects() {
8453 return false;
8454 }
8455 hasEffectsWhenAccessedAtPath(path) {
8456 return path.length > 1;
8457 }
8458 include() {
8459 if (!this.included) {
8460 this.included = true;
8461 if (this.meta.name === 'import') {
8462 this.context.addImportMeta(this);
8463 const parent = this.parent;
8464 this.metaProperty =
8465 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
8466 ? parent.propertyKey
8467 : null;
8468 }
8469 }
8470 }
8471 renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
8472 var _a;
8473 const parent = this.parent;
8474 const metaProperty = this.metaProperty;
8475 if (metaProperty &&
8476 (metaProperty.startsWith(FILE_PREFIX) ||
8477 metaProperty.startsWith(ASSET_PREFIX) ||
8478 metaProperty.startsWith(CHUNK_PREFIX))) {
8479 let referenceId = null;
8480 let assetReferenceId = null;
8481 let chunkReferenceId = null;
8482 let fileName;
8483 if (metaProperty.startsWith(FILE_PREFIX)) {
8484 referenceId = metaProperty.substr(FILE_PREFIX.length);
8485 fileName = outputPluginDriver.getFileName(referenceId);
8486 }
8487 else if (metaProperty.startsWith(ASSET_PREFIX)) {
8488 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
8489 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
8490 fileName = outputPluginDriver.getFileName(assetReferenceId);
8491 }
8492 else {
8493 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
8494 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
8495 fileName = outputPluginDriver.getFileName(chunkReferenceId);
8496 }
8497 const relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
8498 let replacement;
8499 if (assetReferenceId !== null) {
8500 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
8501 {
8502 assetFileName: fileName,
8503 chunkId,
8504 format,
8505 moduleId: this.context.module.id,
8506 relativeAssetPath: relativePath
8507 }
8508 ]);
8509 }
8510 if (!replacement) {
8511 replacement =
8512 outputPluginDriver.hookFirstSync('resolveFileUrl', [
8513 {
8514 assetReferenceId,
8515 chunkId,
8516 chunkReferenceId,
8517 fileName,
8518 format,
8519 moduleId: this.context.module.id,
8520 referenceId: referenceId || assetReferenceId || chunkReferenceId,
8521 relativePath
8522 }
8523 ]) || relativeUrlMechanisms[format](relativePath);
8524 }
8525 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
8526 return;
8527 }
8528 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
8529 metaProperty,
8530 {
8531 chunkId,
8532 format,
8533 moduleId: this.context.module.id
8534 }
8535 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
8536 if (typeof replacement === 'string') {
8537 if (parent instanceof MemberExpression) {
8538 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
8539 }
8540 else {
8541 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
8542 }
8543 }
8544 }
8545}
8546const accessedMetaUrlGlobals = {
8547 amd: ['document', 'module', 'URL'],
8548 cjs: ['document', 'require', 'URL'],
8549 es: [],
8550 iife: ['document', 'URL'],
8551 system: ['module'],
8552 umd: ['document', 'require', 'URL']
8553};
8554const accessedFileUrlGlobals = {
8555 amd: ['document', 'require', 'URL'],
8556 cjs: ['document', 'require', 'URL'],
8557 es: [],
8558 iife: ['document', 'URL'],
8559 system: ['module', 'URL'],
8560 umd: ['document', 'require', 'URL']
8561};
8562const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
8563const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
8564const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
8565 const urlMechanism = getUrl(chunkId);
8566 return prop === null
8567 ? `({ url: ${urlMechanism} })`
8568 : prop === 'url'
8569 ? urlMechanism
8570 : 'undefined';
8571};
8572const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
8573const relativeUrlMechanisms = {
8574 amd: relativePath => {
8575 if (relativePath[0] !== '.')
8576 relativePath = './' + relativePath;
8577 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
8578 },
8579 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
8580 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
8581 iife: relativePath => getRelativeUrlFromDocument(relativePath),
8582 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
8583 umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
8584};
8585const importMetaMechanisms = {
8586 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
8587 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
8588 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
8589 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
8590 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
8591};
8592
8593class NewExpression extends NodeBase {
8594 constructor() {
8595 super(...arguments);
8596 this.deoptimized = false;
8597 }
8598 hasEffects(context) {
8599 if (!this.deoptimized)
8600 this.applyDeoptimizations();
8601 for (const argument of this.arguments) {
8602 if (argument.hasEffects(context))
8603 return true;
8604 }
8605 if (this.context.options.treeshake.annotations &&
8606 this.annotations)
8607 return false;
8608 return (this.callee.hasEffects(context) ||
8609 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
8610 }
8611 hasEffectsWhenAccessedAtPath(path) {
8612 return path.length > 0;
8613 }
8614 initialise() {
8615 this.callOptions = {
8616 args: this.arguments,
8617 thisParam: null,
8618 withNew: true
8619 };
8620 }
8621 applyDeoptimizations() {
8622 this.deoptimized = true;
8623 for (const argument of this.arguments) {
8624 // This will make sure all properties of parameters behave as "unknown"
8625 argument.deoptimizePath(UNKNOWN_PATH);
8626 }
8627 this.context.requestTreeshakingPass();
8628 }
8629}
8630
8631class ObjectExpression extends NodeBase {
8632 constructor() {
8633 super(...arguments);
8634 this.objectEntity = null;
8635 }
8636 deoptimizeCache() {
8637 this.getObjectEntity().deoptimizeAllProperties();
8638 }
8639 deoptimizePath(path) {
8640 this.getObjectEntity().deoptimizePath(path);
8641 }
8642 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
8643 this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
8644 }
8645 getLiteralValueAtPath(path, recursionTracker, origin) {
8646 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
8647 }
8648 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
8649 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
8650 }
8651 hasEffectsWhenAccessedAtPath(path, context) {
8652 return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
8653 }
8654 hasEffectsWhenAssignedAtPath(path, context) {
8655 return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
8656 }
8657 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8658 return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
8659 }
8660 render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
8661 super.render(code, options);
8662 const surroundingElement = renderedParentType || renderedSurroundingElement;
8663 if (surroundingElement === ExpressionStatement$1 ||
8664 surroundingElement === ArrowFunctionExpression$1) {
8665 code.appendRight(this.start, '(');
8666 code.prependLeft(this.end, ')');
8667 }
8668 }
8669 getObjectEntity() {
8670 if (this.objectEntity !== null) {
8671 return this.objectEntity;
8672 }
8673 let prototype = OBJECT_PROTOTYPE;
8674 const properties = [];
8675 for (const property of this.properties) {
8676 if (property instanceof SpreadElement) {
8677 properties.push({ key: UnknownKey, kind: 'init', property });
8678 continue;
8679 }
8680 let key;
8681 if (property.computed) {
8682 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8683 if (keyValue === UnknownValue) {
8684 properties.push({ key: UnknownKey, kind: property.kind, property });
8685 continue;
8686 }
8687 else {
8688 key = String(keyValue);
8689 }
8690 }
8691 else {
8692 key =
8693 property.key instanceof Identifier
8694 ? property.key.name
8695 : String(property.key.value);
8696 if (key === '__proto__' && property.kind === 'init') {
8697 prototype =
8698 property.value instanceof Literal && property.value.value === null
8699 ? null
8700 : property.value;
8701 continue;
8702 }
8703 }
8704 properties.push({ key, kind: property.kind, property });
8705 }
8706 return (this.objectEntity = new ObjectEntity(properties, prototype));
8707 }
8708}
8709
8710class ObjectPattern extends NodeBase {
8711 addExportedVariables(variables, exportNamesByVariable) {
8712 for (const property of this.properties) {
8713 if (property.type === Property$1) {
8714 property.value.addExportedVariables(variables, exportNamesByVariable);
8715 }
8716 else {
8717 property.argument.addExportedVariables(variables, exportNamesByVariable);
8718 }
8719 }
8720 }
8721 declare(kind, init) {
8722 const variables = [];
8723 for (const property of this.properties) {
8724 variables.push(...property.declare(kind, init));
8725 }
8726 return variables;
8727 }
8728 deoptimizePath(path) {
8729 if (path.length === 0) {
8730 for (const property of this.properties) {
8731 property.deoptimizePath(path);
8732 }
8733 }
8734 }
8735 hasEffectsWhenAssignedAtPath(path, context) {
8736 if (path.length > 0)
8737 return true;
8738 for (const property of this.properties) {
8739 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
8740 return true;
8741 }
8742 return false;
8743 }
8744 markDeclarationReached() {
8745 for (const property of this.properties) {
8746 property.markDeclarationReached();
8747 }
8748 }
8749}
8750
8751class PrivateIdentifier extends NodeBase {
8752}
8753
8754class Property extends MethodBase {
8755 constructor() {
8756 super(...arguments);
8757 this.deoptimized = false;
8758 this.declarationInit = null;
8759 }
8760 declare(kind, init) {
8761 this.declarationInit = init;
8762 return this.value.declare(kind, UNKNOWN_EXPRESSION);
8763 }
8764 hasEffects(context) {
8765 if (!this.deoptimized)
8766 this.applyDeoptimizations();
8767 const propertyReadSideEffects = this.context.options.treeshake
8768 .propertyReadSideEffects;
8769 return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
8770 this.key.hasEffects(context) ||
8771 this.value.hasEffects(context));
8772 }
8773 markDeclarationReached() {
8774 this.value.markDeclarationReached();
8775 }
8776 render(code, options) {
8777 if (!this.shorthand) {
8778 this.key.render(code, options);
8779 }
8780 this.value.render(code, options, { isShorthandProperty: this.shorthand });
8781 }
8782 applyDeoptimizations() {
8783 this.deoptimized = true;
8784 if (this.declarationInit !== null) {
8785 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8786 this.context.requestTreeshakingPass();
8787 }
8788 }
8789}
8790
8791class PropertyDefinition extends NodeBase {
8792 deoptimizePath(path) {
8793 var _a;
8794 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
8795 }
8796 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
8797 var _a;
8798 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
8799 }
8800 getLiteralValueAtPath(path, recursionTracker, origin) {
8801 return this.value
8802 ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
8803 : UnknownValue;
8804 }
8805 getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
8806 return this.value
8807 ? this.value.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
8808 : UNKNOWN_EXPRESSION;
8809 }
8810 hasEffects(context) {
8811 return (this.key.hasEffects(context) ||
8812 (this.static && this.value !== null && this.value.hasEffects(context)));
8813 }
8814 hasEffectsWhenAccessedAtPath(path, context) {
8815 return !this.value || this.value.hasEffectsWhenAccessedAtPath(path, context);
8816 }
8817 hasEffectsWhenAssignedAtPath(path, context) {
8818 return !this.value || this.value.hasEffectsWhenAssignedAtPath(path, context);
8819 }
8820 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8821 return !this.value || this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
8822 }
8823}
8824
8825class ReturnStatement extends NodeBase {
8826 hasEffects(context) {
8827 if (!context.ignore.returnYield ||
8828 (this.argument !== null && this.argument.hasEffects(context)))
8829 return true;
8830 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8831 return false;
8832 }
8833 include(context, includeChildrenRecursively) {
8834 this.included = true;
8835 if (this.argument) {
8836 this.argument.include(context, includeChildrenRecursively);
8837 }
8838 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8839 }
8840 initialise() {
8841 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
8842 }
8843 render(code, options) {
8844 if (this.argument) {
8845 this.argument.render(code, options, { preventASI: true });
8846 if (this.argument.start === this.start + 6 /* 'return'.length */) {
8847 code.prependLeft(this.start + 6, ' ');
8848 }
8849 }
8850 }
8851}
8852
8853class SequenceExpression extends NodeBase {
8854 deoptimizePath(path) {
8855 this.expressions[this.expressions.length - 1].deoptimizePath(path);
8856 }
8857 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
8858 this.expressions[this.expressions.length - 1].deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
8859 }
8860 getLiteralValueAtPath(path, recursionTracker, origin) {
8861 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
8862 }
8863 hasEffects(context) {
8864 for (const expression of this.expressions) {
8865 if (expression.hasEffects(context))
8866 return true;
8867 }
8868 return false;
8869 }
8870 hasEffectsWhenAccessedAtPath(path, context) {
8871 return (path.length > 0 &&
8872 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
8873 }
8874 hasEffectsWhenAssignedAtPath(path, context) {
8875 return this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context);
8876 }
8877 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8878 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
8879 }
8880 include(context, includeChildrenRecursively) {
8881 this.included = true;
8882 const lastExpression = this.expressions[this.expressions.length - 1];
8883 for (const expression of this.expressions) {
8884 if (includeChildrenRecursively ||
8885 (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
8886 expression.shouldBeIncluded(context))
8887 expression.include(context, includeChildrenRecursively);
8888 }
8889 }
8890 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
8891 let includedNodes = 0;
8892 let lastSeparatorPos = null;
8893 const lastNode = this.expressions[this.expressions.length - 1];
8894 for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
8895 if (!node.included) {
8896 treeshakeNode(node, code, start, end);
8897 continue;
8898 }
8899 includedNodes++;
8900 lastSeparatorPos = separator;
8901 if (includedNodes === 1 && preventASI) {
8902 removeLineBreaks(code, start, node.start);
8903 }
8904 if (includedNodes === 1) {
8905 if (node === lastNode) {
8906 node.render(code, options, {
8907 isCalleeOfRenderedParent,
8908 renderedParentType: renderedParentType || this.parent.type
8909 });
8910 }
8911 else {
8912 node.render(code, options, {
8913 renderedSurroundingElement: renderedParentType || this.parent.type
8914 });
8915 }
8916 }
8917 else {
8918 node.render(code, options);
8919 }
8920 }
8921 if (lastSeparatorPos) {
8922 code.remove(lastSeparatorPos, this.end);
8923 }
8924 }
8925}
8926
8927class Super extends NodeBase {
8928 bind() {
8929 this.variable = this.scope.findVariable('this');
8930 }
8931 deoptimizePath(path) {
8932 this.variable.deoptimizePath(path);
8933 }
8934 include() {
8935 if (!this.included) {
8936 this.included = true;
8937 this.context.includeVariableInModule(this.variable);
8938 }
8939 }
8940}
8941
8942class SwitchCase extends NodeBase {
8943 hasEffects(context) {
8944 if (this.test && this.test.hasEffects(context))
8945 return true;
8946 for (const node of this.consequent) {
8947 if (context.brokenFlow)
8948 break;
8949 if (node.hasEffects(context))
8950 return true;
8951 }
8952 return false;
8953 }
8954 include(context, includeChildrenRecursively) {
8955 this.included = true;
8956 if (this.test)
8957 this.test.include(context, includeChildrenRecursively);
8958 for (const node of this.consequent) {
8959 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8960 node.include(context, includeChildrenRecursively);
8961 }
8962 }
8963 render(code, options, nodeRenderOptions) {
8964 if (this.consequent.length) {
8965 this.test && this.test.render(code, options);
8966 const testEnd = this.test
8967 ? this.test.end
8968 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
8969 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
8970 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
8971 }
8972 else {
8973 super.render(code, options);
8974 }
8975 }
8976}
8977SwitchCase.prototype.needsBoundaries = true;
8978
8979class SwitchStatement extends NodeBase {
8980 createScope(parentScope) {
8981 this.scope = new BlockScope(parentScope);
8982 }
8983 hasEffects(context) {
8984 if (this.discriminant.hasEffects(context))
8985 return true;
8986 const { brokenFlow, ignore: { breaks } } = context;
8987 let minBrokenFlow = Infinity;
8988 context.ignore.breaks = true;
8989 for (const switchCase of this.cases) {
8990 if (switchCase.hasEffects(context))
8991 return true;
8992 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
8993 context.brokenFlow = brokenFlow;
8994 }
8995 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8996 context.brokenFlow = minBrokenFlow;
8997 }
8998 context.ignore.breaks = breaks;
8999 return false;
9000 }
9001 include(context, includeChildrenRecursively) {
9002 this.included = true;
9003 this.discriminant.include(context, includeChildrenRecursively);
9004 const { brokenFlow } = context;
9005 let minBrokenFlow = Infinity;
9006 let isCaseIncluded = includeChildrenRecursively ||
9007 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
9008 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
9009 const switchCase = this.cases[caseIndex];
9010 if (switchCase.included) {
9011 isCaseIncluded = true;
9012 }
9013 if (!isCaseIncluded) {
9014 const hasEffectsContext = createHasEffectsContext();
9015 hasEffectsContext.ignore.breaks = true;
9016 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
9017 }
9018 if (isCaseIncluded) {
9019 switchCase.include(context, includeChildrenRecursively);
9020 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
9021 context.brokenFlow = brokenFlow;
9022 }
9023 else {
9024 minBrokenFlow = brokenFlow;
9025 }
9026 }
9027 if (isCaseIncluded &&
9028 this.defaultCase !== null &&
9029 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
9030 context.brokenFlow = minBrokenFlow;
9031 }
9032 }
9033 initialise() {
9034 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
9035 if (this.cases[caseIndex].test === null) {
9036 this.defaultCase = caseIndex;
9037 return;
9038 }
9039 }
9040 this.defaultCase = null;
9041 }
9042 render(code, options) {
9043 this.discriminant.render(code, options);
9044 if (this.cases.length > 0) {
9045 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
9046 }
9047 }
9048}
9049
9050class TaggedTemplateExpression extends NodeBase {
9051 bind() {
9052 super.bind();
9053 if (this.tag.type === Identifier$1) {
9054 const name = this.tag.name;
9055 const variable = this.scope.findVariable(name);
9056 if (variable.isNamespace) {
9057 this.context.warn({
9058 code: 'CANNOT_CALL_NAMESPACE',
9059 message: `Cannot call a namespace ('${name}')`
9060 }, this.start);
9061 }
9062 }
9063 }
9064 hasEffects(context) {
9065 return (super.hasEffects(context) ||
9066 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
9067 }
9068 initialise() {
9069 this.callOptions = {
9070 args: NO_ARGS,
9071 thisParam: null,
9072 withNew: false
9073 };
9074 }
9075 render(code, options) {
9076 this.tag.render(code, options, { isCalleeOfRenderedParent: true });
9077 this.quasi.render(code, options);
9078 }
9079}
9080
9081class TemplateElement extends NodeBase {
9082 // Do not try to bind value
9083 bind() { }
9084 hasEffects() {
9085 return false;
9086 }
9087 include() {
9088 this.included = true;
9089 }
9090 parseNode(esTreeNode) {
9091 this.value = esTreeNode.value;
9092 super.parseNode(esTreeNode);
9093 }
9094 render() { }
9095}
9096
9097class UndefinedVariable extends Variable {
9098 constructor() {
9099 super('undefined');
9100 }
9101 getLiteralValueAtPath() {
9102 return undefined;
9103 }
9104}
9105
9106class ExportDefaultVariable extends LocalVariable {
9107 constructor(name, exportDefaultDeclaration, context) {
9108 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
9109 this.hasId = false;
9110 this.originalId = null;
9111 this.originalVariable = null;
9112 const declaration = exportDefaultDeclaration.declaration;
9113 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
9114 declaration.id) {
9115 this.hasId = true;
9116 this.originalId = declaration.id;
9117 }
9118 else if (declaration instanceof Identifier) {
9119 this.originalId = declaration;
9120 }
9121 }
9122 addReference(identifier) {
9123 if (!this.hasId) {
9124 this.name = identifier.name;
9125 }
9126 }
9127 getAssignedVariableName() {
9128 return (this.originalId && this.originalId.name) || null;
9129 }
9130 getBaseVariableName() {
9131 const original = this.getOriginalVariable();
9132 if (original === this) {
9133 return super.getBaseVariableName();
9134 }
9135 else {
9136 return original.getBaseVariableName();
9137 }
9138 }
9139 getDirectOriginalVariable() {
9140 return this.originalId &&
9141 (this.hasId ||
9142 !(this.originalId.isPossibleTDZ() ||
9143 this.originalId.variable.isReassigned ||
9144 this.originalId.variable instanceof UndefinedVariable ||
9145 // this avoids a circular dependency
9146 'syntheticNamespace' in this.originalId.variable))
9147 ? this.originalId.variable
9148 : null;
9149 }
9150 getName() {
9151 const original = this.getOriginalVariable();
9152 if (original === this) {
9153 return super.getName();
9154 }
9155 else {
9156 return original.getName();
9157 }
9158 }
9159 getOriginalVariable() {
9160 if (this.originalVariable)
9161 return this.originalVariable;
9162 // eslint-disable-next-line @typescript-eslint/no-this-alias
9163 let original = this;
9164 let currentVariable;
9165 const checkedVariables = new Set();
9166 do {
9167 checkedVariables.add(original);
9168 currentVariable = original;
9169 original = currentVariable.getDirectOriginalVariable();
9170 } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
9171 return (this.originalVariable = original || currentVariable);
9172 }
9173}
9174
9175class ModuleScope extends ChildScope {
9176 constructor(parent, context) {
9177 super(parent);
9178 this.context = context;
9179 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
9180 }
9181 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
9182 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
9183 this.variables.set('default', variable);
9184 return variable;
9185 }
9186 addNamespaceMemberAccess() { }
9187 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
9188 // all module level variables are already deconflicted when deconflicting the chunk
9189 for (const scope of this.children)
9190 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
9191 }
9192 findLexicalBoundary() {
9193 return this;
9194 }
9195 findVariable(name) {
9196 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
9197 if (knownVariable) {
9198 return knownVariable;
9199 }
9200 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
9201 if (variable instanceof GlobalVariable) {
9202 this.accessedOutsideVariables.set(name, variable);
9203 }
9204 return variable;
9205 }
9206}
9207
9208class ThisExpression extends NodeBase {
9209 bind() {
9210 this.variable = this.scope.findVariable('this');
9211 }
9212 deoptimizePath(path) {
9213 this.variable.deoptimizePath(path);
9214 }
9215 deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
9216 this.variable.deoptimizeThisOnEventAtPath(event, path,
9217 // We rewrite the parameter so that a ThisVariable can detect self-mutations
9218 thisParameter === this ? this.variable : thisParameter, recursionTracker);
9219 }
9220 hasEffectsWhenAccessedAtPath(path, context) {
9221 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
9222 }
9223 hasEffectsWhenAssignedAtPath(path, context) {
9224 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
9225 }
9226 include() {
9227 if (!this.included) {
9228 this.included = true;
9229 this.context.includeVariableInModule(this.variable);
9230 }
9231 }
9232 initialise() {
9233 this.alias =
9234 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
9235 if (this.alias === 'undefined') {
9236 this.context.warn({
9237 code: 'THIS_IS_UNDEFINED',
9238 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
9239 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
9240 }, this.start);
9241 }
9242 }
9243 render(code) {
9244 if (this.alias !== null) {
9245 code.overwrite(this.start, this.end, this.alias, {
9246 contentOnly: false,
9247 storeName: true
9248 });
9249 }
9250 }
9251}
9252
9253class ThrowStatement extends NodeBase {
9254 hasEffects() {
9255 return true;
9256 }
9257 include(context, includeChildrenRecursively) {
9258 this.included = true;
9259 this.argument.include(context, includeChildrenRecursively);
9260 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
9261 }
9262 render(code, options) {
9263 this.argument.render(code, options, { preventASI: true });
9264 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
9265 code.prependLeft(this.start + 5, ' ');
9266 }
9267 }
9268}
9269
9270class TryStatement extends NodeBase {
9271 constructor() {
9272 super(...arguments);
9273 this.directlyIncluded = false;
9274 this.includedLabelsAfterBlock = null;
9275 }
9276 hasEffects(context) {
9277 return ((this.context.options.treeshake.tryCatchDeoptimization
9278 ? this.block.body.length > 0
9279 : this.block.hasEffects(context)) ||
9280 (this.finalizer !== null && this.finalizer.hasEffects(context)));
9281 }
9282 include(context, includeChildrenRecursively) {
9283 var _a;
9284 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
9285 const { brokenFlow } = context;
9286 if (!this.directlyIncluded || !tryCatchDeoptimization) {
9287 this.included = true;
9288 this.directlyIncluded = true;
9289 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
9290 if (context.includedLabels.size > 0) {
9291 this.includedLabelsAfterBlock = [...context.includedLabels];
9292 }
9293 context.brokenFlow = brokenFlow;
9294 }
9295 else if (this.includedLabelsAfterBlock) {
9296 for (const label of this.includedLabelsAfterBlock) {
9297 context.includedLabels.add(label);
9298 }
9299 }
9300 if (this.handler !== null) {
9301 this.handler.include(context, includeChildrenRecursively);
9302 context.brokenFlow = brokenFlow;
9303 }
9304 if (this.finalizer !== null) {
9305 this.finalizer.include(context, includeChildrenRecursively);
9306 }
9307 }
9308}
9309
9310const unaryOperators = {
9311 '!': value => !value,
9312 '+': value => +value,
9313 '-': value => -value,
9314 delete: () => UnknownValue,
9315 typeof: value => typeof value,
9316 void: () => undefined,
9317 '~': value => ~value
9318};
9319class UnaryExpression extends NodeBase {
9320 constructor() {
9321 super(...arguments);
9322 this.deoptimized = false;
9323 }
9324 getLiteralValueAtPath(path, recursionTracker, origin) {
9325 if (path.length > 0)
9326 return UnknownValue;
9327 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
9328 if (argumentValue === UnknownValue)
9329 return UnknownValue;
9330 return unaryOperators[this.operator](argumentValue);
9331 }
9332 hasEffects(context) {
9333 if (!this.deoptimized)
9334 this.applyDeoptimizations();
9335 if (this.operator === 'typeof' && this.argument instanceof Identifier)
9336 return false;
9337 return (this.argument.hasEffects(context) ||
9338 (this.operator === 'delete' &&
9339 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
9340 }
9341 hasEffectsWhenAccessedAtPath(path) {
9342 if (this.operator === 'void') {
9343 return path.length > 0;
9344 }
9345 return path.length > 1;
9346 }
9347 applyDeoptimizations() {
9348 this.deoptimized = true;
9349 if (this.operator === 'delete') {
9350 this.argument.deoptimizePath(EMPTY_PATH);
9351 this.context.requestTreeshakingPass();
9352 }
9353 }
9354}
9355
9356class UnknownNode extends NodeBase {
9357 hasEffects() {
9358 return true;
9359 }
9360 include(context) {
9361 super.include(context, true);
9362 }
9363}
9364
9365class UpdateExpression extends NodeBase {
9366 constructor() {
9367 super(...arguments);
9368 this.deoptimized = false;
9369 }
9370 hasEffects(context) {
9371 if (!this.deoptimized)
9372 this.applyDeoptimizations();
9373 return (this.argument.hasEffects(context) ||
9374 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
9375 }
9376 hasEffectsWhenAccessedAtPath(path) {
9377 return path.length > 1;
9378 }
9379 render(code, options) {
9380 this.argument.render(code, options);
9381 if (options.format === 'system') {
9382 const variable = this.argument.variable;
9383 const exportNames = options.exportNamesByVariable.get(variable);
9384 if (exportNames && exportNames.length) {
9385 const _ = options.compact ? '' : ' ';
9386 const name = variable.getName();
9387 if (this.prefix) {
9388 if (exportNames.length === 1) {
9389 code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
9390 }
9391 else {
9392 code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
9393 }
9394 }
9395 else if (exportNames.length > 1) {
9396 code.overwrite(this.start, this.end, `(${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name}))`);
9397 }
9398 else {
9399 let op;
9400 switch (this.operator) {
9401 case '++':
9402 op = `${name}${_}+${_}1`;
9403 break;
9404 case '--':
9405 op = `${name}${_}-${_}1`;
9406 break;
9407 }
9408 code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
9409 }
9410 }
9411 }
9412 }
9413 applyDeoptimizations() {
9414 this.deoptimized = true;
9415 this.argument.deoptimizePath(EMPTY_PATH);
9416 if (this.argument instanceof Identifier) {
9417 const variable = this.scope.findVariable(this.argument.name);
9418 variable.isReassigned = true;
9419 }
9420 this.context.requestTreeshakingPass();
9421 }
9422}
9423
9424class VariableDeclarator extends NodeBase {
9425 declareDeclarator(kind) {
9426 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
9427 }
9428 deoptimizePath(path) {
9429 this.id.deoptimizePath(path);
9430 }
9431 hasEffects(context) {
9432 const initEffect = this.init !== null && this.init.hasEffects(context);
9433 this.id.markDeclarationReached();
9434 return initEffect || this.id.hasEffects(context);
9435 }
9436 include(context, includeChildrenRecursively) {
9437 this.included = true;
9438 if (this.init) {
9439 this.init.include(context, includeChildrenRecursively);
9440 }
9441 this.id.markDeclarationReached();
9442 if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
9443 this.id.include(context, includeChildrenRecursively);
9444 }
9445 }
9446 render(code, options) {
9447 const renderId = this.id.included;
9448 if (renderId) {
9449 this.id.render(code, options);
9450 }
9451 else {
9452 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
9453 code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
9454 }
9455 if (this.init) {
9456 this.init.render(code, options, renderId ? BLANK : { renderedParentType: ExpressionStatement$1 });
9457 }
9458 else if (this.id instanceof Identifier &&
9459 isReassignedExportsMember(this.id.variable, options.exportNamesByVariable)) {
9460 const _ = options.compact ? '' : ' ';
9461 code.appendLeft(this.end, `${_}=${_}void 0`);
9462 }
9463 }
9464}
9465
9466class WhileStatement extends NodeBase {
9467 hasEffects(context) {
9468 if (this.test.hasEffects(context))
9469 return true;
9470 const { brokenFlow, ignore: { breaks, continues } } = context;
9471 context.ignore.breaks = true;
9472 context.ignore.continues = true;
9473 if (this.body.hasEffects(context))
9474 return true;
9475 context.ignore.breaks = breaks;
9476 context.ignore.continues = continues;
9477 context.brokenFlow = brokenFlow;
9478 return false;
9479 }
9480 include(context, includeChildrenRecursively) {
9481 this.included = true;
9482 this.test.include(context, includeChildrenRecursively);
9483 const { brokenFlow } = context;
9484 this.body.includeAsSingleStatement(context, includeChildrenRecursively);
9485 context.brokenFlow = brokenFlow;
9486 }
9487}
9488
9489class YieldExpression extends NodeBase {
9490 constructor() {
9491 super(...arguments);
9492 this.deoptimized = false;
9493 }
9494 hasEffects(context) {
9495 if (!this.deoptimized)
9496 this.applyDeoptimizations();
9497 return (!context.ignore.returnYield || (this.argument !== null && this.argument.hasEffects(context)));
9498 }
9499 render(code, options) {
9500 if (this.argument) {
9501 this.argument.render(code, options, { preventASI: true });
9502 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
9503 code.prependLeft(this.start + 5, ' ');
9504 }
9505 }
9506 }
9507 applyDeoptimizations() {
9508 this.deoptimized = true;
9509 const { argument } = this;
9510 if (argument) {
9511 argument.deoptimizePath(UNKNOWN_PATH);
9512 this.context.requestTreeshakingPass();
9513 }
9514 }
9515}
9516
9517const nodeConstructors = {
9518 ArrayExpression,
9519 ArrayPattern,
9520 ArrowFunctionExpression,
9521 AssignmentExpression,
9522 AssignmentPattern,
9523 AwaitExpression,
9524 BinaryExpression,
9525 BlockStatement,
9526 BreakStatement,
9527 CallExpression,
9528 CatchClause,
9529 ChainExpression,
9530 ClassBody,
9531 ClassDeclaration,
9532 ClassExpression,
9533 ConditionalExpression,
9534 ContinueStatement,
9535 DoWhileStatement,
9536 EmptyStatement,
9537 ExportAllDeclaration,
9538 ExportDefaultDeclaration,
9539 ExportNamedDeclaration,
9540 ExportSpecifier,
9541 ExpressionStatement,
9542 ForInStatement,
9543 ForOfStatement,
9544 ForStatement,
9545 FunctionDeclaration,
9546 FunctionExpression,
9547 Identifier,
9548 IfStatement,
9549 ImportDeclaration,
9550 ImportDefaultSpecifier,
9551 ImportExpression,
9552 ImportNamespaceSpecifier,
9553 ImportSpecifier,
9554 LabeledStatement,
9555 Literal,
9556 LogicalExpression,
9557 MemberExpression,
9558 MetaProperty,
9559 MethodDefinition,
9560 NewExpression,
9561 ObjectExpression,
9562 ObjectPattern,
9563 PrivateIdentifier,
9564 Program,
9565 Property,
9566 PropertyDefinition,
9567 RestElement,
9568 ReturnStatement,
9569 SequenceExpression,
9570 SpreadElement,
9571 Super,
9572 SwitchCase,
9573 SwitchStatement,
9574 TaggedTemplateExpression,
9575 TemplateElement,
9576 TemplateLiteral,
9577 ThisExpression,
9578 ThrowStatement,
9579 TryStatement,
9580 UnaryExpression,
9581 UnknownNode,
9582 UpdateExpression,
9583 VariableDeclaration,
9584 VariableDeclarator,
9585 WhileStatement,
9586 YieldExpression
9587};
9588
9589const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
9590
9591class ExportShimVariable extends Variable {
9592 constructor(module) {
9593 super(MISSING_EXPORT_SHIM_VARIABLE);
9594 this.module = module;
9595 }
9596}
9597
9598class NamespaceVariable extends Variable {
9599 constructor(context, syntheticNamedExports) {
9600 super(context.getModuleName());
9601 this.memberVariables = null;
9602 this.mergedNamespaces = [];
9603 this.referencedEarly = false;
9604 this.references = [];
9605 this.context = context;
9606 this.module = context.module;
9607 this.syntheticNamedExports = syntheticNamedExports;
9608 }
9609 addReference(identifier) {
9610 this.references.push(identifier);
9611 this.name = identifier.name;
9612 }
9613 getMemberVariables() {
9614 if (this.memberVariables) {
9615 return this.memberVariables;
9616 }
9617 const memberVariables = Object.create(null);
9618 for (const name of this.context.getExports().concat(this.context.getReexports())) {
9619 if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
9620 const exportedVariable = this.context.traceExport(name);
9621 if (exportedVariable) {
9622 memberVariables[name] = exportedVariable;
9623 }
9624 }
9625 }
9626 return (this.memberVariables = memberVariables);
9627 }
9628 include() {
9629 this.included = true;
9630 this.context.includeAllExports();
9631 }
9632 prepareNamespace(mergedNamespaces) {
9633 this.mergedNamespaces = mergedNamespaces;
9634 const moduleExecIndex = this.context.getModuleExecIndex();
9635 for (const identifier of this.references) {
9636 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
9637 this.referencedEarly = true;
9638 break;
9639 }
9640 }
9641 }
9642 renderBlock(options) {
9643 const _ = options.compact ? '' : ' ';
9644 const n = options.compact ? '' : '\n';
9645 const t = options.indent;
9646 const memberVariables = this.getMemberVariables();
9647 const members = Object.entries(memberVariables).map(([name, original]) => {
9648 if (this.referencedEarly || original.isReassigned) {
9649 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
9650 }
9651 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
9652 return `${t}${safeName}: ${original.getName()}`;
9653 });
9654 if (options.namespaceToStringTag) {
9655 members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
9656 }
9657 const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
9658 if (!needsObjectAssign)
9659 members.unshift(`${t}__proto__:${_}null`);
9660 let output = `{${n}${members.join(`,${n}`)}${n}}`;
9661 if (needsObjectAssign) {
9662 const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
9663 if (this.mergedNamespaces.length > 0) {
9664 assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
9665 }
9666 if (this.syntheticNamedExports) {
9667 assignmentArgs.push(this.module.getSyntheticNamespace().getName());
9668 }
9669 if (members.length > 0) {
9670 assignmentArgs.push(output);
9671 }
9672 output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
9673 }
9674 if (options.freeze) {
9675 output = `/*#__PURE__*/Object.freeze(${output})`;
9676 }
9677 const name = this.getName();
9678 output = `${options.varOrConst} ${name}${_}=${_}${output};`;
9679 if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
9680 output += `${n}${getSystemExportStatement([this], options)};`;
9681 }
9682 return output;
9683 }
9684 renderFirst() {
9685 return this.referencedEarly;
9686 }
9687}
9688NamespaceVariable.prototype.isNamespace = true;
9689
9690class SyntheticNamedExportVariable extends Variable {
9691 constructor(context, name, syntheticNamespace) {
9692 super(name);
9693 this.baseVariable = null;
9694 this.context = context;
9695 this.module = context.module;
9696 this.syntheticNamespace = syntheticNamespace;
9697 }
9698 getBaseVariable() {
9699 if (this.baseVariable)
9700 return this.baseVariable;
9701 let baseVariable = this.syntheticNamespace;
9702 while (baseVariable instanceof ExportDefaultVariable ||
9703 baseVariable instanceof SyntheticNamedExportVariable) {
9704 if (baseVariable instanceof ExportDefaultVariable) {
9705 const original = baseVariable.getOriginalVariable();
9706 if (original === baseVariable)
9707 break;
9708 baseVariable = original;
9709 }
9710 if (baseVariable instanceof SyntheticNamedExportVariable) {
9711 baseVariable = baseVariable.syntheticNamespace;
9712 }
9713 }
9714 return (this.baseVariable = baseVariable);
9715 }
9716 getBaseVariableName() {
9717 return this.syntheticNamespace.getBaseVariableName();
9718 }
9719 getName() {
9720 const name = this.name;
9721 return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
9722 }
9723 include() {
9724 if (!this.included) {
9725 this.included = true;
9726 this.context.includeVariableInModule(this.syntheticNamespace);
9727 }
9728 }
9729 setRenderNames(baseName, name) {
9730 super.setRenderNames(baseName, name);
9731 }
9732}
9733const getPropertyAccess = (name) => {
9734 return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
9735 ? `.${name}`
9736 : `[${JSON.stringify(name)}]`;
9737};
9738
9739function getId(m) {
9740 return m.id;
9741}
9742
9743function getOriginalLocation(sourcemapChain, location) {
9744 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
9745 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
9746 while (filteredSourcemapChain.length > 0) {
9747 const sourcemap = filteredSourcemapChain.pop();
9748 const line = sourcemap.mappings[location.line - 1];
9749 let locationFound = false;
9750 if (line !== undefined) {
9751 for (const segment of line) {
9752 if (segment[0] >= location.column) {
9753 if (segment.length === 1)
9754 break;
9755 location = {
9756 column: segment[3],
9757 line: segment[2] + 1,
9758 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
9759 source: sourcemap.sources[segment[1]]
9760 };
9761 locationFound = true;
9762 break;
9763 }
9764 }
9765 }
9766 if (!locationFound) {
9767 throw new Error("Can't resolve original location of error.");
9768 }
9769 }
9770 return location;
9771}
9772
9773const NOOP = () => { };
9774let getStartTime = () => [0, 0];
9775let getElapsedTime = () => 0;
9776let getMemory = () => 0;
9777let timers = {};
9778const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
9779function setTimeHelpers() {
9780 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
9781 getStartTime = process.hrtime.bind(process);
9782 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
9783 }
9784 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
9785 getStartTime = () => [performance.now(), 0];
9786 getElapsedTime = previous => performance.now() - previous[0];
9787 }
9788 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
9789 getMemory = () => process.memoryUsage().heapUsed;
9790 }
9791}
9792function getPersistedLabel(label, level) {
9793 switch (level) {
9794 case 1:
9795 return `# ${label}`;
9796 case 2:
9797 return `## ${label}`;
9798 case 3:
9799 return label;
9800 default:
9801 return `${' '.repeat(level - 4)}- ${label}`;
9802 }
9803}
9804function timeStartImpl(label, level = 3) {
9805 label = getPersistedLabel(label, level);
9806 if (!timers.hasOwnProperty(label)) {
9807 timers[label] = {
9808 memory: 0,
9809 startMemory: undefined,
9810 startTime: undefined,
9811 time: 0,
9812 totalMemory: 0
9813 };
9814 }
9815 const currentMemory = getMemory();
9816 timers[label].startTime = getStartTime();
9817 timers[label].startMemory = currentMemory;
9818}
9819function timeEndImpl(label, level = 3) {
9820 label = getPersistedLabel(label, level);
9821 if (timers.hasOwnProperty(label)) {
9822 const currentMemory = getMemory();
9823 timers[label].time += getElapsedTime(timers[label].startTime);
9824 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
9825 timers[label].memory += currentMemory - timers[label].startMemory;
9826 }
9827}
9828function getTimings() {
9829 const newTimings = {};
9830 for (const [label, { time, memory, totalMemory }] of Object.entries(timers)) {
9831 newTimings[label] = [time, memory, totalMemory];
9832 }
9833 return newTimings;
9834}
9835let timeStart = NOOP, timeEnd = NOOP;
9836const TIMED_PLUGIN_HOOKS = {
9837 load: true,
9838 resolveDynamicImport: true,
9839 resolveId: true,
9840 transform: true
9841};
9842function getPluginWithTimers(plugin, index) {
9843 const timedPlugin = {};
9844 for (const hook of Object.keys(plugin)) {
9845 if (TIMED_PLUGIN_HOOKS[hook] === true) {
9846 let timerLabel = `plugin ${index}`;
9847 if (plugin.name) {
9848 timerLabel += ` (${plugin.name})`;
9849 }
9850 timerLabel += ` - ${hook}`;
9851 timedPlugin[hook] = function (...args) {
9852 timeStart(timerLabel, 4);
9853 let result = plugin[hook].apply(this === timedPlugin ? plugin : this, args);
9854 timeEnd(timerLabel, 4);
9855 if (result && typeof result.then === 'function') {
9856 timeStart(`${timerLabel} (async)`, 4);
9857 result = result.then((hookResult) => {
9858 timeEnd(`${timerLabel} (async)`, 4);
9859 return hookResult;
9860 });
9861 }
9862 return result;
9863 };
9864 }
9865 else {
9866 timedPlugin[hook] = plugin[hook];
9867 }
9868 }
9869 return timedPlugin;
9870}
9871function initialiseTimers(inputOptions) {
9872 if (inputOptions.perf) {
9873 timers = {};
9874 setTimeHelpers();
9875 timeStart = timeStartImpl;
9876 timeEnd = timeEndImpl;
9877 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
9878 }
9879 else {
9880 timeStart = NOOP;
9881 timeEnd = NOOP;
9882 }
9883}
9884
9885function markModuleAndImpureDependenciesAsExecuted(baseModule) {
9886 baseModule.isExecuted = true;
9887 const modules = [baseModule];
9888 const visitedModules = new Set();
9889 for (const module of modules) {
9890 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
9891 if (!(dependency instanceof ExternalModule) &&
9892 !dependency.isExecuted &&
9893 (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
9894 !visitedModules.has(dependency.id)) {
9895 dependency.isExecuted = true;
9896 visitedModules.add(dependency.id);
9897 modules.push(dependency);
9898 }
9899 }
9900 }
9901}
9902
9903const MISSING_EXPORT_SHIM_DESCRIPTION = {
9904 identifier: null,
9905 localName: MISSING_EXPORT_SHIM_VARIABLE
9906};
9907function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map(), skipExternalNamespaceReexports) {
9908 const searchedModules = searchedNamesAndModules.get(name);
9909 if (searchedModules) {
9910 if (searchedModules.has(target)) {
9911 return isExportAllSearch ? null : error(errCircularReexport(name, target.id));
9912 }
9913 searchedModules.add(target);
9914 }
9915 else {
9916 searchedNamesAndModules.set(name, new Set([target]));
9917 }
9918 return target.getVariableForExportName(name, {
9919 importerForSideEffects,
9920 isExportAllSearch,
9921 searchedNamesAndModules,
9922 skipExternalNamespaceReexports
9923 });
9924}
9925function getAndExtendSideEffectModules(variable, module) {
9926 const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
9927 let currentVariable = variable;
9928 const referencedVariables = new Set([currentVariable]);
9929 while (true) {
9930 const importingModule = currentVariable.module;
9931 currentVariable =
9932 currentVariable instanceof ExportDefaultVariable
9933 ? currentVariable.getDirectOriginalVariable()
9934 : currentVariable instanceof SyntheticNamedExportVariable
9935 ? currentVariable.syntheticNamespace
9936 : null;
9937 if (!currentVariable || referencedVariables.has(currentVariable)) {
9938 break;
9939 }
9940 referencedVariables.add(currentVariable);
9941 sideEffectModules.add(importingModule);
9942 const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
9943 if (originalSideEffects) {
9944 for (const module of originalSideEffects) {
9945 sideEffectModules.add(module);
9946 }
9947 }
9948 }
9949 return sideEffectModules;
9950}
9951class Module {
9952 constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
9953 this.graph = graph;
9954 this.id = id;
9955 this.options = options;
9956 this.alternativeReexportModules = new Map();
9957 this.ast = null;
9958 this.chunkFileNames = new Set();
9959 this.chunkName = null;
9960 this.cycles = new Set();
9961 this.dependencies = new Set();
9962 this.dynamicDependencies = new Set();
9963 this.dynamicImporters = [];
9964 this.dynamicImports = [];
9965 this.execIndex = Infinity;
9966 this.exportAllSources = new Set();
9967 this.exports = Object.create(null);
9968 this.exportsAll = Object.create(null);
9969 this.implicitlyLoadedAfter = new Set();
9970 this.implicitlyLoadedBefore = new Set();
9971 this.importDescriptions = Object.create(null);
9972 this.importMetas = [];
9973 this.importedFromNotTreeshaken = false;
9974 this.importers = [];
9975 this.imports = new Set();
9976 this.includedDynamicImporters = [];
9977 this.isExecuted = false;
9978 this.isUserDefinedEntryPoint = false;
9979 this.preserveSignature = this.options.preserveEntrySignatures;
9980 this.reexportDescriptions = Object.create(null);
9981 this.sideEffectDependenciesByVariable = new Map();
9982 this.sources = new Set();
9983 this.userChunkNames = new Set();
9984 this.usesTopLevelAwait = false;
9985 this.allExportNames = null;
9986 this.exportAllModules = [];
9987 this.exportNamesByVariable = null;
9988 this.exportShimVariable = new ExportShimVariable(this);
9989 this.namespaceReexportsByName = Object.create(null);
9990 this.relevantDependencies = null;
9991 this.syntheticExports = new Map();
9992 this.syntheticNamespace = null;
9993 this.transformDependencies = [];
9994 this.transitiveReexports = null;
9995 this.excludeFromSourcemap = /\0/.test(id);
9996 this.context = options.moduleContext(id);
9997 // eslint-disable-next-line @typescript-eslint/no-this-alias
9998 const module = this;
9999 this.info = {
10000 ast: null,
10001 code: null,
10002 get dynamicallyImportedIds() {
10003 const dynamicallyImportedIds = [];
10004 for (const { resolution } of module.dynamicImports) {
10005 if (resolution instanceof Module || resolution instanceof ExternalModule) {
10006 dynamicallyImportedIds.push(resolution.id);
10007 }
10008 }
10009 return dynamicallyImportedIds;
10010 },
10011 get dynamicImporters() {
10012 return module.dynamicImporters.sort();
10013 },
10014 hasModuleSideEffects,
10015 id,
10016 get implicitlyLoadedAfterOneOf() {
10017 return Array.from(module.implicitlyLoadedAfter, getId);
10018 },
10019 get implicitlyLoadedBefore() {
10020 return Array.from(module.implicitlyLoadedBefore, getId);
10021 },
10022 get importedIds() {
10023 return Array.from(module.sources, source => module.resolvedIds[source].id);
10024 },
10025 get importers() {
10026 return module.importers.sort();
10027 },
10028 isEntry,
10029 isExternal: false,
10030 meta,
10031 syntheticNamedExports
10032 };
10033 }
10034 basename() {
10035 const base = path.basename(this.id);
10036 const ext = path.extname(this.id);
10037 return makeLegal(ext ? base.slice(0, -ext.length) : base);
10038 }
10039 bindReferences() {
10040 this.ast.bind();
10041 }
10042 error(props, pos) {
10043 this.addLocationToLogProps(props, pos);
10044 return error(props);
10045 }
10046 getAllExportNames() {
10047 if (this.allExportNames) {
10048 return this.allExportNames;
10049 }
10050 const allExportNames = (this.allExportNames = new Set());
10051 for (const name of Object.keys(this.exports)) {
10052 allExportNames.add(name);
10053 }
10054 for (const name of Object.keys(this.reexportDescriptions)) {
10055 allExportNames.add(name);
10056 }
10057 for (const module of this.exportAllModules) {
10058 if (module instanceof ExternalModule) {
10059 allExportNames.add(`*${module.id}`);
10060 continue;
10061 }
10062 for (const name of module.getAllExportNames()) {
10063 if (name !== 'default')
10064 allExportNames.add(name);
10065 }
10066 }
10067 return allExportNames;
10068 }
10069 getDependenciesToBeIncluded() {
10070 if (this.relevantDependencies)
10071 return this.relevantDependencies;
10072 const relevantDependencies = new Set();
10073 const necessaryDependencies = new Set();
10074 const alwaysCheckedDependencies = new Set();
10075 let dependencyVariables = this.imports.keys();
10076 if (this.info.isEntry ||
10077 this.includedDynamicImporters.length > 0 ||
10078 this.namespace.included ||
10079 this.implicitlyLoadedAfter.size > 0) {
10080 dependencyVariables = new Set(dependencyVariables);
10081 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
10082 const exportedVariable = this.getVariableForExportName(exportName);
10083 if (exportedVariable) {
10084 dependencyVariables.add(exportedVariable);
10085 }
10086 }
10087 }
10088 for (let variable of dependencyVariables) {
10089 const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
10090 if (sideEffectDependencies) {
10091 for (const module of sideEffectDependencies) {
10092 alwaysCheckedDependencies.add(module);
10093 }
10094 }
10095 if (variable instanceof SyntheticNamedExportVariable) {
10096 variable = variable.getBaseVariable();
10097 }
10098 else if (variable instanceof ExportDefaultVariable) {
10099 variable = variable.getOriginalVariable();
10100 }
10101 necessaryDependencies.add(variable.module);
10102 }
10103 if (!this.options.treeshake || this.info.hasModuleSideEffects === 'no-treeshake') {
10104 for (const dependency of this.dependencies) {
10105 relevantDependencies.add(dependency);
10106 }
10107 }
10108 else {
10109 this.addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
10110 }
10111 for (const dependency of necessaryDependencies) {
10112 relevantDependencies.add(dependency);
10113 }
10114 return (this.relevantDependencies = relevantDependencies);
10115 }
10116 getExportNamesByVariable() {
10117 if (this.exportNamesByVariable) {
10118 return this.exportNamesByVariable;
10119 }
10120 const exportNamesByVariable = new Map();
10121 for (const exportName of this.getAllExportNames()) {
10122 if (exportName === this.info.syntheticNamedExports)
10123 continue;
10124 let tracedVariable = this.getVariableForExportName(exportName);
10125 if (tracedVariable instanceof ExportDefaultVariable) {
10126 tracedVariable = tracedVariable.getOriginalVariable();
10127 }
10128 if (!tracedVariable ||
10129 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
10130 continue;
10131 }
10132 const existingExportNames = exportNamesByVariable.get(tracedVariable);
10133 if (existingExportNames) {
10134 existingExportNames.push(exportName);
10135 }
10136 else {
10137 exportNamesByVariable.set(tracedVariable, [exportName]);
10138 }
10139 }
10140 return (this.exportNamesByVariable = exportNamesByVariable);
10141 }
10142 getExports() {
10143 return Object.keys(this.exports);
10144 }
10145 getReexports() {
10146 if (this.transitiveReexports) {
10147 return this.transitiveReexports;
10148 }
10149 // to avoid infinite recursion when using circular `export * from X`
10150 this.transitiveReexports = [];
10151 const reexports = new Set();
10152 for (const name in this.reexportDescriptions) {
10153 reexports.add(name);
10154 }
10155 for (const module of this.exportAllModules) {
10156 if (module instanceof ExternalModule) {
10157 reexports.add(`*${module.id}`);
10158 }
10159 else {
10160 for (const name of [...module.getReexports(), ...module.getExports()]) {
10161 if (name !== 'default')
10162 reexports.add(name);
10163 }
10164 }
10165 }
10166 return (this.transitiveReexports = [...reexports]);
10167 }
10168 getRenderedExports() {
10169 // only direct exports are counted here, not reexports at all
10170 const renderedExports = [];
10171 const removedExports = [];
10172 for (const exportName in this.exports) {
10173 const variable = this.getVariableForExportName(exportName);
10174 (variable && variable.included ? renderedExports : removedExports).push(exportName);
10175 }
10176 return { removedExports, renderedExports };
10177 }
10178 getSyntheticNamespace() {
10179 if (this.syntheticNamespace === null) {
10180 this.syntheticNamespace = undefined;
10181 this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
10182 ? this.info.syntheticNamedExports
10183 : 'default');
10184 }
10185 if (!this.syntheticNamespace) {
10186 return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
10187 }
10188 return this.syntheticNamespace;
10189 }
10190 getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules, skipExternalNamespaceReexports } = EMPTY_OBJECT) {
10191 if (name[0] === '*') {
10192 if (name.length === 1) {
10193 // export * from './other'
10194 return this.namespace;
10195 }
10196 else {
10197 // export * from 'external'
10198 const module = this.graph.modulesById.get(name.slice(1));
10199 return module.getVariableForExportName('*');
10200 }
10201 }
10202 // export { foo } from './other'
10203 const reexportDeclaration = this.reexportDescriptions[name];
10204 if (reexportDeclaration) {
10205 const variable = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules, false);
10206 if (!variable) {
10207 return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
10208 }
10209 if (importerForSideEffects) {
10210 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
10211 }
10212 return variable;
10213 }
10214 const exportDeclaration = this.exports[name];
10215 if (exportDeclaration) {
10216 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
10217 return this.exportShimVariable;
10218 }
10219 const name = exportDeclaration.localName;
10220 const variable = this.traceVariable(name, importerForSideEffects);
10221 if (importerForSideEffects) {
10222 getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
10223 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
10224 }
10225 return variable;
10226 }
10227 if (name !== 'default') {
10228 const foundNamespaceReexport = name in this.namespaceReexportsByName
10229 ? this.namespaceReexportsByName[name]
10230 : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports);
10231 if (!skipExternalNamespaceReexports) {
10232 this.namespaceReexportsByName[name] = foundNamespaceReexport;
10233 }
10234 if (foundNamespaceReexport) {
10235 return foundNamespaceReexport;
10236 }
10237 }
10238 if (this.info.syntheticNamedExports) {
10239 let syntheticExport = this.syntheticExports.get(name);
10240 if (!syntheticExport) {
10241 const syntheticNamespace = this.getSyntheticNamespace();
10242 syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
10243 this.syntheticExports.set(name, syntheticExport);
10244 return syntheticExport;
10245 }
10246 return syntheticExport;
10247 }
10248 // we don't want to create shims when we are just
10249 // probing export * modules for exports
10250 if (!isExportAllSearch) {
10251 if (this.options.shimMissingExports) {
10252 this.shimMissingExport(name);
10253 return this.exportShimVariable;
10254 }
10255 }
10256 return null;
10257 }
10258 hasEffects() {
10259 return (this.info.hasModuleSideEffects === 'no-treeshake' ||
10260 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
10261 }
10262 include() {
10263 const context = createInclusionContext();
10264 if (this.ast.shouldBeIncluded(context))
10265 this.ast.include(context, false);
10266 }
10267 includeAllExports(includeNamespaceMembers) {
10268 if (!this.isExecuted) {
10269 markModuleAndImpureDependenciesAsExecuted(this);
10270 this.graph.needsTreeshakingPass = true;
10271 }
10272 for (const exportName of this.getExports()) {
10273 if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
10274 const variable = this.getVariableForExportName(exportName);
10275 variable.deoptimizePath(UNKNOWN_PATH);
10276 if (!variable.included) {
10277 this.includeVariable(variable);
10278 }
10279 }
10280 }
10281 for (const name of this.getReexports()) {
10282 const variable = this.getVariableForExportName(name);
10283 if (variable) {
10284 variable.deoptimizePath(UNKNOWN_PATH);
10285 if (!variable.included) {
10286 this.includeVariable(variable);
10287 }
10288 if (variable instanceof ExternalVariable) {
10289 variable.module.reexported = true;
10290 }
10291 }
10292 }
10293 if (includeNamespaceMembers) {
10294 this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
10295 }
10296 }
10297 includeAllInBundle() {
10298 this.ast.include(createInclusionContext(), true);
10299 this.includeAllExports(false);
10300 }
10301 isIncluded() {
10302 return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
10303 }
10304 linkImports() {
10305 this.addModulesToImportDescriptions(this.importDescriptions);
10306 this.addModulesToImportDescriptions(this.reexportDescriptions);
10307 for (const name in this.exports) {
10308 if (name !== 'default' && name !== this.info.syntheticNamedExports) {
10309 this.exportsAll[name] = this.id;
10310 }
10311 }
10312 const externalExportAllModules = [];
10313 for (const source of this.exportAllSources) {
10314 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
10315 if (module instanceof ExternalModule) {
10316 externalExportAllModules.push(module);
10317 continue;
10318 }
10319 this.exportAllModules.push(module);
10320 for (const name in module.exportsAll) {
10321 if (name in this.exportsAll) {
10322 this.options.onwarn(errNamespaceConflict(name, this, module));
10323 }
10324 else {
10325 this.exportsAll[name] = module.exportsAll[name];
10326 }
10327 }
10328 }
10329 this.exportAllModules.push(...externalExportAllModules);
10330 }
10331 render(options) {
10332 const magicString = this.magicString.clone();
10333 this.ast.render(magicString, options);
10334 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
10335 return magicString;
10336 }
10337 setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
10338 this.info.code = code;
10339 this.originalCode = originalCode;
10340 this.originalSourcemap = originalSourcemap;
10341 this.sourcemapChain = sourcemapChain;
10342 if (transformFiles) {
10343 this.transformFiles = transformFiles;
10344 }
10345 this.transformDependencies = transformDependencies;
10346 this.customTransformCache = customTransformCache;
10347 this.updateOptions(moduleOptions);
10348 timeStart('generate ast', 3);
10349 if (!ast) {
10350 ast = this.tryParse();
10351 }
10352 timeEnd('generate ast', 3);
10353 this.resolvedIds = resolvedIds || Object.create(null);
10354 // By default, `id` is the file name. Custom resolvers and loaders
10355 // can change that, but it makes sense to use it for the source file name
10356 const fileName = this.id;
10357 this.magicString = new MagicString$1(code, {
10358 filename: (this.excludeFromSourcemap ? null : fileName),
10359 indentExclusionRanges: []
10360 });
10361 timeStart('analyse ast', 3);
10362 this.astContext = {
10363 addDynamicImport: this.addDynamicImport.bind(this),
10364 addExport: this.addExport.bind(this),
10365 addImport: this.addImport.bind(this),
10366 addImportMeta: this.addImportMeta.bind(this),
10367 code,
10368 deoptimizationTracker: this.graph.deoptimizationTracker,
10369 error: this.error.bind(this),
10370 fileName,
10371 getExports: this.getExports.bind(this),
10372 getModuleExecIndex: () => this.execIndex,
10373 getModuleName: this.basename.bind(this),
10374 getReexports: this.getReexports.bind(this),
10375 importDescriptions: this.importDescriptions,
10376 includeAllExports: () => this.includeAllExports(true),
10377 includeDynamicImport: this.includeDynamicImport.bind(this),
10378 includeVariableInModule: this.includeVariableInModule.bind(this),
10379 magicString: this.magicString,
10380 module: this,
10381 moduleContext: this.context,
10382 nodeConstructors,
10383 options: this.options,
10384 requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
10385 traceExport: this.getVariableForExportName.bind(this),
10386 traceVariable: this.traceVariable.bind(this),
10387 usesTopLevelAwait: false,
10388 warn: this.warn.bind(this)
10389 };
10390 this.scope = new ModuleScope(this.graph.scope, this.astContext);
10391 this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
10392 this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
10393 this.info.ast = ast;
10394 timeEnd('analyse ast', 3);
10395 }
10396 toJSON() {
10397 return {
10398 ast: this.ast.esTreeNode,
10399 code: this.info.code,
10400 customTransformCache: this.customTransformCache,
10401 dependencies: Array.from(this.dependencies, getId),
10402 id: this.id,
10403 meta: this.info.meta,
10404 moduleSideEffects: this.info.hasModuleSideEffects,
10405 originalCode: this.originalCode,
10406 originalSourcemap: this.originalSourcemap,
10407 resolvedIds: this.resolvedIds,
10408 sourcemapChain: this.sourcemapChain,
10409 syntheticNamedExports: this.info.syntheticNamedExports,
10410 transformDependencies: this.transformDependencies,
10411 transformFiles: this.transformFiles
10412 };
10413 }
10414 traceVariable(name, importerForSideEffects) {
10415 const localVariable = this.scope.variables.get(name);
10416 if (localVariable) {
10417 return localVariable;
10418 }
10419 if (name in this.importDescriptions) {
10420 const importDeclaration = this.importDescriptions[name];
10421 const otherModule = importDeclaration.module;
10422 if (otherModule instanceof Module && importDeclaration.name === '*') {
10423 return otherModule.namespace;
10424 }
10425 const declaration = otherModule.getVariableForExportName(importDeclaration.name, {
10426 importerForSideEffects: importerForSideEffects || this
10427 });
10428 if (!declaration) {
10429 return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
10430 }
10431 return declaration;
10432 }
10433 return null;
10434 }
10435 tryParse() {
10436 try {
10437 return this.graph.contextParse(this.info.code);
10438 }
10439 catch (err) {
10440 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
10441 if (this.id.endsWith('.json')) {
10442 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
10443 }
10444 else if (!this.id.endsWith('.js')) {
10445 message += ' (Note that you need plugins to import files that are not JavaScript)';
10446 }
10447 return this.error({
10448 code: 'PARSE_ERROR',
10449 message,
10450 parserError: err
10451 }, err.pos);
10452 }
10453 }
10454 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
10455 if (moduleSideEffects != null) {
10456 this.info.hasModuleSideEffects = moduleSideEffects;
10457 }
10458 if (syntheticNamedExports != null) {
10459 this.info.syntheticNamedExports = syntheticNamedExports;
10460 }
10461 if (meta != null) {
10462 this.info.meta = { ...this.info.meta, ...meta };
10463 }
10464 }
10465 warn(props, pos) {
10466 this.addLocationToLogProps(props, pos);
10467 this.options.onwarn(props);
10468 }
10469 addDynamicImport(node) {
10470 let argument = node.source;
10471 if (argument instanceof TemplateLiteral) {
10472 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
10473 argument = argument.quasis[0].value.cooked;
10474 }
10475 }
10476 else if (argument instanceof Literal && typeof argument.value === 'string') {
10477 argument = argument.value;
10478 }
10479 this.dynamicImports.push({ argument, node, resolution: null });
10480 }
10481 addExport(node) {
10482 if (node instanceof ExportDefaultDeclaration) {
10483 // export default foo;
10484 this.exports.default = {
10485 identifier: node.variable.getAssignedVariableName(),
10486 localName: 'default'
10487 };
10488 }
10489 else if (node instanceof ExportAllDeclaration) {
10490 const source = node.source.value;
10491 this.sources.add(source);
10492 if (node.exported) {
10493 // export * as name from './other'
10494 const name = node.exported.name;
10495 this.reexportDescriptions[name] = {
10496 localName: '*',
10497 module: null,
10498 source,
10499 start: node.start
10500 };
10501 }
10502 else {
10503 // export * from './other'
10504 this.exportAllSources.add(source);
10505 }
10506 }
10507 else if (node.source instanceof Literal) {
10508 // export { name } from './other'
10509 const source = node.source.value;
10510 this.sources.add(source);
10511 for (const specifier of node.specifiers) {
10512 const name = specifier.exported.name;
10513 this.reexportDescriptions[name] = {
10514 localName: specifier.local.name,
10515 module: null,
10516 source,
10517 start: specifier.start
10518 };
10519 }
10520 }
10521 else if (node.declaration) {
10522 const declaration = node.declaration;
10523 if (declaration instanceof VariableDeclaration) {
10524 // export var { foo, bar } = ...
10525 // export var foo = 1, bar = 2;
10526 for (const declarator of declaration.declarations) {
10527 for (const localName of extractAssignedNames(declarator.id)) {
10528 this.exports[localName] = { identifier: null, localName };
10529 }
10530 }
10531 }
10532 else {
10533 // export function foo () {}
10534 const localName = declaration.id.name;
10535 this.exports[localName] = { identifier: null, localName };
10536 }
10537 }
10538 else {
10539 // export { foo, bar, baz }
10540 for (const specifier of node.specifiers) {
10541 const localName = specifier.local.name;
10542 const exportedName = specifier.exported.name;
10543 this.exports[exportedName] = { identifier: null, localName };
10544 }
10545 }
10546 }
10547 addImport(node) {
10548 const source = node.source.value;
10549 this.sources.add(source);
10550 for (const specifier of node.specifiers) {
10551 const isDefault = specifier.type === ImportDefaultSpecifier$1;
10552 const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
10553 const name = isDefault
10554 ? 'default'
10555 : isNamespace
10556 ? '*'
10557 : specifier.imported.name;
10558 this.importDescriptions[specifier.local.name] = {
10559 module: null,
10560 name,
10561 source,
10562 start: specifier.start
10563 };
10564 }
10565 }
10566 addImportMeta(node) {
10567 this.importMetas.push(node);
10568 }
10569 addLocationToLogProps(props, pos) {
10570 props.id = this.id;
10571 props.pos = pos;
10572 let code = this.info.code;
10573 const location = locate(code, pos, { offsetLine: 1 });
10574 if (location) {
10575 let { column, line } = location;
10576 try {
10577 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
10578 code = this.originalCode;
10579 }
10580 catch (e) {
10581 this.options.onwarn({
10582 code: 'SOURCEMAP_ERROR',
10583 id: this.id,
10584 loc: {
10585 column,
10586 file: this.id,
10587 line
10588 },
10589 message: `Error when using sourcemap for reporting an error: ${e.message}`,
10590 pos
10591 });
10592 }
10593 augmentCodeLocation(props, { column, line }, code, this.id);
10594 }
10595 }
10596 addModulesToImportDescriptions(importDescription) {
10597 for (const specifier of Object.values(importDescription)) {
10598 const id = this.resolvedIds[specifier.source].id;
10599 specifier.module = this.graph.modulesById.get(id);
10600 }
10601 }
10602 addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
10603 const handledDependencies = new Set();
10604 const addSideEffectDependencies = (possibleDependencies) => {
10605 for (const dependency of possibleDependencies) {
10606 if (handledDependencies.has(dependency)) {
10607 continue;
10608 }
10609 handledDependencies.add(dependency);
10610 if (necessaryDependencies.has(dependency)) {
10611 relevantDependencies.add(dependency);
10612 continue;
10613 }
10614 if (!(dependency.info.hasModuleSideEffects || alwaysCheckedDependencies.has(dependency))) {
10615 continue;
10616 }
10617 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
10618 relevantDependencies.add(dependency);
10619 continue;
10620 }
10621 addSideEffectDependencies(dependency.dependencies);
10622 }
10623 };
10624 addSideEffectDependencies(this.dependencies);
10625 addSideEffectDependencies(alwaysCheckedDependencies);
10626 }
10627 getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports = false) {
10628 let foundSyntheticDeclaration = null;
10629 const skipExternalNamespaceValues = [{ searchedNamesAndModules, skipExternalNamespaces: true }];
10630 if (!skipExternalNamespaceReexports) {
10631 const clonedSearchedNamesAndModules = new Map();
10632 for (const [name, modules] of searchedNamesAndModules || []) {
10633 clonedSearchedNamesAndModules.set(name, new Set(modules));
10634 }
10635 skipExternalNamespaceValues.push({
10636 searchedNamesAndModules: clonedSearchedNamesAndModules,
10637 skipExternalNamespaces: false
10638 });
10639 }
10640 for (const { skipExternalNamespaces, searchedNamesAndModules } of skipExternalNamespaceValues) {
10641 const foundDeclarations = new Set();
10642 for (const module of this.exportAllModules) {
10643 if (module instanceof Module || !skipExternalNamespaces) {
10644 const declaration = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, searchedNamesAndModules, skipExternalNamespaces);
10645 if (declaration) {
10646 if (!(declaration instanceof SyntheticNamedExportVariable)) {
10647 foundDeclarations.add(declaration);
10648 }
10649 else if (!foundSyntheticDeclaration) {
10650 foundSyntheticDeclaration = declaration;
10651 }
10652 }
10653 }
10654 }
10655 if (foundDeclarations.size === 1) {
10656 return [...foundDeclarations][0];
10657 }
10658 if (foundDeclarations.size > 1) {
10659 if (skipExternalNamespaces) {
10660 return null;
10661 }
10662 const foundDeclarationList = [...foundDeclarations];
10663 const usedDeclaration = foundDeclarationList[0];
10664 this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
10665 return usedDeclaration;
10666 }
10667 }
10668 if (foundSyntheticDeclaration) {
10669 return foundSyntheticDeclaration;
10670 }
10671 return null;
10672 }
10673 includeAndGetAdditionalMergedNamespaces() {
10674 const mergedNamespaces = [];
10675 for (const module of this.exportAllModules) {
10676 if (module instanceof ExternalModule) {
10677 const externalVariable = module.getVariableForExportName('*');
10678 externalVariable.include();
10679 this.imports.add(externalVariable);
10680 mergedNamespaces.push(externalVariable);
10681 }
10682 else if (module.info.syntheticNamedExports) {
10683 const syntheticNamespace = module.getSyntheticNamespace();
10684 syntheticNamespace.include();
10685 this.imports.add(syntheticNamespace);
10686 mergedNamespaces.push(syntheticNamespace);
10687 }
10688 }
10689 return mergedNamespaces;
10690 }
10691 includeDynamicImport(node) {
10692 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
10693 if (resolution instanceof Module) {
10694 resolution.includedDynamicImporters.push(this);
10695 resolution.includeAllExports(true);
10696 }
10697 }
10698 includeVariable(variable) {
10699 if (!variable.included) {
10700 variable.include();
10701 this.graph.needsTreeshakingPass = true;
10702 const variableModule = variable.module;
10703 if (variableModule && variableModule instanceof Module) {
10704 if (!variableModule.isExecuted) {
10705 markModuleAndImpureDependenciesAsExecuted(variableModule);
10706 }
10707 if (variableModule !== this) {
10708 const sideEffectModules = getAndExtendSideEffectModules(variable, this);
10709 for (const module of sideEffectModules) {
10710 if (!module.isExecuted) {
10711 markModuleAndImpureDependenciesAsExecuted(module);
10712 }
10713 }
10714 }
10715 }
10716 }
10717 }
10718 includeVariableInModule(variable) {
10719 this.includeVariable(variable);
10720 const variableModule = variable.module;
10721 if (variableModule && variableModule !== this) {
10722 this.imports.add(variable);
10723 }
10724 }
10725 shimMissingExport(name) {
10726 this.options.onwarn({
10727 code: 'SHIMMED_EXPORT',
10728 exporter: relativeId(this.id),
10729 exportName: name,
10730 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
10731 });
10732 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
10733 }
10734}
10735// if there is a cyclic import in the reexport chain, we should not
10736// import from the original module but from the cyclic module to not
10737// mess up execution order.
10738function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
10739 if (variable.module instanceof Module && variable.module !== reexporter) {
10740 const exporterCycles = variable.module.cycles;
10741 if (exporterCycles.size > 0) {
10742 const importerCycles = reexporter.cycles;
10743 for (const cycleSymbol of importerCycles) {
10744 if (exporterCycles.has(cycleSymbol)) {
10745 importer.alternativeReexportModules.set(variable, reexporter);
10746 break;
10747 }
10748 }
10749 }
10750 }
10751}
10752
10753function removeJsExtension(name) {
10754 return name.endsWith('.js') ? name.slice(0, -3) : name;
10755}
10756
10757function getCompleteAmdId(options, chunkId) {
10758 if (!options.autoId) {
10759 return options.id || '';
10760 }
10761 else {
10762 return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
10763 }
10764}
10765
10766function getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
10767 const _ = compact ? '' : ' ';
10768 const n = compact ? '' : '\n';
10769 if (!namedExportsMode) {
10770 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
10771 }
10772 let exportBlock = '';
10773 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
10774 if (reexports && namedExportsMode) {
10775 for (const specifier of reexports) {
10776 if (specifier.reexported !== '*') {
10777 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
10778 if (exportBlock)
10779 exportBlock += n;
10780 exportBlock +=
10781 specifier.imported !== '*' && specifier.needsLiveBinding
10782 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
10783 `${t}enumerable:${_}true,${n}` +
10784 `${t}get:${_}function${_}()${_}{${n}` +
10785 `${t}${t}return ${importName};${n}${t}}${n}});`
10786 : `exports.${specifier.reexported}${_}=${_}${importName};`;
10787 }
10788 }
10789 }
10790 }
10791 for (const { exported, local } of exports) {
10792 const lhs = `exports${RESERVED_NAMES[exported] ? `['${exported}']` : `.${exported}`}`;
10793 const rhs = local;
10794 if (lhs !== rhs) {
10795 if (exportBlock)
10796 exportBlock += n;
10797 exportBlock += `${lhs}${_}=${_}${rhs};`;
10798 }
10799 }
10800 for (const { name, reexports } of dependencies) {
10801 if (reexports && namedExportsMode) {
10802 for (const specifier of reexports) {
10803 if (specifier.reexported === '*') {
10804 if (exportBlock)
10805 exportBlock += n;
10806 if (specifier.needsLiveBinding) {
10807 exportBlock +=
10808 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
10809 `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
10810 `${t}${t}enumerable:${_}true,${n}` +
10811 `${t}${t}get:${_}function${_}()${_}{${n}` +
10812 `${t}${t}${t}return ${name}[k];${n}` +
10813 `${t}${t}}${n}${t}});${n}});`;
10814 }
10815 else {
10816 exportBlock +=
10817 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
10818 `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}exports[k]${_}=${_}${name}[k];${n}});`;
10819 }
10820 }
10821 }
10822 }
10823 }
10824 if (exportBlock) {
10825 return `${n}${n}${exportBlock}`;
10826 }
10827 return '';
10828}
10829function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
10830 if (exports.length > 0) {
10831 return exports[0].local;
10832 }
10833 else {
10834 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
10835 if (reexports) {
10836 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
10837 }
10838 }
10839 }
10840}
10841function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
10842 if (imported === 'default') {
10843 if (!isChunk) {
10844 const moduleInterop = String(interop(moduleId));
10845 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
10846 ? defaultVariableName
10847 : moduleVariableName;
10848 return isDefaultAProperty(moduleInterop, externalLiveBindings)
10849 ? `${variableName}['default']`
10850 : variableName;
10851 }
10852 return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
10853 }
10854 if (imported === '*') {
10855 return (isChunk
10856 ? !depNamedExportsMode
10857 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
10858 ? namespaceVariableName
10859 : moduleVariableName;
10860 }
10861 return `${moduleVariableName}.${imported}`;
10862}
10863function getEsModuleExport(_) {
10864 return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
10865}
10866function getNamespaceToStringExport(_) {
10867 return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
10868}
10869function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
10870 let namespaceMarkers = '';
10871 if (hasNamedExports) {
10872 if (addEsModule) {
10873 namespaceMarkers += getEsModuleExport(_);
10874 }
10875 if (addNamespaceToStringTag) {
10876 if (namespaceMarkers) {
10877 namespaceMarkers += n;
10878 }
10879 namespaceMarkers += getNamespaceToStringExport(_);
10880 }
10881 }
10882 return namespaceMarkers;
10883}
10884
10885function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
10886 const neededInteropHelpers = new Set();
10887 const interopStatements = [];
10888 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
10889 neededInteropHelpers.add(helper);
10890 interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
10891 };
10892 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
10893 if (isChunk) {
10894 for (const { imported, reexported } of [
10895 ...(imports || []),
10896 ...(reexports || [])
10897 ]) {
10898 if (imported === '*' && reexported !== '*') {
10899 if (!namedExportsMode) {
10900 addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
10901 }
10902 break;
10903 }
10904 }
10905 }
10906 else {
10907 const moduleInterop = String(interop(id));
10908 let hasDefault = false;
10909 let hasNamespace = false;
10910 for (const { imported, reexported } of [
10911 ...(imports || []),
10912 ...(reexports || [])
10913 ]) {
10914 let helper;
10915 let variableName;
10916 if (imported === 'default') {
10917 if (!hasDefault) {
10918 hasDefault = true;
10919 if (defaultVariableName !== namespaceVariableName) {
10920 variableName = defaultVariableName;
10921 helper = defaultInteropHelpersByInteropType[moduleInterop];
10922 }
10923 }
10924 }
10925 else if (imported === '*' && reexported !== '*') {
10926 if (!hasNamespace) {
10927 hasNamespace = true;
10928 helper = namespaceInteropHelpersByInteropType[moduleInterop];
10929 variableName = namespaceVariableName;
10930 }
10931 }
10932 if (helper) {
10933 addInteropStatement(variableName, helper, name);
10934 }
10935 }
10936 }
10937 }
10938 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
10939}
10940
10941// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
10942// The assumption is that this makes sense for all relative ids:
10943// https://requirejs.org/docs/api.html#jsfiles
10944function removeExtensionFromRelativeAmdId(id) {
10945 return id[0] === '.' ? removeJsExtension(id) : id;
10946}
10947
10948const builtins = {
10949 assert: true,
10950 buffer: true,
10951 console: true,
10952 constants: true,
10953 domain: true,
10954 events: true,
10955 http: true,
10956 https: true,
10957 os: true,
10958 path: true,
10959 process: true,
10960 punycode: true,
10961 querystring: true,
10962 stream: true,
10963 string_decoder: true,
10964 timers: true,
10965 tty: true,
10966 url: true,
10967 util: true,
10968 vm: true,
10969 zlib: true
10970};
10971function warnOnBuiltins(warn, dependencies) {
10972 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
10973 if (!externalBuiltins.length)
10974 return;
10975 warn({
10976 code: 'MISSING_NODE_BUILTINS',
10977 message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node`,
10978 modules: externalBuiltins
10979 });
10980}
10981
10982function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
10983 warnOnBuiltins(warn, dependencies);
10984 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
10985 const args = dependencies.map(m => m.name);
10986 const n = compact ? '' : '\n';
10987 const s = compact ? '' : ';';
10988 const _ = compact ? '' : ' ';
10989 if (namedExportsMode && hasExports) {
10990 args.unshift(`exports`);
10991 deps.unshift(`'exports'`);
10992 }
10993 if (accessedGlobals.has('require')) {
10994 args.unshift('require');
10995 deps.unshift(`'require'`);
10996 }
10997 if (accessedGlobals.has('module')) {
10998 args.unshift('module');
10999 deps.unshift(`'module'`);
11000 }
11001 const completeAmdId = getCompleteAmdId(amd, id);
11002 const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
11003 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
11004 const useStrict = strict ? `${_}'use strict';` : '';
11005 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
11006 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
11007 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
11008 if (namespaceMarkers) {
11009 namespaceMarkers = n + n + namespaceMarkers;
11010 }
11011 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
11012 return magicString
11013 .indent(t)
11014 .prepend(`${amd.define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
11015 .append(`${n}${n}});`);
11016}
11017
11018function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
11019 const n = compact ? '' : '\n';
11020 const s = compact ? '' : ';';
11021 const _ = compact ? '' : ' ';
11022 const useStrict = strict ? `'use strict';${n}${n}` : '';
11023 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
11024 if (namespaceMarkers) {
11025 namespaceMarkers += n + n;
11026 }
11027 const importBlock = getImportBlock$1(dependencies, compact, varOrConst, n, _);
11028 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
11029 magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
11030 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
11031 return magicString.append(`${exportBlock}${outro}`);
11032}
11033function getImportBlock$1(dependencies, compact, varOrConst, n, _) {
11034 let importBlock = '';
11035 let definingVariable = false;
11036 for (const { id, name, reexports, imports } of dependencies) {
11037 if (!reexports && !imports) {
11038 if (importBlock) {
11039 importBlock += !compact || definingVariable ? `;${n}` : ',';
11040 }
11041 definingVariable = false;
11042 importBlock += `require('${id}')`;
11043 }
11044 else {
11045 importBlock +=
11046 compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
11047 definingVariable = true;
11048 importBlock += `${name}${_}=${_}require('${id}')`;
11049 }
11050 }
11051 if (importBlock) {
11052 return `${importBlock};${n}${n}`;
11053 }
11054 return '';
11055}
11056
11057function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
11058 const _ = compact ? '' : ' ';
11059 const n = compact ? '' : '\n';
11060 const importBlock = getImportBlock(dependencies, _);
11061 if (importBlock.length > 0)
11062 intro += importBlock.join(n) + n + n;
11063 if (intro)
11064 magicString.prepend(intro);
11065 const exportBlock = getExportBlock(exports, _, varOrConst);
11066 if (exportBlock.length)
11067 magicString.append(n + n + exportBlock.join(n).trim());
11068 if (outro)
11069 magicString.append(outro);
11070 return magicString.trim();
11071}
11072function getImportBlock(dependencies, _) {
11073 const importBlock = [];
11074 for (const { id, reexports, imports, name } of dependencies) {
11075 if (!reexports && !imports) {
11076 importBlock.push(`import${_}'${id}';`);
11077 continue;
11078 }
11079 if (imports) {
11080 let defaultImport = null;
11081 let starImport = null;
11082 const importedNames = [];
11083 for (const specifier of imports) {
11084 if (specifier.imported === 'default') {
11085 defaultImport = specifier;
11086 }
11087 else if (specifier.imported === '*') {
11088 starImport = specifier;
11089 }
11090 else {
11091 importedNames.push(specifier);
11092 }
11093 }
11094 if (starImport) {
11095 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
11096 }
11097 if (defaultImport && importedNames.length === 0) {
11098 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
11099 }
11100 else if (importedNames.length > 0) {
11101 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
11102 .map(specifier => {
11103 if (specifier.imported === specifier.local) {
11104 return specifier.imported;
11105 }
11106 else {
11107 return `${specifier.imported} as ${specifier.local}`;
11108 }
11109 })
11110 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
11111 }
11112 }
11113 if (reexports) {
11114 let starExport = null;
11115 const namespaceReexports = [];
11116 const namedReexports = [];
11117 for (const specifier of reexports) {
11118 if (specifier.reexported === '*') {
11119 starExport = specifier;
11120 }
11121 else if (specifier.imported === '*') {
11122 namespaceReexports.push(specifier);
11123 }
11124 else {
11125 namedReexports.push(specifier);
11126 }
11127 }
11128 if (starExport) {
11129 importBlock.push(`export${_}*${_}from${_}'${id}';`);
11130 }
11131 if (namespaceReexports.length > 0) {
11132 if (!imports ||
11133 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
11134 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
11135 }
11136 for (const specifier of namespaceReexports) {
11137 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
11138 }
11139 }
11140 if (namedReexports.length > 0) {
11141 importBlock.push(`export${_}{${_}${namedReexports
11142 .map(specifier => {
11143 if (specifier.imported === specifier.reexported) {
11144 return specifier.imported;
11145 }
11146 else {
11147 return `${specifier.imported} as ${specifier.reexported}`;
11148 }
11149 })
11150 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
11151 }
11152 }
11153 }
11154 return importBlock;
11155}
11156function getExportBlock(exports, _, varOrConst) {
11157 const exportBlock = [];
11158 const exportDeclaration = [];
11159 for (const specifier of exports) {
11160 if (specifier.expression) {
11161 exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
11162 }
11163 exportDeclaration.push(specifier.exported === specifier.local
11164 ? specifier.local
11165 : `${specifier.local} as ${specifier.exported}`);
11166 }
11167 if (exportDeclaration.length) {
11168 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
11169 }
11170 return exportBlock;
11171}
11172
11173// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
11174// if the property name isn't trivial
11175const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
11176function property(prop) {
11177 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
11178}
11179function keypath(keypath) {
11180 return keypath.split('.').map(property).join('');
11181}
11182
11183function setupNamespace(name, root, globals, compact) {
11184 const _ = compact ? '' : ' ';
11185 const parts = name.split('.');
11186 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
11187 parts.pop();
11188 let acc = root;
11189 return (parts
11190 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
11191 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
11192}
11193function assignToDeepVariable(deepName, root, globals, compact, assignment) {
11194 const _ = compact ? '' : ' ';
11195 const parts = deepName.split('.');
11196 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
11197 const last = parts.pop();
11198 let acc = root;
11199 let deepAssignment = parts
11200 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
11201 .concat(`${acc}${property(last)}`)
11202 .join(`,${_}`)
11203 .concat(`${_}=${_}${assignment}`);
11204 if (parts.length > 0) {
11205 deepAssignment = `(${deepAssignment})`;
11206 }
11207 return deepAssignment;
11208}
11209
11210function trimEmptyImports(dependencies) {
11211 let i = dependencies.length;
11212 while (i--) {
11213 const { imports, reexports } = dependencies[i];
11214 if (imports || reexports) {
11215 return dependencies.slice(0, i + 1);
11216 }
11217 }
11218 return [];
11219}
11220
11221const thisProp = (name) => `this${keypath(name)}`;
11222function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
11223 const _ = compact ? '' : ' ';
11224 const s = compact ? '' : ';';
11225 const n = compact ? '' : '\n';
11226 const isNamespaced = name && name.indexOf('.') !== -1;
11227 const useVariableAssignment = !extend && !isNamespaced;
11228 if (name && useVariableAssignment && !isLegal(name)) {
11229 return error({
11230 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
11231 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
11232 });
11233 }
11234 warnOnBuiltins(warn, dependencies);
11235 const external = trimEmptyImports(dependencies);
11236 const deps = external.map(dep => dep.globalName || 'null');
11237 const args = external.map(m => m.name);
11238 if (hasExports && !name) {
11239 warn({
11240 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
11241 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
11242 });
11243 }
11244 if (namedExportsMode && hasExports) {
11245 if (extend) {
11246 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
11247 args.unshift('exports');
11248 }
11249 else {
11250 deps.unshift('{}');
11251 args.unshift('exports');
11252 }
11253 }
11254 const useStrict = strict ? `${t}'use strict';${n}` : '';
11255 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
11256 magicString.prepend(`${intro}${interopBlock}`);
11257 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
11258 if (hasExports) {
11259 if (name && !(extend && namedExportsMode)) {
11260 wrapperIntro =
11261 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
11262 `${_}=${_}${wrapperIntro}`;
11263 }
11264 if (isNamespaced) {
11265 wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
11266 }
11267 }
11268 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
11269 if (hasExports && !extend && namedExportsMode) {
11270 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
11271 }
11272 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
11273 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
11274 if (namespaceMarkers) {
11275 namespaceMarkers = n + n + namespaceMarkers;
11276 }
11277 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
11278 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
11279}
11280
11281function getStarExcludes({ dependencies, exports }) {
11282 const starExcludes = new Set(exports.map(expt => expt.exported));
11283 if (!starExcludes.has('default'))
11284 starExcludes.add('default');
11285 // also include reexport names
11286 for (const { reexports } of dependencies) {
11287 if (reexports) {
11288 for (const reexport of reexports) {
11289 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
11290 starExcludes.add(reexport.reexported);
11291 }
11292 }
11293 }
11294 return starExcludes;
11295}
11296const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
11297 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
11298 .map(prop => `${prop}:${_}1`)
11299 .join(`,${_}`)}${_}};`
11300 : '';
11301const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
11302function getExportsBlock(exports, _, t, n) {
11303 if (exports.length === 0) {
11304 return '';
11305 }
11306 if (exports.length === 1) {
11307 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
11308 }
11309 return (`${t}${t}${t}exports({${n}` +
11310 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
11311 `${n}${t}${t}${t}});${n}${n}`);
11312}
11313const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
11314 .filter(expt => expt.hoisted || expt.uninitialized)
11315 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
11316const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
11317 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
11318 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
11319const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
11320 .filter(expt => expt.expression)
11321 .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
11322function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
11323 const n = options.compact ? '' : '\n';
11324 const _ = options.compact ? '' : ' ';
11325 const dependencyIds = dependencies.map(m => `'${m.id}'`);
11326 const importBindings = [];
11327 let starExcludes;
11328 const setters = [];
11329 for (const { imports, reexports } of dependencies) {
11330 const setter = [];
11331 if (imports) {
11332 for (const specifier of imports) {
11333 importBindings.push(specifier.local);
11334 if (specifier.imported === '*') {
11335 setter.push(`${specifier.local}${_}=${_}module;`);
11336 }
11337 else {
11338 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
11339 }
11340 }
11341 }
11342 if (reexports) {
11343 let createdSetter = false;
11344 // bulk-reexport form
11345 if (reexports.length > 1 ||
11346 (reexports.length === 1 &&
11347 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
11348 // star reexports
11349 for (const specifier of reexports) {
11350 if (specifier.reexported !== '*')
11351 continue;
11352 // need own exports list for deduping in star export case
11353 if (!starExcludes) {
11354 starExcludes = getStarExcludes({ dependencies, exports });
11355 }
11356 if (!createdSetter) {
11357 setter.push(`${varOrConst} _setter${_}=${_}{};`);
11358 createdSetter = true;
11359 }
11360 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
11361 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
11362 setter.push('}');
11363 }
11364 // star import reexport
11365 for (const specifier of reexports) {
11366 if (specifier.imported !== '*' || specifier.reexported === '*')
11367 continue;
11368 setter.push(`exports('${specifier.reexported}',${_}module);`);
11369 }
11370 // reexports
11371 for (const specifier of reexports) {
11372 if (specifier.reexported === '*' || specifier.imported === '*')
11373 continue;
11374 if (!createdSetter) {
11375 setter.push(`${varOrConst} _setter${_}=${_}{};`);
11376 createdSetter = true;
11377 }
11378 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
11379 }
11380 if (createdSetter) {
11381 setter.push('exports(_setter);');
11382 }
11383 }
11384 else {
11385 // single reexport
11386 for (const specifier of reexports) {
11387 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
11388 }
11389 }
11390 }
11391 setters.push(setter.join(`${n}${t}${t}${t}`));
11392 }
11393 const registeredName = options.name ? `'${options.name}',${_}` : '';
11394 const wrapperParams = accessedGlobals.has('module')
11395 ? `exports,${_}module`
11396 : hasExports
11397 ? 'exports'
11398 : '';
11399 let wrapperStart = `System.register(${registeredName}[` +
11400 dependencyIds.join(`,${_}`) +
11401 `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
11402 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
11403 getImportBindingsBlock(importBindings, _, t, n) +
11404 `${n}${t}return${_}{${setters.length
11405 ? `${n}${t}${t}setters:${_}[${setters
11406 .map(s => s
11407 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
11408 : options.systemNullSetters
11409 ? `null`
11410 : `function${_}()${_}{}`)
11411 .join(`,${_}`)}],`
11412 : ''}${n}`;
11413 wrapperStart +=
11414 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
11415 getHoistedExportsBlock(exports, _, t, n);
11416 const wrapperEnd = `${n}${n}` +
11417 getSyntheticExportsBlock(exports, _, t, n) +
11418 getMissingExportsBlock(exports, _, t, n) +
11419 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
11420 if (intro)
11421 magicString.prepend(intro);
11422 if (outro)
11423 magicString.append(outro);
11424 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
11425}
11426
11427function globalProp(name, globalVar) {
11428 if (!name)
11429 return 'null';
11430 return `${globalVar}${keypath(name)}`;
11431}
11432function safeAccess(name, globalVar, _) {
11433 const parts = name.split('.');
11434 let acc = globalVar;
11435 return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
11436}
11437function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
11438 const _ = compact ? '' : ' ';
11439 const n = compact ? '' : '\n';
11440 const s = compact ? '' : ';';
11441 const factoryVar = compact ? 'f' : 'factory';
11442 const globalVar = compact ? 'g' : 'global';
11443 if (hasExports && !name) {
11444 return error({
11445 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
11446 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
11447 });
11448 }
11449 warnOnBuiltins(warn, dependencies);
11450 const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
11451 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
11452 const trimmedImports = trimEmptyImports(dependencies);
11453 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
11454 const factoryArgs = trimmedImports.map(m => m.name);
11455 if (namedExportsMode && (hasExports || noConflict)) {
11456 amdDeps.unshift(`'exports'`);
11457 cjsDeps.unshift(`exports`);
11458 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
11459 factoryArgs.unshift('exports');
11460 }
11461 const completeAmdId = getCompleteAmdId(amd, id);
11462 const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
11463 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
11464 const define = amd.define;
11465 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
11466 const useStrict = strict ? `${_}'use strict';${n}` : ``;
11467 let iifeExport;
11468 if (noConflict) {
11469 const noConflictExportsVar = compact ? 'e' : 'exports';
11470 let factory;
11471 if (!namedExportsMode && hasExports) {
11472 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
11473 }
11474 else {
11475 const module = globalDeps.shift();
11476 factory =
11477 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
11478 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
11479 }
11480 iifeExport =
11481 `(function${_}()${_}{${n}` +
11482 `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
11483 `${t}${t}${factory}${n}` +
11484 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
11485 `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
11486 `${t}}())`;
11487 }
11488 else {
11489 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
11490 if (!namedExportsMode && hasExports) {
11491 iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
11492 }
11493 }
11494 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
11495 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
11496 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
11497 const iifeStart = iifeNeedsGlobal
11498 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
11499 : '';
11500 const iifeEnd = iifeNeedsGlobal ? ')' : '';
11501 const cjsIntro = iifeNeedsGlobal
11502 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
11503 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
11504 : '';
11505 // factory function should be wrapped by parentheses to avoid lazy parsing
11506 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
11507 cjsIntro +
11508 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
11509 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
11510 `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
11511 const wrapperOutro = n + n + '})));';
11512 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
11513 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
11514 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
11515 if (namespaceMarkers) {
11516 namespaceMarkers = n + n + namespaceMarkers;
11517 }
11518 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
11519 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
11520}
11521
11522var finalisers = { amd, cjs, es, iife, system, umd };
11523
11524class Source {
11525 constructor(filename, content) {
11526 this.isOriginal = true;
11527 this.filename = filename;
11528 this.content = content;
11529 }
11530 traceSegment(line, column, name) {
11531 return { column, line, name, source: this };
11532 }
11533}
11534class Link {
11535 constructor(map, sources) {
11536 this.sources = sources;
11537 this.names = map.names;
11538 this.mappings = map.mappings;
11539 }
11540 traceMappings() {
11541 const sources = [];
11542 const sourcesContent = [];
11543 const names = [];
11544 const nameIndexMap = new Map();
11545 const mappings = [];
11546 for (const line of this.mappings) {
11547 const tracedLine = [];
11548 for (const segment of line) {
11549 if (segment.length == 1)
11550 continue;
11551 const source = this.sources[segment[1]];
11552 if (!source)
11553 continue;
11554 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
11555 if (traced) {
11556 // newer sources are more likely to be used, so search backwards.
11557 let sourceIndex = sources.lastIndexOf(traced.source.filename);
11558 if (sourceIndex === -1) {
11559 sourceIndex = sources.length;
11560 sources.push(traced.source.filename);
11561 sourcesContent[sourceIndex] = traced.source.content;
11562 }
11563 else if (sourcesContent[sourceIndex] == null) {
11564 sourcesContent[sourceIndex] = traced.source.content;
11565 }
11566 else if (traced.source.content != null &&
11567 sourcesContent[sourceIndex] !== traced.source.content) {
11568 return error({
11569 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
11570 });
11571 }
11572 const tracedSegment = [
11573 segment[0],
11574 sourceIndex,
11575 traced.line,
11576 traced.column
11577 ];
11578 if (traced.name) {
11579 let nameIndex = nameIndexMap.get(traced.name);
11580 if (nameIndex === undefined) {
11581 nameIndex = names.length;
11582 names.push(traced.name);
11583 nameIndexMap.set(traced.name, nameIndex);
11584 }
11585 tracedSegment[4] = nameIndex;
11586 }
11587 tracedLine.push(tracedSegment);
11588 }
11589 }
11590 mappings.push(tracedLine);
11591 }
11592 return { mappings, names, sources, sourcesContent };
11593 }
11594 traceSegment(line, column, name) {
11595 const segments = this.mappings[line];
11596 if (!segments)
11597 return null;
11598 // binary search through segments for the given column
11599 let i = 0;
11600 let j = segments.length - 1;
11601 while (i <= j) {
11602 const m = (i + j) >> 1;
11603 const segment = segments[m];
11604 if (segment[0] === column) {
11605 if (segment.length == 1)
11606 return null;
11607 const source = this.sources[segment[1]];
11608 if (!source)
11609 return null;
11610 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
11611 }
11612 if (segment[0] > column) {
11613 j = m - 1;
11614 }
11615 else {
11616 i = m + 1;
11617 }
11618 }
11619 return null;
11620 }
11621}
11622function getLinkMap(warn) {
11623 return function linkMap(source, map) {
11624 if (map.mappings) {
11625 return new Link(map, [source]);
11626 }
11627 warn({
11628 code: 'SOURCEMAP_BROKEN',
11629 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
11630 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
11631 'documentation for help',
11632 plugin: map.plugin,
11633 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
11634 });
11635 return new Link({
11636 mappings: [],
11637 names: []
11638 }, [source]);
11639 };
11640}
11641function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
11642 let source;
11643 if (!originalSourcemap) {
11644 source = new Source(id, originalCode);
11645 }
11646 else {
11647 const sources = originalSourcemap.sources;
11648 const sourcesContent = originalSourcemap.sourcesContent || [];
11649 const directory = path.dirname(id) || '.';
11650 const sourceRoot = originalSourcemap.sourceRoot || '.';
11651 const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
11652 source = new Link(originalSourcemap, baseSources);
11653 }
11654 return sourcemapChain.reduce(linkMap, source);
11655}
11656function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
11657 const linkMap = getLinkMap(warn);
11658 const moduleSources = modules
11659 .filter(module => !module.excludeFromSourcemap)
11660 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
11661 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
11662 // correct SourceMapSegment tuples. Cast it here to gain type safety.
11663 let source = new Link(map, moduleSources);
11664 source = bundleSourcemapChain.reduce(linkMap, source);
11665 let { sources, sourcesContent, names, mappings } = source.traceMappings();
11666 if (file) {
11667 const directory = path.dirname(file);
11668 sources = sources.map((source) => path.relative(directory, source));
11669 file = path.basename(file);
11670 }
11671 sourcesContent = (excludeContent ? null : sourcesContent);
11672 return new SourceMap({ file, mappings, names, sources, sourcesContent });
11673}
11674function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
11675 if (!sourcemapChain.length) {
11676 return originalSourcemap;
11677 }
11678 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
11679 const map = source.traceMappings();
11680 return { version: 3, ...map };
11681}
11682
11683const createHash = () => crypto.createHash('sha256');
11684
11685const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
11686 amd: deconflictImportsOther,
11687 cjs: deconflictImportsOther,
11688 es: deconflictImportsEsmOrSystem,
11689 iife: deconflictImportsOther,
11690 system: deconflictImportsEsmOrSystem,
11691 umd: deconflictImportsOther
11692};
11693function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
11694 const reversedModules = modules.slice().reverse();
11695 for (const module of reversedModules) {
11696 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
11697 }
11698 deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
11699 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
11700 for (const module of reversedModules) {
11701 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
11702 }
11703}
11704function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
11705 // This is needed for namespace reexports
11706 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
11707 if (preserveModules || dependency instanceof ExternalModule) {
11708 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
11709 }
11710 }
11711 for (const variable of imports) {
11712 const module = variable.module;
11713 const name = variable.name;
11714 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
11715 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
11716 }
11717 else if (module instanceof ExternalModule && name === 'default') {
11718 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
11719 ? module.suggestedVariableName + '__default'
11720 : module.suggestedVariableName, usedNames));
11721 }
11722 else {
11723 variable.setRenderNames(null, getSafeName(name, usedNames));
11724 }
11725 }
11726 for (const variable of syntheticExports) {
11727 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
11728 }
11729}
11730function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
11731 for (const chunkOrExternalModule of dependencies) {
11732 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
11733 }
11734 for (const externalModuleOrChunk of deconflictedNamespace) {
11735 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
11736 }
11737 for (const externalModule of deconflictedDefault) {
11738 if (deconflictedNamespace.has(externalModule) &&
11739 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
11740 externalModule.defaultVariableName = externalModule.namespaceVariableName;
11741 }
11742 else {
11743 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
11744 }
11745 }
11746 for (const variable of imports) {
11747 const module = variable.module;
11748 if (module instanceof ExternalModule) {
11749 const name = variable.name;
11750 if (name === 'default') {
11751 const moduleInterop = String(interop(module.id));
11752 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
11753 ? module.defaultVariableName
11754 : module.variableName;
11755 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
11756 variable.setRenderNames(variableName, 'default');
11757 }
11758 else {
11759 variable.setRenderNames(null, variableName);
11760 }
11761 }
11762 else if (name === '*') {
11763 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
11764 ? module.namespaceVariableName
11765 : module.variableName);
11766 }
11767 else {
11768 // if the second parameter is `null`, it uses its "name" for the property name
11769 variable.setRenderNames(module.variableName, null);
11770 }
11771 }
11772 else {
11773 const chunk = chunkByModule.get(module);
11774 if (preserveModules && variable.isNamespace) {
11775 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
11776 }
11777 else if (chunk.exportMode === 'default') {
11778 variable.setRenderNames(null, chunk.variableName);
11779 }
11780 else {
11781 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
11782 }
11783 }
11784 }
11785}
11786function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
11787 for (const module of modules) {
11788 for (const variable of module.scope.variables.values()) {
11789 if (variable.included &&
11790 // this will only happen for exports in some formats
11791 !(variable.renderBaseName ||
11792 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
11793 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
11794 }
11795 }
11796 if (includedNamespaces.has(module)) {
11797 const namespace = module.namespace;
11798 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
11799 }
11800 }
11801}
11802
11803const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
11804const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
11805const backSlashRegEx = /\\/g;
11806function escapeId(id) {
11807 if (!id.match(needsEscapeRegEx))
11808 return id;
11809 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
11810}
11811
11812function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
11813 let nameIndex = 0;
11814 for (const variable of exports) {
11815 let exportName = variable.name[0];
11816 if (exportsByName[exportName]) {
11817 do {
11818 exportName = toBase64(++nameIndex);
11819 // skip past leading number identifiers
11820 if (exportName.charCodeAt(0) === 49 /* '1' */) {
11821 nameIndex += 9 * 64 ** (exportName.length - 1);
11822 exportName = toBase64(nameIndex);
11823 }
11824 } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
11825 }
11826 exportsByName[exportName] = variable;
11827 exportNamesByVariable.set(variable, [exportName]);
11828 }
11829}
11830function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
11831 for (const variable of exports) {
11832 let nameIndex = 0;
11833 let exportName = variable.name;
11834 while (exportsByName[exportName]) {
11835 exportName = variable.name + '$' + ++nameIndex;
11836 }
11837 exportsByName[exportName] = variable;
11838 exportNamesByVariable.set(variable, [exportName]);
11839 }
11840}
11841
11842function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
11843 const exportKeys = chunk.getExportNames();
11844 if (exportMode === 'default') {
11845 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
11846 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
11847 }
11848 }
11849 else if (exportMode === 'none' && exportKeys.length) {
11850 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
11851 }
11852 if (exportMode === 'auto') {
11853 if (exportKeys.length === 0) {
11854 exportMode = 'none';
11855 }
11856 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
11857 if (format === 'cjs' && unsetOptions.has('exports')) {
11858 warn(errPreferNamedExports(facadeModuleId));
11859 }
11860 exportMode = 'default';
11861 }
11862 else {
11863 if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
11864 warn(errMixedExport(facadeModuleId, name));
11865 }
11866 exportMode = 'named';
11867 }
11868 }
11869 return exportMode;
11870}
11871
11872function guessIndentString(code) {
11873 const lines = code.split('\n');
11874 const tabbed = lines.filter(line => /^\t+/.test(line));
11875 const spaced = lines.filter(line => /^ {2,}/.test(line));
11876 if (tabbed.length === 0 && spaced.length === 0) {
11877 return null;
11878 }
11879 // More lines tabbed than spaced? Assume tabs, and
11880 // default to tabs in the case of a tie (or nothing
11881 // to go on)
11882 if (tabbed.length >= spaced.length) {
11883 return '\t';
11884 }
11885 // Otherwise, we need to guess the multiple
11886 const min = spaced.reduce((previous, current) => {
11887 const numSpaces = /^ +/.exec(current)[0].length;
11888 return Math.min(numSpaces, previous);
11889 }, Infinity);
11890 return new Array(min + 1).join(' ');
11891}
11892function getIndentString(modules, options) {
11893 if (options.indent !== true)
11894 return options.indent;
11895 for (let i = 0; i < modules.length; i++) {
11896 const indent = guessIndentString(modules[i].originalCode);
11897 if (indent !== null)
11898 return indent;
11899 }
11900 return '\t';
11901}
11902
11903function getStaticDependencies(chunk, orderedModules, chunkByModule) {
11904 const staticDependencyBlocks = [];
11905 const handledDependencies = new Set();
11906 for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
11907 const module = orderedModules[modulePos];
11908 if (!handledDependencies.has(module)) {
11909 const staticDependencies = [];
11910 addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
11911 staticDependencyBlocks.unshift(staticDependencies);
11912 }
11913 }
11914 const dependencies = new Set();
11915 for (const block of staticDependencyBlocks) {
11916 for (const dependency of block) {
11917 dependencies.add(dependency);
11918 }
11919 }
11920 return dependencies;
11921}
11922function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
11923 const dependencies = module.getDependenciesToBeIncluded();
11924 for (const dependency of dependencies) {
11925 if (dependency instanceof ExternalModule) {
11926 staticDependencies.push(dependency);
11927 continue;
11928 }
11929 const dependencyChunk = chunkByModule.get(dependency);
11930 if (dependencyChunk !== chunk) {
11931 staticDependencies.push(dependencyChunk);
11932 continue;
11933 }
11934 if (!handledModules.has(dependency)) {
11935 handledModules.add(dependency);
11936 addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
11937 }
11938 }
11939}
11940
11941function decodedSourcemap(map) {
11942 if (!map)
11943 return null;
11944 if (typeof map === 'string') {
11945 map = JSON.parse(map);
11946 }
11947 if (map.mappings === '') {
11948 return {
11949 mappings: [],
11950 names: [],
11951 sources: [],
11952 version: 3
11953 };
11954 }
11955 let mappings;
11956 if (typeof map.mappings === 'string') {
11957 mappings = decode(map.mappings);
11958 }
11959 else {
11960 mappings = map.mappings;
11961 }
11962 return { ...map, mappings };
11963}
11964
11965function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
11966 const renderChunkReducer = (code, result, plugin) => {
11967 if (result == null)
11968 return code;
11969 if (typeof result === 'string')
11970 result = {
11971 code: result,
11972 map: undefined
11973 };
11974 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
11975 if (result.map !== null) {
11976 const map = decodedSourcemap(result.map);
11977 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
11978 }
11979 return result.code;
11980 };
11981 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
11982}
11983
11984function renderNamePattern(pattern, patternName, replacements) {
11985 if (isPathFragment(pattern))
11986 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
11987 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
11988 if (!replacements.hasOwnProperty(type)) {
11989 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
11990 }
11991 const replacement = replacements[type]();
11992 if (isPathFragment(replacement))
11993 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
11994 return replacement;
11995 });
11996}
11997function makeUnique(name, existingNames) {
11998 const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
11999 if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
12000 return name;
12001 const ext = path.extname(name);
12002 name = name.substr(0, name.length - ext.length);
12003 let uniqueName, uniqueIndex = 1;
12004 while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
12005 ;
12006 return uniqueName;
12007}
12008
12009const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
12010function getGlobalName(module, globals, hasExports, warn) {
12011 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
12012 if (globalName) {
12013 return globalName;
12014 }
12015 if (hasExports) {
12016 warn({
12017 code: 'MISSING_GLOBAL_NAME',
12018 guess: module.variableName,
12019 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
12020 source: module.id
12021 });
12022 return module.variableName;
12023 }
12024}
12025class Chunk {
12026 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
12027 this.orderedModules = orderedModules;
12028 this.inputOptions = inputOptions;
12029 this.outputOptions = outputOptions;
12030 this.unsetOptions = unsetOptions;
12031 this.pluginDriver = pluginDriver;
12032 this.modulesById = modulesById;
12033 this.chunkByModule = chunkByModule;
12034 this.facadeChunkByModule = facadeChunkByModule;
12035 this.includedNamespaces = includedNamespaces;
12036 this.manualChunkAlias = manualChunkAlias;
12037 this.entryModules = [];
12038 this.exportMode = 'named';
12039 this.facadeModule = null;
12040 this.id = null;
12041 this.namespaceVariableName = '';
12042 this.variableName = '';
12043 this.accessedGlobalsByScope = new Map();
12044 this.dependencies = new Set();
12045 this.dynamicDependencies = new Set();
12046 this.dynamicEntryModules = [];
12047 this.dynamicName = null;
12048 this.exportNamesByVariable = new Map();
12049 this.exports = new Set();
12050 this.exportsByName = Object.create(null);
12051 this.fileName = null;
12052 this.implicitEntryModules = [];
12053 this.implicitlyLoadedBefore = new Set();
12054 this.imports = new Set();
12055 this.indentString = undefined;
12056 this.isEmpty = true;
12057 this.name = null;
12058 this.needsExportsShim = false;
12059 this.renderedDependencies = null;
12060 this.renderedExports = null;
12061 this.renderedHash = undefined;
12062 this.renderedModuleSources = new Map();
12063 this.renderedModules = Object.create(null);
12064 this.renderedSource = null;
12065 this.sortedExportNames = null;
12066 this.strictFacade = false;
12067 this.usedModules = undefined;
12068 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
12069 const chunkModules = new Set(orderedModules);
12070 for (const module of orderedModules) {
12071 if (module.namespace.included) {
12072 includedNamespaces.add(module);
12073 }
12074 if (this.isEmpty && module.isIncluded()) {
12075 this.isEmpty = false;
12076 }
12077 if (module.info.isEntry || outputOptions.preserveModules) {
12078 this.entryModules.push(module);
12079 }
12080 for (const importer of module.includedDynamicImporters) {
12081 if (!chunkModules.has(importer)) {
12082 this.dynamicEntryModules.push(module);
12083 // Modules with synthetic exports need an artificial namespace for dynamic imports
12084 if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
12085 includedNamespaces.add(module);
12086 this.exports.add(module.namespace);
12087 }
12088 }
12089 }
12090 if (module.implicitlyLoadedAfter.size > 0) {
12091 this.implicitEntryModules.push(module);
12092 }
12093 }
12094 this.suggestedVariableName = makeLegal(this.generateVariableName());
12095 }
12096 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
12097 const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
12098 chunk.assignFacadeName(facadeName, facadedModule);
12099 if (!facadeChunkByModule.has(facadedModule)) {
12100 facadeChunkByModule.set(facadedModule, chunk);
12101 }
12102 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
12103 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
12104 }
12105 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
12106 facadedModule.info.hasModuleSideEffects &&
12107 facadedModule.hasEffects()) {
12108 chunk.dependencies.add(chunkByModule.get(facadedModule));
12109 }
12110 chunk.ensureReexportsAreAvailableForModule(facadedModule);
12111 chunk.facadeModule = facadedModule;
12112 chunk.strictFacade = true;
12113 return chunk;
12114 }
12115 canModuleBeFacade(module, exposedVariables) {
12116 const moduleExportNamesByVariable = module.getExportNamesByVariable();
12117 for (const exposedVariable of this.exports) {
12118 if (!moduleExportNamesByVariable.has(exposedVariable)) {
12119 if (moduleExportNamesByVariable.size === 0 &&
12120 module.isUserDefinedEntryPoint &&
12121 module.preserveSignature === 'strict' &&
12122 this.unsetOptions.has('preserveEntrySignatures')) {
12123 this.inputOptions.onwarn({
12124 code: 'EMPTY_FACADE',
12125 id: module.id,
12126 message: `To preserve the export signature of the entry module "${relativeId(module.id)}", an empty facade chunk was created. This often happens when creating a bundle for a web app where chunks are placed in script tags and exports are ignored. In this case it is recommended to set "preserveEntrySignatures: false" to avoid this and reduce the number of chunks. Otherwise if this is intentional, set "preserveEntrySignatures: 'strict'" explicitly to silence this warning.`,
12127 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
12128 });
12129 }
12130 return false;
12131 }
12132 }
12133 for (const exposedVariable of exposedVariables) {
12134 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
12135 return false;
12136 }
12137 }
12138 return true;
12139 }
12140 generateExports() {
12141 this.sortedExportNames = null;
12142 const remainingExports = new Set(this.exports);
12143 if (this.facadeModule !== null &&
12144 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
12145 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
12146 for (const [variable, exportNames] of exportNamesByVariable) {
12147 this.exportNamesByVariable.set(variable, [...exportNames]);
12148 for (const exportName of exportNames) {
12149 this.exportsByName[exportName] = variable;
12150 }
12151 remainingExports.delete(variable);
12152 }
12153 }
12154 if (this.outputOptions.minifyInternalExports) {
12155 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
12156 }
12157 else {
12158 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
12159 }
12160 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
12161 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
12162 }
12163 generateFacades() {
12164 var _a;
12165 const facades = [];
12166 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
12167 const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
12168 for (const module of entryModules) {
12169 if (module.preserveSignature) {
12170 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
12171 exposedVariables.add(exportedVariable);
12172 }
12173 }
12174 }
12175 for (const module of entryModules) {
12176 const requiredFacades = Array.from(module.userChunkNames, name => ({
12177 name
12178 }));
12179 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
12180 requiredFacades.push({});
12181 }
12182 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
12183 if (requiredFacades.length === 0) {
12184 requiredFacades.push({});
12185 }
12186 if (!this.facadeModule) {
12187 const needsStrictFacade = module.preserveSignature === 'strict' ||
12188 (module.preserveSignature === 'exports-only' &&
12189 module.getExportNamesByVariable().size !== 0);
12190 if (!needsStrictFacade ||
12191 this.outputOptions.preserveModules ||
12192 this.canModuleBeFacade(module, exposedVariables)) {
12193 this.facadeModule = module;
12194 this.facadeChunkByModule.set(module, this);
12195 if (module.preserveSignature) {
12196 this.strictFacade = needsStrictFacade;
12197 }
12198 this.assignFacadeName(requiredFacades.shift(), module);
12199 }
12200 }
12201 for (const facadeName of requiredFacades) {
12202 facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
12203 }
12204 }
12205 for (const module of this.dynamicEntryModules) {
12206 if (module.info.syntheticNamedExports)
12207 continue;
12208 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
12209 this.facadeModule = module;
12210 this.facadeChunkByModule.set(module, this);
12211 this.strictFacade = true;
12212 this.dynamicName = getChunkNameFromModule(module);
12213 }
12214 else if (this.facadeModule === module &&
12215 !this.strictFacade &&
12216 this.canModuleBeFacade(module, exposedVariables)) {
12217 this.strictFacade = true;
12218 }
12219 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
12220 this.includedNamespaces.add(module);
12221 this.exports.add(module.namespace);
12222 }
12223 }
12224 return facades;
12225 }
12226 generateId(addons, options, existingNames, includeHash) {
12227 if (this.fileName !== null) {
12228 return this.fileName;
12229 }
12230 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
12231 ? [options.entryFileNames, 'output.entryFileNames']
12232 : [options.chunkFileNames, 'output.chunkFileNames'];
12233 return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
12234 format: () => options.format,
12235 hash: () => includeHash
12236 ? this.computeContentHashWithDependencies(addons, options, existingNames)
12237 : '[hash]',
12238 name: () => this.getChunkName()
12239 }), existingNames);
12240 }
12241 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
12242 const id = this.orderedModules[0].id;
12243 const sanitizedId = this.outputOptions.sanitizeFileName(id);
12244 let path$1;
12245 if (isAbsolute(id)) {
12246 const extension = path.extname(id);
12247 const pattern = unsetOptions.has('entryFileNames')
12248 ? '[name][assetExtname].js'
12249 : options.entryFileNames;
12250 const currentDir = path.dirname(sanitizedId);
12251 const fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, 'output.entryFileNames', {
12252 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
12253 ext: () => extension.substr(1),
12254 extname: () => extension,
12255 format: () => options.format,
12256 name: () => this.getChunkName()
12257 });
12258 const currentPath = `${currentDir}/${fileName}`;
12259 const { preserveModulesRoot } = options;
12260 if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
12261 path$1 = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
12262 }
12263 else {
12264 path$1 = relative(preserveModulesRelativeDir, currentPath);
12265 }
12266 }
12267 else {
12268 path$1 = `_virtual/${path.basename(sanitizedId)}`;
12269 }
12270 return makeUnique(normalize(path$1), existingNames);
12271 }
12272 getChunkInfo() {
12273 const facadeModule = this.facadeModule;
12274 const getChunkName = this.getChunkName.bind(this);
12275 return {
12276 exports: this.getExportNames(),
12277 facadeModuleId: facadeModule && facadeModule.id,
12278 isDynamicEntry: this.dynamicEntryModules.length > 0,
12279 isEntry: facadeModule !== null && facadeModule.info.isEntry,
12280 isImplicitEntry: this.implicitEntryModules.length > 0,
12281 modules: this.renderedModules,
12282 get name() {
12283 return getChunkName();
12284 },
12285 type: 'chunk'
12286 };
12287 }
12288 getChunkInfoWithFileNames() {
12289 return Object.assign(this.getChunkInfo(), {
12290 code: undefined,
12291 dynamicImports: Array.from(this.dynamicDependencies, getId),
12292 fileName: this.id,
12293 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
12294 importedBindings: this.getImportedBindingsPerDependency(),
12295 imports: Array.from(this.dependencies, getId),
12296 map: undefined,
12297 referencedFiles: this.getReferencedFiles()
12298 });
12299 }
12300 getChunkName() {
12301 return (this.name || (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
12302 }
12303 getExportNames() {
12304 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
12305 }
12306 getRenderedHash() {
12307 if (this.renderedHash)
12308 return this.renderedHash;
12309 const hash = createHash();
12310 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
12311 if (pluginHash) {
12312 augmentation += pluginHash;
12313 }
12314 return augmentation;
12315 });
12316 hash.update(hashAugmentation);
12317 hash.update(this.renderedSource.toString());
12318 hash.update(this.getExportNames()
12319 .map(exportName => {
12320 const variable = this.exportsByName[exportName];
12321 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
12322 })
12323 .join(','));
12324 return (this.renderedHash = hash.digest('hex'));
12325 }
12326 getVariableExportName(variable) {
12327 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
12328 return '*';
12329 }
12330 return this.exportNamesByVariable.get(variable)[0];
12331 }
12332 link() {
12333 this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
12334 for (const module of this.orderedModules) {
12335 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
12336 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
12337 this.setUpChunkImportsAndExportsForModule(module);
12338 }
12339 }
12340 // prerender allows chunk hashes and names to be generated before finalizing
12341 preRender(options, inputBase) {
12342 const magicString = new Bundle$1({ separator: options.compact ? '' : '\n\n' });
12343 this.usedModules = [];
12344 this.indentString = getIndentString(this.orderedModules, options);
12345 const n = options.compact ? '' : '\n';
12346 const _ = options.compact ? '' : ' ';
12347 const renderOptions = {
12348 compact: options.compact,
12349 dynamicImportFunction: options.dynamicImportFunction,
12350 exportNamesByVariable: this.exportNamesByVariable,
12351 format: options.format,
12352 freeze: options.freeze,
12353 indent: this.indentString,
12354 namespaceToStringTag: options.namespaceToStringTag,
12355 outputPluginDriver: this.pluginDriver,
12356 varOrConst: options.preferConst ? 'const' : 'var'
12357 };
12358 // for static and dynamic entry points, inline the execution list to avoid loading latency
12359 if (options.hoistTransitiveImports &&
12360 !this.outputOptions.preserveModules &&
12361 this.facadeModule !== null) {
12362 for (const dep of this.dependencies) {
12363 if (dep instanceof Chunk)
12364 this.inlineChunkDependencies(dep);
12365 }
12366 }
12367 this.prepareDynamicImportsAndImportMetas();
12368 this.setIdentifierRenderResolutions(options);
12369 let hoistedSource = '';
12370 const renderedModules = this.renderedModules;
12371 for (const module of this.orderedModules) {
12372 let renderedLength = 0;
12373 if (module.isIncluded() || this.includedNamespaces.has(module)) {
12374 const source = module.render(renderOptions).trim();
12375 renderedLength = source.length();
12376 if (renderedLength) {
12377 if (options.compact && source.lastLine().indexOf('//') !== -1)
12378 source.append('\n');
12379 this.renderedModuleSources.set(module, source);
12380 magicString.addSource(source);
12381 this.usedModules.push(module);
12382 }
12383 const namespace = module.namespace;
12384 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
12385 const rendered = namespace.renderBlock(renderOptions);
12386 if (namespace.renderFirst())
12387 hoistedSource += n + rendered;
12388 else
12389 magicString.addSource(new MagicString$1(rendered));
12390 }
12391 }
12392 const { renderedExports, removedExports } = module.getRenderedExports();
12393 const { renderedModuleSources } = this;
12394 renderedModules[module.id] = {
12395 get code() {
12396 var _a, _b;
12397 return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
12398 },
12399 originalLength: module.originalCode.length,
12400 removedExports,
12401 renderedExports,
12402 renderedLength
12403 };
12404 }
12405 if (hoistedSource)
12406 magicString.prepend(hoistedSource + n + n);
12407 if (this.needsExportsShim) {
12408 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
12409 }
12410 if (options.compact) {
12411 this.renderedSource = magicString;
12412 }
12413 else {
12414 this.renderedSource = magicString.trim();
12415 }
12416 this.renderedHash = undefined;
12417 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
12418 const chunkName = this.getChunkName();
12419 this.inputOptions.onwarn({
12420 chunkName,
12421 code: 'EMPTY_BUNDLE',
12422 message: `Generated an empty chunk: "${chunkName}"`
12423 });
12424 }
12425 this.setExternalRenderPaths(options, inputBase);
12426 this.renderedDependencies = this.getChunkDependencyDeclarations(options);
12427 this.renderedExports =
12428 this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
12429 }
12430 async render(options, addons, outputChunk) {
12431 timeStart('render format', 2);
12432 const format = options.format;
12433 const finalise = finalisers[format];
12434 if (options.dynamicImportFunction && format !== 'es') {
12435 this.inputOptions.onwarn({
12436 code: 'INVALID_OPTION',
12437 message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
12438 });
12439 }
12440 // populate ids in the rendered declarations only here
12441 // as chunk ids known only after prerender
12442 for (const dependency of this.dependencies) {
12443 const renderedDependency = this.renderedDependencies.get(dependency);
12444 if (dependency instanceof ExternalModule) {
12445 const originalId = dependency.renderPath;
12446 renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
12447 }
12448 else {
12449 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
12450 renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
12451 }
12452 }
12453 this.finaliseDynamicImports(options);
12454 this.finaliseImportMetas(format);
12455 const hasExports = this.renderedExports.length !== 0 ||
12456 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
12457 let usesTopLevelAwait = false;
12458 const accessedGlobals = new Set();
12459 for (const module of this.orderedModules) {
12460 if (module.usesTopLevelAwait) {
12461 usesTopLevelAwait = true;
12462 }
12463 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
12464 if (accessedGlobalVariables) {
12465 for (const name of accessedGlobalVariables) {
12466 accessedGlobals.add(name);
12467 }
12468 }
12469 }
12470 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
12471 return error({
12472 code: 'INVALID_TLA_FORMAT',
12473 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
12474 });
12475 }
12476 /* istanbul ignore next */
12477 if (!this.id) {
12478 throw new Error('Internal Error: expecting chunk id');
12479 }
12480 const magicString = finalise(this.renderedSource, {
12481 accessedGlobals,
12482 dependencies: [...this.renderedDependencies.values()],
12483 exports: this.renderedExports,
12484 hasExports,
12485 id: this.id,
12486 indentString: this.indentString,
12487 intro: addons.intro,
12488 isEntryFacade: this.outputOptions.preserveModules ||
12489 (this.facadeModule !== null && this.facadeModule.info.isEntry),
12490 isModuleFacade: this.facadeModule !== null,
12491 namedExportsMode: this.exportMode !== 'default',
12492 outro: addons.outro,
12493 usesTopLevelAwait,
12494 varOrConst: options.preferConst ? 'const' : 'var',
12495 warn: this.inputOptions.onwarn
12496 }, options);
12497 if (addons.banner)
12498 magicString.prepend(addons.banner);
12499 if (addons.footer)
12500 magicString.append(addons.footer);
12501 const prevCode = magicString.toString();
12502 timeEnd('render format', 2);
12503 let map = null;
12504 const chunkSourcemapChain = [];
12505 let code = await renderChunk({
12506 code: prevCode,
12507 options,
12508 outputPluginDriver: this.pluginDriver,
12509 renderChunk: outputChunk,
12510 sourcemapChain: chunkSourcemapChain
12511 });
12512 if (options.sourcemap) {
12513 timeStart('sourcemap', 2);
12514 let file;
12515 if (options.file)
12516 file = path.resolve(options.sourcemapFile || options.file);
12517 else if (options.dir)
12518 file = path.resolve(options.dir, this.id);
12519 else
12520 file = path.resolve(this.id);
12521 const decodedMap = magicString.generateDecodedMap({});
12522 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
12523 map.sources = map.sources
12524 .map(sourcePath => {
12525 const { sourcemapPathTransform } = options;
12526 if (sourcemapPathTransform) {
12527 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
12528 if (typeof newSourcePath !== 'string') {
12529 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
12530 }
12531 return newSourcePath;
12532 }
12533 return sourcePath;
12534 })
12535 .map(normalize);
12536 timeEnd('sourcemap', 2);
12537 }
12538 if (!options.compact && code[code.length - 1] !== '\n')
12539 code += '\n';
12540 return { code, map };
12541 }
12542 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
12543 for (const module of moduleDependencies) {
12544 if (module instanceof Module) {
12545 const chunk = this.chunkByModule.get(module);
12546 if (chunk && chunk !== this) {
12547 chunkDependencies.add(chunk);
12548 }
12549 }
12550 else {
12551 chunkDependencies.add(module);
12552 }
12553 }
12554 }
12555 assignFacadeName({ fileName, name }, facadedModule) {
12556 if (fileName) {
12557 this.fileName = fileName;
12558 }
12559 else {
12560 this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
12561 }
12562 }
12563 checkCircularDependencyImport(variable, importingModule) {
12564 const variableModule = variable.module;
12565 if (variableModule instanceof Module) {
12566 const exportChunk = this.chunkByModule.get(variableModule);
12567 let alternativeReexportModule;
12568 do {
12569 alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
12570 if (alternativeReexportModule) {
12571 const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
12572 if (exportingChunk && exportingChunk !== exportChunk) {
12573 this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
12574 }
12575 importingModule = alternativeReexportModule;
12576 }
12577 } while (alternativeReexportModule);
12578 }
12579 }
12580 computeContentHashWithDependencies(addons, options, existingNames) {
12581 const hash = createHash();
12582 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
12583 hash.update(options.format);
12584 const dependenciesForHashing = new Set([this]);
12585 for (const current of dependenciesForHashing) {
12586 if (current instanceof ExternalModule) {
12587 hash.update(':' + current.renderPath);
12588 }
12589 else {
12590 hash.update(current.getRenderedHash());
12591 hash.update(current.generateId(addons, options, existingNames, false));
12592 }
12593 if (current instanceof ExternalModule)
12594 continue;
12595 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
12596 dependenciesForHashing.add(dependency);
12597 }
12598 }
12599 return hash.digest('hex').substr(0, 8);
12600 }
12601 ensureReexportsAreAvailableForModule(module) {
12602 const map = module.getExportNamesByVariable();
12603 for (const exportedVariable of map.keys()) {
12604 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
12605 const importedVariable = isSynthetic
12606 ? exportedVariable.getBaseVariable()
12607 : exportedVariable;
12608 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
12609 this.checkCircularDependencyImport(importedVariable, module);
12610 const exportingModule = importedVariable.module;
12611 if (exportingModule instanceof Module) {
12612 const chunk = this.chunkByModule.get(exportingModule);
12613 if (chunk && chunk !== this) {
12614 chunk.exports.add(importedVariable);
12615 if (isSynthetic) {
12616 this.imports.add(importedVariable);
12617 }
12618 }
12619 }
12620 }
12621 }
12622 }
12623 finaliseDynamicImports(options) {
12624 const stripKnownJsExtensions = options.format === 'amd';
12625 for (const [module, code] of this.renderedModuleSources) {
12626 for (const { node, resolution } of module.dynamicImports) {
12627 const chunk = this.chunkByModule.get(resolution);
12628 const facadeChunk = this.facadeChunkByModule.get(resolution);
12629 if (!resolution || !node.included || chunk === this) {
12630 continue;
12631 }
12632 const renderedResolution = resolution instanceof Module
12633 ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
12634 : resolution instanceof ExternalModule
12635 ? `'${resolution.renormalizeRenderPath
12636 ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
12637 : resolution.renderPath}'`
12638 : resolution;
12639 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
12640 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
12641 chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
12642 }
12643 }
12644 }
12645 finaliseImportMetas(format) {
12646 for (const [module, code] of this.renderedModuleSources) {
12647 for (const importMeta of module.importMetas) {
12648 importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
12649 }
12650 }
12651 }
12652 generateVariableName() {
12653 if (this.manualChunkAlias) {
12654 return this.manualChunkAlias;
12655 }
12656 const moduleForNaming = this.entryModules[0] ||
12657 this.implicitEntryModules[0] ||
12658 this.dynamicEntryModules[0] ||
12659 this.orderedModules[this.orderedModules.length - 1];
12660 if (moduleForNaming) {
12661 return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
12662 }
12663 return 'chunk';
12664 }
12665 getChunkDependencyDeclarations(options) {
12666 const importSpecifiers = this.getImportSpecifiers();
12667 const reexportSpecifiers = this.getReexportSpecifiers();
12668 const dependencyDeclaration = new Map();
12669 for (const dep of this.dependencies) {
12670 const imports = importSpecifiers.get(dep) || null;
12671 const reexports = reexportSpecifiers.get(dep) || null;
12672 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
12673 dependencyDeclaration.set(dep, {
12674 defaultVariableName: dep.defaultVariableName,
12675 globalName: (dep instanceof ExternalModule &&
12676 (options.format === 'umd' || options.format === 'iife') &&
12677 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
12678 id: undefined,
12679 imports,
12680 isChunk: dep instanceof Chunk,
12681 name: dep.variableName,
12682 namedExportsMode,
12683 namespaceVariableName: dep.namespaceVariableName,
12684 reexports
12685 });
12686 }
12687 return dependencyDeclaration;
12688 }
12689 getChunkExportDeclarations(format) {
12690 const exports = [];
12691 for (const exportName of this.getExportNames()) {
12692 if (exportName[0] === '*')
12693 continue;
12694 const variable = this.exportsByName[exportName];
12695 if (!(variable instanceof SyntheticNamedExportVariable)) {
12696 const module = variable.module;
12697 if (module && this.chunkByModule.get(module) !== this)
12698 continue;
12699 }
12700 let expression = null;
12701 let hoisted = false;
12702 let uninitialized = false;
12703 let local = variable.getName();
12704 if (variable instanceof LocalVariable) {
12705 if (variable.init === UNDEFINED_EXPRESSION) {
12706 uninitialized = true;
12707 }
12708 for (const declaration of variable.declarations) {
12709 if (declaration.parent instanceof FunctionDeclaration ||
12710 (declaration instanceof ExportDefaultDeclaration &&
12711 declaration.declaration instanceof FunctionDeclaration)) {
12712 hoisted = true;
12713 break;
12714 }
12715 }
12716 }
12717 else if (variable instanceof SyntheticNamedExportVariable) {
12718 expression = local;
12719 if (format === 'es') {
12720 local = variable.renderName;
12721 }
12722 }
12723 exports.push({
12724 exported: exportName,
12725 expression,
12726 hoisted,
12727 local,
12728 uninitialized
12729 });
12730 }
12731 return exports;
12732 }
12733 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
12734 const dependencies = new Set();
12735 const deconflictedDefault = new Set();
12736 const deconflictedNamespace = new Set();
12737 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
12738 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
12739 const module = variable.module;
12740 if (module instanceof ExternalModule) {
12741 dependencies.add(module);
12742 if (addNonNamespacesAndInteropHelpers) {
12743 if (variable.name === 'default') {
12744 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
12745 deconflictedDefault.add(module);
12746 }
12747 }
12748 else if (variable.name === '*') {
12749 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
12750 deconflictedNamespace.add(module);
12751 }
12752 }
12753 }
12754 }
12755 else {
12756 const chunk = this.chunkByModule.get(module);
12757 if (chunk !== this) {
12758 dependencies.add(chunk);
12759 if (addNonNamespacesAndInteropHelpers &&
12760 chunk.exportMode === 'default' &&
12761 variable.isNamespace) {
12762 deconflictedNamespace.add(chunk);
12763 }
12764 }
12765 }
12766 }
12767 }
12768 if (addDependenciesWithoutBindings) {
12769 for (const dependency of this.dependencies) {
12770 dependencies.add(dependency);
12771 }
12772 }
12773 return { deconflictedDefault, deconflictedNamespace, dependencies };
12774 }
12775 getFallbackChunkName() {
12776 if (this.manualChunkAlias) {
12777 return this.manualChunkAlias;
12778 }
12779 if (this.dynamicName) {
12780 return this.dynamicName;
12781 }
12782 if (this.fileName) {
12783 return getAliasName(this.fileName);
12784 }
12785 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
12786 }
12787 getImportSpecifiers() {
12788 const { interop } = this.outputOptions;
12789 const importsByDependency = new Map();
12790 for (const variable of this.imports) {
12791 const module = variable.module;
12792 let dependency;
12793 let imported;
12794 if (module instanceof ExternalModule) {
12795 dependency = module;
12796 imported = variable.name;
12797 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
12798 return error(errUnexpectedNamedImport(module.id, imported, false));
12799 }
12800 }
12801 else {
12802 dependency = this.chunkByModule.get(module);
12803 imported = dependency.getVariableExportName(variable);
12804 }
12805 getOrCreate(importsByDependency, dependency, () => []).push({
12806 imported,
12807 local: variable.getName()
12808 });
12809 }
12810 return importsByDependency;
12811 }
12812 getImportedBindingsPerDependency() {
12813 const importSpecifiers = {};
12814 for (const [dependency, declaration] of this.renderedDependencies) {
12815 const specifiers = new Set();
12816 if (declaration.imports) {
12817 for (const { imported } of declaration.imports) {
12818 specifiers.add(imported);
12819 }
12820 }
12821 if (declaration.reexports) {
12822 for (const { imported } of declaration.reexports) {
12823 specifiers.add(imported);
12824 }
12825 }
12826 importSpecifiers[dependency.id] = [...specifiers];
12827 }
12828 return importSpecifiers;
12829 }
12830 getReexportSpecifiers() {
12831 const { externalLiveBindings, interop } = this.outputOptions;
12832 const reexportSpecifiers = new Map();
12833 for (let exportName of this.getExportNames()) {
12834 let dependency;
12835 let imported;
12836 let needsLiveBinding = false;
12837 if (exportName[0] === '*') {
12838 const id = exportName.substr(1);
12839 if (interop(id) === 'defaultOnly') {
12840 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
12841 }
12842 needsLiveBinding = externalLiveBindings;
12843 dependency = this.modulesById.get(id);
12844 imported = exportName = '*';
12845 }
12846 else {
12847 const variable = this.exportsByName[exportName];
12848 if (variable instanceof SyntheticNamedExportVariable)
12849 continue;
12850 const module = variable.module;
12851 if (module instanceof Module) {
12852 dependency = this.chunkByModule.get(module);
12853 if (dependency === this)
12854 continue;
12855 imported = dependency.getVariableExportName(variable);
12856 needsLiveBinding = variable.isReassigned;
12857 }
12858 else {
12859 dependency = module;
12860 imported = variable.name;
12861 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
12862 return error(errUnexpectedNamedImport(module.id, imported, true));
12863 }
12864 needsLiveBinding =
12865 externalLiveBindings &&
12866 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
12867 }
12868 }
12869 getOrCreate(reexportSpecifiers, dependency, () => []).push({
12870 imported,
12871 needsLiveBinding,
12872 reexported: exportName
12873 });
12874 }
12875 return reexportSpecifiers;
12876 }
12877 getReferencedFiles() {
12878 const referencedFiles = [];
12879 for (const module of this.orderedModules) {
12880 for (const meta of module.importMetas) {
12881 const fileName = meta.getReferencedFileName(this.pluginDriver);
12882 if (fileName) {
12883 referencedFiles.push(fileName);
12884 }
12885 }
12886 }
12887 return referencedFiles;
12888 }
12889 getRelativePath(targetPath, stripJsExtension) {
12890 let relativePath = normalize(relative(path.dirname(this.id), targetPath));
12891 if (stripJsExtension && relativePath.endsWith('.js')) {
12892 relativePath = relativePath.slice(0, -3);
12893 }
12894 if (relativePath === '..')
12895 return '../../' + path.basename(targetPath);
12896 if (relativePath === '')
12897 return '../' + path.basename(targetPath);
12898 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
12899 }
12900 inlineChunkDependencies(chunk) {
12901 for (const dep of chunk.dependencies) {
12902 if (this.dependencies.has(dep))
12903 continue;
12904 this.dependencies.add(dep);
12905 if (dep instanceof Chunk) {
12906 this.inlineChunkDependencies(dep);
12907 }
12908 }
12909 }
12910 prepareDynamicImportsAndImportMetas() {
12911 var _a;
12912 const accessedGlobalsByScope = this.accessedGlobalsByScope;
12913 for (const module of this.orderedModules) {
12914 for (const { node, resolution } of module.dynamicImports) {
12915 if (node.included) {
12916 if (resolution instanceof Module) {
12917 const chunk = this.chunkByModule.get(resolution);
12918 if (chunk === this) {
12919 node.setInternalResolution(resolution.namespace);
12920 }
12921 else {
12922 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
12923 }
12924 }
12925 else {
12926 node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
12927 }
12928 }
12929 }
12930 for (const importMeta of module.importMetas) {
12931 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
12932 }
12933 }
12934 }
12935 setExternalRenderPaths(options, inputBase) {
12936 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
12937 if (dependency instanceof ExternalModule) {
12938 dependency.setRenderPath(options, inputBase);
12939 }
12940 }
12941 }
12942 setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
12943 const syntheticExports = new Set();
12944 for (const exportName of this.getExportNames()) {
12945 const exportVariable = this.exportsByName[exportName];
12946 if (exportVariable instanceof ExportShimVariable) {
12947 this.needsExportsShim = true;
12948 }
12949 if (format !== 'es' &&
12950 format !== 'system' &&
12951 exportVariable.isReassigned &&
12952 !exportVariable.isId) {
12953 exportVariable.setRenderNames('exports', exportName);
12954 }
12955 else if (exportVariable instanceof SyntheticNamedExportVariable) {
12956 syntheticExports.add(exportVariable);
12957 }
12958 else {
12959 exportVariable.setRenderNames(null, null);
12960 }
12961 }
12962 const usedNames = new Set(['Object', 'Promise']);
12963 if (this.needsExportsShim) {
12964 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
12965 }
12966 if (namespaceToStringTag) {
12967 usedNames.add('Symbol');
12968 }
12969 switch (format) {
12970 case 'system':
12971 usedNames.add('module').add('exports');
12972 break;
12973 case 'es':
12974 break;
12975 case 'cjs':
12976 usedNames.add('module').add('require').add('__filename').add('__dirname');
12977 // fallthrough
12978 default:
12979 usedNames.add('exports');
12980 for (const helper of HELPER_NAMES) {
12981 usedNames.add(helper);
12982 }
12983 }
12984 deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
12985 }
12986 setUpChunkImportsAndExportsForModule(module) {
12987 const moduleImports = new Set(module.imports);
12988 // when we are not preserving modules, we need to make all namespace variables available for
12989 // rendering the namespace object
12990 if (!this.outputOptions.preserveModules) {
12991 if (this.includedNamespaces.has(module)) {
12992 const memberVariables = module.namespace.getMemberVariables();
12993 for (const variable of Object.values(memberVariables)) {
12994 moduleImports.add(variable);
12995 }
12996 }
12997 }
12998 for (let variable of moduleImports) {
12999 if (variable instanceof ExportDefaultVariable) {
13000 variable = variable.getOriginalVariable();
13001 }
13002 if (variable instanceof SyntheticNamedExportVariable) {
13003 variable = variable.getBaseVariable();
13004 }
13005 const chunk = this.chunkByModule.get(variable.module);
13006 if (chunk !== this) {
13007 this.imports.add(variable);
13008 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
13009 variable.module instanceof Module) {
13010 chunk.exports.add(variable);
13011 this.checkCircularDependencyImport(variable, module);
13012 }
13013 }
13014 }
13015 if (this.includedNamespaces.has(module) ||
13016 (module.info.isEntry && module.preserveSignature !== false) ||
13017 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
13018 this.ensureReexportsAreAvailableForModule(module);
13019 }
13020 for (const { node, resolution } of module.dynamicImports) {
13021 if (node.included &&
13022 resolution instanceof Module &&
13023 this.chunkByModule.get(resolution) === this &&
13024 !this.includedNamespaces.has(resolution)) {
13025 this.includedNamespaces.add(resolution);
13026 this.ensureReexportsAreAvailableForModule(resolution);
13027 }
13028 }
13029 }
13030}
13031function getChunkNameFromModule(module) {
13032 return module.chunkName || getAliasName(module.id);
13033}
13034
13035var BuildPhase;
13036(function (BuildPhase) {
13037 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
13038 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
13039 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
13040})(BuildPhase || (BuildPhase = {}));
13041
13042function generateAssetFileName(name, source, outputOptions, bundle) {
13043 const emittedName = outputOptions.sanitizeFileName(name || 'asset');
13044 return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
13045 ? outputOptions.assetFileNames({ name, source, type: 'asset' })
13046 : outputOptions.assetFileNames, 'output.assetFileNames', {
13047 ext: () => path.extname(emittedName).substr(1),
13048 extname: () => path.extname(emittedName),
13049 hash() {
13050 const hash = createHash();
13051 hash.update(emittedName);
13052 hash.update(':');
13053 hash.update(source);
13054 return hash.digest('hex').substr(0, 8);
13055 },
13056 name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
13057 }), bundle);
13058}
13059function reserveFileNameInBundle(fileName, bundle, warn) {
13060 if (fileName in bundle) {
13061 warn(errFileNameConflict(fileName));
13062 }
13063 bundle[fileName] = FILE_PLACEHOLDER;
13064}
13065const FILE_PLACEHOLDER = {
13066 type: 'placeholder'
13067};
13068function hasValidType(emittedFile) {
13069 return Boolean(emittedFile &&
13070 (emittedFile.type === 'asset' ||
13071 emittedFile.type === 'chunk'));
13072}
13073function hasValidName(emittedFile) {
13074 const validatedName = emittedFile.fileName || emittedFile.name;
13075 return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
13076}
13077function getValidSource(source, emittedFile, fileReferenceId) {
13078 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
13079 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
13080 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
13081 }
13082 return source;
13083}
13084function getAssetFileName(file, referenceId) {
13085 if (typeof file.fileName !== 'string') {
13086 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
13087 }
13088 return file.fileName;
13089}
13090function getChunkFileName(file, facadeChunkByModule) {
13091 var _a;
13092 const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
13093 if (!fileName)
13094 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
13095 return fileName;
13096}
13097class FileEmitter {
13098 constructor(graph, options, baseFileEmitter) {
13099 this.graph = graph;
13100 this.options = options;
13101 this.bundle = null;
13102 this.facadeChunkByModule = null;
13103 this.outputOptions = null;
13104 this.assertAssetsFinalized = () => {
13105 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
13106 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
13107 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
13108 }
13109 };
13110 this.emitFile = (emittedFile) => {
13111 if (!hasValidType(emittedFile)) {
13112 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
13113 }
13114 if (!hasValidName(emittedFile)) {
13115 return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
13116 }
13117 if (emittedFile.type === 'chunk') {
13118 return this.emitChunk(emittedFile);
13119 }
13120 else {
13121 return this.emitAsset(emittedFile);
13122 }
13123 };
13124 this.getFileName = (fileReferenceId) => {
13125 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
13126 if (!emittedFile)
13127 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
13128 if (emittedFile.type === 'chunk') {
13129 return getChunkFileName(emittedFile, this.facadeChunkByModule);
13130 }
13131 else {
13132 return getAssetFileName(emittedFile, fileReferenceId);
13133 }
13134 };
13135 this.setAssetSource = (referenceId, requestedSource) => {
13136 const consumedFile = this.filesByReferenceId.get(referenceId);
13137 if (!consumedFile)
13138 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
13139 if (consumedFile.type !== 'asset') {
13140 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
13141 }
13142 if (consumedFile.source !== undefined) {
13143 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
13144 }
13145 const source = getValidSource(requestedSource, consumedFile, referenceId);
13146 if (this.bundle) {
13147 this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
13148 }
13149 else {
13150 consumedFile.source = source;
13151 }
13152 };
13153 this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
13154 this.outputOptions = outputOptions;
13155 this.bundle = outputBundle;
13156 this.facadeChunkByModule = facadeChunkByModule;
13157 for (const emittedFile of this.filesByReferenceId.values()) {
13158 if (emittedFile.fileName) {
13159 reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
13160 }
13161 }
13162 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
13163 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
13164 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
13165 }
13166 }
13167 };
13168 this.filesByReferenceId = baseFileEmitter
13169 ? new Map(baseFileEmitter.filesByReferenceId)
13170 : new Map();
13171 }
13172 assignReferenceId(file, idBase) {
13173 let referenceId;
13174 do {
13175 const hash = createHash();
13176 if (referenceId) {
13177 hash.update(referenceId);
13178 }
13179 else {
13180 hash.update(idBase);
13181 }
13182 referenceId = hash.digest('hex').substr(0, 8);
13183 } while (this.filesByReferenceId.has(referenceId));
13184 this.filesByReferenceId.set(referenceId, file);
13185 return referenceId;
13186 }
13187 emitAsset(emittedAsset) {
13188 const source = typeof emittedAsset.source !== 'undefined'
13189 ? getValidSource(emittedAsset.source, emittedAsset, null)
13190 : undefined;
13191 const consumedAsset = {
13192 fileName: emittedAsset.fileName,
13193 name: emittedAsset.name,
13194 source,
13195 type: 'asset'
13196 };
13197 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
13198 if (this.bundle) {
13199 if (emittedAsset.fileName) {
13200 reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
13201 }
13202 if (source !== undefined) {
13203 this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
13204 }
13205 }
13206 return referenceId;
13207 }
13208 emitChunk(emittedChunk) {
13209 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
13210 return error(errInvalidRollupPhaseForChunkEmission());
13211 }
13212 if (typeof emittedChunk.id !== 'string') {
13213 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
13214 }
13215 const consumedChunk = {
13216 fileName: emittedChunk.fileName,
13217 module: null,
13218 name: emittedChunk.name || emittedChunk.id,
13219 type: 'chunk'
13220 };
13221 this.graph.moduleLoader
13222 .emitChunk(emittedChunk)
13223 .then(module => (consumedChunk.module = module))
13224 .catch(() => {
13225 // Avoid unhandled Promise rejection as the error will be thrown later
13226 // once module loading has finished
13227 });
13228 return this.assignReferenceId(consumedChunk, emittedChunk.id);
13229 }
13230 finalizeAsset(consumedFile, source, referenceId, bundle) {
13231 const fileName = consumedFile.fileName ||
13232 findExistingAssetFileNameWithSource(bundle, source) ||
13233 generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
13234 // We must not modify the original assets to avoid interaction between outputs
13235 const assetWithFileName = { ...consumedFile, fileName, source };
13236 this.filesByReferenceId.set(referenceId, assetWithFileName);
13237 const { options } = this;
13238 bundle[fileName] = {
13239 fileName,
13240 get isAsset() {
13241 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
13242 return true;
13243 },
13244 name: consumedFile.name,
13245 source,
13246 type: 'asset'
13247 };
13248 }
13249}
13250function findExistingAssetFileNameWithSource(bundle, source) {
13251 for (const [fileName, outputFile] of Object.entries(bundle)) {
13252 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
13253 return fileName;
13254 }
13255 return null;
13256}
13257function areSourcesEqual(sourceA, sourceB) {
13258 if (typeof sourceA === 'string') {
13259 return sourceA === sourceB;
13260 }
13261 if (typeof sourceB === 'string') {
13262 return false;
13263 }
13264 if ('equals' in sourceA) {
13265 return sourceA.equals(sourceB);
13266 }
13267 if (sourceA.length !== sourceB.length) {
13268 return false;
13269 }
13270 for (let index = 0; index < sourceA.length; index++) {
13271 if (sourceA[index] !== sourceB[index]) {
13272 return false;
13273 }
13274 }
13275 return true;
13276}
13277
13278const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
13279const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
13280async function createAddons(options, outputPluginDriver) {
13281 try {
13282 let [banner, footer, intro, outro] = await Promise.all([
13283 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
13284 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
13285 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
13286 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
13287 ]);
13288 if (intro)
13289 intro += '\n\n';
13290 if (outro)
13291 outro = `\n\n${outro}`;
13292 if (banner.length)
13293 banner += '\n';
13294 if (footer.length)
13295 footer = '\n' + footer;
13296 return { banner, footer, intro, outro };
13297 }
13298 catch (err) {
13299 return error({
13300 code: 'ADDON_ERROR',
13301 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
13302\tError Message: ${err.message}`
13303 });
13304 }
13305}
13306
13307function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
13308 const chunkDefinitions = [];
13309 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
13310 const manualChunkModulesByAlias = Object.create(null);
13311 for (const [entry, alias] of manualChunkAliasByEntry) {
13312 const chunkModules = (manualChunkModulesByAlias[alias] =
13313 manualChunkModulesByAlias[alias] || []);
13314 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
13315 }
13316 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
13317 chunkDefinitions.push({ alias, modules });
13318 }
13319 const assignedEntryPointsByModule = new Map();
13320 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
13321 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
13322 const staticEntries = new Set(entryModules);
13323 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
13324 const modulesToHandle = new Set([entry]);
13325 for (const module of modulesToHandle) {
13326 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
13327 if (dynamicDependentEntryPoints &&
13328 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
13329 continue;
13330 }
13331 else {
13332 assignedEntryPoints.add(entry);
13333 }
13334 for (const dependency of module.getDependenciesToBeIncluded()) {
13335 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
13336 modulesToHandle.add(dependency);
13337 }
13338 }
13339 }
13340 }
13341 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
13342 const entriesToCheck = new Set(entryPoints);
13343 for (const entry of entriesToCheck) {
13344 if (!containedIn.has(entry)) {
13345 if (staticEntries.has(entry))
13346 return false;
13347 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
13348 for (const dependentEntry of dynamicallyDependentEntryPoints) {
13349 entriesToCheck.add(dependentEntry);
13350 }
13351 }
13352 }
13353 return true;
13354 }
13355 for (const entry of entryModules) {
13356 if (!modulesInManualChunks.has(entry)) {
13357 assignEntryToStaticDependencies(entry, null);
13358 }
13359 }
13360 for (const entry of dynamicEntryModules) {
13361 if (!modulesInManualChunks.has(entry)) {
13362 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
13363 }
13364 }
13365 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
13366 return chunkDefinitions;
13367}
13368function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
13369 const modulesToHandle = new Set([entry]);
13370 for (const module of modulesToHandle) {
13371 modulesInManualChunks.add(module);
13372 manualChunkModules.push(module);
13373 for (const dependency of module.dependencies) {
13374 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
13375 modulesToHandle.add(dependency);
13376 }
13377 }
13378 }
13379}
13380function analyzeModuleGraph(entryModules) {
13381 const dynamicEntryModules = new Set();
13382 const dependentEntryPointsByModule = new Map();
13383 const entriesToHandle = new Set(entryModules);
13384 for (const currentEntry of entriesToHandle) {
13385 const modulesToHandle = new Set([currentEntry]);
13386 for (const module of modulesToHandle) {
13387 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
13388 for (const dependency of module.getDependenciesToBeIncluded()) {
13389 if (!(dependency instanceof ExternalModule)) {
13390 modulesToHandle.add(dependency);
13391 }
13392 }
13393 for (const { resolution } of module.dynamicImports) {
13394 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
13395 dynamicEntryModules.add(resolution);
13396 entriesToHandle.add(resolution);
13397 }
13398 }
13399 for (const dependency of module.implicitlyLoadedBefore) {
13400 dynamicEntryModules.add(dependency);
13401 entriesToHandle.add(dependency);
13402 }
13403 }
13404 }
13405 return { dependentEntryPointsByModule, dynamicEntryModules };
13406}
13407function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
13408 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
13409 for (const dynamicEntry of dynamicEntryModules) {
13410 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
13411 for (const importer of [
13412 ...dynamicEntry.includedDynamicImporters,
13413 ...dynamicEntry.implicitlyLoadedAfter
13414 ]) {
13415 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
13416 dynamicDependentEntryPoints.add(entryPoint);
13417 }
13418 }
13419 }
13420 return dynamicallyDependentEntryPointsByDynamicEntry;
13421}
13422function createChunks(allEntryPoints, assignedEntryPointsByModule) {
13423 const chunkModules = Object.create(null);
13424 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
13425 let chunkSignature = '';
13426 for (const entry of allEntryPoints) {
13427 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
13428 }
13429 const chunk = chunkModules[chunkSignature];
13430 if (chunk) {
13431 chunk.push(module);
13432 }
13433 else {
13434 chunkModules[chunkSignature] = [module];
13435 }
13436 }
13437 return Object.values(chunkModules).map(modules => ({
13438 alias: null,
13439 modules
13440 }));
13441}
13442
13443// ported from https://github.com/substack/node-commondir
13444function commondir(files) {
13445 if (files.length === 0)
13446 return '/';
13447 if (files.length === 1)
13448 return path.dirname(files[0]);
13449 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
13450 const pathSegements = file.split(/\/+|\\+/);
13451 let i;
13452 for (i = 0; commonSegments[i] === pathSegements[i] &&
13453 i < Math.min(commonSegments.length, pathSegements.length); i++)
13454 ;
13455 return commonSegments.slice(0, i);
13456 }, files[0].split(/\/+|\\+/));
13457 // Windows correctly handles paths with forward-slashes
13458 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
13459}
13460
13461const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
13462function sortByExecutionOrder(units) {
13463 units.sort(compareExecIndex);
13464}
13465function analyseModuleExecution(entryModules) {
13466 let nextExecIndex = 0;
13467 const cyclePaths = [];
13468 const analysedModules = new Set();
13469 const dynamicImports = new Set();
13470 const parents = new Map();
13471 const orderedModules = [];
13472 const analyseModule = (module) => {
13473 if (module instanceof Module) {
13474 for (const dependency of module.dependencies) {
13475 if (parents.has(dependency)) {
13476 if (!analysedModules.has(dependency)) {
13477 cyclePaths.push(getCyclePath(dependency, module, parents));
13478 }
13479 continue;
13480 }
13481 parents.set(dependency, module);
13482 analyseModule(dependency);
13483 }
13484 for (const dependency of module.implicitlyLoadedBefore) {
13485 dynamicImports.add(dependency);
13486 }
13487 for (const { resolution } of module.dynamicImports) {
13488 if (resolution instanceof Module) {
13489 dynamicImports.add(resolution);
13490 }
13491 }
13492 orderedModules.push(module);
13493 }
13494 module.execIndex = nextExecIndex++;
13495 analysedModules.add(module);
13496 };
13497 for (const curEntry of entryModules) {
13498 if (!parents.has(curEntry)) {
13499 parents.set(curEntry, null);
13500 analyseModule(curEntry);
13501 }
13502 }
13503 for (const curEntry of dynamicImports) {
13504 if (!parents.has(curEntry)) {
13505 parents.set(curEntry, null);
13506 analyseModule(curEntry);
13507 }
13508 }
13509 return { cyclePaths, orderedModules };
13510}
13511function getCyclePath(module, parent, parents) {
13512 const cycleSymbol = Symbol(module.id);
13513 const path = [relativeId(module.id)];
13514 let nextModule = parent;
13515 module.cycles.add(cycleSymbol);
13516 while (nextModule !== module) {
13517 nextModule.cycles.add(cycleSymbol);
13518 path.push(relativeId(nextModule.id));
13519 nextModule = parents.get(nextModule);
13520 }
13521 path.push(path[0]);
13522 path.reverse();
13523 return path;
13524}
13525
13526class Bundle {
13527 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
13528 this.outputOptions = outputOptions;
13529 this.unsetOptions = unsetOptions;
13530 this.inputOptions = inputOptions;
13531 this.pluginDriver = pluginDriver;
13532 this.graph = graph;
13533 this.facadeChunkByModule = new Map();
13534 this.includedNamespaces = new Set();
13535 }
13536 async generate(isWrite) {
13537 timeStart('GENERATE', 1);
13538 const outputBundle = Object.create(null);
13539 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
13540 try {
13541 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
13542 timeStart('generate chunks', 2);
13543 const chunks = await this.generateChunks();
13544 if (chunks.length > 1) {
13545 validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
13546 }
13547 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
13548 timeEnd('generate chunks', 2);
13549 timeStart('render modules', 2);
13550 // We need to create addons before prerender because at the moment, there
13551 // can be no async code between prerender and render due to internal state
13552 const addons = await createAddons(this.outputOptions, this.pluginDriver);
13553 this.prerenderChunks(chunks, inputBase);
13554 timeEnd('render modules', 2);
13555 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
13556 }
13557 catch (error) {
13558 await this.pluginDriver.hookParallel('renderError', [error]);
13559 throw error;
13560 }
13561 await this.pluginDriver.hookSeq('generateBundle', [
13562 this.outputOptions,
13563 outputBundle,
13564 isWrite
13565 ]);
13566 this.finaliseAssets(outputBundle);
13567 timeEnd('GENERATE', 1);
13568 return outputBundle;
13569 }
13570 async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
13571 this.assignChunkIds(chunks, inputBase, addons, outputBundle);
13572 for (const chunk of chunks) {
13573 outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
13574 }
13575 await Promise.all(chunks.map(async (chunk) => {
13576 const outputChunk = outputBundle[chunk.id];
13577 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
13578 }));
13579 }
13580 async addManualChunks(manualChunks) {
13581 const manualChunkAliasByEntry = new Map();
13582 const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
13583 alias,
13584 entries: await this.graph.moduleLoader.addAdditionalModules(files)
13585 })));
13586 for (const { alias, entries } of chunkEntries) {
13587 for (const entry of entries) {
13588 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
13589 }
13590 }
13591 return manualChunkAliasByEntry;
13592 }
13593 assignChunkIds(chunks, inputBase, addons, bundle) {
13594 const entryChunks = [];
13595 const otherChunks = [];
13596 for (const chunk of chunks) {
13597 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
13598 ? entryChunks
13599 : otherChunks).push(chunk);
13600 }
13601 // make sure entry chunk names take precedence with regard to deconflicting
13602 const chunksForNaming = entryChunks.concat(otherChunks);
13603 for (const chunk of chunksForNaming) {
13604 if (this.outputOptions.file) {
13605 chunk.id = path.basename(this.outputOptions.file);
13606 }
13607 else if (this.outputOptions.preserveModules) {
13608 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
13609 }
13610 else {
13611 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
13612 }
13613 bundle[chunk.id] = FILE_PLACEHOLDER;
13614 }
13615 }
13616 assignManualChunks(getManualChunk) {
13617 const manualChunkAliasByEntry = new Map();
13618 const manualChunksApi = {
13619 getModuleIds: () => this.graph.modulesById.keys(),
13620 getModuleInfo: this.graph.getModuleInfo
13621 };
13622 for (const module of this.graph.modulesById.values()) {
13623 if (module instanceof Module) {
13624 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
13625 if (typeof manualChunkAlias === 'string') {
13626 addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
13627 }
13628 }
13629 }
13630 return manualChunkAliasByEntry;
13631 }
13632 finaliseAssets(outputBundle) {
13633 for (const file of Object.values(outputBundle)) {
13634 if (!file.type) {
13635 warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
13636 file.type = 'asset';
13637 }
13638 if (this.outputOptions.validate && typeof file.code == 'string') {
13639 try {
13640 this.graph.contextParse(file.code, {
13641 allowHashBang: true,
13642 ecmaVersion: 'latest'
13643 });
13644 }
13645 catch (exception) {
13646 this.inputOptions.onwarn(errChunkInvalid(file, exception));
13647 }
13648 }
13649 }
13650 this.pluginDriver.finaliseAssets();
13651 }
13652 async generateChunks() {
13653 const { manualChunks } = this.outputOptions;
13654 const manualChunkAliasByEntry = typeof manualChunks === 'object'
13655 ? await this.addManualChunks(manualChunks)
13656 : this.assignManualChunks(manualChunks);
13657 const chunks = [];
13658 const chunkByModule = new Map();
13659 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
13660 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
13661 : this.outputOptions.preserveModules
13662 ? getIncludedModules(this.graph.modulesById).map(module => ({
13663 alias: null,
13664 modules: [module]
13665 }))
13666 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
13667 sortByExecutionOrder(modules);
13668 const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
13669 chunks.push(chunk);
13670 for (const module of modules) {
13671 chunkByModule.set(module, chunk);
13672 }
13673 }
13674 for (const chunk of chunks) {
13675 chunk.link();
13676 }
13677 const facades = [];
13678 for (const chunk of chunks) {
13679 facades.push(...chunk.generateFacades());
13680 }
13681 return [...chunks, ...facades];
13682 }
13683 prerenderChunks(chunks, inputBase) {
13684 for (const chunk of chunks) {
13685 chunk.generateExports();
13686 }
13687 for (const chunk of chunks) {
13688 chunk.preRender(this.outputOptions, inputBase);
13689 }
13690 }
13691}
13692function getAbsoluteEntryModulePaths(chunks) {
13693 const absoluteEntryModulePaths = [];
13694 for (const chunk of chunks) {
13695 for (const entryModule of chunk.entryModules) {
13696 if (isAbsolute(entryModule.id)) {
13697 absoluteEntryModulePaths.push(entryModule.id);
13698 }
13699 }
13700 }
13701 return absoluteEntryModulePaths;
13702}
13703function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
13704 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
13705 return error({
13706 code: 'INVALID_OPTION',
13707 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
13708 });
13709 if (typeof outputOptions.file === 'string')
13710 return error({
13711 code: 'INVALID_OPTION',
13712 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
13713 'To inline dynamic imports, set the "inlineDynamicImports" option.'
13714 });
13715 if (outputOptions.sourcemapFile)
13716 return error({
13717 code: 'INVALID_OPTION',
13718 message: '"output.sourcemapFile" is only supported for single-file builds.'
13719 });
13720 if (!outputOptions.amd.autoId && outputOptions.amd.id)
13721 onWarn({
13722 code: 'INVALID_OPTION',
13723 message: '"output.amd.id" is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath".'
13724 });
13725}
13726function getIncludedModules(modulesById) {
13727 return [...modulesById.values()].filter(module => module instanceof Module &&
13728 (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
13729}
13730function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
13731 const existingAlias = manualChunkAliasByEntry.get(module);
13732 if (typeof existingAlias === 'string' && existingAlias !== alias) {
13733 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
13734 }
13735 manualChunkAliasByEntry.set(module, alias);
13736}
13737
13738// Reserved word lists for various dialects of the language
13739
13740var reservedWords = {
13741 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
13742 5: "class enum extends super const export import",
13743 6: "enum",
13744 strict: "implements interface let package private protected public static yield",
13745 strictBind: "eval arguments"
13746};
13747
13748// And the keywords
13749
13750var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
13751
13752var keywords = {
13753 5: ecma5AndLessKeywords,
13754 "5module": ecma5AndLessKeywords + " export import",
13755 6: ecma5AndLessKeywords + " const class extends export import super"
13756};
13757
13758var keywordRelationalOperator = /^in(stanceof)?$/;
13759
13760// ## Character categories
13761
13762// Big ugly regular expressions that match characters in the
13763// whitespace, identifier, and identifier-start categories. These
13764// are only applied when a character is found to actually have a
13765// code point above 128.
13766// Generated by `bin/generate-identifier-regex.js`.
13767var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
13768var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
13769
13770var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
13771var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
13772
13773nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
13774
13775// These are a run-length and offset encoded representation of the
13776// >0xffff code points that are a valid part of identifiers. The
13777// offset starts at 0x10000, and each pair of numbers represents an
13778// offset to the next range, and then a size of the range. They were
13779// generated by bin/generate-identifier-regex.js
13780
13781// eslint-disable-next-line comma-spacing
13782var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
13783
13784// eslint-disable-next-line comma-spacing
13785var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
13786
13787// This has a complexity linear to the value of the code. The
13788// assumption is that looking up astral identifier characters is
13789// rare.
13790function isInAstralSet(code, set) {
13791 var pos = 0x10000;
13792 for (var i = 0; i < set.length; i += 2) {
13793 pos += set[i];
13794 if (pos > code) { return false }
13795 pos += set[i + 1];
13796 if (pos >= code) { return true }
13797 }
13798}
13799
13800// Test whether a given character code starts an identifier.
13801
13802function isIdentifierStart(code, astral) {
13803 if (code < 65) { return code === 36 }
13804 if (code < 91) { return true }
13805 if (code < 97) { return code === 95 }
13806 if (code < 123) { return true }
13807 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
13808 if (astral === false) { return false }
13809 return isInAstralSet(code, astralIdentifierStartCodes)
13810}
13811
13812// Test whether a given character is part of an identifier.
13813
13814function isIdentifierChar(code, astral) {
13815 if (code < 48) { return code === 36 }
13816 if (code < 58) { return true }
13817 if (code < 65) { return false }
13818 if (code < 91) { return true }
13819 if (code < 97) { return code === 95 }
13820 if (code < 123) { return true }
13821 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
13822 if (astral === false) { return false }
13823 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
13824}
13825
13826// ## Token types
13827
13828// The assignment of fine-grained, information-carrying type objects
13829// allows the tokenizer to store the information it has about a
13830// token in a way that is very cheap for the parser to look up.
13831
13832// All token type variables start with an underscore, to make them
13833// easy to recognize.
13834
13835// The `beforeExpr` property is used to disambiguate between regular
13836// expressions and divisions. It is set on all token types that can
13837// be followed by an expression (thus, a slash after them would be a
13838// regular expression).
13839//
13840// The `startsExpr` property is used to check if the token ends a
13841// `yield` expression. It is set on all token types that either can
13842// directly start an expression (like a quotation mark) or can
13843// continue an expression (like the body of a string).
13844//
13845// `isLoop` marks a keyword as starting a loop, which is important
13846// to know when parsing a label, in order to allow or disallow
13847// continue jumps to that label.
13848
13849var TokenType = function TokenType(label, conf) {
13850 if ( conf === void 0 ) conf = {};
13851
13852 this.label = label;
13853 this.keyword = conf.keyword;
13854 this.beforeExpr = !!conf.beforeExpr;
13855 this.startsExpr = !!conf.startsExpr;
13856 this.isLoop = !!conf.isLoop;
13857 this.isAssign = !!conf.isAssign;
13858 this.prefix = !!conf.prefix;
13859 this.postfix = !!conf.postfix;
13860 this.binop = conf.binop || null;
13861 this.updateContext = null;
13862};
13863
13864function binop(name, prec) {
13865 return new TokenType(name, {beforeExpr: true, binop: prec})
13866}
13867var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
13868
13869// Map keyword names to token types.
13870
13871var keywords$1 = {};
13872
13873// Succinct definitions of keyword token types
13874function kw(name, options) {
13875 if ( options === void 0 ) options = {};
13876
13877 options.keyword = name;
13878 return keywords$1[name] = new TokenType(name, options)
13879}
13880
13881var types = {
13882 num: new TokenType("num", startsExpr),
13883 regexp: new TokenType("regexp", startsExpr),
13884 string: new TokenType("string", startsExpr),
13885 name: new TokenType("name", startsExpr),
13886 privateId: new TokenType("privateId", startsExpr),
13887 eof: new TokenType("eof"),
13888
13889 // Punctuation token types.
13890 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
13891 bracketR: new TokenType("]"),
13892 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
13893 braceR: new TokenType("}"),
13894 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
13895 parenR: new TokenType(")"),
13896 comma: new TokenType(",", beforeExpr),
13897 semi: new TokenType(";", beforeExpr),
13898 colon: new TokenType(":", beforeExpr),
13899 dot: new TokenType("."),
13900 question: new TokenType("?", beforeExpr),
13901 questionDot: new TokenType("?."),
13902 arrow: new TokenType("=>", beforeExpr),
13903 template: new TokenType("template"),
13904 invalidTemplate: new TokenType("invalidTemplate"),
13905 ellipsis: new TokenType("...", beforeExpr),
13906 backQuote: new TokenType("`", startsExpr),
13907 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
13908
13909 // Operators. These carry several kinds of properties to help the
13910 // parser use them properly (the presence of these properties is
13911 // what categorizes them as operators).
13912 //
13913 // `binop`, when present, specifies that this operator is a binary
13914 // operator, and will refer to its precedence.
13915 //
13916 // `prefix` and `postfix` mark the operator as a prefix or postfix
13917 // unary operator.
13918 //
13919 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
13920 // binary operators with a very low precedence, that should result
13921 // in AssignmentExpression nodes.
13922
13923 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
13924 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
13925 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
13926 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
13927 logicalOR: binop("||", 1),
13928 logicalAND: binop("&&", 2),
13929 bitwiseOR: binop("|", 3),
13930 bitwiseXOR: binop("^", 4),
13931 bitwiseAND: binop("&", 5),
13932 equality: binop("==/!=/===/!==", 6),
13933 relational: binop("</>/<=/>=", 7),
13934 bitShift: binop("<</>>/>>>", 8),
13935 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
13936 modulo: binop("%", 10),
13937 star: binop("*", 10),
13938 slash: binop("/", 10),
13939 starstar: new TokenType("**", {beforeExpr: true}),
13940 coalesce: binop("??", 1),
13941
13942 // Keyword token types.
13943 _break: kw("break"),
13944 _case: kw("case", beforeExpr),
13945 _catch: kw("catch"),
13946 _continue: kw("continue"),
13947 _debugger: kw("debugger"),
13948 _default: kw("default", beforeExpr),
13949 _do: kw("do", {isLoop: true, beforeExpr: true}),
13950 _else: kw("else", beforeExpr),
13951 _finally: kw("finally"),
13952 _for: kw("for", {isLoop: true}),
13953 _function: kw("function", startsExpr),
13954 _if: kw("if"),
13955 _return: kw("return", beforeExpr),
13956 _switch: kw("switch"),
13957 _throw: kw("throw", beforeExpr),
13958 _try: kw("try"),
13959 _var: kw("var"),
13960 _const: kw("const"),
13961 _while: kw("while", {isLoop: true}),
13962 _with: kw("with"),
13963 _new: kw("new", {beforeExpr: true, startsExpr: true}),
13964 _this: kw("this", startsExpr),
13965 _super: kw("super", startsExpr),
13966 _class: kw("class", startsExpr),
13967 _extends: kw("extends", beforeExpr),
13968 _export: kw("export"),
13969 _import: kw("import", startsExpr),
13970 _null: kw("null", startsExpr),
13971 _true: kw("true", startsExpr),
13972 _false: kw("false", startsExpr),
13973 _in: kw("in", {beforeExpr: true, binop: 7}),
13974 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
13975 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
13976 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
13977 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
13978};
13979
13980// Matches a whole line break (where CRLF is considered a single
13981// line break). Used to count lines.
13982
13983var lineBreak = /\r\n?|\n|\u2028|\u2029/;
13984var lineBreakG = new RegExp(lineBreak.source, "g");
13985
13986function isNewLine(code, ecma2019String) {
13987 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
13988}
13989
13990var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
13991
13992var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
13993
13994var ref = Object.prototype;
13995var hasOwnProperty = ref.hasOwnProperty;
13996var toString = ref.toString;
13997
13998// Checks if an object has a property.
13999
14000function has(obj, propName) {
14001 return hasOwnProperty.call(obj, propName)
14002}
14003
14004var isArray = Array.isArray || (function (obj) { return (
14005 toString.call(obj) === "[object Array]"
14006); });
14007
14008function wordsRegexp(words) {
14009 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
14010}
14011
14012// These are used when `options.locations` is on, for the
14013// `startLoc` and `endLoc` properties.
14014
14015var Position = function Position(line, col) {
14016 this.line = line;
14017 this.column = col;
14018};
14019
14020Position.prototype.offset = function offset (n) {
14021 return new Position(this.line, this.column + n)
14022};
14023
14024var SourceLocation = function SourceLocation(p, start, end) {
14025 this.start = start;
14026 this.end = end;
14027 if (p.sourceFile !== null) { this.source = p.sourceFile; }
14028};
14029
14030// The `getLineInfo` function is mostly useful when the
14031// `locations` option is off (for performance reasons) and you
14032// want to find the line/column position for a given character
14033// offset. `input` should be the code string that the offset refers
14034// into.
14035
14036function getLineInfo(input, offset) {
14037 for (var line = 1, cur = 0;;) {
14038 lineBreakG.lastIndex = cur;
14039 var match = lineBreakG.exec(input);
14040 if (match && match.index < offset) {
14041 ++line;
14042 cur = match.index + match[0].length;
14043 } else {
14044 return new Position(line, offset - cur)
14045 }
14046 }
14047}
14048
14049// A second argument must be given to configure the parser process.
14050// These options are recognized (only `ecmaVersion` is required):
14051
14052var defaultOptions = {
14053 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
14054 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
14055 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
14056 // latest version the library supports). This influences support
14057 // for strict mode, the set of reserved words, and support for
14058 // new syntax features.
14059 ecmaVersion: null,
14060 // `sourceType` indicates the mode the code should be parsed in.
14061 // Can be either `"script"` or `"module"`. This influences global
14062 // strict mode and parsing of `import` and `export` declarations.
14063 sourceType: "script",
14064 // `onInsertedSemicolon` can be a callback that will be called
14065 // when a semicolon is automatically inserted. It will be passed
14066 // the position of the comma as an offset, and if `locations` is
14067 // enabled, it is given the location as a `{line, column}` object
14068 // as second argument.
14069 onInsertedSemicolon: null,
14070 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
14071 // trailing commas.
14072 onTrailingComma: null,
14073 // By default, reserved words are only enforced if ecmaVersion >= 5.
14074 // Set `allowReserved` to a boolean value to explicitly turn this on
14075 // an off. When this option has the value "never", reserved words
14076 // and keywords can also not be used as property names.
14077 allowReserved: null,
14078 // When enabled, a return at the top level is not considered an
14079 // error.
14080 allowReturnOutsideFunction: false,
14081 // When enabled, import/export statements are not constrained to
14082 // appearing at the top of the program, and an import.meta expression
14083 // in a script isn't considered an error.
14084 allowImportExportEverywhere: false,
14085 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
14086 // When enabled, await identifiers are allowed to appear at the top-level scope,
14087 // but they are still not allowed in non-async functions.
14088 allowAwaitOutsideFunction: null,
14089 // When enabled, super identifiers are not constrained to
14090 // appearing in methods and do not raise an error when they appear elsewhere.
14091 allowSuperOutsideMethod: null,
14092 // When enabled, hashbang directive in the beginning of file
14093 // is allowed and treated as a line comment.
14094 allowHashBang: false,
14095 // When `locations` is on, `loc` properties holding objects with
14096 // `start` and `end` properties in `{line, column}` form (with
14097 // line being 1-based and column 0-based) will be attached to the
14098 // nodes.
14099 locations: false,
14100 // A function can be passed as `onToken` option, which will
14101 // cause Acorn to call that function with object in the same
14102 // format as tokens returned from `tokenizer().getToken()`. Note
14103 // that you are not allowed to call the parser from the
14104 // callback—that will corrupt its internal state.
14105 onToken: null,
14106 // A function can be passed as `onComment` option, which will
14107 // cause Acorn to call that function with `(block, text, start,
14108 // end)` parameters whenever a comment is skipped. `block` is a
14109 // boolean indicating whether this is a block (`/* */`) comment,
14110 // `text` is the content of the comment, and `start` and `end` are
14111 // character offsets that denote the start and end of the comment.
14112 // When the `locations` option is on, two more parameters are
14113 // passed, the full `{line, column}` locations of the start and
14114 // end of the comments. Note that you are not allowed to call the
14115 // parser from the callback—that will corrupt its internal state.
14116 onComment: null,
14117 // Nodes have their start and end characters offsets recorded in
14118 // `start` and `end` properties (directly on the node, rather than
14119 // the `loc` object, which holds line/column data. To also add a
14120 // [semi-standardized][range] `range` property holding a `[start,
14121 // end]` array with the same numbers, set the `ranges` option to
14122 // `true`.
14123 //
14124 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
14125 ranges: false,
14126 // It is possible to parse multiple files into a single AST by
14127 // passing the tree produced by parsing the first file as
14128 // `program` option in subsequent parses. This will add the
14129 // toplevel forms of the parsed file to the `Program` (top) node
14130 // of an existing parse tree.
14131 program: null,
14132 // When `locations` is on, you can pass this to record the source
14133 // file in every node's `loc` object.
14134 sourceFile: null,
14135 // This value, if given, is stored in every node, whether
14136 // `locations` is on or off.
14137 directSourceFile: null,
14138 // When enabled, parenthesized expressions are represented by
14139 // (non-standard) ParenthesizedExpression nodes
14140 preserveParens: false
14141};
14142
14143// Interpret and default an options object
14144
14145var warnedAboutEcmaVersion = false;
14146
14147function getOptions(opts) {
14148 var options = {};
14149
14150 for (var opt in defaultOptions)
14151 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
14152
14153 if (options.ecmaVersion === "latest") {
14154 options.ecmaVersion = 1e8;
14155 } else if (options.ecmaVersion == null) {
14156 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
14157 warnedAboutEcmaVersion = true;
14158 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
14159 }
14160 options.ecmaVersion = 11;
14161 } else if (options.ecmaVersion >= 2015) {
14162 options.ecmaVersion -= 2009;
14163 }
14164
14165 if (options.allowReserved == null)
14166 { options.allowReserved = options.ecmaVersion < 5; }
14167 if (options.allowAwaitOutsideFunction == null)
14168 { options.allowAwaitOutsideFunction = options.ecmaVersion >= 13; }
14169
14170 if (isArray(options.onToken)) {
14171 var tokens = options.onToken;
14172 options.onToken = function (token) { return tokens.push(token); };
14173 }
14174 if (isArray(options.onComment))
14175 { options.onComment = pushComment(options, options.onComment); }
14176
14177 return options
14178}
14179
14180function pushComment(options, array) {
14181 return function(block, text, start, end, startLoc, endLoc) {
14182 var comment = {
14183 type: block ? "Block" : "Line",
14184 value: text,
14185 start: start,
14186 end: end
14187 };
14188 if (options.locations)
14189 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
14190 if (options.ranges)
14191 { comment.range = [start, end]; }
14192 array.push(comment);
14193 }
14194}
14195
14196// Each scope gets a bitset that may contain these flags
14197var
14198 SCOPE_TOP = 1,
14199 SCOPE_FUNCTION = 2,
14200 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
14201 SCOPE_ASYNC = 4,
14202 SCOPE_GENERATOR = 8,
14203 SCOPE_ARROW = 16,
14204 SCOPE_SIMPLE_CATCH = 32,
14205 SCOPE_SUPER = 64,
14206 SCOPE_DIRECT_SUPER = 128;
14207
14208function functionFlags(async, generator) {
14209 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
14210}
14211
14212// Used in checkLVal* and declareName to determine the type of a binding
14213var
14214 BIND_NONE = 0, // Not a binding
14215 BIND_VAR = 1, // Var-style binding
14216 BIND_LEXICAL = 2, // Let- or const-style binding
14217 BIND_FUNCTION = 3, // Function declaration
14218 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
14219 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
14220
14221var Parser = function Parser(options, input, startPos) {
14222 this.options = options = getOptions(options);
14223 this.sourceFile = options.sourceFile;
14224 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
14225 var reserved = "";
14226 if (options.allowReserved !== true) {
14227 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
14228 if (options.sourceType === "module") { reserved += " await"; }
14229 }
14230 this.reservedWords = wordsRegexp(reserved);
14231 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
14232 this.reservedWordsStrict = wordsRegexp(reservedStrict);
14233 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
14234 this.input = String(input);
14235
14236 // Used to signal to callers of `readWord1` whether the word
14237 // contained any escape sequences. This is needed because words with
14238 // escape sequences must not be interpreted as keywords.
14239 this.containsEsc = false;
14240
14241 // Set up token state
14242
14243 // The current position of the tokenizer in the input.
14244 if (startPos) {
14245 this.pos = startPos;
14246 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
14247 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
14248 } else {
14249 this.pos = this.lineStart = 0;
14250 this.curLine = 1;
14251 }
14252
14253 // Properties of the current token:
14254 // Its type
14255 this.type = types.eof;
14256 // For tokens that include more information than their type, the value
14257 this.value = null;
14258 // Its start and end offset
14259 this.start = this.end = this.pos;
14260 // And, if locations are used, the {line, column} object
14261 // corresponding to those offsets
14262 this.startLoc = this.endLoc = this.curPosition();
14263
14264 // Position information for the previous token
14265 this.lastTokEndLoc = this.lastTokStartLoc = null;
14266 this.lastTokStart = this.lastTokEnd = this.pos;
14267
14268 // The context stack is used to superficially track syntactic
14269 // context to predict whether a regular expression is allowed in a
14270 // given position.
14271 this.context = this.initialContext();
14272 this.exprAllowed = true;
14273
14274 // Figure out if it's a module code.
14275 this.inModule = options.sourceType === "module";
14276 this.strict = this.inModule || this.strictDirective(this.pos);
14277
14278 // Used to signify the start of a potential arrow function
14279 this.potentialArrowAt = -1;
14280 this.potentialArrowInForAwait = false;
14281
14282 // Positions to delayed-check that yield/await does not exist in default parameters.
14283 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
14284 // Labels in scope.
14285 this.labels = [];
14286 // Thus-far undefined exports.
14287 this.undefinedExports = Object.create(null);
14288
14289 // If enabled, skip leading hashbang line.
14290 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
14291 { this.skipLineComment(2); }
14292
14293 // Scope tracking for duplicate variable names (see scope.js)
14294 this.scopeStack = [];
14295 this.enterScope(SCOPE_TOP);
14296
14297 // For RegExp validation
14298 this.regexpState = null;
14299
14300 // The stack of private names.
14301 // Each element has two properties: 'declared' and 'used'.
14302 // When it exited from the outermost class definition, all used private names must be declared.
14303 this.privateNameStack = [];
14304};
14305
14306var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
14307
14308Parser.prototype.parse = function parse () {
14309 var node = this.options.program || this.startNode();
14310 this.nextToken();
14311 return this.parseTopLevel(node)
14312};
14313
14314prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
14315prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
14316prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
14317prototypeAccessors.allowSuper.get = function () {
14318 var ref = this.currentThisScope();
14319 var flags = ref.flags;
14320 var inClassFieldInit = ref.inClassFieldInit;
14321 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
14322};
14323prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
14324prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
14325prototypeAccessors.inNonArrowFunction.get = function () {
14326 var ref = this.currentThisScope();
14327 var flags = ref.flags;
14328 var inClassFieldInit = ref.inClassFieldInit;
14329 return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
14330};
14331
14332Parser.extend = function extend () {
14333 var plugins = [], len = arguments.length;
14334 while ( len-- ) plugins[ len ] = arguments[ len ];
14335
14336 var cls = this;
14337 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
14338 return cls
14339};
14340
14341Parser.parse = function parse (input, options) {
14342 return new this(options, input).parse()
14343};
14344
14345Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
14346 var parser = new this(options, input, pos);
14347 parser.nextToken();
14348 return parser.parseExpression()
14349};
14350
14351Parser.tokenizer = function tokenizer (input, options) {
14352 return new this(options, input)
14353};
14354
14355Object.defineProperties( Parser.prototype, prototypeAccessors );
14356
14357var pp = Parser.prototype;
14358
14359// ## Parser utilities
14360
14361var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
14362pp.strictDirective = function(start) {
14363 for (;;) {
14364 // Try to find string literal.
14365 skipWhiteSpace.lastIndex = start;
14366 start += skipWhiteSpace.exec(this.input)[0].length;
14367 var match = literal.exec(this.input.slice(start));
14368 if (!match) { return false }
14369 if ((match[1] || match[2]) === "use strict") {
14370 skipWhiteSpace.lastIndex = start + match[0].length;
14371 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
14372 var next = this.input.charAt(end);
14373 return next === ";" || next === "}" ||
14374 (lineBreak.test(spaceAfter[0]) &&
14375 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
14376 }
14377 start += match[0].length;
14378
14379 // Skip semicolon, if any.
14380 skipWhiteSpace.lastIndex = start;
14381 start += skipWhiteSpace.exec(this.input)[0].length;
14382 if (this.input[start] === ";")
14383 { start++; }
14384 }
14385};
14386
14387// Predicate that tests whether the next token is of the given
14388// type, and if yes, consumes it as a side effect.
14389
14390pp.eat = function(type) {
14391 if (this.type === type) {
14392 this.next();
14393 return true
14394 } else {
14395 return false
14396 }
14397};
14398
14399// Tests whether parsed token is a contextual keyword.
14400
14401pp.isContextual = function(name) {
14402 return this.type === types.name && this.value === name && !this.containsEsc
14403};
14404
14405// Consumes contextual keyword if possible.
14406
14407pp.eatContextual = function(name) {
14408 if (!this.isContextual(name)) { return false }
14409 this.next();
14410 return true
14411};
14412
14413// Asserts that following token is given contextual keyword.
14414
14415pp.expectContextual = function(name) {
14416 if (!this.eatContextual(name)) { this.unexpected(); }
14417};
14418
14419// Test whether a semicolon can be inserted at the current position.
14420
14421pp.canInsertSemicolon = function() {
14422 return this.type === types.eof ||
14423 this.type === types.braceR ||
14424 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
14425};
14426
14427pp.insertSemicolon = function() {
14428 if (this.canInsertSemicolon()) {
14429 if (this.options.onInsertedSemicolon)
14430 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
14431 return true
14432 }
14433};
14434
14435// Consume a semicolon, or, failing that, see if we are allowed to
14436// pretend that there is a semicolon at this position.
14437
14438pp.semicolon = function() {
14439 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
14440};
14441
14442pp.afterTrailingComma = function(tokType, notNext) {
14443 if (this.type === tokType) {
14444 if (this.options.onTrailingComma)
14445 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
14446 if (!notNext)
14447 { this.next(); }
14448 return true
14449 }
14450};
14451
14452// Expect a token of a given type. If found, consume it, otherwise,
14453// raise an unexpected token error.
14454
14455pp.expect = function(type) {
14456 this.eat(type) || this.unexpected();
14457};
14458
14459// Raise an unexpected token error.
14460
14461pp.unexpected = function(pos) {
14462 this.raise(pos != null ? pos : this.start, "Unexpected token");
14463};
14464
14465function DestructuringErrors() {
14466 this.shorthandAssign =
14467 this.trailingComma =
14468 this.parenthesizedAssign =
14469 this.parenthesizedBind =
14470 this.doubleProto =
14471 -1;
14472}
14473
14474pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
14475 if (!refDestructuringErrors) { return }
14476 if (refDestructuringErrors.trailingComma > -1)
14477 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
14478 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
14479 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
14480};
14481
14482pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
14483 if (!refDestructuringErrors) { return false }
14484 var shorthandAssign = refDestructuringErrors.shorthandAssign;
14485 var doubleProto = refDestructuringErrors.doubleProto;
14486 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
14487 if (shorthandAssign >= 0)
14488 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
14489 if (doubleProto >= 0)
14490 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
14491};
14492
14493pp.checkYieldAwaitInDefaultParams = function() {
14494 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
14495 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
14496 if (this.awaitPos)
14497 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
14498};
14499
14500pp.isSimpleAssignTarget = function(expr) {
14501 if (expr.type === "ParenthesizedExpression")
14502 { return this.isSimpleAssignTarget(expr.expression) }
14503 return expr.type === "Identifier" || expr.type === "MemberExpression"
14504};
14505
14506var pp$1 = Parser.prototype;
14507
14508// ### Statement parsing
14509
14510// Parse a program. Initializes the parser, reads any number of
14511// statements, and wraps them in a Program node. Optionally takes a
14512// `program` argument. If present, the statements will be appended
14513// to its body instead of creating a new node.
14514
14515pp$1.parseTopLevel = function(node) {
14516 var exports = Object.create(null);
14517 if (!node.body) { node.body = []; }
14518 while (this.type !== types.eof) {
14519 var stmt = this.parseStatement(null, true, exports);
14520 node.body.push(stmt);
14521 }
14522 if (this.inModule)
14523 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
14524 {
14525 var name = list[i];
14526
14527 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
14528 } }
14529 this.adaptDirectivePrologue(node.body);
14530 this.next();
14531 node.sourceType = this.options.sourceType;
14532 return this.finishNode(node, "Program")
14533};
14534
14535var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
14536
14537pp$1.isLet = function(context) {
14538 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
14539 skipWhiteSpace.lastIndex = this.pos;
14540 var skip = skipWhiteSpace.exec(this.input);
14541 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
14542 // For ambiguous cases, determine if a LexicalDeclaration (or only a
14543 // Statement) is allowed here. If context is not empty then only a Statement
14544 // is allowed. However, `let [` is an explicit negative lookahead for
14545 // ExpressionStatement, so special-case it first.
14546 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
14547 if (context) { return false }
14548
14549 if (nextCh === 123) { return true } // '{'
14550 if (isIdentifierStart(nextCh, true)) {
14551 var pos = next + 1;
14552 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
14553 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
14554 var ident = this.input.slice(next, pos);
14555 if (!keywordRelationalOperator.test(ident)) { return true }
14556 }
14557 return false
14558};
14559
14560// check 'async [no LineTerminator here] function'
14561// - 'async /*foo*/ function' is OK.
14562// - 'async /*\n*/ function' is invalid.
14563pp$1.isAsyncFunction = function() {
14564 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
14565 { return false }
14566
14567 skipWhiteSpace.lastIndex = this.pos;
14568 var skip = skipWhiteSpace.exec(this.input);
14569 var next = this.pos + skip[0].length, after;
14570 return !lineBreak.test(this.input.slice(this.pos, next)) &&
14571 this.input.slice(next, next + 8) === "function" &&
14572 (next + 8 === this.input.length ||
14573 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
14574};
14575
14576// Parse a single statement.
14577//
14578// If expecting a statement and finding a slash operator, parse a
14579// regular expression literal. This is to handle cases like
14580// `if (foo) /blah/.exec(foo)`, where looking at the previous token
14581// does not help.
14582
14583pp$1.parseStatement = function(context, topLevel, exports) {
14584 var starttype = this.type, node = this.startNode(), kind;
14585
14586 if (this.isLet(context)) {
14587 starttype = types._var;
14588 kind = "let";
14589 }
14590
14591 // Most types of statements are recognized by the keyword they
14592 // start with. Many are trivial to parse, some require a bit of
14593 // complexity.
14594
14595 switch (starttype) {
14596 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
14597 case types._debugger: return this.parseDebuggerStatement(node)
14598 case types._do: return this.parseDoStatement(node)
14599 case types._for: return this.parseForStatement(node)
14600 case types._function:
14601 // Function as sole body of either an if statement or a labeled statement
14602 // works, but not when it is part of a labeled statement that is the sole
14603 // body of an if statement.
14604 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
14605 return this.parseFunctionStatement(node, false, !context)
14606 case types._class:
14607 if (context) { this.unexpected(); }
14608 return this.parseClass(node, true)
14609 case types._if: return this.parseIfStatement(node)
14610 case types._return: return this.parseReturnStatement(node)
14611 case types._switch: return this.parseSwitchStatement(node)
14612 case types._throw: return this.parseThrowStatement(node)
14613 case types._try: return this.parseTryStatement(node)
14614 case types._const: case types._var:
14615 kind = kind || this.value;
14616 if (context && kind !== "var") { this.unexpected(); }
14617 return this.parseVarStatement(node, kind)
14618 case types._while: return this.parseWhileStatement(node)
14619 case types._with: return this.parseWithStatement(node)
14620 case types.braceL: return this.parseBlock(true, node)
14621 case types.semi: return this.parseEmptyStatement(node)
14622 case types._export:
14623 case types._import:
14624 if (this.options.ecmaVersion > 10 && starttype === types._import) {
14625 skipWhiteSpace.lastIndex = this.pos;
14626 var skip = skipWhiteSpace.exec(this.input);
14627 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
14628 if (nextCh === 40 || nextCh === 46) // '(' or '.'
14629 { return this.parseExpressionStatement(node, this.parseExpression()) }
14630 }
14631
14632 if (!this.options.allowImportExportEverywhere) {
14633 if (!topLevel)
14634 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
14635 if (!this.inModule)
14636 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
14637 }
14638 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
14639
14640 // If the statement does not start with a statement keyword or a
14641 // brace, it's an ExpressionStatement or LabeledStatement. We
14642 // simply start parsing an expression, and afterwards, if the
14643 // next token is a colon and the expression was a simple
14644 // Identifier node, we switch to interpreting it as a label.
14645 default:
14646 if (this.isAsyncFunction()) {
14647 if (context) { this.unexpected(); }
14648 this.next();
14649 return this.parseFunctionStatement(node, true, !context)
14650 }
14651
14652 var maybeName = this.value, expr = this.parseExpression();
14653 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
14654 { return this.parseLabeledStatement(node, maybeName, expr, context) }
14655 else { return this.parseExpressionStatement(node, expr) }
14656 }
14657};
14658
14659pp$1.parseBreakContinueStatement = function(node, keyword) {
14660 var isBreak = keyword === "break";
14661 this.next();
14662 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
14663 else if (this.type !== types.name) { this.unexpected(); }
14664 else {
14665 node.label = this.parseIdent();
14666 this.semicolon();
14667 }
14668
14669 // Verify that there is an actual destination to break or
14670 // continue to.
14671 var i = 0;
14672 for (; i < this.labels.length; ++i) {
14673 var lab = this.labels[i];
14674 if (node.label == null || lab.name === node.label.name) {
14675 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
14676 if (node.label && isBreak) { break }
14677 }
14678 }
14679 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
14680 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
14681};
14682
14683pp$1.parseDebuggerStatement = function(node) {
14684 this.next();
14685 this.semicolon();
14686 return this.finishNode(node, "DebuggerStatement")
14687};
14688
14689pp$1.parseDoStatement = function(node) {
14690 this.next();
14691 this.labels.push(loopLabel);
14692 node.body = this.parseStatement("do");
14693 this.labels.pop();
14694 this.expect(types._while);
14695 node.test = this.parseParenExpression();
14696 if (this.options.ecmaVersion >= 6)
14697 { this.eat(types.semi); }
14698 else
14699 { this.semicolon(); }
14700 return this.finishNode(node, "DoWhileStatement")
14701};
14702
14703// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
14704// loop is non-trivial. Basically, we have to parse the init `var`
14705// statement or expression, disallowing the `in` operator (see
14706// the second parameter to `parseExpression`), and then check
14707// whether the next token is `in` or `of`. When there is no init
14708// part (semicolon immediately after the opening parenthesis), it
14709// is a regular `for` loop.
14710
14711pp$1.parseForStatement = function(node) {
14712 this.next();
14713 var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
14714 this.labels.push(loopLabel);
14715 this.enterScope(0);
14716 this.expect(types.parenL);
14717 if (this.type === types.semi) {
14718 if (awaitAt > -1) { this.unexpected(awaitAt); }
14719 return this.parseFor(node, null)
14720 }
14721 var isLet = this.isLet();
14722 if (this.type === types._var || this.type === types._const || isLet) {
14723 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
14724 this.next();
14725 this.parseVar(init$1, true, kind);
14726 this.finishNode(init$1, "VariableDeclaration");
14727 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
14728 if (this.options.ecmaVersion >= 9) {
14729 if (this.type === types._in) {
14730 if (awaitAt > -1) { this.unexpected(awaitAt); }
14731 } else { node.await = awaitAt > -1; }
14732 }
14733 return this.parseForIn(node, init$1)
14734 }
14735 if (awaitAt > -1) { this.unexpected(awaitAt); }
14736 return this.parseFor(node, init$1)
14737 }
14738 var refDestructuringErrors = new DestructuringErrors;
14739 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
14740 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
14741 if (this.options.ecmaVersion >= 9) {
14742 if (this.type === types._in) {
14743 if (awaitAt > -1) { this.unexpected(awaitAt); }
14744 } else { node.await = awaitAt > -1; }
14745 }
14746 this.toAssignable(init, false, refDestructuringErrors);
14747 this.checkLValPattern(init);
14748 return this.parseForIn(node, init)
14749 } else {
14750 this.checkExpressionErrors(refDestructuringErrors, true);
14751 }
14752 if (awaitAt > -1) { this.unexpected(awaitAt); }
14753 return this.parseFor(node, init)
14754};
14755
14756pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
14757 this.next();
14758 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
14759};
14760
14761pp$1.parseIfStatement = function(node) {
14762 this.next();
14763 node.test = this.parseParenExpression();
14764 // allow function declarations in branches, but only in non-strict mode
14765 node.consequent = this.parseStatement("if");
14766 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
14767 return this.finishNode(node, "IfStatement")
14768};
14769
14770pp$1.parseReturnStatement = function(node) {
14771 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
14772 { this.raise(this.start, "'return' outside of function"); }
14773 this.next();
14774
14775 // In `return` (and `break`/`continue`), the keywords with
14776 // optional arguments, we eagerly look for a semicolon or the
14777 // possibility to insert one.
14778
14779 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
14780 else { node.argument = this.parseExpression(); this.semicolon(); }
14781 return this.finishNode(node, "ReturnStatement")
14782};
14783
14784pp$1.parseSwitchStatement = function(node) {
14785 this.next();
14786 node.discriminant = this.parseParenExpression();
14787 node.cases = [];
14788 this.expect(types.braceL);
14789 this.labels.push(switchLabel);
14790 this.enterScope(0);
14791
14792 // Statements under must be grouped (by label) in SwitchCase
14793 // nodes. `cur` is used to keep the node that we are currently
14794 // adding statements to.
14795
14796 var cur;
14797 for (var sawDefault = false; this.type !== types.braceR;) {
14798 if (this.type === types._case || this.type === types._default) {
14799 var isCase = this.type === types._case;
14800 if (cur) { this.finishNode(cur, "SwitchCase"); }
14801 node.cases.push(cur = this.startNode());
14802 cur.consequent = [];
14803 this.next();
14804 if (isCase) {
14805 cur.test = this.parseExpression();
14806 } else {
14807 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
14808 sawDefault = true;
14809 cur.test = null;
14810 }
14811 this.expect(types.colon);
14812 } else {
14813 if (!cur) { this.unexpected(); }
14814 cur.consequent.push(this.parseStatement(null));
14815 }
14816 }
14817 this.exitScope();
14818 if (cur) { this.finishNode(cur, "SwitchCase"); }
14819 this.next(); // Closing brace
14820 this.labels.pop();
14821 return this.finishNode(node, "SwitchStatement")
14822};
14823
14824pp$1.parseThrowStatement = function(node) {
14825 this.next();
14826 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
14827 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
14828 node.argument = this.parseExpression();
14829 this.semicolon();
14830 return this.finishNode(node, "ThrowStatement")
14831};
14832
14833// Reused empty array added for node fields that are always empty.
14834
14835var empty = [];
14836
14837pp$1.parseTryStatement = function(node) {
14838 this.next();
14839 node.block = this.parseBlock();
14840 node.handler = null;
14841 if (this.type === types._catch) {
14842 var clause = this.startNode();
14843 this.next();
14844 if (this.eat(types.parenL)) {
14845 clause.param = this.parseBindingAtom();
14846 var simple = clause.param.type === "Identifier";
14847 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
14848 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
14849 this.expect(types.parenR);
14850 } else {
14851 if (this.options.ecmaVersion < 10) { this.unexpected(); }
14852 clause.param = null;
14853 this.enterScope(0);
14854 }
14855 clause.body = this.parseBlock(false);
14856 this.exitScope();
14857 node.handler = this.finishNode(clause, "CatchClause");
14858 }
14859 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
14860 if (!node.handler && !node.finalizer)
14861 { this.raise(node.start, "Missing catch or finally clause"); }
14862 return this.finishNode(node, "TryStatement")
14863};
14864
14865pp$1.parseVarStatement = function(node, kind) {
14866 this.next();
14867 this.parseVar(node, false, kind);
14868 this.semicolon();
14869 return this.finishNode(node, "VariableDeclaration")
14870};
14871
14872pp$1.parseWhileStatement = function(node) {
14873 this.next();
14874 node.test = this.parseParenExpression();
14875 this.labels.push(loopLabel);
14876 node.body = this.parseStatement("while");
14877 this.labels.pop();
14878 return this.finishNode(node, "WhileStatement")
14879};
14880
14881pp$1.parseWithStatement = function(node) {
14882 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
14883 this.next();
14884 node.object = this.parseParenExpression();
14885 node.body = this.parseStatement("with");
14886 return this.finishNode(node, "WithStatement")
14887};
14888
14889pp$1.parseEmptyStatement = function(node) {
14890 this.next();
14891 return this.finishNode(node, "EmptyStatement")
14892};
14893
14894pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
14895 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
14896 {
14897 var label = list[i$1];
14898
14899 if (label.name === maybeName)
14900 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
14901 } }
14902 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
14903 for (var i = this.labels.length - 1; i >= 0; i--) {
14904 var label$1 = this.labels[i];
14905 if (label$1.statementStart === node.start) {
14906 // Update information about previous labels on this node
14907 label$1.statementStart = this.start;
14908 label$1.kind = kind;
14909 } else { break }
14910 }
14911 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
14912 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
14913 this.labels.pop();
14914 node.label = expr;
14915 return this.finishNode(node, "LabeledStatement")
14916};
14917
14918pp$1.parseExpressionStatement = function(node, expr) {
14919 node.expression = expr;
14920 this.semicolon();
14921 return this.finishNode(node, "ExpressionStatement")
14922};
14923
14924// Parse a semicolon-enclosed block of statements, handling `"use
14925// strict"` declarations when `allowStrict` is true (used for
14926// function bodies).
14927
14928pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
14929 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
14930 if ( node === void 0 ) node = this.startNode();
14931
14932 node.body = [];
14933 this.expect(types.braceL);
14934 if (createNewLexicalScope) { this.enterScope(0); }
14935 while (this.type !== types.braceR) {
14936 var stmt = this.parseStatement(null);
14937 node.body.push(stmt);
14938 }
14939 if (exitStrict) { this.strict = false; }
14940 this.next();
14941 if (createNewLexicalScope) { this.exitScope(); }
14942 return this.finishNode(node, "BlockStatement")
14943};
14944
14945// Parse a regular `for` loop. The disambiguation code in
14946// `parseStatement` will already have parsed the init statement or
14947// expression.
14948
14949pp$1.parseFor = function(node, init) {
14950 node.init = init;
14951 this.expect(types.semi);
14952 node.test = this.type === types.semi ? null : this.parseExpression();
14953 this.expect(types.semi);
14954 node.update = this.type === types.parenR ? null : this.parseExpression();
14955 this.expect(types.parenR);
14956 node.body = this.parseStatement("for");
14957 this.exitScope();
14958 this.labels.pop();
14959 return this.finishNode(node, "ForStatement")
14960};
14961
14962// Parse a `for`/`in` and `for`/`of` loop, which are almost
14963// same from parser's perspective.
14964
14965pp$1.parseForIn = function(node, init) {
14966 var isForIn = this.type === types._in;
14967 this.next();
14968
14969 if (
14970 init.type === "VariableDeclaration" &&
14971 init.declarations[0].init != null &&
14972 (
14973 !isForIn ||
14974 this.options.ecmaVersion < 8 ||
14975 this.strict ||
14976 init.kind !== "var" ||
14977 init.declarations[0].id.type !== "Identifier"
14978 )
14979 ) {
14980 this.raise(
14981 init.start,
14982 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
14983 );
14984 }
14985 node.left = init;
14986 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
14987 this.expect(types.parenR);
14988 node.body = this.parseStatement("for");
14989 this.exitScope();
14990 this.labels.pop();
14991 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
14992};
14993
14994// Parse a list of variable declarations.
14995
14996pp$1.parseVar = function(node, isFor, kind) {
14997 node.declarations = [];
14998 node.kind = kind;
14999 for (;;) {
15000 var decl = this.startNode();
15001 this.parseVarId(decl, kind);
15002 if (this.eat(types.eq)) {
15003 decl.init = this.parseMaybeAssign(isFor);
15004 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
15005 this.unexpected();
15006 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
15007 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
15008 } else {
15009 decl.init = null;
15010 }
15011 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
15012 if (!this.eat(types.comma)) { break }
15013 }
15014 return node
15015};
15016
15017pp$1.parseVarId = function(decl, kind) {
15018 decl.id = this.parseBindingAtom();
15019 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
15020};
15021
15022var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
15023
15024// Parse a function declaration or literal (depending on the
15025// `statement & FUNC_STATEMENT`).
15026
15027// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
15028pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
15029 this.initFunction(node);
15030 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
15031 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
15032 { this.unexpected(); }
15033 node.generator = this.eat(types.star);
15034 }
15035 if (this.options.ecmaVersion >= 8)
15036 { node.async = !!isAsync; }
15037
15038 if (statement & FUNC_STATEMENT) {
15039 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
15040 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
15041 // If it is a regular function declaration in sloppy mode, then it is
15042 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
15043 // mode depends on properties of the current scope (see
15044 // treatFunctionsAsVar).
15045 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
15046 }
15047
15048 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
15049 this.yieldPos = 0;
15050 this.awaitPos = 0;
15051 this.awaitIdentPos = 0;
15052 this.enterScope(functionFlags(node.async, node.generator));
15053
15054 if (!(statement & FUNC_STATEMENT))
15055 { node.id = this.type === types.name ? this.parseIdent() : null; }
15056
15057 this.parseFunctionParams(node);
15058 this.parseFunctionBody(node, allowExpressionBody, false);
15059
15060 this.yieldPos = oldYieldPos;
15061 this.awaitPos = oldAwaitPos;
15062 this.awaitIdentPos = oldAwaitIdentPos;
15063 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
15064};
15065
15066pp$1.parseFunctionParams = function(node) {
15067 this.expect(types.parenL);
15068 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
15069 this.checkYieldAwaitInDefaultParams();
15070};
15071
15072// Parse a class declaration or literal (depending on the
15073// `isStatement` parameter).
15074
15075pp$1.parseClass = function(node, isStatement) {
15076 this.next();
15077
15078 // ecma-262 14.6 Class Definitions
15079 // A class definition is always strict mode code.
15080 var oldStrict = this.strict;
15081 this.strict = true;
15082
15083 this.parseClassId(node, isStatement);
15084 this.parseClassSuper(node);
15085 var privateNameMap = this.enterClassBody();
15086 var classBody = this.startNode();
15087 var hadConstructor = false;
15088 classBody.body = [];
15089 this.expect(types.braceL);
15090 while (this.type !== types.braceR) {
15091 var element = this.parseClassElement(node.superClass !== null);
15092 if (element) {
15093 classBody.body.push(element);
15094 if (element.type === "MethodDefinition" && element.kind === "constructor") {
15095 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
15096 hadConstructor = true;
15097 } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
15098 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
15099 }
15100 }
15101 }
15102 this.strict = oldStrict;
15103 this.next();
15104 node.body = this.finishNode(classBody, "ClassBody");
15105 this.exitClassBody();
15106 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
15107};
15108
15109pp$1.parseClassElement = function(constructorAllowsSuper) {
15110 if (this.eat(types.semi)) { return null }
15111
15112 var ecmaVersion = this.options.ecmaVersion;
15113 var node = this.startNode();
15114 var keyName = "";
15115 var isGenerator = false;
15116 var isAsync = false;
15117 var kind = "method";
15118
15119 // Parse modifiers
15120 node.static = false;
15121 if (this.eatContextual("static")) {
15122 if (this.isClassElementNameStart() || this.type === types.star) {
15123 node.static = true;
15124 } else {
15125 keyName = "static";
15126 }
15127 }
15128 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
15129 if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
15130 isAsync = true;
15131 } else {
15132 keyName = "async";
15133 }
15134 }
15135 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
15136 isGenerator = true;
15137 }
15138 if (!keyName && !isAsync && !isGenerator) {
15139 var lastValue = this.value;
15140 if (this.eatContextual("get") || this.eatContextual("set")) {
15141 if (this.isClassElementNameStart()) {
15142 kind = lastValue;
15143 } else {
15144 keyName = lastValue;
15145 }
15146 }
15147 }
15148
15149 // Parse element name
15150 if (keyName) {
15151 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
15152 // The last token is any of those. Make it the element name.
15153 node.computed = false;
15154 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
15155 node.key.name = keyName;
15156 this.finishNode(node.key, "Identifier");
15157 } else {
15158 this.parseClassElementName(node);
15159 }
15160
15161 // Parse element value
15162 if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
15163 var isConstructor = !node.static && checkKeyName(node, "constructor");
15164 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
15165 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
15166 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
15167 node.kind = isConstructor ? "constructor" : kind;
15168 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
15169 } else {
15170 this.parseClassField(node);
15171 }
15172
15173 return node
15174};
15175
15176pp$1.isClassElementNameStart = function() {
15177 return (
15178 this.type === types.name ||
15179 this.type === types.privateId ||
15180 this.type === types.num ||
15181 this.type === types.string ||
15182 this.type === types.bracketL ||
15183 this.type.keyword
15184 )
15185};
15186
15187pp$1.parseClassElementName = function(element) {
15188 if (this.type === types.privateId) {
15189 if (this.value === "constructor") {
15190 this.raise(this.start, "Classes can't have an element named '#constructor'");
15191 }
15192 element.computed = false;
15193 element.key = this.parsePrivateIdent();
15194 } else {
15195 this.parsePropertyName(element);
15196 }
15197};
15198
15199pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
15200 // Check key and flags
15201 var key = method.key;
15202 if (method.kind === "constructor") {
15203 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
15204 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
15205 } else if (method.static && checkKeyName(method, "prototype")) {
15206 this.raise(key.start, "Classes may not have a static property named prototype");
15207 }
15208
15209 // Parse value
15210 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
15211
15212 // Check value
15213 if (method.kind === "get" && value.params.length !== 0)
15214 { this.raiseRecoverable(value.start, "getter should have no params"); }
15215 if (method.kind === "set" && value.params.length !== 1)
15216 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
15217 if (method.kind === "set" && value.params[0].type === "RestElement")
15218 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
15219
15220 return this.finishNode(method, "MethodDefinition")
15221};
15222
15223pp$1.parseClassField = function(field) {
15224 if (checkKeyName(field, "constructor")) {
15225 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
15226 } else if (field.static && checkKeyName(field, "prototype")) {
15227 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
15228 }
15229
15230 if (this.eat(types.eq)) {
15231 // To raise SyntaxError if 'arguments' exists in the initializer.
15232 var scope = this.currentThisScope();
15233 var inClassFieldInit = scope.inClassFieldInit;
15234 scope.inClassFieldInit = true;
15235 field.value = this.parseMaybeAssign();
15236 scope.inClassFieldInit = inClassFieldInit;
15237 } else {
15238 field.value = null;
15239 }
15240 this.semicolon();
15241
15242 return this.finishNode(field, "PropertyDefinition")
15243};
15244
15245pp$1.parseClassId = function(node, isStatement) {
15246 if (this.type === types.name) {
15247 node.id = this.parseIdent();
15248 if (isStatement)
15249 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
15250 } else {
15251 if (isStatement === true)
15252 { this.unexpected(); }
15253 node.id = null;
15254 }
15255};
15256
15257pp$1.parseClassSuper = function(node) {
15258 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
15259};
15260
15261pp$1.enterClassBody = function() {
15262 var element = {declared: Object.create(null), used: []};
15263 this.privateNameStack.push(element);
15264 return element.declared
15265};
15266
15267pp$1.exitClassBody = function() {
15268 var ref = this.privateNameStack.pop();
15269 var declared = ref.declared;
15270 var used = ref.used;
15271 var len = this.privateNameStack.length;
15272 var parent = len === 0 ? null : this.privateNameStack[len - 1];
15273 for (var i = 0; i < used.length; ++i) {
15274 var id = used[i];
15275 if (!has(declared, id.name)) {
15276 if (parent) {
15277 parent.used.push(id);
15278 } else {
15279 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
15280 }
15281 }
15282 }
15283};
15284
15285function isPrivateNameConflicted(privateNameMap, element) {
15286 var name = element.key.name;
15287 var curr = privateNameMap[name];
15288
15289 var next = "true";
15290 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
15291 next = (element.static ? "s" : "i") + element.kind;
15292 }
15293
15294 // `class { get #a(){}; static set #a(_){} }` is also conflict.
15295 if (
15296 curr === "iget" && next === "iset" ||
15297 curr === "iset" && next === "iget" ||
15298 curr === "sget" && next === "sset" ||
15299 curr === "sset" && next === "sget"
15300 ) {
15301 privateNameMap[name] = "true";
15302 return false
15303 } else if (!curr) {
15304 privateNameMap[name] = next;
15305 return false
15306 } else {
15307 return true
15308 }
15309}
15310
15311function checkKeyName(node, name) {
15312 var computed = node.computed;
15313 var key = node.key;
15314 return !computed && (
15315 key.type === "Identifier" && key.name === name ||
15316 key.type === "Literal" && key.value === name
15317 )
15318}
15319
15320// Parses module export declaration.
15321
15322pp$1.parseExport = function(node, exports) {
15323 this.next();
15324 // export * from '...'
15325 if (this.eat(types.star)) {
15326 if (this.options.ecmaVersion >= 11) {
15327 if (this.eatContextual("as")) {
15328 node.exported = this.parseIdent(true);
15329 this.checkExport(exports, node.exported.name, this.lastTokStart);
15330 } else {
15331 node.exported = null;
15332 }
15333 }
15334 this.expectContextual("from");
15335 if (this.type !== types.string) { this.unexpected(); }
15336 node.source = this.parseExprAtom();
15337 this.semicolon();
15338 return this.finishNode(node, "ExportAllDeclaration")
15339 }
15340 if (this.eat(types._default)) { // export default ...
15341 this.checkExport(exports, "default", this.lastTokStart);
15342 var isAsync;
15343 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
15344 var fNode = this.startNode();
15345 this.next();
15346 if (isAsync) { this.next(); }
15347 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
15348 } else if (this.type === types._class) {
15349 var cNode = this.startNode();
15350 node.declaration = this.parseClass(cNode, "nullableID");
15351 } else {
15352 node.declaration = this.parseMaybeAssign();
15353 this.semicolon();
15354 }
15355 return this.finishNode(node, "ExportDefaultDeclaration")
15356 }
15357 // export var|const|let|function|class ...
15358 if (this.shouldParseExportStatement()) {
15359 node.declaration = this.parseStatement(null);
15360 if (node.declaration.type === "VariableDeclaration")
15361 { this.checkVariableExport(exports, node.declaration.declarations); }
15362 else
15363 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
15364 node.specifiers = [];
15365 node.source = null;
15366 } else { // export { x, y as z } [from '...']
15367 node.declaration = null;
15368 node.specifiers = this.parseExportSpecifiers(exports);
15369 if (this.eatContextual("from")) {
15370 if (this.type !== types.string) { this.unexpected(); }
15371 node.source = this.parseExprAtom();
15372 } else {
15373 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
15374 // check for keywords used as local names
15375 var spec = list[i];
15376
15377 this.checkUnreserved(spec.local);
15378 // check if export is defined
15379 this.checkLocalExport(spec.local);
15380 }
15381
15382 node.source = null;
15383 }
15384 this.semicolon();
15385 }
15386 return this.finishNode(node, "ExportNamedDeclaration")
15387};
15388
15389pp$1.checkExport = function(exports, name, pos) {
15390 if (!exports) { return }
15391 if (has(exports, name))
15392 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
15393 exports[name] = true;
15394};
15395
15396pp$1.checkPatternExport = function(exports, pat) {
15397 var type = pat.type;
15398 if (type === "Identifier")
15399 { this.checkExport(exports, pat.name, pat.start); }
15400 else if (type === "ObjectPattern")
15401 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
15402 {
15403 var prop = list[i];
15404
15405 this.checkPatternExport(exports, prop);
15406 } }
15407 else if (type === "ArrayPattern")
15408 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
15409 var elt = list$1[i$1];
15410
15411 if (elt) { this.checkPatternExport(exports, elt); }
15412 } }
15413 else if (type === "Property")
15414 { this.checkPatternExport(exports, pat.value); }
15415 else if (type === "AssignmentPattern")
15416 { this.checkPatternExport(exports, pat.left); }
15417 else if (type === "RestElement")
15418 { this.checkPatternExport(exports, pat.argument); }
15419 else if (type === "ParenthesizedExpression")
15420 { this.checkPatternExport(exports, pat.expression); }
15421};
15422
15423pp$1.checkVariableExport = function(exports, decls) {
15424 if (!exports) { return }
15425 for (var i = 0, list = decls; i < list.length; i += 1)
15426 {
15427 var decl = list[i];
15428
15429 this.checkPatternExport(exports, decl.id);
15430 }
15431};
15432
15433pp$1.shouldParseExportStatement = function() {
15434 return this.type.keyword === "var" ||
15435 this.type.keyword === "const" ||
15436 this.type.keyword === "class" ||
15437 this.type.keyword === "function" ||
15438 this.isLet() ||
15439 this.isAsyncFunction()
15440};
15441
15442// Parses a comma-separated list of module exports.
15443
15444pp$1.parseExportSpecifiers = function(exports) {
15445 var nodes = [], first = true;
15446 // export { x, y as z } [from '...']
15447 this.expect(types.braceL);
15448 while (!this.eat(types.braceR)) {
15449 if (!first) {
15450 this.expect(types.comma);
15451 if (this.afterTrailingComma(types.braceR)) { break }
15452 } else { first = false; }
15453
15454 var node = this.startNode();
15455 node.local = this.parseIdent(true);
15456 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
15457 this.checkExport(exports, node.exported.name, node.exported.start);
15458 nodes.push(this.finishNode(node, "ExportSpecifier"));
15459 }
15460 return nodes
15461};
15462
15463// Parses import declaration.
15464
15465pp$1.parseImport = function(node) {
15466 this.next();
15467 // import '...'
15468 if (this.type === types.string) {
15469 node.specifiers = empty;
15470 node.source = this.parseExprAtom();
15471 } else {
15472 node.specifiers = this.parseImportSpecifiers();
15473 this.expectContextual("from");
15474 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
15475 }
15476 this.semicolon();
15477 return this.finishNode(node, "ImportDeclaration")
15478};
15479
15480// Parses a comma-separated list of module imports.
15481
15482pp$1.parseImportSpecifiers = function() {
15483 var nodes = [], first = true;
15484 if (this.type === types.name) {
15485 // import defaultObj, { x, y as z } from '...'
15486 var node = this.startNode();
15487 node.local = this.parseIdent();
15488 this.checkLValSimple(node.local, BIND_LEXICAL);
15489 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
15490 if (!this.eat(types.comma)) { return nodes }
15491 }
15492 if (this.type === types.star) {
15493 var node$1 = this.startNode();
15494 this.next();
15495 this.expectContextual("as");
15496 node$1.local = this.parseIdent();
15497 this.checkLValSimple(node$1.local, BIND_LEXICAL);
15498 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
15499 return nodes
15500 }
15501 this.expect(types.braceL);
15502 while (!this.eat(types.braceR)) {
15503 if (!first) {
15504 this.expect(types.comma);
15505 if (this.afterTrailingComma(types.braceR)) { break }
15506 } else { first = false; }
15507
15508 var node$2 = this.startNode();
15509 node$2.imported = this.parseIdent(true);
15510 if (this.eatContextual("as")) {
15511 node$2.local = this.parseIdent();
15512 } else {
15513 this.checkUnreserved(node$2.imported);
15514 node$2.local = node$2.imported;
15515 }
15516 this.checkLValSimple(node$2.local, BIND_LEXICAL);
15517 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
15518 }
15519 return nodes
15520};
15521
15522// Set `ExpressionStatement#directive` property for directive prologues.
15523pp$1.adaptDirectivePrologue = function(statements) {
15524 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
15525 statements[i].directive = statements[i].expression.raw.slice(1, -1);
15526 }
15527};
15528pp$1.isDirectiveCandidate = function(statement) {
15529 return (
15530 statement.type === "ExpressionStatement" &&
15531 statement.expression.type === "Literal" &&
15532 typeof statement.expression.value === "string" &&
15533 // Reject parenthesized strings.
15534 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
15535 )
15536};
15537
15538var pp$2 = Parser.prototype;
15539
15540// Convert existing expression atom to assignable pattern
15541// if possible.
15542
15543pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
15544 if (this.options.ecmaVersion >= 6 && node) {
15545 switch (node.type) {
15546 case "Identifier":
15547 if (this.inAsync && node.name === "await")
15548 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
15549 break
15550
15551 case "ObjectPattern":
15552 case "ArrayPattern":
15553 case "AssignmentPattern":
15554 case "RestElement":
15555 break
15556
15557 case "ObjectExpression":
15558 node.type = "ObjectPattern";
15559 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
15560 for (var i = 0, list = node.properties; i < list.length; i += 1) {
15561 var prop = list[i];
15562
15563 this.toAssignable(prop, isBinding);
15564 // Early error:
15565 // AssignmentRestProperty[Yield, Await] :
15566 // `...` DestructuringAssignmentTarget[Yield, Await]
15567 //
15568 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
15569 if (
15570 prop.type === "RestElement" &&
15571 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
15572 ) {
15573 this.raise(prop.argument.start, "Unexpected token");
15574 }
15575 }
15576 break
15577
15578 case "Property":
15579 // AssignmentProperty has type === "Property"
15580 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
15581 this.toAssignable(node.value, isBinding);
15582 break
15583
15584 case "ArrayExpression":
15585 node.type = "ArrayPattern";
15586 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
15587 this.toAssignableList(node.elements, isBinding);
15588 break
15589
15590 case "SpreadElement":
15591 node.type = "RestElement";
15592 this.toAssignable(node.argument, isBinding);
15593 if (node.argument.type === "AssignmentPattern")
15594 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
15595 break
15596
15597 case "AssignmentExpression":
15598 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
15599 node.type = "AssignmentPattern";
15600 delete node.operator;
15601 this.toAssignable(node.left, isBinding);
15602 break
15603
15604 case "ParenthesizedExpression":
15605 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
15606 break
15607
15608 case "ChainExpression":
15609 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
15610 break
15611
15612 case "MemberExpression":
15613 if (!isBinding) { break }
15614
15615 default:
15616 this.raise(node.start, "Assigning to rvalue");
15617 }
15618 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
15619 return node
15620};
15621
15622// Convert list of expression atoms to binding list.
15623
15624pp$2.toAssignableList = function(exprList, isBinding) {
15625 var end = exprList.length;
15626 for (var i = 0; i < end; i++) {
15627 var elt = exprList[i];
15628 if (elt) { this.toAssignable(elt, isBinding); }
15629 }
15630 if (end) {
15631 var last = exprList[end - 1];
15632 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
15633 { this.unexpected(last.argument.start); }
15634 }
15635 return exprList
15636};
15637
15638// Parses spread element.
15639
15640pp$2.parseSpread = function(refDestructuringErrors) {
15641 var node = this.startNode();
15642 this.next();
15643 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
15644 return this.finishNode(node, "SpreadElement")
15645};
15646
15647pp$2.parseRestBinding = function() {
15648 var node = this.startNode();
15649 this.next();
15650
15651 // RestElement inside of a function parameter must be an identifier
15652 if (this.options.ecmaVersion === 6 && this.type !== types.name)
15653 { this.unexpected(); }
15654
15655 node.argument = this.parseBindingAtom();
15656
15657 return this.finishNode(node, "RestElement")
15658};
15659
15660// Parses lvalue (assignable) atom.
15661
15662pp$2.parseBindingAtom = function() {
15663 if (this.options.ecmaVersion >= 6) {
15664 switch (this.type) {
15665 case types.bracketL:
15666 var node = this.startNode();
15667 this.next();
15668 node.elements = this.parseBindingList(types.bracketR, true, true);
15669 return this.finishNode(node, "ArrayPattern")
15670
15671 case types.braceL:
15672 return this.parseObj(true)
15673 }
15674 }
15675 return this.parseIdent()
15676};
15677
15678pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
15679 var elts = [], first = true;
15680 while (!this.eat(close)) {
15681 if (first) { first = false; }
15682 else { this.expect(types.comma); }
15683 if (allowEmpty && this.type === types.comma) {
15684 elts.push(null);
15685 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
15686 break
15687 } else if (this.type === types.ellipsis) {
15688 var rest = this.parseRestBinding();
15689 this.parseBindingListItem(rest);
15690 elts.push(rest);
15691 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
15692 this.expect(close);
15693 break
15694 } else {
15695 var elem = this.parseMaybeDefault(this.start, this.startLoc);
15696 this.parseBindingListItem(elem);
15697 elts.push(elem);
15698 }
15699 }
15700 return elts
15701};
15702
15703pp$2.parseBindingListItem = function(param) {
15704 return param
15705};
15706
15707// Parses assignment pattern around given atom if possible.
15708
15709pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
15710 left = left || this.parseBindingAtom();
15711 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
15712 var node = this.startNodeAt(startPos, startLoc);
15713 node.left = left;
15714 node.right = this.parseMaybeAssign();
15715 return this.finishNode(node, "AssignmentPattern")
15716};
15717
15718// The following three functions all verify that a node is an lvalue —
15719// something that can be bound, or assigned to. In order to do so, they perform
15720// a variety of checks:
15721//
15722// - Check that none of the bound/assigned-to identifiers are reserved words.
15723// - Record name declarations for bindings in the appropriate scope.
15724// - Check duplicate argument names, if checkClashes is set.
15725//
15726// If a complex binding pattern is encountered (e.g., object and array
15727// destructuring), the entire pattern is recursively checked.
15728//
15729// There are three versions of checkLVal*() appropriate for different
15730// circumstances:
15731//
15732// - checkLValSimple() shall be used if the syntactic construct supports
15733// nothing other than identifiers and member expressions. Parenthesized
15734// expressions are also correctly handled. This is generally appropriate for
15735// constructs for which the spec says
15736//
15737// > It is a Syntax Error if AssignmentTargetType of [the production] is not
15738// > simple.
15739//
15740// It is also appropriate for checking if an identifier is valid and not
15741// defined elsewhere, like import declarations or function/class identifiers.
15742//
15743// Examples where this is used include:
15744// a += …;
15745// import a from '…';
15746// where a is the node to be checked.
15747//
15748// - checkLValPattern() shall be used if the syntactic construct supports
15749// anything checkLValSimple() supports, as well as object and array
15750// destructuring patterns. This is generally appropriate for constructs for
15751// which the spec says
15752//
15753// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
15754// > an ArrayLiteral and AssignmentTargetType of [the production] is not
15755// > simple.
15756//
15757// Examples where this is used include:
15758// (a = …);
15759// const a = …;
15760// try { … } catch (a) { … }
15761// where a is the node to be checked.
15762//
15763// - checkLValInnerPattern() shall be used if the syntactic construct supports
15764// anything checkLValPattern() supports, as well as default assignment
15765// patterns, rest elements, and other constructs that may appear within an
15766// object or array destructuring pattern.
15767//
15768// As a special case, function parameters also use checkLValInnerPattern(),
15769// as they also support defaults and rest constructs.
15770//
15771// These functions deliberately support both assignment and binding constructs,
15772// as the logic for both is exceedingly similar. If the node is the target of
15773// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
15774// should be set to the appropriate BIND_* constant, like BIND_VAR or
15775// BIND_LEXICAL.
15776//
15777// If the function is called with a non-BIND_NONE bindingType, then
15778// additionally a checkClashes object may be specified to allow checking for
15779// duplicate argument names. checkClashes is ignored if the provided construct
15780// is an assignment (i.e., bindingType is BIND_NONE).
15781
15782pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
15783 if ( bindingType === void 0 ) bindingType = BIND_NONE;
15784
15785 var isBind = bindingType !== BIND_NONE;
15786
15787 switch (expr.type) {
15788 case "Identifier":
15789 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
15790 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
15791 if (isBind) {
15792 if (bindingType === BIND_LEXICAL && expr.name === "let")
15793 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
15794 if (checkClashes) {
15795 if (has(checkClashes, expr.name))
15796 { this.raiseRecoverable(expr.start, "Argument name clash"); }
15797 checkClashes[expr.name] = true;
15798 }
15799 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
15800 }
15801 break
15802
15803 case "ChainExpression":
15804 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
15805 break
15806
15807 case "MemberExpression":
15808 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
15809 break
15810
15811 case "ParenthesizedExpression":
15812 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
15813 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
15814
15815 default:
15816 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
15817 }
15818};
15819
15820pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
15821 if ( bindingType === void 0 ) bindingType = BIND_NONE;
15822
15823 switch (expr.type) {
15824 case "ObjectPattern":
15825 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
15826 var prop = list[i];
15827
15828 this.checkLValInnerPattern(prop, bindingType, checkClashes);
15829 }
15830 break
15831
15832 case "ArrayPattern":
15833 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
15834 var elem = list$1[i$1];
15835
15836 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
15837 }
15838 break
15839
15840 default:
15841 this.checkLValSimple(expr, bindingType, checkClashes);
15842 }
15843};
15844
15845pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
15846 if ( bindingType === void 0 ) bindingType = BIND_NONE;
15847
15848 switch (expr.type) {
15849 case "Property":
15850 // AssignmentProperty has type === "Property"
15851 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
15852 break
15853
15854 case "AssignmentPattern":
15855 this.checkLValPattern(expr.left, bindingType, checkClashes);
15856 break
15857
15858 case "RestElement":
15859 this.checkLValPattern(expr.argument, bindingType, checkClashes);
15860 break
15861
15862 default:
15863 this.checkLValPattern(expr, bindingType, checkClashes);
15864 }
15865};
15866
15867// A recursive descent parser operates by defining functions for all
15868
15869var pp$3 = Parser.prototype;
15870
15871// Check if property name clashes with already added.
15872// Object/class getters and setters are not allowed to clash —
15873// either with each other or with an init property — and in
15874// strict mode, init properties are also not allowed to be repeated.
15875
15876pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
15877 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
15878 { return }
15879 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
15880 { return }
15881 var key = prop.key;
15882 var name;
15883 switch (key.type) {
15884 case "Identifier": name = key.name; break
15885 case "Literal": name = String(key.value); break
15886 default: return
15887 }
15888 var kind = prop.kind;
15889 if (this.options.ecmaVersion >= 6) {
15890 if (name === "__proto__" && kind === "init") {
15891 if (propHash.proto) {
15892 if (refDestructuringErrors) {
15893 if (refDestructuringErrors.doubleProto < 0)
15894 { refDestructuringErrors.doubleProto = key.start; }
15895 // Backwards-compat kludge. Can be removed in version 6.0
15896 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
15897 }
15898 propHash.proto = true;
15899 }
15900 return
15901 }
15902 name = "$" + name;
15903 var other = propHash[name];
15904 if (other) {
15905 var redefinition;
15906 if (kind === "init") {
15907 redefinition = this.strict && other.init || other.get || other.set;
15908 } else {
15909 redefinition = other.init || other[kind];
15910 }
15911 if (redefinition)
15912 { this.raiseRecoverable(key.start, "Redefinition of property"); }
15913 } else {
15914 other = propHash[name] = {
15915 init: false,
15916 get: false,
15917 set: false
15918 };
15919 }
15920 other[kind] = true;
15921};
15922
15923// ### Expression parsing
15924
15925// These nest, from the most general expression type at the top to
15926// 'atomic', nondivisible expression types at the bottom. Most of
15927// the functions will simply let the function(s) below them parse,
15928// and, *if* the syntactic construct they handle is present, wrap
15929// the AST node that the inner parser gave them in another node.
15930
15931// Parse a full expression. The optional arguments are used to
15932// forbid the `in` operator (in for loops initalization expressions)
15933// and provide reference for storing '=' operator inside shorthand
15934// property assignment in contexts where both object expression
15935// and object pattern might appear (so it's possible to raise
15936// delayed syntax error at correct position).
15937
15938pp$3.parseExpression = function(forInit, refDestructuringErrors) {
15939 var startPos = this.start, startLoc = this.startLoc;
15940 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
15941 if (this.type === types.comma) {
15942 var node = this.startNodeAt(startPos, startLoc);
15943 node.expressions = [expr];
15944 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
15945 return this.finishNode(node, "SequenceExpression")
15946 }
15947 return expr
15948};
15949
15950// Parse an assignment expression. This includes applications of
15951// operators like `+=`.
15952
15953pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
15954 if (this.isContextual("yield")) {
15955 if (this.inGenerator) { return this.parseYield(forInit) }
15956 // The tokenizer will assume an expression is allowed after
15957 // `yield`, but this isn't that kind of yield
15958 else { this.exprAllowed = false; }
15959 }
15960
15961 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
15962 if (refDestructuringErrors) {
15963 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
15964 oldTrailingComma = refDestructuringErrors.trailingComma;
15965 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
15966 } else {
15967 refDestructuringErrors = new DestructuringErrors;
15968 ownDestructuringErrors = true;
15969 }
15970
15971 var startPos = this.start, startLoc = this.startLoc;
15972 if (this.type === types.parenL || this.type === types.name) {
15973 this.potentialArrowAt = this.start;
15974 this.potentialArrowInForAwait = forInit === "await";
15975 }
15976 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
15977 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
15978 if (this.type.isAssign) {
15979 var node = this.startNodeAt(startPos, startLoc);
15980 node.operator = this.value;
15981 if (this.type === types.eq)
15982 { left = this.toAssignable(left, false, refDestructuringErrors); }
15983 if (!ownDestructuringErrors) {
15984 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
15985 }
15986 if (refDestructuringErrors.shorthandAssign >= left.start)
15987 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
15988 if (this.type === types.eq)
15989 { this.checkLValPattern(left); }
15990 else
15991 { this.checkLValSimple(left); }
15992 node.left = left;
15993 this.next();
15994 node.right = this.parseMaybeAssign(forInit);
15995 return this.finishNode(node, "AssignmentExpression")
15996 } else {
15997 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
15998 }
15999 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
16000 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
16001 return left
16002};
16003
16004// Parse a ternary conditional (`?:`) operator.
16005
16006pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
16007 var startPos = this.start, startLoc = this.startLoc;
16008 var expr = this.parseExprOps(forInit, refDestructuringErrors);
16009 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
16010 if (this.eat(types.question)) {
16011 var node = this.startNodeAt(startPos, startLoc);
16012 node.test = expr;
16013 node.consequent = this.parseMaybeAssign();
16014 this.expect(types.colon);
16015 node.alternate = this.parseMaybeAssign(forInit);
16016 return this.finishNode(node, "ConditionalExpression")
16017 }
16018 return expr
16019};
16020
16021// Start the precedence parser.
16022
16023pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
16024 var startPos = this.start, startLoc = this.startLoc;
16025 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
16026 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
16027 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
16028};
16029
16030// Parse binary operators with the operator precedence parsing
16031// algorithm. `left` is the left-hand side of the operator.
16032// `minPrec` provides context that allows the function to stop and
16033// defer further parser to one of its callers when it encounters an
16034// operator that has a lower precedence than the set it is parsing.
16035
16036pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
16037 var prec = this.type.binop;
16038 if (prec != null && (!forInit || this.type !== types._in)) {
16039 if (prec > minPrec) {
16040 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
16041 var coalesce = this.type === types.coalesce;
16042 if (coalesce) {
16043 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
16044 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
16045 prec = types.logicalAND.binop;
16046 }
16047 var op = this.value;
16048 this.next();
16049 var startPos = this.start, startLoc = this.startLoc;
16050 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
16051 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
16052 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
16053 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
16054 }
16055 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
16056 }
16057 }
16058 return left
16059};
16060
16061pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
16062 var node = this.startNodeAt(startPos, startLoc);
16063 node.left = left;
16064 node.operator = op;
16065 node.right = right;
16066 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
16067};
16068
16069// Parse unary operators, both prefix and postfix.
16070
16071pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
16072 var startPos = this.start, startLoc = this.startLoc, expr;
16073 if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
16074 expr = this.parseAwait();
16075 sawUnary = true;
16076 } else if (this.type.prefix) {
16077 var node = this.startNode(), update = this.type === types.incDec;
16078 node.operator = this.value;
16079 node.prefix = true;
16080 this.next();
16081 node.argument = this.parseMaybeUnary(null, true, update);
16082 this.checkExpressionErrors(refDestructuringErrors, true);
16083 if (update) { this.checkLValSimple(node.argument); }
16084 else if (this.strict && node.operator === "delete" &&
16085 node.argument.type === "Identifier")
16086 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
16087 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
16088 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
16089 else { sawUnary = true; }
16090 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
16091 } else {
16092 expr = this.parseExprSubscripts(refDestructuringErrors);
16093 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
16094 while (this.type.postfix && !this.canInsertSemicolon()) {
16095 var node$1 = this.startNodeAt(startPos, startLoc);
16096 node$1.operator = this.value;
16097 node$1.prefix = false;
16098 node$1.argument = expr;
16099 this.checkLValSimple(expr);
16100 this.next();
16101 expr = this.finishNode(node$1, "UpdateExpression");
16102 }
16103 }
16104
16105 if (!incDec && this.eat(types.starstar)) {
16106 if (sawUnary)
16107 { this.unexpected(this.lastTokStart); }
16108 else
16109 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
16110 } else {
16111 return expr
16112 }
16113};
16114
16115function isPrivateFieldAccess(node) {
16116 return (
16117 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
16118 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
16119 )
16120}
16121
16122// Parse call, dot, and `[]`-subscript expressions.
16123
16124pp$3.parseExprSubscripts = function(refDestructuringErrors) {
16125 var startPos = this.start, startLoc = this.startLoc;
16126 var expr = this.parseExprAtom(refDestructuringErrors);
16127 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
16128 { return expr }
16129 var result = this.parseSubscripts(expr, startPos, startLoc);
16130 if (refDestructuringErrors && result.type === "MemberExpression") {
16131 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
16132 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
16133 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
16134 }
16135 return result
16136};
16137
16138pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
16139 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
16140 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
16141 this.potentialArrowAt === base.start;
16142 var optionalChained = false;
16143
16144 while (true) {
16145 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
16146
16147 if (element.optional) { optionalChained = true; }
16148 if (element === base || element.type === "ArrowFunctionExpression") {
16149 if (optionalChained) {
16150 var chainNode = this.startNodeAt(startPos, startLoc);
16151 chainNode.expression = element;
16152 element = this.finishNode(chainNode, "ChainExpression");
16153 }
16154 return element
16155 }
16156
16157 base = element;
16158 }
16159};
16160
16161pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
16162 var optionalSupported = this.options.ecmaVersion >= 11;
16163 var optional = optionalSupported && this.eat(types.questionDot);
16164 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
16165
16166 var computed = this.eat(types.bracketL);
16167 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
16168 var node = this.startNodeAt(startPos, startLoc);
16169 node.object = base;
16170 if (computed) {
16171 node.property = this.parseExpression();
16172 this.expect(types.bracketR);
16173 } else if (this.type === types.privateId && base.type !== "Super") {
16174 node.property = this.parsePrivateIdent();
16175 } else {
16176 node.property = this.parseIdent(this.options.allowReserved !== "never");
16177 }
16178 node.computed = !!computed;
16179 if (optionalSupported) {
16180 node.optional = optional;
16181 }
16182 base = this.finishNode(node, "MemberExpression");
16183 } else if (!noCalls && this.eat(types.parenL)) {
16184 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
16185 this.yieldPos = 0;
16186 this.awaitPos = 0;
16187 this.awaitIdentPos = 0;
16188 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
16189 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
16190 this.checkPatternErrors(refDestructuringErrors, false);
16191 this.checkYieldAwaitInDefaultParams();
16192 if (this.awaitIdentPos > 0)
16193 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
16194 this.yieldPos = oldYieldPos;
16195 this.awaitPos = oldAwaitPos;
16196 this.awaitIdentPos = oldAwaitIdentPos;
16197 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
16198 }
16199 this.checkExpressionErrors(refDestructuringErrors, true);
16200 this.yieldPos = oldYieldPos || this.yieldPos;
16201 this.awaitPos = oldAwaitPos || this.awaitPos;
16202 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
16203 var node$1 = this.startNodeAt(startPos, startLoc);
16204 node$1.callee = base;
16205 node$1.arguments = exprList;
16206 if (optionalSupported) {
16207 node$1.optional = optional;
16208 }
16209 base = this.finishNode(node$1, "CallExpression");
16210 } else if (this.type === types.backQuote) {
16211 if (optional || optionalChained) {
16212 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
16213 }
16214 var node$2 = this.startNodeAt(startPos, startLoc);
16215 node$2.tag = base;
16216 node$2.quasi = this.parseTemplate({isTagged: true});
16217 base = this.finishNode(node$2, "TaggedTemplateExpression");
16218 }
16219 return base
16220};
16221
16222// Parse an atomic expression — either a single token that is an
16223// expression, an expression started by a keyword like `function` or
16224// `new`, or an expression wrapped in punctuation like `()`, `[]`,
16225// or `{}`.
16226
16227pp$3.parseExprAtom = function(refDestructuringErrors) {
16228 // If a division operator appears in an expression position, the
16229 // tokenizer got confused, and we force it to read a regexp instead.
16230 if (this.type === types.slash) { this.readRegexp(); }
16231
16232 var node, canBeArrow = this.potentialArrowAt === this.start;
16233 switch (this.type) {
16234 case types._super:
16235 if (!this.allowSuper)
16236 { this.raise(this.start, "'super' keyword outside a method"); }
16237 node = this.startNode();
16238 this.next();
16239 if (this.type === types.parenL && !this.allowDirectSuper)
16240 { this.raise(node.start, "super() call outside constructor of a subclass"); }
16241 // The `super` keyword can appear at below:
16242 // SuperProperty:
16243 // super [ Expression ]
16244 // super . IdentifierName
16245 // SuperCall:
16246 // super ( Arguments )
16247 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
16248 { this.unexpected(); }
16249 return this.finishNode(node, "Super")
16250
16251 case types._this:
16252 node = this.startNode();
16253 this.next();
16254 return this.finishNode(node, "ThisExpression")
16255
16256 case types.name:
16257 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
16258 var id = this.parseIdent(false);
16259 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
16260 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
16261 if (canBeArrow && !this.canInsertSemicolon()) {
16262 if (this.eat(types.arrow))
16263 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
16264 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
16265 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
16266 id = this.parseIdent(false);
16267 if (this.canInsertSemicolon() || !this.eat(types.arrow))
16268 { this.unexpected(); }
16269 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
16270 }
16271 }
16272 return id
16273
16274 case types.regexp:
16275 var value = this.value;
16276 node = this.parseLiteral(value.value);
16277 node.regex = {pattern: value.pattern, flags: value.flags};
16278 return node
16279
16280 case types.num: case types.string:
16281 return this.parseLiteral(this.value)
16282
16283 case types._null: case types._true: case types._false:
16284 node = this.startNode();
16285 node.value = this.type === types._null ? null : this.type === types._true;
16286 node.raw = this.type.keyword;
16287 this.next();
16288 return this.finishNode(node, "Literal")
16289
16290 case types.parenL:
16291 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
16292 if (refDestructuringErrors) {
16293 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
16294 { refDestructuringErrors.parenthesizedAssign = start; }
16295 if (refDestructuringErrors.parenthesizedBind < 0)
16296 { refDestructuringErrors.parenthesizedBind = start; }
16297 }
16298 return expr
16299
16300 case types.bracketL:
16301 node = this.startNode();
16302 this.next();
16303 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
16304 return this.finishNode(node, "ArrayExpression")
16305
16306 case types.braceL:
16307 return this.parseObj(false, refDestructuringErrors)
16308
16309 case types._function:
16310 node = this.startNode();
16311 this.next();
16312 return this.parseFunction(node, 0)
16313
16314 case types._class:
16315 return this.parseClass(this.startNode(), false)
16316
16317 case types._new:
16318 return this.parseNew()
16319
16320 case types.backQuote:
16321 return this.parseTemplate()
16322
16323 case types._import:
16324 if (this.options.ecmaVersion >= 11) {
16325 return this.parseExprImport()
16326 } else {
16327 return this.unexpected()
16328 }
16329
16330 default:
16331 this.unexpected();
16332 }
16333};
16334
16335pp$3.parseExprImport = function() {
16336 var node = this.startNode();
16337
16338 // Consume `import` as an identifier for `import.meta`.
16339 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
16340 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
16341 var meta = this.parseIdent(true);
16342
16343 switch (this.type) {
16344 case types.parenL:
16345 return this.parseDynamicImport(node)
16346 case types.dot:
16347 node.meta = meta;
16348 return this.parseImportMeta(node)
16349 default:
16350 this.unexpected();
16351 }
16352};
16353
16354pp$3.parseDynamicImport = function(node) {
16355 this.next(); // skip `(`
16356
16357 // Parse node.source.
16358 node.source = this.parseMaybeAssign();
16359
16360 // Verify ending.
16361 if (!this.eat(types.parenR)) {
16362 var errorPos = this.start;
16363 if (this.eat(types.comma) && this.eat(types.parenR)) {
16364 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
16365 } else {
16366 this.unexpected(errorPos);
16367 }
16368 }
16369
16370 return this.finishNode(node, "ImportExpression")
16371};
16372
16373pp$3.parseImportMeta = function(node) {
16374 this.next(); // skip `.`
16375
16376 var containsEsc = this.containsEsc;
16377 node.property = this.parseIdent(true);
16378
16379 if (node.property.name !== "meta")
16380 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
16381 if (containsEsc)
16382 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
16383 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
16384 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
16385
16386 return this.finishNode(node, "MetaProperty")
16387};
16388
16389pp$3.parseLiteral = function(value) {
16390 var node = this.startNode();
16391 node.value = value;
16392 node.raw = this.input.slice(this.start, this.end);
16393 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
16394 this.next();
16395 return this.finishNode(node, "Literal")
16396};
16397
16398pp$3.parseParenExpression = function() {
16399 this.expect(types.parenL);
16400 var val = this.parseExpression();
16401 this.expect(types.parenR);
16402 return val
16403};
16404
16405pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
16406 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
16407 if (this.options.ecmaVersion >= 6) {
16408 this.next();
16409
16410 var innerStartPos = this.start, innerStartLoc = this.startLoc;
16411 var exprList = [], first = true, lastIsComma = false;
16412 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
16413 this.yieldPos = 0;
16414 this.awaitPos = 0;
16415 // Do not save awaitIdentPos to allow checking awaits nested in parameters
16416 while (this.type !== types.parenR) {
16417 first ? first = false : this.expect(types.comma);
16418 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
16419 lastIsComma = true;
16420 break
16421 } else if (this.type === types.ellipsis) {
16422 spreadStart = this.start;
16423 exprList.push(this.parseParenItem(this.parseRestBinding()));
16424 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
16425 break
16426 } else {
16427 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
16428 }
16429 }
16430 var innerEndPos = this.start, innerEndLoc = this.startLoc;
16431 this.expect(types.parenR);
16432
16433 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
16434 this.checkPatternErrors(refDestructuringErrors, false);
16435 this.checkYieldAwaitInDefaultParams();
16436 this.yieldPos = oldYieldPos;
16437 this.awaitPos = oldAwaitPos;
16438 return this.parseParenArrowList(startPos, startLoc, exprList)
16439 }
16440
16441 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
16442 if (spreadStart) { this.unexpected(spreadStart); }
16443 this.checkExpressionErrors(refDestructuringErrors, true);
16444 this.yieldPos = oldYieldPos || this.yieldPos;
16445 this.awaitPos = oldAwaitPos || this.awaitPos;
16446
16447 if (exprList.length > 1) {
16448 val = this.startNodeAt(innerStartPos, innerStartLoc);
16449 val.expressions = exprList;
16450 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
16451 } else {
16452 val = exprList[0];
16453 }
16454 } else {
16455 val = this.parseParenExpression();
16456 }
16457
16458 if (this.options.preserveParens) {
16459 var par = this.startNodeAt(startPos, startLoc);
16460 par.expression = val;
16461 return this.finishNode(par, "ParenthesizedExpression")
16462 } else {
16463 return val
16464 }
16465};
16466
16467pp$3.parseParenItem = function(item) {
16468 return item
16469};
16470
16471pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
16472 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
16473};
16474
16475// New's precedence is slightly tricky. It must allow its argument to
16476// be a `[]` or dot subscript expression, but not a call — at least,
16477// not without wrapping it in parentheses. Thus, it uses the noCalls
16478// argument to parseSubscripts to prevent it from consuming the
16479// argument list.
16480
16481var empty$1 = [];
16482
16483pp$3.parseNew = function() {
16484 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
16485 var node = this.startNode();
16486 var meta = this.parseIdent(true);
16487 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
16488 node.meta = meta;
16489 var containsEsc = this.containsEsc;
16490 node.property = this.parseIdent(true);
16491 if (node.property.name !== "target")
16492 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
16493 if (containsEsc)
16494 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
16495 if (!this.inNonArrowFunction)
16496 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
16497 return this.finishNode(node, "MetaProperty")
16498 }
16499 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
16500 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
16501 if (isImport && node.callee.type === "ImportExpression") {
16502 this.raise(startPos, "Cannot use new with import()");
16503 }
16504 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
16505 else { node.arguments = empty$1; }
16506 return this.finishNode(node, "NewExpression")
16507};
16508
16509// Parse template expression.
16510
16511pp$3.parseTemplateElement = function(ref) {
16512 var isTagged = ref.isTagged;
16513
16514 var elem = this.startNode();
16515 if (this.type === types.invalidTemplate) {
16516 if (!isTagged) {
16517 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
16518 }
16519 elem.value = {
16520 raw: this.value,
16521 cooked: null
16522 };
16523 } else {
16524 elem.value = {
16525 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
16526 cooked: this.value
16527 };
16528 }
16529 this.next();
16530 elem.tail = this.type === types.backQuote;
16531 return this.finishNode(elem, "TemplateElement")
16532};
16533
16534pp$3.parseTemplate = function(ref) {
16535 if ( ref === void 0 ) ref = {};
16536 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
16537
16538 var node = this.startNode();
16539 this.next();
16540 node.expressions = [];
16541 var curElt = this.parseTemplateElement({isTagged: isTagged});
16542 node.quasis = [curElt];
16543 while (!curElt.tail) {
16544 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
16545 this.expect(types.dollarBraceL);
16546 node.expressions.push(this.parseExpression());
16547 this.expect(types.braceR);
16548 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
16549 }
16550 this.next();
16551 return this.finishNode(node, "TemplateLiteral")
16552};
16553
16554pp$3.isAsyncProp = function(prop) {
16555 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
16556 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
16557 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
16558};
16559
16560// Parse an object literal or binding pattern.
16561
16562pp$3.parseObj = function(isPattern, refDestructuringErrors) {
16563 var node = this.startNode(), first = true, propHash = {};
16564 node.properties = [];
16565 this.next();
16566 while (!this.eat(types.braceR)) {
16567 if (!first) {
16568 this.expect(types.comma);
16569 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
16570 } else { first = false; }
16571
16572 var prop = this.parseProperty(isPattern, refDestructuringErrors);
16573 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
16574 node.properties.push(prop);
16575 }
16576 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
16577};
16578
16579pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
16580 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
16581 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
16582 if (isPattern) {
16583 prop.argument = this.parseIdent(false);
16584 if (this.type === types.comma) {
16585 this.raise(this.start, "Comma is not permitted after the rest element");
16586 }
16587 return this.finishNode(prop, "RestElement")
16588 }
16589 // To disallow parenthesized identifier via `this.toAssignable()`.
16590 if (this.type === types.parenL && refDestructuringErrors) {
16591 if (refDestructuringErrors.parenthesizedAssign < 0) {
16592 refDestructuringErrors.parenthesizedAssign = this.start;
16593 }
16594 if (refDestructuringErrors.parenthesizedBind < 0) {
16595 refDestructuringErrors.parenthesizedBind = this.start;
16596 }
16597 }
16598 // Parse argument.
16599 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
16600 // To disallow trailing comma via `this.toAssignable()`.
16601 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
16602 refDestructuringErrors.trailingComma = this.start;
16603 }
16604 // Finish
16605 return this.finishNode(prop, "SpreadElement")
16606 }
16607 if (this.options.ecmaVersion >= 6) {
16608 prop.method = false;
16609 prop.shorthand = false;
16610 if (isPattern || refDestructuringErrors) {
16611 startPos = this.start;
16612 startLoc = this.startLoc;
16613 }
16614 if (!isPattern)
16615 { isGenerator = this.eat(types.star); }
16616 }
16617 var containsEsc = this.containsEsc;
16618 this.parsePropertyName(prop);
16619 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
16620 isAsync = true;
16621 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
16622 this.parsePropertyName(prop, refDestructuringErrors);
16623 } else {
16624 isAsync = false;
16625 }
16626 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
16627 return this.finishNode(prop, "Property")
16628};
16629
16630pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
16631 if ((isGenerator || isAsync) && this.type === types.colon)
16632 { this.unexpected(); }
16633
16634 if (this.eat(types.colon)) {
16635 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
16636 prop.kind = "init";
16637 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
16638 if (isPattern) { this.unexpected(); }
16639 prop.kind = "init";
16640 prop.method = true;
16641 prop.value = this.parseMethod(isGenerator, isAsync);
16642 } else if (!isPattern && !containsEsc &&
16643 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
16644 (prop.key.name === "get" || prop.key.name === "set") &&
16645 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
16646 if (isGenerator || isAsync) { this.unexpected(); }
16647 prop.kind = prop.key.name;
16648 this.parsePropertyName(prop);
16649 prop.value = this.parseMethod(false);
16650 var paramCount = prop.kind === "get" ? 0 : 1;
16651 if (prop.value.params.length !== paramCount) {
16652 var start = prop.value.start;
16653 if (prop.kind === "get")
16654 { this.raiseRecoverable(start, "getter should have no params"); }
16655 else
16656 { this.raiseRecoverable(start, "setter should have exactly one param"); }
16657 } else {
16658 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
16659 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
16660 }
16661 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
16662 if (isGenerator || isAsync) { this.unexpected(); }
16663 this.checkUnreserved(prop.key);
16664 if (prop.key.name === "await" && !this.awaitIdentPos)
16665 { this.awaitIdentPos = startPos; }
16666 prop.kind = "init";
16667 if (isPattern) {
16668 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
16669 } else if (this.type === types.eq && refDestructuringErrors) {
16670 if (refDestructuringErrors.shorthandAssign < 0)
16671 { refDestructuringErrors.shorthandAssign = this.start; }
16672 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
16673 } else {
16674 prop.value = this.copyNode(prop.key);
16675 }
16676 prop.shorthand = true;
16677 } else { this.unexpected(); }
16678};
16679
16680pp$3.parsePropertyName = function(prop) {
16681 if (this.options.ecmaVersion >= 6) {
16682 if (this.eat(types.bracketL)) {
16683 prop.computed = true;
16684 prop.key = this.parseMaybeAssign();
16685 this.expect(types.bracketR);
16686 return prop.key
16687 } else {
16688 prop.computed = false;
16689 }
16690 }
16691 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
16692};
16693
16694// Initialize empty function node.
16695
16696pp$3.initFunction = function(node) {
16697 node.id = null;
16698 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
16699 if (this.options.ecmaVersion >= 8) { node.async = false; }
16700};
16701
16702// Parse object or class method.
16703
16704pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
16705 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
16706
16707 this.initFunction(node);
16708 if (this.options.ecmaVersion >= 6)
16709 { node.generator = isGenerator; }
16710 if (this.options.ecmaVersion >= 8)
16711 { node.async = !!isAsync; }
16712
16713 this.yieldPos = 0;
16714 this.awaitPos = 0;
16715 this.awaitIdentPos = 0;
16716 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
16717
16718 this.expect(types.parenL);
16719 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
16720 this.checkYieldAwaitInDefaultParams();
16721 this.parseFunctionBody(node, false, true);
16722
16723 this.yieldPos = oldYieldPos;
16724 this.awaitPos = oldAwaitPos;
16725 this.awaitIdentPos = oldAwaitIdentPos;
16726 return this.finishNode(node, "FunctionExpression")
16727};
16728
16729// Parse arrow function expression with given parameters.
16730
16731pp$3.parseArrowExpression = function(node, params, isAsync) {
16732 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
16733
16734 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
16735 this.initFunction(node);
16736 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
16737
16738 this.yieldPos = 0;
16739 this.awaitPos = 0;
16740 this.awaitIdentPos = 0;
16741
16742 node.params = this.toAssignableList(params, true);
16743 this.parseFunctionBody(node, true, false);
16744
16745 this.yieldPos = oldYieldPos;
16746 this.awaitPos = oldAwaitPos;
16747 this.awaitIdentPos = oldAwaitIdentPos;
16748 return this.finishNode(node, "ArrowFunctionExpression")
16749};
16750
16751// Parse function body and check parameters.
16752
16753pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
16754 var isExpression = isArrowFunction && this.type !== types.braceL;
16755 var oldStrict = this.strict, useStrict = false;
16756
16757 if (isExpression) {
16758 node.body = this.parseMaybeAssign();
16759 node.expression = true;
16760 this.checkParams(node, false);
16761 } else {
16762 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
16763 if (!oldStrict || nonSimple) {
16764 useStrict = this.strictDirective(this.end);
16765 // If this is a strict mode function, verify that argument names
16766 // are not repeated, and it does not try to bind the words `eval`
16767 // or `arguments`.
16768 if (useStrict && nonSimple)
16769 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
16770 }
16771 // Start a new scope with regard to labels and the `inFunction`
16772 // flag (restore them to their old value afterwards).
16773 var oldLabels = this.labels;
16774 this.labels = [];
16775 if (useStrict) { this.strict = true; }
16776
16777 // Add the params to varDeclaredNames to ensure that an error is thrown
16778 // if a let/const declaration in the function clashes with one of the params.
16779 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
16780 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
16781 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
16782 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
16783 node.expression = false;
16784 this.adaptDirectivePrologue(node.body.body);
16785 this.labels = oldLabels;
16786 }
16787 this.exitScope();
16788};
16789
16790pp$3.isSimpleParamList = function(params) {
16791 for (var i = 0, list = params; i < list.length; i += 1)
16792 {
16793 var param = list[i];
16794
16795 if (param.type !== "Identifier") { return false
16796 } }
16797 return true
16798};
16799
16800// Checks function params for various disallowed patterns such as using "eval"
16801// or "arguments" and duplicate parameters.
16802
16803pp$3.checkParams = function(node, allowDuplicates) {
16804 var nameHash = Object.create(null);
16805 for (var i = 0, list = node.params; i < list.length; i += 1)
16806 {
16807 var param = list[i];
16808
16809 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
16810 }
16811};
16812
16813// Parses a comma-separated list of expressions, and returns them as
16814// an array. `close` is the token type that ends the list, and
16815// `allowEmpty` can be turned on to allow subsequent commas with
16816// nothing in between them to be parsed as `null` (which is needed
16817// for array literals).
16818
16819pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
16820 var elts = [], first = true;
16821 while (!this.eat(close)) {
16822 if (!first) {
16823 this.expect(types.comma);
16824 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
16825 } else { first = false; }
16826
16827 var elt = (void 0);
16828 if (allowEmpty && this.type === types.comma)
16829 { elt = null; }
16830 else if (this.type === types.ellipsis) {
16831 elt = this.parseSpread(refDestructuringErrors);
16832 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
16833 { refDestructuringErrors.trailingComma = this.start; }
16834 } else {
16835 elt = this.parseMaybeAssign(false, refDestructuringErrors);
16836 }
16837 elts.push(elt);
16838 }
16839 return elts
16840};
16841
16842pp$3.checkUnreserved = function(ref) {
16843 var start = ref.start;
16844 var end = ref.end;
16845 var name = ref.name;
16846
16847 if (this.inGenerator && name === "yield")
16848 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
16849 if (this.inAsync && name === "await")
16850 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
16851 if (this.currentThisScope().inClassFieldInit && name === "arguments")
16852 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
16853 if (this.keywords.test(name))
16854 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
16855 if (this.options.ecmaVersion < 6 &&
16856 this.input.slice(start, end).indexOf("\\") !== -1) { return }
16857 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
16858 if (re.test(name)) {
16859 if (!this.inAsync && name === "await")
16860 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
16861 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
16862 }
16863};
16864
16865// Parse the next token as an identifier. If `liberal` is true (used
16866// when parsing properties), it will also convert keywords into
16867// identifiers.
16868
16869pp$3.parseIdent = function(liberal, isBinding) {
16870 var node = this.startNode();
16871 if (this.type === types.name) {
16872 node.name = this.value;
16873 } else if (this.type.keyword) {
16874 node.name = this.type.keyword;
16875
16876 // To fix https://github.com/acornjs/acorn/issues/575
16877 // `class` and `function` keywords push new context into this.context.
16878 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
16879 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
16880 if ((node.name === "class" || node.name === "function") &&
16881 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
16882 this.context.pop();
16883 }
16884 } else {
16885 this.unexpected();
16886 }
16887 this.next(!!liberal);
16888 this.finishNode(node, "Identifier");
16889 if (!liberal) {
16890 this.checkUnreserved(node);
16891 if (node.name === "await" && !this.awaitIdentPos)
16892 { this.awaitIdentPos = node.start; }
16893 }
16894 return node
16895};
16896
16897pp$3.parsePrivateIdent = function() {
16898 var node = this.startNode();
16899 if (this.type === types.privateId) {
16900 node.name = this.value;
16901 } else {
16902 this.unexpected();
16903 }
16904 this.next();
16905 this.finishNode(node, "PrivateIdentifier");
16906
16907 // For validating existence
16908 if (this.privateNameStack.length === 0) {
16909 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
16910 } else {
16911 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
16912 }
16913
16914 return node
16915};
16916
16917// Parses yield expression inside generator.
16918
16919pp$3.parseYield = function(forInit) {
16920 if (!this.yieldPos) { this.yieldPos = this.start; }
16921
16922 var node = this.startNode();
16923 this.next();
16924 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
16925 node.delegate = false;
16926 node.argument = null;
16927 } else {
16928 node.delegate = this.eat(types.star);
16929 node.argument = this.parseMaybeAssign(forInit);
16930 }
16931 return this.finishNode(node, "YieldExpression")
16932};
16933
16934pp$3.parseAwait = function() {
16935 if (!this.awaitPos) { this.awaitPos = this.start; }
16936
16937 var node = this.startNode();
16938 this.next();
16939 node.argument = this.parseMaybeUnary(null, true);
16940 return this.finishNode(node, "AwaitExpression")
16941};
16942
16943var pp$4 = Parser.prototype;
16944
16945// This function is used to raise exceptions on parse errors. It
16946// takes an offset integer (into the current `input`) to indicate
16947// the location of the error, attaches the position to the end
16948// of the error message, and then raises a `SyntaxError` with that
16949// message.
16950
16951pp$4.raise = function(pos, message) {
16952 var loc = getLineInfo(this.input, pos);
16953 message += " (" + loc.line + ":" + loc.column + ")";
16954 var err = new SyntaxError(message);
16955 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
16956 throw err
16957};
16958
16959pp$4.raiseRecoverable = pp$4.raise;
16960
16961pp$4.curPosition = function() {
16962 if (this.options.locations) {
16963 return new Position(this.curLine, this.pos - this.lineStart)
16964 }
16965};
16966
16967var pp$5 = Parser.prototype;
16968
16969var Scope = function Scope(flags) {
16970 this.flags = flags;
16971 // A list of var-declared names in the current lexical scope
16972 this.var = [];
16973 // A list of lexically-declared names in the current lexical scope
16974 this.lexical = [];
16975 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
16976 this.functions = [];
16977 // A switch to disallow the identifier reference 'arguments'
16978 this.inClassFieldInit = false;
16979};
16980
16981// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
16982
16983pp$5.enterScope = function(flags) {
16984 this.scopeStack.push(new Scope(flags));
16985};
16986
16987pp$5.exitScope = function() {
16988 this.scopeStack.pop();
16989};
16990
16991// The spec says:
16992// > At the top level of a function, or script, function declarations are
16993// > treated like var declarations rather than like lexical declarations.
16994pp$5.treatFunctionsAsVarInScope = function(scope) {
16995 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
16996};
16997
16998pp$5.declareName = function(name, bindingType, pos) {
16999 var redeclared = false;
17000 if (bindingType === BIND_LEXICAL) {
17001 var scope = this.currentScope();
17002 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
17003 scope.lexical.push(name);
17004 if (this.inModule && (scope.flags & SCOPE_TOP))
17005 { delete this.undefinedExports[name]; }
17006 } else if (bindingType === BIND_SIMPLE_CATCH) {
17007 var scope$1 = this.currentScope();
17008 scope$1.lexical.push(name);
17009 } else if (bindingType === BIND_FUNCTION) {
17010 var scope$2 = this.currentScope();
17011 if (this.treatFunctionsAsVar)
17012 { redeclared = scope$2.lexical.indexOf(name) > -1; }
17013 else
17014 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
17015 scope$2.functions.push(name);
17016 } else {
17017 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
17018 var scope$3 = this.scopeStack[i];
17019 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
17020 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
17021 redeclared = true;
17022 break
17023 }
17024 scope$3.var.push(name);
17025 if (this.inModule && (scope$3.flags & SCOPE_TOP))
17026 { delete this.undefinedExports[name]; }
17027 if (scope$3.flags & SCOPE_VAR) { break }
17028 }
17029 }
17030 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
17031};
17032
17033pp$5.checkLocalExport = function(id) {
17034 // scope.functions must be empty as Module code is always strict.
17035 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
17036 this.scopeStack[0].var.indexOf(id.name) === -1) {
17037 this.undefinedExports[id.name] = id;
17038 }
17039};
17040
17041pp$5.currentScope = function() {
17042 return this.scopeStack[this.scopeStack.length - 1]
17043};
17044
17045pp$5.currentVarScope = function() {
17046 for (var i = this.scopeStack.length - 1;; i--) {
17047 var scope = this.scopeStack[i];
17048 if (scope.flags & SCOPE_VAR) { return scope }
17049 }
17050};
17051
17052// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
17053pp$5.currentThisScope = function() {
17054 for (var i = this.scopeStack.length - 1;; i--) {
17055 var scope = this.scopeStack[i];
17056 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
17057 }
17058};
17059
17060var Node = function Node(parser, pos, loc) {
17061 this.type = "";
17062 this.start = pos;
17063 this.end = 0;
17064 if (parser.options.locations)
17065 { this.loc = new SourceLocation(parser, loc); }
17066 if (parser.options.directSourceFile)
17067 { this.sourceFile = parser.options.directSourceFile; }
17068 if (parser.options.ranges)
17069 { this.range = [pos, 0]; }
17070};
17071
17072// Start an AST node, attaching a start offset.
17073
17074var pp$6 = Parser.prototype;
17075
17076pp$6.startNode = function() {
17077 return new Node(this, this.start, this.startLoc)
17078};
17079
17080pp$6.startNodeAt = function(pos, loc) {
17081 return new Node(this, pos, loc)
17082};
17083
17084// Finish an AST node, adding `type` and `end` properties.
17085
17086function finishNodeAt(node, type, pos, loc) {
17087 node.type = type;
17088 node.end = pos;
17089 if (this.options.locations)
17090 { node.loc.end = loc; }
17091 if (this.options.ranges)
17092 { node.range[1] = pos; }
17093 return node
17094}
17095
17096pp$6.finishNode = function(node, type) {
17097 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
17098};
17099
17100// Finish node at given position
17101
17102pp$6.finishNodeAt = function(node, type, pos, loc) {
17103 return finishNodeAt.call(this, node, type, pos, loc)
17104};
17105
17106pp$6.copyNode = function(node) {
17107 var newNode = new Node(this, node.start, this.startLoc);
17108 for (var prop in node) { newNode[prop] = node[prop]; }
17109 return newNode
17110};
17111
17112// The algorithm used to determine whether a regexp can appear at a
17113
17114var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
17115 this.token = token;
17116 this.isExpr = !!isExpr;
17117 this.preserveSpace = !!preserveSpace;
17118 this.override = override;
17119 this.generator = !!generator;
17120};
17121
17122var types$1 = {
17123 b_stat: new TokContext("{", false),
17124 b_expr: new TokContext("{", true),
17125 b_tmpl: new TokContext("${", false),
17126 p_stat: new TokContext("(", false),
17127 p_expr: new TokContext("(", true),
17128 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
17129 f_stat: new TokContext("function", false),
17130 f_expr: new TokContext("function", true),
17131 f_expr_gen: new TokContext("function", true, false, null, true),
17132 f_gen: new TokContext("function", false, false, null, true)
17133};
17134
17135var pp$7 = Parser.prototype;
17136
17137pp$7.initialContext = function() {
17138 return [types$1.b_stat]
17139};
17140
17141pp$7.braceIsBlock = function(prevType) {
17142 var parent = this.curContext();
17143 if (parent === types$1.f_expr || parent === types$1.f_stat)
17144 { return true }
17145 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
17146 { return !parent.isExpr }
17147
17148 // The check for `tt.name && exprAllowed` detects whether we are
17149 // after a `yield` or `of` construct. See the `updateContext` for
17150 // `tt.name`.
17151 if (prevType === types._return || prevType === types.name && this.exprAllowed)
17152 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
17153 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
17154 { return true }
17155 if (prevType === types.braceL)
17156 { return parent === types$1.b_stat }
17157 if (prevType === types._var || prevType === types._const || prevType === types.name)
17158 { return false }
17159 return !this.exprAllowed
17160};
17161
17162pp$7.inGeneratorContext = function() {
17163 for (var i = this.context.length - 1; i >= 1; i--) {
17164 var context = this.context[i];
17165 if (context.token === "function")
17166 { return context.generator }
17167 }
17168 return false
17169};
17170
17171pp$7.updateContext = function(prevType) {
17172 var update, type = this.type;
17173 if (type.keyword && prevType === types.dot)
17174 { this.exprAllowed = false; }
17175 else if (update = type.updateContext)
17176 { update.call(this, prevType); }
17177 else
17178 { this.exprAllowed = type.beforeExpr; }
17179};
17180
17181// Token-specific context update code
17182
17183types.parenR.updateContext = types.braceR.updateContext = function() {
17184 if (this.context.length === 1) {
17185 this.exprAllowed = true;
17186 return
17187 }
17188 var out = this.context.pop();
17189 if (out === types$1.b_stat && this.curContext().token === "function") {
17190 out = this.context.pop();
17191 }
17192 this.exprAllowed = !out.isExpr;
17193};
17194
17195types.braceL.updateContext = function(prevType) {
17196 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
17197 this.exprAllowed = true;
17198};
17199
17200types.dollarBraceL.updateContext = function() {
17201 this.context.push(types$1.b_tmpl);
17202 this.exprAllowed = true;
17203};
17204
17205types.parenL.updateContext = function(prevType) {
17206 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
17207 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
17208 this.exprAllowed = true;
17209};
17210
17211types.incDec.updateContext = function() {
17212 // tokExprAllowed stays unchanged
17213};
17214
17215types._function.updateContext = types._class.updateContext = function(prevType) {
17216 if (prevType.beforeExpr && prevType !== types._else &&
17217 !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
17218 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
17219 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
17220 { this.context.push(types$1.f_expr); }
17221 else
17222 { this.context.push(types$1.f_stat); }
17223 this.exprAllowed = false;
17224};
17225
17226types.backQuote.updateContext = function() {
17227 if (this.curContext() === types$1.q_tmpl)
17228 { this.context.pop(); }
17229 else
17230 { this.context.push(types$1.q_tmpl); }
17231 this.exprAllowed = false;
17232};
17233
17234types.star.updateContext = function(prevType) {
17235 if (prevType === types._function) {
17236 var index = this.context.length - 1;
17237 if (this.context[index] === types$1.f_expr)
17238 { this.context[index] = types$1.f_expr_gen; }
17239 else
17240 { this.context[index] = types$1.f_gen; }
17241 }
17242 this.exprAllowed = true;
17243};
17244
17245types.name.updateContext = function(prevType) {
17246 var allowed = false;
17247 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
17248 if (this.value === "of" && !this.exprAllowed ||
17249 this.value === "yield" && this.inGeneratorContext())
17250 { allowed = true; }
17251 }
17252 this.exprAllowed = allowed;
17253};
17254
17255// This file contains Unicode properties extracted from the ECMAScript
17256// specification. The lists are extracted like so:
17257// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
17258
17259// #table-binary-unicode-properties
17260var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
17261var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
17262var ecma11BinaryProperties = ecma10BinaryProperties;
17263var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
17264var unicodeBinaryProperties = {
17265 9: ecma9BinaryProperties,
17266 10: ecma10BinaryProperties,
17267 11: ecma11BinaryProperties,
17268 12: ecma12BinaryProperties
17269};
17270
17271// #table-unicode-general-category-values
17272var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
17273
17274// #table-unicode-script-values
17275var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
17276var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
17277var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
17278var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
17279var unicodeScriptValues = {
17280 9: ecma9ScriptValues,
17281 10: ecma10ScriptValues,
17282 11: ecma11ScriptValues,
17283 12: ecma12ScriptValues
17284};
17285
17286var data = {};
17287function buildUnicodeData(ecmaVersion) {
17288 var d = data[ecmaVersion] = {
17289 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
17290 nonBinary: {
17291 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
17292 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
17293 }
17294 };
17295 d.nonBinary.Script_Extensions = d.nonBinary.Script;
17296
17297 d.nonBinary.gc = d.nonBinary.General_Category;
17298 d.nonBinary.sc = d.nonBinary.Script;
17299 d.nonBinary.scx = d.nonBinary.Script_Extensions;
17300}
17301buildUnicodeData(9);
17302buildUnicodeData(10);
17303buildUnicodeData(11);
17304buildUnicodeData(12);
17305
17306var pp$8 = Parser.prototype;
17307
17308var RegExpValidationState = function RegExpValidationState(parser) {
17309 this.parser = parser;
17310 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
17311 this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
17312 this.source = "";
17313 this.flags = "";
17314 this.start = 0;
17315 this.switchU = false;
17316 this.switchN = false;
17317 this.pos = 0;
17318 this.lastIntValue = 0;
17319 this.lastStringValue = "";
17320 this.lastAssertionIsQuantifiable = false;
17321 this.numCapturingParens = 0;
17322 this.maxBackReference = 0;
17323 this.groupNames = [];
17324 this.backReferenceNames = [];
17325};
17326
17327RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
17328 var unicode = flags.indexOf("u") !== -1;
17329 this.start = start | 0;
17330 this.source = pattern + "";
17331 this.flags = flags;
17332 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
17333 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
17334};
17335
17336RegExpValidationState.prototype.raise = function raise (message) {
17337 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
17338};
17339
17340// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
17341// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
17342RegExpValidationState.prototype.at = function at (i, forceU) {
17343 if ( forceU === void 0 ) forceU = false;
17344
17345 var s = this.source;
17346 var l = s.length;
17347 if (i >= l) {
17348 return -1
17349 }
17350 var c = s.charCodeAt(i);
17351 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
17352 return c
17353 }
17354 var next = s.charCodeAt(i + 1);
17355 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
17356};
17357
17358RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
17359 if ( forceU === void 0 ) forceU = false;
17360
17361 var s = this.source;
17362 var l = s.length;
17363 if (i >= l) {
17364 return l
17365 }
17366 var c = s.charCodeAt(i), next;
17367 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
17368 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
17369 return i + 1
17370 }
17371 return i + 2
17372};
17373
17374RegExpValidationState.prototype.current = function current (forceU) {
17375 if ( forceU === void 0 ) forceU = false;
17376
17377 return this.at(this.pos, forceU)
17378};
17379
17380RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
17381 if ( forceU === void 0 ) forceU = false;
17382
17383 return this.at(this.nextIndex(this.pos, forceU), forceU)
17384};
17385
17386RegExpValidationState.prototype.advance = function advance (forceU) {
17387 if ( forceU === void 0 ) forceU = false;
17388
17389 this.pos = this.nextIndex(this.pos, forceU);
17390};
17391
17392RegExpValidationState.prototype.eat = function eat (ch, forceU) {
17393 if ( forceU === void 0 ) forceU = false;
17394
17395 if (this.current(forceU) === ch) {
17396 this.advance(forceU);
17397 return true
17398 }
17399 return false
17400};
17401
17402function codePointToString(ch) {
17403 if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
17404 ch -= 0x10000;
17405 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
17406}
17407
17408/**
17409 * Validate the flags part of a given RegExpLiteral.
17410 *
17411 * @param {RegExpValidationState} state The state to validate RegExp.
17412 * @returns {void}
17413 */
17414pp$8.validateRegExpFlags = function(state) {
17415 var validFlags = state.validFlags;
17416 var flags = state.flags;
17417
17418 for (var i = 0; i < flags.length; i++) {
17419 var flag = flags.charAt(i);
17420 if (validFlags.indexOf(flag) === -1) {
17421 this.raise(state.start, "Invalid regular expression flag");
17422 }
17423 if (flags.indexOf(flag, i + 1) > -1) {
17424 this.raise(state.start, "Duplicate regular expression flag");
17425 }
17426 }
17427};
17428
17429/**
17430 * Validate the pattern part of a given RegExpLiteral.
17431 *
17432 * @param {RegExpValidationState} state The state to validate RegExp.
17433 * @returns {void}
17434 */
17435pp$8.validateRegExpPattern = function(state) {
17436 this.regexp_pattern(state);
17437
17438 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
17439 // parsing contains a |GroupName|, reparse with the goal symbol
17440 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
17441 // exception if _P_ did not conform to the grammar, if any elements of _P_
17442 // were not matched by the parse, or if any Early Error conditions exist.
17443 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
17444 state.switchN = true;
17445 this.regexp_pattern(state);
17446 }
17447};
17448
17449// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
17450pp$8.regexp_pattern = function(state) {
17451 state.pos = 0;
17452 state.lastIntValue = 0;
17453 state.lastStringValue = "";
17454 state.lastAssertionIsQuantifiable = false;
17455 state.numCapturingParens = 0;
17456 state.maxBackReference = 0;
17457 state.groupNames.length = 0;
17458 state.backReferenceNames.length = 0;
17459
17460 this.regexp_disjunction(state);
17461
17462 if (state.pos !== state.source.length) {
17463 // Make the same messages as V8.
17464 if (state.eat(0x29 /* ) */)) {
17465 state.raise("Unmatched ')'");
17466 }
17467 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
17468 state.raise("Lone quantifier brackets");
17469 }
17470 }
17471 if (state.maxBackReference > state.numCapturingParens) {
17472 state.raise("Invalid escape");
17473 }
17474 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
17475 var name = list[i];
17476
17477 if (state.groupNames.indexOf(name) === -1) {
17478 state.raise("Invalid named capture referenced");
17479 }
17480 }
17481};
17482
17483// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
17484pp$8.regexp_disjunction = function(state) {
17485 this.regexp_alternative(state);
17486 while (state.eat(0x7C /* | */)) {
17487 this.regexp_alternative(state);
17488 }
17489
17490 // Make the same message as V8.
17491 if (this.regexp_eatQuantifier(state, true)) {
17492 state.raise("Nothing to repeat");
17493 }
17494 if (state.eat(0x7B /* { */)) {
17495 state.raise("Lone quantifier brackets");
17496 }
17497};
17498
17499// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
17500pp$8.regexp_alternative = function(state) {
17501 while (state.pos < state.source.length && this.regexp_eatTerm(state))
17502 { }
17503};
17504
17505// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
17506pp$8.regexp_eatTerm = function(state) {
17507 if (this.regexp_eatAssertion(state)) {
17508 // Handle `QuantifiableAssertion Quantifier` alternative.
17509 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
17510 // is a QuantifiableAssertion.
17511 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
17512 // Make the same message as V8.
17513 if (state.switchU) {
17514 state.raise("Invalid quantifier");
17515 }
17516 }
17517 return true
17518 }
17519
17520 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
17521 this.regexp_eatQuantifier(state);
17522 return true
17523 }
17524
17525 return false
17526};
17527
17528// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
17529pp$8.regexp_eatAssertion = function(state) {
17530 var start = state.pos;
17531 state.lastAssertionIsQuantifiable = false;
17532
17533 // ^, $
17534 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
17535 return true
17536 }
17537
17538 // \b \B
17539 if (state.eat(0x5C /* \ */)) {
17540 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
17541 return true
17542 }
17543 state.pos = start;
17544 }
17545
17546 // Lookahead / Lookbehind
17547 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
17548 var lookbehind = false;
17549 if (this.options.ecmaVersion >= 9) {
17550 lookbehind = state.eat(0x3C /* < */);
17551 }
17552 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
17553 this.regexp_disjunction(state);
17554 if (!state.eat(0x29 /* ) */)) {
17555 state.raise("Unterminated group");
17556 }
17557 state.lastAssertionIsQuantifiable = !lookbehind;
17558 return true
17559 }
17560 }
17561
17562 state.pos = start;
17563 return false
17564};
17565
17566// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
17567pp$8.regexp_eatQuantifier = function(state, noError) {
17568 if ( noError === void 0 ) noError = false;
17569
17570 if (this.regexp_eatQuantifierPrefix(state, noError)) {
17571 state.eat(0x3F /* ? */);
17572 return true
17573 }
17574 return false
17575};
17576
17577// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
17578pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
17579 return (
17580 state.eat(0x2A /* * */) ||
17581 state.eat(0x2B /* + */) ||
17582 state.eat(0x3F /* ? */) ||
17583 this.regexp_eatBracedQuantifier(state, noError)
17584 )
17585};
17586pp$8.regexp_eatBracedQuantifier = function(state, noError) {
17587 var start = state.pos;
17588 if (state.eat(0x7B /* { */)) {
17589 var min = 0, max = -1;
17590 if (this.regexp_eatDecimalDigits(state)) {
17591 min = state.lastIntValue;
17592 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
17593 max = state.lastIntValue;
17594 }
17595 if (state.eat(0x7D /* } */)) {
17596 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
17597 if (max !== -1 && max < min && !noError) {
17598 state.raise("numbers out of order in {} quantifier");
17599 }
17600 return true
17601 }
17602 }
17603 if (state.switchU && !noError) {
17604 state.raise("Incomplete quantifier");
17605 }
17606 state.pos = start;
17607 }
17608 return false
17609};
17610
17611// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
17612pp$8.regexp_eatAtom = function(state) {
17613 return (
17614 this.regexp_eatPatternCharacters(state) ||
17615 state.eat(0x2E /* . */) ||
17616 this.regexp_eatReverseSolidusAtomEscape(state) ||
17617 this.regexp_eatCharacterClass(state) ||
17618 this.regexp_eatUncapturingGroup(state) ||
17619 this.regexp_eatCapturingGroup(state)
17620 )
17621};
17622pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
17623 var start = state.pos;
17624 if (state.eat(0x5C /* \ */)) {
17625 if (this.regexp_eatAtomEscape(state)) {
17626 return true
17627 }
17628 state.pos = start;
17629 }
17630 return false
17631};
17632pp$8.regexp_eatUncapturingGroup = function(state) {
17633 var start = state.pos;
17634 if (state.eat(0x28 /* ( */)) {
17635 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
17636 this.regexp_disjunction(state);
17637 if (state.eat(0x29 /* ) */)) {
17638 return true
17639 }
17640 state.raise("Unterminated group");
17641 }
17642 state.pos = start;
17643 }
17644 return false
17645};
17646pp$8.regexp_eatCapturingGroup = function(state) {
17647 if (state.eat(0x28 /* ( */)) {
17648 if (this.options.ecmaVersion >= 9) {
17649 this.regexp_groupSpecifier(state);
17650 } else if (state.current() === 0x3F /* ? */) {
17651 state.raise("Invalid group");
17652 }
17653 this.regexp_disjunction(state);
17654 if (state.eat(0x29 /* ) */)) {
17655 state.numCapturingParens += 1;
17656 return true
17657 }
17658 state.raise("Unterminated group");
17659 }
17660 return false
17661};
17662
17663// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
17664pp$8.regexp_eatExtendedAtom = function(state) {
17665 return (
17666 state.eat(0x2E /* . */) ||
17667 this.regexp_eatReverseSolidusAtomEscape(state) ||
17668 this.regexp_eatCharacterClass(state) ||
17669 this.regexp_eatUncapturingGroup(state) ||
17670 this.regexp_eatCapturingGroup(state) ||
17671 this.regexp_eatInvalidBracedQuantifier(state) ||
17672 this.regexp_eatExtendedPatternCharacter(state)
17673 )
17674};
17675
17676// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
17677pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
17678 if (this.regexp_eatBracedQuantifier(state, true)) {
17679 state.raise("Nothing to repeat");
17680 }
17681 return false
17682};
17683
17684// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
17685pp$8.regexp_eatSyntaxCharacter = function(state) {
17686 var ch = state.current();
17687 if (isSyntaxCharacter(ch)) {
17688 state.lastIntValue = ch;
17689 state.advance();
17690 return true
17691 }
17692 return false
17693};
17694function isSyntaxCharacter(ch) {
17695 return (
17696 ch === 0x24 /* $ */ ||
17697 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
17698 ch === 0x2E /* . */ ||
17699 ch === 0x3F /* ? */ ||
17700 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
17701 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
17702 )
17703}
17704
17705// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
17706// But eat eager.
17707pp$8.regexp_eatPatternCharacters = function(state) {
17708 var start = state.pos;
17709 var ch = 0;
17710 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
17711 state.advance();
17712 }
17713 return state.pos !== start
17714};
17715
17716// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
17717pp$8.regexp_eatExtendedPatternCharacter = function(state) {
17718 var ch = state.current();
17719 if (
17720 ch !== -1 &&
17721 ch !== 0x24 /* $ */ &&
17722 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
17723 ch !== 0x2E /* . */ &&
17724 ch !== 0x3F /* ? */ &&
17725 ch !== 0x5B /* [ */ &&
17726 ch !== 0x5E /* ^ */ &&
17727 ch !== 0x7C /* | */
17728 ) {
17729 state.advance();
17730 return true
17731 }
17732 return false
17733};
17734
17735// GroupSpecifier ::
17736// [empty]
17737// `?` GroupName
17738pp$8.regexp_groupSpecifier = function(state) {
17739 if (state.eat(0x3F /* ? */)) {
17740 if (this.regexp_eatGroupName(state)) {
17741 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
17742 state.raise("Duplicate capture group name");
17743 }
17744 state.groupNames.push(state.lastStringValue);
17745 return
17746 }
17747 state.raise("Invalid group");
17748 }
17749};
17750
17751// GroupName ::
17752// `<` RegExpIdentifierName `>`
17753// Note: this updates `state.lastStringValue` property with the eaten name.
17754pp$8.regexp_eatGroupName = function(state) {
17755 state.lastStringValue = "";
17756 if (state.eat(0x3C /* < */)) {
17757 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
17758 return true
17759 }
17760 state.raise("Invalid capture group name");
17761 }
17762 return false
17763};
17764
17765// RegExpIdentifierName ::
17766// RegExpIdentifierStart
17767// RegExpIdentifierName RegExpIdentifierPart
17768// Note: this updates `state.lastStringValue` property with the eaten name.
17769pp$8.regexp_eatRegExpIdentifierName = function(state) {
17770 state.lastStringValue = "";
17771 if (this.regexp_eatRegExpIdentifierStart(state)) {
17772 state.lastStringValue += codePointToString(state.lastIntValue);
17773 while (this.regexp_eatRegExpIdentifierPart(state)) {
17774 state.lastStringValue += codePointToString(state.lastIntValue);
17775 }
17776 return true
17777 }
17778 return false
17779};
17780
17781// RegExpIdentifierStart ::
17782// UnicodeIDStart
17783// `$`
17784// `_`
17785// `\` RegExpUnicodeEscapeSequence[+U]
17786pp$8.regexp_eatRegExpIdentifierStart = function(state) {
17787 var start = state.pos;
17788 var forceU = this.options.ecmaVersion >= 11;
17789 var ch = state.current(forceU);
17790 state.advance(forceU);
17791
17792 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
17793 ch = state.lastIntValue;
17794 }
17795 if (isRegExpIdentifierStart(ch)) {
17796 state.lastIntValue = ch;
17797 return true
17798 }
17799
17800 state.pos = start;
17801 return false
17802};
17803function isRegExpIdentifierStart(ch) {
17804 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
17805}
17806
17807// RegExpIdentifierPart ::
17808// UnicodeIDContinue
17809// `$`
17810// `_`
17811// `\` RegExpUnicodeEscapeSequence[+U]
17812// <ZWNJ>
17813// <ZWJ>
17814pp$8.regexp_eatRegExpIdentifierPart = function(state) {
17815 var start = state.pos;
17816 var forceU = this.options.ecmaVersion >= 11;
17817 var ch = state.current(forceU);
17818 state.advance(forceU);
17819
17820 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
17821 ch = state.lastIntValue;
17822 }
17823 if (isRegExpIdentifierPart(ch)) {
17824 state.lastIntValue = ch;
17825 return true
17826 }
17827
17828 state.pos = start;
17829 return false
17830};
17831function isRegExpIdentifierPart(ch) {
17832 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
17833}
17834
17835// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
17836pp$8.regexp_eatAtomEscape = function(state) {
17837 if (
17838 this.regexp_eatBackReference(state) ||
17839 this.regexp_eatCharacterClassEscape(state) ||
17840 this.regexp_eatCharacterEscape(state) ||
17841 (state.switchN && this.regexp_eatKGroupName(state))
17842 ) {
17843 return true
17844 }
17845 if (state.switchU) {
17846 // Make the same message as V8.
17847 if (state.current() === 0x63 /* c */) {
17848 state.raise("Invalid unicode escape");
17849 }
17850 state.raise("Invalid escape");
17851 }
17852 return false
17853};
17854pp$8.regexp_eatBackReference = function(state) {
17855 var start = state.pos;
17856 if (this.regexp_eatDecimalEscape(state)) {
17857 var n = state.lastIntValue;
17858 if (state.switchU) {
17859 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
17860 if (n > state.maxBackReference) {
17861 state.maxBackReference = n;
17862 }
17863 return true
17864 }
17865 if (n <= state.numCapturingParens) {
17866 return true
17867 }
17868 state.pos = start;
17869 }
17870 return false
17871};
17872pp$8.regexp_eatKGroupName = function(state) {
17873 if (state.eat(0x6B /* k */)) {
17874 if (this.regexp_eatGroupName(state)) {
17875 state.backReferenceNames.push(state.lastStringValue);
17876 return true
17877 }
17878 state.raise("Invalid named reference");
17879 }
17880 return false
17881};
17882
17883// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
17884pp$8.regexp_eatCharacterEscape = function(state) {
17885 return (
17886 this.regexp_eatControlEscape(state) ||
17887 this.regexp_eatCControlLetter(state) ||
17888 this.regexp_eatZero(state) ||
17889 this.regexp_eatHexEscapeSequence(state) ||
17890 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
17891 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
17892 this.regexp_eatIdentityEscape(state)
17893 )
17894};
17895pp$8.regexp_eatCControlLetter = function(state) {
17896 var start = state.pos;
17897 if (state.eat(0x63 /* c */)) {
17898 if (this.regexp_eatControlLetter(state)) {
17899 return true
17900 }
17901 state.pos = start;
17902 }
17903 return false
17904};
17905pp$8.regexp_eatZero = function(state) {
17906 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
17907 state.lastIntValue = 0;
17908 state.advance();
17909 return true
17910 }
17911 return false
17912};
17913
17914// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
17915pp$8.regexp_eatControlEscape = function(state) {
17916 var ch = state.current();
17917 if (ch === 0x74 /* t */) {
17918 state.lastIntValue = 0x09; /* \t */
17919 state.advance();
17920 return true
17921 }
17922 if (ch === 0x6E /* n */) {
17923 state.lastIntValue = 0x0A; /* \n */
17924 state.advance();
17925 return true
17926 }
17927 if (ch === 0x76 /* v */) {
17928 state.lastIntValue = 0x0B; /* \v */
17929 state.advance();
17930 return true
17931 }
17932 if (ch === 0x66 /* f */) {
17933 state.lastIntValue = 0x0C; /* \f */
17934 state.advance();
17935 return true
17936 }
17937 if (ch === 0x72 /* r */) {
17938 state.lastIntValue = 0x0D; /* \r */
17939 state.advance();
17940 return true
17941 }
17942 return false
17943};
17944
17945// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
17946pp$8.regexp_eatControlLetter = function(state) {
17947 var ch = state.current();
17948 if (isControlLetter(ch)) {
17949 state.lastIntValue = ch % 0x20;
17950 state.advance();
17951 return true
17952 }
17953 return false
17954};
17955function isControlLetter(ch) {
17956 return (
17957 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
17958 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
17959 )
17960}
17961
17962// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
17963pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
17964 if ( forceU === void 0 ) forceU = false;
17965
17966 var start = state.pos;
17967 var switchU = forceU || state.switchU;
17968
17969 if (state.eat(0x75 /* u */)) {
17970 if (this.regexp_eatFixedHexDigits(state, 4)) {
17971 var lead = state.lastIntValue;
17972 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
17973 var leadSurrogateEnd = state.pos;
17974 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
17975 var trail = state.lastIntValue;
17976 if (trail >= 0xDC00 && trail <= 0xDFFF) {
17977 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
17978 return true
17979 }
17980 }
17981 state.pos = leadSurrogateEnd;
17982 state.lastIntValue = lead;
17983 }
17984 return true
17985 }
17986 if (
17987 switchU &&
17988 state.eat(0x7B /* { */) &&
17989 this.regexp_eatHexDigits(state) &&
17990 state.eat(0x7D /* } */) &&
17991 isValidUnicode(state.lastIntValue)
17992 ) {
17993 return true
17994 }
17995 if (switchU) {
17996 state.raise("Invalid unicode escape");
17997 }
17998 state.pos = start;
17999 }
18000
18001 return false
18002};
18003function isValidUnicode(ch) {
18004 return ch >= 0 && ch <= 0x10FFFF
18005}
18006
18007// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
18008pp$8.regexp_eatIdentityEscape = function(state) {
18009 if (state.switchU) {
18010 if (this.regexp_eatSyntaxCharacter(state)) {
18011 return true
18012 }
18013 if (state.eat(0x2F /* / */)) {
18014 state.lastIntValue = 0x2F; /* / */
18015 return true
18016 }
18017 return false
18018 }
18019
18020 var ch = state.current();
18021 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
18022 state.lastIntValue = ch;
18023 state.advance();
18024 return true
18025 }
18026
18027 return false
18028};
18029
18030// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
18031pp$8.regexp_eatDecimalEscape = function(state) {
18032 state.lastIntValue = 0;
18033 var ch = state.current();
18034 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
18035 do {
18036 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
18037 state.advance();
18038 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
18039 return true
18040 }
18041 return false
18042};
18043
18044// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
18045pp$8.regexp_eatCharacterClassEscape = function(state) {
18046 var ch = state.current();
18047
18048 if (isCharacterClassEscape(ch)) {
18049 state.lastIntValue = -1;
18050 state.advance();
18051 return true
18052 }
18053
18054 if (
18055 state.switchU &&
18056 this.options.ecmaVersion >= 9 &&
18057 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
18058 ) {
18059 state.lastIntValue = -1;
18060 state.advance();
18061 if (
18062 state.eat(0x7B /* { */) &&
18063 this.regexp_eatUnicodePropertyValueExpression(state) &&
18064 state.eat(0x7D /* } */)
18065 ) {
18066 return true
18067 }
18068 state.raise("Invalid property name");
18069 }
18070
18071 return false
18072};
18073function isCharacterClassEscape(ch) {
18074 return (
18075 ch === 0x64 /* d */ ||
18076 ch === 0x44 /* D */ ||
18077 ch === 0x73 /* s */ ||
18078 ch === 0x53 /* S */ ||
18079 ch === 0x77 /* w */ ||
18080 ch === 0x57 /* W */
18081 )
18082}
18083
18084// UnicodePropertyValueExpression ::
18085// UnicodePropertyName `=` UnicodePropertyValue
18086// LoneUnicodePropertyNameOrValue
18087pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
18088 var start = state.pos;
18089
18090 // UnicodePropertyName `=` UnicodePropertyValue
18091 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
18092 var name = state.lastStringValue;
18093 if (this.regexp_eatUnicodePropertyValue(state)) {
18094 var value = state.lastStringValue;
18095 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
18096 return true
18097 }
18098 }
18099 state.pos = start;
18100
18101 // LoneUnicodePropertyNameOrValue
18102 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
18103 var nameOrValue = state.lastStringValue;
18104 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
18105 return true
18106 }
18107 return false
18108};
18109pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
18110 if (!has(state.unicodeProperties.nonBinary, name))
18111 { state.raise("Invalid property name"); }
18112 if (!state.unicodeProperties.nonBinary[name].test(value))
18113 { state.raise("Invalid property value"); }
18114};
18115pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
18116 if (!state.unicodeProperties.binary.test(nameOrValue))
18117 { state.raise("Invalid property name"); }
18118};
18119
18120// UnicodePropertyName ::
18121// UnicodePropertyNameCharacters
18122pp$8.regexp_eatUnicodePropertyName = function(state) {
18123 var ch = 0;
18124 state.lastStringValue = "";
18125 while (isUnicodePropertyNameCharacter(ch = state.current())) {
18126 state.lastStringValue += codePointToString(ch);
18127 state.advance();
18128 }
18129 return state.lastStringValue !== ""
18130};
18131function isUnicodePropertyNameCharacter(ch) {
18132 return isControlLetter(ch) || ch === 0x5F /* _ */
18133}
18134
18135// UnicodePropertyValue ::
18136// UnicodePropertyValueCharacters
18137pp$8.regexp_eatUnicodePropertyValue = function(state) {
18138 var ch = 0;
18139 state.lastStringValue = "";
18140 while (isUnicodePropertyValueCharacter(ch = state.current())) {
18141 state.lastStringValue += codePointToString(ch);
18142 state.advance();
18143 }
18144 return state.lastStringValue !== ""
18145};
18146function isUnicodePropertyValueCharacter(ch) {
18147 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
18148}
18149
18150// LoneUnicodePropertyNameOrValue ::
18151// UnicodePropertyValueCharacters
18152pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
18153 return this.regexp_eatUnicodePropertyValue(state)
18154};
18155
18156// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
18157pp$8.regexp_eatCharacterClass = function(state) {
18158 if (state.eat(0x5B /* [ */)) {
18159 state.eat(0x5E /* ^ */);
18160 this.regexp_classRanges(state);
18161 if (state.eat(0x5D /* ] */)) {
18162 return true
18163 }
18164 // Unreachable since it threw "unterminated regular expression" error before.
18165 state.raise("Unterminated character class");
18166 }
18167 return false
18168};
18169
18170// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
18171// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
18172// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
18173pp$8.regexp_classRanges = function(state) {
18174 while (this.regexp_eatClassAtom(state)) {
18175 var left = state.lastIntValue;
18176 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
18177 var right = state.lastIntValue;
18178 if (state.switchU && (left === -1 || right === -1)) {
18179 state.raise("Invalid character class");
18180 }
18181 if (left !== -1 && right !== -1 && left > right) {
18182 state.raise("Range out of order in character class");
18183 }
18184 }
18185 }
18186};
18187
18188// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
18189// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
18190pp$8.regexp_eatClassAtom = function(state) {
18191 var start = state.pos;
18192
18193 if (state.eat(0x5C /* \ */)) {
18194 if (this.regexp_eatClassEscape(state)) {
18195 return true
18196 }
18197 if (state.switchU) {
18198 // Make the same message as V8.
18199 var ch$1 = state.current();
18200 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
18201 state.raise("Invalid class escape");
18202 }
18203 state.raise("Invalid escape");
18204 }
18205 state.pos = start;
18206 }
18207
18208 var ch = state.current();
18209 if (ch !== 0x5D /* ] */) {
18210 state.lastIntValue = ch;
18211 state.advance();
18212 return true
18213 }
18214
18215 return false
18216};
18217
18218// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
18219pp$8.regexp_eatClassEscape = function(state) {
18220 var start = state.pos;
18221
18222 if (state.eat(0x62 /* b */)) {
18223 state.lastIntValue = 0x08; /* <BS> */
18224 return true
18225 }
18226
18227 if (state.switchU && state.eat(0x2D /* - */)) {
18228 state.lastIntValue = 0x2D; /* - */
18229 return true
18230 }
18231
18232 if (!state.switchU && state.eat(0x63 /* c */)) {
18233 if (this.regexp_eatClassControlLetter(state)) {
18234 return true
18235 }
18236 state.pos = start;
18237 }
18238
18239 return (
18240 this.regexp_eatCharacterClassEscape(state) ||
18241 this.regexp_eatCharacterEscape(state)
18242 )
18243};
18244
18245// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
18246pp$8.regexp_eatClassControlLetter = function(state) {
18247 var ch = state.current();
18248 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
18249 state.lastIntValue = ch % 0x20;
18250 state.advance();
18251 return true
18252 }
18253 return false
18254};
18255
18256// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
18257pp$8.regexp_eatHexEscapeSequence = function(state) {
18258 var start = state.pos;
18259 if (state.eat(0x78 /* x */)) {
18260 if (this.regexp_eatFixedHexDigits(state, 2)) {
18261 return true
18262 }
18263 if (state.switchU) {
18264 state.raise("Invalid escape");
18265 }
18266 state.pos = start;
18267 }
18268 return false
18269};
18270
18271// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
18272pp$8.regexp_eatDecimalDigits = function(state) {
18273 var start = state.pos;
18274 var ch = 0;
18275 state.lastIntValue = 0;
18276 while (isDecimalDigit(ch = state.current())) {
18277 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
18278 state.advance();
18279 }
18280 return state.pos !== start
18281};
18282function isDecimalDigit(ch) {
18283 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
18284}
18285
18286// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
18287pp$8.regexp_eatHexDigits = function(state) {
18288 var start = state.pos;
18289 var ch = 0;
18290 state.lastIntValue = 0;
18291 while (isHexDigit(ch = state.current())) {
18292 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
18293 state.advance();
18294 }
18295 return state.pos !== start
18296};
18297function isHexDigit(ch) {
18298 return (
18299 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
18300 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
18301 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
18302 )
18303}
18304function hexToInt(ch) {
18305 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
18306 return 10 + (ch - 0x41 /* A */)
18307 }
18308 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
18309 return 10 + (ch - 0x61 /* a */)
18310 }
18311 return ch - 0x30 /* 0 */
18312}
18313
18314// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
18315// Allows only 0-377(octal) i.e. 0-255(decimal).
18316pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
18317 if (this.regexp_eatOctalDigit(state)) {
18318 var n1 = state.lastIntValue;
18319 if (this.regexp_eatOctalDigit(state)) {
18320 var n2 = state.lastIntValue;
18321 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
18322 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
18323 } else {
18324 state.lastIntValue = n1 * 8 + n2;
18325 }
18326 } else {
18327 state.lastIntValue = n1;
18328 }
18329 return true
18330 }
18331 return false
18332};
18333
18334// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
18335pp$8.regexp_eatOctalDigit = function(state) {
18336 var ch = state.current();
18337 if (isOctalDigit(ch)) {
18338 state.lastIntValue = ch - 0x30; /* 0 */
18339 state.advance();
18340 return true
18341 }
18342 state.lastIntValue = 0;
18343 return false
18344};
18345function isOctalDigit(ch) {
18346 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
18347}
18348
18349// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
18350// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
18351// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
18352pp$8.regexp_eatFixedHexDigits = function(state, length) {
18353 var start = state.pos;
18354 state.lastIntValue = 0;
18355 for (var i = 0; i < length; ++i) {
18356 var ch = state.current();
18357 if (!isHexDigit(ch)) {
18358 state.pos = start;
18359 return false
18360 }
18361 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
18362 state.advance();
18363 }
18364 return true
18365};
18366
18367// Object type used to represent tokens. Note that normally, tokens
18368// simply exist as properties on the parser object. This is only
18369// used for the onToken callback and the external tokenizer.
18370
18371var Token = function Token(p) {
18372 this.type = p.type;
18373 this.value = p.value;
18374 this.start = p.start;
18375 this.end = p.end;
18376 if (p.options.locations)
18377 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
18378 if (p.options.ranges)
18379 { this.range = [p.start, p.end]; }
18380};
18381
18382// ## Tokenizer
18383
18384var pp$9 = Parser.prototype;
18385
18386// Move to the next token
18387
18388pp$9.next = function(ignoreEscapeSequenceInKeyword) {
18389 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
18390 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
18391 if (this.options.onToken)
18392 { this.options.onToken(new Token(this)); }
18393
18394 this.lastTokEnd = this.end;
18395 this.lastTokStart = this.start;
18396 this.lastTokEndLoc = this.endLoc;
18397 this.lastTokStartLoc = this.startLoc;
18398 this.nextToken();
18399};
18400
18401pp$9.getToken = function() {
18402 this.next();
18403 return new Token(this)
18404};
18405
18406// If we're in an ES6 environment, make parsers iterable
18407if (typeof Symbol !== "undefined")
18408 { pp$9[Symbol.iterator] = function() {
18409 var this$1$1 = this;
18410
18411 return {
18412 next: function () {
18413 var token = this$1$1.getToken();
18414 return {
18415 done: token.type === types.eof,
18416 value: token
18417 }
18418 }
18419 }
18420 }; }
18421
18422// Toggle strict mode. Re-reads the next number or string to please
18423// pedantic tests (`"use strict"; 010;` should fail).
18424
18425pp$9.curContext = function() {
18426 return this.context[this.context.length - 1]
18427};
18428
18429// Read a single token, updating the parser object's token-related
18430// properties.
18431
18432pp$9.nextToken = function() {
18433 var curContext = this.curContext();
18434 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
18435
18436 this.start = this.pos;
18437 if (this.options.locations) { this.startLoc = this.curPosition(); }
18438 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
18439
18440 if (curContext.override) { return curContext.override(this) }
18441 else { this.readToken(this.fullCharCodeAtPos()); }
18442};
18443
18444pp$9.readToken = function(code) {
18445 // Identifier or keyword. '\uXXXX' sequences are allowed in
18446 // identifiers, so '\' also dispatches to that.
18447 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
18448 { return this.readWord() }
18449
18450 return this.getTokenFromCode(code)
18451};
18452
18453pp$9.fullCharCodeAtPos = function() {
18454 var code = this.input.charCodeAt(this.pos);
18455 if (code <= 0xd7ff || code >= 0xdc00) { return code }
18456 var next = this.input.charCodeAt(this.pos + 1);
18457 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
18458};
18459
18460pp$9.skipBlockComment = function() {
18461 var startLoc = this.options.onComment && this.curPosition();
18462 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
18463 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
18464 this.pos = end + 2;
18465 if (this.options.locations) {
18466 lineBreakG.lastIndex = start;
18467 var match;
18468 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
18469 ++this.curLine;
18470 this.lineStart = match.index + match[0].length;
18471 }
18472 }
18473 if (this.options.onComment)
18474 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
18475 startLoc, this.curPosition()); }
18476};
18477
18478pp$9.skipLineComment = function(startSkip) {
18479 var start = this.pos;
18480 var startLoc = this.options.onComment && this.curPosition();
18481 var ch = this.input.charCodeAt(this.pos += startSkip);
18482 while (this.pos < this.input.length && !isNewLine(ch)) {
18483 ch = this.input.charCodeAt(++this.pos);
18484 }
18485 if (this.options.onComment)
18486 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
18487 startLoc, this.curPosition()); }
18488};
18489
18490// Called at the start of the parse and after every token. Skips
18491// whitespace and comments, and.
18492
18493pp$9.skipSpace = function() {
18494 loop: while (this.pos < this.input.length) {
18495 var ch = this.input.charCodeAt(this.pos);
18496 switch (ch) {
18497 case 32: case 160: // ' '
18498 ++this.pos;
18499 break
18500 case 13:
18501 if (this.input.charCodeAt(this.pos + 1) === 10) {
18502 ++this.pos;
18503 }
18504 case 10: case 8232: case 8233:
18505 ++this.pos;
18506 if (this.options.locations) {
18507 ++this.curLine;
18508 this.lineStart = this.pos;
18509 }
18510 break
18511 case 47: // '/'
18512 switch (this.input.charCodeAt(this.pos + 1)) {
18513 case 42: // '*'
18514 this.skipBlockComment();
18515 break
18516 case 47:
18517 this.skipLineComment(2);
18518 break
18519 default:
18520 break loop
18521 }
18522 break
18523 default:
18524 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
18525 ++this.pos;
18526 } else {
18527 break loop
18528 }
18529 }
18530 }
18531};
18532
18533// Called at the end of every token. Sets `end`, `val`, and
18534// maintains `context` and `exprAllowed`, and skips the space after
18535// the token, so that the next one's `start` will point at the
18536// right position.
18537
18538pp$9.finishToken = function(type, val) {
18539 this.end = this.pos;
18540 if (this.options.locations) { this.endLoc = this.curPosition(); }
18541 var prevType = this.type;
18542 this.type = type;
18543 this.value = val;
18544
18545 this.updateContext(prevType);
18546};
18547
18548// ### Token reading
18549
18550// This is the function that is called to fetch the next token. It
18551// is somewhat obscure, because it works in character codes rather
18552// than characters, and because operator parsing has been inlined
18553// into it.
18554//
18555// All in the name of speed.
18556//
18557pp$9.readToken_dot = function() {
18558 var next = this.input.charCodeAt(this.pos + 1);
18559 if (next >= 48 && next <= 57) { return this.readNumber(true) }
18560 var next2 = this.input.charCodeAt(this.pos + 2);
18561 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
18562 this.pos += 3;
18563 return this.finishToken(types.ellipsis)
18564 } else {
18565 ++this.pos;
18566 return this.finishToken(types.dot)
18567 }
18568};
18569
18570pp$9.readToken_slash = function() { // '/'
18571 var next = this.input.charCodeAt(this.pos + 1);
18572 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
18573 if (next === 61) { return this.finishOp(types.assign, 2) }
18574 return this.finishOp(types.slash, 1)
18575};
18576
18577pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
18578 var next = this.input.charCodeAt(this.pos + 1);
18579 var size = 1;
18580 var tokentype = code === 42 ? types.star : types.modulo;
18581
18582 // exponentiation operator ** and **=
18583 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
18584 ++size;
18585 tokentype = types.starstar;
18586 next = this.input.charCodeAt(this.pos + 2);
18587 }
18588
18589 if (next === 61) { return this.finishOp(types.assign, size + 1) }
18590 return this.finishOp(tokentype, size)
18591};
18592
18593pp$9.readToken_pipe_amp = function(code) { // '|&'
18594 var next = this.input.charCodeAt(this.pos + 1);
18595 if (next === code) {
18596 if (this.options.ecmaVersion >= 12) {
18597 var next2 = this.input.charCodeAt(this.pos + 2);
18598 if (next2 === 61) { return this.finishOp(types.assign, 3) }
18599 }
18600 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
18601 }
18602 if (next === 61) { return this.finishOp(types.assign, 2) }
18603 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
18604};
18605
18606pp$9.readToken_caret = function() { // '^'
18607 var next = this.input.charCodeAt(this.pos + 1);
18608 if (next === 61) { return this.finishOp(types.assign, 2) }
18609 return this.finishOp(types.bitwiseXOR, 1)
18610};
18611
18612pp$9.readToken_plus_min = function(code) { // '+-'
18613 var next = this.input.charCodeAt(this.pos + 1);
18614 if (next === code) {
18615 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
18616 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
18617 // A `-->` line comment
18618 this.skipLineComment(3);
18619 this.skipSpace();
18620 return this.nextToken()
18621 }
18622 return this.finishOp(types.incDec, 2)
18623 }
18624 if (next === 61) { return this.finishOp(types.assign, 2) }
18625 return this.finishOp(types.plusMin, 1)
18626};
18627
18628pp$9.readToken_lt_gt = function(code) { // '<>'
18629 var next = this.input.charCodeAt(this.pos + 1);
18630 var size = 1;
18631 if (next === code) {
18632 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
18633 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
18634 return this.finishOp(types.bitShift, size)
18635 }
18636 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
18637 this.input.charCodeAt(this.pos + 3) === 45) {
18638 // `<!--`, an XML-style comment that should be interpreted as a line comment
18639 this.skipLineComment(4);
18640 this.skipSpace();
18641 return this.nextToken()
18642 }
18643 if (next === 61) { size = 2; }
18644 return this.finishOp(types.relational, size)
18645};
18646
18647pp$9.readToken_eq_excl = function(code) { // '=!'
18648 var next = this.input.charCodeAt(this.pos + 1);
18649 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
18650 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
18651 this.pos += 2;
18652 return this.finishToken(types.arrow)
18653 }
18654 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
18655};
18656
18657pp$9.readToken_question = function() { // '?'
18658 var ecmaVersion = this.options.ecmaVersion;
18659 if (ecmaVersion >= 11) {
18660 var next = this.input.charCodeAt(this.pos + 1);
18661 if (next === 46) {
18662 var next2 = this.input.charCodeAt(this.pos + 2);
18663 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
18664 }
18665 if (next === 63) {
18666 if (ecmaVersion >= 12) {
18667 var next2$1 = this.input.charCodeAt(this.pos + 2);
18668 if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
18669 }
18670 return this.finishOp(types.coalesce, 2)
18671 }
18672 }
18673 return this.finishOp(types.question, 1)
18674};
18675
18676pp$9.readToken_numberSign = function() { // '#'
18677 var ecmaVersion = this.options.ecmaVersion;
18678 var code = 35; // '#'
18679 if (ecmaVersion >= 13) {
18680 ++this.pos;
18681 code = this.fullCharCodeAtPos();
18682 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
18683 return this.finishToken(types.privateId, this.readWord1())
18684 }
18685 }
18686
18687 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
18688};
18689
18690pp$9.getTokenFromCode = function(code) {
18691 switch (code) {
18692 // The interpretation of a dot depends on whether it is followed
18693 // by a digit or another two dots.
18694 case 46: // '.'
18695 return this.readToken_dot()
18696
18697 // Punctuation tokens.
18698 case 40: ++this.pos; return this.finishToken(types.parenL)
18699 case 41: ++this.pos; return this.finishToken(types.parenR)
18700 case 59: ++this.pos; return this.finishToken(types.semi)
18701 case 44: ++this.pos; return this.finishToken(types.comma)
18702 case 91: ++this.pos; return this.finishToken(types.bracketL)
18703 case 93: ++this.pos; return this.finishToken(types.bracketR)
18704 case 123: ++this.pos; return this.finishToken(types.braceL)
18705 case 125: ++this.pos; return this.finishToken(types.braceR)
18706 case 58: ++this.pos; return this.finishToken(types.colon)
18707
18708 case 96: // '`'
18709 if (this.options.ecmaVersion < 6) { break }
18710 ++this.pos;
18711 return this.finishToken(types.backQuote)
18712
18713 case 48: // '0'
18714 var next = this.input.charCodeAt(this.pos + 1);
18715 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
18716 if (this.options.ecmaVersion >= 6) {
18717 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
18718 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
18719 }
18720
18721 // Anything else beginning with a digit is an integer, octal
18722 // number, or float.
18723 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
18724 return this.readNumber(false)
18725
18726 // Quotes produce strings.
18727 case 34: case 39: // '"', "'"
18728 return this.readString(code)
18729
18730 // Operators are parsed inline in tiny state machines. '=' (61) is
18731 // often referred to. `finishOp` simply skips the amount of
18732 // characters it is given as second argument, and returns a token
18733 // of the type given by its first argument.
18734
18735 case 47: // '/'
18736 return this.readToken_slash()
18737
18738 case 37: case 42: // '%*'
18739 return this.readToken_mult_modulo_exp(code)
18740
18741 case 124: case 38: // '|&'
18742 return this.readToken_pipe_amp(code)
18743
18744 case 94: // '^'
18745 return this.readToken_caret()
18746
18747 case 43: case 45: // '+-'
18748 return this.readToken_plus_min(code)
18749
18750 case 60: case 62: // '<>'
18751 return this.readToken_lt_gt(code)
18752
18753 case 61: case 33: // '=!'
18754 return this.readToken_eq_excl(code)
18755
18756 case 63: // '?'
18757 return this.readToken_question()
18758
18759 case 126: // '~'
18760 return this.finishOp(types.prefix, 1)
18761
18762 case 35: // '#'
18763 return this.readToken_numberSign()
18764 }
18765
18766 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
18767};
18768
18769pp$9.finishOp = function(type, size) {
18770 var str = this.input.slice(this.pos, this.pos + size);
18771 this.pos += size;
18772 return this.finishToken(type, str)
18773};
18774
18775pp$9.readRegexp = function() {
18776 var escaped, inClass, start = this.pos;
18777 for (;;) {
18778 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
18779 var ch = this.input.charAt(this.pos);
18780 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
18781 if (!escaped) {
18782 if (ch === "[") { inClass = true; }
18783 else if (ch === "]" && inClass) { inClass = false; }
18784 else if (ch === "/" && !inClass) { break }
18785 escaped = ch === "\\";
18786 } else { escaped = false; }
18787 ++this.pos;
18788 }
18789 var pattern = this.input.slice(start, this.pos);
18790 ++this.pos;
18791 var flagsStart = this.pos;
18792 var flags = this.readWord1();
18793 if (this.containsEsc) { this.unexpected(flagsStart); }
18794
18795 // Validate pattern
18796 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
18797 state.reset(start, pattern, flags);
18798 this.validateRegExpFlags(state);
18799 this.validateRegExpPattern(state);
18800
18801 // Create Literal#value property value.
18802 var value = null;
18803 try {
18804 value = new RegExp(pattern, flags);
18805 } catch (e) {
18806 // ESTree requires null if it failed to instantiate RegExp object.
18807 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
18808 }
18809
18810 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
18811};
18812
18813// Read an integer in the given radix. Return null if zero digits
18814// were read, the integer value otherwise. When `len` is given, this
18815// will return `null` unless the integer has exactly `len` digits.
18816
18817pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
18818 // `len` is used for character escape sequences. In that case, disallow separators.
18819 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
18820
18821 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
18822 // and isn't fraction part nor exponent part. In that case, if the first digit
18823 // is zero then disallow separators.
18824 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
18825
18826 var start = this.pos, total = 0, lastCode = 0;
18827 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
18828 var code = this.input.charCodeAt(this.pos), val = (void 0);
18829
18830 if (allowSeparators && code === 95) {
18831 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
18832 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
18833 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
18834 lastCode = code;
18835 continue
18836 }
18837
18838 if (code >= 97) { val = code - 97 + 10; } // a
18839 else if (code >= 65) { val = code - 65 + 10; } // A
18840 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
18841 else { val = Infinity; }
18842 if (val >= radix) { break }
18843 lastCode = code;
18844 total = total * radix + val;
18845 }
18846
18847 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
18848 if (this.pos === start || len != null && this.pos - start !== len) { return null }
18849
18850 return total
18851};
18852
18853function stringToNumber(str, isLegacyOctalNumericLiteral) {
18854 if (isLegacyOctalNumericLiteral) {
18855 return parseInt(str, 8)
18856 }
18857
18858 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
18859 return parseFloat(str.replace(/_/g, ""))
18860}
18861
18862function stringToBigInt(str) {
18863 if (typeof BigInt !== "function") {
18864 return null
18865 }
18866
18867 // `BigInt(value)` throws syntax error if the string contains numeric separators.
18868 return BigInt(str.replace(/_/g, ""))
18869}
18870
18871pp$9.readRadixNumber = function(radix) {
18872 var start = this.pos;
18873 this.pos += 2; // 0x
18874 var val = this.readInt(radix);
18875 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
18876 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
18877 val = stringToBigInt(this.input.slice(start, this.pos));
18878 ++this.pos;
18879 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
18880 return this.finishToken(types.num, val)
18881};
18882
18883// Read an integer, octal integer, or floating-point number.
18884
18885pp$9.readNumber = function(startsWithDot) {
18886 var start = this.pos;
18887 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
18888 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
18889 if (octal && this.strict) { this.raise(start, "Invalid number"); }
18890 var next = this.input.charCodeAt(this.pos);
18891 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
18892 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
18893 ++this.pos;
18894 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
18895 return this.finishToken(types.num, val$1)
18896 }
18897 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
18898 if (next === 46 && !octal) { // '.'
18899 ++this.pos;
18900 this.readInt(10);
18901 next = this.input.charCodeAt(this.pos);
18902 }
18903 if ((next === 69 || next === 101) && !octal) { // 'eE'
18904 next = this.input.charCodeAt(++this.pos);
18905 if (next === 43 || next === 45) { ++this.pos; } // '+-'
18906 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
18907 }
18908 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
18909
18910 var val = stringToNumber(this.input.slice(start, this.pos), octal);
18911 return this.finishToken(types.num, val)
18912};
18913
18914// Read a string value, interpreting backslash-escapes.
18915
18916pp$9.readCodePoint = function() {
18917 var ch = this.input.charCodeAt(this.pos), code;
18918
18919 if (ch === 123) { // '{'
18920 if (this.options.ecmaVersion < 6) { this.unexpected(); }
18921 var codePos = ++this.pos;
18922 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
18923 ++this.pos;
18924 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
18925 } else {
18926 code = this.readHexChar(4);
18927 }
18928 return code
18929};
18930
18931function codePointToString$1(code) {
18932 // UTF-16 Decoding
18933 if (code <= 0xFFFF) { return String.fromCharCode(code) }
18934 code -= 0x10000;
18935 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
18936}
18937
18938pp$9.readString = function(quote) {
18939 var out = "", chunkStart = ++this.pos;
18940 for (;;) {
18941 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
18942 var ch = this.input.charCodeAt(this.pos);
18943 if (ch === quote) { break }
18944 if (ch === 92) { // '\'
18945 out += this.input.slice(chunkStart, this.pos);
18946 out += this.readEscapedChar(false);
18947 chunkStart = this.pos;
18948 } else {
18949 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
18950 ++this.pos;
18951 }
18952 }
18953 out += this.input.slice(chunkStart, this.pos++);
18954 return this.finishToken(types.string, out)
18955};
18956
18957// Reads template string tokens.
18958
18959var INVALID_TEMPLATE_ESCAPE_ERROR = {};
18960
18961pp$9.tryReadTemplateToken = function() {
18962 this.inTemplateElement = true;
18963 try {
18964 this.readTmplToken();
18965 } catch (err) {
18966 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
18967 this.readInvalidTemplateToken();
18968 } else {
18969 throw err
18970 }
18971 }
18972
18973 this.inTemplateElement = false;
18974};
18975
18976pp$9.invalidStringToken = function(position, message) {
18977 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
18978 throw INVALID_TEMPLATE_ESCAPE_ERROR
18979 } else {
18980 this.raise(position, message);
18981 }
18982};
18983
18984pp$9.readTmplToken = function() {
18985 var out = "", chunkStart = this.pos;
18986 for (;;) {
18987 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
18988 var ch = this.input.charCodeAt(this.pos);
18989 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
18990 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
18991 if (ch === 36) {
18992 this.pos += 2;
18993 return this.finishToken(types.dollarBraceL)
18994 } else {
18995 ++this.pos;
18996 return this.finishToken(types.backQuote)
18997 }
18998 }
18999 out += this.input.slice(chunkStart, this.pos);
19000 return this.finishToken(types.template, out)
19001 }
19002 if (ch === 92) { // '\'
19003 out += this.input.slice(chunkStart, this.pos);
19004 out += this.readEscapedChar(true);
19005 chunkStart = this.pos;
19006 } else if (isNewLine(ch)) {
19007 out += this.input.slice(chunkStart, this.pos);
19008 ++this.pos;
19009 switch (ch) {
19010 case 13:
19011 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
19012 case 10:
19013 out += "\n";
19014 break
19015 default:
19016 out += String.fromCharCode(ch);
19017 break
19018 }
19019 if (this.options.locations) {
19020 ++this.curLine;
19021 this.lineStart = this.pos;
19022 }
19023 chunkStart = this.pos;
19024 } else {
19025 ++this.pos;
19026 }
19027 }
19028};
19029
19030// Reads a template token to search for the end, without validating any escape sequences
19031pp$9.readInvalidTemplateToken = function() {
19032 for (; this.pos < this.input.length; this.pos++) {
19033 switch (this.input[this.pos]) {
19034 case "\\":
19035 ++this.pos;
19036 break
19037
19038 case "$":
19039 if (this.input[this.pos + 1] !== "{") {
19040 break
19041 }
19042 // falls through
19043
19044 case "`":
19045 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
19046
19047 // no default
19048 }
19049 }
19050 this.raise(this.start, "Unterminated template");
19051};
19052
19053// Used to read escaped characters
19054
19055pp$9.readEscapedChar = function(inTemplate) {
19056 var ch = this.input.charCodeAt(++this.pos);
19057 ++this.pos;
19058 switch (ch) {
19059 case 110: return "\n" // 'n' -> '\n'
19060 case 114: return "\r" // 'r' -> '\r'
19061 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
19062 case 117: return codePointToString$1(this.readCodePoint()) // 'u'
19063 case 116: return "\t" // 't' -> '\t'
19064 case 98: return "\b" // 'b' -> '\b'
19065 case 118: return "\u000b" // 'v' -> '\u000b'
19066 case 102: return "\f" // 'f' -> '\f'
19067 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
19068 case 10: // ' \n'
19069 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
19070 return ""
19071 case 56:
19072 case 57:
19073 if (this.strict) {
19074 this.invalidStringToken(
19075 this.pos - 1,
19076 "Invalid escape sequence"
19077 );
19078 }
19079 if (inTemplate) {
19080 var codePos = this.pos - 1;
19081
19082 this.invalidStringToken(
19083 codePos,
19084 "Invalid escape sequence in template string"
19085 );
19086
19087 return null
19088 }
19089 default:
19090 if (ch >= 48 && ch <= 55) {
19091 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
19092 var octal = parseInt(octalStr, 8);
19093 if (octal > 255) {
19094 octalStr = octalStr.slice(0, -1);
19095 octal = parseInt(octalStr, 8);
19096 }
19097 this.pos += octalStr.length - 1;
19098 ch = this.input.charCodeAt(this.pos);
19099 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
19100 this.invalidStringToken(
19101 this.pos - 1 - octalStr.length,
19102 inTemplate
19103 ? "Octal literal in template string"
19104 : "Octal literal in strict mode"
19105 );
19106 }
19107 return String.fromCharCode(octal)
19108 }
19109 if (isNewLine(ch)) {
19110 // Unicode new line characters after \ get removed from output in both
19111 // template literals and strings
19112 return ""
19113 }
19114 return String.fromCharCode(ch)
19115 }
19116};
19117
19118// Used to read character escape sequences ('\x', '\u', '\U').
19119
19120pp$9.readHexChar = function(len) {
19121 var codePos = this.pos;
19122 var n = this.readInt(16, len);
19123 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
19124 return n
19125};
19126
19127// Read an identifier, and return it as a string. Sets `this.containsEsc`
19128// to whether the word contained a '\u' escape.
19129//
19130// Incrementally adds only escaped chars, adding other chunks as-is
19131// as a micro-optimization.
19132
19133pp$9.readWord1 = function() {
19134 this.containsEsc = false;
19135 var word = "", first = true, chunkStart = this.pos;
19136 var astral = this.options.ecmaVersion >= 6;
19137 while (this.pos < this.input.length) {
19138 var ch = this.fullCharCodeAtPos();
19139 if (isIdentifierChar(ch, astral)) {
19140 this.pos += ch <= 0xffff ? 1 : 2;
19141 } else if (ch === 92) { // "\"
19142 this.containsEsc = true;
19143 word += this.input.slice(chunkStart, this.pos);
19144 var escStart = this.pos;
19145 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
19146 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
19147 ++this.pos;
19148 var esc = this.readCodePoint();
19149 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
19150 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
19151 word += codePointToString$1(esc);
19152 chunkStart = this.pos;
19153 } else {
19154 break
19155 }
19156 first = false;
19157 }
19158 return word + this.input.slice(chunkStart, this.pos)
19159};
19160
19161// Read an identifier or keyword token. Will check for reserved
19162// words when necessary.
19163
19164pp$9.readWord = function() {
19165 var word = this.readWord1();
19166 var type = types.name;
19167 if (this.keywords.test(word)) {
19168 type = keywords$1[word];
19169 }
19170 return this.finishToken(type, word)
19171};
19172
19173// Acorn is a tiny, fast JavaScript parser written in JavaScript.
19174
19175var version = "8.4.0";
19176
19177Parser.acorn = {
19178 Parser: Parser,
19179 version: version,
19180 defaultOptions: defaultOptions,
19181 Position: Position,
19182 SourceLocation: SourceLocation,
19183 getLineInfo: getLineInfo,
19184 Node: Node,
19185 TokenType: TokenType,
19186 tokTypes: types,
19187 keywordTypes: keywords$1,
19188 TokContext: TokContext,
19189 tokContexts: types$1,
19190 isIdentifierChar: isIdentifierChar,
19191 isIdentifierStart: isIdentifierStart,
19192 Token: Token,
19193 isNewLine: isNewLine,
19194 lineBreak: lineBreak,
19195 lineBreakG: lineBreakG,
19196 nonASCIIwhitespace: nonASCIIwhitespace
19197};
19198
19199const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
19200function mkdirpath(path$1) {
19201 const dir = path.dirname(path$1);
19202 try {
19203 fs.readdirSync(dir);
19204 }
19205 catch (err) {
19206 mkdirpath(dir);
19207 try {
19208 fs.mkdirSync(dir);
19209 }
19210 catch (err2) {
19211 if (err2.code !== 'EEXIST') {
19212 throw err2;
19213 }
19214 }
19215 }
19216}
19217function writeFile(dest, data) {
19218 return new Promise((fulfil, reject) => {
19219 mkdirpath(dest);
19220 fs.writeFile(dest, data, err => {
19221 if (err) {
19222 reject(err);
19223 }
19224 else {
19225 fulfil();
19226 }
19227 });
19228 });
19229}
19230
19231class Queue {
19232 constructor(maxParallel = 1) {
19233 this.maxParallel = maxParallel;
19234 this.queue = new Array();
19235 this.workerCount = 0;
19236 }
19237 run(task) {
19238 return new Promise((resolve, reject) => {
19239 this.queue.push({ reject, resolve, task });
19240 this.work();
19241 });
19242 }
19243 async work() {
19244 if (this.workerCount >= this.maxParallel)
19245 return;
19246 this.workerCount++;
19247 let entry;
19248 while ((entry = this.queue.shift())) {
19249 const { reject, resolve, task } = entry;
19250 try {
19251 const result = await task();
19252 resolve(result);
19253 }
19254 catch (err) {
19255 reject(err);
19256 }
19257 }
19258 this.workerCount--;
19259 }
19260}
19261
19262function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
19263 let skipped = null;
19264 let replaceContext = null;
19265 if (skip) {
19266 skipped = new Set();
19267 for (const skippedCall of skip) {
19268 if (source === skippedCall.source && importer === skippedCall.importer) {
19269 skipped.add(skippedCall.plugin);
19270 }
19271 }
19272 replaceContext = (pluginContext, plugin) => ({
19273 ...pluginContext,
19274 resolve: (source, importer, { custom, skipSelf } = BLANK) => {
19275 return moduleLoaderResolveId(source, importer, custom, skipSelf ? [...skip, { importer, plugin, source }] : skip);
19276 }
19277 });
19278 }
19279 return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], replaceContext, skipped);
19280}
19281
19282async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
19283 const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions);
19284 if (pluginResult != null)
19285 return pluginResult;
19286 // external modules (non-entry modules that start with neither '.' or '/')
19287 // are skipped at this stage.
19288 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
19289 return null;
19290 // `resolve` processes paths from right to left, prepending them until an
19291 // absolute path is created. Absolute importees therefore shortcircuit the
19292 // resolve call and require no special handing on our part.
19293 // See https://nodejs.org/api/path.html#path_path_resolve_paths
19294 return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
19295}
19296function addJsExtensionIfNecessary(file, preserveSymlinks) {
19297 let found = findFile(file, preserveSymlinks);
19298 if (found)
19299 return found;
19300 found = findFile(file + '.mjs', preserveSymlinks);
19301 if (found)
19302 return found;
19303 found = findFile(file + '.js', preserveSymlinks);
19304 return found;
19305}
19306function findFile(file, preserveSymlinks) {
19307 try {
19308 const stats = fs.lstatSync(file);
19309 if (!preserveSymlinks && stats.isSymbolicLink())
19310 return findFile(fs.realpathSync(file), preserveSymlinks);
19311 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
19312 // check case
19313 const name = path.basename(file);
19314 const files = fs.readdirSync(path.dirname(file));
19315 if (files.indexOf(name) !== -1)
19316 return file;
19317 }
19318 }
19319 catch (_a) {
19320 // suppress
19321 }
19322}
19323
19324const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
19325const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
19326function throwPluginError(err, plugin, { hook, id } = {}) {
19327 if (typeof err === 'string')
19328 err = { message: err };
19329 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
19330 err.pluginCode = err.code;
19331 }
19332 err.code = Errors.PLUGIN_ERROR;
19333 err.plugin = plugin;
19334 if (hook) {
19335 err.hook = hook;
19336 }
19337 if (id) {
19338 err.id = id;
19339 }
19340 return error(err);
19341}
19342const deprecatedHooks = [
19343 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
19344];
19345function warnDeprecatedHooks(plugins, options) {
19346 for (const { active, deprecated, replacement } of deprecatedHooks) {
19347 for (const plugin of plugins) {
19348 if (deprecated in plugin) {
19349 warnDeprecation({
19350 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
19351 plugin: plugin.name
19352 }, active, options);
19353 }
19354 }
19355 }
19356}
19357
19358function createPluginCache(cache) {
19359 return {
19360 delete(id) {
19361 return delete cache[id];
19362 },
19363 get(id) {
19364 const item = cache[id];
19365 if (!item)
19366 return undefined;
19367 item[0] = 0;
19368 return item[1];
19369 },
19370 has(id) {
19371 const item = cache[id];
19372 if (!item)
19373 return false;
19374 item[0] = 0;
19375 return true;
19376 },
19377 set(id, value) {
19378 cache[id] = [0, value];
19379 }
19380 };
19381}
19382function getTrackedPluginCache(pluginCache, onUse) {
19383 return {
19384 delete(id) {
19385 onUse();
19386 return pluginCache.delete(id);
19387 },
19388 get(id) {
19389 onUse();
19390 return pluginCache.get(id);
19391 },
19392 has(id) {
19393 onUse();
19394 return pluginCache.has(id);
19395 },
19396 set(id, value) {
19397 onUse();
19398 return pluginCache.set(id, value);
19399 }
19400 };
19401}
19402const NO_CACHE = {
19403 delete() {
19404 return false;
19405 },
19406 get() {
19407 return undefined;
19408 },
19409 has() {
19410 return false;
19411 },
19412 set() { }
19413};
19414function uncacheablePluginError(pluginName) {
19415 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
19416 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
19417 return error({
19418 code: 'ANONYMOUS_PLUGIN_CACHE',
19419 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
19420 });
19421 }
19422 return error({
19423 code: 'DUPLICATE_PLUGIN_NAME',
19424 message: `The plugin name ${pluginName} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
19425 });
19426}
19427function getCacheForUncacheablePlugin(pluginName) {
19428 return {
19429 delete() {
19430 return uncacheablePluginError(pluginName);
19431 },
19432 get() {
19433 return uncacheablePluginError(pluginName);
19434 },
19435 has() {
19436 return uncacheablePluginError(pluginName);
19437 },
19438 set() {
19439 return uncacheablePluginError(pluginName);
19440 }
19441 };
19442}
19443
19444function transform(source, module, pluginDriver, warn) {
19445 const id = module.id;
19446 const sourcemapChain = [];
19447 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
19448 const originalCode = source.code;
19449 let ast = source.ast;
19450 const transformDependencies = [];
19451 const emittedFiles = [];
19452 let customTransformCache = false;
19453 const useCustomTransformCache = () => (customTransformCache = true);
19454 let curPlugin;
19455 const curSource = source.code;
19456 function transformReducer(previousCode, result, plugin) {
19457 let code;
19458 let map;
19459 if (typeof result === 'string') {
19460 code = result;
19461 }
19462 else if (result && typeof result === 'object') {
19463 module.updateOptions(result);
19464 if (result.code == null) {
19465 if (result.map || result.ast) {
19466 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
19467 }
19468 return previousCode;
19469 }
19470 ({ code, map, ast } = result);
19471 }
19472 else {
19473 return previousCode;
19474 }
19475 // strict null check allows 'null' maps to not be pushed to the chain,
19476 // while 'undefined' gets the missing map warning
19477 if (map !== null) {
19478 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
19479 missing: true,
19480 plugin: plugin.name
19481 });
19482 }
19483 return code;
19484 }
19485 return pluginDriver
19486 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
19487 curPlugin = plugin;
19488 return {
19489 ...pluginContext,
19490 addWatchFile(id) {
19491 transformDependencies.push(id);
19492 pluginContext.addWatchFile(id);
19493 },
19494 cache: customTransformCache
19495 ? pluginContext.cache
19496 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
19497 emitAsset(name, source) {
19498 emittedFiles.push({ name, source, type: 'asset' });
19499 return pluginContext.emitAsset(name, source);
19500 },
19501 emitChunk(id, options) {
19502 emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
19503 return pluginContext.emitChunk(id, options);
19504 },
19505 emitFile(emittedFile) {
19506 emittedFiles.push(emittedFile);
19507 return pluginDriver.emitFile(emittedFile);
19508 },
19509 error(err, pos) {
19510 if (typeof err === 'string')
19511 err = { message: err };
19512 if (pos)
19513 augmentCodeLocation(err, pos, curSource, id);
19514 err.id = id;
19515 err.hook = 'transform';
19516 return pluginContext.error(err);
19517 },
19518 getCombinedSourcemap() {
19519 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
19520 if (!combinedMap) {
19521 const magicString = new MagicString$1(originalCode);
19522 return magicString.generateMap({ hires: true, includeContent: true, source: id });
19523 }
19524 if (originalSourcemap !== combinedMap) {
19525 originalSourcemap = combinedMap;
19526 sourcemapChain.length = 0;
19527 }
19528 return new SourceMap({
19529 ...combinedMap,
19530 file: null,
19531 sourcesContent: combinedMap.sourcesContent
19532 });
19533 },
19534 setAssetSource() {
19535 return this.error({
19536 code: 'INVALID_SETASSETSOURCE',
19537 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
19538 });
19539 },
19540 warn(warning, pos) {
19541 if (typeof warning === 'string')
19542 warning = { message: warning };
19543 if (pos)
19544 augmentCodeLocation(warning, pos, curSource, id);
19545 warning.id = id;
19546 warning.hook = 'transform';
19547 pluginContext.warn(warning);
19548 }
19549 };
19550 })
19551 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
19552 .then(code => {
19553 if (!customTransformCache) {
19554 // files emitted by a transform hook need to be emitted again if the hook is skipped
19555 if (emittedFiles.length)
19556 module.transformFiles = emittedFiles;
19557 }
19558 return {
19559 ast,
19560 code,
19561 customTransformCache,
19562 meta: module.info.meta,
19563 originalCode,
19564 originalSourcemap,
19565 sourcemapChain,
19566 transformDependencies
19567 };
19568 });
19569}
19570
19571class ModuleLoader {
19572 constructor(graph, modulesById, options, pluginDriver) {
19573 this.graph = graph;
19574 this.modulesById = modulesById;
19575 this.options = options;
19576 this.pluginDriver = pluginDriver;
19577 this.implicitEntryModules = new Set();
19578 this.indexedEntryModules = [];
19579 this.latestLoadModulesPromise = Promise.resolve();
19580 this.nextEntryModuleIndex = 0;
19581 this.readQueue = new Queue();
19582 this.resolveId = async (source, importer, customOptions, skip = null) => {
19583 return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
19584 ? false
19585 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions), importer, source));
19586 };
19587 this.hasModuleSideEffects = options.treeshake
19588 ? options.treeshake.moduleSideEffects
19589 : () => true;
19590 this.readQueue.maxParallel = options.maxParallelFileReads;
19591 }
19592 async addAdditionalModules(unresolvedModules) {
19593 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
19594 await this.awaitLoadModulesPromise();
19595 return result;
19596 }
19597 async addEntryModules(unresolvedEntryModules, isUserDefined) {
19598 const firstEntryModuleIndex = this.nextEntryModuleIndex;
19599 this.nextEntryModuleIndex += unresolvedEntryModules.length;
19600 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
19601 let moduleIndex = firstEntryModuleIndex;
19602 for (let index = 0; index < entryModules.length; index++) {
19603 const entryModule = entryModules[index];
19604 entryModule.isUserDefinedEntryPoint =
19605 entryModule.isUserDefinedEntryPoint || isUserDefined;
19606 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
19607 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
19608 if (!existingIndexedModule) {
19609 this.indexedEntryModules.push({ index: moduleIndex, module: entryModule });
19610 }
19611 else {
19612 existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
19613 }
19614 moduleIndex++;
19615 }
19616 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
19617 return entryModules;
19618 }));
19619 await this.awaitLoadModulesPromise();
19620 return {
19621 entryModules: this.indexedEntryModules.map(({ module }) => module),
19622 implicitEntryModules: [...this.implicitEntryModules],
19623 newEntryModules
19624 };
19625 }
19626 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
19627 const unresolvedModule = {
19628 fileName: fileName || null,
19629 id,
19630 importer,
19631 name: name || null
19632 };
19633 const module = implicitlyLoadedAfterOneOf
19634 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
19635 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
19636 if (preserveSignature != null) {
19637 module.preserveSignature = preserveSignature;
19638 }
19639 return module;
19640 }
19641 addDefaultsToResolvedId(resolvedId) {
19642 var _a, _b;
19643 if (!resolvedId) {
19644 return null;
19645 }
19646 const external = resolvedId.external || false;
19647 return {
19648 external,
19649 id: resolvedId.id,
19650 meta: resolvedId.meta || EMPTY_OBJECT,
19651 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
19652 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
19653 };
19654 }
19655 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
19656 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
19657 addChunkNamesToModule(entryModule, unresolvedModule, false);
19658 if (!entryModule.info.isEntry) {
19659 this.implicitEntryModules.add(entryModule);
19660 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
19661 for (const module of implicitlyLoadedAfterModules) {
19662 entryModule.implicitlyLoadedAfter.add(module);
19663 }
19664 for (const dependant of entryModule.implicitlyLoadedAfter) {
19665 dependant.implicitlyLoadedBefore.add(entryModule);
19666 }
19667 }
19668 return entryModule;
19669 }));
19670 }
19671 async addModuleSource(id, importer, module) {
19672 var _a;
19673 timeStart('load modules', 3);
19674 let source;
19675 try {
19676 source =
19677 (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await this.readQueue.run(async () => readFile(id)));
19678 }
19679 catch (err) {
19680 timeEnd('load modules', 3);
19681 let msg = `Could not load ${id}`;
19682 if (importer)
19683 msg += ` (imported by ${relativeId(importer)})`;
19684 msg += `: ${err.message}`;
19685 err.message = msg;
19686 throw err;
19687 }
19688 timeEnd('load modules', 3);
19689 const sourceDescription = typeof source === 'string'
19690 ? { code: source }
19691 : typeof source === 'object' && typeof source.code === 'string'
19692 ? source
19693 : error(errBadLoader(id));
19694 const cachedModule = this.graph.cachedModules.get(id);
19695 if (cachedModule &&
19696 !cachedModule.customTransformCache &&
19697 cachedModule.originalCode === sourceDescription.code) {
19698 if (cachedModule.transformFiles) {
19699 for (const emittedFile of cachedModule.transformFiles)
19700 this.pluginDriver.emitFile(emittedFile);
19701 }
19702 module.setSource(cachedModule);
19703 }
19704 else {
19705 module.updateOptions(sourceDescription);
19706 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
19707 }
19708 }
19709 async awaitLoadModulesPromise() {
19710 let startingPromise;
19711 do {
19712 startingPromise = this.latestLoadModulesPromise;
19713 await startingPromise;
19714 } while (startingPromise !== this.latestLoadModulesPromise);
19715 }
19716 extendLoadModulesPromise(loadNewModulesPromise) {
19717 this.latestLoadModulesPromise = Promise.all([
19718 loadNewModulesPromise,
19719 this.latestLoadModulesPromise
19720 ]);
19721 this.latestLoadModulesPromise.catch(() => {
19722 /* Avoid unhandled Promise rejections */
19723 });
19724 return loadNewModulesPromise;
19725 }
19726 async fetchDynamicDependencies(module) {
19727 const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
19728 const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
19729 ? dynamicImport.argument
19730 : dynamicImport.argument.esTreeNode, module.id);
19731 if (resolvedId === null)
19732 return null;
19733 if (typeof resolvedId === 'string') {
19734 dynamicImport.resolution = resolvedId;
19735 return null;
19736 }
19737 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
19738 }));
19739 for (const dependency of dependencies) {
19740 if (dependency) {
19741 module.dynamicDependencies.add(dependency);
19742 dependency.dynamicImporters.push(module.id);
19743 }
19744 }
19745 }
19746 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
19747 const existingModule = this.modulesById.get(id);
19748 if (existingModule instanceof Module) {
19749 if (isEntry) {
19750 existingModule.info.isEntry = true;
19751 this.implicitEntryModules.delete(existingModule);
19752 for (const dependant of existingModule.implicitlyLoadedAfter) {
19753 dependant.implicitlyLoadedBefore.delete(existingModule);
19754 }
19755 existingModule.implicitlyLoadedAfter.clear();
19756 }
19757 return existingModule;
19758 }
19759 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
19760 this.modulesById.set(id, module);
19761 this.graph.watchFiles[id] = true;
19762 await this.addModuleSource(id, importer, module);
19763 await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
19764 await Promise.all([
19765 this.fetchStaticDependencies(module),
19766 this.fetchDynamicDependencies(module)
19767 ]);
19768 module.linkImports();
19769 return module;
19770 }
19771 fetchResolvedDependency(source, importer, resolvedId) {
19772 if (resolvedId.external) {
19773 const { external, id, moduleSideEffects, meta } = resolvedId;
19774 if (!this.modulesById.has(id)) {
19775 this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
19776 }
19777 const externalModule = this.modulesById.get(id);
19778 if (!(externalModule instanceof ExternalModule)) {
19779 return error(errInternalIdCannotBeExternal(source, importer));
19780 }
19781 return Promise.resolve(externalModule);
19782 }
19783 else {
19784 return this.fetchModule(resolvedId, importer, false);
19785 }
19786 }
19787 async fetchStaticDependencies(module) {
19788 for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
19789 module.resolvedIds[source] ||
19790 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
19791 module.dependencies.add(dependency);
19792 dependency.importers.push(module.id);
19793 }
19794 if (!this.options.treeshake || module.info.hasModuleSideEffects === 'no-treeshake') {
19795 for (const dependency of module.dependencies) {
19796 if (dependency instanceof Module) {
19797 dependency.importedFromNotTreeshaken = true;
19798 }
19799 }
19800 }
19801 }
19802 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
19803 const { makeAbsoluteExternalsRelative } = this.options;
19804 if (resolveIdResult) {
19805 if (typeof resolveIdResult === 'object') {
19806 const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
19807 return {
19808 ...resolveIdResult,
19809 external: external &&
19810 (external === 'relative' ||
19811 !isAbsolute(resolveIdResult.id) ||
19812 (external === true &&
19813 isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
19814 'absolute')
19815 };
19816 }
19817 const external = this.options.external(resolveIdResult, importer, true);
19818 return {
19819 external: external &&
19820 (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
19821 'absolute'),
19822 id: external && makeAbsoluteExternalsRelative
19823 ? normalizeRelativeExternalId(resolveIdResult, importer)
19824 : resolveIdResult
19825 };
19826 }
19827 const id = makeAbsoluteExternalsRelative
19828 ? normalizeRelativeExternalId(source, importer)
19829 : source;
19830 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
19831 return null;
19832 }
19833 return {
19834 external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
19835 id
19836 };
19837 }
19838 handleResolveId(resolvedId, source, importer) {
19839 if (resolvedId === null) {
19840 if (isRelative(source)) {
19841 return error(errUnresolvedImport(source, importer));
19842 }
19843 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
19844 return {
19845 external: true,
19846 id: source,
19847 meta: EMPTY_OBJECT,
19848 moduleSideEffects: this.hasModuleSideEffects(source, true),
19849 syntheticNamedExports: false
19850 };
19851 }
19852 else {
19853 if (resolvedId.external && resolvedId.syntheticNamedExports) {
19854 this.options.onwarn(errExternalSyntheticExports(source, importer));
19855 }
19856 }
19857 return resolvedId;
19858 }
19859 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
19860 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT);
19861 if (resolveIdResult == null) {
19862 return error(implicitlyLoadedBefore === null
19863 ? errUnresolvedEntry(unresolvedId)
19864 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
19865 }
19866 if (resolveIdResult === false ||
19867 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
19868 return error(implicitlyLoadedBefore === null
19869 ? errEntryCannotBeExternal(unresolvedId)
19870 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
19871 }
19872 return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object'
19873 ? resolveIdResult
19874 : { id: resolveIdResult }), undefined, isEntry);
19875 }
19876 async resolveDynamicImport(module, specifier, importer) {
19877 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
19878 specifier,
19879 importer
19880 ]);
19881 if (typeof specifier !== 'string') {
19882 if (typeof resolution === 'string') {
19883 return resolution;
19884 }
19885 if (!resolution) {
19886 return null;
19887 }
19888 return {
19889 external: false,
19890 moduleSideEffects: true,
19891 ...resolution
19892 };
19893 }
19894 if (resolution == null) {
19895 return (module.resolvedIds[specifier] =
19896 module.resolvedIds[specifier] ||
19897 this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
19898 }
19899 return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
19900 }
19901}
19902function normalizeRelativeExternalId(source, importer) {
19903 return isRelative(source)
19904 ? importer
19905 ? path.resolve(importer, '..', source)
19906 : path.resolve(source)
19907 : source;
19908}
19909function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
19910 if (fileName !== null) {
19911 module.chunkFileNames.add(fileName);
19912 }
19913 else if (name !== null) {
19914 if (module.chunkName === null) {
19915 module.chunkName = name;
19916 }
19917 if (isUserDefined) {
19918 module.userChunkNames.add(name);
19919 }
19920 }
19921}
19922function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
19923 return (makeAbsoluteExternalsRelative === true ||
19924 (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
19925 !isAbsolute(id));
19926}
19927
19928class GlobalScope extends Scope$1 {
19929 constructor() {
19930 super();
19931 this.variables.set('undefined', new UndefinedVariable());
19932 }
19933 findVariable(name) {
19934 let variable = this.variables.get(name);
19935 if (!variable) {
19936 variable = new GlobalVariable(name);
19937 this.variables.set(name, variable);
19938 }
19939 return variable;
19940 }
19941}
19942
19943// eslint-disable-next-line @typescript-eslint/ban-types
19944function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
19945 let deprecationWarningShown = false;
19946 return ((...args) => {
19947 if (!deprecationWarningShown) {
19948 deprecationWarningShown = true;
19949 warnDeprecation({
19950 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
19951 plugin: pluginName
19952 }, activeDeprecation, options);
19953 }
19954 return handler(...args);
19955 });
19956}
19957function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
19958 let cacheable = true;
19959 if (typeof plugin.cacheKey !== 'string') {
19960 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
19961 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
19962 existingPluginNames.has(plugin.name)) {
19963 cacheable = false;
19964 }
19965 else {
19966 existingPluginNames.add(plugin.name);
19967 }
19968 }
19969 let cacheInstance;
19970 if (!pluginCache) {
19971 cacheInstance = NO_CACHE;
19972 }
19973 else if (cacheable) {
19974 const cacheKey = plugin.cacheKey || plugin.name;
19975 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
19976 }
19977 else {
19978 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
19979 }
19980 const context = {
19981 addWatchFile(id) {
19982 if (graph.phase >= BuildPhase.GENERATE) {
19983 return this.error(errInvalidRollupPhaseForAddWatchFile());
19984 }
19985 graph.watchFiles[id] = true;
19986 },
19987 cache: cacheInstance,
19988 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
19989 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
19990 emitFile: fileEmitter.emitFile.bind(fileEmitter),
19991 error(err) {
19992 return throwPluginError(err, plugin.name);
19993 },
19994 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
19995 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
19996 getFileName: fileEmitter.getFileName,
19997 getModuleIds: () => graph.modulesById.keys(),
19998 getModuleInfo: graph.getModuleInfo,
19999 getWatchFiles: () => Object.keys(graph.watchFiles),
20000 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
20001 meta: {
20002 rollupVersion: version$1,
20003 watchMode: graph.watchMode
20004 },
20005 get moduleIds() {
20006 function* wrappedModuleIds() {
20007 warnDeprecation({
20008 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
20009 plugin: plugin.name
20010 }, false, options);
20011 yield* moduleIds;
20012 }
20013 const moduleIds = graph.modulesById.keys();
20014 return wrappedModuleIds();
20015 },
20016 parse: graph.contextParse.bind(graph),
20017 resolve(source, importer, { custom, skipSelf } = BLANK) {
20018 return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? [{ importer, plugin, source }] : null);
20019 },
20020 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
20021 .resolveId(source, importer, BLANK)
20022 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
20023 setAssetSource: fileEmitter.setAssetSource,
20024 warn(warning) {
20025 if (typeof warning === 'string')
20026 warning = { message: warning };
20027 if (warning.code)
20028 warning.pluginCode = warning.code;
20029 warning.code = 'PLUGIN_WARNING';
20030 warning.plugin = plugin.name;
20031 options.onwarn(warning);
20032 }
20033 };
20034 return context;
20035}
20036
20037const inputHookNames = {
20038 buildEnd: 1,
20039 buildStart: 1,
20040 closeBundle: 1,
20041 closeWatcher: 1,
20042 load: 1,
20043 moduleParsed: 1,
20044 options: 1,
20045 resolveDynamicImport: 1,
20046 resolveId: 1,
20047 transform: 1,
20048 watchChange: 1
20049};
20050const inputHooks = Object.keys(inputHookNames);
20051function throwInvalidHookError(hookName, pluginName) {
20052 return error({
20053 code: 'INVALID_PLUGIN_HOOK',
20054 message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
20055 });
20056}
20057class PluginDriver {
20058 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
20059 this.graph = graph;
20060 this.options = options;
20061 this.pluginContexts = new Map();
20062 warnDeprecatedHooks(userPlugins, options);
20063 this.pluginCache = pluginCache;
20064 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
20065 this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
20066 this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
20067 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
20068 this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
20069 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
20070 const existingPluginNames = new Set();
20071 for (const plugin of this.plugins) {
20072 this.pluginContexts.set(plugin, getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames));
20073 }
20074 if (basePluginDriver) {
20075 for (const plugin of userPlugins) {
20076 for (const hook of inputHooks) {
20077 if (hook in plugin) {
20078 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
20079 }
20080 }
20081 }
20082 }
20083 }
20084 createOutputPluginDriver(plugins) {
20085 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
20086 }
20087 // chains, first non-null result stops and returns
20088 hookFirst(hookName, args, replaceContext, skipped) {
20089 let promise = Promise.resolve(undefined);
20090 for (const plugin of this.plugins) {
20091 if (skipped && skipped.has(plugin))
20092 continue;
20093 promise = promise.then(result => {
20094 if (result != null)
20095 return result;
20096 return this.runHook(hookName, args, plugin, false, replaceContext);
20097 });
20098 }
20099 return promise;
20100 }
20101 // chains synchronously, first non-null result stops and returns
20102 hookFirstSync(hookName, args, replaceContext) {
20103 for (const plugin of this.plugins) {
20104 const result = this.runHookSync(hookName, args, plugin, replaceContext);
20105 if (result != null)
20106 return result;
20107 }
20108 return null;
20109 }
20110 // parallel, ignores returns
20111 hookParallel(hookName, args, replaceContext) {
20112 const promises = [];
20113 for (const plugin of this.plugins) {
20114 const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
20115 if (!hookPromise)
20116 continue;
20117 promises.push(hookPromise);
20118 }
20119 return Promise.all(promises).then(() => { });
20120 }
20121 // chains, reduces returned value, handling the reduced value as the first hook argument
20122 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
20123 let promise = Promise.resolve(arg0);
20124 for (const plugin of this.plugins) {
20125 promise = promise.then(arg0 => {
20126 const args = [arg0, ...rest];
20127 const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
20128 if (!hookPromise)
20129 return arg0;
20130 return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
20131 });
20132 }
20133 return promise;
20134 }
20135 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
20136 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
20137 for (const plugin of this.plugins) {
20138 const args = [arg0, ...rest];
20139 const result = this.runHookSync(hookName, args, plugin, replaceContext);
20140 arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
20141 }
20142 return arg0;
20143 }
20144 // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
20145 hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
20146 let promise = Promise.resolve(initialValue);
20147 for (const plugin of this.plugins) {
20148 promise = promise.then(value => {
20149 const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
20150 if (!hookPromise)
20151 return value;
20152 return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
20153 });
20154 }
20155 return promise;
20156 }
20157 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
20158 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
20159 let acc = initialValue;
20160 for (const plugin of this.plugins) {
20161 const result = this.runHookSync(hookName, args, plugin, replaceContext);
20162 acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
20163 }
20164 return acc;
20165 }
20166 // chains, ignores returns
20167 hookSeq(hookName, args, replaceContext) {
20168 let promise = Promise.resolve();
20169 for (const plugin of this.plugins) {
20170 promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
20171 }
20172 return promise;
20173 }
20174 // chains synchronously, ignores returns
20175 hookSeqSync(hookName, args, replaceContext) {
20176 for (const plugin of this.plugins) {
20177 this.runHookSync(hookName, args, plugin, replaceContext);
20178 }
20179 }
20180 runHook(hookName, args, plugin, permitValues, hookContext) {
20181 const hook = plugin[hookName];
20182 if (!hook)
20183 return undefined;
20184 let context = this.pluginContexts.get(plugin);
20185 if (hookContext) {
20186 context = hookContext(context, plugin);
20187 }
20188 return Promise.resolve()
20189 .then(() => {
20190 // permit values allows values to be returned instead of a functional hook
20191 if (typeof hook !== 'function') {
20192 if (permitValues)
20193 return hook;
20194 return throwInvalidHookError(hookName, plugin.name);
20195 }
20196 // eslint-disable-next-line @typescript-eslint/ban-types
20197 return hook.apply(context, args);
20198 })
20199 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
20200 }
20201 /**
20202 * Run a sync plugin hook and return the result.
20203 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
20204 * @param args Arguments passed to the plugin hook.
20205 * @param plugin The acutal plugin
20206 * @param hookContext When passed, the plugin context can be overridden.
20207 */
20208 runHookSync(hookName, args, plugin, hookContext) {
20209 const hook = plugin[hookName];
20210 if (!hook)
20211 return undefined;
20212 let context = this.pluginContexts.get(plugin);
20213 if (hookContext) {
20214 context = hookContext(context, plugin);
20215 }
20216 try {
20217 // permit values allows values to be returned instead of a functional hook
20218 if (typeof hook !== 'function') {
20219 return throwInvalidHookError(hookName, plugin.name);
20220 }
20221 // eslint-disable-next-line @typescript-eslint/ban-types
20222 return hook.apply(context, args);
20223 }
20224 catch (err) {
20225 return throwPluginError(err, plugin.name, { hook: hookName });
20226 }
20227 }
20228}
20229
20230function normalizeEntryModules(entryModules) {
20231 if (Array.isArray(entryModules)) {
20232 return entryModules.map(id => ({
20233 fileName: null,
20234 id,
20235 implicitlyLoadedAfter: [],
20236 importer: undefined,
20237 name: null
20238 }));
20239 }
20240 return Object.entries(entryModules).map(([name, id]) => ({
20241 fileName: null,
20242 id,
20243 implicitlyLoadedAfter: [],
20244 importer: undefined,
20245 name
20246 }));
20247}
20248class Graph {
20249 constructor(options, watcher) {
20250 var _a, _b;
20251 this.options = options;
20252 this.entryModules = [];
20253 this.modulesById = new Map();
20254 this.needsTreeshakingPass = false;
20255 this.phase = BuildPhase.LOAD_AND_PARSE;
20256 this.watchFiles = Object.create(null);
20257 this.watchMode = false;
20258 this.externalModules = [];
20259 this.implicitEntryModules = [];
20260 this.modules = [];
20261 this.getModuleInfo = (moduleId) => {
20262 const foundModule = this.modulesById.get(moduleId);
20263 if (!foundModule)
20264 return null;
20265 return foundModule.info;
20266 };
20267 this.deoptimizationTracker = new PathTracker();
20268 this.cachedModules = new Map();
20269 if (options.cache !== false) {
20270 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
20271 for (const module of options.cache.modules)
20272 this.cachedModules.set(module.id, module);
20273 }
20274 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
20275 // increment access counter
20276 for (const name in this.pluginCache) {
20277 const cache = this.pluginCache[name];
20278 for (const value of Object.values(cache))
20279 value[0]++;
20280 }
20281 }
20282 if (watcher) {
20283 this.watchMode = true;
20284 const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
20285 const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
20286 watcher.on('change', handleChange);
20287 watcher.on('close', handleClose);
20288 watcher.once('restart', () => {
20289 watcher.removeListener('change', handleChange);
20290 watcher.removeListener('close', handleClose);
20291 });
20292 }
20293 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
20294 this.scope = new GlobalScope();
20295 this.acornParser = Parser.extend(...options.acornInjectPlugins);
20296 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
20297 }
20298 async build() {
20299 timeStart('generate module graph', 2);
20300 await this.generateModuleGraph();
20301 timeEnd('generate module graph', 2);
20302 timeStart('sort modules', 2);
20303 this.phase = BuildPhase.ANALYSE;
20304 this.sortModules();
20305 timeEnd('sort modules', 2);
20306 timeStart('mark included statements', 2);
20307 this.includeStatements();
20308 timeEnd('mark included statements', 2);
20309 this.phase = BuildPhase.GENERATE;
20310 }
20311 contextParse(code, options = {}) {
20312 const onCommentOrig = options.onComment;
20313 const comments = [];
20314 if (onCommentOrig && typeof onCommentOrig == 'function') {
20315 options.onComment = (block, text, start, end, ...args) => {
20316 comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
20317 return onCommentOrig.call(options, block, text, start, end, ...args);
20318 };
20319 }
20320 else {
20321 options.onComment = comments;
20322 }
20323 const ast = this.acornParser.parse(code, {
20324 ...this.options.acorn,
20325 ...options
20326 });
20327 if (typeof onCommentOrig == 'object') {
20328 onCommentOrig.push(...comments);
20329 }
20330 options.onComment = onCommentOrig;
20331 addAnnotations(comments, ast, code);
20332 return ast;
20333 }
20334 getCache() {
20335 // handle plugin cache eviction
20336 for (const name in this.pluginCache) {
20337 const cache = this.pluginCache[name];
20338 let allDeleted = true;
20339 for (const [key, value] of Object.entries(cache)) {
20340 if (value[0] >= this.options.experimentalCacheExpiry)
20341 delete cache[key];
20342 else
20343 allDeleted = false;
20344 }
20345 if (allDeleted)
20346 delete this.pluginCache[name];
20347 }
20348 return {
20349 modules: this.modules.map(module => module.toJSON()),
20350 plugins: this.pluginCache
20351 };
20352 }
20353 async generateModuleGraph() {
20354 ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
20355 await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
20356 if (this.entryModules.length === 0) {
20357 throw new Error('You must supply options.input to rollup');
20358 }
20359 for (const module of this.modulesById.values()) {
20360 if (module instanceof Module) {
20361 this.modules.push(module);
20362 }
20363 else {
20364 this.externalModules.push(module);
20365 }
20366 }
20367 }
20368 includeStatements() {
20369 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
20370 markModuleAndImpureDependenciesAsExecuted(module);
20371 }
20372 if (this.options.treeshake) {
20373 let treeshakingPass = 1;
20374 do {
20375 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
20376 this.needsTreeshakingPass = false;
20377 for (const module of this.modules) {
20378 if (module.isExecuted) {
20379 if (module.info.hasModuleSideEffects === 'no-treeshake') {
20380 module.includeAllInBundle();
20381 }
20382 else {
20383 module.include();
20384 }
20385 }
20386 }
20387 if (treeshakingPass === 1) {
20388 // We only include exports after the first pass to avoid issues with
20389 // the TDZ detection logic
20390 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
20391 if (module.preserveSignature !== false) {
20392 module.includeAllExports(false);
20393 this.needsTreeshakingPass = true;
20394 }
20395 }
20396 }
20397 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
20398 } while (this.needsTreeshakingPass);
20399 }
20400 else {
20401 for (const module of this.modules)
20402 module.includeAllInBundle();
20403 }
20404 for (const externalModule of this.externalModules)
20405 externalModule.warnUnusedImports();
20406 for (const module of this.implicitEntryModules) {
20407 for (const dependant of module.implicitlyLoadedAfter) {
20408 if (!(dependant.info.isEntry || dependant.isIncluded())) {
20409 error(errImplicitDependantIsNotIncluded(dependant));
20410 }
20411 }
20412 }
20413 }
20414 sortModules() {
20415 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
20416 for (const cyclePath of cyclePaths) {
20417 this.options.onwarn({
20418 code: 'CIRCULAR_DEPENDENCY',
20419 cycle: cyclePath,
20420 importer: cyclePath[0],
20421 message: `Circular dependency: ${cyclePath.join(' -> ')}`
20422 });
20423 }
20424 this.modules = orderedModules;
20425 for (const module of this.modules) {
20426 module.bindReferences();
20427 }
20428 this.warnForMissingExports();
20429 }
20430 warnForMissingExports() {
20431 for (const module of this.modules) {
20432 for (const importDescription of Object.values(module.importDescriptions)) {
20433 if (importDescription.name !== '*' &&
20434 !importDescription.module.getVariableForExportName(importDescription.name)) {
20435 module.warn({
20436 code: 'NON_EXISTENT_EXPORT',
20437 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
20438 name: importDescription.name,
20439 source: importDescription.module.id
20440 }, importDescription.start);
20441 }
20442 }
20443 }
20444 }
20445}
20446
20447function normalizeInputOptions(config) {
20448 var _a, _b, _c;
20449 // These are options that may trigger special warnings or behaviour later
20450 // if the user did not select an explicit value
20451 const unsetOptions = new Set();
20452 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
20453 const onwarn = getOnwarn(config);
20454 const strictDeprecations = config.strictDeprecations || false;
20455 const options = {
20456 acorn: getAcorn(config),
20457 acornInjectPlugins: getAcornInjectPlugins(config),
20458 cache: getCache(config),
20459 context,
20460 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
20461 external: getIdMatcher(config.external),
20462 inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
20463 input: getInput(config),
20464 makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
20465 manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
20466 maxParallelFileReads: getMaxParallelFileReads(config),
20467 moduleContext: getModuleContext(config, context),
20468 onwarn,
20469 perf: config.perf || false,
20470 plugins: ensureArray(config.plugins),
20471 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
20472 preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
20473 preserveSymlinks: config.preserveSymlinks || false,
20474 shimMissingExports: config.shimMissingExports || false,
20475 strictDeprecations,
20476 treeshake: getTreeshake(config, onwarn, strictDeprecations)
20477 };
20478 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
20479 return { options, unsetOptions };
20480}
20481const getOnwarn = (config) => {
20482 const { onwarn } = config;
20483 return onwarn
20484 ? warning => {
20485 warning.toString = () => {
20486 let str = '';
20487 if (warning.plugin)
20488 str += `(${warning.plugin} plugin) `;
20489 if (warning.loc)
20490 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
20491 str += warning.message;
20492 return str;
20493 };
20494 onwarn(warning, defaultOnWarn);
20495 }
20496 : defaultOnWarn;
20497};
20498const getAcorn = (config) => ({
20499 allowAwaitOutsideFunction: true,
20500 ecmaVersion: 'latest',
20501 preserveParens: false,
20502 sourceType: 'module',
20503 ...config.acorn
20504});
20505const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
20506const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
20507const getIdMatcher = (option) => {
20508 if (option === true) {
20509 return () => true;
20510 }
20511 if (typeof option === 'function') {
20512 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
20513 }
20514 if (option) {
20515 const ids = new Set();
20516 const matchers = [];
20517 for (const value of ensureArray(option)) {
20518 if (value instanceof RegExp) {
20519 matchers.push(value);
20520 }
20521 else {
20522 ids.add(value);
20523 }
20524 }
20525 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
20526 }
20527 return () => false;
20528};
20529const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
20530 const configInlineDynamicImports = config.inlineDynamicImports;
20531 if (configInlineDynamicImports) {
20532 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
20533 }
20534 return configInlineDynamicImports;
20535};
20536const getInput = (config) => {
20537 const configInput = config.input;
20538 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
20539};
20540const getManualChunks$1 = (config, warn, strictDeprecations) => {
20541 const configManualChunks = config.manualChunks;
20542 if (configManualChunks) {
20543 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
20544 }
20545 return configManualChunks;
20546};
20547const getMaxParallelFileReads = (config) => {
20548 const maxParallelFileReads = config.maxParallelFileReads;
20549 if (typeof maxParallelFileReads === 'number') {
20550 if (maxParallelFileReads <= 0)
20551 return Infinity;
20552 return maxParallelFileReads;
20553 }
20554 return 20;
20555};
20556const getModuleContext = (config, context) => {
20557 const configModuleContext = config.moduleContext;
20558 if (typeof configModuleContext === 'function') {
20559 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
20560 }
20561 if (configModuleContext) {
20562 const contextByModuleId = Object.create(null);
20563 for (const [key, moduleContext] of Object.entries(configModuleContext)) {
20564 contextByModuleId[path.resolve(key)] = moduleContext;
20565 }
20566 return id => contextByModuleId[id] || context;
20567 }
20568 return () => context;
20569};
20570const getPreserveEntrySignatures = (config, unsetOptions) => {
20571 const configPreserveEntrySignatures = config.preserveEntrySignatures;
20572 if (configPreserveEntrySignatures == null) {
20573 unsetOptions.add('preserveEntrySignatures');
20574 }
20575 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
20576};
20577const getPreserveModules$1 = (config, warn, strictDeprecations) => {
20578 const configPreserveModules = config.preserveModules;
20579 if (configPreserveModules) {
20580 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
20581 }
20582 return configPreserveModules;
20583};
20584const getTreeshake = (config, warn, strictDeprecations) => {
20585 const configTreeshake = config.treeshake;
20586 if (configTreeshake === false) {
20587 return false;
20588 }
20589 if (typeof configTreeshake === 'string') {
20590 const preset = treeshakePresets[configTreeshake];
20591 if (preset) {
20592 return preset;
20593 }
20594 error(errInvalidOption('treeshake', `valid values are false, true, ${printQuotedStringList(Object.keys(treeshakePresets))}. You can also supply an object for more fine-grained control`));
20595 }
20596 let configWithPreset = {};
20597 if (typeof configTreeshake === 'object') {
20598 if (typeof configTreeshake.pureExternalModules !== 'undefined') {
20599 warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
20600 }
20601 configWithPreset = configTreeshake;
20602 const presetName = configTreeshake.preset;
20603 if (presetName) {
20604 const preset = treeshakePresets[presetName];
20605 if (preset) {
20606 configWithPreset = { ...preset, ...configTreeshake };
20607 }
20608 else {
20609 error(errInvalidOption('treeshake.preset', `valid values are ${printQuotedStringList(Object.keys(treeshakePresets))}`));
20610 }
20611 }
20612 }
20613 return {
20614 annotations: configWithPreset.annotations !== false,
20615 correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
20616 moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
20617 ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
20618 : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
20619 propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
20620 ? 'always'
20621 : configWithPreset.propertyReadSideEffects !== false,
20622 tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
20623 unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
20624 };
20625};
20626const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
20627 if (typeof moduleSideEffectsOption === 'boolean') {
20628 return () => moduleSideEffectsOption;
20629 }
20630 if (moduleSideEffectsOption === 'no-external') {
20631 return (_id, external) => !external;
20632 }
20633 if (typeof moduleSideEffectsOption === 'function') {
20634 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
20635 }
20636 if (Array.isArray(moduleSideEffectsOption)) {
20637 const ids = new Set(moduleSideEffectsOption);
20638 return id => ids.has(id);
20639 }
20640 if (moduleSideEffectsOption) {
20641 error(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
20642 }
20643 const isPureExternalModule = getIdMatcher(pureExternalModules);
20644 return (id, external) => !(external && isPureExternalModule(id));
20645};
20646
20647function sanitizeFileName(name) {
20648 const match = /^[a-z]:/i.exec(name);
20649 const driveLetter = match ? match[0] : '';
20650 // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
20651 // Otherwise, avoid them because they can refer to NTFS alternate data streams.
20652 return driveLetter + name.substr(driveLetter.length).replace(/[\0?*:]/g, '_');
20653}
20654
20655function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
20656 var _a, _b, _c, _d, _e, _f, _g;
20657 // These are options that may trigger special warnings or behaviour later
20658 // if the user did not select an explicit value
20659 const unsetOptions = new Set(unsetInputOptions);
20660 const compact = config.compact || false;
20661 const format = getFormat(config);
20662 const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
20663 const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
20664 const file = getFile(config, preserveModules, inputOptions);
20665 const outputOptions = {
20666 amd: getAmd(config),
20667 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
20668 banner: getAddon(config, 'banner'),
20669 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
20670 compact,
20671 dir: getDir(config, file),
20672 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
20673 entryFileNames: getEntryFileNames(config, unsetOptions),
20674 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
20675 exports: getExports(config, unsetOptions),
20676 extend: config.extend || false,
20677 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
20678 file,
20679 footer: getAddon(config, 'footer'),
20680 format,
20681 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
20682 globals: config.globals || {},
20683 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
20684 indent: getIndent(config, compact),
20685 inlineDynamicImports,
20686 interop: getInterop(config, inputOptions),
20687 intro: getAddon(config, 'intro'),
20688 manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
20689 minifyInternalExports: getMinifyInternalExports(config, format, compact),
20690 name: config.name,
20691 namespaceToStringTag: config.namespaceToStringTag || false,
20692 noConflict: config.noConflict || false,
20693 outro: getAddon(config, 'outro'),
20694 paths: config.paths || {},
20695 plugins: ensureArray(config.plugins),
20696 preferConst: config.preferConst || false,
20697 preserveModules,
20698 preserveModulesRoot: getPreserveModulesRoot(config),
20699 sanitizeFileName: typeof config.sanitizeFileName === 'function'
20700 ? config.sanitizeFileName
20701 : config.sanitizeFileName === false
20702 ? id => id
20703 : sanitizeFileName,
20704 sourcemap: config.sourcemap || false,
20705 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
20706 sourcemapFile: config.sourcemapFile,
20707 sourcemapPathTransform: config.sourcemapPathTransform,
20708 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
20709 systemNullSetters: config.systemNullSetters || false,
20710 validate: config.validate || false
20711 };
20712 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
20713 return { options: outputOptions, unsetOptions };
20714}
20715const getFile = (config, preserveModules, inputOptions) => {
20716 const { file } = config;
20717 if (typeof file === 'string') {
20718 if (preserveModules) {
20719 return error({
20720 code: 'INVALID_OPTION',
20721 message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
20722 });
20723 }
20724 if (!Array.isArray(inputOptions.input))
20725 return error({
20726 code: 'INVALID_OPTION',
20727 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
20728 });
20729 }
20730 return file;
20731};
20732const getFormat = (config) => {
20733 const configFormat = config.format;
20734 switch (configFormat) {
20735 case undefined:
20736 case 'es':
20737 case 'esm':
20738 case 'module':
20739 return 'es';
20740 case 'cjs':
20741 case 'commonjs':
20742 return 'cjs';
20743 case 'system':
20744 case 'systemjs':
20745 return 'system';
20746 case 'amd':
20747 case 'iife':
20748 case 'umd':
20749 return configFormat;
20750 default:
20751 return error({
20752 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
20753 url: `https://rollupjs.org/guide/en/#outputformat`
20754 });
20755 }
20756};
20757const getInlineDynamicImports = (config, inputOptions) => {
20758 var _a;
20759 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
20760 const { input } = inputOptions;
20761 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
20762 return error({
20763 code: 'INVALID_OPTION',
20764 message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
20765 });
20766 }
20767 return inlineDynamicImports;
20768};
20769const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
20770 var _a;
20771 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
20772 if (preserveModules) {
20773 if (inlineDynamicImports) {
20774 return error({
20775 code: 'INVALID_OPTION',
20776 message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
20777 });
20778 }
20779 if (inputOptions.preserveEntrySignatures === false) {
20780 return error({
20781 code: 'INVALID_OPTION',
20782 message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
20783 });
20784 }
20785 }
20786 return preserveModules;
20787};
20788const getPreserveModulesRoot = (config) => {
20789 const { preserveModulesRoot } = config;
20790 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
20791 return undefined;
20792 }
20793 return path.resolve(preserveModulesRoot);
20794};
20795const getAmd = (config) => {
20796 const collection = {
20797 autoId: false,
20798 basePath: '',
20799 define: 'define',
20800 ...config.amd
20801 };
20802 if ((collection.autoId || collection.basePath) && collection.id) {
20803 return error({
20804 code: 'INVALID_OPTION',
20805 message: '"output.amd.autoId"/"output.amd.basePath" and "output.amd.id" cannot be used together.'
20806 });
20807 }
20808 if (collection.basePath && !collection.autoId) {
20809 return error({
20810 code: 'INVALID_OPTION',
20811 message: '"output.amd.basePath" only works with "output.amd.autoId".'
20812 });
20813 }
20814 let normalized;
20815 if (collection.autoId) {
20816 normalized = {
20817 autoId: true,
20818 basePath: collection.basePath,
20819 define: collection.define
20820 };
20821 }
20822 else {
20823 normalized = {
20824 autoId: false,
20825 define: collection.define,
20826 id: collection.id
20827 };
20828 }
20829 return normalized;
20830};
20831const getAddon = (config, name) => {
20832 const configAddon = config[name];
20833 if (typeof configAddon === 'function') {
20834 return configAddon;
20835 }
20836 return () => configAddon || '';
20837};
20838const getDir = (config, file) => {
20839 const { dir } = config;
20840 if (typeof dir === 'string' && typeof file === 'string') {
20841 return error({
20842 code: 'INVALID_OPTION',
20843 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
20844 });
20845 }
20846 return dir;
20847};
20848const getDynamicImportFunction = (config, inputOptions) => {
20849 const configDynamicImportFunction = config.dynamicImportFunction;
20850 if (configDynamicImportFunction) {
20851 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
20852 }
20853 return configDynamicImportFunction;
20854};
20855const getEntryFileNames = (config, unsetOptions) => {
20856 const configEntryFileNames = config.entryFileNames;
20857 if (configEntryFileNames == null) {
20858 unsetOptions.add('entryFileNames');
20859 }
20860 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
20861};
20862function getExports(config, unsetOptions) {
20863 const configExports = config.exports;
20864 if (configExports == null) {
20865 unsetOptions.add('exports');
20866 }
20867 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
20868 return error(errInvalidExportOptionValue(configExports));
20869 }
20870 return configExports || 'auto';
20871}
20872const getIndent = (config, compact) => {
20873 if (compact) {
20874 return '';
20875 }
20876 const configIndent = config.indent;
20877 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
20878};
20879const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
20880const getInterop = (config, inputOptions) => {
20881 const configInterop = config.interop;
20882 const validatedInteropTypes = new Set();
20883 const validateInterop = (interop) => {
20884 if (!validatedInteropTypes.has(interop)) {
20885 validatedInteropTypes.add(interop);
20886 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
20887 return error({
20888 code: 'INVALID_OPTION',
20889 message: `The value ${JSON.stringify(interop)} is not supported for "output.interop". Use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value => JSON.stringify(value)).join(', ')} instead.`,
20890 url: 'https://rollupjs.org/guide/en/#outputinterop'
20891 });
20892 }
20893 if (typeof interop === 'boolean') {
20894 warnDeprecation({
20895 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
20896 url: 'https://rollupjs.org/guide/en/#outputinterop'
20897 }, false, inputOptions);
20898 }
20899 }
20900 return interop;
20901 };
20902 if (typeof configInterop === 'function') {
20903 const interopPerId = Object.create(null);
20904 let defaultInterop = null;
20905 return id => id === null
20906 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
20907 : id in interopPerId
20908 ? interopPerId[id]
20909 : validateInterop((interopPerId[id] = configInterop(id)));
20910 }
20911 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
20912};
20913const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
20914 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
20915 if (configManualChunks) {
20916 if (inlineDynamicImports) {
20917 return error({
20918 code: 'INVALID_OPTION',
20919 message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
20920 });
20921 }
20922 if (preserveModules) {
20923 return error({
20924 code: 'INVALID_OPTION',
20925 message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
20926 });
20927 }
20928 }
20929 return configManualChunks || {};
20930};
20931const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
20932
20933function rollup(rawInputOptions) {
20934 return rollupInternal(rawInputOptions, null);
20935}
20936async function rollupInternal(rawInputOptions, watcher) {
20937 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
20938 initialiseTimers(inputOptions);
20939 const graph = new Graph(inputOptions, watcher);
20940 // remove the cache option from the memory after graph creation (cache is not used anymore)
20941 const useCache = rawInputOptions.cache !== false;
20942 delete inputOptions.cache;
20943 delete rawInputOptions.cache;
20944 timeStart('BUILD', 1);
20945 try {
20946 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
20947 await graph.build();
20948 }
20949 catch (err) {
20950 const watchFiles = Object.keys(graph.watchFiles);
20951 if (watchFiles.length > 0) {
20952 err.watchFiles = watchFiles;
20953 }
20954 await graph.pluginDriver.hookParallel('buildEnd', [err]);
20955 await graph.pluginDriver.hookParallel('closeBundle', []);
20956 throw err;
20957 }
20958 await graph.pluginDriver.hookParallel('buildEnd', []);
20959 timeEnd('BUILD', 1);
20960 const result = {
20961 cache: useCache ? graph.getCache() : undefined,
20962 async close() {
20963 if (result.closed)
20964 return;
20965 result.closed = true;
20966 await graph.pluginDriver.hookParallel('closeBundle', []);
20967 },
20968 closed: false,
20969 async generate(rawOutputOptions) {
20970 if (result.closed)
20971 return error(errAlreadyClosed());
20972 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
20973 },
20974 watchFiles: Object.keys(graph.watchFiles),
20975 async write(rawOutputOptions) {
20976 if (result.closed)
20977 return error(errAlreadyClosed());
20978 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
20979 }
20980 };
20981 if (inputOptions.perf)
20982 result.getTimings = getTimings;
20983 return result;
20984}
20985async function getInputOptions(rawInputOptions, watchMode) {
20986 if (!rawInputOptions) {
20987 throw new Error('You must supply an options object to rollup');
20988 }
20989 const rawPlugins = ensureArray(rawInputOptions.plugins);
20990 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
20991 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
20992 return { options, unsetOptions };
20993}
20994function applyOptionHook(watchMode) {
20995 return async (inputOptions, plugin) => {
20996 if (plugin.options) {
20997 return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
20998 }
20999 return inputOptions;
21000 };
21001}
21002function normalizePlugins(plugins, anonymousPrefix) {
21003 for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
21004 const plugin = plugins[pluginIndex];
21005 if (!plugin.name) {
21006 plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
21007 }
21008 }
21009}
21010async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
21011 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
21012 const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
21013 const generated = await bundle.generate(isWrite);
21014 if (isWrite) {
21015 if (!outputOptions.dir && !outputOptions.file) {
21016 return error({
21017 code: 'MISSING_OPTION',
21018 message: 'You must specify "output.file" or "output.dir" for the build.'
21019 });
21020 }
21021 await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions)));
21022 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
21023 }
21024 return createOutput(generated);
21025}
21026function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
21027 if (!rawOutputOptions) {
21028 throw new Error('You must supply an options object');
21029 }
21030 const rawPlugins = ensureArray(rawOutputOptions.plugins);
21031 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
21032 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
21033 return {
21034 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
21035 outputPluginDriver
21036 };
21037}
21038function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
21039 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
21040 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
21041 return {
21042 ...pluginContext,
21043 emitFile: emitError,
21044 setAssetSource: emitError
21045 };
21046 }), inputOptions, unsetInputOptions);
21047}
21048function createOutput(outputBundle) {
21049 return {
21050 output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
21051 const fileTypeA = getSortingFileType(outputFileA);
21052 const fileTypeB = getSortingFileType(outputFileB);
21053 if (fileTypeA === fileTypeB)
21054 return 0;
21055 return fileTypeA < fileTypeB ? -1 : 1;
21056 })
21057 };
21058}
21059var SortingFileType;
21060(function (SortingFileType) {
21061 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
21062 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
21063 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
21064})(SortingFileType || (SortingFileType = {}));
21065function getSortingFileType(file) {
21066 if (file.type === 'asset') {
21067 return SortingFileType.ASSET;
21068 }
21069 if (file.isEntry) {
21070 return SortingFileType.ENTRY_CHUNK;
21071 }
21072 return SortingFileType.SECONDARY_CHUNK;
21073}
21074function writeOutputFile(outputFile, outputOptions) {
21075 const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
21076 let writeSourceMapPromise;
21077 let source;
21078 if (outputFile.type === 'asset') {
21079 source = outputFile.source;
21080 }
21081 else {
21082 source = outputFile.code;
21083 if (outputOptions.sourcemap && outputFile.map) {
21084 let url;
21085 if (outputOptions.sourcemap === 'inline') {
21086 url = outputFile.map.toUrl();
21087 }
21088 else {
21089 url = `${path.basename(outputFile.fileName)}.map`;
21090 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
21091 }
21092 if (outputOptions.sourcemap !== 'hidden') {
21093 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
21094 }
21095 }
21096 }
21097 return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
21098}
21099/**
21100 * Auxiliary function for defining rollup configuration
21101 * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
21102 * @param options
21103 */
21104function defineConfig(options) {
21105 return options;
21106}
21107
21108class WatchEmitter extends require$$0.EventEmitter {
21109 constructor() {
21110 super();
21111 // Allows more than 10 bundles to be watched without
21112 // showing the `MaxListenersExceededWarning` to the user.
21113 this.setMaxListeners(Infinity);
21114 }
21115 close() { }
21116}
21117function watch(configs) {
21118 const emitter = new WatchEmitter();
21119 const configArray = ensureArray(configs);
21120 const watchConfigs = configArray.filter(config => config.watch !== false);
21121 if (watchConfigs.length === 0) {
21122 throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
21123 }
21124 loadFsEvents()
21125 .then(() => Promise.resolve().then(function () { return require('./watch.js'); }))
21126 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
21127 return emitter;
21128}
21129
21130exports.defaultOnWarn = defaultOnWarn;
21131exports.defineConfig = defineConfig;
21132exports.ensureArray = ensureArray;
21133exports.errInvalidOption = errInvalidOption;
21134exports.error = error;
21135exports.fseventsImporter = fseventsImporter;
21136exports.getAliasName = getAliasName;
21137exports.getOrCreate = getOrCreate;
21138exports.loadFsEvents = loadFsEvents;
21139exports.printQuotedStringList = printQuotedStringList;
21140exports.relativeId = relativeId;
21141exports.rollup = rollup;
21142exports.rollupInternal = rollupInternal;
21143exports.treeshakePresets = treeshakePresets;
21144exports.version = version$1;
21145exports.warnUnknownOptions = warnUnknownOptions;
21146exports.watch = watch;
21147//# sourceMappingURL=rollup.js.map