UNPKG

891 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.75.7
4 Mon, 20 Jun 2022 07:24:02 GMT - commit 057171c2d3bc2092b7f543fc05ead01f12595f12
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10'use strict';
11
12const require$$0 = require('path');
13const process$1 = require('process');
14const perf_hooks = require('perf_hooks');
15const crypto = require('crypto');
16const require$$0$1 = require('fs');
17const require$$0$2 = require('events');
18
19function _interopNamespaceDefault(e) {
20 const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
21 if (e) {
22 for (const k in e) {
23 n[k] = e[k];
24 }
25 }
26 n.default = e;
27 return n;
28}
29
30var version$1 = "2.75.7";
31
32function ensureArray$1(items) {
33 if (Array.isArray(items)) {
34 return items.filter(Boolean);
35 }
36 if (items) {
37 return [items];
38 }
39 return [];
40}
41
42function getLocator$1(source, options) {
43 if (options === void 0) { options = {}; }
44 var offsetLine = options.offsetLine || 0;
45 var offsetColumn = options.offsetColumn || 0;
46 var originalLines = source.split('\n');
47 var start = 0;
48 var lineRanges = originalLines.map(function (line, i) {
49 var end = start + line.length + 1;
50 var range = { start: start, end: end, line: i };
51 start = end;
52 return range;
53 });
54 var i = 0;
55 function rangeContains(range, index) {
56 return range.start <= index && index < range.end;
57 }
58 function getLocation(range, index) {
59 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
60 }
61 function locate(search, startIndex) {
62 if (typeof search === 'string') {
63 search = source.indexOf(search, startIndex || 0);
64 }
65 var range = lineRanges[i];
66 var d = search >= range.end ? 1 : -1;
67 while (range) {
68 if (rangeContains(range, search))
69 return getLocation(range, search);
70 i += d;
71 range = lineRanges[i];
72 }
73 }
74 return locate;
75}
76function locate(source, search, options) {
77 if (typeof options === 'number') {
78 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
79 }
80 return getLocator$1(source, options)(search, options && options.startIndex);
81}
82
83function spaces(i) {
84 let result = '';
85 while (i--)
86 result += ' ';
87 return result;
88}
89function tabsToSpaces(str) {
90 return str.replace(/^\t+/, match => match.split('\t').join(' '));
91}
92function getCodeFrame(source, line, column) {
93 let lines = source.split('\n');
94 const frameStart = Math.max(0, line - 3);
95 let frameEnd = Math.min(line + 2, lines.length);
96 lines = lines.slice(frameStart, frameEnd);
97 while (!/\S/.test(lines[lines.length - 1])) {
98 lines.pop();
99 frameEnd -= 1;
100 }
101 const digits = String(frameEnd).length;
102 return lines
103 .map((str, i) => {
104 const isErrorLine = frameStart + i + 1 === line;
105 let lineNum = String(i + frameStart + 1);
106 while (lineNum.length < digits)
107 lineNum = ` ${lineNum}`;
108 if (isErrorLine) {
109 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
110 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
111 }
112 return `${lineNum}: ${tabsToSpaces(str)}`;
113 })
114 .join('\n');
115}
116
117function printQuotedStringList(list, verbs) {
118 const isSingleItem = list.length <= 1;
119 const quotedList = list.map(item => `"${item}"`);
120 let output = isSingleItem
121 ? quotedList[0]
122 : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
123 if (verbs) {
124 output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
125 }
126 return output;
127}
128
129const ANY_SLASH_REGEX = /[/\\]/;
130function relative(from, to) {
131 const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
132 const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
133 if (fromParts[0] === '.')
134 fromParts.shift();
135 if (toParts[0] === '.')
136 toParts.shift();
137 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
138 fromParts.shift();
139 toParts.shift();
140 }
141 while (toParts[0] === '..' && fromParts.length > 0) {
142 toParts.shift();
143 fromParts.pop();
144 }
145 while (fromParts.pop()) {
146 toParts.unshift('..');
147 }
148 return toParts.join('/');
149}
150
151const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
152const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
153function isAbsolute(path) {
154 return ABSOLUTE_PATH_REGEX.test(path);
155}
156function isRelative(path) {
157 return RELATIVE_PATH_REGEX.test(path);
158}
159const BACKSLASH_REGEX = /\\/g;
160function normalize(path) {
161 return path.replace(BACKSLASH_REGEX, '/');
162}
163
164function getAliasName(id) {
165 const base = require$$0.basename(id);
166 return base.substring(0, base.length - require$$0.extname(id).length);
167}
168function relativeId(id) {
169 if (!isAbsolute(id))
170 return id;
171 return relative(require$$0.resolve(), id);
172}
173function isPathFragment(name) {
174 // starting with "/", "./", "../", "C:/"
175 return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
176}
177const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
178function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
179 let relativePath = normalize(relative(require$$0.dirname(importerId), targetPath));
180 if (stripJsExtension && relativePath.endsWith('.js')) {
181 relativePath = relativePath.slice(0, -3);
182 }
183 if (ensureFileName) {
184 if (relativePath === '')
185 return '../' + require$$0.basename(targetPath);
186 if (UPPER_DIR_REGEX.test(relativePath)) {
187 return relativePath
188 .split('/')
189 .concat(['..', require$$0.basename(targetPath)])
190 .join('/');
191 }
192 }
193 return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
194}
195
196function error(base) {
197 if (!(base instanceof Error))
198 base = Object.assign(new Error(base.message), base);
199 throw base;
200}
201function augmentCodeLocation(props, pos, source, id) {
202 if (typeof pos === 'object') {
203 const { line, column } = pos;
204 props.loc = { column, file: id, line };
205 }
206 else {
207 props.pos = pos;
208 const { line, column } = locate(source, pos, { offsetLine: 1 });
209 props.loc = { column, file: id, line };
210 }
211 if (props.frame === undefined) {
212 const { line, column } = props.loc;
213 props.frame = getCodeFrame(source, line, column);
214 }
215}
216var Errors;
217(function (Errors) {
218 Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
219 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
220 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
221 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
222 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
223 Errors["BAD_LOADER"] = "BAD_LOADER";
224 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
225 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
226 Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
227 Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
228 Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
229 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
230 Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
231 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
232 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
233 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
234 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
235 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
236 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
237 Errors["INVALID_OPTION"] = "INVALID_OPTION";
238 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
239 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
240 Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
241 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
242 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
243 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
244 Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
245 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
246 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
247 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
248 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
249 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
250 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
251 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
252 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
253})(Errors || (Errors = {}));
254function errAssetNotFinalisedForFileName(name) {
255 return {
256 code: Errors.ASSET_NOT_FINALISED,
257 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
258 };
259}
260function errCannotEmitFromOptionsHook() {
261 return {
262 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
263 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
264 };
265}
266function errChunkNotGeneratedForFileName(name) {
267 return {
268 code: Errors.CHUNK_NOT_GENERATED,
269 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
270 };
271}
272function errChunkInvalid({ fileName, code }, exception) {
273 const errorProps = {
274 code: Errors.CHUNK_INVALID,
275 message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
276 };
277 augmentCodeLocation(errorProps, exception.loc, code, fileName);
278 return errorProps;
279}
280function errCircularReexport(exportName, importedModule) {
281 return {
282 code: Errors.CIRCULAR_REEXPORT,
283 id: importedModule,
284 message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
285 };
286}
287function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
288 return {
289 code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
290 exporter,
291 importer,
292 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.`,
293 reexporter
294 };
295}
296function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
297 return {
298 code: Errors.ASSET_NOT_FOUND,
299 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
300 };
301}
302function errAssetSourceAlreadySet(name) {
303 return {
304 code: Errors.ASSET_SOURCE_ALREADY_SET,
305 message: `Unable to set the source for asset "${name}", source already set.`
306 };
307}
308function errNoAssetSourceSet(assetName) {
309 return {
310 code: Errors.ASSET_SOURCE_MISSING,
311 message: `Plugin error creating asset "${assetName}" - no asset source set.`
312 };
313}
314function errBadLoader(id) {
315 return {
316 code: Errors.BAD_LOADER,
317 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
318 };
319}
320function errDeprecation(deprecation) {
321 return {
322 code: Errors.DEPRECATED_FEATURE,
323 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
324 };
325}
326function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
327 return {
328 code: Errors.FILE_NOT_FOUND,
329 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
330 };
331}
332function errFileNameConflict(fileName) {
333 return {
334 code: Errors.FILE_NAME_CONFLICT,
335 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
336 };
337}
338function errInputHookInOutputPlugin(pluginName, hookName) {
339 return {
340 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
341 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.`
342 };
343}
344function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
345 return {
346 code: Errors.INVALID_CHUNK,
347 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
348 };
349}
350function errInvalidExportOptionValue(optionValue) {
351 return {
352 code: Errors.INVALID_EXPORT_OPTION,
353 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
354 url: `https://rollupjs.org/guide/en/#outputexports`
355 };
356}
357function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
358 return {
359 code: 'INVALID_EXPORT_OPTION',
360 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
361 };
362}
363function errInternalIdCannotBeExternal(source, importer) {
364 return {
365 code: Errors.INVALID_EXTERNAL_ID,
366 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
367 };
368}
369function errInvalidOption(option, urlHash, explanation, value) {
370 return {
371 code: Errors.INVALID_OPTION,
372 message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
373 url: `https://rollupjs.org/guide/en/#${urlHash}`
374 };
375}
376function errInvalidRollupPhaseForAddWatchFile() {
377 return {
378 code: Errors.INVALID_ROLLUP_PHASE,
379 message: `Cannot call addWatchFile after the build has finished.`
380 };
381}
382function errInvalidRollupPhaseForChunkEmission() {
383 return {
384 code: Errors.INVALID_ROLLUP_PHASE,
385 message: `Cannot emit chunks after module loading has finished.`
386 };
387}
388function errMissingExport(exportName, importingModule, importedModule) {
389 return {
390 code: Errors.MISSING_EXPORT,
391 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
392 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
393 };
394}
395function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
396 return {
397 code: Errors.MISSING_IMPLICIT_DEPENDANT,
398 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
399 };
400}
401function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
402 return {
403 code: Errors.MISSING_IMPLICIT_DEPENDANT,
404 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
405 };
406}
407function errImplicitDependantIsNotIncluded(module) {
408 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
409 return {
410 code: Errors.MISSING_IMPLICIT_DEPENDANT,
411 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.`
412 };
413}
414function errMixedExport(facadeModuleId, name) {
415 return {
416 code: Errors.MIXED_EXPORTS,
417 id: facadeModuleId,
418 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`,
419 url: `https://rollupjs.org/guide/en/#outputexports`
420 };
421}
422function errNamespaceConflict(name, reexportingModuleId, sources) {
423 return {
424 code: Errors.NAMESPACE_CONFLICT,
425 message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
426 name,
427 reexporter: reexportingModuleId,
428 sources
429 };
430}
431function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
432 return {
433 code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
434 message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
435 name,
436 reexporter: reexportingModule,
437 sources
438 };
439}
440function errNoTransformMapOrAstWithoutCode(pluginName) {
441 return {
442 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
443 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
444 'a "code". This will be ignored.'
445 };
446}
447function errPreferNamedExports(facadeModuleId) {
448 const file = relativeId(facadeModuleId);
449 return {
450 code: Errors.PREFER_NAMED_EXPORTS,
451 id: facadeModuleId,
452 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.`,
453 url: `https://rollupjs.org/guide/en/#outputexports`
454 };
455}
456function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
457 return {
458 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
459 id,
460 message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
461 ? `an explicit export named "${syntheticNamedExportsOption}"`
462 : 'a default export'} that does not reexport an unresolved named export of the same module.`
463 };
464}
465function errUnexpectedNamedImport(id, imported, isReexport) {
466 const importType = isReexport ? 'reexport' : 'import';
467 return {
468 code: Errors.UNEXPECTED_NAMED_IMPORT,
469 id,
470 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.`,
471 url: 'https://rollupjs.org/guide/en/#outputinterop'
472 };
473}
474function errUnexpectedNamespaceReexport(id) {
475 return {
476 code: Errors.UNEXPECTED_NAMED_IMPORT,
477 id,
478 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.`,
479 url: 'https://rollupjs.org/guide/en/#outputinterop'
480 };
481}
482function errEntryCannotBeExternal(unresolvedId) {
483 return {
484 code: Errors.UNRESOLVED_ENTRY,
485 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
486 };
487}
488function errUnresolvedEntry(unresolvedId) {
489 return {
490 code: Errors.UNRESOLVED_ENTRY,
491 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
492 };
493}
494function errUnresolvedImport(source, importer) {
495 return {
496 code: Errors.UNRESOLVED_IMPORT,
497 message: `Could not resolve '${source}' from ${relativeId(importer)}`
498 };
499}
500function errUnresolvedImportTreatedAsExternal(source, importer) {
501 return {
502 code: Errors.UNRESOLVED_IMPORT,
503 importer: relativeId(importer),
504 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
505 source,
506 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
507 };
508}
509function errExternalSyntheticExports(source, importer) {
510 return {
511 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
512 importer: relativeId(importer),
513 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
514 source
515 };
516}
517function errFailedValidation(message) {
518 return {
519 code: Errors.VALIDATION_ERROR,
520 message
521 };
522}
523function errAlreadyClosed() {
524 return {
525 code: Errors.ALREADY_CLOSED,
526 message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
527 };
528}
529function warnDeprecation(deprecation, activeDeprecation, options) {
530 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
531}
532function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
533 if (activeDeprecation || strictDeprecations) {
534 const warning = errDeprecation(deprecation);
535 if (strictDeprecations) {
536 return error(warning);
537 }
538 warn(warning);
539 }
540}
541
542const defaultOnWarn = warning => console.warn(warning.message || warning);
543function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
544 const validOptionSet = new Set(validOptions);
545 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
546 if (unknownOptions.length > 0) {
547 warn({
548 code: 'UNKNOWN_OPTION',
549 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
550 ...validOptionSet
551 ]
552 .sort()
553 .join(', ')}`
554 });
555 }
556}
557const treeshakePresets = {
558 recommended: {
559 annotations: true,
560 correctVarValueBeforeDeclaration: false,
561 moduleSideEffects: () => true,
562 propertyReadSideEffects: true,
563 tryCatchDeoptimization: true,
564 unknownGlobalSideEffects: false
565 },
566 safest: {
567 annotations: true,
568 correctVarValueBeforeDeclaration: true,
569 moduleSideEffects: () => true,
570 propertyReadSideEffects: true,
571 tryCatchDeoptimization: true,
572 unknownGlobalSideEffects: true
573 },
574 smallest: {
575 annotations: true,
576 correctVarValueBeforeDeclaration: false,
577 moduleSideEffects: () => false,
578 propertyReadSideEffects: false,
579 tryCatchDeoptimization: false,
580 unknownGlobalSideEffects: false
581 }
582};
583const generatedCodePresets = {
584 es2015: {
585 arrowFunctions: true,
586 constBindings: true,
587 objectShorthand: true,
588 reservedNamesAsProps: true,
589 symbols: true
590 },
591 es5: {
592 arrowFunctions: false,
593 constBindings: false,
594 objectShorthand: false,
595 reservedNamesAsProps: true,
596 symbols: false
597 }
598};
599const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
600const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
601 if (typeof value === 'string') {
602 const preset = presets[value];
603 if (preset) {
604 return preset;
605 }
606 error(errInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
607 }
608 return objectifyOption(value);
609};
610const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
611 const presetName = value === null || value === void 0 ? void 0 : value.preset;
612 if (presetName) {
613 const preset = presets[presetName];
614 if (preset) {
615 return { ...preset, ...value };
616 }
617 else {
618 error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
619 }
620 }
621 return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
622};
623const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
624
625let fsEvents;
626let fsEventsImportError;
627async function loadFsEvents() {
628 try {
629 ({ default: fsEvents } = await Promise.resolve().then(() => /*#__PURE__*/_interopNamespaceDefault(require('fsevents'))));
630 }
631 catch (err) {
632 fsEventsImportError = err;
633 }
634}
635// A call to this function will be injected into the chokidar code
636function getFsEvents() {
637 if (fsEventsImportError)
638 throw fsEventsImportError;
639 return fsEvents;
640}
641
642const fseventsImporter = /*#__PURE__*/Object.defineProperty({
643 __proto__: null,
644 loadFsEvents,
645 getFsEvents
646}, Symbol.toStringTag, { value: 'Module' });
647
648var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
649
650function getDefaultExportFromCjs (x) {
651 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
652}
653
654function getAugmentedNamespace(n) {
655 var f = n.default;
656 if (typeof f == "function") {
657 var a = function () {
658 return f.apply(this, arguments);
659 };
660 a.prototype = f.prototype;
661 } else a = {};
662 Object.defineProperty(a, '__esModule', {value: true});
663 Object.keys(n).forEach(function (k) {
664 var d = Object.getOwnPropertyDescriptor(n, k);
665 Object.defineProperty(a, k, d.get ? d : {
666 enumerable: true,
667 get: function () {
668 return n[k];
669 }
670 });
671 });
672 return a;
673}
674
675var charToInteger = {};
676var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
677for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
678 charToInteger[chars$1.charCodeAt(i$1)] = i$1;
679}
680function decode(mappings) {
681 var decoded = [];
682 var line = [];
683 var segment = [
684 0,
685 0,
686 0,
687 0,
688 0,
689 ];
690 var j = 0;
691 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
692 var c = mappings.charCodeAt(i);
693 if (c === 44) { // ","
694 segmentify(line, segment, j);
695 j = 0;
696 }
697 else if (c === 59) { // ";"
698 segmentify(line, segment, j);
699 j = 0;
700 decoded.push(line);
701 line = [];
702 segment[0] = 0;
703 }
704 else {
705 var integer = charToInteger[c];
706 if (integer === undefined) {
707 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
708 }
709 var hasContinuationBit = integer & 32;
710 integer &= 31;
711 value += integer << shift;
712 if (hasContinuationBit) {
713 shift += 5;
714 }
715 else {
716 var shouldNegate = value & 1;
717 value >>>= 1;
718 if (shouldNegate) {
719 value = value === 0 ? -0x80000000 : -value;
720 }
721 segment[j] += value;
722 j++;
723 value = shift = 0; // reset
724 }
725 }
726 }
727 segmentify(line, segment, j);
728 decoded.push(line);
729 return decoded;
730}
731function segmentify(line, segment, j) {
732 // This looks ugly, but we're creating specialized arrays with a specific
733 // length. This is much faster than creating a new array (which v8 expands to
734 // a capacity of 17 after pushing the first item), or slicing out a subarray
735 // (which is slow). Length 4 is assumed to be the most frequent, followed by
736 // length 5 (since not everything will have an associated name), followed by
737 // length 1 (it's probably rare for a source substring to not have an
738 // associated segment data).
739 if (j === 4)
740 line.push([segment[0], segment[1], segment[2], segment[3]]);
741 else if (j === 5)
742 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
743 else if (j === 1)
744 line.push([segment[0]]);
745}
746function encode(decoded) {
747 var sourceFileIndex = 0; // second field
748 var sourceCodeLine = 0; // third field
749 var sourceCodeColumn = 0; // fourth field
750 var nameIndex = 0; // fifth field
751 var mappings = '';
752 for (var i = 0; i < decoded.length; i++) {
753 var line = decoded[i];
754 if (i > 0)
755 mappings += ';';
756 if (line.length === 0)
757 continue;
758 var generatedCodeColumn = 0; // first field
759 var lineMappings = [];
760 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
761 var segment = line_1[_i];
762 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
763 generatedCodeColumn = segment[0];
764 if (segment.length > 1) {
765 segmentMappings +=
766 encodeInteger(segment[1] - sourceFileIndex) +
767 encodeInteger(segment[2] - sourceCodeLine) +
768 encodeInteger(segment[3] - sourceCodeColumn);
769 sourceFileIndex = segment[1];
770 sourceCodeLine = segment[2];
771 sourceCodeColumn = segment[3];
772 }
773 if (segment.length === 5) {
774 segmentMappings += encodeInteger(segment[4] - nameIndex);
775 nameIndex = segment[4];
776 }
777 lineMappings.push(segmentMappings);
778 }
779 mappings += lineMappings.join(',');
780 }
781 return mappings;
782}
783function encodeInteger(num) {
784 var result = '';
785 num = num < 0 ? (-num << 1) | 1 : num << 1;
786 do {
787 var clamped = num & 31;
788 num >>>= 5;
789 if (num > 0) {
790 clamped |= 32;
791 }
792 result += chars$1[clamped];
793 } while (num > 0);
794 return result;
795}
796
797class BitSet {
798 constructor(arg) {
799 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
800 }
801
802 add(n) {
803 this.bits[n >> 5] |= 1 << (n & 31);
804 }
805
806 has(n) {
807 return !!(this.bits[n >> 5] & (1 << (n & 31)));
808 }
809}
810
811class Chunk$1 {
812 constructor(start, end, content) {
813 this.start = start;
814 this.end = end;
815 this.original = content;
816
817 this.intro = '';
818 this.outro = '';
819
820 this.content = content;
821 this.storeName = false;
822 this.edited = false;
823
824 // we make these non-enumerable, for sanity while debugging
825 Object.defineProperties(this, {
826 previous: { writable: true, value: null },
827 next: { writable: true, value: null },
828 });
829 }
830
831 appendLeft(content) {
832 this.outro += content;
833 }
834
835 appendRight(content) {
836 this.intro = this.intro + content;
837 }
838
839 clone() {
840 const chunk = new Chunk$1(this.start, this.end, this.original);
841
842 chunk.intro = this.intro;
843 chunk.outro = this.outro;
844 chunk.content = this.content;
845 chunk.storeName = this.storeName;
846 chunk.edited = this.edited;
847
848 return chunk;
849 }
850
851 contains(index) {
852 return this.start < index && index < this.end;
853 }
854
855 eachNext(fn) {
856 let chunk = this;
857 while (chunk) {
858 fn(chunk);
859 chunk = chunk.next;
860 }
861 }
862
863 eachPrevious(fn) {
864 let chunk = this;
865 while (chunk) {
866 fn(chunk);
867 chunk = chunk.previous;
868 }
869 }
870
871 edit(content, storeName, contentOnly) {
872 this.content = content;
873 if (!contentOnly) {
874 this.intro = '';
875 this.outro = '';
876 }
877 this.storeName = storeName;
878
879 this.edited = true;
880
881 return this;
882 }
883
884 prependLeft(content) {
885 this.outro = content + this.outro;
886 }
887
888 prependRight(content) {
889 this.intro = content + this.intro;
890 }
891
892 split(index) {
893 const sliceIndex = index - this.start;
894
895 const originalBefore = this.original.slice(0, sliceIndex);
896 const originalAfter = this.original.slice(sliceIndex);
897
898 this.original = originalBefore;
899
900 const newChunk = new Chunk$1(index, this.end, originalAfter);
901 newChunk.outro = this.outro;
902 this.outro = '';
903
904 this.end = index;
905
906 if (this.edited) {
907 // TODO is this block necessary?...
908 newChunk.edit('', false);
909 this.content = '';
910 } else {
911 this.content = originalBefore;
912 }
913
914 newChunk.next = this.next;
915 if (newChunk.next) newChunk.next.previous = newChunk;
916 newChunk.previous = this;
917 this.next = newChunk;
918
919 return newChunk;
920 }
921
922 toString() {
923 return this.intro + this.content + this.outro;
924 }
925
926 trimEnd(rx) {
927 this.outro = this.outro.replace(rx, '');
928 if (this.outro.length) return true;
929
930 const trimmed = this.content.replace(rx, '');
931
932 if (trimmed.length) {
933 if (trimmed !== this.content) {
934 this.split(this.start + trimmed.length).edit('', undefined, true);
935 }
936 return true;
937 } else {
938 this.edit('', undefined, true);
939
940 this.intro = this.intro.replace(rx, '');
941 if (this.intro.length) return true;
942 }
943 }
944
945 trimStart(rx) {
946 this.intro = this.intro.replace(rx, '');
947 if (this.intro.length) return true;
948
949 const trimmed = this.content.replace(rx, '');
950
951 if (trimmed.length) {
952 if (trimmed !== this.content) {
953 this.split(this.end - trimmed.length);
954 this.edit('', undefined, true);
955 }
956 return true;
957 } else {
958 this.edit('', undefined, true);
959
960 this.outro = this.outro.replace(rx, '');
961 if (this.outro.length) return true;
962 }
963 }
964}
965
966let btoa = () => {
967 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
968};
969if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
970 btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
971} else if (typeof Buffer === 'function') {
972 btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
973}
974
975class SourceMap {
976 constructor(properties) {
977 this.version = 3;
978 this.file = properties.file;
979 this.sources = properties.sources;
980 this.sourcesContent = properties.sourcesContent;
981 this.names = properties.names;
982 this.mappings = encode(properties.mappings);
983 }
984
985 toString() {
986 return JSON.stringify(this);
987 }
988
989 toUrl() {
990 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
991 }
992}
993
994function guessIndent(code) {
995 const lines = code.split('\n');
996
997 const tabbed = lines.filter((line) => /^\t+/.test(line));
998 const spaced = lines.filter((line) => /^ {2,}/.test(line));
999
1000 if (tabbed.length === 0 && spaced.length === 0) {
1001 return null;
1002 }
1003
1004 // More lines tabbed than spaced? Assume tabs, and
1005 // default to tabs in the case of a tie (or nothing
1006 // to go on)
1007 if (tabbed.length >= spaced.length) {
1008 return '\t';
1009 }
1010
1011 // Otherwise, we need to guess the multiple
1012 const min = spaced.reduce((previous, current) => {
1013 const numSpaces = /^ +/.exec(current)[0].length;
1014 return Math.min(numSpaces, previous);
1015 }, Infinity);
1016
1017 return new Array(min + 1).join(' ');
1018}
1019
1020function getRelativePath(from, to) {
1021 const fromParts = from.split(/[/\\]/);
1022 const toParts = to.split(/[/\\]/);
1023
1024 fromParts.pop(); // get dirname
1025
1026 while (fromParts[0] === toParts[0]) {
1027 fromParts.shift();
1028 toParts.shift();
1029 }
1030
1031 if (fromParts.length) {
1032 let i = fromParts.length;
1033 while (i--) fromParts[i] = '..';
1034 }
1035
1036 return fromParts.concat(toParts).join('/');
1037}
1038
1039const toString$1 = Object.prototype.toString;
1040
1041function isObject$1(thing) {
1042 return toString$1.call(thing) === '[object Object]';
1043}
1044
1045function getLocator(source) {
1046 const originalLines = source.split('\n');
1047 const lineOffsets = [];
1048
1049 for (let i = 0, pos = 0; i < originalLines.length; i++) {
1050 lineOffsets.push(pos);
1051 pos += originalLines[i].length + 1;
1052 }
1053
1054 return function locate(index) {
1055 let i = 0;
1056 let j = lineOffsets.length;
1057 while (i < j) {
1058 const m = (i + j) >> 1;
1059 if (index < lineOffsets[m]) {
1060 j = m;
1061 } else {
1062 i = m + 1;
1063 }
1064 }
1065 const line = i - 1;
1066 const column = index - lineOffsets[line];
1067 return { line, column };
1068 };
1069}
1070
1071class Mappings {
1072 constructor(hires) {
1073 this.hires = hires;
1074 this.generatedCodeLine = 0;
1075 this.generatedCodeColumn = 0;
1076 this.raw = [];
1077 this.rawSegments = this.raw[this.generatedCodeLine] = [];
1078 this.pending = null;
1079 }
1080
1081 addEdit(sourceIndex, content, loc, nameIndex) {
1082 if (content.length) {
1083 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1084 if (nameIndex >= 0) {
1085 segment.push(nameIndex);
1086 }
1087 this.rawSegments.push(segment);
1088 } else if (this.pending) {
1089 this.rawSegments.push(this.pending);
1090 }
1091
1092 this.advance(content);
1093 this.pending = null;
1094 }
1095
1096 addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
1097 let originalCharIndex = chunk.start;
1098 let first = true;
1099
1100 while (originalCharIndex < chunk.end) {
1101 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
1102 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
1103 }
1104
1105 if (original[originalCharIndex] === '\n') {
1106 loc.line += 1;
1107 loc.column = 0;
1108 this.generatedCodeLine += 1;
1109 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1110 this.generatedCodeColumn = 0;
1111 first = true;
1112 } else {
1113 loc.column += 1;
1114 this.generatedCodeColumn += 1;
1115 first = false;
1116 }
1117
1118 originalCharIndex += 1;
1119 }
1120
1121 this.pending = null;
1122 }
1123
1124 advance(str) {
1125 if (!str) return;
1126
1127 const lines = str.split('\n');
1128
1129 if (lines.length > 1) {
1130 for (let i = 0; i < lines.length - 1; i++) {
1131 this.generatedCodeLine++;
1132 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1133 }
1134 this.generatedCodeColumn = 0;
1135 }
1136
1137 this.generatedCodeColumn += lines[lines.length - 1].length;
1138 }
1139}
1140
1141const n = '\n';
1142
1143const warned = {
1144 insertLeft: false,
1145 insertRight: false,
1146 storeName: false,
1147};
1148
1149class MagicString {
1150 constructor(string, options = {}) {
1151 const chunk = new Chunk$1(0, string.length, string);
1152
1153 Object.defineProperties(this, {
1154 original: { writable: true, value: string },
1155 outro: { writable: true, value: '' },
1156 intro: { writable: true, value: '' },
1157 firstChunk: { writable: true, value: chunk },
1158 lastChunk: { writable: true, value: chunk },
1159 lastSearchedChunk: { writable: true, value: chunk },
1160 byStart: { writable: true, value: {} },
1161 byEnd: { writable: true, value: {} },
1162 filename: { writable: true, value: options.filename },
1163 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1164 sourcemapLocations: { writable: true, value: new BitSet() },
1165 storedNames: { writable: true, value: {} },
1166 indentStr: { writable: true, value: guessIndent(string) },
1167 });
1168
1169 this.byStart[0] = chunk;
1170 this.byEnd[string.length] = chunk;
1171 }
1172
1173 addSourcemapLocation(char) {
1174 this.sourcemapLocations.add(char);
1175 }
1176
1177 append(content) {
1178 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1179
1180 this.outro += content;
1181 return this;
1182 }
1183
1184 appendLeft(index, content) {
1185 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1186
1187 this._split(index);
1188
1189 const chunk = this.byEnd[index];
1190
1191 if (chunk) {
1192 chunk.appendLeft(content);
1193 } else {
1194 this.intro += content;
1195 }
1196 return this;
1197 }
1198
1199 appendRight(index, content) {
1200 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1201
1202 this._split(index);
1203
1204 const chunk = this.byStart[index];
1205
1206 if (chunk) {
1207 chunk.appendRight(content);
1208 } else {
1209 this.outro += content;
1210 }
1211 return this;
1212 }
1213
1214 clone() {
1215 const cloned = new MagicString(this.original, { filename: this.filename });
1216
1217 let originalChunk = this.firstChunk;
1218 let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1219
1220 while (originalChunk) {
1221 cloned.byStart[clonedChunk.start] = clonedChunk;
1222 cloned.byEnd[clonedChunk.end] = clonedChunk;
1223
1224 const nextOriginalChunk = originalChunk.next;
1225 const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1226
1227 if (nextClonedChunk) {
1228 clonedChunk.next = nextClonedChunk;
1229 nextClonedChunk.previous = clonedChunk;
1230
1231 clonedChunk = nextClonedChunk;
1232 }
1233
1234 originalChunk = nextOriginalChunk;
1235 }
1236
1237 cloned.lastChunk = clonedChunk;
1238
1239 if (this.indentExclusionRanges) {
1240 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1241 }
1242
1243 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
1244
1245 cloned.intro = this.intro;
1246 cloned.outro = this.outro;
1247
1248 return cloned;
1249 }
1250
1251 generateDecodedMap(options) {
1252 options = options || {};
1253
1254 const sourceIndex = 0;
1255 const names = Object.keys(this.storedNames);
1256 const mappings = new Mappings(options.hires);
1257
1258 const locate = getLocator(this.original);
1259
1260 if (this.intro) {
1261 mappings.advance(this.intro);
1262 }
1263
1264 this.firstChunk.eachNext((chunk) => {
1265 const loc = locate(chunk.start);
1266
1267 if (chunk.intro.length) mappings.advance(chunk.intro);
1268
1269 if (chunk.edited) {
1270 mappings.addEdit(
1271 sourceIndex,
1272 chunk.content,
1273 loc,
1274 chunk.storeName ? names.indexOf(chunk.original) : -1
1275 );
1276 } else {
1277 mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
1278 }
1279
1280 if (chunk.outro.length) mappings.advance(chunk.outro);
1281 });
1282
1283 return {
1284 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1285 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1286 sourcesContent: options.includeContent ? [this.original] : [null],
1287 names,
1288 mappings: mappings.raw,
1289 };
1290 }
1291
1292 generateMap(options) {
1293 return new SourceMap(this.generateDecodedMap(options));
1294 }
1295
1296 getIndentString() {
1297 return this.indentStr === null ? '\t' : this.indentStr;
1298 }
1299
1300 indent(indentStr, options) {
1301 const pattern = /^[^\r\n]/gm;
1302
1303 if (isObject$1(indentStr)) {
1304 options = indentStr;
1305 indentStr = undefined;
1306 }
1307
1308 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1309
1310 if (indentStr === '') return this; // noop
1311
1312 options = options || {};
1313
1314 // Process exclusion ranges
1315 const isExcluded = {};
1316
1317 if (options.exclude) {
1318 const exclusions =
1319 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1320 exclusions.forEach((exclusion) => {
1321 for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
1322 isExcluded[i] = true;
1323 }
1324 });
1325 }
1326
1327 let shouldIndentNextCharacter = options.indentStart !== false;
1328 const replacer = (match) => {
1329 if (shouldIndentNextCharacter) return `${indentStr}${match}`;
1330 shouldIndentNextCharacter = true;
1331 return match;
1332 };
1333
1334 this.intro = this.intro.replace(pattern, replacer);
1335
1336 let charIndex = 0;
1337 let chunk = this.firstChunk;
1338
1339 while (chunk) {
1340 const end = chunk.end;
1341
1342 if (chunk.edited) {
1343 if (!isExcluded[charIndex]) {
1344 chunk.content = chunk.content.replace(pattern, replacer);
1345
1346 if (chunk.content.length) {
1347 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1348 }
1349 }
1350 } else {
1351 charIndex = chunk.start;
1352
1353 while (charIndex < end) {
1354 if (!isExcluded[charIndex]) {
1355 const char = this.original[charIndex];
1356
1357 if (char === '\n') {
1358 shouldIndentNextCharacter = true;
1359 } else if (char !== '\r' && shouldIndentNextCharacter) {
1360 shouldIndentNextCharacter = false;
1361
1362 if (charIndex === chunk.start) {
1363 chunk.prependRight(indentStr);
1364 } else {
1365 this._splitChunk(chunk, charIndex);
1366 chunk = chunk.next;
1367 chunk.prependRight(indentStr);
1368 }
1369 }
1370 }
1371
1372 charIndex += 1;
1373 }
1374 }
1375
1376 charIndex = chunk.end;
1377 chunk = chunk.next;
1378 }
1379
1380 this.outro = this.outro.replace(pattern, replacer);
1381
1382 return this;
1383 }
1384
1385 insert() {
1386 throw new Error(
1387 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
1388 );
1389 }
1390
1391 insertLeft(index, content) {
1392 if (!warned.insertLeft) {
1393 console.warn(
1394 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
1395 ); // eslint-disable-line no-console
1396 warned.insertLeft = true;
1397 }
1398
1399 return this.appendLeft(index, content);
1400 }
1401
1402 insertRight(index, content) {
1403 if (!warned.insertRight) {
1404 console.warn(
1405 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
1406 ); // eslint-disable-line no-console
1407 warned.insertRight = true;
1408 }
1409
1410 return this.prependRight(index, content);
1411 }
1412
1413 move(start, end, index) {
1414 if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
1415
1416 this._split(start);
1417 this._split(end);
1418 this._split(index);
1419
1420 const first = this.byStart[start];
1421 const last = this.byEnd[end];
1422
1423 const oldLeft = first.previous;
1424 const oldRight = last.next;
1425
1426 const newRight = this.byStart[index];
1427 if (!newRight && last === this.lastChunk) return this;
1428 const newLeft = newRight ? newRight.previous : this.lastChunk;
1429
1430 if (oldLeft) oldLeft.next = oldRight;
1431 if (oldRight) oldRight.previous = oldLeft;
1432
1433 if (newLeft) newLeft.next = first;
1434 if (newRight) newRight.previous = last;
1435
1436 if (!first.previous) this.firstChunk = last.next;
1437 if (!last.next) {
1438 this.lastChunk = first.previous;
1439 this.lastChunk.next = null;
1440 }
1441
1442 first.previous = newLeft;
1443 last.next = newRight || null;
1444
1445 if (!newLeft) this.firstChunk = first;
1446 if (!newRight) this.lastChunk = last;
1447 return this;
1448 }
1449
1450 overwrite(start, end, content, options) {
1451 if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
1452
1453 while (start < 0) start += this.original.length;
1454 while (end < 0) end += this.original.length;
1455
1456 if (end > this.original.length) throw new Error('end is out of bounds');
1457 if (start === end)
1458 throw new Error(
1459 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
1460 );
1461
1462 this._split(start);
1463 this._split(end);
1464
1465 if (options === true) {
1466 if (!warned.storeName) {
1467 console.warn(
1468 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
1469 ); // eslint-disable-line no-console
1470 warned.storeName = true;
1471 }
1472
1473 options = { storeName: true };
1474 }
1475 const storeName = options !== undefined ? options.storeName : false;
1476 const contentOnly = options !== undefined ? options.contentOnly : false;
1477
1478 if (storeName) {
1479 const original = this.original.slice(start, end);
1480 Object.defineProperty(this.storedNames, original, {
1481 writable: true,
1482 value: true,
1483 enumerable: true,
1484 });
1485 }
1486
1487 const first = this.byStart[start];
1488 const last = this.byEnd[end];
1489
1490 if (first) {
1491 let chunk = first;
1492 while (chunk !== last) {
1493 if (chunk.next !== this.byStart[chunk.end]) {
1494 throw new Error('Cannot overwrite across a split point');
1495 }
1496 chunk = chunk.next;
1497 chunk.edit('', false);
1498 }
1499
1500 first.edit(content, storeName, contentOnly);
1501 } else {
1502 // must be inserting at the end
1503 const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
1504
1505 // TODO last chunk in the array may not be the last chunk, if it's moved...
1506 last.next = newChunk;
1507 newChunk.previous = last;
1508 }
1509 return this;
1510 }
1511
1512 prepend(content) {
1513 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1514
1515 this.intro = content + this.intro;
1516 return this;
1517 }
1518
1519 prependLeft(index, content) {
1520 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1521
1522 this._split(index);
1523
1524 const chunk = this.byEnd[index];
1525
1526 if (chunk) {
1527 chunk.prependLeft(content);
1528 } else {
1529 this.intro = content + this.intro;
1530 }
1531 return this;
1532 }
1533
1534 prependRight(index, content) {
1535 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1536
1537 this._split(index);
1538
1539 const chunk = this.byStart[index];
1540
1541 if (chunk) {
1542 chunk.prependRight(content);
1543 } else {
1544 this.outro = content + this.outro;
1545 }
1546 return this;
1547 }
1548
1549 remove(start, end) {
1550 while (start < 0) start += this.original.length;
1551 while (end < 0) end += this.original.length;
1552
1553 if (start === end) return this;
1554
1555 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1556 if (start > end) throw new Error('end must be greater than start');
1557
1558 this._split(start);
1559 this._split(end);
1560
1561 let chunk = this.byStart[start];
1562
1563 while (chunk) {
1564 chunk.intro = '';
1565 chunk.outro = '';
1566 chunk.edit('');
1567
1568 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1569 }
1570 return this;
1571 }
1572
1573 lastChar() {
1574 if (this.outro.length) return this.outro[this.outro.length - 1];
1575 let chunk = this.lastChunk;
1576 do {
1577 if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1578 if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1579 if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1580 } while ((chunk = chunk.previous));
1581 if (this.intro.length) return this.intro[this.intro.length - 1];
1582 return '';
1583 }
1584
1585 lastLine() {
1586 let lineIndex = this.outro.lastIndexOf(n);
1587 if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1588 let lineStr = this.outro;
1589 let chunk = this.lastChunk;
1590 do {
1591 if (chunk.outro.length > 0) {
1592 lineIndex = chunk.outro.lastIndexOf(n);
1593 if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1594 lineStr = chunk.outro + lineStr;
1595 }
1596
1597 if (chunk.content.length > 0) {
1598 lineIndex = chunk.content.lastIndexOf(n);
1599 if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1600 lineStr = chunk.content + lineStr;
1601 }
1602
1603 if (chunk.intro.length > 0) {
1604 lineIndex = chunk.intro.lastIndexOf(n);
1605 if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1606 lineStr = chunk.intro + lineStr;
1607 }
1608 } while ((chunk = chunk.previous));
1609 lineIndex = this.intro.lastIndexOf(n);
1610 if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1611 return this.intro + lineStr;
1612 }
1613
1614 slice(start = 0, end = this.original.length) {
1615 while (start < 0) start += this.original.length;
1616 while (end < 0) end += this.original.length;
1617
1618 let result = '';
1619
1620 // find start chunk
1621 let chunk = this.firstChunk;
1622 while (chunk && (chunk.start > start || chunk.end <= start)) {
1623 // found end chunk before start
1624 if (chunk.start < end && chunk.end >= end) {
1625 return result;
1626 }
1627
1628 chunk = chunk.next;
1629 }
1630
1631 if (chunk && chunk.edited && chunk.start !== start)
1632 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1633
1634 const startChunk = chunk;
1635 while (chunk) {
1636 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1637 result += chunk.intro;
1638 }
1639
1640 const containsEnd = chunk.start < end && chunk.end >= end;
1641 if (containsEnd && chunk.edited && chunk.end !== end)
1642 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1643
1644 const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1645 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1646
1647 result += chunk.content.slice(sliceStart, sliceEnd);
1648
1649 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1650 result += chunk.outro;
1651 }
1652
1653 if (containsEnd) {
1654 break;
1655 }
1656
1657 chunk = chunk.next;
1658 }
1659
1660 return result;
1661 }
1662
1663 // TODO deprecate this? not really very useful
1664 snip(start, end) {
1665 const clone = this.clone();
1666 clone.remove(0, start);
1667 clone.remove(end, clone.original.length);
1668
1669 return clone;
1670 }
1671
1672 _split(index) {
1673 if (this.byStart[index] || this.byEnd[index]) return;
1674
1675 let chunk = this.lastSearchedChunk;
1676 const searchForward = index > chunk.end;
1677
1678 while (chunk) {
1679 if (chunk.contains(index)) return this._splitChunk(chunk, index);
1680
1681 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1682 }
1683 }
1684
1685 _splitChunk(chunk, index) {
1686 if (chunk.edited && chunk.content.length) {
1687 // zero-length edited chunks are a special case (overlapping replacements)
1688 const loc = getLocator(this.original)(index);
1689 throw new Error(
1690 `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
1691 );
1692 }
1693
1694 const newChunk = chunk.split(index);
1695
1696 this.byEnd[index] = chunk;
1697 this.byStart[index] = newChunk;
1698 this.byEnd[newChunk.end] = newChunk;
1699
1700 if (chunk === this.lastChunk) this.lastChunk = newChunk;
1701
1702 this.lastSearchedChunk = chunk;
1703 return true;
1704 }
1705
1706 toString() {
1707 let str = this.intro;
1708
1709 let chunk = this.firstChunk;
1710 while (chunk) {
1711 str += chunk.toString();
1712 chunk = chunk.next;
1713 }
1714
1715 return str + this.outro;
1716 }
1717
1718 isEmpty() {
1719 let chunk = this.firstChunk;
1720 do {
1721 if (
1722 (chunk.intro.length && chunk.intro.trim()) ||
1723 (chunk.content.length && chunk.content.trim()) ||
1724 (chunk.outro.length && chunk.outro.trim())
1725 )
1726 return false;
1727 } while ((chunk = chunk.next));
1728 return true;
1729 }
1730
1731 length() {
1732 let chunk = this.firstChunk;
1733 let length = 0;
1734 do {
1735 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1736 } while ((chunk = chunk.next));
1737 return length;
1738 }
1739
1740 trimLines() {
1741 return this.trim('[\\r\\n]');
1742 }
1743
1744 trim(charType) {
1745 return this.trimStart(charType).trimEnd(charType);
1746 }
1747
1748 trimEndAborted(charType) {
1749 const rx = new RegExp((charType || '\\s') + '+$');
1750
1751 this.outro = this.outro.replace(rx, '');
1752 if (this.outro.length) return true;
1753
1754 let chunk = this.lastChunk;
1755
1756 do {
1757 const end = chunk.end;
1758 const aborted = chunk.trimEnd(rx);
1759
1760 // if chunk was trimmed, we have a new lastChunk
1761 if (chunk.end !== end) {
1762 if (this.lastChunk === chunk) {
1763 this.lastChunk = chunk.next;
1764 }
1765
1766 this.byEnd[chunk.end] = chunk;
1767 this.byStart[chunk.next.start] = chunk.next;
1768 this.byEnd[chunk.next.end] = chunk.next;
1769 }
1770
1771 if (aborted) return true;
1772 chunk = chunk.previous;
1773 } while (chunk);
1774
1775 return false;
1776 }
1777
1778 trimEnd(charType) {
1779 this.trimEndAborted(charType);
1780 return this;
1781 }
1782 trimStartAborted(charType) {
1783 const rx = new RegExp('^' + (charType || '\\s') + '+');
1784
1785 this.intro = this.intro.replace(rx, '');
1786 if (this.intro.length) return true;
1787
1788 let chunk = this.firstChunk;
1789
1790 do {
1791 const end = chunk.end;
1792 const aborted = chunk.trimStart(rx);
1793
1794 if (chunk.end !== end) {
1795 // special case...
1796 if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1797
1798 this.byEnd[chunk.end] = chunk;
1799 this.byStart[chunk.next.start] = chunk.next;
1800 this.byEnd[chunk.next.end] = chunk.next;
1801 }
1802
1803 if (aborted) return true;
1804 chunk = chunk.next;
1805 } while (chunk);
1806
1807 return false;
1808 }
1809
1810 trimStart(charType) {
1811 this.trimStartAborted(charType);
1812 return this;
1813 }
1814
1815 hasChanged() {
1816 return this.original !== this.toString();
1817 }
1818
1819 replace(searchValue, replacement) {
1820 function getReplacement(match, str) {
1821 if (typeof replacement === 'string') {
1822 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1823 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1824 if (i === '$') return '$';
1825 if (i === '&') return match[0];
1826 const num = +i;
1827 if (num < match.length) return match[+i];
1828 return `$${i}`;
1829 });
1830 } else {
1831 return replacement(...match, match.index, str, match.groups);
1832 }
1833 }
1834 function matchAll(re, str) {
1835 let match;
1836 const matches = [];
1837 while ((match = re.exec(str))) {
1838 matches.push(match);
1839 }
1840 return matches;
1841 }
1842 if (typeof searchValue !== 'string' && searchValue.global) {
1843 const matches = matchAll(searchValue, this.original);
1844 matches.forEach((match) => {
1845 if (match.index != null)
1846 this.overwrite(
1847 match.index,
1848 match.index + match[0].length,
1849 getReplacement(match, this.original)
1850 );
1851 });
1852 } else {
1853 const match = this.original.match(searchValue);
1854 if (match && match.index != null)
1855 this.overwrite(
1856 match.index,
1857 match.index + match[0].length,
1858 getReplacement(match, this.original)
1859 );
1860 }
1861 return this;
1862 }
1863}
1864
1865const hasOwnProp = Object.prototype.hasOwnProperty;
1866
1867class Bundle$1 {
1868 constructor(options = {}) {
1869 this.intro = options.intro || '';
1870 this.separator = options.separator !== undefined ? options.separator : '\n';
1871 this.sources = [];
1872 this.uniqueSources = [];
1873 this.uniqueSourceIndexByFilename = {};
1874 }
1875
1876 addSource(source) {
1877 if (source instanceof MagicString) {
1878 return this.addSource({
1879 content: source,
1880 filename: source.filename,
1881 separator: this.separator,
1882 });
1883 }
1884
1885 if (!isObject$1(source) || !source.content) {
1886 throw new Error(
1887 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
1888 );
1889 }
1890
1891 ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
1892 if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
1893 });
1894
1895 if (source.separator === undefined) {
1896 // TODO there's a bunch of this sort of thing, needs cleaning up
1897 source.separator = this.separator;
1898 }
1899
1900 if (source.filename) {
1901 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1902 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1903 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1904 } else {
1905 const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1906 if (source.content.original !== uniqueSource.content) {
1907 throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
1908 }
1909 }
1910 }
1911
1912 this.sources.push(source);
1913 return this;
1914 }
1915
1916 append(str, options) {
1917 this.addSource({
1918 content: new MagicString(str),
1919 separator: (options && options.separator) || '',
1920 });
1921
1922 return this;
1923 }
1924
1925 clone() {
1926 const bundle = new Bundle$1({
1927 intro: this.intro,
1928 separator: this.separator,
1929 });
1930
1931 this.sources.forEach((source) => {
1932 bundle.addSource({
1933 filename: source.filename,
1934 content: source.content.clone(),
1935 separator: source.separator,
1936 });
1937 });
1938
1939 return bundle;
1940 }
1941
1942 generateDecodedMap(options = {}) {
1943 const names = [];
1944 this.sources.forEach((source) => {
1945 Object.keys(source.content.storedNames).forEach((name) => {
1946 if (!~names.indexOf(name)) names.push(name);
1947 });
1948 });
1949
1950 const mappings = new Mappings(options.hires);
1951
1952 if (this.intro) {
1953 mappings.advance(this.intro);
1954 }
1955
1956 this.sources.forEach((source, i) => {
1957 if (i > 0) {
1958 mappings.advance(this.separator);
1959 }
1960
1961 const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
1962 const magicString = source.content;
1963 const locate = getLocator(magicString.original);
1964
1965 if (magicString.intro) {
1966 mappings.advance(magicString.intro);
1967 }
1968
1969 magicString.firstChunk.eachNext((chunk) => {
1970 const loc = locate(chunk.start);
1971
1972 if (chunk.intro.length) mappings.advance(chunk.intro);
1973
1974 if (source.filename) {
1975 if (chunk.edited) {
1976 mappings.addEdit(
1977 sourceIndex,
1978 chunk.content,
1979 loc,
1980 chunk.storeName ? names.indexOf(chunk.original) : -1
1981 );
1982 } else {
1983 mappings.addUneditedChunk(
1984 sourceIndex,
1985 chunk,
1986 magicString.original,
1987 loc,
1988 magicString.sourcemapLocations
1989 );
1990 }
1991 } else {
1992 mappings.advance(chunk.content);
1993 }
1994
1995 if (chunk.outro.length) mappings.advance(chunk.outro);
1996 });
1997
1998 if (magicString.outro) {
1999 mappings.advance(magicString.outro);
2000 }
2001 });
2002
2003 return {
2004 file: options.file ? options.file.split(/[/\\]/).pop() : null,
2005 sources: this.uniqueSources.map((source) => {
2006 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
2007 }),
2008 sourcesContent: this.uniqueSources.map((source) => {
2009 return options.includeContent ? source.content : null;
2010 }),
2011 names,
2012 mappings: mappings.raw,
2013 };
2014 }
2015
2016 generateMap(options) {
2017 return new SourceMap(this.generateDecodedMap(options));
2018 }
2019
2020 getIndentString() {
2021 const indentStringCounts = {};
2022
2023 this.sources.forEach((source) => {
2024 const indentStr = source.content.indentStr;
2025
2026 if (indentStr === null) return;
2027
2028 if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
2029 indentStringCounts[indentStr] += 1;
2030 });
2031
2032 return (
2033 Object.keys(indentStringCounts).sort((a, b) => {
2034 return indentStringCounts[a] - indentStringCounts[b];
2035 })[0] || '\t'
2036 );
2037 }
2038
2039 indent(indentStr) {
2040 if (!arguments.length) {
2041 indentStr = this.getIndentString();
2042 }
2043
2044 if (indentStr === '') return this; // noop
2045
2046 let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
2047
2048 this.sources.forEach((source, i) => {
2049 const separator = source.separator !== undefined ? source.separator : this.separator;
2050 const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
2051
2052 source.content.indent(indentStr, {
2053 exclude: source.indentExclusionRanges,
2054 indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
2055 });
2056
2057 trailingNewline = source.content.lastChar() === '\n';
2058 });
2059
2060 if (this.intro) {
2061 this.intro =
2062 indentStr +
2063 this.intro.replace(/^[^\n]/gm, (match, index) => {
2064 return index > 0 ? indentStr + match : match;
2065 });
2066 }
2067
2068 return this;
2069 }
2070
2071 prepend(str) {
2072 this.intro = str + this.intro;
2073 return this;
2074 }
2075
2076 toString() {
2077 const body = this.sources
2078 .map((source, i) => {
2079 const separator = source.separator !== undefined ? source.separator : this.separator;
2080 const str = (i > 0 ? separator : '') + source.content.toString();
2081
2082 return str;
2083 })
2084 .join('');
2085
2086 return this.intro + body;
2087 }
2088
2089 isEmpty() {
2090 if (this.intro.length && this.intro.trim()) return false;
2091 if (this.sources.some((source) => !source.content.isEmpty())) return false;
2092 return true;
2093 }
2094
2095 length() {
2096 return this.sources.reduce(
2097 (length, source) => length + source.content.length(),
2098 this.intro.length
2099 );
2100 }
2101
2102 trimLines() {
2103 return this.trim('[\\r\\n]');
2104 }
2105
2106 trim(charType) {
2107 return this.trimStart(charType).trimEnd(charType);
2108 }
2109
2110 trimStart(charType) {
2111 const rx = new RegExp('^' + (charType || '\\s') + '+');
2112 this.intro = this.intro.replace(rx, '');
2113
2114 if (!this.intro) {
2115 let source;
2116 let i = 0;
2117
2118 do {
2119 source = this.sources[i++];
2120 if (!source) {
2121 break;
2122 }
2123 } while (!source.content.trimStartAborted(charType));
2124 }
2125
2126 return this;
2127 }
2128
2129 trimEnd(charType) {
2130 const rx = new RegExp((charType || '\\s') + '+$');
2131
2132 let source;
2133 let i = this.sources.length - 1;
2134
2135 do {
2136 source = this.sources[i--];
2137 if (!source) {
2138 this.intro = this.intro.replace(rx, '');
2139 break;
2140 }
2141 } while (!source.content.trimEndAborted(charType));
2142
2143 return this;
2144 }
2145}
2146
2147function getOrCreate(map, key, init) {
2148 const existing = map.get(key);
2149 if (existing) {
2150 return existing;
2151 }
2152 const value = init();
2153 map.set(key, value);
2154 return value;
2155}
2156
2157const UnknownKey = Symbol('Unknown Key');
2158const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
2159const UnknownInteger = Symbol('Unknown Integer');
2160const EMPTY_PATH = [];
2161const UNKNOWN_PATH = [UnknownKey];
2162// For deoptimizations, this means we are modifying an unknown property but did
2163// not lose track of the object or are creating a setter/getter;
2164// For assignment effects it means we do not check for setter/getter effects
2165// but only if something is mutated that is included, which is relevant for
2166// Object.defineProperty
2167const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
2168const UNKNOWN_INTEGER_PATH = [UnknownInteger];
2169const EntitiesKey = Symbol('Entities');
2170class PathTracker {
2171 constructor() {
2172 this.entityPaths = Object.create(null, {
2173 [EntitiesKey]: { value: new Set() }
2174 });
2175 }
2176 trackEntityAtPathAndGetIfTracked(path, entity) {
2177 const trackedEntities = this.getEntities(path);
2178 if (trackedEntities.has(entity))
2179 return true;
2180 trackedEntities.add(entity);
2181 return false;
2182 }
2183 withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
2184 const trackedEntities = this.getEntities(path);
2185 if (trackedEntities.has(entity))
2186 return returnIfTracked;
2187 trackedEntities.add(entity);
2188 const result = onUntracked();
2189 trackedEntities.delete(entity);
2190 return result;
2191 }
2192 getEntities(path) {
2193 let currentPaths = this.entityPaths;
2194 for (const pathSegment of path) {
2195 currentPaths = currentPaths[pathSegment] =
2196 currentPaths[pathSegment] ||
2197 Object.create(null, { [EntitiesKey]: { value: new Set() } });
2198 }
2199 return currentPaths[EntitiesKey];
2200 }
2201}
2202const SHARED_RECURSION_TRACKER = new PathTracker();
2203class DiscriminatedPathTracker {
2204 constructor() {
2205 this.entityPaths = Object.create(null, {
2206 [EntitiesKey]: { value: new Map() }
2207 });
2208 }
2209 trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
2210 let currentPaths = this.entityPaths;
2211 for (const pathSegment of path) {
2212 currentPaths = currentPaths[pathSegment] =
2213 currentPaths[pathSegment] ||
2214 Object.create(null, { [EntitiesKey]: { value: new Map() } });
2215 }
2216 const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
2217 if (trackedEntities.has(entity))
2218 return true;
2219 trackedEntities.add(entity);
2220 return false;
2221 }
2222}
2223
2224const UnknownValue = Symbol('Unknown Value');
2225const UnknownTruthyValue = Symbol('Unknown Truthy Value');
2226class ExpressionEntity {
2227 constructor() {
2228 this.included = false;
2229 }
2230 deoptimizePath(_path) { }
2231 deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
2232 thisArg.deoptimizePath(UNKNOWN_PATH);
2233 }
2234 /**
2235 * If possible it returns a stringifyable literal value for this node that can be used
2236 * for inlining or comparing values.
2237 * Otherwise it should return UnknownValue.
2238 */
2239 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2240 return UnknownValue;
2241 }
2242 getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
2243 return UNKNOWN_EXPRESSION;
2244 }
2245 hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
2246 return true;
2247 }
2248 include(_context, _includeChildrenRecursively, _options) {
2249 this.included = true;
2250 }
2251 includeCallArguments(context, args) {
2252 for (const arg of args) {
2253 arg.include(context, false);
2254 }
2255 }
2256 shouldBeIncluded(_context) {
2257 return true;
2258 }
2259}
2260const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
2261})();
2262
2263const INTERACTION_ACCESSED = 0;
2264const INTERACTION_ASSIGNED = 1;
2265const INTERACTION_CALLED = 2;
2266const NODE_INTERACTION_UNKNOWN_ACCESS = {
2267 thisArg: null,
2268 type: INTERACTION_ACCESSED
2269};
2270const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
2271const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
2272 args: UNKNOWN_ARG,
2273 thisArg: null,
2274 type: INTERACTION_ASSIGNED
2275};
2276const NO_ARGS = [];
2277// While this is technically a call without arguments, we can compare against
2278// this reference in places where precise values or thisArg would make a
2279// difference
2280const NODE_INTERACTION_UNKNOWN_CALL = {
2281 args: NO_ARGS,
2282 thisArg: null,
2283 type: INTERACTION_CALLED,
2284 withNew: false
2285};
2286
2287class Variable extends ExpressionEntity {
2288 constructor(name) {
2289 super();
2290 this.name = name;
2291 this.alwaysRendered = false;
2292 this.initReached = false;
2293 this.isId = false;
2294 this.isReassigned = false;
2295 this.kind = null;
2296 this.renderBaseName = null;
2297 this.renderName = null;
2298 }
2299 /**
2300 * Binds identifiers that reference this variable to this variable.
2301 * Necessary to be able to change variable names.
2302 */
2303 addReference(_identifier) { }
2304 getBaseVariableName() {
2305 return this.renderBaseName || this.renderName || this.name;
2306 }
2307 getName(getPropertyAccess) {
2308 const name = this.renderName || this.name;
2309 return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
2310 }
2311 hasEffectsOnInteractionAtPath(path, { type }, _context) {
2312 return type !== INTERACTION_ACCESSED || path.length > 0;
2313 }
2314 /**
2315 * Marks this variable as being part of the bundle, which is usually the case when one of
2316 * its identifiers becomes part of the bundle. Returns true if it has not been included
2317 * previously.
2318 * Once a variable is included, it should take care all its declarations are included.
2319 */
2320 include() {
2321 this.included = true;
2322 }
2323 markCalledFromTryStatement() { }
2324 setRenderNames(baseName, name) {
2325 this.renderBaseName = baseName;
2326 this.renderName = name;
2327 }
2328}
2329
2330class ExternalVariable extends Variable {
2331 constructor(module, name) {
2332 super(name);
2333 this.referenced = false;
2334 this.module = module;
2335 this.isNamespace = name === '*';
2336 }
2337 addReference(identifier) {
2338 this.referenced = true;
2339 if (this.name === 'default' || this.name === '*') {
2340 this.module.suggestName(identifier.name);
2341 }
2342 }
2343 hasEffectsOnInteractionAtPath(path, { type }) {
2344 return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
2345 }
2346 include() {
2347 if (!this.included) {
2348 this.included = true;
2349 this.module.used = true;
2350 }
2351 }
2352}
2353
2354const BLANK = Object.freeze(Object.create(null));
2355const EMPTY_OBJECT = Object.freeze({});
2356const EMPTY_ARRAY = Object.freeze([]);
2357
2358const RESERVED_NAMES = new Set([
2359 'await',
2360 'break',
2361 'case',
2362 'catch',
2363 'class',
2364 'const',
2365 'continue',
2366 'debugger',
2367 'default',
2368 'delete',
2369 'do',
2370 'else',
2371 'enum',
2372 'eval',
2373 'export',
2374 'extends',
2375 'false',
2376 'finally',
2377 'for',
2378 'function',
2379 'if',
2380 'implements',
2381 'import',
2382 'in',
2383 'instanceof',
2384 'interface',
2385 'let',
2386 'NaN',
2387 'new',
2388 'null',
2389 'package',
2390 'private',
2391 'protected',
2392 'public',
2393 'return',
2394 'static',
2395 'super',
2396 'switch',
2397 'this',
2398 'throw',
2399 'true',
2400 'try',
2401 'typeof',
2402 'undefined',
2403 'var',
2404 'void',
2405 'while',
2406 'with',
2407 'yield'
2408]);
2409const RESERVED_NAMES$1 = RESERVED_NAMES;
2410
2411const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2412const startsWithDigit = (str) => /\d/.test(str[0]);
2413function isLegal(str) {
2414 if (startsWithDigit(str) || RESERVED_NAMES$1.has(str)) {
2415 return false;
2416 }
2417 return !illegalCharacters.test(str);
2418}
2419function makeLegal(str) {
2420 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2421 if (startsWithDigit(str) || RESERVED_NAMES$1.has(str))
2422 str = `_${str}`;
2423 return str || '_';
2424}
2425
2426class ExternalModule {
2427 constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
2428 this.options = options;
2429 this.id = id;
2430 this.renormalizeRenderPath = renormalizeRenderPath;
2431 this.declarations = new Map();
2432 this.defaultVariableName = '';
2433 this.dynamicImporters = [];
2434 this.execIndex = Infinity;
2435 this.exportedVariables = new Map();
2436 this.importers = [];
2437 this.mostCommonSuggestion = 0;
2438 this.nameSuggestions = new Map();
2439 this.namespaceVariableName = '';
2440 this.reexported = false;
2441 this.renderPath = undefined;
2442 this.used = false;
2443 this.variableName = '';
2444 this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2445 const { importers, dynamicImporters } = this;
2446 const info = (this.info = {
2447 ast: null,
2448 code: null,
2449 dynamicallyImportedIdResolutions: EMPTY_ARRAY,
2450 dynamicallyImportedIds: EMPTY_ARRAY,
2451 get dynamicImporters() {
2452 return dynamicImporters.sort();
2453 },
2454 hasDefaultExport: null,
2455 get hasModuleSideEffects() {
2456 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
2457 return info.moduleSideEffects;
2458 },
2459 id,
2460 implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
2461 implicitlyLoadedBefore: EMPTY_ARRAY,
2462 importedIdResolutions: EMPTY_ARRAY,
2463 importedIds: EMPTY_ARRAY,
2464 get importers() {
2465 return importers.sort();
2466 },
2467 isEntry: false,
2468 isExternal: true,
2469 isIncluded: null,
2470 meta,
2471 moduleSideEffects,
2472 syntheticNamedExports: false
2473 });
2474 // Hide the deprecated key so that it only warns when accessed explicitly
2475 Object.defineProperty(this.info, 'hasModuleSideEffects', {
2476 enumerable: false
2477 });
2478 }
2479 getVariableForExportName(name) {
2480 const declaration = this.declarations.get(name);
2481 if (declaration)
2482 return [declaration];
2483 const externalVariable = new ExternalVariable(this, name);
2484 this.declarations.set(name, externalVariable);
2485 this.exportedVariables.set(externalVariable, name);
2486 return [externalVariable];
2487 }
2488 setRenderPath(options, inputBase) {
2489 this.renderPath =
2490 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2491 if (!this.renderPath) {
2492 this.renderPath = this.renormalizeRenderPath
2493 ? normalize(require$$0.relative(inputBase, this.id))
2494 : this.id;
2495 }
2496 }
2497 suggestName(name) {
2498 var _a;
2499 const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
2500 this.nameSuggestions.set(name, value);
2501 if (value > this.mostCommonSuggestion) {
2502 this.mostCommonSuggestion = value;
2503 this.suggestedVariableName = name;
2504 }
2505 }
2506 warnUnusedImports() {
2507 const unused = Array.from(this.declarations)
2508 .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
2509 .map(([name]) => name);
2510 if (unused.length === 0)
2511 return;
2512 const importersSet = new Set();
2513 for (const name of unused) {
2514 for (const importer of this.declarations.get(name).module.importers) {
2515 importersSet.add(importer);
2516 }
2517 }
2518 const importersArray = [...importersSet];
2519 this.options.onwarn({
2520 code: 'UNUSED_EXTERNAL_IMPORT',
2521 message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
2522 names: unused,
2523 source: this.id,
2524 sources: importersArray
2525 });
2526 }
2527}
2528
2529var picomatch$1 = {exports: {}};
2530
2531var utils$3 = {};
2532
2533const path$1 = require$$0;
2534const WIN_SLASH = '\\\\/';
2535const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2536
2537/**
2538 * Posix glob regex
2539 */
2540
2541const DOT_LITERAL = '\\.';
2542const PLUS_LITERAL = '\\+';
2543const QMARK_LITERAL = '\\?';
2544const SLASH_LITERAL = '\\/';
2545const ONE_CHAR = '(?=.)';
2546const QMARK = '[^/]';
2547const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
2548const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
2549const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
2550const NO_DOT = `(?!${DOT_LITERAL})`;
2551const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
2552const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
2553const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
2554const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
2555const STAR = `${QMARK}*?`;
2556
2557const POSIX_CHARS = {
2558 DOT_LITERAL,
2559 PLUS_LITERAL,
2560 QMARK_LITERAL,
2561 SLASH_LITERAL,
2562 ONE_CHAR,
2563 QMARK,
2564 END_ANCHOR,
2565 DOTS_SLASH,
2566 NO_DOT,
2567 NO_DOTS,
2568 NO_DOT_SLASH,
2569 NO_DOTS_SLASH,
2570 QMARK_NO_DOT,
2571 STAR,
2572 START_ANCHOR
2573};
2574
2575/**
2576 * Windows glob regex
2577 */
2578
2579const WINDOWS_CHARS = {
2580 ...POSIX_CHARS,
2581
2582 SLASH_LITERAL: `[${WIN_SLASH}]`,
2583 QMARK: WIN_NO_SLASH,
2584 STAR: `${WIN_NO_SLASH}*?`,
2585 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
2586 NO_DOT: `(?!${DOT_LITERAL})`,
2587 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2588 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
2589 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2590 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
2591 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
2592 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
2593};
2594
2595/**
2596 * POSIX Bracket Regex
2597 */
2598
2599const POSIX_REGEX_SOURCE$1 = {
2600 alnum: 'a-zA-Z0-9',
2601 alpha: 'a-zA-Z',
2602 ascii: '\\x00-\\x7F',
2603 blank: ' \\t',
2604 cntrl: '\\x00-\\x1F\\x7F',
2605 digit: '0-9',
2606 graph: '\\x21-\\x7E',
2607 lower: 'a-z',
2608 print: '\\x20-\\x7E ',
2609 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
2610 space: ' \\t\\r\\n\\v\\f',
2611 upper: 'A-Z',
2612 word: 'A-Za-z0-9_',
2613 xdigit: 'A-Fa-f0-9'
2614};
2615
2616var constants$2 = {
2617 MAX_LENGTH: 1024 * 64,
2618 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
2619
2620 // regular expressions
2621 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
2622 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
2623 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
2624 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
2625 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
2626 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2627
2628 // Replace globs with equivalent patterns to reduce parsing time.
2629 REPLACEMENTS: {
2630 '***': '*',
2631 '**/**': '**',
2632 '**/**/**': '**'
2633 },
2634
2635 // Digits
2636 CHAR_0: 48, /* 0 */
2637 CHAR_9: 57, /* 9 */
2638
2639 // Alphabet chars.
2640 CHAR_UPPERCASE_A: 65, /* A */
2641 CHAR_LOWERCASE_A: 97, /* a */
2642 CHAR_UPPERCASE_Z: 90, /* Z */
2643 CHAR_LOWERCASE_Z: 122, /* z */
2644
2645 CHAR_LEFT_PARENTHESES: 40, /* ( */
2646 CHAR_RIGHT_PARENTHESES: 41, /* ) */
2647
2648 CHAR_ASTERISK: 42, /* * */
2649
2650 // Non-alphabetic chars.
2651 CHAR_AMPERSAND: 38, /* & */
2652 CHAR_AT: 64, /* @ */
2653 CHAR_BACKWARD_SLASH: 92, /* \ */
2654 CHAR_CARRIAGE_RETURN: 13, /* \r */
2655 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
2656 CHAR_COLON: 58, /* : */
2657 CHAR_COMMA: 44, /* , */
2658 CHAR_DOT: 46, /* . */
2659 CHAR_DOUBLE_QUOTE: 34, /* " */
2660 CHAR_EQUAL: 61, /* = */
2661 CHAR_EXCLAMATION_MARK: 33, /* ! */
2662 CHAR_FORM_FEED: 12, /* \f */
2663 CHAR_FORWARD_SLASH: 47, /* / */
2664 CHAR_GRAVE_ACCENT: 96, /* ` */
2665 CHAR_HASH: 35, /* # */
2666 CHAR_HYPHEN_MINUS: 45, /* - */
2667 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
2668 CHAR_LEFT_CURLY_BRACE: 123, /* { */
2669 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
2670 CHAR_LINE_FEED: 10, /* \n */
2671 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
2672 CHAR_PERCENT: 37, /* % */
2673 CHAR_PLUS: 43, /* + */
2674 CHAR_QUESTION_MARK: 63, /* ? */
2675 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
2676 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
2677 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
2678 CHAR_SEMICOLON: 59, /* ; */
2679 CHAR_SINGLE_QUOTE: 39, /* ' */
2680 CHAR_SPACE: 32, /* */
2681 CHAR_TAB: 9, /* \t */
2682 CHAR_UNDERSCORE: 95, /* _ */
2683 CHAR_VERTICAL_LINE: 124, /* | */
2684 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
2685
2686 SEP: path$1.sep,
2687
2688 /**
2689 * Create EXTGLOB_CHARS
2690 */
2691
2692 extglobChars(chars) {
2693 return {
2694 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
2695 '?': { type: 'qmark', open: '(?:', close: ')?' },
2696 '+': { type: 'plus', open: '(?:', close: ')+' },
2697 '*': { type: 'star', open: '(?:', close: ')*' },
2698 '@': { type: 'at', open: '(?:', close: ')' }
2699 };
2700 },
2701
2702 /**
2703 * Create GLOB_CHARS
2704 */
2705
2706 globChars(win32) {
2707 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
2708 }
2709};
2710
2711(function (exports) {
2712
2713 const path = require$$0;
2714 const win32 = process.platform === 'win32';
2715 const {
2716 REGEX_BACKSLASH,
2717 REGEX_REMOVE_BACKSLASH,
2718 REGEX_SPECIAL_CHARS,
2719 REGEX_SPECIAL_CHARS_GLOBAL
2720 } = constants$2;
2721
2722 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
2723 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
2724 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
2725 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
2726 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
2727
2728 exports.removeBackslashes = str => {
2729 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
2730 return match === '\\' ? '' : match;
2731 });
2732 };
2733
2734 exports.supportsLookbehinds = () => {
2735 const segs = process.version.slice(1).split('.').map(Number);
2736 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
2737 return true;
2738 }
2739 return false;
2740 };
2741
2742 exports.isWindows = options => {
2743 if (options && typeof options.windows === 'boolean') {
2744 return options.windows;
2745 }
2746 return win32 === true || path.sep === '\\';
2747 };
2748
2749 exports.escapeLast = (input, char, lastIdx) => {
2750 const idx = input.lastIndexOf(char, lastIdx);
2751 if (idx === -1) return input;
2752 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
2753 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
2754 };
2755
2756 exports.removePrefix = (input, state = {}) => {
2757 let output = input;
2758 if (output.startsWith('./')) {
2759 output = output.slice(2);
2760 state.prefix = './';
2761 }
2762 return output;
2763 };
2764
2765 exports.wrapOutput = (input, state = {}, options = {}) => {
2766 const prepend = options.contains ? '' : '^';
2767 const append = options.contains ? '' : '$';
2768
2769 let output = `${prepend}(?:${input})${append}`;
2770 if (state.negated === true) {
2771 output = `(?:^(?!${output}).*$)`;
2772 }
2773 return output;
2774 };
2775} (utils$3));
2776
2777const utils$2 = utils$3;
2778const {
2779 CHAR_ASTERISK, /* * */
2780 CHAR_AT, /* @ */
2781 CHAR_BACKWARD_SLASH, /* \ */
2782 CHAR_COMMA, /* , */
2783 CHAR_DOT, /* . */
2784 CHAR_EXCLAMATION_MARK, /* ! */
2785 CHAR_FORWARD_SLASH, /* / */
2786 CHAR_LEFT_CURLY_BRACE, /* { */
2787 CHAR_LEFT_PARENTHESES, /* ( */
2788 CHAR_LEFT_SQUARE_BRACKET, /* [ */
2789 CHAR_PLUS, /* + */
2790 CHAR_QUESTION_MARK, /* ? */
2791 CHAR_RIGHT_CURLY_BRACE, /* } */
2792 CHAR_RIGHT_PARENTHESES, /* ) */
2793 CHAR_RIGHT_SQUARE_BRACKET /* ] */
2794} = constants$2;
2795
2796const isPathSeparator = code => {
2797 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
2798};
2799
2800const depth = token => {
2801 if (token.isPrefix !== true) {
2802 token.depth = token.isGlobstar ? Infinity : 1;
2803 }
2804};
2805
2806/**
2807 * Quickly scans a glob pattern and returns an object with a handful of
2808 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
2809 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
2810 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
2811 *
2812 * ```js
2813 * const pm = require('picomatch');
2814 * console.log(pm.scan('foo/bar/*.js'));
2815 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
2816 * ```
2817 * @param {String} `str`
2818 * @param {Object} `options`
2819 * @return {Object} Returns an object with tokens and regex source string.
2820 * @api public
2821 */
2822
2823const scan$1 = (input, options) => {
2824 const opts = options || {};
2825
2826 const length = input.length - 1;
2827 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
2828 const slashes = [];
2829 const tokens = [];
2830 const parts = [];
2831
2832 let str = input;
2833 let index = -1;
2834 let start = 0;
2835 let lastIndex = 0;
2836 let isBrace = false;
2837 let isBracket = false;
2838 let isGlob = false;
2839 let isExtglob = false;
2840 let isGlobstar = false;
2841 let braceEscaped = false;
2842 let backslashes = false;
2843 let negated = false;
2844 let negatedExtglob = false;
2845 let finished = false;
2846 let braces = 0;
2847 let prev;
2848 let code;
2849 let token = { value: '', depth: 0, isGlob: false };
2850
2851 const eos = () => index >= length;
2852 const peek = () => str.charCodeAt(index + 1);
2853 const advance = () => {
2854 prev = code;
2855 return str.charCodeAt(++index);
2856 };
2857
2858 while (index < length) {
2859 code = advance();
2860 let next;
2861
2862 if (code === CHAR_BACKWARD_SLASH) {
2863 backslashes = token.backslashes = true;
2864 code = advance();
2865
2866 if (code === CHAR_LEFT_CURLY_BRACE) {
2867 braceEscaped = true;
2868 }
2869 continue;
2870 }
2871
2872 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
2873 braces++;
2874
2875 while (eos() !== true && (code = advance())) {
2876 if (code === CHAR_BACKWARD_SLASH) {
2877 backslashes = token.backslashes = true;
2878 advance();
2879 continue;
2880 }
2881
2882 if (code === CHAR_LEFT_CURLY_BRACE) {
2883 braces++;
2884 continue;
2885 }
2886
2887 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
2888 isBrace = token.isBrace = true;
2889 isGlob = token.isGlob = true;
2890 finished = true;
2891
2892 if (scanToEnd === true) {
2893 continue;
2894 }
2895
2896 break;
2897 }
2898
2899 if (braceEscaped !== true && code === CHAR_COMMA) {
2900 isBrace = token.isBrace = true;
2901 isGlob = token.isGlob = true;
2902 finished = true;
2903
2904 if (scanToEnd === true) {
2905 continue;
2906 }
2907
2908 break;
2909 }
2910
2911 if (code === CHAR_RIGHT_CURLY_BRACE) {
2912 braces--;
2913
2914 if (braces === 0) {
2915 braceEscaped = false;
2916 isBrace = token.isBrace = true;
2917 finished = true;
2918 break;
2919 }
2920 }
2921 }
2922
2923 if (scanToEnd === true) {
2924 continue;
2925 }
2926
2927 break;
2928 }
2929
2930 if (code === CHAR_FORWARD_SLASH) {
2931 slashes.push(index);
2932 tokens.push(token);
2933 token = { value: '', depth: 0, isGlob: false };
2934
2935 if (finished === true) continue;
2936 if (prev === CHAR_DOT && index === (start + 1)) {
2937 start += 2;
2938 continue;
2939 }
2940
2941 lastIndex = index + 1;
2942 continue;
2943 }
2944
2945 if (opts.noext !== true) {
2946 const isExtglobChar = code === CHAR_PLUS
2947 || code === CHAR_AT
2948 || code === CHAR_ASTERISK
2949 || code === CHAR_QUESTION_MARK
2950 || code === CHAR_EXCLAMATION_MARK;
2951
2952 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
2953 isGlob = token.isGlob = true;
2954 isExtglob = token.isExtglob = true;
2955 finished = true;
2956 if (code === CHAR_EXCLAMATION_MARK && index === start) {
2957 negatedExtglob = true;
2958 }
2959
2960 if (scanToEnd === true) {
2961 while (eos() !== true && (code = advance())) {
2962 if (code === CHAR_BACKWARD_SLASH) {
2963 backslashes = token.backslashes = true;
2964 code = advance();
2965 continue;
2966 }
2967
2968 if (code === CHAR_RIGHT_PARENTHESES) {
2969 isGlob = token.isGlob = true;
2970 finished = true;
2971 break;
2972 }
2973 }
2974 continue;
2975 }
2976 break;
2977 }
2978 }
2979
2980 if (code === CHAR_ASTERISK) {
2981 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
2982 isGlob = token.isGlob = true;
2983 finished = true;
2984
2985 if (scanToEnd === true) {
2986 continue;
2987 }
2988 break;
2989 }
2990
2991 if (code === CHAR_QUESTION_MARK) {
2992 isGlob = token.isGlob = true;
2993 finished = true;
2994
2995 if (scanToEnd === true) {
2996 continue;
2997 }
2998 break;
2999 }
3000
3001 if (code === CHAR_LEFT_SQUARE_BRACKET) {
3002 while (eos() !== true && (next = advance())) {
3003 if (next === CHAR_BACKWARD_SLASH) {
3004 backslashes = token.backslashes = true;
3005 advance();
3006 continue;
3007 }
3008
3009 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
3010 isBracket = token.isBracket = true;
3011 isGlob = token.isGlob = true;
3012 finished = true;
3013 break;
3014 }
3015 }
3016
3017 if (scanToEnd === true) {
3018 continue;
3019 }
3020
3021 break;
3022 }
3023
3024 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
3025 negated = token.negated = true;
3026 start++;
3027 continue;
3028 }
3029
3030 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
3031 isGlob = token.isGlob = true;
3032
3033 if (scanToEnd === true) {
3034 while (eos() !== true && (code = advance())) {
3035 if (code === CHAR_LEFT_PARENTHESES) {
3036 backslashes = token.backslashes = true;
3037 code = advance();
3038 continue;
3039 }
3040
3041 if (code === CHAR_RIGHT_PARENTHESES) {
3042 finished = true;
3043 break;
3044 }
3045 }
3046 continue;
3047 }
3048 break;
3049 }
3050
3051 if (isGlob === true) {
3052 finished = true;
3053
3054 if (scanToEnd === true) {
3055 continue;
3056 }
3057
3058 break;
3059 }
3060 }
3061
3062 if (opts.noext === true) {
3063 isExtglob = false;
3064 isGlob = false;
3065 }
3066
3067 let base = str;
3068 let prefix = '';
3069 let glob = '';
3070
3071 if (start > 0) {
3072 prefix = str.slice(0, start);
3073 str = str.slice(start);
3074 lastIndex -= start;
3075 }
3076
3077 if (base && isGlob === true && lastIndex > 0) {
3078 base = str.slice(0, lastIndex);
3079 glob = str.slice(lastIndex);
3080 } else if (isGlob === true) {
3081 base = '';
3082 glob = str;
3083 } else {
3084 base = str;
3085 }
3086
3087 if (base && base !== '' && base !== '/' && base !== str) {
3088 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
3089 base = base.slice(0, -1);
3090 }
3091 }
3092
3093 if (opts.unescape === true) {
3094 if (glob) glob = utils$2.removeBackslashes(glob);
3095
3096 if (base && backslashes === true) {
3097 base = utils$2.removeBackslashes(base);
3098 }
3099 }
3100
3101 const state = {
3102 prefix,
3103 input,
3104 start,
3105 base,
3106 glob,
3107 isBrace,
3108 isBracket,
3109 isGlob,
3110 isExtglob,
3111 isGlobstar,
3112 negated,
3113 negatedExtglob
3114 };
3115
3116 if (opts.tokens === true) {
3117 state.maxDepth = 0;
3118 if (!isPathSeparator(code)) {
3119 tokens.push(token);
3120 }
3121 state.tokens = tokens;
3122 }
3123
3124 if (opts.parts === true || opts.tokens === true) {
3125 let prevIndex;
3126
3127 for (let idx = 0; idx < slashes.length; idx++) {
3128 const n = prevIndex ? prevIndex + 1 : start;
3129 const i = slashes[idx];
3130 const value = input.slice(n, i);
3131 if (opts.tokens) {
3132 if (idx === 0 && start !== 0) {
3133 tokens[idx].isPrefix = true;
3134 tokens[idx].value = prefix;
3135 } else {
3136 tokens[idx].value = value;
3137 }
3138 depth(tokens[idx]);
3139 state.maxDepth += tokens[idx].depth;
3140 }
3141 if (idx !== 0 || value !== '') {
3142 parts.push(value);
3143 }
3144 prevIndex = i;
3145 }
3146
3147 if (prevIndex && prevIndex + 1 < input.length) {
3148 const value = input.slice(prevIndex + 1);
3149 parts.push(value);
3150
3151 if (opts.tokens) {
3152 tokens[tokens.length - 1].value = value;
3153 depth(tokens[tokens.length - 1]);
3154 state.maxDepth += tokens[tokens.length - 1].depth;
3155 }
3156 }
3157
3158 state.slashes = slashes;
3159 state.parts = parts;
3160 }
3161
3162 return state;
3163};
3164
3165var scan_1 = scan$1;
3166
3167const constants$1 = constants$2;
3168const utils$1 = utils$3;
3169
3170/**
3171 * Constants
3172 */
3173
3174const {
3175 MAX_LENGTH,
3176 POSIX_REGEX_SOURCE,
3177 REGEX_NON_SPECIAL_CHARS,
3178 REGEX_SPECIAL_CHARS_BACKREF,
3179 REPLACEMENTS
3180} = constants$1;
3181
3182/**
3183 * Helpers
3184 */
3185
3186const expandRange = (args, options) => {
3187 if (typeof options.expandRange === 'function') {
3188 return options.expandRange(...args, options);
3189 }
3190
3191 args.sort();
3192 const value = `[${args.join('-')}]`;
3193
3194 return value;
3195};
3196
3197/**
3198 * Create the message for a syntax error
3199 */
3200
3201const syntaxError = (type, char) => {
3202 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
3203};
3204
3205/**
3206 * Parse the given input string.
3207 * @param {String} input
3208 * @param {Object} options
3209 * @return {Object}
3210 */
3211
3212const parse$1 = (input, options) => {
3213 if (typeof input !== 'string') {
3214 throw new TypeError('Expected a string');
3215 }
3216
3217 input = REPLACEMENTS[input] || input;
3218
3219 const opts = { ...options };
3220 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
3221
3222 let len = input.length;
3223 if (len > max) {
3224 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
3225 }
3226
3227 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
3228 const tokens = [bos];
3229
3230 const capture = opts.capture ? '' : '?:';
3231 const win32 = utils$1.isWindows(options);
3232
3233 // create constants based on platform, for windows or posix
3234 const PLATFORM_CHARS = constants$1.globChars(win32);
3235 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
3236
3237 const {
3238 DOT_LITERAL,
3239 PLUS_LITERAL,
3240 SLASH_LITERAL,
3241 ONE_CHAR,
3242 DOTS_SLASH,
3243 NO_DOT,
3244 NO_DOT_SLASH,
3245 NO_DOTS_SLASH,
3246 QMARK,
3247 QMARK_NO_DOT,
3248 STAR,
3249 START_ANCHOR
3250 } = PLATFORM_CHARS;
3251
3252 const globstar = opts => {
3253 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
3254 };
3255
3256 const nodot = opts.dot ? '' : NO_DOT;
3257 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
3258 let star = opts.bash === true ? globstar(opts) : STAR;
3259
3260 if (opts.capture) {
3261 star = `(${star})`;
3262 }
3263
3264 // minimatch options support
3265 if (typeof opts.noext === 'boolean') {
3266 opts.noextglob = opts.noext;
3267 }
3268
3269 const state = {
3270 input,
3271 index: -1,
3272 start: 0,
3273 dot: opts.dot === true,
3274 consumed: '',
3275 output: '',
3276 prefix: '',
3277 backtrack: false,
3278 negated: false,
3279 brackets: 0,
3280 braces: 0,
3281 parens: 0,
3282 quotes: 0,
3283 globstar: false,
3284 tokens
3285 };
3286
3287 input = utils$1.removePrefix(input, state);
3288 len = input.length;
3289
3290 const extglobs = [];
3291 const braces = [];
3292 const stack = [];
3293 let prev = bos;
3294 let value;
3295
3296 /**
3297 * Tokenizing helpers
3298 */
3299
3300 const eos = () => state.index === len - 1;
3301 const peek = state.peek = (n = 1) => input[state.index + n];
3302 const advance = state.advance = () => input[++state.index] || '';
3303 const remaining = () => input.slice(state.index + 1);
3304 const consume = (value = '', num = 0) => {
3305 state.consumed += value;
3306 state.index += num;
3307 };
3308
3309 const append = token => {
3310 state.output += token.output != null ? token.output : token.value;
3311 consume(token.value);
3312 };
3313
3314 const negate = () => {
3315 let count = 1;
3316
3317 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
3318 advance();
3319 state.start++;
3320 count++;
3321 }
3322
3323 if (count % 2 === 0) {
3324 return false;
3325 }
3326
3327 state.negated = true;
3328 state.start++;
3329 return true;
3330 };
3331
3332 const increment = type => {
3333 state[type]++;
3334 stack.push(type);
3335 };
3336
3337 const decrement = type => {
3338 state[type]--;
3339 stack.pop();
3340 };
3341
3342 /**
3343 * Push tokens onto the tokens array. This helper speeds up
3344 * tokenizing by 1) helping us avoid backtracking as much as possible,
3345 * and 2) helping us avoid creating extra tokens when consecutive
3346 * characters are plain text. This improves performance and simplifies
3347 * lookbehinds.
3348 */
3349
3350 const push = tok => {
3351 if (prev.type === 'globstar') {
3352 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
3353 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
3354
3355 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
3356 state.output = state.output.slice(0, -prev.output.length);
3357 prev.type = 'star';
3358 prev.value = '*';
3359 prev.output = star;
3360 state.output += prev.output;
3361 }
3362 }
3363
3364 if (extglobs.length && tok.type !== 'paren') {
3365 extglobs[extglobs.length - 1].inner += tok.value;
3366 }
3367
3368 if (tok.value || tok.output) append(tok);
3369 if (prev && prev.type === 'text' && tok.type === 'text') {
3370 prev.value += tok.value;
3371 prev.output = (prev.output || '') + tok.value;
3372 return;
3373 }
3374
3375 tok.prev = prev;
3376 tokens.push(tok);
3377 prev = tok;
3378 };
3379
3380 const extglobOpen = (type, value) => {
3381 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
3382
3383 token.prev = prev;
3384 token.parens = state.parens;
3385 token.output = state.output;
3386 const output = (opts.capture ? '(' : '') + token.open;
3387
3388 increment('parens');
3389 push({ type, value, output: state.output ? '' : ONE_CHAR });
3390 push({ type: 'paren', extglob: true, value: advance(), output });
3391 extglobs.push(token);
3392 };
3393
3394 const extglobClose = token => {
3395 let output = token.close + (opts.capture ? ')' : '');
3396 let rest;
3397
3398 if (token.type === 'negate') {
3399 let extglobStar = star;
3400
3401 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
3402 extglobStar = globstar(opts);
3403 }
3404
3405 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
3406 output = token.close = `)$))${extglobStar}`;
3407 }
3408
3409 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
3410 // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
3411 // In this case, we need to parse the string and use it in the output of the original pattern.
3412 // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
3413 //
3414 // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
3415 const expression = parse$1(rest, { ...options, fastpaths: false }).output;
3416
3417 output = token.close = `)${expression})${extglobStar})`;
3418 }
3419
3420 if (token.prev.type === 'bos') {
3421 state.negatedExtglob = true;
3422 }
3423 }
3424
3425 push({ type: 'paren', extglob: true, value, output });
3426 decrement('parens');
3427 };
3428
3429 /**
3430 * Fast paths
3431 */
3432
3433 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
3434 let backslashes = false;
3435
3436 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
3437 if (first === '\\') {
3438 backslashes = true;
3439 return m;
3440 }
3441
3442 if (first === '?') {
3443 if (esc) {
3444 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
3445 }
3446 if (index === 0) {
3447 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
3448 }
3449 return QMARK.repeat(chars.length);
3450 }
3451
3452 if (first === '.') {
3453 return DOT_LITERAL.repeat(chars.length);
3454 }
3455
3456 if (first === '*') {
3457 if (esc) {
3458 return esc + first + (rest ? star : '');
3459 }
3460 return star;
3461 }
3462 return esc ? m : `\\${m}`;
3463 });
3464
3465 if (backslashes === true) {
3466 if (opts.unescape === true) {
3467 output = output.replace(/\\/g, '');
3468 } else {
3469 output = output.replace(/\\+/g, m => {
3470 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
3471 });
3472 }
3473 }
3474
3475 if (output === input && opts.contains === true) {
3476 state.output = input;
3477 return state;
3478 }
3479
3480 state.output = utils$1.wrapOutput(output, state, options);
3481 return state;
3482 }
3483
3484 /**
3485 * Tokenize input until we reach end-of-string
3486 */
3487
3488 while (!eos()) {
3489 value = advance();
3490
3491 if (value === '\u0000') {
3492 continue;
3493 }
3494
3495 /**
3496 * Escaped characters
3497 */
3498
3499 if (value === '\\') {
3500 const next = peek();
3501
3502 if (next === '/' && opts.bash !== true) {
3503 continue;
3504 }
3505
3506 if (next === '.' || next === ';') {
3507 continue;
3508 }
3509
3510 if (!next) {
3511 value += '\\';
3512 push({ type: 'text', value });
3513 continue;
3514 }
3515
3516 // collapse slashes to reduce potential for exploits
3517 const match = /^\\+/.exec(remaining());
3518 let slashes = 0;
3519
3520 if (match && match[0].length > 2) {
3521 slashes = match[0].length;
3522 state.index += slashes;
3523 if (slashes % 2 !== 0) {
3524 value += '\\';
3525 }
3526 }
3527
3528 if (opts.unescape === true) {
3529 value = advance();
3530 } else {
3531 value += advance();
3532 }
3533
3534 if (state.brackets === 0) {
3535 push({ type: 'text', value });
3536 continue;
3537 }
3538 }
3539
3540 /**
3541 * If we're inside a regex character class, continue
3542 * until we reach the closing bracket.
3543 */
3544
3545 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
3546 if (opts.posix !== false && value === ':') {
3547 const inner = prev.value.slice(1);
3548 if (inner.includes('[')) {
3549 prev.posix = true;
3550
3551 if (inner.includes(':')) {
3552 const idx = prev.value.lastIndexOf('[');
3553 const pre = prev.value.slice(0, idx);
3554 const rest = prev.value.slice(idx + 2);
3555 const posix = POSIX_REGEX_SOURCE[rest];
3556 if (posix) {
3557 prev.value = pre + posix;
3558 state.backtrack = true;
3559 advance();
3560
3561 if (!bos.output && tokens.indexOf(prev) === 1) {
3562 bos.output = ONE_CHAR;
3563 }
3564 continue;
3565 }
3566 }
3567 }
3568 }
3569
3570 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
3571 value = `\\${value}`;
3572 }
3573
3574 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
3575 value = `\\${value}`;
3576 }
3577
3578 if (opts.posix === true && value === '!' && prev.value === '[') {
3579 value = '^';
3580 }
3581
3582 prev.value += value;
3583 append({ value });
3584 continue;
3585 }
3586
3587 /**
3588 * If we're inside a quoted string, continue
3589 * until we reach the closing double quote.
3590 */
3591
3592 if (state.quotes === 1 && value !== '"') {
3593 value = utils$1.escapeRegex(value);
3594 prev.value += value;
3595 append({ value });
3596 continue;
3597 }
3598
3599 /**
3600 * Double quotes
3601 */
3602
3603 if (value === '"') {
3604 state.quotes = state.quotes === 1 ? 0 : 1;
3605 if (opts.keepQuotes === true) {
3606 push({ type: 'text', value });
3607 }
3608 continue;
3609 }
3610
3611 /**
3612 * Parentheses
3613 */
3614
3615 if (value === '(') {
3616 increment('parens');
3617 push({ type: 'paren', value });
3618 continue;
3619 }
3620
3621 if (value === ')') {
3622 if (state.parens === 0 && opts.strictBrackets === true) {
3623 throw new SyntaxError(syntaxError('opening', '('));
3624 }
3625
3626 const extglob = extglobs[extglobs.length - 1];
3627 if (extglob && state.parens === extglob.parens + 1) {
3628 extglobClose(extglobs.pop());
3629 continue;
3630 }
3631
3632 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
3633 decrement('parens');
3634 continue;
3635 }
3636
3637 /**
3638 * Square brackets
3639 */
3640
3641 if (value === '[') {
3642 if (opts.nobracket === true || !remaining().includes(']')) {
3643 if (opts.nobracket !== true && opts.strictBrackets === true) {
3644 throw new SyntaxError(syntaxError('closing', ']'));
3645 }
3646
3647 value = `\\${value}`;
3648 } else {
3649 increment('brackets');
3650 }
3651
3652 push({ type: 'bracket', value });
3653 continue;
3654 }
3655
3656 if (value === ']') {
3657 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
3658 push({ type: 'text', value, output: `\\${value}` });
3659 continue;
3660 }
3661
3662 if (state.brackets === 0) {
3663 if (opts.strictBrackets === true) {
3664 throw new SyntaxError(syntaxError('opening', '['));
3665 }
3666
3667 push({ type: 'text', value, output: `\\${value}` });
3668 continue;
3669 }
3670
3671 decrement('brackets');
3672
3673 const prevValue = prev.value.slice(1);
3674 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
3675 value = `/${value}`;
3676 }
3677
3678 prev.value += value;
3679 append({ value });
3680
3681 // when literal brackets are explicitly disabled
3682 // assume we should match with a regex character class
3683 if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
3684 continue;
3685 }
3686
3687 const escaped = utils$1.escapeRegex(prev.value);
3688 state.output = state.output.slice(0, -prev.value.length);
3689
3690 // when literal brackets are explicitly enabled
3691 // assume we should escape the brackets to match literal characters
3692 if (opts.literalBrackets === true) {
3693 state.output += escaped;
3694 prev.value = escaped;
3695 continue;
3696 }
3697
3698 // when the user specifies nothing, try to match both
3699 prev.value = `(${capture}${escaped}|${prev.value})`;
3700 state.output += prev.value;
3701 continue;
3702 }
3703
3704 /**
3705 * Braces
3706 */
3707
3708 if (value === '{' && opts.nobrace !== true) {
3709 increment('braces');
3710
3711 const open = {
3712 type: 'brace',
3713 value,
3714 output: '(',
3715 outputIndex: state.output.length,
3716 tokensIndex: state.tokens.length
3717 };
3718
3719 braces.push(open);
3720 push(open);
3721 continue;
3722 }
3723
3724 if (value === '}') {
3725 const brace = braces[braces.length - 1];
3726
3727 if (opts.nobrace === true || !brace) {
3728 push({ type: 'text', value, output: value });
3729 continue;
3730 }
3731
3732 let output = ')';
3733
3734 if (brace.dots === true) {
3735 const arr = tokens.slice();
3736 const range = [];
3737
3738 for (let i = arr.length - 1; i >= 0; i--) {
3739 tokens.pop();
3740 if (arr[i].type === 'brace') {
3741 break;
3742 }
3743 if (arr[i].type !== 'dots') {
3744 range.unshift(arr[i].value);
3745 }
3746 }
3747
3748 output = expandRange(range, opts);
3749 state.backtrack = true;
3750 }
3751
3752 if (brace.comma !== true && brace.dots !== true) {
3753 const out = state.output.slice(0, brace.outputIndex);
3754 const toks = state.tokens.slice(brace.tokensIndex);
3755 brace.value = brace.output = '\\{';
3756 value = output = '\\}';
3757 state.output = out;
3758 for (const t of toks) {
3759 state.output += (t.output || t.value);
3760 }
3761 }
3762
3763 push({ type: 'brace', value, output });
3764 decrement('braces');
3765 braces.pop();
3766 continue;
3767 }
3768
3769 /**
3770 * Pipes
3771 */
3772
3773 if (value === '|') {
3774 if (extglobs.length > 0) {
3775 extglobs[extglobs.length - 1].conditions++;
3776 }
3777 push({ type: 'text', value });
3778 continue;
3779 }
3780
3781 /**
3782 * Commas
3783 */
3784
3785 if (value === ',') {
3786 let output = value;
3787
3788 const brace = braces[braces.length - 1];
3789 if (brace && stack[stack.length - 1] === 'braces') {
3790 brace.comma = true;
3791 output = '|';
3792 }
3793
3794 push({ type: 'comma', value, output });
3795 continue;
3796 }
3797
3798 /**
3799 * Slashes
3800 */
3801
3802 if (value === '/') {
3803 // if the beginning of the glob is "./", advance the start
3804 // to the current index, and don't add the "./" characters
3805 // to the state. This greatly simplifies lookbehinds when
3806 // checking for BOS characters like "!" and "." (not "./")
3807 if (prev.type === 'dot' && state.index === state.start + 1) {
3808 state.start = state.index + 1;
3809 state.consumed = '';
3810 state.output = '';
3811 tokens.pop();
3812 prev = bos; // reset "prev" to the first token
3813 continue;
3814 }
3815
3816 push({ type: 'slash', value, output: SLASH_LITERAL });
3817 continue;
3818 }
3819
3820 /**
3821 * Dots
3822 */
3823
3824 if (value === '.') {
3825 if (state.braces > 0 && prev.type === 'dot') {
3826 if (prev.value === '.') prev.output = DOT_LITERAL;
3827 const brace = braces[braces.length - 1];
3828 prev.type = 'dots';
3829 prev.output += value;
3830 prev.value += value;
3831 brace.dots = true;
3832 continue;
3833 }
3834
3835 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
3836 push({ type: 'text', value, output: DOT_LITERAL });
3837 continue;
3838 }
3839
3840 push({ type: 'dot', value, output: DOT_LITERAL });
3841 continue;
3842 }
3843
3844 /**
3845 * Question marks
3846 */
3847
3848 if (value === '?') {
3849 const isGroup = prev && prev.value === '(';
3850 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3851 extglobOpen('qmark', value);
3852 continue;
3853 }
3854
3855 if (prev && prev.type === 'paren') {
3856 const next = peek();
3857 let output = value;
3858
3859 if (next === '<' && !utils$1.supportsLookbehinds()) {
3860 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
3861 }
3862
3863 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
3864 output = `\\${value}`;
3865 }
3866
3867 push({ type: 'text', value, output });
3868 continue;
3869 }
3870
3871 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
3872 push({ type: 'qmark', value, output: QMARK_NO_DOT });
3873 continue;
3874 }
3875
3876 push({ type: 'qmark', value, output: QMARK });
3877 continue;
3878 }
3879
3880 /**
3881 * Exclamation
3882 */
3883
3884 if (value === '!') {
3885 if (opts.noextglob !== true && peek() === '(') {
3886 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
3887 extglobOpen('negate', value);
3888 continue;
3889 }
3890 }
3891
3892 if (opts.nonegate !== true && state.index === 0) {
3893 negate();
3894 continue;
3895 }
3896 }
3897
3898 /**
3899 * Plus
3900 */
3901
3902 if (value === '+') {
3903 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3904 extglobOpen('plus', value);
3905 continue;
3906 }
3907
3908 if ((prev && prev.value === '(') || opts.regex === false) {
3909 push({ type: 'plus', value, output: PLUS_LITERAL });
3910 continue;
3911 }
3912
3913 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
3914 push({ type: 'plus', value });
3915 continue;
3916 }
3917
3918 push({ type: 'plus', value: PLUS_LITERAL });
3919 continue;
3920 }
3921
3922 /**
3923 * Plain text
3924 */
3925
3926 if (value === '@') {
3927 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3928 push({ type: 'at', extglob: true, value, output: '' });
3929 continue;
3930 }
3931
3932 push({ type: 'text', value });
3933 continue;
3934 }
3935
3936 /**
3937 * Plain text
3938 */
3939
3940 if (value !== '*') {
3941 if (value === '$' || value === '^') {
3942 value = `\\${value}`;
3943 }
3944
3945 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
3946 if (match) {
3947 value += match[0];
3948 state.index += match[0].length;
3949 }
3950
3951 push({ type: 'text', value });
3952 continue;
3953 }
3954
3955 /**
3956 * Stars
3957 */
3958
3959 if (prev && (prev.type === 'globstar' || prev.star === true)) {
3960 prev.type = 'star';
3961 prev.star = true;
3962 prev.value += value;
3963 prev.output = star;
3964 state.backtrack = true;
3965 state.globstar = true;
3966 consume(value);
3967 continue;
3968 }
3969
3970 let rest = remaining();
3971 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
3972 extglobOpen('star', value);
3973 continue;
3974 }
3975
3976 if (prev.type === 'star') {
3977 if (opts.noglobstar === true) {
3978 consume(value);
3979 continue;
3980 }
3981
3982 const prior = prev.prev;
3983 const before = prior.prev;
3984 const isStart = prior.type === 'slash' || prior.type === 'bos';
3985 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
3986
3987 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
3988 push({ type: 'star', value, output: '' });
3989 continue;
3990 }
3991
3992 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
3993 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
3994 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
3995 push({ type: 'star', value, output: '' });
3996 continue;
3997 }
3998
3999 // strip consecutive `/**/`
4000 while (rest.slice(0, 3) === '/**') {
4001 const after = input[state.index + 4];
4002 if (after && after !== '/') {
4003 break;
4004 }
4005 rest = rest.slice(3);
4006 consume('/**', 3);
4007 }
4008
4009 if (prior.type === 'bos' && eos()) {
4010 prev.type = 'globstar';
4011 prev.value += value;
4012 prev.output = globstar(opts);
4013 state.output = prev.output;
4014 state.globstar = true;
4015 consume(value);
4016 continue;
4017 }
4018
4019 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
4020 state.output = state.output.slice(0, -(prior.output + prev.output).length);
4021 prior.output = `(?:${prior.output}`;
4022
4023 prev.type = 'globstar';
4024 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
4025 prev.value += value;
4026 state.globstar = true;
4027 state.output += prior.output + prev.output;
4028 consume(value);
4029 continue;
4030 }
4031
4032 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
4033 const end = rest[1] !== void 0 ? '|$' : '';
4034
4035 state.output = state.output.slice(0, -(prior.output + prev.output).length);
4036 prior.output = `(?:${prior.output}`;
4037
4038 prev.type = 'globstar';
4039 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
4040 prev.value += value;
4041
4042 state.output += prior.output + prev.output;
4043 state.globstar = true;
4044
4045 consume(value + advance());
4046
4047 push({ type: 'slash', value: '/', output: '' });
4048 continue;
4049 }
4050
4051 if (prior.type === 'bos' && rest[0] === '/') {
4052 prev.type = 'globstar';
4053 prev.value += value;
4054 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
4055 state.output = prev.output;
4056 state.globstar = true;
4057 consume(value + advance());
4058 push({ type: 'slash', value: '/', output: '' });
4059 continue;
4060 }
4061
4062 // remove single star from output
4063 state.output = state.output.slice(0, -prev.output.length);
4064
4065 // reset previous token to globstar
4066 prev.type = 'globstar';
4067 prev.output = globstar(opts);
4068 prev.value += value;
4069
4070 // reset output with globstar
4071 state.output += prev.output;
4072 state.globstar = true;
4073 consume(value);
4074 continue;
4075 }
4076
4077 const token = { type: 'star', value, output: star };
4078
4079 if (opts.bash === true) {
4080 token.output = '.*?';
4081 if (prev.type === 'bos' || prev.type === 'slash') {
4082 token.output = nodot + token.output;
4083 }
4084 push(token);
4085 continue;
4086 }
4087
4088 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
4089 token.output = value;
4090 push(token);
4091 continue;
4092 }
4093
4094 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
4095 if (prev.type === 'dot') {
4096 state.output += NO_DOT_SLASH;
4097 prev.output += NO_DOT_SLASH;
4098
4099 } else if (opts.dot === true) {
4100 state.output += NO_DOTS_SLASH;
4101 prev.output += NO_DOTS_SLASH;
4102
4103 } else {
4104 state.output += nodot;
4105 prev.output += nodot;
4106 }
4107
4108 if (peek() !== '*') {
4109 state.output += ONE_CHAR;
4110 prev.output += ONE_CHAR;
4111 }
4112 }
4113
4114 push(token);
4115 }
4116
4117 while (state.brackets > 0) {
4118 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
4119 state.output = utils$1.escapeLast(state.output, '[');
4120 decrement('brackets');
4121 }
4122
4123 while (state.parens > 0) {
4124 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
4125 state.output = utils$1.escapeLast(state.output, '(');
4126 decrement('parens');
4127 }
4128
4129 while (state.braces > 0) {
4130 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
4131 state.output = utils$1.escapeLast(state.output, '{');
4132 decrement('braces');
4133 }
4134
4135 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
4136 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
4137 }
4138
4139 // rebuild the output if we had to backtrack at any point
4140 if (state.backtrack === true) {
4141 state.output = '';
4142
4143 for (const token of state.tokens) {
4144 state.output += token.output != null ? token.output : token.value;
4145
4146 if (token.suffix) {
4147 state.output += token.suffix;
4148 }
4149 }
4150 }
4151
4152 return state;
4153};
4154
4155/**
4156 * Fast paths for creating regular expressions for common glob patterns.
4157 * This can significantly speed up processing and has very little downside
4158 * impact when none of the fast paths match.
4159 */
4160
4161parse$1.fastpaths = (input, options) => {
4162 const opts = { ...options };
4163 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
4164 const len = input.length;
4165 if (len > max) {
4166 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
4167 }
4168
4169 input = REPLACEMENTS[input] || input;
4170 const win32 = utils$1.isWindows(options);
4171
4172 // create constants based on platform, for windows or posix
4173 const {
4174 DOT_LITERAL,
4175 SLASH_LITERAL,
4176 ONE_CHAR,
4177 DOTS_SLASH,
4178 NO_DOT,
4179 NO_DOTS,
4180 NO_DOTS_SLASH,
4181 STAR,
4182 START_ANCHOR
4183 } = constants$1.globChars(win32);
4184
4185 const nodot = opts.dot ? NO_DOTS : NO_DOT;
4186 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
4187 const capture = opts.capture ? '' : '?:';
4188 const state = { negated: false, prefix: '' };
4189 let star = opts.bash === true ? '.*?' : STAR;
4190
4191 if (opts.capture) {
4192 star = `(${star})`;
4193 }
4194
4195 const globstar = opts => {
4196 if (opts.noglobstar === true) return star;
4197 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
4198 };
4199
4200 const create = str => {
4201 switch (str) {
4202 case '*':
4203 return `${nodot}${ONE_CHAR}${star}`;
4204
4205 case '.*':
4206 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
4207
4208 case '*.*':
4209 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4210
4211 case '*/*':
4212 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
4213
4214 case '**':
4215 return nodot + globstar(opts);
4216
4217 case '**/*':
4218 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
4219
4220 case '**/*.*':
4221 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4222
4223 case '**/.*':
4224 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
4225
4226 default: {
4227 const match = /^(.*?)\.(\w+)$/.exec(str);
4228 if (!match) return;
4229
4230 const source = create(match[1]);
4231 if (!source) return;
4232
4233 return source + DOT_LITERAL + match[2];
4234 }
4235 }
4236 };
4237
4238 const output = utils$1.removePrefix(input, state);
4239 let source = create(output);
4240
4241 if (source && opts.strictSlashes !== true) {
4242 source += `${SLASH_LITERAL}?`;
4243 }
4244
4245 return source;
4246};
4247
4248var parse_1 = parse$1;
4249
4250const path = require$$0;
4251const scan = scan_1;
4252const parse = parse_1;
4253const utils = utils$3;
4254const constants = constants$2;
4255const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
4256
4257/**
4258 * Creates a matcher function from one or more glob patterns. The
4259 * returned function takes a string to match as its first argument,
4260 * and returns true if the string is a match. The returned matcher
4261 * function also takes a boolean as the second argument that, when true,
4262 * returns an object with additional information.
4263 *
4264 * ```js
4265 * const picomatch = require('picomatch');
4266 * // picomatch(glob[, options]);
4267 *
4268 * const isMatch = picomatch('*.!(*a)');
4269 * console.log(isMatch('a.a')); //=> false
4270 * console.log(isMatch('a.b')); //=> true
4271 * ```
4272 * @name picomatch
4273 * @param {String|Array} `globs` One or more glob patterns.
4274 * @param {Object=} `options`
4275 * @return {Function=} Returns a matcher function.
4276 * @api public
4277 */
4278
4279const picomatch = (glob, options, returnState = false) => {
4280 if (Array.isArray(glob)) {
4281 const fns = glob.map(input => picomatch(input, options, returnState));
4282 const arrayMatcher = str => {
4283 for (const isMatch of fns) {
4284 const state = isMatch(str);
4285 if (state) return state;
4286 }
4287 return false;
4288 };
4289 return arrayMatcher;
4290 }
4291
4292 const isState = isObject(glob) && glob.tokens && glob.input;
4293
4294 if (glob === '' || (typeof glob !== 'string' && !isState)) {
4295 throw new TypeError('Expected pattern to be a non-empty string');
4296 }
4297
4298 const opts = options || {};
4299 const posix = utils.isWindows(options);
4300 const regex = isState
4301 ? picomatch.compileRe(glob, options)
4302 : picomatch.makeRe(glob, options, false, true);
4303
4304 const state = regex.state;
4305 delete regex.state;
4306
4307 let isIgnored = () => false;
4308 if (opts.ignore) {
4309 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
4310 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
4311 }
4312
4313 const matcher = (input, returnObject = false) => {
4314 const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
4315 const result = { glob, state, regex, posix, input, output, match, isMatch };
4316
4317 if (typeof opts.onResult === 'function') {
4318 opts.onResult(result);
4319 }
4320
4321 if (isMatch === false) {
4322 result.isMatch = false;
4323 return returnObject ? result : false;
4324 }
4325
4326 if (isIgnored(input)) {
4327 if (typeof opts.onIgnore === 'function') {
4328 opts.onIgnore(result);
4329 }
4330 result.isMatch = false;
4331 return returnObject ? result : false;
4332 }
4333
4334 if (typeof opts.onMatch === 'function') {
4335 opts.onMatch(result);
4336 }
4337 return returnObject ? result : true;
4338 };
4339
4340 if (returnState) {
4341 matcher.state = state;
4342 }
4343
4344 return matcher;
4345};
4346
4347/**
4348 * Test `input` with the given `regex`. This is used by the main
4349 * `picomatch()` function to test the input string.
4350 *
4351 * ```js
4352 * const picomatch = require('picomatch');
4353 * // picomatch.test(input, regex[, options]);
4354 *
4355 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
4356 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
4357 * ```
4358 * @param {String} `input` String to test.
4359 * @param {RegExp} `regex`
4360 * @return {Object} Returns an object with matching info.
4361 * @api public
4362 */
4363
4364picomatch.test = (input, regex, options, { glob, posix } = {}) => {
4365 if (typeof input !== 'string') {
4366 throw new TypeError('Expected input to be a string');
4367 }
4368
4369 if (input === '') {
4370 return { isMatch: false, output: '' };
4371 }
4372
4373 const opts = options || {};
4374 const format = opts.format || (posix ? utils.toPosixSlashes : null);
4375 let match = input === glob;
4376 let output = (match && format) ? format(input) : input;
4377
4378 if (match === false) {
4379 output = format ? format(input) : input;
4380 match = output === glob;
4381 }
4382
4383 if (match === false || opts.capture === true) {
4384 if (opts.matchBase === true || opts.basename === true) {
4385 match = picomatch.matchBase(input, regex, options, posix);
4386 } else {
4387 match = regex.exec(output);
4388 }
4389 }
4390
4391 return { isMatch: Boolean(match), match, output };
4392};
4393
4394/**
4395 * Match the basename of a filepath.
4396 *
4397 * ```js
4398 * const picomatch = require('picomatch');
4399 * // picomatch.matchBase(input, glob[, options]);
4400 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
4401 * ```
4402 * @param {String} `input` String to test.
4403 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
4404 * @return {Boolean}
4405 * @api public
4406 */
4407
4408picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
4409 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
4410 return regex.test(path.basename(input));
4411};
4412
4413/**
4414 * Returns true if **any** of the given glob `patterns` match the specified `string`.
4415 *
4416 * ```js
4417 * const picomatch = require('picomatch');
4418 * // picomatch.isMatch(string, patterns[, options]);
4419 *
4420 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
4421 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
4422 * ```
4423 * @param {String|Array} str The string to test.
4424 * @param {String|Array} patterns One or more glob patterns to use for matching.
4425 * @param {Object} [options] See available [options](#options).
4426 * @return {Boolean} Returns true if any patterns match `str`
4427 * @api public
4428 */
4429
4430picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
4431
4432/**
4433 * Parse a glob pattern to create the source string for a regular
4434 * expression.
4435 *
4436 * ```js
4437 * const picomatch = require('picomatch');
4438 * const result = picomatch.parse(pattern[, options]);
4439 * ```
4440 * @param {String} `pattern`
4441 * @param {Object} `options`
4442 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
4443 * @api public
4444 */
4445
4446picomatch.parse = (pattern, options) => {
4447 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
4448 return parse(pattern, { ...options, fastpaths: false });
4449};
4450
4451/**
4452 * Scan a glob pattern to separate the pattern into segments.
4453 *
4454 * ```js
4455 * const picomatch = require('picomatch');
4456 * // picomatch.scan(input[, options]);
4457 *
4458 * const result = picomatch.scan('!./foo/*.js');
4459 * console.log(result);
4460 * { prefix: '!./',
4461 * input: '!./foo/*.js',
4462 * start: 3,
4463 * base: 'foo',
4464 * glob: '*.js',
4465 * isBrace: false,
4466 * isBracket: false,
4467 * isGlob: true,
4468 * isExtglob: false,
4469 * isGlobstar: false,
4470 * negated: true }
4471 * ```
4472 * @param {String} `input` Glob pattern to scan.
4473 * @param {Object} `options`
4474 * @return {Object} Returns an object with
4475 * @api public
4476 */
4477
4478picomatch.scan = (input, options) => scan(input, options);
4479
4480/**
4481 * Compile a regular expression from the `state` object returned by the
4482 * [parse()](#parse) method.
4483 *
4484 * @param {Object} `state`
4485 * @param {Object} `options`
4486 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
4487 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
4488 * @return {RegExp}
4489 * @api public
4490 */
4491
4492picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
4493 if (returnOutput === true) {
4494 return state.output;
4495 }
4496
4497 const opts = options || {};
4498 const prepend = opts.contains ? '' : '^';
4499 const append = opts.contains ? '' : '$';
4500
4501 let source = `${prepend}(?:${state.output})${append}`;
4502 if (state && state.negated === true) {
4503 source = `^(?!${source}).*$`;
4504 }
4505
4506 const regex = picomatch.toRegex(source, options);
4507 if (returnState === true) {
4508 regex.state = state;
4509 }
4510
4511 return regex;
4512};
4513
4514/**
4515 * Create a regular expression from a parsed glob pattern.
4516 *
4517 * ```js
4518 * const picomatch = require('picomatch');
4519 * const state = picomatch.parse('*.js');
4520 * // picomatch.compileRe(state[, options]);
4521 *
4522 * console.log(picomatch.compileRe(state));
4523 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4524 * ```
4525 * @param {String} `state` The object returned from the `.parse` method.
4526 * @param {Object} `options`
4527 * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
4528 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
4529 * @return {RegExp} Returns a regex created from the given pattern.
4530 * @api public
4531 */
4532
4533picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
4534 if (!input || typeof input !== 'string') {
4535 throw new TypeError('Expected a non-empty string');
4536 }
4537
4538 let parsed = { negated: false, fastpaths: true };
4539
4540 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
4541 parsed.output = parse.fastpaths(input, options);
4542 }
4543
4544 if (!parsed.output) {
4545 parsed = parse(input, options);
4546 }
4547
4548 return picomatch.compileRe(parsed, options, returnOutput, returnState);
4549};
4550
4551/**
4552 * Create a regular expression from the given regex source string.
4553 *
4554 * ```js
4555 * const picomatch = require('picomatch');
4556 * // picomatch.toRegex(source[, options]);
4557 *
4558 * const { output } = picomatch.parse('*.js');
4559 * console.log(picomatch.toRegex(output));
4560 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4561 * ```
4562 * @param {String} `source` Regular expression source string.
4563 * @param {Object} `options`
4564 * @return {RegExp}
4565 * @api public
4566 */
4567
4568picomatch.toRegex = (source, options) => {
4569 try {
4570 const opts = options || {};
4571 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
4572 } catch (err) {
4573 if (options && options.debug === true) throw err;
4574 return /$^/;
4575 }
4576};
4577
4578/**
4579 * Picomatch constants.
4580 * @return {Object}
4581 */
4582
4583picomatch.constants = constants;
4584
4585/**
4586 * Expose "picomatch"
4587 */
4588
4589var picomatch_1 = picomatch;
4590
4591(function (module) {
4592
4593 module.exports = picomatch_1;
4594} (picomatch$1));
4595
4596const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
4597
4598const extractors = {
4599 ArrayPattern(names, param) {
4600 for (const element of param.elements) {
4601 if (element)
4602 extractors[element.type](names, element);
4603 }
4604 },
4605 AssignmentPattern(names, param) {
4606 extractors[param.left.type](names, param.left);
4607 },
4608 Identifier(names, param) {
4609 names.push(param.name);
4610 },
4611 MemberExpression() { },
4612 ObjectPattern(names, param) {
4613 for (const prop of param.properties) {
4614 // @ts-ignore Typescript reports that this is not a valid type
4615 if (prop.type === 'RestElement') {
4616 extractors.RestElement(names, prop);
4617 }
4618 else {
4619 extractors[prop.value.type](names, prop.value);
4620 }
4621 }
4622 },
4623 RestElement(names, param) {
4624 extractors[param.argument.type](names, param.argument);
4625 }
4626};
4627const extractAssignedNames = function extractAssignedNames(param) {
4628 const names = [];
4629 extractors[param.type](names, param);
4630 return names;
4631};
4632
4633// Helper since Typescript can't detect readonly arrays with Array.isArray
4634function isArray$1(arg) {
4635 return Array.isArray(arg);
4636}
4637function ensureArray(thing) {
4638 if (isArray$1(thing))
4639 return thing;
4640 if (thing == null)
4641 return [];
4642 return [thing];
4643}
4644
4645const normalizePath = function normalizePath(filename) {
4646 return filename.split(require$$0.win32.sep).join(require$$0.posix.sep);
4647};
4648
4649function getMatcherString(id, resolutionBase) {
4650 if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('*')) {
4651 return normalizePath(id);
4652 }
4653 // resolve('') is valid and will default to process.cwd()
4654 const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
4655 // escape all possible (posix + win) path characters that might interfere with regex
4656 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
4657 // Note that we use posix.join because:
4658 // 1. the basePath has been normalized to use /
4659 // 2. the incoming glob (id) matcher, also uses /
4660 // otherwise Node will force backslash (\) on windows
4661 return require$$0.posix.join(basePath, normalizePath(id));
4662}
4663const createFilter = function createFilter(include, exclude, options) {
4664 const resolutionBase = options && options.resolve;
4665 const getMatcher = (id) => id instanceof RegExp
4666 ? id
4667 : {
4668 test: (what) => {
4669 // this refactor is a tad overly verbose but makes for easy debugging
4670 const pattern = getMatcherString(id, resolutionBase);
4671 const fn = pm(pattern, { dot: true });
4672 const result = fn(what);
4673 return result;
4674 }
4675 };
4676 const includeMatchers = ensureArray(include).map(getMatcher);
4677 const excludeMatchers = ensureArray(exclude).map(getMatcher);
4678 return function result(id) {
4679 if (typeof id !== 'string')
4680 return false;
4681 if (/\0/.test(id))
4682 return false;
4683 const pathId = normalizePath(id);
4684 for (let i = 0; i < excludeMatchers.length; ++i) {
4685 const matcher = excludeMatchers[i];
4686 if (matcher.test(pathId))
4687 return false;
4688 }
4689 for (let i = 0; i < includeMatchers.length; ++i) {
4690 const matcher = includeMatchers[i];
4691 if (matcher.test(pathId))
4692 return true;
4693 }
4694 return !includeMatchers.length;
4695 };
4696};
4697
4698const 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';
4699const builtins$1 = 'arguments 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';
4700const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
4701forbiddenIdentifiers.add('');
4702
4703const BROKEN_FLOW_NONE = 0;
4704const BROKEN_FLOW_BREAK_CONTINUE = 1;
4705const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
4706function createInclusionContext() {
4707 return {
4708 brokenFlow: BROKEN_FLOW_NONE,
4709 includedCallArguments: new Set(),
4710 includedLabels: new Set()
4711 };
4712}
4713function createHasEffectsContext() {
4714 return {
4715 accessed: new PathTracker(),
4716 assigned: new PathTracker(),
4717 brokenFlow: BROKEN_FLOW_NONE,
4718 called: new DiscriminatedPathTracker(),
4719 ignore: {
4720 breaks: false,
4721 continues: false,
4722 labels: new Set(),
4723 returnYield: false
4724 },
4725 includedLabels: new Set(),
4726 instantiated: new DiscriminatedPathTracker(),
4727 replacedVariableInits: new Map()
4728 };
4729}
4730
4731function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
4732 return Object.create(inheritedDescriptions, memberDescriptions);
4733}
4734const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
4735 getLiteralValueAtPath() {
4736 return undefined;
4737 }
4738})();
4739const returnsUnknown = {
4740 value: {
4741 hasEffectsWhenCalled: null,
4742 returns: UNKNOWN_EXPRESSION
4743 }
4744};
4745const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
4746 getReturnExpressionWhenCalledAtPath(path) {
4747 if (path.length === 1) {
4748 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
4749 }
4750 return UNKNOWN_EXPRESSION;
4751 }
4752 hasEffectsOnInteractionAtPath(path, interaction, context) {
4753 if (interaction.type === INTERACTION_ACCESSED) {
4754 return path.length > 1;
4755 }
4756 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4757 return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
4758 }
4759 return true;
4760 }
4761})();
4762const returnsBoolean = {
4763 value: {
4764 hasEffectsWhenCalled: null,
4765 returns: UNKNOWN_LITERAL_BOOLEAN
4766 }
4767};
4768const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
4769 getReturnExpressionWhenCalledAtPath(path) {
4770 if (path.length === 1) {
4771 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
4772 }
4773 return UNKNOWN_EXPRESSION;
4774 }
4775 hasEffectsOnInteractionAtPath(path, interaction, context) {
4776 if (interaction.type === INTERACTION_ACCESSED) {
4777 return path.length > 1;
4778 }
4779 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4780 return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
4781 }
4782 return true;
4783 }
4784})();
4785const returnsNumber = {
4786 value: {
4787 hasEffectsWhenCalled: null,
4788 returns: UNKNOWN_LITERAL_NUMBER
4789 }
4790};
4791const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
4792 getReturnExpressionWhenCalledAtPath(path) {
4793 if (path.length === 1) {
4794 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
4795 }
4796 return UNKNOWN_EXPRESSION;
4797 }
4798 hasEffectsOnInteractionAtPath(path, interaction, context) {
4799 if (interaction.type === INTERACTION_ACCESSED) {
4800 return path.length > 1;
4801 }
4802 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4803 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
4804 }
4805 return true;
4806 }
4807})();
4808const returnsString = {
4809 value: {
4810 hasEffectsWhenCalled: null,
4811 returns: UNKNOWN_LITERAL_STRING
4812 }
4813};
4814const stringReplace = {
4815 value: {
4816 hasEffectsWhenCalled({ args }, context) {
4817 const arg1 = args[1];
4818 return (args.length < 2 ||
4819 (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4820 deoptimizeCache() { }
4821 }) === 'symbol' &&
4822 arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
4823 },
4824 returns: UNKNOWN_LITERAL_STRING
4825 }
4826};
4827const objectMembers = assembleMemberDescriptions({
4828 hasOwnProperty: returnsBoolean,
4829 isPrototypeOf: returnsBoolean,
4830 propertyIsEnumerable: returnsBoolean,
4831 toLocaleString: returnsString,
4832 toString: returnsString,
4833 valueOf: returnsUnknown
4834});
4835const literalBooleanMembers = assembleMemberDescriptions({
4836 valueOf: returnsBoolean
4837}, objectMembers);
4838const literalNumberMembers = assembleMemberDescriptions({
4839 toExponential: returnsString,
4840 toFixed: returnsString,
4841 toLocaleString: returnsString,
4842 toPrecision: returnsString,
4843 valueOf: returnsNumber
4844}, objectMembers);
4845const literalStringMembers = assembleMemberDescriptions({
4846 anchor: returnsString,
4847 at: returnsUnknown,
4848 big: returnsString,
4849 blink: returnsString,
4850 bold: returnsString,
4851 charAt: returnsString,
4852 charCodeAt: returnsNumber,
4853 codePointAt: returnsUnknown,
4854 concat: returnsString,
4855 endsWith: returnsBoolean,
4856 fixed: returnsString,
4857 fontcolor: returnsString,
4858 fontsize: returnsString,
4859 includes: returnsBoolean,
4860 indexOf: returnsNumber,
4861 italics: returnsString,
4862 lastIndexOf: returnsNumber,
4863 link: returnsString,
4864 localeCompare: returnsNumber,
4865 match: returnsUnknown,
4866 matchAll: returnsUnknown,
4867 normalize: returnsString,
4868 padEnd: returnsString,
4869 padStart: returnsString,
4870 repeat: returnsString,
4871 replace: stringReplace,
4872 replaceAll: stringReplace,
4873 search: returnsNumber,
4874 slice: returnsString,
4875 small: returnsString,
4876 split: returnsUnknown,
4877 startsWith: returnsBoolean,
4878 strike: returnsString,
4879 sub: returnsString,
4880 substr: returnsString,
4881 substring: returnsString,
4882 sup: returnsString,
4883 toLocaleLowerCase: returnsString,
4884 toLocaleUpperCase: returnsString,
4885 toLowerCase: returnsString,
4886 toString: returnsString,
4887 toUpperCase: returnsString,
4888 trim: returnsString,
4889 trimEnd: returnsString,
4890 trimLeft: returnsString,
4891 trimRight: returnsString,
4892 trimStart: returnsString,
4893 valueOf: returnsString
4894}, objectMembers);
4895function getLiteralMembersForValue(value) {
4896 switch (typeof value) {
4897 case 'boolean':
4898 return literalBooleanMembers;
4899 case 'number':
4900 return literalNumberMembers;
4901 case 'string':
4902 return literalStringMembers;
4903 }
4904 return Object.create(null);
4905}
4906function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
4907 var _a, _b;
4908 if (typeof memberName !== 'string' || !members[memberName]) {
4909 return true;
4910 }
4911 return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
4912}
4913function getMemberReturnExpressionWhenCalled(members, memberName) {
4914 if (typeof memberName !== 'string' || !members[memberName])
4915 return UNKNOWN_EXPRESSION;
4916 return members[memberName].returns;
4917}
4918
4919// AST walker module for Mozilla Parser API compatible trees
4920
4921function skipThrough(node, st, c) { c(node, st); }
4922function ignore(_node, _st, _c) {}
4923
4924// Node walkers.
4925
4926var base$1 = {};
4927
4928base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
4929 for (var i = 0, list = node.body; i < list.length; i += 1)
4930 {
4931 var stmt = list[i];
4932
4933 c(stmt, st, "Statement");
4934 }
4935};
4936base$1.Statement = skipThrough;
4937base$1.EmptyStatement = ignore;
4938base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
4939 function (node, st, c) { return c(node.expression, st, "Expression"); };
4940base$1.IfStatement = function (node, st, c) {
4941 c(node.test, st, "Expression");
4942 c(node.consequent, st, "Statement");
4943 if (node.alternate) { c(node.alternate, st, "Statement"); }
4944};
4945base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
4946base$1.BreakStatement = base$1.ContinueStatement = ignore;
4947base$1.WithStatement = function (node, st, c) {
4948 c(node.object, st, "Expression");
4949 c(node.body, st, "Statement");
4950};
4951base$1.SwitchStatement = function (node, st, c) {
4952 c(node.discriminant, st, "Expression");
4953 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
4954 var cs = list$1[i$1];
4955
4956 if (cs.test) { c(cs.test, st, "Expression"); }
4957 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
4958 {
4959 var cons = list[i];
4960
4961 c(cons, st, "Statement");
4962 }
4963 }
4964};
4965base$1.SwitchCase = function (node, st, c) {
4966 if (node.test) { c(node.test, st, "Expression"); }
4967 for (var i = 0, list = node.consequent; i < list.length; i += 1)
4968 {
4969 var cons = list[i];
4970
4971 c(cons, st, "Statement");
4972 }
4973};
4974base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
4975 if (node.argument) { c(node.argument, st, "Expression"); }
4976};
4977base$1.ThrowStatement = base$1.SpreadElement =
4978 function (node, st, c) { return c(node.argument, st, "Expression"); };
4979base$1.TryStatement = function (node, st, c) {
4980 c(node.block, st, "Statement");
4981 if (node.handler) { c(node.handler, st); }
4982 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
4983};
4984base$1.CatchClause = function (node, st, c) {
4985 if (node.param) { c(node.param, st, "Pattern"); }
4986 c(node.body, st, "Statement");
4987};
4988base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
4989 c(node.test, st, "Expression");
4990 c(node.body, st, "Statement");
4991};
4992base$1.ForStatement = function (node, st, c) {
4993 if (node.init) { c(node.init, st, "ForInit"); }
4994 if (node.test) { c(node.test, st, "Expression"); }
4995 if (node.update) { c(node.update, st, "Expression"); }
4996 c(node.body, st, "Statement");
4997};
4998base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
4999 c(node.left, st, "ForInit");
5000 c(node.right, st, "Expression");
5001 c(node.body, st, "Statement");
5002};
5003base$1.ForInit = function (node, st, c) {
5004 if (node.type === "VariableDeclaration") { c(node, st); }
5005 else { c(node, st, "Expression"); }
5006};
5007base$1.DebuggerStatement = ignore;
5008
5009base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
5010base$1.VariableDeclaration = function (node, st, c) {
5011 for (var i = 0, list = node.declarations; i < list.length; i += 1)
5012 {
5013 var decl = list[i];
5014
5015 c(decl, st);
5016 }
5017};
5018base$1.VariableDeclarator = function (node, st, c) {
5019 c(node.id, st, "Pattern");
5020 if (node.init) { c(node.init, st, "Expression"); }
5021};
5022
5023base$1.Function = function (node, st, c) {
5024 if (node.id) { c(node.id, st, "Pattern"); }
5025 for (var i = 0, list = node.params; i < list.length; i += 1)
5026 {
5027 var param = list[i];
5028
5029 c(param, st, "Pattern");
5030 }
5031 c(node.body, st, node.expression ? "Expression" : "Statement");
5032};
5033
5034base$1.Pattern = function (node, st, c) {
5035 if (node.type === "Identifier")
5036 { c(node, st, "VariablePattern"); }
5037 else if (node.type === "MemberExpression")
5038 { c(node, st, "MemberPattern"); }
5039 else
5040 { c(node, st); }
5041};
5042base$1.VariablePattern = ignore;
5043base$1.MemberPattern = skipThrough;
5044base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
5045base$1.ArrayPattern = function (node, st, c) {
5046 for (var i = 0, list = node.elements; i < list.length; i += 1) {
5047 var elt = list[i];
5048
5049 if (elt) { c(elt, st, "Pattern"); }
5050 }
5051};
5052base$1.ObjectPattern = function (node, st, c) {
5053 for (var i = 0, list = node.properties; i < list.length; i += 1) {
5054 var prop = list[i];
5055
5056 if (prop.type === "Property") {
5057 if (prop.computed) { c(prop.key, st, "Expression"); }
5058 c(prop.value, st, "Pattern");
5059 } else if (prop.type === "RestElement") {
5060 c(prop.argument, st, "Pattern");
5061 }
5062 }
5063};
5064
5065base$1.Expression = skipThrough;
5066base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
5067base$1.ArrayExpression = function (node, st, c) {
5068 for (var i = 0, list = node.elements; i < list.length; i += 1) {
5069 var elt = list[i];
5070
5071 if (elt) { c(elt, st, "Expression"); }
5072 }
5073};
5074base$1.ObjectExpression = function (node, st, c) {
5075 for (var i = 0, list = node.properties; i < list.length; i += 1)
5076 {
5077 var prop = list[i];
5078
5079 c(prop, st);
5080 }
5081};
5082base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
5083base$1.SequenceExpression = function (node, st, c) {
5084 for (var i = 0, list = node.expressions; i < list.length; i += 1)
5085 {
5086 var expr = list[i];
5087
5088 c(expr, st, "Expression");
5089 }
5090};
5091base$1.TemplateLiteral = function (node, st, c) {
5092 for (var i = 0, list = node.quasis; i < list.length; i += 1)
5093 {
5094 var quasi = list[i];
5095
5096 c(quasi, st);
5097 }
5098
5099 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
5100 {
5101 var expr = list$1[i$1];
5102
5103 c(expr, st, "Expression");
5104 }
5105};
5106base$1.TemplateElement = ignore;
5107base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
5108 c(node.argument, st, "Expression");
5109};
5110base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
5111 c(node.left, st, "Expression");
5112 c(node.right, st, "Expression");
5113};
5114base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
5115 c(node.left, st, "Pattern");
5116 c(node.right, st, "Expression");
5117};
5118base$1.ConditionalExpression = function (node, st, c) {
5119 c(node.test, st, "Expression");
5120 c(node.consequent, st, "Expression");
5121 c(node.alternate, st, "Expression");
5122};
5123base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
5124 c(node.callee, st, "Expression");
5125 if (node.arguments)
5126 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
5127 {
5128 var arg = list[i];
5129
5130 c(arg, st, "Expression");
5131 } }
5132};
5133base$1.MemberExpression = function (node, st, c) {
5134 c(node.object, st, "Expression");
5135 if (node.computed) { c(node.property, st, "Expression"); }
5136};
5137base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
5138 if (node.declaration)
5139 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
5140 if (node.source) { c(node.source, st, "Expression"); }
5141};
5142base$1.ExportAllDeclaration = function (node, st, c) {
5143 if (node.exported)
5144 { c(node.exported, st); }
5145 c(node.source, st, "Expression");
5146};
5147base$1.ImportDeclaration = function (node, st, c) {
5148 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
5149 {
5150 var spec = list[i];
5151
5152 c(spec, st);
5153 }
5154 c(node.source, st, "Expression");
5155};
5156base$1.ImportExpression = function (node, st, c) {
5157 c(node.source, st, "Expression");
5158};
5159base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
5160
5161base$1.TaggedTemplateExpression = function (node, st, c) {
5162 c(node.tag, st, "Expression");
5163 c(node.quasi, st, "Expression");
5164};
5165base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
5166base$1.Class = function (node, st, c) {
5167 if (node.id) { c(node.id, st, "Pattern"); }
5168 if (node.superClass) { c(node.superClass, st, "Expression"); }
5169 c(node.body, st);
5170};
5171base$1.ClassBody = function (node, st, c) {
5172 for (var i = 0, list = node.body; i < list.length; i += 1)
5173 {
5174 var elt = list[i];
5175
5176 c(elt, st);
5177 }
5178};
5179base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
5180 if (node.computed) { c(node.key, st, "Expression"); }
5181 if (node.value) { c(node.value, st, "Expression"); }
5182};
5183
5184const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
5185const BinaryExpression$1 = 'BinaryExpression';
5186const BlockStatement$1 = 'BlockStatement';
5187const CallExpression$1 = 'CallExpression';
5188const ChainExpression$1 = 'ChainExpression';
5189const ConditionalExpression$1 = 'ConditionalExpression';
5190const ExpressionStatement$1 = 'ExpressionStatement';
5191const Identifier$1 = 'Identifier';
5192const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
5193const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
5194const LogicalExpression$1 = 'LogicalExpression';
5195const NewExpression$1 = 'NewExpression';
5196const Program$1 = 'Program';
5197const Property$1 = 'Property';
5198const ReturnStatement$1 = 'ReturnStatement';
5199const SequenceExpression$1 = 'SequenceExpression';
5200
5201// this looks ridiculous, but it prevents sourcemap tooling from mistaking
5202// this for an actual sourceMappingURL
5203exports.SOURCEMAPPING_URL = 'sourceMa';
5204exports.SOURCEMAPPING_URL += 'ppingURL';
5205const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
5206const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${exports.SOURCEMAPPING_URL}=.+`);
5207
5208const ANNOTATION_KEY = '_rollupAnnotations';
5209const INVALID_COMMENT_KEY = '_rollupRemoved';
5210function handlePureAnnotationsOfNode(node, state, type = node.type) {
5211 const { annotations } = state;
5212 let comment = annotations[state.annotationIndex];
5213 while (comment && node.start >= comment.end) {
5214 markPureNode(node, comment, state.code);
5215 comment = annotations[++state.annotationIndex];
5216 }
5217 if (comment && comment.end <= node.end) {
5218 base$1[type](node, state, handlePureAnnotationsOfNode);
5219 while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
5220 ++state.annotationIndex;
5221 annotateNode(node, comment, false);
5222 }
5223 }
5224}
5225const neitherWithespaceNorBrackets = /[^\s(]/g;
5226const noWhitespace = /\S/g;
5227function markPureNode(node, comment, code) {
5228 const annotatedNodes = [];
5229 let invalidAnnotation;
5230 const codeInBetween = code.slice(comment.end, node.start);
5231 if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
5232 const parentStart = node.start;
5233 while (true) {
5234 annotatedNodes.push(node);
5235 switch (node.type) {
5236 case ExpressionStatement$1:
5237 case ChainExpression$1:
5238 node = node.expression;
5239 continue;
5240 case SequenceExpression$1:
5241 // if there are parentheses, the annotation would apply to the entire expression
5242 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5243 node = node.expressions[0];
5244 continue;
5245 }
5246 invalidAnnotation = true;
5247 break;
5248 case ConditionalExpression$1:
5249 // if there are parentheses, the annotation would apply to the entire expression
5250 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5251 node = node.test;
5252 continue;
5253 }
5254 invalidAnnotation = true;
5255 break;
5256 case LogicalExpression$1:
5257 case BinaryExpression$1:
5258 // if there are parentheses, the annotation would apply to the entire expression
5259 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5260 node = node.left;
5261 continue;
5262 }
5263 invalidAnnotation = true;
5264 break;
5265 case CallExpression$1:
5266 case NewExpression$1:
5267 break;
5268 default:
5269 invalidAnnotation = true;
5270 }
5271 break;
5272 }
5273 }
5274 else {
5275 invalidAnnotation = true;
5276 }
5277 if (invalidAnnotation) {
5278 annotateNode(node, comment, false);
5279 }
5280 else {
5281 for (const node of annotatedNodes) {
5282 annotateNode(node, comment, true);
5283 }
5284 }
5285}
5286function doesNotMatchOutsideComment(code, forbiddenChars) {
5287 let nextMatch;
5288 while ((nextMatch = forbiddenChars.exec(code)) !== null) {
5289 if (nextMatch[0] === '/') {
5290 const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
5291 if (charCodeAfterSlash === 42 /*"*"*/) {
5292 forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
5293 continue;
5294 }
5295 else if (charCodeAfterSlash === 47 /*"/"*/) {
5296 forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
5297 continue;
5298 }
5299 }
5300 forbiddenChars.lastIndex = 0;
5301 return false;
5302 }
5303 return true;
5304}
5305const pureCommentRegex = /[@#]__PURE__/;
5306function addAnnotations(comments, esTreeAst, code) {
5307 const annotations = [];
5308 const sourceMappingComments = [];
5309 for (const comment of comments) {
5310 if (pureCommentRegex.test(comment.value)) {
5311 annotations.push(comment);
5312 }
5313 else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
5314 sourceMappingComments.push(comment);
5315 }
5316 }
5317 for (const comment of sourceMappingComments) {
5318 annotateNode(esTreeAst, comment, false);
5319 }
5320 handlePureAnnotationsOfNode(esTreeAst, {
5321 annotationIndex: 0,
5322 annotations,
5323 code
5324 });
5325}
5326function annotateNode(node, comment, valid) {
5327 const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
5328 const property = node[key];
5329 if (property) {
5330 property.push(comment);
5331 }
5332 else {
5333 node[key] = [comment];
5334 }
5335}
5336
5337const keys = {
5338 Literal: [],
5339 Program: ['body']
5340};
5341function getAndCreateKeys(esTreeNode) {
5342 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
5343 return keys[esTreeNode.type];
5344}
5345
5346const INCLUDE_PARAMETERS = 'variables';
5347class NodeBase extends ExpressionEntity {
5348 constructor(esTreeNode, parent, parentScope) {
5349 super();
5350 /**
5351 * Nodes can apply custom deoptimizations once they become part of the
5352 * executed code. To do this, they must initialize this as false, implement
5353 * applyDeoptimizations and call this from include and hasEffects if they have
5354 * custom handlers
5355 */
5356 this.deoptimized = false;
5357 this.esTreeNode = esTreeNode;
5358 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
5359 this.parent = parent;
5360 this.context = parent.context;
5361 this.createScope(parentScope);
5362 this.parseNode(esTreeNode);
5363 this.initialise();
5364 this.context.magicString.addSourcemapLocation(this.start);
5365 this.context.magicString.addSourcemapLocation(this.end);
5366 }
5367 addExportedVariables(_variables, _exportNamesByVariable) { }
5368 /**
5369 * Override this to bind assignments to variables and do any initialisations that
5370 * require the scopes to be populated with variables.
5371 */
5372 bind() {
5373 for (const key of this.keys) {
5374 const value = this[key];
5375 if (value === null)
5376 continue;
5377 if (Array.isArray(value)) {
5378 for (const child of value) {
5379 child === null || child === void 0 ? void 0 : child.bind();
5380 }
5381 }
5382 else {
5383 value.bind();
5384 }
5385 }
5386 }
5387 /**
5388 * Override if this node should receive a different scope than the parent scope.
5389 */
5390 createScope(parentScope) {
5391 this.scope = parentScope;
5392 }
5393 hasEffects(context) {
5394 if (!this.deoptimized)
5395 this.applyDeoptimizations();
5396 for (const key of this.keys) {
5397 const value = this[key];
5398 if (value === null)
5399 continue;
5400 if (Array.isArray(value)) {
5401 for (const child of value) {
5402 if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
5403 return true;
5404 }
5405 }
5406 else if (value.hasEffects(context))
5407 return true;
5408 }
5409 return false;
5410 }
5411 hasEffectsAsAssignmentTarget(context, _checkAccess) {
5412 return (this.hasEffects(context) ||
5413 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
5414 }
5415 include(context, includeChildrenRecursively, _options) {
5416 if (!this.deoptimized)
5417 this.applyDeoptimizations();
5418 this.included = true;
5419 for (const key of this.keys) {
5420 const value = this[key];
5421 if (value === null)
5422 continue;
5423 if (Array.isArray(value)) {
5424 for (const child of value) {
5425 child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
5426 }
5427 }
5428 else {
5429 value.include(context, includeChildrenRecursively);
5430 }
5431 }
5432 }
5433 includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
5434 this.include(context, includeChildrenRecursively);
5435 }
5436 /**
5437 * Override to perform special initialisation steps after the scope is initialised
5438 */
5439 initialise() { }
5440 insertSemicolon(code) {
5441 if (code.original[this.end - 1] !== ';') {
5442 code.appendLeft(this.end, ';');
5443 }
5444 }
5445 parseNode(esTreeNode) {
5446 for (const [key, value] of Object.entries(esTreeNode)) {
5447 // That way, we can override this function to add custom initialisation and then call super.parseNode
5448 if (this.hasOwnProperty(key))
5449 continue;
5450 if (key.charCodeAt(0) === 95 /* _ */) {
5451 if (key === ANNOTATION_KEY) {
5452 this.annotations = value;
5453 }
5454 else if (key === INVALID_COMMENT_KEY) {
5455 for (const { start, end } of value)
5456 this.context.magicString.remove(start, end);
5457 }
5458 }
5459 else if (typeof value !== 'object' || value === null) {
5460 this[key] = value;
5461 }
5462 else if (Array.isArray(value)) {
5463 this[key] = [];
5464 for (const child of value) {
5465 this[key].push(child === null
5466 ? null
5467 : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
5468 }
5469 }
5470 else {
5471 this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
5472 }
5473 }
5474 }
5475 render(code, options) {
5476 for (const key of this.keys) {
5477 const value = this[key];
5478 if (value === null)
5479 continue;
5480 if (Array.isArray(value)) {
5481 for (const child of value) {
5482 child === null || child === void 0 ? void 0 : child.render(code, options);
5483 }
5484 }
5485 else {
5486 value.render(code, options);
5487 }
5488 }
5489 }
5490 setAssignedValue(value) {
5491 this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
5492 }
5493 shouldBeIncluded(context) {
5494 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
5495 }
5496 /**
5497 * Just deoptimize everything by default so that when e.g. we do not track
5498 * something properly, it is deoptimized.
5499 * @protected
5500 */
5501 applyDeoptimizations() {
5502 this.deoptimized = true;
5503 for (const key of this.keys) {
5504 const value = this[key];
5505 if (value === null)
5506 continue;
5507 if (Array.isArray(value)) {
5508 for (const child of value) {
5509 child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
5510 }
5511 }
5512 else {
5513 value.deoptimizePath(UNKNOWN_PATH);
5514 }
5515 }
5516 this.context.requestTreeshakingPass();
5517 }
5518}
5519
5520class SpreadElement extends NodeBase {
5521 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5522 if (path.length > 0) {
5523 this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
5524 }
5525 }
5526 hasEffects(context) {
5527 if (!this.deoptimized)
5528 this.applyDeoptimizations();
5529 const { propertyReadSideEffects } = this.context.options
5530 .treeshake;
5531 return (this.argument.hasEffects(context) ||
5532 (propertyReadSideEffects &&
5533 (propertyReadSideEffects === 'always' ||
5534 this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
5535 }
5536 applyDeoptimizations() {
5537 this.deoptimized = true;
5538 // Only properties of properties of the argument could become subject to reassignment
5539 // This will also reassign the return values of iterators
5540 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
5541 this.context.requestTreeshakingPass();
5542 }
5543}
5544
5545class Method extends ExpressionEntity {
5546 constructor(description) {
5547 super();
5548 this.description = description;
5549 }
5550 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5551 if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
5552 thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
5553 }
5554 }
5555 getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
5556 if (path.length > 0) {
5557 return UNKNOWN_EXPRESSION;
5558 }
5559 return (this.description.returnsPrimitive ||
5560 (this.description.returns === 'self'
5561 ? thisArg || UNKNOWN_EXPRESSION
5562 : this.description.returns()));
5563 }
5564 hasEffectsOnInteractionAtPath(path, interaction, context) {
5565 var _a, _b;
5566 const { type } = interaction;
5567 if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
5568 return true;
5569 }
5570 if (type === INTERACTION_CALLED) {
5571 if (this.description.mutatesSelfAsArray === true &&
5572 ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
5573 return true;
5574 }
5575 if (this.description.callsArgs) {
5576 for (const argIndex of this.description.callsArgs) {
5577 if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
5578 return true;
5579 }
5580 }
5581 }
5582 }
5583 return false;
5584 }
5585}
5586const METHOD_RETURNS_BOOLEAN = [
5587 new Method({
5588 callsArgs: null,
5589 mutatesSelfAsArray: false,
5590 returns: null,
5591 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
5592 })
5593];
5594const METHOD_RETURNS_STRING = [
5595 new Method({
5596 callsArgs: null,
5597 mutatesSelfAsArray: false,
5598 returns: null,
5599 returnsPrimitive: UNKNOWN_LITERAL_STRING
5600 })
5601];
5602const METHOD_RETURNS_NUMBER = [
5603 new Method({
5604 callsArgs: null,
5605 mutatesSelfAsArray: false,
5606 returns: null,
5607 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5608 })
5609];
5610const METHOD_RETURNS_UNKNOWN = [
5611 new Method({
5612 callsArgs: null,
5613 mutatesSelfAsArray: false,
5614 returns: null,
5615 returnsPrimitive: UNKNOWN_EXPRESSION
5616 })
5617];
5618
5619const INTEGER_REG_EXP = /^\d+$/;
5620class ObjectEntity extends ExpressionEntity {
5621 // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
5622 // and we assume there are no setters or getters
5623 constructor(properties, prototypeExpression, immutable = false) {
5624 super();
5625 this.prototypeExpression = prototypeExpression;
5626 this.immutable = immutable;
5627 this.allProperties = [];
5628 this.deoptimizedPaths = Object.create(null);
5629 this.expressionsToBeDeoptimizedByKey = Object.create(null);
5630 this.gettersByKey = Object.create(null);
5631 this.hasLostTrack = false;
5632 this.hasUnknownDeoptimizedInteger = false;
5633 this.hasUnknownDeoptimizedProperty = false;
5634 this.propertiesAndGettersByKey = Object.create(null);
5635 this.propertiesAndSettersByKey = Object.create(null);
5636 this.settersByKey = Object.create(null);
5637 this.thisParametersToBeDeoptimized = new Set();
5638 this.unknownIntegerProps = [];
5639 this.unmatchableGetters = [];
5640 this.unmatchablePropertiesAndGetters = [];
5641 this.unmatchableSetters = [];
5642 if (Array.isArray(properties)) {
5643 this.buildPropertyMaps(properties);
5644 }
5645 else {
5646 this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
5647 for (const propertiesForKey of Object.values(properties)) {
5648 this.allProperties.push(...propertiesForKey);
5649 }
5650 }
5651 }
5652 deoptimizeAllProperties(noAccessors) {
5653 var _a;
5654 const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
5655 if (noAccessors) {
5656 this.hasUnknownDeoptimizedProperty = true;
5657 }
5658 else {
5659 this.hasLostTrack = true;
5660 }
5661 if (isDeoptimized) {
5662 return;
5663 }
5664 for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
5665 for (const property of properties) {
5666 property.deoptimizePath(UNKNOWN_PATH);
5667 }
5668 }
5669 // While the prototype itself cannot be mutated, each property can
5670 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
5671 this.deoptimizeCachedEntities();
5672 }
5673 deoptimizeIntegerProperties() {
5674 if (this.hasLostTrack ||
5675 this.hasUnknownDeoptimizedProperty ||
5676 this.hasUnknownDeoptimizedInteger) {
5677 return;
5678 }
5679 this.hasUnknownDeoptimizedInteger = true;
5680 for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
5681 if (INTEGER_REG_EXP.test(key)) {
5682 for (const property of propertiesAndGetters) {
5683 property.deoptimizePath(UNKNOWN_PATH);
5684 }
5685 }
5686 }
5687 this.deoptimizeCachedIntegerEntities();
5688 }
5689 // Assumption: If only a specific path is deoptimized, no accessors are created
5690 deoptimizePath(path) {
5691 var _a;
5692 if (this.hasLostTrack || this.immutable) {
5693 return;
5694 }
5695 const key = path[0];
5696 if (path.length === 1) {
5697 if (typeof key !== 'string') {
5698 if (key === UnknownInteger) {
5699 return this.deoptimizeIntegerProperties();
5700 }
5701 return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
5702 }
5703 if (!this.deoptimizedPaths[key]) {
5704 this.deoptimizedPaths[key] = true;
5705 // we only deoptimizeCache exact matches as in all other cases,
5706 // we do not return a literal value or return expression
5707 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
5708 if (expressionsToBeDeoptimized) {
5709 for (const expression of expressionsToBeDeoptimized) {
5710 expression.deoptimizeCache();
5711 }
5712 }
5713 }
5714 }
5715 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
5716 for (const property of typeof key === 'string'
5717 ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
5718 : this.allProperties) {
5719 property.deoptimizePath(subPath);
5720 }
5721 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
5722 }
5723 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5724 var _a;
5725 const [key, ...subPath] = path;
5726 if (this.hasLostTrack ||
5727 // single paths that are deoptimized will not become getters or setters
5728 ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
5729 (this.hasUnknownDeoptimizedProperty ||
5730 (typeof key === 'string' && this.deoptimizedPaths[key])))) {
5731 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
5732 return;
5733 }
5734 const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
5735 ? [
5736 this.propertiesAndGettersByKey,
5737 this.propertiesAndGettersByKey,
5738 this.unmatchablePropertiesAndGetters
5739 ]
5740 : interaction.type === INTERACTION_ACCESSED
5741 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5742 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5743 if (typeof key === 'string') {
5744 if (propertiesForExactMatchByKey[key]) {
5745 const properties = relevantPropertiesByKey[key];
5746 if (properties) {
5747 for (const property of properties) {
5748 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5749 }
5750 }
5751 if (!this.immutable) {
5752 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5753 }
5754 return;
5755 }
5756 for (const property of relevantUnmatchableProperties) {
5757 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5758 }
5759 if (INTEGER_REG_EXP.test(key)) {
5760 for (const property of this.unknownIntegerProps) {
5761 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5762 }
5763 }
5764 }
5765 else {
5766 for (const properties of Object.values(relevantPropertiesByKey).concat([
5767 relevantUnmatchableProperties
5768 ])) {
5769 for (const property of properties) {
5770 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5771 }
5772 }
5773 for (const property of this.unknownIntegerProps) {
5774 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5775 }
5776 }
5777 if (!this.immutable) {
5778 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5779 }
5780 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
5781 }
5782 getLiteralValueAtPath(path, recursionTracker, origin) {
5783 if (path.length === 0) {
5784 return UnknownTruthyValue;
5785 }
5786 const key = path[0];
5787 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5788 if (expressionAtPath) {
5789 return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
5790 }
5791 if (this.prototypeExpression) {
5792 return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
5793 }
5794 if (path.length === 1) {
5795 return undefined;
5796 }
5797 return UnknownValue;
5798 }
5799 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
5800 if (path.length === 0) {
5801 return UNKNOWN_EXPRESSION;
5802 }
5803 const [key, ...subPath] = path;
5804 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5805 if (expressionAtPath) {
5806 return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
5807 }
5808 if (this.prototypeExpression) {
5809 return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
5810 }
5811 return UNKNOWN_EXPRESSION;
5812 }
5813 hasEffectsOnInteractionAtPath(path, interaction, context) {
5814 const [key, ...subPath] = path;
5815 if (subPath.length || interaction.type === INTERACTION_CALLED) {
5816 const expressionAtPath = this.getMemberExpression(key);
5817 if (expressionAtPath) {
5818 return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
5819 }
5820 if (this.prototypeExpression) {
5821 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5822 }
5823 return true;
5824 }
5825 if (key === UnknownNonAccessorKey)
5826 return false;
5827 if (this.hasLostTrack)
5828 return true;
5829 const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
5830 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5831 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5832 if (typeof key === 'string') {
5833 if (propertiesAndAccessorsByKey[key]) {
5834 const accessors = accessorsByKey[key];
5835 if (accessors) {
5836 for (const accessor of accessors) {
5837 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5838 return true;
5839 }
5840 }
5841 return false;
5842 }
5843 for (const accessor of unmatchableAccessors) {
5844 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
5845 return true;
5846 }
5847 }
5848 }
5849 else {
5850 for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
5851 for (const accessor of accessors) {
5852 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5853 return true;
5854 }
5855 }
5856 }
5857 if (this.prototypeExpression) {
5858 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5859 }
5860 return false;
5861 }
5862 buildPropertyMaps(properties) {
5863 const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
5864 const unmatchablePropertiesAndSetters = [];
5865 for (let index = properties.length - 1; index >= 0; index--) {
5866 const { key, kind, property } = properties[index];
5867 allProperties.push(property);
5868 if (typeof key !== 'string') {
5869 if (key === UnknownInteger) {
5870 unknownIntegerProps.push(property);
5871 continue;
5872 }
5873 if (kind === 'set')
5874 unmatchableSetters.push(property);
5875 if (kind === 'get')
5876 unmatchableGetters.push(property);
5877 if (kind !== 'get')
5878 unmatchablePropertiesAndSetters.push(property);
5879 if (kind !== 'set')
5880 unmatchablePropertiesAndGetters.push(property);
5881 }
5882 else {
5883 if (kind === 'set') {
5884 if (!propertiesAndSettersByKey[key]) {
5885 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5886 settersByKey[key] = [property, ...unmatchableSetters];
5887 }
5888 }
5889 else if (kind === 'get') {
5890 if (!propertiesAndGettersByKey[key]) {
5891 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5892 gettersByKey[key] = [property, ...unmatchableGetters];
5893 }
5894 }
5895 else {
5896 if (!propertiesAndSettersByKey[key]) {
5897 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5898 }
5899 if (!propertiesAndGettersByKey[key]) {
5900 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5901 }
5902 }
5903 }
5904 }
5905 }
5906 deoptimizeCachedEntities() {
5907 for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
5908 for (const expression of expressionsToBeDeoptimized) {
5909 expression.deoptimizeCache();
5910 }
5911 }
5912 for (const expression of this.thisParametersToBeDeoptimized) {
5913 expression.deoptimizePath(UNKNOWN_PATH);
5914 }
5915 }
5916 deoptimizeCachedIntegerEntities() {
5917 for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
5918 if (INTEGER_REG_EXP.test(key)) {
5919 for (const expression of expressionsToBeDeoptimized) {
5920 expression.deoptimizeCache();
5921 }
5922 }
5923 }
5924 for (const expression of this.thisParametersToBeDeoptimized) {
5925 expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
5926 }
5927 }
5928 getMemberExpression(key) {
5929 if (this.hasLostTrack ||
5930 this.hasUnknownDeoptimizedProperty ||
5931 typeof key !== 'string' ||
5932 (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
5933 this.deoptimizedPaths[key]) {
5934 return UNKNOWN_EXPRESSION;
5935 }
5936 const properties = this.propertiesAndGettersByKey[key];
5937 if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
5938 return properties[0];
5939 }
5940 if (properties ||
5941 this.unmatchablePropertiesAndGetters.length > 0 ||
5942 (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
5943 return UNKNOWN_EXPRESSION;
5944 }
5945 return null;
5946 }
5947 getMemberExpressionAndTrackDeopt(key, origin) {
5948 if (typeof key !== 'string') {
5949 return UNKNOWN_EXPRESSION;
5950 }
5951 const expression = this.getMemberExpression(key);
5952 if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
5953 const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
5954 this.expressionsToBeDeoptimizedByKey[key] || []);
5955 expressionsToBeDeoptimized.push(origin);
5956 }
5957 return expression;
5958 }
5959}
5960
5961const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
5962// This makes sure unknown properties are not handled as "undefined" but as
5963// "unknown" but without access side effects. An exception is done for numeric
5964// properties as we do not expect new builtin properties to be numbers, this
5965// will improve tree-shaking for out-of-bounds array properties
5966const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
5967 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5968 if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
5969 thisArg.deoptimizePath(UNKNOWN_PATH);
5970 }
5971 }
5972 getLiteralValueAtPath(path) {
5973 // We ignore number properties as we do not expect new properties to be
5974 // numbers and also want to keep handling out-of-bound array elements as
5975 // "undefined"
5976 return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
5977 }
5978 hasEffectsOnInteractionAtPath(path, { type }) {
5979 return path.length > 1 || type === INTERACTION_CALLED;
5980 }
5981})();
5982const OBJECT_PROTOTYPE = new ObjectEntity({
5983 __proto__: null,
5984 hasOwnProperty: METHOD_RETURNS_BOOLEAN,
5985 isPrototypeOf: METHOD_RETURNS_BOOLEAN,
5986 propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
5987 toLocaleString: METHOD_RETURNS_STRING,
5988 toString: METHOD_RETURNS_STRING,
5989 valueOf: METHOD_RETURNS_UNKNOWN
5990}, OBJECT_PROTOTYPE_FALLBACK, true);
5991
5992const NEW_ARRAY_PROPERTIES = [
5993 { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
5994 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
5995];
5996const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
5997 new Method({
5998 callsArgs: [0],
5999 mutatesSelfAsArray: 'deopt-only',
6000 returns: null,
6001 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
6002 })
6003];
6004const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
6005 new Method({
6006 callsArgs: [0],
6007 mutatesSelfAsArray: 'deopt-only',
6008 returns: null,
6009 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6010 })
6011];
6012const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
6013 new Method({
6014 callsArgs: null,
6015 mutatesSelfAsArray: true,
6016 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6017 returnsPrimitive: null
6018 })
6019];
6020const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6021 new Method({
6022 callsArgs: null,
6023 mutatesSelfAsArray: 'deopt-only',
6024 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6025 returnsPrimitive: null
6026 })
6027];
6028const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6029 new Method({
6030 callsArgs: [0],
6031 mutatesSelfAsArray: 'deopt-only',
6032 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6033 returnsPrimitive: null
6034 })
6035];
6036const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
6037 new Method({
6038 callsArgs: null,
6039 mutatesSelfAsArray: true,
6040 returns: null,
6041 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6042 })
6043];
6044const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
6045 new Method({
6046 callsArgs: null,
6047 mutatesSelfAsArray: true,
6048 returns: null,
6049 returnsPrimitive: UNKNOWN_EXPRESSION
6050 })
6051];
6052const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
6053 new Method({
6054 callsArgs: null,
6055 mutatesSelfAsArray: 'deopt-only',
6056 returns: null,
6057 returnsPrimitive: UNKNOWN_EXPRESSION
6058 })
6059];
6060const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
6061 new Method({
6062 callsArgs: [0],
6063 mutatesSelfAsArray: 'deopt-only',
6064 returns: null,
6065 returnsPrimitive: UNKNOWN_EXPRESSION
6066 })
6067];
6068const METHOD_MUTATES_SELF_RETURNS_SELF = [
6069 new Method({
6070 callsArgs: null,
6071 mutatesSelfAsArray: true,
6072 returns: 'self',
6073 returnsPrimitive: null
6074 })
6075];
6076const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
6077 new Method({
6078 callsArgs: [0],
6079 mutatesSelfAsArray: true,
6080 returns: 'self',
6081 returnsPrimitive: null
6082 })
6083];
6084const ARRAY_PROTOTYPE = new ObjectEntity({
6085 __proto__: null,
6086 // We assume that accessors have effects as we do not track the accessed value afterwards
6087 at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
6088 concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6089 copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
6090 entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6091 every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6092 fill: METHOD_MUTATES_SELF_RETURNS_SELF,
6093 filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6094 find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6095 findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
6096 findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6097 findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
6098 flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6099 flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6100 forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6101 group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6102 groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6103 includes: METHOD_RETURNS_BOOLEAN,
6104 indexOf: METHOD_RETURNS_NUMBER,
6105 join: METHOD_RETURNS_STRING,
6106 keys: METHOD_RETURNS_UNKNOWN,
6107 lastIndexOf: METHOD_RETURNS_NUMBER,
6108 map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6109 pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6110 push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6111 reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6112 reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6113 reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
6114 shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6115 slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6116 some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6117 sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
6118 splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
6119 toLocaleString: METHOD_RETURNS_STRING,
6120 toString: METHOD_RETURNS_STRING,
6121 unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6122 values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
6123}, OBJECT_PROTOTYPE, true);
6124
6125class ArrayExpression extends NodeBase {
6126 constructor() {
6127 super(...arguments);
6128 this.objectEntity = null;
6129 }
6130 deoptimizePath(path) {
6131 this.getObjectEntity().deoptimizePath(path);
6132 }
6133 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6134 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
6135 }
6136 getLiteralValueAtPath(path, recursionTracker, origin) {
6137 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
6138 }
6139 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6140 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6141 }
6142 hasEffectsOnInteractionAtPath(path, interaction, context) {
6143 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
6144 }
6145 applyDeoptimizations() {
6146 this.deoptimized = true;
6147 let hasSpread = false;
6148 for (let index = 0; index < this.elements.length; index++) {
6149 const element = this.elements[index];
6150 if (element) {
6151 if (hasSpread || element instanceof SpreadElement) {
6152 hasSpread = true;
6153 element.deoptimizePath(UNKNOWN_PATH);
6154 }
6155 }
6156 }
6157 this.context.requestTreeshakingPass();
6158 }
6159 getObjectEntity() {
6160 if (this.objectEntity !== null) {
6161 return this.objectEntity;
6162 }
6163 const properties = [
6164 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6165 ];
6166 let hasSpread = false;
6167 for (let index = 0; index < this.elements.length; index++) {
6168 const element = this.elements[index];
6169 if (hasSpread || element instanceof SpreadElement) {
6170 if (element) {
6171 hasSpread = true;
6172 properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
6173 }
6174 }
6175 else if (!element) {
6176 properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
6177 }
6178 else {
6179 properties.push({ key: String(index), kind: 'init', property: element });
6180 }
6181 }
6182 return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
6183 }
6184}
6185
6186class ArrayPattern extends NodeBase {
6187 addExportedVariables(variables, exportNamesByVariable) {
6188 for (const element of this.elements) {
6189 element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
6190 }
6191 }
6192 declare(kind) {
6193 const variables = [];
6194 for (const element of this.elements) {
6195 if (element !== null) {
6196 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
6197 }
6198 }
6199 return variables;
6200 }
6201 // Patterns can only be deoptimized at the empty path at the moment
6202 deoptimizePath() {
6203 for (const element of this.elements) {
6204 element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
6205 }
6206 }
6207 // Patterns are only checked at the emtpy path at the moment
6208 hasEffectsOnInteractionAtPath(_path, interaction, context) {
6209 for (const element of this.elements) {
6210 if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
6211 return true;
6212 }
6213 return false;
6214 }
6215 markDeclarationReached() {
6216 for (const element of this.elements) {
6217 element === null || element === void 0 ? void 0 : element.markDeclarationReached();
6218 }
6219 }
6220}
6221
6222class LocalVariable extends Variable {
6223 constructor(name, declarator, init, context) {
6224 super(name);
6225 this.calledFromTryStatement = false;
6226 this.additionalInitializers = null;
6227 this.expressionsToBeDeoptimized = [];
6228 this.declarations = declarator ? [declarator] : [];
6229 this.init = init;
6230 this.deoptimizationTracker = context.deoptimizationTracker;
6231 this.module = context.module;
6232 }
6233 addDeclaration(identifier, init) {
6234 this.declarations.push(identifier);
6235 const additionalInitializers = this.markInitializersForDeoptimization();
6236 if (init !== null) {
6237 additionalInitializers.push(init);
6238 }
6239 }
6240 consolidateInitializers() {
6241 if (this.additionalInitializers !== null) {
6242 for (const initializer of this.additionalInitializers) {
6243 initializer.deoptimizePath(UNKNOWN_PATH);
6244 }
6245 this.additionalInitializers = null;
6246 }
6247 }
6248 deoptimizePath(path) {
6249 var _a, _b;
6250 if (this.isReassigned ||
6251 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
6252 return;
6253 }
6254 if (path.length === 0) {
6255 if (!this.isReassigned) {
6256 this.isReassigned = true;
6257 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6258 this.expressionsToBeDeoptimized = [];
6259 for (const expression of expressionsToBeDeoptimized) {
6260 expression.deoptimizeCache();
6261 }
6262 (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
6263 }
6264 }
6265 else {
6266 (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
6267 }
6268 }
6269 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6270 if (this.isReassigned || !this.init) {
6271 return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
6272 }
6273 recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
6274 }
6275 getLiteralValueAtPath(path, recursionTracker, origin) {
6276 if (this.isReassigned || !this.init) {
6277 return UnknownValue;
6278 }
6279 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6280 this.expressionsToBeDeoptimized.push(origin);
6281 return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
6282 }, UnknownValue);
6283 }
6284 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6285 if (this.isReassigned || !this.init) {
6286 return UNKNOWN_EXPRESSION;
6287 }
6288 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6289 this.expressionsToBeDeoptimized.push(origin);
6290 return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6291 }, UNKNOWN_EXPRESSION);
6292 }
6293 hasEffectsOnInteractionAtPath(path, interaction, context) {
6294 switch (interaction.type) {
6295 case INTERACTION_ACCESSED:
6296 if (this.isReassigned)
6297 return true;
6298 return (this.init &&
6299 !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
6300 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6301 case INTERACTION_ASSIGNED:
6302 if (this.included)
6303 return true;
6304 if (path.length === 0)
6305 return false;
6306 if (this.isReassigned)
6307 return true;
6308 return (this.init &&
6309 !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
6310 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6311 case INTERACTION_CALLED:
6312 if (this.isReassigned)
6313 return true;
6314 return (this.init &&
6315 !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
6316 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6317 }
6318 }
6319 include() {
6320 if (!this.included) {
6321 this.included = true;
6322 for (const declaration of this.declarations) {
6323 // If node is a default export, it can save a tree-shaking run to include the full declaration now
6324 if (!declaration.included)
6325 declaration.include(createInclusionContext(), false);
6326 let node = declaration.parent;
6327 while (!node.included) {
6328 // We do not want to properly include parents in case they are part of a dead branch
6329 // in which case .include() might pull in more dead code
6330 node.included = true;
6331 if (node.type === Program$1)
6332 break;
6333 node = node.parent;
6334 }
6335 }
6336 }
6337 }
6338 includeCallArguments(context, args) {
6339 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
6340 for (const arg of args) {
6341 arg.include(context, false);
6342 }
6343 }
6344 else if (this.init) {
6345 context.includedCallArguments.add(this.init);
6346 this.init.includeCallArguments(context, args);
6347 context.includedCallArguments.delete(this.init);
6348 }
6349 }
6350 markCalledFromTryStatement() {
6351 this.calledFromTryStatement = true;
6352 }
6353 markInitializersForDeoptimization() {
6354 if (this.additionalInitializers === null) {
6355 this.additionalInitializers = this.init === null ? [] : [this.init];
6356 this.init = UNKNOWN_EXPRESSION;
6357 this.isReassigned = true;
6358 }
6359 return this.additionalInitializers;
6360 }
6361}
6362
6363const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
6364const base = 64;
6365function toBase64(num) {
6366 let outStr = '';
6367 do {
6368 const curDigit = num % base;
6369 num = Math.floor(num / base);
6370 outStr = chars[curDigit] + outStr;
6371 } while (num !== 0);
6372 return outStr;
6373}
6374
6375function getSafeName(baseName, usedNames) {
6376 let safeName = baseName;
6377 let count = 1;
6378 while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
6379 safeName = `${baseName}$${toBase64(count++)}`;
6380 }
6381 usedNames.add(safeName);
6382 return safeName;
6383}
6384
6385class Scope$1 {
6386 constructor() {
6387 this.children = [];
6388 this.variables = new Map();
6389 }
6390 addDeclaration(identifier, context, init, _isHoisted) {
6391 const name = identifier.name;
6392 let variable = this.variables.get(name);
6393 if (variable) {
6394 variable.addDeclaration(identifier, init);
6395 }
6396 else {
6397 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
6398 this.variables.set(name, variable);
6399 }
6400 return variable;
6401 }
6402 contains(name) {
6403 return this.variables.has(name);
6404 }
6405 findVariable(_name) {
6406 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
6407 }
6408}
6409
6410class ChildScope extends Scope$1 {
6411 constructor(parent) {
6412 super();
6413 this.accessedOutsideVariables = new Map();
6414 this.parent = parent;
6415 parent.children.push(this);
6416 }
6417 addAccessedDynamicImport(importExpression) {
6418 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
6419 if (this.parent instanceof ChildScope) {
6420 this.parent.addAccessedDynamicImport(importExpression);
6421 }
6422 }
6423 addAccessedGlobals(globals, accessedGlobalsByScope) {
6424 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
6425 for (const name of globals) {
6426 accessedGlobals.add(name);
6427 }
6428 accessedGlobalsByScope.set(this, accessedGlobals);
6429 if (this.parent instanceof ChildScope) {
6430 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
6431 }
6432 }
6433 addNamespaceMemberAccess(name, variable) {
6434 this.accessedOutsideVariables.set(name, variable);
6435 this.parent.addNamespaceMemberAccess(name, variable);
6436 }
6437 addReturnExpression(expression) {
6438 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
6439 }
6440 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
6441 for (const variable of this.accessedOutsideVariables.values()) {
6442 if (variable.included) {
6443 usedNames.add(variable.getBaseVariableName());
6444 if (format === 'system' && exportNamesByVariable.has(variable)) {
6445 usedNames.add('exports');
6446 }
6447 }
6448 }
6449 const accessedGlobals = accessedGlobalsByScope.get(this);
6450 if (accessedGlobals) {
6451 for (const name of accessedGlobals) {
6452 usedNames.add(name);
6453 }
6454 }
6455 }
6456 contains(name) {
6457 return this.variables.has(name) || this.parent.contains(name);
6458 }
6459 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
6460 const usedNames = new Set();
6461 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
6462 if (this.accessedDynamicImports) {
6463 for (const importExpression of this.accessedDynamicImports) {
6464 if (importExpression.inlineNamespace) {
6465 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
6466 }
6467 }
6468 }
6469 for (const [name, variable] of this.variables) {
6470 if (variable.included || variable.alwaysRendered) {
6471 variable.setRenderNames(null, getSafeName(name, usedNames));
6472 }
6473 }
6474 for (const scope of this.children) {
6475 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
6476 }
6477 }
6478 findLexicalBoundary() {
6479 return this.parent.findLexicalBoundary();
6480 }
6481 findVariable(name) {
6482 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
6483 if (knownVariable) {
6484 return knownVariable;
6485 }
6486 const variable = this.parent.findVariable(name);
6487 this.accessedOutsideVariables.set(name, variable);
6488 return variable;
6489 }
6490}
6491
6492class ParameterScope extends ChildScope {
6493 constructor(parent, context) {
6494 super(parent);
6495 this.parameters = [];
6496 this.hasRest = false;
6497 this.context = context;
6498 this.hoistedBodyVarScope = new ChildScope(this);
6499 }
6500 /**
6501 * Adds a parameter to this scope. Parameters must be added in the correct
6502 * order, e.g. from left to right.
6503 */
6504 addParameterDeclaration(identifier) {
6505 const name = identifier.name;
6506 let variable = this.hoistedBodyVarScope.variables.get(name);
6507 if (variable) {
6508 variable.addDeclaration(identifier, null);
6509 }
6510 else {
6511 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
6512 }
6513 this.variables.set(name, variable);
6514 return variable;
6515 }
6516 addParameterVariables(parameters, hasRest) {
6517 this.parameters = parameters;
6518 for (const parameterList of parameters) {
6519 for (const parameter of parameterList) {
6520 parameter.alwaysRendered = true;
6521 }
6522 }
6523 this.hasRest = hasRest;
6524 }
6525 includeCallArguments(context, args) {
6526 let calledFromTryStatement = false;
6527 let argIncluded = false;
6528 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
6529 for (const checkedArg of args) {
6530 if (checkedArg instanceof SpreadElement) {
6531 for (const arg of args) {
6532 arg.include(context, false);
6533 }
6534 break;
6535 }
6536 }
6537 for (let index = args.length - 1; index >= 0; index--) {
6538 const paramVars = this.parameters[index] || restParam;
6539 const arg = args[index];
6540 if (paramVars) {
6541 calledFromTryStatement = false;
6542 if (paramVars.length === 0) {
6543 // handle empty destructuring
6544 argIncluded = true;
6545 }
6546 else {
6547 for (const variable of paramVars) {
6548 if (variable.included) {
6549 argIncluded = true;
6550 }
6551 if (variable.calledFromTryStatement) {
6552 calledFromTryStatement = true;
6553 }
6554 }
6555 }
6556 }
6557 if (!argIncluded && arg.shouldBeIncluded(context)) {
6558 argIncluded = true;
6559 }
6560 if (argIncluded) {
6561 arg.include(context, calledFromTryStatement);
6562 }
6563 }
6564 }
6565}
6566
6567class ReturnValueScope extends ParameterScope {
6568 constructor() {
6569 super(...arguments);
6570 this.returnExpression = null;
6571 this.returnExpressions = [];
6572 }
6573 addReturnExpression(expression) {
6574 this.returnExpressions.push(expression);
6575 }
6576 getReturnExpression() {
6577 if (this.returnExpression === null)
6578 this.updateReturnExpression();
6579 return this.returnExpression;
6580 }
6581 updateReturnExpression() {
6582 if (this.returnExpressions.length === 1) {
6583 this.returnExpression = this.returnExpressions[0];
6584 }
6585 else {
6586 this.returnExpression = UNKNOWN_EXPRESSION;
6587 for (const expression of this.returnExpressions) {
6588 expression.deoptimizePath(UNKNOWN_PATH);
6589 }
6590 }
6591 }
6592}
6593
6594//@ts-check
6595/** @typedef { import('estree').Node} Node */
6596/** @typedef {Node | {
6597 * type: 'PropertyDefinition';
6598 * computed: boolean;
6599 * value: Node
6600 * }} NodeWithPropertyDefinition */
6601
6602/**
6603 *
6604 * @param {NodeWithPropertyDefinition} node
6605 * @param {NodeWithPropertyDefinition} parent
6606 * @returns boolean
6607 */
6608function is_reference (node, parent) {
6609 if (node.type === 'MemberExpression') {
6610 return !node.computed && is_reference(node.object, node);
6611 }
6612
6613 if (node.type === 'Identifier') {
6614 if (!parent) return true;
6615
6616 switch (parent.type) {
6617 // disregard `bar` in `foo.bar`
6618 case 'MemberExpression': return parent.computed || node === parent.object;
6619
6620 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
6621 case 'MethodDefinition': return parent.computed;
6622
6623 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
6624 case 'PropertyDefinition': return parent.computed || node === parent.value;
6625
6626 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6627 case 'Property': return parent.computed || node === parent.value;
6628
6629 // disregard the `bar` in `export { foo as bar }` or
6630 // the foo in `import { foo as bar }`
6631 case 'ExportSpecifier':
6632 case 'ImportSpecifier': return node === parent.local;
6633
6634 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
6635 case 'LabeledStatement':
6636 case 'BreakStatement':
6637 case 'ContinueStatement': return false;
6638 default: return true;
6639 }
6640 }
6641
6642 return false;
6643}
6644
6645/* eslint sort-keys: "off" */
6646const ValueProperties = Symbol('Value Properties');
6647const PURE = {
6648 hasEffectsWhenCalled() {
6649 return false;
6650 }
6651};
6652const IMPURE = {
6653 hasEffectsWhenCalled() {
6654 return true;
6655 }
6656};
6657// We use shortened variables to reduce file size here
6658/* OBJECT */
6659const O = {
6660 __proto__: null,
6661 [ValueProperties]: IMPURE
6662};
6663/* PURE FUNCTION */
6664const PF = {
6665 __proto__: null,
6666 [ValueProperties]: PURE
6667};
6668/* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
6669const MUTATES_ARG_WITHOUT_ACCESSOR = {
6670 __proto__: null,
6671 [ValueProperties]: {
6672 hasEffectsWhenCalled({ args }, context) {
6673 return (!args.length ||
6674 args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
6675 }
6676 }
6677};
6678/* CONSTRUCTOR */
6679const C = {
6680 __proto__: null,
6681 [ValueProperties]: IMPURE,
6682 prototype: O
6683};
6684/* PURE CONSTRUCTOR */
6685const PC = {
6686 __proto__: null,
6687 [ValueProperties]: PURE,
6688 prototype: O
6689};
6690const ARRAY_TYPE = {
6691 __proto__: null,
6692 [ValueProperties]: PURE,
6693 from: PF,
6694 of: PF,
6695 prototype: O
6696};
6697const INTL_MEMBER = {
6698 __proto__: null,
6699 [ValueProperties]: PURE,
6700 supportedLocalesOf: PC
6701};
6702const knownGlobals = {
6703 // Placeholders for global objects to avoid shape mutations
6704 global: O,
6705 globalThis: O,
6706 self: O,
6707 window: O,
6708 // Common globals
6709 __proto__: null,
6710 [ValueProperties]: IMPURE,
6711 Array: {
6712 __proto__: null,
6713 [ValueProperties]: IMPURE,
6714 from: O,
6715 isArray: PF,
6716 of: PF,
6717 prototype: O
6718 },
6719 ArrayBuffer: {
6720 __proto__: null,
6721 [ValueProperties]: PURE,
6722 isView: PF,
6723 prototype: O
6724 },
6725 Atomics: O,
6726 BigInt: C,
6727 BigInt64Array: C,
6728 BigUint64Array: C,
6729 Boolean: PC,
6730 constructor: C,
6731 DataView: PC,
6732 Date: {
6733 __proto__: null,
6734 [ValueProperties]: PURE,
6735 now: PF,
6736 parse: PF,
6737 prototype: O,
6738 UTC: PF
6739 },
6740 decodeURI: PF,
6741 decodeURIComponent: PF,
6742 encodeURI: PF,
6743 encodeURIComponent: PF,
6744 Error: PC,
6745 escape: PF,
6746 eval: O,
6747 EvalError: PC,
6748 Float32Array: ARRAY_TYPE,
6749 Float64Array: ARRAY_TYPE,
6750 Function: C,
6751 hasOwnProperty: O,
6752 Infinity: O,
6753 Int16Array: ARRAY_TYPE,
6754 Int32Array: ARRAY_TYPE,
6755 Int8Array: ARRAY_TYPE,
6756 isFinite: PF,
6757 isNaN: PF,
6758 isPrototypeOf: O,
6759 JSON: O,
6760 Map: PC,
6761 Math: {
6762 __proto__: null,
6763 [ValueProperties]: IMPURE,
6764 abs: PF,
6765 acos: PF,
6766 acosh: PF,
6767 asin: PF,
6768 asinh: PF,
6769 atan: PF,
6770 atan2: PF,
6771 atanh: PF,
6772 cbrt: PF,
6773 ceil: PF,
6774 clz32: PF,
6775 cos: PF,
6776 cosh: PF,
6777 exp: PF,
6778 expm1: PF,
6779 floor: PF,
6780 fround: PF,
6781 hypot: PF,
6782 imul: PF,
6783 log: PF,
6784 log10: PF,
6785 log1p: PF,
6786 log2: PF,
6787 max: PF,
6788 min: PF,
6789 pow: PF,
6790 random: PF,
6791 round: PF,
6792 sign: PF,
6793 sin: PF,
6794 sinh: PF,
6795 sqrt: PF,
6796 tan: PF,
6797 tanh: PF,
6798 trunc: PF
6799 },
6800 NaN: O,
6801 Number: {
6802 __proto__: null,
6803 [ValueProperties]: PURE,
6804 isFinite: PF,
6805 isInteger: PF,
6806 isNaN: PF,
6807 isSafeInteger: PF,
6808 parseFloat: PF,
6809 parseInt: PF,
6810 prototype: O
6811 },
6812 Object: {
6813 __proto__: null,
6814 [ValueProperties]: PURE,
6815 create: PF,
6816 // Technically those can throw in certain situations, but we ignore this as
6817 // code that relies on this will hopefully wrap this in a try-catch, which
6818 // deoptimizes everything anyway
6819 defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
6820 defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
6821 getOwnPropertyDescriptor: PF,
6822 getOwnPropertyNames: PF,
6823 getOwnPropertySymbols: PF,
6824 getPrototypeOf: PF,
6825 hasOwn: PF,
6826 is: PF,
6827 isExtensible: PF,
6828 isFrozen: PF,
6829 isSealed: PF,
6830 keys: PF,
6831 fromEntries: PF,
6832 entries: PF,
6833 prototype: O
6834 },
6835 parseFloat: PF,
6836 parseInt: PF,
6837 Promise: {
6838 __proto__: null,
6839 [ValueProperties]: IMPURE,
6840 all: O,
6841 prototype: O,
6842 race: O,
6843 reject: O,
6844 resolve: O
6845 },
6846 propertyIsEnumerable: O,
6847 Proxy: O,
6848 RangeError: PC,
6849 ReferenceError: PC,
6850 Reflect: O,
6851 RegExp: PC,
6852 Set: PC,
6853 SharedArrayBuffer: C,
6854 String: {
6855 __proto__: null,
6856 [ValueProperties]: PURE,
6857 fromCharCode: PF,
6858 fromCodePoint: PF,
6859 prototype: O,
6860 raw: PF
6861 },
6862 Symbol: {
6863 __proto__: null,
6864 [ValueProperties]: PURE,
6865 for: PF,
6866 keyFor: PF,
6867 prototype: O
6868 },
6869 SyntaxError: PC,
6870 toLocaleString: O,
6871 toString: O,
6872 TypeError: PC,
6873 Uint16Array: ARRAY_TYPE,
6874 Uint32Array: ARRAY_TYPE,
6875 Uint8Array: ARRAY_TYPE,
6876 Uint8ClampedArray: ARRAY_TYPE,
6877 // Technically, this is a global, but it needs special handling
6878 // undefined: ?,
6879 unescape: PF,
6880 URIError: PC,
6881 valueOf: O,
6882 WeakMap: PC,
6883 WeakSet: PC,
6884 // Additional globals shared by Node and Browser that are not strictly part of the language
6885 clearInterval: C,
6886 clearTimeout: C,
6887 console: O,
6888 Intl: {
6889 __proto__: null,
6890 [ValueProperties]: IMPURE,
6891 Collator: INTL_MEMBER,
6892 DateTimeFormat: INTL_MEMBER,
6893 ListFormat: INTL_MEMBER,
6894 NumberFormat: INTL_MEMBER,
6895 PluralRules: INTL_MEMBER,
6896 RelativeTimeFormat: INTL_MEMBER
6897 },
6898 setInterval: C,
6899 setTimeout: C,
6900 TextDecoder: C,
6901 TextEncoder: C,
6902 URL: C,
6903 URLSearchParams: C,
6904 // Browser specific globals
6905 AbortController: C,
6906 AbortSignal: C,
6907 addEventListener: O,
6908 alert: O,
6909 AnalyserNode: C,
6910 Animation: C,
6911 AnimationEvent: C,
6912 applicationCache: O,
6913 ApplicationCache: C,
6914 ApplicationCacheErrorEvent: C,
6915 atob: O,
6916 Attr: C,
6917 Audio: C,
6918 AudioBuffer: C,
6919 AudioBufferSourceNode: C,
6920 AudioContext: C,
6921 AudioDestinationNode: C,
6922 AudioListener: C,
6923 AudioNode: C,
6924 AudioParam: C,
6925 AudioProcessingEvent: C,
6926 AudioScheduledSourceNode: C,
6927 AudioWorkletNode: C,
6928 BarProp: C,
6929 BaseAudioContext: C,
6930 BatteryManager: C,
6931 BeforeUnloadEvent: C,
6932 BiquadFilterNode: C,
6933 Blob: C,
6934 BlobEvent: C,
6935 blur: O,
6936 BroadcastChannel: C,
6937 btoa: O,
6938 ByteLengthQueuingStrategy: C,
6939 Cache: C,
6940 caches: O,
6941 CacheStorage: C,
6942 cancelAnimationFrame: O,
6943 cancelIdleCallback: O,
6944 CanvasCaptureMediaStreamTrack: C,
6945 CanvasGradient: C,
6946 CanvasPattern: C,
6947 CanvasRenderingContext2D: C,
6948 ChannelMergerNode: C,
6949 ChannelSplitterNode: C,
6950 CharacterData: C,
6951 clientInformation: O,
6952 ClipboardEvent: C,
6953 close: O,
6954 closed: O,
6955 CloseEvent: C,
6956 Comment: C,
6957 CompositionEvent: C,
6958 confirm: O,
6959 ConstantSourceNode: C,
6960 ConvolverNode: C,
6961 CountQueuingStrategy: C,
6962 createImageBitmap: O,
6963 Credential: C,
6964 CredentialsContainer: C,
6965 crypto: O,
6966 Crypto: C,
6967 CryptoKey: C,
6968 CSS: C,
6969 CSSConditionRule: C,
6970 CSSFontFaceRule: C,
6971 CSSGroupingRule: C,
6972 CSSImportRule: C,
6973 CSSKeyframeRule: C,
6974 CSSKeyframesRule: C,
6975 CSSMediaRule: C,
6976 CSSNamespaceRule: C,
6977 CSSPageRule: C,
6978 CSSRule: C,
6979 CSSRuleList: C,
6980 CSSStyleDeclaration: C,
6981 CSSStyleRule: C,
6982 CSSStyleSheet: C,
6983 CSSSupportsRule: C,
6984 CustomElementRegistry: C,
6985 customElements: O,
6986 CustomEvent: C,
6987 DataTransfer: C,
6988 DataTransferItem: C,
6989 DataTransferItemList: C,
6990 defaultstatus: O,
6991 defaultStatus: O,
6992 DelayNode: C,
6993 DeviceMotionEvent: C,
6994 DeviceOrientationEvent: C,
6995 devicePixelRatio: O,
6996 dispatchEvent: O,
6997 document: O,
6998 Document: C,
6999 DocumentFragment: C,
7000 DocumentType: C,
7001 DOMError: C,
7002 DOMException: C,
7003 DOMImplementation: C,
7004 DOMMatrix: C,
7005 DOMMatrixReadOnly: C,
7006 DOMParser: C,
7007 DOMPoint: C,
7008 DOMPointReadOnly: C,
7009 DOMQuad: C,
7010 DOMRect: C,
7011 DOMRectReadOnly: C,
7012 DOMStringList: C,
7013 DOMStringMap: C,
7014 DOMTokenList: C,
7015 DragEvent: C,
7016 DynamicsCompressorNode: C,
7017 Element: C,
7018 ErrorEvent: C,
7019 Event: C,
7020 EventSource: C,
7021 EventTarget: C,
7022 external: O,
7023 fetch: O,
7024 File: C,
7025 FileList: C,
7026 FileReader: C,
7027 find: O,
7028 focus: O,
7029 FocusEvent: C,
7030 FontFace: C,
7031 FontFaceSetLoadEvent: C,
7032 FormData: C,
7033 frames: O,
7034 GainNode: C,
7035 Gamepad: C,
7036 GamepadButton: C,
7037 GamepadEvent: C,
7038 getComputedStyle: O,
7039 getSelection: O,
7040 HashChangeEvent: C,
7041 Headers: C,
7042 history: O,
7043 History: C,
7044 HTMLAllCollection: C,
7045 HTMLAnchorElement: C,
7046 HTMLAreaElement: C,
7047 HTMLAudioElement: C,
7048 HTMLBaseElement: C,
7049 HTMLBodyElement: C,
7050 HTMLBRElement: C,
7051 HTMLButtonElement: C,
7052 HTMLCanvasElement: C,
7053 HTMLCollection: C,
7054 HTMLContentElement: C,
7055 HTMLDataElement: C,
7056 HTMLDataListElement: C,
7057 HTMLDetailsElement: C,
7058 HTMLDialogElement: C,
7059 HTMLDirectoryElement: C,
7060 HTMLDivElement: C,
7061 HTMLDListElement: C,
7062 HTMLDocument: C,
7063 HTMLElement: C,
7064 HTMLEmbedElement: C,
7065 HTMLFieldSetElement: C,
7066 HTMLFontElement: C,
7067 HTMLFormControlsCollection: C,
7068 HTMLFormElement: C,
7069 HTMLFrameElement: C,
7070 HTMLFrameSetElement: C,
7071 HTMLHeadElement: C,
7072 HTMLHeadingElement: C,
7073 HTMLHRElement: C,
7074 HTMLHtmlElement: C,
7075 HTMLIFrameElement: C,
7076 HTMLImageElement: C,
7077 HTMLInputElement: C,
7078 HTMLLabelElement: C,
7079 HTMLLegendElement: C,
7080 HTMLLIElement: C,
7081 HTMLLinkElement: C,
7082 HTMLMapElement: C,
7083 HTMLMarqueeElement: C,
7084 HTMLMediaElement: C,
7085 HTMLMenuElement: C,
7086 HTMLMetaElement: C,
7087 HTMLMeterElement: C,
7088 HTMLModElement: C,
7089 HTMLObjectElement: C,
7090 HTMLOListElement: C,
7091 HTMLOptGroupElement: C,
7092 HTMLOptionElement: C,
7093 HTMLOptionsCollection: C,
7094 HTMLOutputElement: C,
7095 HTMLParagraphElement: C,
7096 HTMLParamElement: C,
7097 HTMLPictureElement: C,
7098 HTMLPreElement: C,
7099 HTMLProgressElement: C,
7100 HTMLQuoteElement: C,
7101 HTMLScriptElement: C,
7102 HTMLSelectElement: C,
7103 HTMLShadowElement: C,
7104 HTMLSlotElement: C,
7105 HTMLSourceElement: C,
7106 HTMLSpanElement: C,
7107 HTMLStyleElement: C,
7108 HTMLTableCaptionElement: C,
7109 HTMLTableCellElement: C,
7110 HTMLTableColElement: C,
7111 HTMLTableElement: C,
7112 HTMLTableRowElement: C,
7113 HTMLTableSectionElement: C,
7114 HTMLTemplateElement: C,
7115 HTMLTextAreaElement: C,
7116 HTMLTimeElement: C,
7117 HTMLTitleElement: C,
7118 HTMLTrackElement: C,
7119 HTMLUListElement: C,
7120 HTMLUnknownElement: C,
7121 HTMLVideoElement: C,
7122 IDBCursor: C,
7123 IDBCursorWithValue: C,
7124 IDBDatabase: C,
7125 IDBFactory: C,
7126 IDBIndex: C,
7127 IDBKeyRange: C,
7128 IDBObjectStore: C,
7129 IDBOpenDBRequest: C,
7130 IDBRequest: C,
7131 IDBTransaction: C,
7132 IDBVersionChangeEvent: C,
7133 IdleDeadline: C,
7134 IIRFilterNode: C,
7135 Image: C,
7136 ImageBitmap: C,
7137 ImageBitmapRenderingContext: C,
7138 ImageCapture: C,
7139 ImageData: C,
7140 indexedDB: O,
7141 innerHeight: O,
7142 innerWidth: O,
7143 InputEvent: C,
7144 IntersectionObserver: C,
7145 IntersectionObserverEntry: C,
7146 isSecureContext: O,
7147 KeyboardEvent: C,
7148 KeyframeEffect: C,
7149 length: O,
7150 localStorage: O,
7151 location: O,
7152 Location: C,
7153 locationbar: O,
7154 matchMedia: O,
7155 MediaDeviceInfo: C,
7156 MediaDevices: C,
7157 MediaElementAudioSourceNode: C,
7158 MediaEncryptedEvent: C,
7159 MediaError: C,
7160 MediaKeyMessageEvent: C,
7161 MediaKeySession: C,
7162 MediaKeyStatusMap: C,
7163 MediaKeySystemAccess: C,
7164 MediaList: C,
7165 MediaQueryList: C,
7166 MediaQueryListEvent: C,
7167 MediaRecorder: C,
7168 MediaSettingsRange: C,
7169 MediaSource: C,
7170 MediaStream: C,
7171 MediaStreamAudioDestinationNode: C,
7172 MediaStreamAudioSourceNode: C,
7173 MediaStreamEvent: C,
7174 MediaStreamTrack: C,
7175 MediaStreamTrackEvent: C,
7176 menubar: O,
7177 MessageChannel: C,
7178 MessageEvent: C,
7179 MessagePort: C,
7180 MIDIAccess: C,
7181 MIDIConnectionEvent: C,
7182 MIDIInput: C,
7183 MIDIInputMap: C,
7184 MIDIMessageEvent: C,
7185 MIDIOutput: C,
7186 MIDIOutputMap: C,
7187 MIDIPort: C,
7188 MimeType: C,
7189 MimeTypeArray: C,
7190 MouseEvent: C,
7191 moveBy: O,
7192 moveTo: O,
7193 MutationEvent: C,
7194 MutationObserver: C,
7195 MutationRecord: C,
7196 name: O,
7197 NamedNodeMap: C,
7198 NavigationPreloadManager: C,
7199 navigator: O,
7200 Navigator: C,
7201 NetworkInformation: C,
7202 Node: C,
7203 NodeFilter: O,
7204 NodeIterator: C,
7205 NodeList: C,
7206 Notification: C,
7207 OfflineAudioCompletionEvent: C,
7208 OfflineAudioContext: C,
7209 offscreenBuffering: O,
7210 OffscreenCanvas: C,
7211 open: O,
7212 openDatabase: O,
7213 Option: C,
7214 origin: O,
7215 OscillatorNode: C,
7216 outerHeight: O,
7217 outerWidth: O,
7218 PageTransitionEvent: C,
7219 pageXOffset: O,
7220 pageYOffset: O,
7221 PannerNode: C,
7222 parent: O,
7223 Path2D: C,
7224 PaymentAddress: C,
7225 PaymentRequest: C,
7226 PaymentRequestUpdateEvent: C,
7227 PaymentResponse: C,
7228 performance: O,
7229 Performance: C,
7230 PerformanceEntry: C,
7231 PerformanceLongTaskTiming: C,
7232 PerformanceMark: C,
7233 PerformanceMeasure: C,
7234 PerformanceNavigation: C,
7235 PerformanceNavigationTiming: C,
7236 PerformanceObserver: C,
7237 PerformanceObserverEntryList: C,
7238 PerformancePaintTiming: C,
7239 PerformanceResourceTiming: C,
7240 PerformanceTiming: C,
7241 PeriodicWave: C,
7242 Permissions: C,
7243 PermissionStatus: C,
7244 personalbar: O,
7245 PhotoCapabilities: C,
7246 Plugin: C,
7247 PluginArray: C,
7248 PointerEvent: C,
7249 PopStateEvent: C,
7250 postMessage: O,
7251 Presentation: C,
7252 PresentationAvailability: C,
7253 PresentationConnection: C,
7254 PresentationConnectionAvailableEvent: C,
7255 PresentationConnectionCloseEvent: C,
7256 PresentationConnectionList: C,
7257 PresentationReceiver: C,
7258 PresentationRequest: C,
7259 print: O,
7260 ProcessingInstruction: C,
7261 ProgressEvent: C,
7262 PromiseRejectionEvent: C,
7263 prompt: O,
7264 PushManager: C,
7265 PushSubscription: C,
7266 PushSubscriptionOptions: C,
7267 queueMicrotask: O,
7268 RadioNodeList: C,
7269 Range: C,
7270 ReadableStream: C,
7271 RemotePlayback: C,
7272 removeEventListener: O,
7273 Request: C,
7274 requestAnimationFrame: O,
7275 requestIdleCallback: O,
7276 resizeBy: O,
7277 ResizeObserver: C,
7278 ResizeObserverEntry: C,
7279 resizeTo: O,
7280 Response: C,
7281 RTCCertificate: C,
7282 RTCDataChannel: C,
7283 RTCDataChannelEvent: C,
7284 RTCDtlsTransport: C,
7285 RTCIceCandidate: C,
7286 RTCIceTransport: C,
7287 RTCPeerConnection: C,
7288 RTCPeerConnectionIceEvent: C,
7289 RTCRtpReceiver: C,
7290 RTCRtpSender: C,
7291 RTCSctpTransport: C,
7292 RTCSessionDescription: C,
7293 RTCStatsReport: C,
7294 RTCTrackEvent: C,
7295 screen: O,
7296 Screen: C,
7297 screenLeft: O,
7298 ScreenOrientation: C,
7299 screenTop: O,
7300 screenX: O,
7301 screenY: O,
7302 ScriptProcessorNode: C,
7303 scroll: O,
7304 scrollbars: O,
7305 scrollBy: O,
7306 scrollTo: O,
7307 scrollX: O,
7308 scrollY: O,
7309 SecurityPolicyViolationEvent: C,
7310 Selection: C,
7311 ServiceWorker: C,
7312 ServiceWorkerContainer: C,
7313 ServiceWorkerRegistration: C,
7314 sessionStorage: O,
7315 ShadowRoot: C,
7316 SharedWorker: C,
7317 SourceBuffer: C,
7318 SourceBufferList: C,
7319 speechSynthesis: O,
7320 SpeechSynthesisEvent: C,
7321 SpeechSynthesisUtterance: C,
7322 StaticRange: C,
7323 status: O,
7324 statusbar: O,
7325 StereoPannerNode: C,
7326 stop: O,
7327 Storage: C,
7328 StorageEvent: C,
7329 StorageManager: C,
7330 styleMedia: O,
7331 StyleSheet: C,
7332 StyleSheetList: C,
7333 SubtleCrypto: C,
7334 SVGAElement: C,
7335 SVGAngle: C,
7336 SVGAnimatedAngle: C,
7337 SVGAnimatedBoolean: C,
7338 SVGAnimatedEnumeration: C,
7339 SVGAnimatedInteger: C,
7340 SVGAnimatedLength: C,
7341 SVGAnimatedLengthList: C,
7342 SVGAnimatedNumber: C,
7343 SVGAnimatedNumberList: C,
7344 SVGAnimatedPreserveAspectRatio: C,
7345 SVGAnimatedRect: C,
7346 SVGAnimatedString: C,
7347 SVGAnimatedTransformList: C,
7348 SVGAnimateElement: C,
7349 SVGAnimateMotionElement: C,
7350 SVGAnimateTransformElement: C,
7351 SVGAnimationElement: C,
7352 SVGCircleElement: C,
7353 SVGClipPathElement: C,
7354 SVGComponentTransferFunctionElement: C,
7355 SVGDefsElement: C,
7356 SVGDescElement: C,
7357 SVGDiscardElement: C,
7358 SVGElement: C,
7359 SVGEllipseElement: C,
7360 SVGFEBlendElement: C,
7361 SVGFEColorMatrixElement: C,
7362 SVGFEComponentTransferElement: C,
7363 SVGFECompositeElement: C,
7364 SVGFEConvolveMatrixElement: C,
7365 SVGFEDiffuseLightingElement: C,
7366 SVGFEDisplacementMapElement: C,
7367 SVGFEDistantLightElement: C,
7368 SVGFEDropShadowElement: C,
7369 SVGFEFloodElement: C,
7370 SVGFEFuncAElement: C,
7371 SVGFEFuncBElement: C,
7372 SVGFEFuncGElement: C,
7373 SVGFEFuncRElement: C,
7374 SVGFEGaussianBlurElement: C,
7375 SVGFEImageElement: C,
7376 SVGFEMergeElement: C,
7377 SVGFEMergeNodeElement: C,
7378 SVGFEMorphologyElement: C,
7379 SVGFEOffsetElement: C,
7380 SVGFEPointLightElement: C,
7381 SVGFESpecularLightingElement: C,
7382 SVGFESpotLightElement: C,
7383 SVGFETileElement: C,
7384 SVGFETurbulenceElement: C,
7385 SVGFilterElement: C,
7386 SVGForeignObjectElement: C,
7387 SVGGElement: C,
7388 SVGGeometryElement: C,
7389 SVGGradientElement: C,
7390 SVGGraphicsElement: C,
7391 SVGImageElement: C,
7392 SVGLength: C,
7393 SVGLengthList: C,
7394 SVGLinearGradientElement: C,
7395 SVGLineElement: C,
7396 SVGMarkerElement: C,
7397 SVGMaskElement: C,
7398 SVGMatrix: C,
7399 SVGMetadataElement: C,
7400 SVGMPathElement: C,
7401 SVGNumber: C,
7402 SVGNumberList: C,
7403 SVGPathElement: C,
7404 SVGPatternElement: C,
7405 SVGPoint: C,
7406 SVGPointList: C,
7407 SVGPolygonElement: C,
7408 SVGPolylineElement: C,
7409 SVGPreserveAspectRatio: C,
7410 SVGRadialGradientElement: C,
7411 SVGRect: C,
7412 SVGRectElement: C,
7413 SVGScriptElement: C,
7414 SVGSetElement: C,
7415 SVGStopElement: C,
7416 SVGStringList: C,
7417 SVGStyleElement: C,
7418 SVGSVGElement: C,
7419 SVGSwitchElement: C,
7420 SVGSymbolElement: C,
7421 SVGTextContentElement: C,
7422 SVGTextElement: C,
7423 SVGTextPathElement: C,
7424 SVGTextPositioningElement: C,
7425 SVGTitleElement: C,
7426 SVGTransform: C,
7427 SVGTransformList: C,
7428 SVGTSpanElement: C,
7429 SVGUnitTypes: C,
7430 SVGUseElement: C,
7431 SVGViewElement: C,
7432 TaskAttributionTiming: C,
7433 Text: C,
7434 TextEvent: C,
7435 TextMetrics: C,
7436 TextTrack: C,
7437 TextTrackCue: C,
7438 TextTrackCueList: C,
7439 TextTrackList: C,
7440 TimeRanges: C,
7441 toolbar: O,
7442 top: O,
7443 Touch: C,
7444 TouchEvent: C,
7445 TouchList: C,
7446 TrackEvent: C,
7447 TransitionEvent: C,
7448 TreeWalker: C,
7449 UIEvent: C,
7450 ValidityState: C,
7451 visualViewport: O,
7452 VisualViewport: C,
7453 VTTCue: C,
7454 WaveShaperNode: C,
7455 WebAssembly: O,
7456 WebGL2RenderingContext: C,
7457 WebGLActiveInfo: C,
7458 WebGLBuffer: C,
7459 WebGLContextEvent: C,
7460 WebGLFramebuffer: C,
7461 WebGLProgram: C,
7462 WebGLQuery: C,
7463 WebGLRenderbuffer: C,
7464 WebGLRenderingContext: C,
7465 WebGLSampler: C,
7466 WebGLShader: C,
7467 WebGLShaderPrecisionFormat: C,
7468 WebGLSync: C,
7469 WebGLTexture: C,
7470 WebGLTransformFeedback: C,
7471 WebGLUniformLocation: C,
7472 WebGLVertexArrayObject: C,
7473 WebSocket: C,
7474 WheelEvent: C,
7475 Window: C,
7476 Worker: C,
7477 WritableStream: C,
7478 XMLDocument: C,
7479 XMLHttpRequest: C,
7480 XMLHttpRequestEventTarget: C,
7481 XMLHttpRequestUpload: C,
7482 XMLSerializer: C,
7483 XPathEvaluator: C,
7484 XPathExpression: C,
7485 XPathResult: C,
7486 XSLTProcessor: C
7487};
7488for (const global of ['window', 'global', 'self', 'globalThis']) {
7489 knownGlobals[global] = knownGlobals;
7490}
7491function getGlobalAtPath(path) {
7492 let currentGlobal = knownGlobals;
7493 for (const pathSegment of path) {
7494 if (typeof pathSegment !== 'string') {
7495 return null;
7496 }
7497 currentGlobal = currentGlobal[pathSegment];
7498 if (!currentGlobal) {
7499 return null;
7500 }
7501 }
7502 return currentGlobal[ValueProperties];
7503}
7504
7505class GlobalVariable extends Variable {
7506 constructor() {
7507 super(...arguments);
7508 // Ensure we use live-bindings for globals as we do not know if they have
7509 // been reassigned
7510 this.isReassigned = true;
7511 }
7512 getLiteralValueAtPath(path, _recursionTracker, _origin) {
7513 return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
7514 }
7515 hasEffectsOnInteractionAtPath(path, interaction, context) {
7516 switch (interaction.type) {
7517 case INTERACTION_ACCESSED:
7518 if (path.length === 0) {
7519 // Technically, "undefined" is a global variable of sorts
7520 return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
7521 }
7522 return !getGlobalAtPath([this.name, ...path].slice(0, -1));
7523 case INTERACTION_ASSIGNED:
7524 return true;
7525 case INTERACTION_CALLED: {
7526 const globalAtPath = getGlobalAtPath([this.name, ...path]);
7527 return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
7528 }
7529 }
7530 }
7531}
7532
7533const tdzVariableKinds = {
7534 __proto__: null,
7535 class: true,
7536 const: true,
7537 let: true,
7538 var: true
7539};
7540class Identifier extends NodeBase {
7541 constructor() {
7542 super(...arguments);
7543 this.variable = null;
7544 this.isTDZAccess = null;
7545 }
7546 addExportedVariables(variables, exportNamesByVariable) {
7547 if (exportNamesByVariable.has(this.variable)) {
7548 variables.push(this.variable);
7549 }
7550 }
7551 bind() {
7552 if (!this.variable && is_reference(this, this.parent)) {
7553 this.variable = this.scope.findVariable(this.name);
7554 this.variable.addReference(this);
7555 }
7556 }
7557 declare(kind, init) {
7558 let variable;
7559 const { treeshake } = this.context.options;
7560 switch (kind) {
7561 case 'var':
7562 variable = this.scope.addDeclaration(this, this.context, init, true);
7563 if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
7564 // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
7565 variable.markInitializersForDeoptimization();
7566 }
7567 break;
7568 case 'function':
7569 // in strict mode, functions are only hoisted within a scope but not across block scopes
7570 variable = this.scope.addDeclaration(this, this.context, init, false);
7571 break;
7572 case 'let':
7573 case 'const':
7574 case 'class':
7575 variable = this.scope.addDeclaration(this, this.context, init, false);
7576 break;
7577 case 'parameter':
7578 variable = this.scope.addParameterDeclaration(this);
7579 break;
7580 /* istanbul ignore next */
7581 default:
7582 /* istanbul ignore next */
7583 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
7584 }
7585 variable.kind = kind;
7586 return [(this.variable = variable)];
7587 }
7588 deoptimizePath(path) {
7589 var _a;
7590 if (path.length === 0 && !this.scope.contains(this.name)) {
7591 this.disallowImportReassignment();
7592 }
7593 // We keep conditional chaining because an unknown Node could have an
7594 // Identifier as property that might be deoptimized by default
7595 (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
7596 }
7597 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
7598 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
7599 }
7600 getLiteralValueAtPath(path, recursionTracker, origin) {
7601 return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
7602 }
7603 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
7604 return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
7605 }
7606 hasEffects(context) {
7607 if (!this.deoptimized)
7608 this.applyDeoptimizations();
7609 if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
7610 return true;
7611 }
7612 return (this.context.options.treeshake.unknownGlobalSideEffects &&
7613 this.variable instanceof GlobalVariable &&
7614 this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
7615 }
7616 hasEffectsOnInteractionAtPath(path, interaction, context) {
7617 switch (interaction.type) {
7618 case INTERACTION_ACCESSED:
7619 return (this.variable !== null &&
7620 this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
7621 case INTERACTION_ASSIGNED:
7622 return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
7623 case INTERACTION_CALLED:
7624 return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
7625 }
7626 }
7627 include() {
7628 if (!this.deoptimized)
7629 this.applyDeoptimizations();
7630 if (!this.included) {
7631 this.included = true;
7632 if (this.variable !== null) {
7633 this.context.includeVariableInModule(this.variable);
7634 }
7635 }
7636 }
7637 includeCallArguments(context, args) {
7638 this.variable.includeCallArguments(context, args);
7639 }
7640 isPossibleTDZ() {
7641 // return cached value to avoid issues with the next tree-shaking pass
7642 if (this.isTDZAccess !== null)
7643 return this.isTDZAccess;
7644 if (!(this.variable instanceof LocalVariable) ||
7645 !this.variable.kind ||
7646 !(this.variable.kind in tdzVariableKinds)) {
7647 return (this.isTDZAccess = false);
7648 }
7649 let decl_id;
7650 if (this.variable.declarations &&
7651 this.variable.declarations.length === 1 &&
7652 (decl_id = this.variable.declarations[0]) &&
7653 this.start < decl_id.start &&
7654 closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
7655 // a variable accessed before its declaration
7656 // in the same function or at top level of module
7657 return (this.isTDZAccess = true);
7658 }
7659 if (!this.variable.initReached) {
7660 // Either a const/let TDZ violation or
7661 // var use before declaration was encountered.
7662 return (this.isTDZAccess = true);
7663 }
7664 return (this.isTDZAccess = false);
7665 }
7666 markDeclarationReached() {
7667 this.variable.initReached = true;
7668 }
7669 render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
7670 if (this.variable) {
7671 const name = this.variable.getName(getPropertyAccess);
7672 if (name !== this.name) {
7673 code.overwrite(this.start, this.end, name, {
7674 contentOnly: true,
7675 storeName: true
7676 });
7677 if (isShorthandProperty) {
7678 code.prependRight(this.start, `${this.name}: `);
7679 }
7680 }
7681 // In strict mode, any variable named "eval" must be the actual "eval" function
7682 if (name === 'eval' &&
7683 renderedParentType === CallExpression$1 &&
7684 isCalleeOfRenderedParent) {
7685 code.appendRight(this.start, '0, ');
7686 }
7687 }
7688 }
7689 applyDeoptimizations() {
7690 this.deoptimized = true;
7691 if (this.variable instanceof LocalVariable) {
7692 this.variable.consolidateInitializers();
7693 this.context.requestTreeshakingPass();
7694 }
7695 }
7696 disallowImportReassignment() {
7697 return this.context.error({
7698 code: 'ILLEGAL_REASSIGNMENT',
7699 message: `Illegal reassignment to import '${this.name}'`
7700 }, this.start);
7701 }
7702 getVariableRespectingTDZ() {
7703 if (this.isPossibleTDZ()) {
7704 return UNKNOWN_EXPRESSION;
7705 }
7706 return this.variable;
7707 }
7708}
7709function closestParentFunctionOrProgram(node) {
7710 while (node && !/^Program|Function/.test(node.type)) {
7711 node = node.parent;
7712 }
7713 // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
7714 return node;
7715}
7716
7717function treeshakeNode(node, code, start, end) {
7718 code.remove(start, end);
7719 if (node.annotations) {
7720 for (const annotation of node.annotations) {
7721 if (annotation.start < start) {
7722 code.remove(annotation.start, annotation.end);
7723 }
7724 else {
7725 return;
7726 }
7727 }
7728 }
7729}
7730function removeAnnotations(node, code) {
7731 if (!node.annotations && node.parent.type === ExpressionStatement$1) {
7732 node = node.parent;
7733 }
7734 if (node.annotations) {
7735 for (const annotation of node.annotations) {
7736 code.remove(annotation.start, annotation.end);
7737 }
7738 }
7739}
7740
7741const NO_SEMICOLON = { isNoStatement: true };
7742// This assumes there are only white-space and comments between start and the string we are looking for
7743function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
7744 let searchPos, charCodeAfterSlash;
7745 searchPos = code.indexOf(searchString, start);
7746 while (true) {
7747 start = code.indexOf('/', start);
7748 if (start === -1 || start >= searchPos)
7749 return searchPos;
7750 charCodeAfterSlash = code.charCodeAt(++start);
7751 ++start;
7752 // With our assumption, '/' always starts a comment. Determine comment type:
7753 start =
7754 charCodeAfterSlash === 47 /*"/"*/
7755 ? code.indexOf('\n', start) + 1
7756 : code.indexOf('*/', start) + 2;
7757 if (start > searchPos) {
7758 searchPos = code.indexOf(searchString, start);
7759 }
7760 }
7761}
7762const NON_WHITESPACE = /\S/g;
7763function findNonWhiteSpace(code, index) {
7764 NON_WHITESPACE.lastIndex = index;
7765 const result = NON_WHITESPACE.exec(code);
7766 return result.index;
7767}
7768// This assumes "code" only contains white-space and comments
7769// Returns position of line-comment if applicable
7770function findFirstLineBreakOutsideComment(code) {
7771 let lineBreakPos, charCodeAfterSlash, start = 0;
7772 lineBreakPos = code.indexOf('\n', start);
7773 while (true) {
7774 start = code.indexOf('/', start);
7775 if (start === -1 || start > lineBreakPos)
7776 return [lineBreakPos, lineBreakPos + 1];
7777 // With our assumption, '/' always starts a comment. Determine comment type:
7778 charCodeAfterSlash = code.charCodeAt(start + 1);
7779 if (charCodeAfterSlash === 47 /*"/"*/)
7780 return [start, lineBreakPos + 1];
7781 start = code.indexOf('*/', start + 3) + 2;
7782 if (start > lineBreakPos) {
7783 lineBreakPos = code.indexOf('\n', start);
7784 }
7785 }
7786}
7787function renderStatementList(statements, code, start, end, options) {
7788 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
7789 let nextNode = statements[0];
7790 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
7791 if (nextNodeNeedsBoundaries) {
7792 nextNodeStart =
7793 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
7794 }
7795 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
7796 currentNode = nextNode;
7797 currentNodeStart = nextNodeStart;
7798 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
7799 nextNode = statements[nextIndex];
7800 nextNodeNeedsBoundaries =
7801 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
7802 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
7803 nextNodeStart =
7804 currentNode.end +
7805 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
7806 if (currentNode.included) {
7807 currentNodeNeedsBoundaries
7808 ? currentNode.render(code, options, {
7809 end: nextNodeStart,
7810 start: currentNodeStart
7811 })
7812 : currentNode.render(code, options);
7813 }
7814 else {
7815 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
7816 }
7817 }
7818 else {
7819 currentNode.render(code, options);
7820 }
7821 }
7822}
7823// This assumes that the first character is not part of the first node
7824function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
7825 const splitUpNodes = [];
7826 let node, nextNode, nextNodeStart, contentEnd, char;
7827 let separator = start - 1;
7828 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
7829 nextNode = nodes[nextIndex];
7830 if (node !== undefined) {
7831 separator =
7832 node.end +
7833 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
7834 }
7835 nextNodeStart = contentEnd =
7836 separator +
7837 1 +
7838 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
7839 while (((char = code.original.charCodeAt(nextNodeStart)),
7840 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
7841 nextNodeStart++;
7842 if (node !== undefined) {
7843 splitUpNodes.push({
7844 contentEnd,
7845 end: nextNodeStart,
7846 node,
7847 separator,
7848 start
7849 });
7850 }
7851 node = nextNode;
7852 start = nextNodeStart;
7853 }
7854 splitUpNodes.push({
7855 contentEnd: end,
7856 end,
7857 node: node,
7858 separator: null,
7859 start
7860 });
7861 return splitUpNodes;
7862}
7863// This assumes there are only white-space and comments between start and end
7864function removeLineBreaks(code, start, end) {
7865 while (true) {
7866 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
7867 if (removeStart === -1) {
7868 break;
7869 }
7870 code.remove(start + removeStart, (start += removeEnd));
7871 }
7872}
7873
7874class BlockScope extends ChildScope {
7875 addDeclaration(identifier, context, init, isHoisted) {
7876 if (isHoisted) {
7877 const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
7878 // Necessary to make sure the init is deoptimized for conditional declarations.
7879 // We cannot call deoptimizePath here.
7880 variable.markInitializersForDeoptimization();
7881 return variable;
7882 }
7883 else {
7884 return super.addDeclaration(identifier, context, init, false);
7885 }
7886 }
7887}
7888
7889class ExpressionStatement extends NodeBase {
7890 initialise() {
7891 if (this.directive &&
7892 this.directive !== 'use strict' &&
7893 this.parent.type === Program$1) {
7894 this.context.warn(
7895 // This is necessary, because either way (deleting or not) can lead to errors.
7896 {
7897 code: 'MODULE_LEVEL_DIRECTIVE',
7898 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
7899 }, this.start);
7900 }
7901 }
7902 render(code, options) {
7903 super.render(code, options);
7904 if (this.included)
7905 this.insertSemicolon(code);
7906 }
7907 shouldBeIncluded(context) {
7908 if (this.directive && this.directive !== 'use strict')
7909 return this.parent.type !== Program$1;
7910 return super.shouldBeIncluded(context);
7911 }
7912 applyDeoptimizations() { }
7913}
7914
7915class BlockStatement extends NodeBase {
7916 constructor() {
7917 super(...arguments);
7918 this.directlyIncluded = false;
7919 }
7920 addImplicitReturnExpressionToScope() {
7921 const lastStatement = this.body[this.body.length - 1];
7922 if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
7923 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
7924 }
7925 }
7926 createScope(parentScope) {
7927 this.scope = this.parent.preventChildBlockScope
7928 ? parentScope
7929 : new BlockScope(parentScope);
7930 }
7931 hasEffects(context) {
7932 if (this.deoptimizeBody)
7933 return true;
7934 for (const node of this.body) {
7935 if (context.brokenFlow)
7936 break;
7937 if (node.hasEffects(context))
7938 return true;
7939 }
7940 return false;
7941 }
7942 include(context, includeChildrenRecursively) {
7943 if (!(this.deoptimizeBody && this.directlyIncluded)) {
7944 this.included = true;
7945 this.directlyIncluded = true;
7946 if (this.deoptimizeBody)
7947 includeChildrenRecursively = true;
7948 for (const node of this.body) {
7949 if (includeChildrenRecursively || node.shouldBeIncluded(context))
7950 node.include(context, includeChildrenRecursively);
7951 }
7952 }
7953 }
7954 initialise() {
7955 const firstBodyStatement = this.body[0];
7956 this.deoptimizeBody =
7957 firstBodyStatement instanceof ExpressionStatement &&
7958 firstBodyStatement.directive === 'use asm';
7959 }
7960 render(code, options) {
7961 if (this.body.length) {
7962 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
7963 }
7964 else {
7965 super.render(code, options);
7966 }
7967 }
7968}
7969
7970class RestElement extends NodeBase {
7971 constructor() {
7972 super(...arguments);
7973 this.declarationInit = null;
7974 }
7975 addExportedVariables(variables, exportNamesByVariable) {
7976 this.argument.addExportedVariables(variables, exportNamesByVariable);
7977 }
7978 declare(kind, init) {
7979 this.declarationInit = init;
7980 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
7981 }
7982 deoptimizePath(path) {
7983 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
7984 }
7985 hasEffectsOnInteractionAtPath(path, interaction, context) {
7986 return (path.length > 0 ||
7987 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
7988 }
7989 markDeclarationReached() {
7990 this.argument.markDeclarationReached();
7991 }
7992 applyDeoptimizations() {
7993 this.deoptimized = true;
7994 if (this.declarationInit !== null) {
7995 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
7996 this.context.requestTreeshakingPass();
7997 }
7998 }
7999}
8000
8001class FunctionBase extends NodeBase {
8002 constructor() {
8003 super(...arguments);
8004 this.objectEntity = null;
8005 this.deoptimizedReturn = false;
8006 }
8007 deoptimizePath(path) {
8008 this.getObjectEntity().deoptimizePath(path);
8009 if (path.length === 1 && path[0] === UnknownKey) {
8010 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
8011 // which means the return expression needs to be reassigned
8012 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
8013 }
8014 }
8015 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8016 if (path.length > 0) {
8017 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8018 }
8019 }
8020 getLiteralValueAtPath(path, recursionTracker, origin) {
8021 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
8022 }
8023 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8024 if (path.length > 0) {
8025 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8026 }
8027 if (this.async) {
8028 if (!this.deoptimizedReturn) {
8029 this.deoptimizedReturn = true;
8030 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
8031 this.context.requestTreeshakingPass();
8032 }
8033 return UNKNOWN_EXPRESSION;
8034 }
8035 return this.scope.getReturnExpression();
8036 }
8037 hasEffectsOnInteractionAtPath(path, interaction, context) {
8038 if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
8039 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
8040 }
8041 if (this.async) {
8042 const { propertyReadSideEffects } = this.context.options
8043 .treeshake;
8044 const returnExpression = this.scope.getReturnExpression();
8045 if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
8046 (propertyReadSideEffects &&
8047 (propertyReadSideEffects === 'always' ||
8048 returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
8049 return true;
8050 }
8051 }
8052 for (const param of this.params) {
8053 if (param.hasEffects(context))
8054 return true;
8055 }
8056 return false;
8057 }
8058 include(context, includeChildrenRecursively) {
8059 if (!this.deoptimized)
8060 this.applyDeoptimizations();
8061 this.included = true;
8062 const { brokenFlow } = context;
8063 context.brokenFlow = BROKEN_FLOW_NONE;
8064 this.body.include(context, includeChildrenRecursively);
8065 context.brokenFlow = brokenFlow;
8066 }
8067 includeCallArguments(context, args) {
8068 this.scope.includeCallArguments(context, args);
8069 }
8070 initialise() {
8071 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
8072 if (this.body instanceof BlockStatement) {
8073 this.body.addImplicitReturnExpressionToScope();
8074 }
8075 else {
8076 this.scope.addReturnExpression(this.body);
8077 }
8078 }
8079 parseNode(esTreeNode) {
8080 if (esTreeNode.body.type === BlockStatement$1) {
8081 this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
8082 }
8083 super.parseNode(esTreeNode);
8084 }
8085 applyDeoptimizations() { }
8086}
8087FunctionBase.prototype.preventChildBlockScope = true;
8088
8089class ArrowFunctionExpression extends FunctionBase {
8090 constructor() {
8091 super(...arguments);
8092 this.objectEntity = null;
8093 }
8094 createScope(parentScope) {
8095 this.scope = new ReturnValueScope(parentScope, this.context);
8096 }
8097 hasEffects() {
8098 if (!this.deoptimized)
8099 this.applyDeoptimizations();
8100 return false;
8101 }
8102 hasEffectsOnInteractionAtPath(path, interaction, context) {
8103 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
8104 return true;
8105 if (interaction.type === INTERACTION_CALLED) {
8106 const { ignore, brokenFlow } = context;
8107 context.ignore = {
8108 breaks: false,
8109 continues: false,
8110 labels: new Set(),
8111 returnYield: true
8112 };
8113 if (this.body.hasEffects(context))
8114 return true;
8115 context.ignore = ignore;
8116 context.brokenFlow = brokenFlow;
8117 }
8118 return false;
8119 }
8120 include(context, includeChildrenRecursively) {
8121 super.include(context, includeChildrenRecursively);
8122 for (const param of this.params) {
8123 if (!(param instanceof Identifier)) {
8124 param.include(context, includeChildrenRecursively);
8125 }
8126 }
8127 }
8128 getObjectEntity() {
8129 if (this.objectEntity !== null) {
8130 return this.objectEntity;
8131 }
8132 return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
8133 }
8134}
8135
8136function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
8137 if (exportedVariables.length === 1 &&
8138 exportNamesByVariable.get(exportedVariables[0]).length === 1) {
8139 const variable = exportedVariables[0];
8140 return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
8141 }
8142 else {
8143 const fields = [];
8144 for (const variable of exportedVariables) {
8145 for (const exportName of exportNamesByVariable.get(variable)) {
8146 fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
8147 }
8148 }
8149 return `exports(${getObject(fields, { lineBreakIndent: null })})`;
8150 }
8151}
8152function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
8153 code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
8154 code.appendLeft(expressionEnd, ')');
8155}
8156function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
8157 const { _, getDirectReturnIifeLeft } = options.snippets;
8158 code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
8159 code.appendLeft(expressionEnd, ')');
8160}
8161function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
8162 const { _, getPropertyAccess } = options.snippets;
8163 code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
8164 if (needsParens) {
8165 code.prependRight(expressionStart, '(');
8166 code.appendLeft(expressionEnd, ')');
8167 }
8168}
8169function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
8170 const { _ } = options.snippets;
8171 code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
8172 if (needsParens) {
8173 code.prependRight(expressionStart, '(');
8174 code.appendLeft(expressionEnd, ')');
8175 }
8176}
8177
8178class ObjectPattern extends NodeBase {
8179 addExportedVariables(variables, exportNamesByVariable) {
8180 for (const property of this.properties) {
8181 if (property.type === Property$1) {
8182 property.value.addExportedVariables(variables, exportNamesByVariable);
8183 }
8184 else {
8185 property.argument.addExportedVariables(variables, exportNamesByVariable);
8186 }
8187 }
8188 }
8189 declare(kind, init) {
8190 const variables = [];
8191 for (const property of this.properties) {
8192 variables.push(...property.declare(kind, init));
8193 }
8194 return variables;
8195 }
8196 deoptimizePath(path) {
8197 if (path.length === 0) {
8198 for (const property of this.properties) {
8199 property.deoptimizePath(path);
8200 }
8201 }
8202 }
8203 hasEffectsOnInteractionAtPath(
8204 // At the moment, this is only triggered for assignment left-hand sides,
8205 // where the path is empty
8206 _path, interaction, context) {
8207 for (const property of this.properties) {
8208 if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
8209 return true;
8210 }
8211 return false;
8212 }
8213 markDeclarationReached() {
8214 for (const property of this.properties) {
8215 property.markDeclarationReached();
8216 }
8217 }
8218}
8219
8220class AssignmentExpression extends NodeBase {
8221 hasEffects(context) {
8222 const { deoptimized, left, right } = this;
8223 if (!deoptimized)
8224 this.applyDeoptimizations();
8225 // MemberExpressions do not access the property before assignments if the
8226 // operator is '='.
8227 return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
8228 }
8229 hasEffectsOnInteractionAtPath(path, interaction, context) {
8230 return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
8231 }
8232 include(context, includeChildrenRecursively) {
8233 const { deoptimized, left, right, operator } = this;
8234 if (!deoptimized)
8235 this.applyDeoptimizations();
8236 this.included = true;
8237 if (includeChildrenRecursively ||
8238 operator !== '=' ||
8239 left.included ||
8240 left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
8241 left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
8242 }
8243 right.include(context, includeChildrenRecursively);
8244 }
8245 initialise() {
8246 this.left.setAssignedValue(this.right);
8247 }
8248 render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
8249 const { left, right, start, end, parent } = this;
8250 if (left.included) {
8251 left.render(code, options);
8252 right.render(code, options);
8253 }
8254 else {
8255 const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
8256 code.remove(start, inclusionStart);
8257 if (preventASI) {
8258 removeLineBreaks(code, inclusionStart, right.start);
8259 }
8260 right.render(code, options, {
8261 renderedParentType: renderedParentType || parent.type,
8262 renderedSurroundingElement: renderedSurroundingElement || parent.type
8263 });
8264 }
8265 if (options.format === 'system') {
8266 if (left instanceof Identifier) {
8267 const variable = left.variable;
8268 const exportNames = options.exportNamesByVariable.get(variable);
8269 if (exportNames) {
8270 if (exportNames.length === 1) {
8271 renderSystemExportExpression(variable, start, end, code, options);
8272 }
8273 else {
8274 renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
8275 }
8276 return;
8277 }
8278 }
8279 else {
8280 const systemPatternExports = [];
8281 left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
8282 if (systemPatternExports.length > 0) {
8283 renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
8284 return;
8285 }
8286 }
8287 }
8288 if (left.included &&
8289 left instanceof ObjectPattern &&
8290 (renderedSurroundingElement === ExpressionStatement$1 ||
8291 renderedSurroundingElement === ArrowFunctionExpression$1)) {
8292 code.appendRight(start, '(');
8293 code.prependLeft(end, ')');
8294 }
8295 }
8296 applyDeoptimizations() {
8297 this.deoptimized = true;
8298 this.left.deoptimizePath(EMPTY_PATH);
8299 this.right.deoptimizePath(UNKNOWN_PATH);
8300 this.context.requestTreeshakingPass();
8301 }
8302}
8303
8304class AssignmentPattern extends NodeBase {
8305 addExportedVariables(variables, exportNamesByVariable) {
8306 this.left.addExportedVariables(variables, exportNamesByVariable);
8307 }
8308 declare(kind, init) {
8309 return this.left.declare(kind, init);
8310 }
8311 deoptimizePath(path) {
8312 path.length === 0 && this.left.deoptimizePath(path);
8313 }
8314 hasEffectsOnInteractionAtPath(path, interaction, context) {
8315 return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
8316 }
8317 markDeclarationReached() {
8318 this.left.markDeclarationReached();
8319 }
8320 render(code, options, { isShorthandProperty } = BLANK) {
8321 this.left.render(code, options, { isShorthandProperty });
8322 this.right.render(code, options);
8323 }
8324 applyDeoptimizations() {
8325 this.deoptimized = true;
8326 this.left.deoptimizePath(EMPTY_PATH);
8327 this.right.deoptimizePath(UNKNOWN_PATH);
8328 this.context.requestTreeshakingPass();
8329 }
8330}
8331
8332class ArgumentsVariable extends LocalVariable {
8333 constructor(context) {
8334 super('arguments', null, UNKNOWN_EXPRESSION, context);
8335 }
8336 hasEffectsOnInteractionAtPath(path, { type }) {
8337 return type !== INTERACTION_ACCESSED || path.length > 1;
8338 }
8339}
8340
8341class ThisVariable extends LocalVariable {
8342 constructor(context) {
8343 super('this', null, null, context);
8344 this.deoptimizedPaths = [];
8345 this.entitiesToBeDeoptimized = new Set();
8346 this.thisDeoptimizationList = [];
8347 this.thisDeoptimizations = new DiscriminatedPathTracker();
8348 }
8349 addEntityToBeDeoptimized(entity) {
8350 for (const path of this.deoptimizedPaths) {
8351 entity.deoptimizePath(path);
8352 }
8353 for (const { interaction, path } of this.thisDeoptimizationList) {
8354 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8355 }
8356 this.entitiesToBeDeoptimized.add(entity);
8357 }
8358 deoptimizePath(path) {
8359 if (path.length === 0 ||
8360 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
8361 return;
8362 }
8363 this.deoptimizedPaths.push(path);
8364 for (const entity of this.entitiesToBeDeoptimized) {
8365 entity.deoptimizePath(path);
8366 }
8367 }
8368 deoptimizeThisOnInteractionAtPath(interaction, path) {
8369 const thisDeoptimization = {
8370 interaction,
8371 path
8372 };
8373 if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
8374 for (const entity of this.entitiesToBeDeoptimized) {
8375 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8376 }
8377 this.thisDeoptimizationList.push(thisDeoptimization);
8378 }
8379 }
8380 hasEffectsOnInteractionAtPath(path, interaction, context) {
8381 return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
8382 super.hasEffectsOnInteractionAtPath(path, interaction, context));
8383 }
8384 getInit(context) {
8385 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
8386 }
8387}
8388
8389class FunctionScope extends ReturnValueScope {
8390 constructor(parent, context) {
8391 super(parent, context);
8392 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
8393 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
8394 }
8395 findLexicalBoundary() {
8396 return this;
8397 }
8398 includeCallArguments(context, args) {
8399 super.includeCallArguments(context, args);
8400 if (this.argumentsVariable.included) {
8401 for (const arg of args) {
8402 if (!arg.included) {
8403 arg.include(context, false);
8404 }
8405 }
8406 }
8407 }
8408}
8409
8410class FunctionNode extends FunctionBase {
8411 constructor() {
8412 super(...arguments);
8413 this.objectEntity = null;
8414 }
8415 createScope(parentScope) {
8416 this.scope = new FunctionScope(parentScope, this.context);
8417 }
8418 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8419 super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8420 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
8421 this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
8422 }
8423 }
8424 hasEffects(context) {
8425 var _a;
8426 if (!this.deoptimized)
8427 this.applyDeoptimizations();
8428 return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
8429 }
8430 hasEffectsOnInteractionAtPath(path, interaction, context) {
8431 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
8432 return true;
8433 if (interaction.type === INTERACTION_CALLED) {
8434 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
8435 context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
8436 ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
8437 : UNKNOWN_EXPRESSION);
8438 const { brokenFlow, ignore } = context;
8439 context.ignore = {
8440 breaks: false,
8441 continues: false,
8442 labels: new Set(),
8443 returnYield: true
8444 };
8445 if (this.body.hasEffects(context))
8446 return true;
8447 context.brokenFlow = brokenFlow;
8448 if (thisInit) {
8449 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
8450 }
8451 else {
8452 context.replacedVariableInits.delete(this.scope.thisVariable);
8453 }
8454 context.ignore = ignore;
8455 }
8456 return false;
8457 }
8458 include(context, includeChildrenRecursively) {
8459 var _a;
8460 super.include(context, includeChildrenRecursively);
8461 (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
8462 const hasArguments = this.scope.argumentsVariable.included;
8463 for (const param of this.params) {
8464 if (!(param instanceof Identifier) || hasArguments) {
8465 param.include(context, includeChildrenRecursively);
8466 }
8467 }
8468 }
8469 initialise() {
8470 var _a;
8471 super.initialise();
8472 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
8473 }
8474 getObjectEntity() {
8475 if (this.objectEntity !== null) {
8476 return this.objectEntity;
8477 }
8478 return (this.objectEntity = new ObjectEntity([
8479 {
8480 key: 'prototype',
8481 kind: 'init',
8482 property: new ObjectEntity([], OBJECT_PROTOTYPE)
8483 }
8484 ], OBJECT_PROTOTYPE));
8485 }
8486}
8487
8488class AwaitExpression extends NodeBase {
8489 hasEffects() {
8490 if (!this.deoptimized)
8491 this.applyDeoptimizations();
8492 return true;
8493 }
8494 include(context, includeChildrenRecursively) {
8495 if (!this.deoptimized)
8496 this.applyDeoptimizations();
8497 if (!this.included) {
8498 this.included = true;
8499 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
8500 let parent = this.parent;
8501 do {
8502 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
8503 break checkTopLevelAwait;
8504 } while ((parent = parent.parent));
8505 this.context.usesTopLevelAwait = true;
8506 }
8507 }
8508 this.argument.include(context, includeChildrenRecursively);
8509 }
8510}
8511
8512const binaryOperators = {
8513 '!=': (left, right) => left != right,
8514 '!==': (left, right) => left !== right,
8515 '%': (left, right) => left % right,
8516 '&': (left, right) => left & right,
8517 '*': (left, right) => left * right,
8518 // At the moment, "**" will be transpiled to Math.pow
8519 '**': (left, right) => left ** right,
8520 '+': (left, right) => left + right,
8521 '-': (left, right) => left - right,
8522 '/': (left, right) => left / right,
8523 '<': (left, right) => left < right,
8524 '<<': (left, right) => left << right,
8525 '<=': (left, right) => left <= right,
8526 '==': (left, right) => left == right,
8527 '===': (left, right) => left === right,
8528 '>': (left, right) => left > right,
8529 '>=': (left, right) => left >= right,
8530 '>>': (left, right) => left >> right,
8531 '>>>': (left, right) => left >>> right,
8532 '^': (left, right) => left ^ right,
8533 '|': (left, right) => left | right
8534 // We use the fallback for cases where we return something unknown
8535 // in: () => UnknownValue,
8536 // instanceof: () => UnknownValue,
8537};
8538class BinaryExpression extends NodeBase {
8539 deoptimizeCache() { }
8540 getLiteralValueAtPath(path, recursionTracker, origin) {
8541 if (path.length > 0)
8542 return UnknownValue;
8543 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8544 if (typeof leftValue === 'symbol')
8545 return UnknownValue;
8546 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8547 if (typeof rightValue === 'symbol')
8548 return UnknownValue;
8549 const operatorFn = binaryOperators[this.operator];
8550 if (!operatorFn)
8551 return UnknownValue;
8552 return operatorFn(leftValue, rightValue);
8553 }
8554 hasEffects(context) {
8555 // support some implicit type coercion runtime errors
8556 if (this.operator === '+' &&
8557 this.parent instanceof ExpressionStatement &&
8558 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
8559 return true;
8560 }
8561 return super.hasEffects(context);
8562 }
8563 hasEffectsOnInteractionAtPath(path, { type }) {
8564 return type !== INTERACTION_ACCESSED || path.length > 1;
8565 }
8566 render(code, options, { renderedSurroundingElement } = BLANK) {
8567 this.left.render(code, options, { renderedSurroundingElement });
8568 this.right.render(code, options);
8569 }
8570}
8571
8572class BreakStatement extends NodeBase {
8573 hasEffects(context) {
8574 if (this.label) {
8575 if (!context.ignore.labels.has(this.label.name))
8576 return true;
8577 context.includedLabels.add(this.label.name);
8578 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8579 }
8580 else {
8581 if (!context.ignore.breaks)
8582 return true;
8583 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
8584 }
8585 return false;
8586 }
8587 include(context) {
8588 this.included = true;
8589 if (this.label) {
8590 this.label.include();
8591 context.includedLabels.add(this.label.name);
8592 }
8593 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
8594 }
8595}
8596
8597function renderCallArguments(code, options, node) {
8598 if (node.arguments.length > 0) {
8599 if (node.arguments[node.arguments.length - 1].included) {
8600 for (const arg of node.arguments) {
8601 arg.render(code, options);
8602 }
8603 }
8604 else {
8605 let lastIncludedIndex = node.arguments.length - 2;
8606 while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
8607 lastIncludedIndex--;
8608 }
8609 if (lastIncludedIndex >= 0) {
8610 for (let index = 0; index <= lastIncludedIndex; index++) {
8611 node.arguments[index].render(code, options);
8612 }
8613 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
8614 }
8615 else {
8616 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
8617 }
8618 }
8619 }
8620}
8621
8622class Literal extends NodeBase {
8623 deoptimizeThisOnInteractionAtPath() { }
8624 getLiteralValueAtPath(path) {
8625 if (path.length > 0 ||
8626 // unknown literals can also be null but do not start with an "n"
8627 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
8628 typeof this.value === 'bigint' ||
8629 // to support shims for regular expressions
8630 this.context.code.charCodeAt(this.start) === 47) {
8631 return UnknownValue;
8632 }
8633 return this.value;
8634 }
8635 getReturnExpressionWhenCalledAtPath(path) {
8636 if (path.length !== 1)
8637 return UNKNOWN_EXPRESSION;
8638 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
8639 }
8640 hasEffectsOnInteractionAtPath(path, interaction, context) {
8641 switch (interaction.type) {
8642 case INTERACTION_ACCESSED:
8643 return path.length > (this.value === null ? 0 : 1);
8644 case INTERACTION_ASSIGNED:
8645 return true;
8646 case INTERACTION_CALLED:
8647 return (path.length !== 1 ||
8648 hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
8649 }
8650 }
8651 initialise() {
8652 this.members = getLiteralMembersForValue(this.value);
8653 }
8654 parseNode(esTreeNode) {
8655 this.value = esTreeNode.value;
8656 this.regex = esTreeNode.regex;
8657 super.parseNode(esTreeNode);
8658 }
8659 render(code) {
8660 if (typeof this.value === 'string') {
8661 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
8662 }
8663 }
8664}
8665
8666// To avoid infinite recursions
8667const MAX_PATH_DEPTH = 7;
8668function getResolvablePropertyKey(memberExpression) {
8669 return memberExpression.computed
8670 ? getResolvableComputedPropertyKey(memberExpression.property)
8671 : memberExpression.property.name;
8672}
8673function getResolvableComputedPropertyKey(propertyKey) {
8674 if (propertyKey instanceof Literal) {
8675 return String(propertyKey.value);
8676 }
8677 return null;
8678}
8679function getPathIfNotComputed(memberExpression) {
8680 const nextPathKey = memberExpression.propertyKey;
8681 const object = memberExpression.object;
8682 if (typeof nextPathKey === 'string') {
8683 if (object instanceof Identifier) {
8684 return [
8685 { key: object.name, pos: object.start },
8686 { key: nextPathKey, pos: memberExpression.property.start }
8687 ];
8688 }
8689 if (object instanceof MemberExpression) {
8690 const parentPath = getPathIfNotComputed(object);
8691 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
8692 }
8693 }
8694 return null;
8695}
8696function getStringFromPath(path) {
8697 let pathString = path[0].key;
8698 for (let index = 1; index < path.length; index++) {
8699 pathString += '.' + path[index].key;
8700 }
8701 return pathString;
8702}
8703class MemberExpression extends NodeBase {
8704 constructor() {
8705 super(...arguments);
8706 this.variable = null;
8707 this.assignmentDeoptimized = false;
8708 this.bound = false;
8709 this.expressionsToBeDeoptimized = [];
8710 this.replacement = null;
8711 }
8712 bind() {
8713 this.bound = true;
8714 const path = getPathIfNotComputed(this);
8715 const baseVariable = path && this.scope.findVariable(path[0].key);
8716 if (baseVariable && baseVariable.isNamespace) {
8717 const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
8718 if (!resolvedVariable) {
8719 super.bind();
8720 }
8721 else if (typeof resolvedVariable === 'string') {
8722 this.replacement = resolvedVariable;
8723 }
8724 else {
8725 this.variable = resolvedVariable;
8726 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
8727 }
8728 }
8729 else {
8730 super.bind();
8731 }
8732 }
8733 deoptimizeCache() {
8734 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
8735 this.expressionsToBeDeoptimized = [];
8736 this.propertyKey = UnknownKey;
8737 this.object.deoptimizePath(UNKNOWN_PATH);
8738 for (const expression of expressionsToBeDeoptimized) {
8739 expression.deoptimizeCache();
8740 }
8741 }
8742 deoptimizePath(path) {
8743 if (path.length === 0)
8744 this.disallowNamespaceReassignment();
8745 if (this.variable) {
8746 this.variable.deoptimizePath(path);
8747 }
8748 else if (!this.replacement) {
8749 if (path.length < MAX_PATH_DEPTH) {
8750 const propertyKey = this.getPropertyKey();
8751 this.object.deoptimizePath([
8752 propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
8753 ...path
8754 ]);
8755 }
8756 }
8757 }
8758 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8759 if (this.variable) {
8760 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8761 }
8762 else if (!this.replacement) {
8763 if (path.length < MAX_PATH_DEPTH) {
8764 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
8765 }
8766 else {
8767 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
8768 }
8769 }
8770 }
8771 getLiteralValueAtPath(path, recursionTracker, origin) {
8772 if (this.variable) {
8773 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
8774 }
8775 if (this.replacement) {
8776 return UnknownValue;
8777 }
8778 this.expressionsToBeDeoptimized.push(origin);
8779 if (path.length < MAX_PATH_DEPTH) {
8780 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
8781 }
8782 return UnknownValue;
8783 }
8784 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8785 if (this.variable) {
8786 return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8787 }
8788 if (this.replacement) {
8789 return UNKNOWN_EXPRESSION;
8790 }
8791 this.expressionsToBeDeoptimized.push(origin);
8792 if (path.length < MAX_PATH_DEPTH) {
8793 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
8794 }
8795 return UNKNOWN_EXPRESSION;
8796 }
8797 hasEffects(context) {
8798 if (!this.deoptimized)
8799 this.applyDeoptimizations();
8800 return (this.property.hasEffects(context) ||
8801 this.object.hasEffects(context) ||
8802 this.hasAccessEffect(context));
8803 }
8804 hasEffectsAsAssignmentTarget(context, checkAccess) {
8805 if (checkAccess && !this.deoptimized)
8806 this.applyDeoptimizations();
8807 if (!this.assignmentDeoptimized)
8808 this.applyAssignmentDeoptimization();
8809 return (this.property.hasEffects(context) ||
8810 this.object.hasEffects(context) ||
8811 (checkAccess && this.hasAccessEffect(context)) ||
8812 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
8813 }
8814 hasEffectsOnInteractionAtPath(path, interaction, context) {
8815 if (this.variable) {
8816 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
8817 }
8818 if (this.replacement) {
8819 return true;
8820 }
8821 if (path.length < MAX_PATH_DEPTH) {
8822 return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
8823 }
8824 return true;
8825 }
8826 include(context, includeChildrenRecursively) {
8827 if (!this.deoptimized)
8828 this.applyDeoptimizations();
8829 this.includeProperties(context, includeChildrenRecursively);
8830 }
8831 includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
8832 if (!this.assignmentDeoptimized)
8833 this.applyAssignmentDeoptimization();
8834 if (deoptimizeAccess) {
8835 this.include(context, includeChildrenRecursively);
8836 }
8837 else {
8838 this.includeProperties(context, includeChildrenRecursively);
8839 }
8840 }
8841 includeCallArguments(context, args) {
8842 if (this.variable) {
8843 this.variable.includeCallArguments(context, args);
8844 }
8845 else {
8846 super.includeCallArguments(context, args);
8847 }
8848 }
8849 initialise() {
8850 this.propertyKey = getResolvablePropertyKey(this);
8851 this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
8852 }
8853 render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
8854 if (this.variable || this.replacement) {
8855 const { snippets: { getPropertyAccess } } = options;
8856 let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
8857 if (renderedParentType && isCalleeOfRenderedParent)
8858 replacement = '0, ' + replacement;
8859 code.overwrite(this.start, this.end, replacement, {
8860 contentOnly: true,
8861 storeName: true
8862 });
8863 }
8864 else {
8865 if (renderedParentType && isCalleeOfRenderedParent) {
8866 code.appendRight(this.start, '0, ');
8867 }
8868 this.object.render(code, options, { renderedSurroundingElement });
8869 this.property.render(code, options);
8870 }
8871 }
8872 setAssignedValue(value) {
8873 this.assignmentInteraction = {
8874 args: [value],
8875 thisArg: this.object,
8876 type: INTERACTION_ASSIGNED
8877 };
8878 }
8879 applyDeoptimizations() {
8880 this.deoptimized = true;
8881 const { propertyReadSideEffects } = this.context.options
8882 .treeshake;
8883 if (
8884 // Namespaces are not bound and should not be deoptimized
8885 this.bound &&
8886 propertyReadSideEffects &&
8887 !(this.variable || this.replacement)) {
8888 const propertyKey = this.getPropertyKey();
8889 this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
8890 this.context.requestTreeshakingPass();
8891 }
8892 }
8893 applyAssignmentDeoptimization() {
8894 this.assignmentDeoptimized = true;
8895 const { propertyReadSideEffects } = this.context.options
8896 .treeshake;
8897 if (
8898 // Namespaces are not bound and should not be deoptimized
8899 this.bound &&
8900 propertyReadSideEffects &&
8901 !(this.variable || this.replacement)) {
8902 this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
8903 this.context.requestTreeshakingPass();
8904 }
8905 }
8906 disallowNamespaceReassignment() {
8907 if (this.object instanceof Identifier) {
8908 const variable = this.scope.findVariable(this.object.name);
8909 if (variable.isNamespace) {
8910 if (this.variable) {
8911 this.context.includeVariableInModule(this.variable);
8912 }
8913 this.context.warn({
8914 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
8915 message: `Illegal reassignment to import '${this.object.name}'`
8916 }, this.start);
8917 }
8918 }
8919 }
8920 getPropertyKey() {
8921 if (this.propertyKey === null) {
8922 this.propertyKey = UnknownKey;
8923 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8924 return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
8925 }
8926 return this.propertyKey;
8927 }
8928 hasAccessEffect(context) {
8929 const { propertyReadSideEffects } = this.context.options
8930 .treeshake;
8931 return (!(this.variable || this.replacement) &&
8932 propertyReadSideEffects &&
8933 (propertyReadSideEffects === 'always' ||
8934 this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
8935 }
8936 includeProperties(context, includeChildrenRecursively) {
8937 if (!this.included) {
8938 this.included = true;
8939 if (this.variable) {
8940 this.context.includeVariableInModule(this.variable);
8941 }
8942 }
8943 this.object.include(context, includeChildrenRecursively);
8944 this.property.include(context, includeChildrenRecursively);
8945 }
8946}
8947function resolveNamespaceVariables(baseVariable, path, astContext) {
8948 if (path.length === 0)
8949 return baseVariable;
8950 if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
8951 return null;
8952 const exportName = path[0].key;
8953 const variable = baseVariable.context.traceExport(exportName);
8954 if (!variable) {
8955 const fileName = baseVariable.context.fileName;
8956 astContext.warn({
8957 code: 'MISSING_EXPORT',
8958 exporter: relativeId(fileName),
8959 importer: relativeId(astContext.fileName),
8960 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
8961 missing: exportName,
8962 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
8963 }, path[0].pos);
8964 return 'undefined';
8965 }
8966 return resolveNamespaceVariables(variable, path.slice(1), astContext);
8967}
8968
8969class CallExpressionBase extends NodeBase {
8970 constructor() {
8971 super(...arguments);
8972 this.returnExpression = null;
8973 this.deoptimizableDependentExpressions = [];
8974 this.expressionsToBeDeoptimized = new Set();
8975 }
8976 deoptimizeCache() {
8977 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
8978 this.returnExpression = UNKNOWN_EXPRESSION;
8979 for (const expression of this.deoptimizableDependentExpressions) {
8980 expression.deoptimizeCache();
8981 }
8982 for (const expression of this.expressionsToBeDeoptimized) {
8983 expression.deoptimizePath(UNKNOWN_PATH);
8984 }
8985 }
8986 }
8987 deoptimizePath(path) {
8988 if (path.length === 0 ||
8989 this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
8990 return;
8991 }
8992 const returnExpression = this.getReturnExpression();
8993 if (returnExpression !== UNKNOWN_EXPRESSION) {
8994 returnExpression.deoptimizePath(path);
8995 }
8996 }
8997 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8998 const returnExpression = this.getReturnExpression(recursionTracker);
8999 if (returnExpression === UNKNOWN_EXPRESSION) {
9000 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
9001 }
9002 else {
9003 recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9004 this.expressionsToBeDeoptimized.add(interaction.thisArg);
9005 returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9006 }, undefined);
9007 }
9008 }
9009 getLiteralValueAtPath(path, recursionTracker, origin) {
9010 const returnExpression = this.getReturnExpression(recursionTracker);
9011 if (returnExpression === UNKNOWN_EXPRESSION) {
9012 return UnknownValue;
9013 }
9014 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9015 this.deoptimizableDependentExpressions.push(origin);
9016 return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
9017 }, UnknownValue);
9018 }
9019 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9020 const returnExpression = this.getReturnExpression(recursionTracker);
9021 if (this.returnExpression === UNKNOWN_EXPRESSION) {
9022 return UNKNOWN_EXPRESSION;
9023 }
9024 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9025 this.deoptimizableDependentExpressions.push(origin);
9026 return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9027 }, UNKNOWN_EXPRESSION);
9028 }
9029 hasEffectsOnInteractionAtPath(path, interaction, context) {
9030 const { type } = interaction;
9031 if (type === INTERACTION_CALLED) {
9032 if ((interaction.withNew
9033 ? context.instantiated
9034 : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
9035 return false;
9036 }
9037 }
9038 else if ((type === INTERACTION_ASSIGNED
9039 ? context.assigned
9040 : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
9041 return false;
9042 }
9043 return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
9044 }
9045}
9046
9047class CallExpression extends CallExpressionBase {
9048 bind() {
9049 super.bind();
9050 if (this.callee instanceof Identifier) {
9051 const variable = this.scope.findVariable(this.callee.name);
9052 if (variable.isNamespace) {
9053 this.context.warn({
9054 code: 'CANNOT_CALL_NAMESPACE',
9055 message: `Cannot call a namespace ('${this.callee.name}')`
9056 }, this.start);
9057 }
9058 if (this.callee.name === 'eval') {
9059 this.context.warn({
9060 code: 'EVAL',
9061 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
9062 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
9063 }, this.start);
9064 }
9065 }
9066 this.interaction = {
9067 args: this.arguments,
9068 thisArg: this.callee instanceof MemberExpression && !this.callee.variable
9069 ? this.callee.object
9070 : null,
9071 type: INTERACTION_CALLED,
9072 withNew: false
9073 };
9074 }
9075 hasEffects(context) {
9076 try {
9077 for (const argument of this.arguments) {
9078 if (argument.hasEffects(context))
9079 return true;
9080 }
9081 if (this.context.options.treeshake.annotations &&
9082 this.annotations)
9083 return false;
9084 return (this.callee.hasEffects(context) ||
9085 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
9086 }
9087 finally {
9088 if (!this.deoptimized)
9089 this.applyDeoptimizations();
9090 }
9091 }
9092 include(context, includeChildrenRecursively) {
9093 if (!this.deoptimized)
9094 this.applyDeoptimizations();
9095 if (includeChildrenRecursively) {
9096 super.include(context, includeChildrenRecursively);
9097 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
9098 this.callee instanceof Identifier &&
9099 this.callee.variable) {
9100 this.callee.variable.markCalledFromTryStatement();
9101 }
9102 }
9103 else {
9104 this.included = true;
9105 this.callee.include(context, false);
9106 }
9107 this.callee.includeCallArguments(context, this.arguments);
9108 const returnExpression = this.getReturnExpression();
9109 if (!returnExpression.included) {
9110 returnExpression.include(context, false);
9111 }
9112 }
9113 render(code, options, { renderedSurroundingElement } = BLANK) {
9114 this.callee.render(code, options, {
9115 isCalleeOfRenderedParent: true,
9116 renderedSurroundingElement
9117 });
9118 renderCallArguments(code, options, this);
9119 }
9120 applyDeoptimizations() {
9121 this.deoptimized = true;
9122 if (this.interaction.thisArg) {
9123 this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
9124 }
9125 for (const argument of this.arguments) {
9126 // This will make sure all properties of parameters behave as "unknown"
9127 argument.deoptimizePath(UNKNOWN_PATH);
9128 }
9129 this.context.requestTreeshakingPass();
9130 }
9131 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
9132 if (this.returnExpression === null) {
9133 this.returnExpression = UNKNOWN_EXPRESSION;
9134 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
9135 }
9136 return this.returnExpression;
9137 }
9138}
9139
9140class CatchScope extends ParameterScope {
9141 addDeclaration(identifier, context, init, isHoisted) {
9142 const existingParameter = this.variables.get(identifier.name);
9143 if (existingParameter) {
9144 // While we still create a hoisted declaration, the initializer goes to
9145 // the parameter. Note that technically, the declaration now belongs to
9146 // two variables, which is not correct but should not cause issues.
9147 this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
9148 existingParameter.addDeclaration(identifier, init);
9149 return existingParameter;
9150 }
9151 return this.parent.addDeclaration(identifier, context, init, isHoisted);
9152 }
9153}
9154
9155class CatchClause extends NodeBase {
9156 createScope(parentScope) {
9157 this.scope = new CatchScope(parentScope, this.context);
9158 }
9159 parseNode(esTreeNode) {
9160 // Parameters need to be declared first as the logic is that initializers
9161 // of hoisted body variables are associated with parameters of the same
9162 // name instead of the variable
9163 const { param } = esTreeNode;
9164 if (param) {
9165 this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
9166 this.param.declare('parameter', UNKNOWN_EXPRESSION);
9167 }
9168 super.parseNode(esTreeNode);
9169 }
9170}
9171
9172class ChainExpression extends NodeBase {
9173}
9174
9175class ClassBodyScope extends ChildScope {
9176 constructor(parent, classNode, context) {
9177 super(parent);
9178 this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
9179 this.instanceScope = new ChildScope(this);
9180 this.instanceScope.variables.set('this', new ThisVariable(context));
9181 }
9182 findLexicalBoundary() {
9183 return this;
9184 }
9185}
9186
9187class ClassBody extends NodeBase {
9188 createScope(parentScope) {
9189 this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
9190 }
9191 include(context, includeChildrenRecursively) {
9192 this.included = true;
9193 this.context.includeVariableInModule(this.scope.thisVariable);
9194 for (const definition of this.body) {
9195 definition.include(context, includeChildrenRecursively);
9196 }
9197 }
9198 parseNode(esTreeNode) {
9199 const body = (this.body = []);
9200 for (const definition of esTreeNode.body) {
9201 body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
9202 }
9203 super.parseNode(esTreeNode);
9204 }
9205 applyDeoptimizations() { }
9206}
9207
9208class MethodBase extends NodeBase {
9209 constructor() {
9210 super(...arguments);
9211 this.accessedValue = null;
9212 }
9213 // As getter properties directly receive their values from fixed function
9214 // expressions, there is no known situation where a getter is deoptimized.
9215 deoptimizeCache() { }
9216 deoptimizePath(path) {
9217 this.getAccessedValue().deoptimizePath(path);
9218 }
9219 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9220 if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
9221 return this.value.deoptimizeThisOnInteractionAtPath({
9222 args: NO_ARGS,
9223 thisArg: interaction.thisArg,
9224 type: INTERACTION_CALLED,
9225 withNew: false
9226 }, EMPTY_PATH, recursionTracker);
9227 }
9228 if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
9229 return this.value.deoptimizeThisOnInteractionAtPath({
9230 args: interaction.args,
9231 thisArg: interaction.thisArg,
9232 type: INTERACTION_CALLED,
9233 withNew: false
9234 }, EMPTY_PATH, recursionTracker);
9235 }
9236 this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9237 }
9238 getLiteralValueAtPath(path, recursionTracker, origin) {
9239 return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
9240 }
9241 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9242 return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9243 }
9244 hasEffects(context) {
9245 return this.key.hasEffects(context);
9246 }
9247 hasEffectsOnInteractionAtPath(path, interaction, context) {
9248 if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
9249 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9250 args: NO_ARGS,
9251 thisArg: interaction.thisArg,
9252 type: INTERACTION_CALLED,
9253 withNew: false
9254 }, context);
9255 }
9256 // setters are only called for empty paths
9257 if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
9258 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9259 args: interaction.args,
9260 thisArg: interaction.thisArg,
9261 type: INTERACTION_CALLED,
9262 withNew: false
9263 }, context);
9264 }
9265 return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
9266 }
9267 applyDeoptimizations() { }
9268 getAccessedValue() {
9269 if (this.accessedValue === null) {
9270 if (this.kind === 'get') {
9271 this.accessedValue = UNKNOWN_EXPRESSION;
9272 return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
9273 }
9274 else {
9275 return (this.accessedValue = this.value);
9276 }
9277 }
9278 return this.accessedValue;
9279 }
9280}
9281
9282class MethodDefinition extends MethodBase {
9283 applyDeoptimizations() { }
9284}
9285
9286class ObjectMember extends ExpressionEntity {
9287 constructor(object, key) {
9288 super();
9289 this.object = object;
9290 this.key = key;
9291 }
9292 deoptimizePath(path) {
9293 this.object.deoptimizePath([this.key, ...path]);
9294 }
9295 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9296 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
9297 }
9298 getLiteralValueAtPath(path, recursionTracker, origin) {
9299 return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
9300 }
9301 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9302 return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
9303 }
9304 hasEffectsOnInteractionAtPath(path, interaction, context) {
9305 return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
9306 }
9307}
9308
9309class ClassNode extends NodeBase {
9310 constructor() {
9311 super(...arguments);
9312 this.objectEntity = null;
9313 }
9314 createScope(parentScope) {
9315 this.scope = new ChildScope(parentScope);
9316 }
9317 deoptimizeCache() {
9318 this.getObjectEntity().deoptimizeAllProperties();
9319 }
9320 deoptimizePath(path) {
9321 this.getObjectEntity().deoptimizePath(path);
9322 }
9323 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9324 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9325 }
9326 getLiteralValueAtPath(path, recursionTracker, origin) {
9327 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
9328 }
9329 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9330 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9331 }
9332 hasEffects(context) {
9333 var _a, _b;
9334 if (!this.deoptimized)
9335 this.applyDeoptimizations();
9336 const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
9337 (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
9338 return initEffect || super.hasEffects(context);
9339 }
9340 hasEffectsOnInteractionAtPath(path, interaction, context) {
9341 var _a;
9342 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
9343 return (!interaction.withNew ||
9344 (this.classConstructor !== null
9345 ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
9346 : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
9347 false);
9348 }
9349 else {
9350 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
9351 }
9352 }
9353 include(context, includeChildrenRecursively) {
9354 var _a;
9355 if (!this.deoptimized)
9356 this.applyDeoptimizations();
9357 this.included = true;
9358 (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
9359 this.body.include(context, includeChildrenRecursively);
9360 if (this.id) {
9361 this.id.markDeclarationReached();
9362 this.id.include();
9363 }
9364 }
9365 initialise() {
9366 var _a;
9367 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
9368 for (const method of this.body.body) {
9369 if (method instanceof MethodDefinition && method.kind === 'constructor') {
9370 this.classConstructor = method;
9371 return;
9372 }
9373 }
9374 this.classConstructor = null;
9375 }
9376 applyDeoptimizations() {
9377 this.deoptimized = true;
9378 for (const definition of this.body.body) {
9379 if (!(definition.static ||
9380 (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
9381 // Calls to methods are not tracked, ensure that the return value is deoptimized
9382 definition.deoptimizePath(UNKNOWN_PATH);
9383 }
9384 }
9385 this.context.requestTreeshakingPass();
9386 }
9387 getObjectEntity() {
9388 if (this.objectEntity !== null) {
9389 return this.objectEntity;
9390 }
9391 const staticProperties = [];
9392 const dynamicMethods = [];
9393 for (const definition of this.body.body) {
9394 const properties = definition.static ? staticProperties : dynamicMethods;
9395 const definitionKind = definition.kind;
9396 // Note that class fields do not end up on the prototype
9397 if (properties === dynamicMethods && !definitionKind)
9398 continue;
9399 const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
9400 let key;
9401 if (definition.computed) {
9402 const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9403 if (typeof keyValue === 'symbol') {
9404 properties.push({ key: UnknownKey, kind, property: definition });
9405 continue;
9406 }
9407 else {
9408 key = String(keyValue);
9409 }
9410 }
9411 else {
9412 key =
9413 definition.key instanceof Identifier
9414 ? definition.key.name
9415 : String(definition.key.value);
9416 }
9417 properties.push({ key, kind, property: definition });
9418 }
9419 staticProperties.unshift({
9420 key: 'prototype',
9421 kind: 'init',
9422 property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
9423 });
9424 return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
9425 }
9426}
9427
9428class ClassDeclaration extends ClassNode {
9429 initialise() {
9430 super.initialise();
9431 if (this.id !== null) {
9432 this.id.variable.isId = true;
9433 }
9434 }
9435 parseNode(esTreeNode) {
9436 if (esTreeNode.id !== null) {
9437 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9438 }
9439 super.parseNode(esTreeNode);
9440 }
9441 render(code, options) {
9442 const { exportNamesByVariable, format, snippets: { _ } } = options;
9443 if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
9444 code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
9445 }
9446 super.render(code, options);
9447 }
9448}
9449
9450class ClassExpression extends ClassNode {
9451 render(code, options, { renderedSurroundingElement } = BLANK) {
9452 super.render(code, options);
9453 if (renderedSurroundingElement === ExpressionStatement$1) {
9454 code.appendRight(this.start, '(');
9455 code.prependLeft(this.end, ')');
9456 }
9457 }
9458}
9459
9460class MultiExpression extends ExpressionEntity {
9461 constructor(expressions) {
9462 super();
9463 this.expressions = expressions;
9464 this.included = false;
9465 }
9466 deoptimizePath(path) {
9467 for (const expression of this.expressions) {
9468 expression.deoptimizePath(path);
9469 }
9470 }
9471 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9472 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
9473 }
9474 hasEffectsOnInteractionAtPath(path, interaction, context) {
9475 for (const expression of this.expressions) {
9476 if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
9477 return true;
9478 }
9479 return false;
9480 }
9481 include(context, includeChildrenRecursively) {
9482 // This is only relevant to include values that do not have an AST representation,
9483 // such as UnknownArrayExpression. Thus we only need to include them once.
9484 for (const expression of this.expressions) {
9485 if (!expression.included) {
9486 expression.include(context, includeChildrenRecursively);
9487 }
9488 }
9489 }
9490}
9491
9492class ConditionalExpression extends NodeBase {
9493 constructor() {
9494 super(...arguments);
9495 this.expressionsToBeDeoptimized = [];
9496 this.isBranchResolutionAnalysed = false;
9497 this.usedBranch = null;
9498 }
9499 deoptimizeCache() {
9500 if (this.usedBranch !== null) {
9501 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
9502 this.usedBranch = null;
9503 unusedBranch.deoptimizePath(UNKNOWN_PATH);
9504 for (const expression of this.expressionsToBeDeoptimized) {
9505 expression.deoptimizeCache();
9506 }
9507 }
9508 }
9509 deoptimizePath(path) {
9510 const usedBranch = this.getUsedBranch();
9511 if (!usedBranch) {
9512 this.consequent.deoptimizePath(path);
9513 this.alternate.deoptimizePath(path);
9514 }
9515 else {
9516 usedBranch.deoptimizePath(path);
9517 }
9518 }
9519 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9520 this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9521 this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9522 }
9523 getLiteralValueAtPath(path, recursionTracker, origin) {
9524 const usedBranch = this.getUsedBranch();
9525 if (!usedBranch)
9526 return UnknownValue;
9527 this.expressionsToBeDeoptimized.push(origin);
9528 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
9529 }
9530 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9531 const usedBranch = this.getUsedBranch();
9532 if (!usedBranch)
9533 return new MultiExpression([
9534 this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
9535 this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
9536 ]);
9537 this.expressionsToBeDeoptimized.push(origin);
9538 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9539 }
9540 hasEffects(context) {
9541 if (this.test.hasEffects(context))
9542 return true;
9543 const usedBranch = this.getUsedBranch();
9544 if (!usedBranch) {
9545 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
9546 }
9547 return usedBranch.hasEffects(context);
9548 }
9549 hasEffectsOnInteractionAtPath(path, interaction, context) {
9550 const usedBranch = this.getUsedBranch();
9551 if (!usedBranch) {
9552 return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
9553 this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
9554 }
9555 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
9556 }
9557 include(context, includeChildrenRecursively) {
9558 this.included = true;
9559 const usedBranch = this.getUsedBranch();
9560 if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
9561 this.test.include(context, includeChildrenRecursively);
9562 this.consequent.include(context, includeChildrenRecursively);
9563 this.alternate.include(context, includeChildrenRecursively);
9564 }
9565 else {
9566 usedBranch.include(context, includeChildrenRecursively);
9567 }
9568 }
9569 includeCallArguments(context, args) {
9570 const usedBranch = this.getUsedBranch();
9571 if (!usedBranch) {
9572 this.consequent.includeCallArguments(context, args);
9573 this.alternate.includeCallArguments(context, args);
9574 }
9575 else {
9576 usedBranch.includeCallArguments(context, args);
9577 }
9578 }
9579 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
9580 const usedBranch = this.getUsedBranch();
9581 if (!this.test.included) {
9582 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
9583 const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
9584 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
9585 : colonPos) + 1);
9586 if (preventASI) {
9587 removeLineBreaks(code, inclusionStart, usedBranch.start);
9588 }
9589 code.remove(this.start, inclusionStart);
9590 if (this.consequent.included) {
9591 code.remove(colonPos, this.end);
9592 }
9593 removeAnnotations(this, code);
9594 usedBranch.render(code, options, {
9595 isCalleeOfRenderedParent,
9596 preventASI: true,
9597 renderedParentType: renderedParentType || this.parent.type,
9598 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
9599 });
9600 }
9601 else {
9602 this.test.render(code, options, { renderedSurroundingElement });
9603 this.consequent.render(code, options);
9604 this.alternate.render(code, options);
9605 }
9606 }
9607 getUsedBranch() {
9608 if (this.isBranchResolutionAnalysed) {
9609 return this.usedBranch;
9610 }
9611 this.isBranchResolutionAnalysed = true;
9612 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9613 return typeof testValue === 'symbol'
9614 ? null
9615 : (this.usedBranch = testValue ? this.consequent : this.alternate);
9616 }
9617}
9618
9619class ContinueStatement extends NodeBase {
9620 hasEffects(context) {
9621 if (this.label) {
9622 if (!context.ignore.labels.has(this.label.name))
9623 return true;
9624 context.includedLabels.add(this.label.name);
9625 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
9626 }
9627 else {
9628 if (!context.ignore.continues)
9629 return true;
9630 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
9631 }
9632 return false;
9633 }
9634 include(context) {
9635 this.included = true;
9636 if (this.label) {
9637 this.label.include();
9638 context.includedLabels.add(this.label.name);
9639 }
9640 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
9641 }
9642}
9643
9644class DoWhileStatement extends NodeBase {
9645 hasEffects(context) {
9646 if (this.test.hasEffects(context))
9647 return true;
9648 const { brokenFlow, ignore: { breaks, continues } } = context;
9649 context.ignore.breaks = true;
9650 context.ignore.continues = true;
9651 if (this.body.hasEffects(context))
9652 return true;
9653 context.ignore.breaks = breaks;
9654 context.ignore.continues = continues;
9655 context.brokenFlow = brokenFlow;
9656 return false;
9657 }
9658 include(context, includeChildrenRecursively) {
9659 this.included = true;
9660 this.test.include(context, includeChildrenRecursively);
9661 const { brokenFlow } = context;
9662 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9663 context.brokenFlow = brokenFlow;
9664 }
9665}
9666
9667class EmptyStatement extends NodeBase {
9668 hasEffects() {
9669 return false;
9670 }
9671}
9672
9673class ExportAllDeclaration extends NodeBase {
9674 hasEffects() {
9675 return false;
9676 }
9677 initialise() {
9678 this.context.addExport(this);
9679 }
9680 render(code, _options, nodeRenderOptions) {
9681 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
9682 }
9683 applyDeoptimizations() { }
9684}
9685ExportAllDeclaration.prototype.needsBoundaries = true;
9686
9687class FunctionDeclaration extends FunctionNode {
9688 initialise() {
9689 super.initialise();
9690 if (this.id !== null) {
9691 this.id.variable.isId = true;
9692 }
9693 }
9694 parseNode(esTreeNode) {
9695 if (esTreeNode.id !== null) {
9696 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9697 }
9698 super.parseNode(esTreeNode);
9699 }
9700}
9701
9702// The header ends at the first non-white-space after "default"
9703function getDeclarationStart(code, start) {
9704 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
9705}
9706function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
9707 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
9708 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
9709 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
9710 if (generatorStarPos === -1) {
9711 return declarationEnd;
9712 }
9713 return declarationEnd + generatorStarPos + 1;
9714}
9715class ExportDefaultDeclaration extends NodeBase {
9716 include(context, includeChildrenRecursively) {
9717 super.include(context, includeChildrenRecursively);
9718 if (includeChildrenRecursively) {
9719 this.context.includeVariableInModule(this.variable);
9720 }
9721 }
9722 initialise() {
9723 const declaration = this.declaration;
9724 this.declarationName =
9725 (declaration.id && declaration.id.name) || this.declaration.name;
9726 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
9727 this.context.addExport(this);
9728 }
9729 render(code, options, nodeRenderOptions) {
9730 const { start, end } = nodeRenderOptions;
9731 const declarationStart = getDeclarationStart(code.original, this.start);
9732 if (this.declaration instanceof FunctionDeclaration) {
9733 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
9734 }
9735 else if (this.declaration instanceof ClassDeclaration) {
9736 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
9737 }
9738 else if (this.variable.getOriginalVariable() !== this.variable) {
9739 // Remove altogether to prevent re-declaring the same variable
9740 treeshakeNode(this, code, start, end);
9741 return;
9742 }
9743 else if (this.variable.included) {
9744 this.renderVariableDeclaration(code, declarationStart, options);
9745 }
9746 else {
9747 code.remove(this.start, declarationStart);
9748 this.declaration.render(code, options, {
9749 renderedSurroundingElement: ExpressionStatement$1
9750 });
9751 if (code.original[this.end - 1] !== ';') {
9752 code.appendLeft(this.end, ';');
9753 }
9754 return;
9755 }
9756 this.declaration.render(code, options);
9757 }
9758 applyDeoptimizations() { }
9759 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
9760 const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
9761 const name = this.variable.getName(getPropertyAccess);
9762 // Remove `export default`
9763 code.remove(this.start, declarationStart);
9764 if (needsId) {
9765 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
9766 }
9767 if (format === 'system' &&
9768 this.declaration instanceof ClassDeclaration &&
9769 exportNamesByVariable.has(this.variable)) {
9770 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
9771 }
9772 }
9773 renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
9774 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
9775 const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
9776 if (systemExportNames) {
9777 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
9778 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
9779 }
9780 else {
9781 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
9782 if (!hasTrailingSemicolon) {
9783 code.appendLeft(this.end, ';');
9784 }
9785 }
9786 }
9787}
9788ExportDefaultDeclaration.prototype.needsBoundaries = true;
9789
9790class ExportNamedDeclaration extends NodeBase {
9791 bind() {
9792 var _a;
9793 // Do not bind specifiers
9794 (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
9795 }
9796 hasEffects(context) {
9797 var _a;
9798 return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
9799 }
9800 initialise() {
9801 this.context.addExport(this);
9802 }
9803 render(code, options, nodeRenderOptions) {
9804 const { start, end } = nodeRenderOptions;
9805 if (this.declaration === null) {
9806 code.remove(start, end);
9807 }
9808 else {
9809 code.remove(this.start, this.declaration.start);
9810 this.declaration.render(code, options, { end, start });
9811 }
9812 }
9813 applyDeoptimizations() { }
9814}
9815ExportNamedDeclaration.prototype.needsBoundaries = true;
9816
9817class ExportSpecifier extends NodeBase {
9818 applyDeoptimizations() { }
9819}
9820
9821class ForInStatement extends NodeBase {
9822 createScope(parentScope) {
9823 this.scope = new BlockScope(parentScope);
9824 }
9825 hasEffects(context) {
9826 const { deoptimized, left, right } = this;
9827 if (!deoptimized)
9828 this.applyDeoptimizations();
9829 if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
9830 return true;
9831 const { brokenFlow, ignore: { breaks, continues } } = context;
9832 context.ignore.breaks = true;
9833 context.ignore.continues = true;
9834 if (this.body.hasEffects(context))
9835 return true;
9836 context.ignore.breaks = breaks;
9837 context.ignore.continues = continues;
9838 context.brokenFlow = brokenFlow;
9839 return false;
9840 }
9841 include(context, includeChildrenRecursively) {
9842 const { body, deoptimized, left, right } = this;
9843 if (!deoptimized)
9844 this.applyDeoptimizations();
9845 this.included = true;
9846 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9847 right.include(context, includeChildrenRecursively);
9848 const { brokenFlow } = context;
9849 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9850 context.brokenFlow = brokenFlow;
9851 }
9852 initialise() {
9853 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9854 }
9855 render(code, options) {
9856 this.left.render(code, options, NO_SEMICOLON);
9857 this.right.render(code, options, NO_SEMICOLON);
9858 // handle no space between "in" and the right side
9859 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
9860 code.prependLeft(this.right.start, ' ');
9861 }
9862 this.body.render(code, options);
9863 }
9864 applyDeoptimizations() {
9865 this.deoptimized = true;
9866 this.left.deoptimizePath(EMPTY_PATH);
9867 this.context.requestTreeshakingPass();
9868 }
9869}
9870
9871class ForOfStatement extends NodeBase {
9872 createScope(parentScope) {
9873 this.scope = new BlockScope(parentScope);
9874 }
9875 hasEffects() {
9876 if (!this.deoptimized)
9877 this.applyDeoptimizations();
9878 // Placeholder until proper Symbol.Iterator support
9879 return true;
9880 }
9881 include(context, includeChildrenRecursively) {
9882 const { body, deoptimized, left, right } = this;
9883 if (!deoptimized)
9884 this.applyDeoptimizations();
9885 this.included = true;
9886 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9887 right.include(context, includeChildrenRecursively);
9888 const { brokenFlow } = context;
9889 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9890 context.brokenFlow = brokenFlow;
9891 }
9892 initialise() {
9893 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9894 }
9895 render(code, options) {
9896 this.left.render(code, options, NO_SEMICOLON);
9897 this.right.render(code, options, NO_SEMICOLON);
9898 // handle no space between "of" and the right side
9899 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
9900 code.prependLeft(this.right.start, ' ');
9901 }
9902 this.body.render(code, options);
9903 }
9904 applyDeoptimizations() {
9905 this.deoptimized = true;
9906 this.left.deoptimizePath(EMPTY_PATH);
9907 this.context.requestTreeshakingPass();
9908 }
9909}
9910
9911class ForStatement extends NodeBase {
9912 createScope(parentScope) {
9913 this.scope = new BlockScope(parentScope);
9914 }
9915 hasEffects(context) {
9916 var _a, _b, _c;
9917 if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
9918 ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
9919 ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
9920 return true;
9921 const { brokenFlow, ignore: { breaks, continues } } = context;
9922 context.ignore.breaks = true;
9923 context.ignore.continues = true;
9924 if (this.body.hasEffects(context))
9925 return true;
9926 context.ignore.breaks = breaks;
9927 context.ignore.continues = continues;
9928 context.brokenFlow = brokenFlow;
9929 return false;
9930 }
9931 include(context, includeChildrenRecursively) {
9932 var _a, _b, _c;
9933 this.included = true;
9934 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
9935 (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
9936 const { brokenFlow } = context;
9937 (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
9938 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9939 context.brokenFlow = brokenFlow;
9940 }
9941 render(code, options) {
9942 var _a, _b, _c;
9943 (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
9944 (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
9945 (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
9946 this.body.render(code, options);
9947 }
9948}
9949
9950class FunctionExpression extends FunctionNode {
9951 render(code, options, { renderedSurroundingElement } = BLANK) {
9952 super.render(code, options);
9953 if (renderedSurroundingElement === ExpressionStatement$1) {
9954 code.appendRight(this.start, '(');
9955 code.prependLeft(this.end, ')');
9956 }
9957 }
9958}
9959
9960class TrackingScope extends BlockScope {
9961 constructor() {
9962 super(...arguments);
9963 this.hoistedDeclarations = [];
9964 }
9965 addDeclaration(identifier, context, init, isHoisted) {
9966 this.hoistedDeclarations.push(identifier);
9967 return super.addDeclaration(identifier, context, init, isHoisted);
9968 }
9969}
9970
9971const unset = Symbol('unset');
9972class IfStatement extends NodeBase {
9973 constructor() {
9974 super(...arguments);
9975 this.testValue = unset;
9976 }
9977 deoptimizeCache() {
9978 this.testValue = UnknownValue;
9979 }
9980 hasEffects(context) {
9981 var _a;
9982 if (this.test.hasEffects(context)) {
9983 return true;
9984 }
9985 const testValue = this.getTestValue();
9986 if (typeof testValue === 'symbol') {
9987 const { brokenFlow } = context;
9988 if (this.consequent.hasEffects(context))
9989 return true;
9990 const consequentBrokenFlow = context.brokenFlow;
9991 context.brokenFlow = brokenFlow;
9992 if (this.alternate === null)
9993 return false;
9994 if (this.alternate.hasEffects(context))
9995 return true;
9996 context.brokenFlow =
9997 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
9998 return false;
9999 }
10000 return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
10001 }
10002 include(context, includeChildrenRecursively) {
10003 this.included = true;
10004 if (includeChildrenRecursively) {
10005 this.includeRecursively(includeChildrenRecursively, context);
10006 }
10007 else {
10008 const testValue = this.getTestValue();
10009 if (typeof testValue === 'symbol') {
10010 this.includeUnknownTest(context);
10011 }
10012 else {
10013 this.includeKnownTest(context, testValue);
10014 }
10015 }
10016 }
10017 parseNode(esTreeNode) {
10018 this.consequentScope = new TrackingScope(this.scope);
10019 this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
10020 if (esTreeNode.alternate) {
10021 this.alternateScope = new TrackingScope(this.scope);
10022 this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
10023 }
10024 super.parseNode(esTreeNode);
10025 }
10026 render(code, options) {
10027 const { snippets: { getPropertyAccess } } = options;
10028 // Note that unknown test values are always included
10029 const testValue = this.getTestValue();
10030 const hoistedDeclarations = [];
10031 const includesIfElse = this.test.included;
10032 const noTreeshake = !this.context.options.treeshake;
10033 if (includesIfElse) {
10034 this.test.render(code, options);
10035 }
10036 else {
10037 code.remove(this.start, this.consequent.start);
10038 }
10039 if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
10040 this.consequent.render(code, options);
10041 }
10042 else {
10043 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
10044 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
10045 }
10046 if (this.alternate) {
10047 if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
10048 if (includesIfElse) {
10049 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
10050 code.prependLeft(this.alternate.start, ' ');
10051 }
10052 }
10053 else {
10054 code.remove(this.consequent.end, this.alternate.start);
10055 }
10056 this.alternate.render(code, options);
10057 }
10058 else {
10059 if (includesIfElse && this.shouldKeepAlternateBranch()) {
10060 code.overwrite(this.alternate.start, this.end, ';');
10061 }
10062 else {
10063 code.remove(this.consequent.end, this.end);
10064 }
10065 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
10066 }
10067 }
10068 this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
10069 }
10070 applyDeoptimizations() { }
10071 getTestValue() {
10072 if (this.testValue === unset) {
10073 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
10074 }
10075 return this.testValue;
10076 }
10077 includeKnownTest(context, testValue) {
10078 var _a;
10079 if (this.test.shouldBeIncluded(context)) {
10080 this.test.include(context, false);
10081 }
10082 if (testValue && this.consequent.shouldBeIncluded(context)) {
10083 this.consequent.include(context, false, { asSingleStatement: true });
10084 }
10085 if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
10086 this.alternate.include(context, false, { asSingleStatement: true });
10087 }
10088 }
10089 includeRecursively(includeChildrenRecursively, context) {
10090 var _a;
10091 this.test.include(context, includeChildrenRecursively);
10092 this.consequent.include(context, includeChildrenRecursively);
10093 (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
10094 }
10095 includeUnknownTest(context) {
10096 var _a;
10097 this.test.include(context, false);
10098 const { brokenFlow } = context;
10099 let consequentBrokenFlow = BROKEN_FLOW_NONE;
10100 if (this.consequent.shouldBeIncluded(context)) {
10101 this.consequent.include(context, false, { asSingleStatement: true });
10102 consequentBrokenFlow = context.brokenFlow;
10103 context.brokenFlow = brokenFlow;
10104 }
10105 if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
10106 this.alternate.include(context, false, { asSingleStatement: true });
10107 context.brokenFlow =
10108 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
10109 }
10110 }
10111 renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
10112 const hoistedVars = [
10113 ...new Set(hoistedDeclarations.map(identifier => {
10114 const variable = identifier.variable;
10115 return variable.included ? variable.getName(getPropertyAccess) : '';
10116 }))
10117 ]
10118 .filter(Boolean)
10119 .join(', ');
10120 if (hoistedVars) {
10121 const parentType = this.parent.type;
10122 const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
10123 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
10124 if (needsBraces) {
10125 code.appendLeft(this.end, ` }`);
10126 }
10127 }
10128 }
10129 shouldKeepAlternateBranch() {
10130 let currentParent = this.parent;
10131 do {
10132 if (currentParent instanceof IfStatement && currentParent.alternate) {
10133 return true;
10134 }
10135 if (currentParent instanceof BlockStatement) {
10136 return false;
10137 }
10138 currentParent = currentParent.parent;
10139 } while (currentParent);
10140 return false;
10141 }
10142}
10143
10144class ImportDeclaration extends NodeBase {
10145 // Do not bind specifiers
10146 bind() { }
10147 hasEffects() {
10148 return false;
10149 }
10150 initialise() {
10151 this.context.addImport(this);
10152 }
10153 render(code, _options, nodeRenderOptions) {
10154 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
10155 }
10156 applyDeoptimizations() { }
10157}
10158ImportDeclaration.prototype.needsBoundaries = true;
10159
10160class ImportDefaultSpecifier extends NodeBase {
10161 applyDeoptimizations() { }
10162}
10163
10164const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
10165const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
10166const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
10167const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
10168const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
10169const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
10170const defaultInteropHelpersByInteropType = {
10171 auto: INTEROP_DEFAULT_VARIABLE,
10172 default: null,
10173 defaultOnly: null,
10174 esModule: null,
10175 false: null,
10176 true: INTEROP_DEFAULT_LEGACY_VARIABLE
10177};
10178const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
10179 (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
10180const namespaceInteropHelpersByInteropType = {
10181 auto: INTEROP_NAMESPACE_VARIABLE,
10182 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
10183 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
10184 esModule: null,
10185 false: null,
10186 true: INTEROP_NAMESPACE_VARIABLE
10187};
10188const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
10189 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
10190const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
10191 const usedHelpers = new Set(additionalHelpers);
10192 for (const variable of HELPER_NAMES) {
10193 if (accessedGlobals.has(variable)) {
10194 usedHelpers.add(variable);
10195 }
10196 }
10197 return HELPER_NAMES.map(variable => usedHelpers.has(variable)
10198 ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
10199 : '').join('');
10200};
10201const HELPER_GENERATORS = {
10202 [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
10203 const { _, getDirectReturnFunction, n } = snippets;
10204 const [left, right] = getDirectReturnFunction(['e'], {
10205 functionReturn: true,
10206 lineBreakIndent: null,
10207 name: INTEROP_DEFAULT_LEGACY_VARIABLE
10208 });
10209 return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
10210 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10211 },
10212 [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
10213 const { _, getDirectReturnFunction, n } = snippets;
10214 const [left, right] = getDirectReturnFunction(['e'], {
10215 functionReturn: true,
10216 lineBreakIndent: null,
10217 name: INTEROP_DEFAULT_VARIABLE
10218 });
10219 return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
10220 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10221 },
10222 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
10223 const { getDirectReturnFunction, getObject, n } = snippets;
10224 const [left, right] = getDirectReturnFunction(['e'], {
10225 functionReturn: true,
10226 lineBreakIndent: null,
10227 name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10228 });
10229 return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
10230 ['__proto__', 'null'],
10231 ['default', 'e']
10232 ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
10233 },
10234 [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10235 const { _, n } = snippets;
10236 return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
10237 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10238 `}${n}${n}`);
10239 },
10240 [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
10241 const { _, getDirectReturnFunction, n } = snippets;
10242 if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
10243 const [left, right] = getDirectReturnFunction(['e'], {
10244 functionReturn: true,
10245 lineBreakIndent: null,
10246 name: INTEROP_NAMESPACE_VARIABLE
10247 });
10248 return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
10249 }
10250 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
10251 `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
10252 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10253 `}${n}${n}`);
10254 },
10255 [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10256 const { _, cnst, n } = snippets;
10257 const useForEach = cnst === 'var' && liveBindings;
10258 return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
10259 `${t}${loopOverNamespaces(`{${n}` +
10260 `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
10261 (liveBindings
10262 ? useForEach
10263 ? copyOwnPropertyLiveBinding
10264 : copyPropertyLiveBinding
10265 : copyPropertyStatic)(t, t + t + t + t, snippets) +
10266 `${t}${t}${t}}${n}` +
10267 `${t}${t}}`, useForEach, t, snippets)}${n}` +
10268 `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
10269 `}${n}${n}`);
10270 }
10271};
10272const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
10273const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
10274const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
10275 const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
10276 const copyProperty = `{${n}` +
10277 (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
10278 `${i}${t}}`;
10279 return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
10280 ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
10281 : ''});${n}` +
10282 `${i}if${_}(e)${_}{${n}` +
10283 `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
10284 `${i}}${n}` +
10285 `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
10286 `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
10287};
10288const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
10289 ? `for${_}(${cnst} k in e)${_}${body}`
10290 : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
10291 isAsync: false,
10292 name: null
10293 })}${body})${s}`;
10294const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
10295 if (useForEach) {
10296 const [left, right] = getDirectReturnFunction(['e'], {
10297 functionReturn: false,
10298 lineBreakIndent: { base: t, t },
10299 name: null
10300 });
10301 return (`m.forEach(${left}` +
10302 `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
10303 isAsync: false,
10304 name: null
10305 })}${body})${right});`);
10306 }
10307 return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
10308 `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
10309 `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
10310};
10311const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
10312 const { _, n } = snippets;
10313 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
10314 copyOwnPropertyLiveBinding(t, i + t, snippets) +
10315 `${i}}${n}`);
10316};
10317const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10318 const [left, right] = getDirectReturnFunction([], {
10319 functionReturn: true,
10320 lineBreakIndent: null,
10321 name: null
10322 });
10323 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10324 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10325 `${i}${t}enumerable:${_}true,${n}` +
10326 `${i}${t}get:${_}${left}e[k]${right}${n}` +
10327 `${i}});${n}`);
10328};
10329const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10330 const [left, right] = getDirectReturnFunction([], {
10331 functionReturn: true,
10332 lineBreakIndent: null,
10333 name: null
10334 });
10335 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10336 `${i}if${_}(d)${_}{${n}` +
10337 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10338 `${i}${t}${t}enumerable:${_}true,${n}` +
10339 `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
10340 `${i}${t}});${n}` +
10341 `${i}}${n}`);
10342};
10343const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
10344const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
10345const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
10346 ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
10347 : fragment;
10348const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
10349function getToStringTagValue(getObject) {
10350 return getObject([['value', "'Module'"]], {
10351 lineBreakIndent: null
10352 });
10353}
10354
10355class ImportExpression extends NodeBase {
10356 constructor() {
10357 super(...arguments);
10358 this.inlineNamespace = null;
10359 this.mechanism = null;
10360 this.resolution = null;
10361 }
10362 hasEffects() {
10363 return true;
10364 }
10365 include(context, includeChildrenRecursively) {
10366 if (!this.included) {
10367 this.included = true;
10368 this.context.includeDynamicImport(this);
10369 this.scope.addAccessedDynamicImport(this);
10370 }
10371 this.source.include(context, includeChildrenRecursively);
10372 }
10373 initialise() {
10374 this.context.addDynamicImport(this);
10375 }
10376 render(code, options) {
10377 if (this.inlineNamespace) {
10378 const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10379 const [left, right] = getDirectReturnFunction([], {
10380 functionReturn: true,
10381 lineBreakIndent: null,
10382 name: null
10383 });
10384 code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
10385 return;
10386 }
10387 if (this.mechanism) {
10388 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
10389 code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
10390 }
10391 this.source.render(code, options);
10392 }
10393 renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
10394 code.overwrite(this.source.start, this.source.end, resolution);
10395 if (namespaceExportName) {
10396 const [left, right] = getDirectReturnFunction(['n'], {
10397 functionReturn: true,
10398 lineBreakIndent: null,
10399 name: null
10400 });
10401 code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
10402 }
10403 }
10404 setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
10405 const { format } = options;
10406 this.resolution = resolution;
10407 const accessedGlobals = [...(accessedImportGlobals[format] || [])];
10408 let helper;
10409 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
10410 if (helper) {
10411 accessedGlobals.push(helper);
10412 }
10413 if (accessedGlobals.length > 0) {
10414 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10415 }
10416 }
10417 setInternalResolution(inlineNamespace) {
10418 this.inlineNamespace = inlineNamespace;
10419 }
10420 applyDeoptimizations() { }
10421 getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
10422 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
10423 {
10424 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
10425 format,
10426 moduleId: this.context.module.id,
10427 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
10428 }
10429 ]);
10430 if (mechanism) {
10431 return { helper: null, mechanism };
10432 }
10433 const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
10434 switch (format) {
10435 case 'cjs': {
10436 const helper = getInteropHelper(resolution, exportMode, interop);
10437 let left = `require(`;
10438 let right = `)`;
10439 if (helper) {
10440 left = `/*#__PURE__*/${helper}(${left}`;
10441 right += ')';
10442 }
10443 const [functionLeft, functionRight] = getDirectReturnFunction([], {
10444 functionReturn: true,
10445 lineBreakIndent: null,
10446 name: null
10447 });
10448 left = `Promise.resolve().then(${functionLeft}${left}`;
10449 right += `${functionRight})`;
10450 if (!arrowFunctions && hasDynamicTarget) {
10451 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10452 needsArrowReturnParens: false,
10453 needsWrappedFunction: true
10454 });
10455 right = ')';
10456 }
10457 return {
10458 helper,
10459 mechanism: { left, right }
10460 };
10461 }
10462 case 'amd': {
10463 const resolve = compact ? 'c' : 'resolve';
10464 const reject = compact ? 'e' : 'reject';
10465 const helper = getInteropHelper(resolution, exportMode, interop);
10466 const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
10467 functionReturn: false,
10468 lineBreakIndent: null,
10469 name: null
10470 });
10471 const resolveNamespace = helper
10472 ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
10473 : resolve;
10474 const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
10475 functionReturn: false,
10476 lineBreakIndent: null,
10477 name: null
10478 });
10479 let left = `new Promise(${handlerLeft}require([`;
10480 let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
10481 if (!arrowFunctions && hasDynamicTarget) {
10482 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10483 needsArrowReturnParens: false,
10484 needsWrappedFunction: true
10485 });
10486 right = ')';
10487 }
10488 return {
10489 helper,
10490 mechanism: { left, right }
10491 };
10492 }
10493 case 'system':
10494 return {
10495 helper: null,
10496 mechanism: {
10497 left: 'module.import(',
10498 right: ')'
10499 }
10500 };
10501 case 'es':
10502 if (dynamicImportFunction) {
10503 return {
10504 helper: null,
10505 mechanism: {
10506 left: `${dynamicImportFunction}(`,
10507 right: ')'
10508 }
10509 };
10510 }
10511 }
10512 return { helper: null, mechanism: null };
10513 }
10514}
10515function getInteropHelper(resolution, exportMode, interop) {
10516 return exportMode === 'external'
10517 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
10518 : exportMode === 'default'
10519 ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10520 : null;
10521}
10522const accessedImportGlobals = {
10523 amd: ['require'],
10524 cjs: ['require'],
10525 system: ['module']
10526};
10527
10528class ImportNamespaceSpecifier extends NodeBase {
10529 applyDeoptimizations() { }
10530}
10531
10532class ImportSpecifier extends NodeBase {
10533 applyDeoptimizations() { }
10534}
10535
10536class LabeledStatement extends NodeBase {
10537 hasEffects(context) {
10538 const brokenFlow = context.brokenFlow;
10539 context.ignore.labels.add(this.label.name);
10540 if (this.body.hasEffects(context))
10541 return true;
10542 context.ignore.labels.delete(this.label.name);
10543 if (context.includedLabels.has(this.label.name)) {
10544 context.includedLabels.delete(this.label.name);
10545 context.brokenFlow = brokenFlow;
10546 }
10547 return false;
10548 }
10549 include(context, includeChildrenRecursively) {
10550 this.included = true;
10551 const brokenFlow = context.brokenFlow;
10552 this.body.include(context, includeChildrenRecursively);
10553 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
10554 this.label.include();
10555 context.includedLabels.delete(this.label.name);
10556 context.brokenFlow = brokenFlow;
10557 }
10558 }
10559 render(code, options) {
10560 if (this.label.included) {
10561 this.label.render(code, options);
10562 }
10563 else {
10564 code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
10565 }
10566 this.body.render(code, options);
10567 }
10568}
10569
10570class LogicalExpression extends NodeBase {
10571 constructor() {
10572 super(...arguments);
10573 // We collect deoptimization information if usedBranch !== null
10574 this.expressionsToBeDeoptimized = [];
10575 this.isBranchResolutionAnalysed = false;
10576 this.usedBranch = null;
10577 }
10578 deoptimizeCache() {
10579 if (this.usedBranch) {
10580 const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
10581 this.usedBranch = null;
10582 unusedBranch.deoptimizePath(UNKNOWN_PATH);
10583 for (const expression of this.expressionsToBeDeoptimized) {
10584 expression.deoptimizeCache();
10585 }
10586 // Request another pass because we need to ensure "include" runs again if
10587 // it is rendered
10588 this.context.requestTreeshakingPass();
10589 }
10590 }
10591 deoptimizePath(path) {
10592 const usedBranch = this.getUsedBranch();
10593 if (!usedBranch) {
10594 this.left.deoptimizePath(path);
10595 this.right.deoptimizePath(path);
10596 }
10597 else {
10598 usedBranch.deoptimizePath(path);
10599 }
10600 }
10601 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10602 this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10603 this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10604 }
10605 getLiteralValueAtPath(path, recursionTracker, origin) {
10606 const usedBranch = this.getUsedBranch();
10607 if (!usedBranch)
10608 return UnknownValue;
10609 this.expressionsToBeDeoptimized.push(origin);
10610 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
10611 }
10612 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10613 const usedBranch = this.getUsedBranch();
10614 if (!usedBranch)
10615 return new MultiExpression([
10616 this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
10617 this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
10618 ]);
10619 this.expressionsToBeDeoptimized.push(origin);
10620 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10621 }
10622 hasEffects(context) {
10623 if (this.left.hasEffects(context)) {
10624 return true;
10625 }
10626 if (this.getUsedBranch() !== this.left) {
10627 return this.right.hasEffects(context);
10628 }
10629 return false;
10630 }
10631 hasEffectsOnInteractionAtPath(path, interaction, context) {
10632 const usedBranch = this.getUsedBranch();
10633 if (!usedBranch) {
10634 return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
10635 this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
10636 }
10637 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
10638 }
10639 include(context, includeChildrenRecursively) {
10640 this.included = true;
10641 const usedBranch = this.getUsedBranch();
10642 if (includeChildrenRecursively ||
10643 (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
10644 !usedBranch) {
10645 this.left.include(context, includeChildrenRecursively);
10646 this.right.include(context, includeChildrenRecursively);
10647 }
10648 else {
10649 usedBranch.include(context, includeChildrenRecursively);
10650 }
10651 }
10652 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
10653 if (!this.left.included || !this.right.included) {
10654 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
10655 if (this.right.included) {
10656 const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
10657 code.remove(this.start, removePos);
10658 if (preventASI) {
10659 removeLineBreaks(code, removePos, this.right.start);
10660 }
10661 }
10662 else {
10663 code.remove(operatorPos, this.end);
10664 }
10665 removeAnnotations(this, code);
10666 this.getUsedBranch().render(code, options, {
10667 isCalleeOfRenderedParent,
10668 preventASI,
10669 renderedParentType: renderedParentType || this.parent.type,
10670 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
10671 });
10672 }
10673 else {
10674 this.left.render(code, options, {
10675 preventASI,
10676 renderedSurroundingElement
10677 });
10678 this.right.render(code, options);
10679 }
10680 }
10681 getUsedBranch() {
10682 if (!this.isBranchResolutionAnalysed) {
10683 this.isBranchResolutionAnalysed = true;
10684 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10685 if (typeof leftValue === 'symbol') {
10686 return null;
10687 }
10688 else {
10689 this.usedBranch =
10690 (this.operator === '||' && leftValue) ||
10691 (this.operator === '&&' && !leftValue) ||
10692 (this.operator === '??' && leftValue != null)
10693 ? this.left
10694 : this.right;
10695 }
10696 }
10697 return this.usedBranch;
10698 }
10699}
10700
10701const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
10702const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
10703const FILE_PREFIX = 'ROLLUP_FILE_URL_';
10704class MetaProperty extends NodeBase {
10705 addAccessedGlobals(format, accessedGlobalsByScope) {
10706 const metaProperty = this.metaProperty;
10707 const accessedGlobals = (metaProperty &&
10708 (metaProperty.startsWith(FILE_PREFIX) ||
10709 metaProperty.startsWith(ASSET_PREFIX) ||
10710 metaProperty.startsWith(CHUNK_PREFIX))
10711 ? accessedFileUrlGlobals
10712 : accessedMetaUrlGlobals)[format];
10713 if (accessedGlobals.length > 0) {
10714 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10715 }
10716 }
10717 getReferencedFileName(outputPluginDriver) {
10718 const metaProperty = this.metaProperty;
10719 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
10720 return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10721 }
10722 return null;
10723 }
10724 hasEffects() {
10725 return false;
10726 }
10727 hasEffectsOnInteractionAtPath(path, { type }) {
10728 return path.length > 1 || type !== INTERACTION_ACCESSED;
10729 }
10730 include() {
10731 if (!this.included) {
10732 this.included = true;
10733 if (this.meta.name === 'import') {
10734 this.context.addImportMeta(this);
10735 const parent = this.parent;
10736 this.metaProperty =
10737 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
10738 ? parent.propertyKey
10739 : null;
10740 }
10741 }
10742 }
10743 renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
10744 var _a;
10745 const parent = this.parent;
10746 const metaProperty = this.metaProperty;
10747 if (metaProperty &&
10748 (metaProperty.startsWith(FILE_PREFIX) ||
10749 metaProperty.startsWith(ASSET_PREFIX) ||
10750 metaProperty.startsWith(CHUNK_PREFIX))) {
10751 let referenceId = null;
10752 let assetReferenceId = null;
10753 let chunkReferenceId = null;
10754 let fileName;
10755 if (metaProperty.startsWith(FILE_PREFIX)) {
10756 referenceId = metaProperty.substring(FILE_PREFIX.length);
10757 fileName = outputPluginDriver.getFileName(referenceId);
10758 }
10759 else if (metaProperty.startsWith(ASSET_PREFIX)) {
10760 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10761 assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
10762 fileName = outputPluginDriver.getFileName(assetReferenceId);
10763 }
10764 else {
10765 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10766 chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
10767 fileName = outputPluginDriver.getFileName(chunkReferenceId);
10768 }
10769 const relativePath = normalize(require$$0.relative(require$$0.dirname(chunkId), fileName));
10770 let replacement;
10771 if (assetReferenceId !== null) {
10772 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
10773 {
10774 assetFileName: fileName,
10775 chunkId,
10776 format,
10777 moduleId: this.context.module.id,
10778 relativeAssetPath: relativePath
10779 }
10780 ]);
10781 }
10782 if (!replacement) {
10783 replacement =
10784 outputPluginDriver.hookFirstSync('resolveFileUrl', [
10785 {
10786 assetReferenceId,
10787 chunkId,
10788 chunkReferenceId,
10789 fileName,
10790 format,
10791 moduleId: this.context.module.id,
10792 referenceId: referenceId || assetReferenceId || chunkReferenceId,
10793 relativePath
10794 }
10795 ]) || relativeUrlMechanisms[format](relativePath);
10796 }
10797 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10798 return;
10799 }
10800 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
10801 metaProperty,
10802 {
10803 chunkId,
10804 format,
10805 moduleId: this.context.module.id
10806 }
10807 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
10808 if (typeof replacement === 'string') {
10809 if (parent instanceof MemberExpression) {
10810 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10811 }
10812 else {
10813 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
10814 }
10815 }
10816 }
10817}
10818const accessedMetaUrlGlobals = {
10819 amd: ['document', 'module', 'URL'],
10820 cjs: ['document', 'require', 'URL'],
10821 es: [],
10822 iife: ['document', 'URL'],
10823 system: ['module'],
10824 umd: ['document', 'require', 'URL']
10825};
10826const accessedFileUrlGlobals = {
10827 amd: ['document', 'require', 'URL'],
10828 cjs: ['document', 'require', 'URL'],
10829 es: [],
10830 iife: ['document', 'URL'],
10831 system: ['module', 'URL'],
10832 umd: ['document', 'require', 'URL']
10833};
10834const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
10835const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
10836const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
10837 const urlMechanism = getUrl(chunkId);
10838 return prop === null
10839 ? `({ url: ${urlMechanism} })`
10840 : prop === 'url'
10841 ? urlMechanism
10842 : 'undefined';
10843};
10844const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
10845const relativeUrlMechanisms = {
10846 amd: relativePath => {
10847 if (relativePath[0] !== '.')
10848 relativePath = './' + relativePath;
10849 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
10850 },
10851 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
10852 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
10853 iife: relativePath => getRelativeUrlFromDocument(relativePath),
10854 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
10855 umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
10856};
10857const importMetaMechanisms = {
10858 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
10859 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
10860 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
10861 system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
10862 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
10863};
10864
10865class NewExpression extends NodeBase {
10866 hasEffects(context) {
10867 try {
10868 for (const argument of this.arguments) {
10869 if (argument.hasEffects(context))
10870 return true;
10871 }
10872 if (this.context.options.treeshake.annotations &&
10873 this.annotations) {
10874 return false;
10875 }
10876 return (this.callee.hasEffects(context) ||
10877 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
10878 }
10879 finally {
10880 if (!this.deoptimized)
10881 this.applyDeoptimizations();
10882 }
10883 }
10884 hasEffectsOnInteractionAtPath(path, { type }) {
10885 return path.length > 0 || type !== INTERACTION_ACCESSED;
10886 }
10887 include(context, includeChildrenRecursively) {
10888 if (!this.deoptimized)
10889 this.applyDeoptimizations();
10890 if (includeChildrenRecursively) {
10891 super.include(context, includeChildrenRecursively);
10892 }
10893 else {
10894 this.included = true;
10895 this.callee.include(context, false);
10896 }
10897 this.callee.includeCallArguments(context, this.arguments);
10898 }
10899 initialise() {
10900 this.interaction = {
10901 args: this.arguments,
10902 thisArg: null,
10903 type: INTERACTION_CALLED,
10904 withNew: true
10905 };
10906 }
10907 render(code, options) {
10908 this.callee.render(code, options);
10909 renderCallArguments(code, options, this);
10910 }
10911 applyDeoptimizations() {
10912 this.deoptimized = true;
10913 for (const argument of this.arguments) {
10914 // This will make sure all properties of parameters behave as "unknown"
10915 argument.deoptimizePath(UNKNOWN_PATH);
10916 }
10917 this.context.requestTreeshakingPass();
10918 }
10919}
10920
10921class ObjectExpression extends NodeBase {
10922 constructor() {
10923 super(...arguments);
10924 this.objectEntity = null;
10925 }
10926 deoptimizeCache() {
10927 this.getObjectEntity().deoptimizeAllProperties();
10928 }
10929 deoptimizePath(path) {
10930 this.getObjectEntity().deoptimizePath(path);
10931 }
10932 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10933 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10934 }
10935 getLiteralValueAtPath(path, recursionTracker, origin) {
10936 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
10937 }
10938 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10939 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10940 }
10941 hasEffectsOnInteractionAtPath(path, interaction, context) {
10942 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
10943 }
10944 render(code, options, { renderedSurroundingElement } = BLANK) {
10945 super.render(code, options);
10946 if (renderedSurroundingElement === ExpressionStatement$1 ||
10947 renderedSurroundingElement === ArrowFunctionExpression$1) {
10948 code.appendRight(this.start, '(');
10949 code.prependLeft(this.end, ')');
10950 }
10951 }
10952 applyDeoptimizations() { }
10953 getObjectEntity() {
10954 if (this.objectEntity !== null) {
10955 return this.objectEntity;
10956 }
10957 let prototype = OBJECT_PROTOTYPE;
10958 const properties = [];
10959 for (const property of this.properties) {
10960 if (property instanceof SpreadElement) {
10961 properties.push({ key: UnknownKey, kind: 'init', property });
10962 continue;
10963 }
10964 let key;
10965 if (property.computed) {
10966 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10967 if (typeof keyValue === 'symbol') {
10968 properties.push({ key: UnknownKey, kind: property.kind, property });
10969 continue;
10970 }
10971 else {
10972 key = String(keyValue);
10973 }
10974 }
10975 else {
10976 key =
10977 property.key instanceof Identifier
10978 ? property.key.name
10979 : String(property.key.value);
10980 if (key === '__proto__' && property.kind === 'init') {
10981 prototype =
10982 property.value instanceof Literal && property.value.value === null
10983 ? null
10984 : property.value;
10985 continue;
10986 }
10987 }
10988 properties.push({ key, kind: property.kind, property });
10989 }
10990 return (this.objectEntity = new ObjectEntity(properties, prototype));
10991 }
10992}
10993
10994class PrivateIdentifier extends NodeBase {
10995}
10996
10997class Program extends NodeBase {
10998 constructor() {
10999 super(...arguments);
11000 this.hasCachedEffect = false;
11001 }
11002 hasEffects(context) {
11003 // We are caching here to later more efficiently identify side-effect-free modules
11004 if (this.hasCachedEffect)
11005 return true;
11006 for (const node of this.body) {
11007 if (node.hasEffects(context)) {
11008 return (this.hasCachedEffect = true);
11009 }
11010 }
11011 return false;
11012 }
11013 include(context, includeChildrenRecursively) {
11014 this.included = true;
11015 for (const node of this.body) {
11016 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
11017 node.include(context, includeChildrenRecursively);
11018 }
11019 }
11020 }
11021 render(code, options) {
11022 if (this.body.length) {
11023 renderStatementList(this.body, code, this.start, this.end, options);
11024 }
11025 else {
11026 super.render(code, options);
11027 }
11028 }
11029 applyDeoptimizations() { }
11030}
11031
11032class Property extends MethodBase {
11033 constructor() {
11034 super(...arguments);
11035 this.declarationInit = null;
11036 }
11037 declare(kind, init) {
11038 this.declarationInit = init;
11039 return this.value.declare(kind, UNKNOWN_EXPRESSION);
11040 }
11041 hasEffects(context) {
11042 if (!this.deoptimized)
11043 this.applyDeoptimizations();
11044 const propertyReadSideEffects = this.context.options.treeshake
11045 .propertyReadSideEffects;
11046 return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
11047 this.key.hasEffects(context) ||
11048 this.value.hasEffects(context));
11049 }
11050 markDeclarationReached() {
11051 this.value.markDeclarationReached();
11052 }
11053 render(code, options) {
11054 if (!this.shorthand) {
11055 this.key.render(code, options);
11056 }
11057 this.value.render(code, options, { isShorthandProperty: this.shorthand });
11058 }
11059 applyDeoptimizations() {
11060 this.deoptimized = true;
11061 if (this.declarationInit !== null) {
11062 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
11063 this.context.requestTreeshakingPass();
11064 }
11065 }
11066}
11067
11068class PropertyDefinition extends NodeBase {
11069 deoptimizePath(path) {
11070 var _a;
11071 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
11072 }
11073 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11074 var _a;
11075 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11076 }
11077 getLiteralValueAtPath(path, recursionTracker, origin) {
11078 return this.value
11079 ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
11080 : UnknownValue;
11081 }
11082 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
11083 return this.value
11084 ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
11085 : UNKNOWN_EXPRESSION;
11086 }
11087 hasEffects(context) {
11088 var _a;
11089 return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11090 }
11091 hasEffectsOnInteractionAtPath(path, interaction, context) {
11092 return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
11093 }
11094 applyDeoptimizations() { }
11095}
11096
11097class ReturnStatement extends NodeBase {
11098 hasEffects(context) {
11099 var _a;
11100 if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
11101 return true;
11102 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11103 return false;
11104 }
11105 include(context, includeChildrenRecursively) {
11106 var _a;
11107 this.included = true;
11108 (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11109 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11110 }
11111 initialise() {
11112 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
11113 }
11114 render(code, options) {
11115 if (this.argument) {
11116 this.argument.render(code, options, { preventASI: true });
11117 if (this.argument.start === this.start + 6 /* 'return'.length */) {
11118 code.prependLeft(this.start + 6, ' ');
11119 }
11120 }
11121 }
11122}
11123
11124class SequenceExpression extends NodeBase {
11125 deoptimizePath(path) {
11126 this.expressions[this.expressions.length - 1].deoptimizePath(path);
11127 }
11128 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11129 this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11130 }
11131 getLiteralValueAtPath(path, recursionTracker, origin) {
11132 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
11133 }
11134 hasEffects(context) {
11135 for (const expression of this.expressions) {
11136 if (expression.hasEffects(context))
11137 return true;
11138 }
11139 return false;
11140 }
11141 hasEffectsOnInteractionAtPath(path, interaction, context) {
11142 return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
11143 }
11144 include(context, includeChildrenRecursively) {
11145 this.included = true;
11146 const lastExpression = this.expressions[this.expressions.length - 1];
11147 for (const expression of this.expressions) {
11148 if (includeChildrenRecursively ||
11149 (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
11150 expression.shouldBeIncluded(context))
11151 expression.include(context, includeChildrenRecursively);
11152 }
11153 }
11154 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
11155 let includedNodes = 0;
11156 let lastSeparatorPos = null;
11157 const lastNode = this.expressions[this.expressions.length - 1];
11158 for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
11159 if (!node.included) {
11160 treeshakeNode(node, code, start, end);
11161 continue;
11162 }
11163 includedNodes++;
11164 lastSeparatorPos = separator;
11165 if (includedNodes === 1 && preventASI) {
11166 removeLineBreaks(code, start, node.start);
11167 }
11168 if (includedNodes === 1) {
11169 const parentType = renderedParentType || this.parent.type;
11170 node.render(code, options, {
11171 isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
11172 renderedParentType: parentType,
11173 renderedSurroundingElement: parentType
11174 });
11175 }
11176 else {
11177 node.render(code, options);
11178 }
11179 }
11180 if (lastSeparatorPos) {
11181 code.remove(lastSeparatorPos, this.end);
11182 }
11183 }
11184}
11185
11186class StaticBlock extends NodeBase {
11187 createScope(parentScope) {
11188 this.scope = new BlockScope(parentScope);
11189 }
11190 hasEffects(context) {
11191 for (const node of this.body) {
11192 if (node.hasEffects(context))
11193 return true;
11194 }
11195 return false;
11196 }
11197 include(context, includeChildrenRecursively) {
11198 this.included = true;
11199 for (const node of this.body) {
11200 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11201 node.include(context, includeChildrenRecursively);
11202 }
11203 }
11204 render(code, options) {
11205 if (this.body.length) {
11206 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11207 }
11208 else {
11209 super.render(code, options);
11210 }
11211 }
11212}
11213
11214class Super extends NodeBase {
11215 bind() {
11216 this.variable = this.scope.findVariable('this');
11217 }
11218 deoptimizePath(path) {
11219 this.variable.deoptimizePath(path);
11220 }
11221 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11222 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11223 }
11224 include() {
11225 if (!this.included) {
11226 this.included = true;
11227 this.context.includeVariableInModule(this.variable);
11228 }
11229 }
11230}
11231
11232class SwitchCase extends NodeBase {
11233 hasEffects(context) {
11234 var _a;
11235 if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
11236 return true;
11237 for (const node of this.consequent) {
11238 if (context.brokenFlow)
11239 break;
11240 if (node.hasEffects(context))
11241 return true;
11242 }
11243 return false;
11244 }
11245 include(context, includeChildrenRecursively) {
11246 var _a;
11247 this.included = true;
11248 (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11249 for (const node of this.consequent) {
11250 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11251 node.include(context, includeChildrenRecursively);
11252 }
11253 }
11254 render(code, options, nodeRenderOptions) {
11255 if (this.consequent.length) {
11256 this.test && this.test.render(code, options);
11257 const testEnd = this.test
11258 ? this.test.end
11259 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
11260 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
11261 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
11262 }
11263 else {
11264 super.render(code, options);
11265 }
11266 }
11267}
11268SwitchCase.prototype.needsBoundaries = true;
11269
11270class SwitchStatement extends NodeBase {
11271 createScope(parentScope) {
11272 this.scope = new BlockScope(parentScope);
11273 }
11274 hasEffects(context) {
11275 if (this.discriminant.hasEffects(context))
11276 return true;
11277 const { brokenFlow, ignore: { breaks } } = context;
11278 let minBrokenFlow = Infinity;
11279 context.ignore.breaks = true;
11280 for (const switchCase of this.cases) {
11281 if (switchCase.hasEffects(context))
11282 return true;
11283 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
11284 context.brokenFlow = brokenFlow;
11285 }
11286 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11287 context.brokenFlow = minBrokenFlow;
11288 }
11289 context.ignore.breaks = breaks;
11290 return false;
11291 }
11292 include(context, includeChildrenRecursively) {
11293 this.included = true;
11294 this.discriminant.include(context, includeChildrenRecursively);
11295 const { brokenFlow } = context;
11296 let minBrokenFlow = Infinity;
11297 let isCaseIncluded = includeChildrenRecursively ||
11298 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
11299 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
11300 const switchCase = this.cases[caseIndex];
11301 if (switchCase.included) {
11302 isCaseIncluded = true;
11303 }
11304 if (!isCaseIncluded) {
11305 const hasEffectsContext = createHasEffectsContext();
11306 hasEffectsContext.ignore.breaks = true;
11307 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
11308 }
11309 if (isCaseIncluded) {
11310 switchCase.include(context, includeChildrenRecursively);
11311 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
11312 context.brokenFlow = brokenFlow;
11313 }
11314 else {
11315 minBrokenFlow = brokenFlow;
11316 }
11317 }
11318 if (isCaseIncluded &&
11319 this.defaultCase !== null &&
11320 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11321 context.brokenFlow = minBrokenFlow;
11322 }
11323 }
11324 initialise() {
11325 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
11326 if (this.cases[caseIndex].test === null) {
11327 this.defaultCase = caseIndex;
11328 return;
11329 }
11330 }
11331 this.defaultCase = null;
11332 }
11333 render(code, options) {
11334 this.discriminant.render(code, options);
11335 if (this.cases.length > 0) {
11336 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
11337 }
11338 }
11339}
11340
11341class TaggedTemplateExpression extends CallExpressionBase {
11342 bind() {
11343 super.bind();
11344 if (this.tag.type === Identifier$1) {
11345 const name = this.tag.name;
11346 const variable = this.scope.findVariable(name);
11347 if (variable.isNamespace) {
11348 this.context.warn({
11349 code: 'CANNOT_CALL_NAMESPACE',
11350 message: `Cannot call a namespace ('${name}')`
11351 }, this.start);
11352 }
11353 }
11354 }
11355 hasEffects(context) {
11356 try {
11357 for (const argument of this.quasi.expressions) {
11358 if (argument.hasEffects(context))
11359 return true;
11360 }
11361 return (this.tag.hasEffects(context) ||
11362 this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
11363 }
11364 finally {
11365 if (!this.deoptimized)
11366 this.applyDeoptimizations();
11367 }
11368 }
11369 include(context, includeChildrenRecursively) {
11370 if (!this.deoptimized)
11371 this.applyDeoptimizations();
11372 if (includeChildrenRecursively) {
11373 super.include(context, includeChildrenRecursively);
11374 }
11375 else {
11376 this.included = true;
11377 this.tag.include(context, includeChildrenRecursively);
11378 this.quasi.include(context, includeChildrenRecursively);
11379 }
11380 this.tag.includeCallArguments(context, this.interaction.args);
11381 const returnExpression = this.getReturnExpression();
11382 if (!returnExpression.included) {
11383 returnExpression.include(context, false);
11384 }
11385 }
11386 initialise() {
11387 this.interaction = {
11388 args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
11389 thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
11390 type: INTERACTION_CALLED,
11391 withNew: false
11392 };
11393 }
11394 render(code, options) {
11395 this.tag.render(code, options, { isCalleeOfRenderedParent: true });
11396 this.quasi.render(code, options);
11397 }
11398 applyDeoptimizations() {
11399 this.deoptimized = true;
11400 if (this.interaction.thisArg) {
11401 this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
11402 }
11403 for (const argument of this.quasi.expressions) {
11404 // This will make sure all properties of parameters behave as "unknown"
11405 argument.deoptimizePath(UNKNOWN_PATH);
11406 }
11407 this.context.requestTreeshakingPass();
11408 }
11409 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
11410 if (this.returnExpression === null) {
11411 this.returnExpression = UNKNOWN_EXPRESSION;
11412 return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
11413 }
11414 return this.returnExpression;
11415 }
11416}
11417
11418class TemplateElement extends NodeBase {
11419 // Do not try to bind value
11420 bind() { }
11421 hasEffects() {
11422 return false;
11423 }
11424 include() {
11425 this.included = true;
11426 }
11427 parseNode(esTreeNode) {
11428 this.value = esTreeNode.value;
11429 super.parseNode(esTreeNode);
11430 }
11431 render() { }
11432}
11433
11434class TemplateLiteral extends NodeBase {
11435 deoptimizeThisOnInteractionAtPath() { }
11436 getLiteralValueAtPath(path) {
11437 if (path.length > 0 || this.quasis.length !== 1) {
11438 return UnknownValue;
11439 }
11440 return this.quasis[0].value.cooked;
11441 }
11442 getReturnExpressionWhenCalledAtPath(path) {
11443 if (path.length !== 1) {
11444 return UNKNOWN_EXPRESSION;
11445 }
11446 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
11447 }
11448 hasEffectsOnInteractionAtPath(path, interaction, context) {
11449 if (interaction.type === INTERACTION_ACCESSED) {
11450 return path.length > 1;
11451 }
11452 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
11453 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
11454 }
11455 return true;
11456 }
11457 render(code, options) {
11458 code.indentExclusionRanges.push([this.start, this.end]);
11459 super.render(code, options);
11460 }
11461}
11462
11463class UndefinedVariable extends Variable {
11464 constructor() {
11465 super('undefined');
11466 }
11467 getLiteralValueAtPath() {
11468 return undefined;
11469 }
11470}
11471
11472class ExportDefaultVariable extends LocalVariable {
11473 constructor(name, exportDefaultDeclaration, context) {
11474 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
11475 this.hasId = false;
11476 this.originalId = null;
11477 this.originalVariable = null;
11478 const declaration = exportDefaultDeclaration.declaration;
11479 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
11480 declaration.id) {
11481 this.hasId = true;
11482 this.originalId = declaration.id;
11483 }
11484 else if (declaration instanceof Identifier) {
11485 this.originalId = declaration;
11486 }
11487 }
11488 addReference(identifier) {
11489 if (!this.hasId) {
11490 this.name = identifier.name;
11491 }
11492 }
11493 getAssignedVariableName() {
11494 return (this.originalId && this.originalId.name) || null;
11495 }
11496 getBaseVariableName() {
11497 const original = this.getOriginalVariable();
11498 if (original === this) {
11499 return super.getBaseVariableName();
11500 }
11501 else {
11502 return original.getBaseVariableName();
11503 }
11504 }
11505 getDirectOriginalVariable() {
11506 return this.originalId &&
11507 (this.hasId ||
11508 !(this.originalId.isPossibleTDZ() ||
11509 this.originalId.variable.isReassigned ||
11510 this.originalId.variable instanceof UndefinedVariable ||
11511 // this avoids a circular dependency
11512 'syntheticNamespace' in this.originalId.variable))
11513 ? this.originalId.variable
11514 : null;
11515 }
11516 getName(getPropertyAccess) {
11517 const original = this.getOriginalVariable();
11518 if (original === this) {
11519 return super.getName(getPropertyAccess);
11520 }
11521 else {
11522 return original.getName(getPropertyAccess);
11523 }
11524 }
11525 getOriginalVariable() {
11526 if (this.originalVariable)
11527 return this.originalVariable;
11528 // eslint-disable-next-line @typescript-eslint/no-this-alias
11529 let original = this;
11530 let currentVariable;
11531 const checkedVariables = new Set();
11532 do {
11533 checkedVariables.add(original);
11534 currentVariable = original;
11535 original = currentVariable.getDirectOriginalVariable();
11536 } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
11537 return (this.originalVariable = original || currentVariable);
11538 }
11539}
11540
11541class ModuleScope extends ChildScope {
11542 constructor(parent, context) {
11543 super(parent);
11544 this.context = context;
11545 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
11546 }
11547 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
11548 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
11549 this.variables.set('default', variable);
11550 return variable;
11551 }
11552 addNamespaceMemberAccess() { }
11553 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
11554 // all module level variables are already deconflicted when deconflicting the chunk
11555 for (const scope of this.children)
11556 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
11557 }
11558 findLexicalBoundary() {
11559 return this;
11560 }
11561 findVariable(name) {
11562 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
11563 if (knownVariable) {
11564 return knownVariable;
11565 }
11566 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
11567 if (variable instanceof GlobalVariable) {
11568 this.accessedOutsideVariables.set(name, variable);
11569 }
11570 return variable;
11571 }
11572}
11573
11574class ThisExpression extends NodeBase {
11575 bind() {
11576 this.variable = this.scope.findVariable('this');
11577 }
11578 deoptimizePath(path) {
11579 this.variable.deoptimizePath(path);
11580 }
11581 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11582 // We rewrite the parameter so that a ThisVariable can detect self-mutations
11583 this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
11584 }
11585 hasEffectsOnInteractionAtPath(path, interaction, context) {
11586 if (path.length === 0) {
11587 return interaction.type !== INTERACTION_ACCESSED;
11588 }
11589 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
11590 }
11591 include() {
11592 if (!this.included) {
11593 this.included = true;
11594 this.context.includeVariableInModule(this.variable);
11595 }
11596 }
11597 initialise() {
11598 this.alias =
11599 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
11600 if (this.alias === 'undefined') {
11601 this.context.warn({
11602 code: 'THIS_IS_UNDEFINED',
11603 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
11604 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
11605 }, this.start);
11606 }
11607 }
11608 render(code) {
11609 if (this.alias !== null) {
11610 code.overwrite(this.start, this.end, this.alias, {
11611 contentOnly: false,
11612 storeName: true
11613 });
11614 }
11615 }
11616}
11617
11618class ThrowStatement extends NodeBase {
11619 hasEffects() {
11620 return true;
11621 }
11622 include(context, includeChildrenRecursively) {
11623 this.included = true;
11624 this.argument.include(context, includeChildrenRecursively);
11625 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11626 }
11627 render(code, options) {
11628 this.argument.render(code, options, { preventASI: true });
11629 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
11630 code.prependLeft(this.start + 5, ' ');
11631 }
11632 }
11633}
11634
11635class TryStatement extends NodeBase {
11636 constructor() {
11637 super(...arguments);
11638 this.directlyIncluded = false;
11639 this.includedLabelsAfterBlock = null;
11640 }
11641 hasEffects(context) {
11642 var _a;
11643 return ((this.context.options.treeshake.tryCatchDeoptimization
11644 ? this.block.body.length > 0
11645 : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11646 }
11647 include(context, includeChildrenRecursively) {
11648 var _a, _b;
11649 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
11650 const { brokenFlow } = context;
11651 if (!this.directlyIncluded || !tryCatchDeoptimization) {
11652 this.included = true;
11653 this.directlyIncluded = true;
11654 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
11655 if (context.includedLabels.size > 0) {
11656 this.includedLabelsAfterBlock = [...context.includedLabels];
11657 }
11658 context.brokenFlow = brokenFlow;
11659 }
11660 else if (this.includedLabelsAfterBlock) {
11661 for (const label of this.includedLabelsAfterBlock) {
11662 context.includedLabels.add(label);
11663 }
11664 }
11665 if (this.handler !== null) {
11666 this.handler.include(context, includeChildrenRecursively);
11667 context.brokenFlow = brokenFlow;
11668 }
11669 (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
11670 }
11671}
11672
11673const unaryOperators = {
11674 '!': value => !value,
11675 '+': value => +value,
11676 '-': value => -value,
11677 delete: () => UnknownValue,
11678 typeof: value => typeof value,
11679 void: () => undefined,
11680 '~': value => ~value
11681};
11682class UnaryExpression extends NodeBase {
11683 getLiteralValueAtPath(path, recursionTracker, origin) {
11684 if (path.length > 0)
11685 return UnknownValue;
11686 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11687 if (typeof argumentValue === 'symbol')
11688 return UnknownValue;
11689 return unaryOperators[this.operator](argumentValue);
11690 }
11691 hasEffects(context) {
11692 if (!this.deoptimized)
11693 this.applyDeoptimizations();
11694 if (this.operator === 'typeof' && this.argument instanceof Identifier)
11695 return false;
11696 return (this.argument.hasEffects(context) ||
11697 (this.operator === 'delete' &&
11698 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
11699 }
11700 hasEffectsOnInteractionAtPath(path, { type }) {
11701 return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
11702 }
11703 applyDeoptimizations() {
11704 this.deoptimized = true;
11705 if (this.operator === 'delete') {
11706 this.argument.deoptimizePath(EMPTY_PATH);
11707 this.context.requestTreeshakingPass();
11708 }
11709 }
11710}
11711
11712class UnknownNode extends NodeBase {
11713 hasEffects() {
11714 return true;
11715 }
11716 include(context) {
11717 super.include(context, true);
11718 }
11719}
11720
11721class UpdateExpression extends NodeBase {
11722 hasEffects(context) {
11723 if (!this.deoptimized)
11724 this.applyDeoptimizations();
11725 return this.argument.hasEffectsAsAssignmentTarget(context, true);
11726 }
11727 hasEffectsOnInteractionAtPath(path, { type }) {
11728 return path.length > 1 || type !== INTERACTION_ACCESSED;
11729 }
11730 include(context, includeChildrenRecursively) {
11731 if (!this.deoptimized)
11732 this.applyDeoptimizations();
11733 this.included = true;
11734 this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
11735 }
11736 initialise() {
11737 this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
11738 }
11739 render(code, options) {
11740 const { exportNamesByVariable, format, snippets: { _ } } = options;
11741 this.argument.render(code, options);
11742 if (format === 'system') {
11743 const variable = this.argument.variable;
11744 const exportNames = exportNamesByVariable.get(variable);
11745 if (exportNames) {
11746 if (this.prefix) {
11747 if (exportNames.length === 1) {
11748 renderSystemExportExpression(variable, this.start, this.end, code, options);
11749 }
11750 else {
11751 renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
11752 }
11753 }
11754 else {
11755 const operator = this.operator[0];
11756 renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
11757 }
11758 }
11759 }
11760 }
11761 applyDeoptimizations() {
11762 this.deoptimized = true;
11763 this.argument.deoptimizePath(EMPTY_PATH);
11764 if (this.argument instanceof Identifier) {
11765 const variable = this.scope.findVariable(this.argument.name);
11766 variable.isReassigned = true;
11767 }
11768 this.context.requestTreeshakingPass();
11769 }
11770}
11771
11772function isReassignedExportsMember(variable, exportNamesByVariable) {
11773 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
11774}
11775
11776function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
11777 for (const declarator of declarations) {
11778 if (!declarator.id.included)
11779 return false;
11780 if (declarator.id.type === Identifier$1) {
11781 if (exportNamesByVariable.has(declarator.id.variable))
11782 return false;
11783 }
11784 else {
11785 const exportedVariables = [];
11786 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
11787 if (exportedVariables.length > 0)
11788 return false;
11789 }
11790 }
11791 return true;
11792}
11793class VariableDeclaration extends NodeBase {
11794 deoptimizePath() {
11795 for (const declarator of this.declarations) {
11796 declarator.deoptimizePath(EMPTY_PATH);
11797 }
11798 }
11799 hasEffectsOnInteractionAtPath() {
11800 return false;
11801 }
11802 include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
11803 this.included = true;
11804 for (const declarator of this.declarations) {
11805 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
11806 declarator.include(context, includeChildrenRecursively);
11807 if (asSingleStatement) {
11808 declarator.id.include(context, includeChildrenRecursively);
11809 }
11810 }
11811 }
11812 initialise() {
11813 for (const declarator of this.declarations) {
11814 declarator.declareDeclarator(this.kind);
11815 }
11816 }
11817 render(code, options, nodeRenderOptions = BLANK) {
11818 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
11819 for (const declarator of this.declarations) {
11820 declarator.render(code, options);
11821 }
11822 if (!nodeRenderOptions.isNoStatement &&
11823 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
11824 code.appendLeft(this.end, ';');
11825 }
11826 }
11827 else {
11828 this.renderReplacedDeclarations(code, options);
11829 }
11830 }
11831 applyDeoptimizations() { }
11832 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
11833 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
11834 code.remove(this.end - 1, this.end);
11835 }
11836 separatorString += ';';
11837 if (lastSeparatorPos !== null) {
11838 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
11839 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
11840 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
11841 actualContentEnd--;
11842 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
11843 actualContentEnd--;
11844 }
11845 }
11846 if (actualContentEnd === lastSeparatorPos + 1) {
11847 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
11848 }
11849 else {
11850 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11851 code.remove(actualContentEnd, renderedContentEnd);
11852 }
11853 }
11854 else {
11855 code.appendLeft(renderedContentEnd, separatorString);
11856 }
11857 if (systemPatternExports.length > 0) {
11858 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
11859 }
11860 }
11861 renderReplacedDeclarations(code, options) {
11862 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
11863 let actualContentEnd, renderedContentEnd;
11864 renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
11865 let lastSeparatorPos = renderedContentEnd - 1;
11866 code.remove(this.start, lastSeparatorPos);
11867 let isInDeclaration = false;
11868 let hasRenderedContent = false;
11869 let separatorString = '', leadingString, nextSeparatorString;
11870 const aggregatedSystemExports = [];
11871 const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
11872 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
11873 if (!node.included) {
11874 code.remove(start, end);
11875 continue;
11876 }
11877 node.render(code, options);
11878 leadingString = '';
11879 nextSeparatorString = '';
11880 if (!node.id.included ||
11881 (node.id instanceof Identifier &&
11882 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
11883 if (hasRenderedContent) {
11884 separatorString += ';';
11885 }
11886 isInDeclaration = false;
11887 }
11888 else {
11889 if (singleSystemExport && singleSystemExport === node.id.variable) {
11890 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
11891 renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
11892 }
11893 if (isInDeclaration) {
11894 separatorString += ',';
11895 }
11896 else {
11897 if (hasRenderedContent) {
11898 separatorString += ';';
11899 }
11900 leadingString += `${this.kind} `;
11901 isInDeclaration = true;
11902 }
11903 }
11904 if (renderedContentEnd === lastSeparatorPos + 1) {
11905 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
11906 }
11907 else {
11908 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11909 code.appendLeft(renderedContentEnd, leadingString);
11910 }
11911 actualContentEnd = contentEnd;
11912 renderedContentEnd = end;
11913 hasRenderedContent = true;
11914 lastSeparatorPos = separator;
11915 separatorString = nextSeparatorString;
11916 }
11917 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
11918 }
11919}
11920function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
11921 var _a;
11922 let singleSystemExport = null;
11923 if (options.format === 'system') {
11924 for (const { node } of separatedNodes) {
11925 if (node.id instanceof Identifier &&
11926 node.init &&
11927 aggregatedSystemExports.length === 0 &&
11928 ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
11929 singleSystemExport = node.id.variable;
11930 aggregatedSystemExports.push(singleSystemExport);
11931 }
11932 else {
11933 node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
11934 }
11935 }
11936 if (aggregatedSystemExports.length > 1) {
11937 singleSystemExport = null;
11938 }
11939 else if (singleSystemExport) {
11940 aggregatedSystemExports.length = 0;
11941 }
11942 }
11943 return singleSystemExport;
11944}
11945
11946class VariableDeclarator extends NodeBase {
11947 declareDeclarator(kind) {
11948 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
11949 }
11950 deoptimizePath(path) {
11951 this.id.deoptimizePath(path);
11952 }
11953 hasEffects(context) {
11954 var _a;
11955 const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
11956 this.id.markDeclarationReached();
11957 return initEffect || this.id.hasEffects(context);
11958 }
11959 include(context, includeChildrenRecursively) {
11960 var _a;
11961 this.included = true;
11962 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11963 this.id.markDeclarationReached();
11964 if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
11965 this.id.include(context, includeChildrenRecursively);
11966 }
11967 }
11968 render(code, options) {
11969 const { exportNamesByVariable, snippets: { _ } } = options;
11970 const renderId = this.id.included;
11971 if (renderId) {
11972 this.id.render(code, options);
11973 }
11974 else {
11975 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
11976 code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
11977 }
11978 if (this.init) {
11979 this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
11980 }
11981 else if (this.id instanceof Identifier &&
11982 isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
11983 code.appendLeft(this.end, `${_}=${_}void 0`);
11984 }
11985 }
11986 applyDeoptimizations() { }
11987}
11988
11989class WhileStatement extends NodeBase {
11990 hasEffects(context) {
11991 if (this.test.hasEffects(context))
11992 return true;
11993 const { brokenFlow, ignore: { breaks, continues } } = context;
11994 context.ignore.breaks = true;
11995 context.ignore.continues = true;
11996 if (this.body.hasEffects(context))
11997 return true;
11998 context.ignore.breaks = breaks;
11999 context.ignore.continues = continues;
12000 context.brokenFlow = brokenFlow;
12001 return false;
12002 }
12003 include(context, includeChildrenRecursively) {
12004 this.included = true;
12005 this.test.include(context, includeChildrenRecursively);
12006 const { brokenFlow } = context;
12007 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
12008 context.brokenFlow = brokenFlow;
12009 }
12010}
12011
12012class YieldExpression extends NodeBase {
12013 hasEffects(context) {
12014 var _a;
12015 if (!this.deoptimized)
12016 this.applyDeoptimizations();
12017 return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
12018 }
12019 render(code, options) {
12020 if (this.argument) {
12021 this.argument.render(code, options, { preventASI: true });
12022 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
12023 code.prependLeft(this.start + 5, ' ');
12024 }
12025 }
12026 }
12027}
12028
12029const nodeConstructors = {
12030 ArrayExpression,
12031 ArrayPattern,
12032 ArrowFunctionExpression,
12033 AssignmentExpression,
12034 AssignmentPattern,
12035 AwaitExpression,
12036 BinaryExpression,
12037 BlockStatement,
12038 BreakStatement,
12039 CallExpression,
12040 CatchClause,
12041 ChainExpression,
12042 ClassBody,
12043 ClassDeclaration,
12044 ClassExpression,
12045 ConditionalExpression,
12046 ContinueStatement,
12047 DoWhileStatement,
12048 EmptyStatement,
12049 ExportAllDeclaration,
12050 ExportDefaultDeclaration,
12051 ExportNamedDeclaration,
12052 ExportSpecifier,
12053 ExpressionStatement,
12054 ForInStatement,
12055 ForOfStatement,
12056 ForStatement,
12057 FunctionDeclaration,
12058 FunctionExpression,
12059 Identifier,
12060 IfStatement,
12061 ImportDeclaration,
12062 ImportDefaultSpecifier,
12063 ImportExpression,
12064 ImportNamespaceSpecifier,
12065 ImportSpecifier,
12066 LabeledStatement,
12067 Literal,
12068 LogicalExpression,
12069 MemberExpression,
12070 MetaProperty,
12071 MethodDefinition,
12072 NewExpression,
12073 ObjectExpression,
12074 ObjectPattern,
12075 PrivateIdentifier,
12076 Program,
12077 Property,
12078 PropertyDefinition,
12079 RestElement,
12080 ReturnStatement,
12081 SequenceExpression,
12082 SpreadElement,
12083 StaticBlock,
12084 Super,
12085 SwitchCase,
12086 SwitchStatement,
12087 TaggedTemplateExpression,
12088 TemplateElement,
12089 TemplateLiteral,
12090 ThisExpression,
12091 ThrowStatement,
12092 TryStatement,
12093 UnaryExpression,
12094 UnknownNode,
12095 UpdateExpression,
12096 VariableDeclaration,
12097 VariableDeclarator,
12098 WhileStatement,
12099 YieldExpression
12100};
12101
12102const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
12103
12104class ExportShimVariable extends Variable {
12105 constructor(module) {
12106 super(MISSING_EXPORT_SHIM_VARIABLE);
12107 this.module = module;
12108 }
12109 include() {
12110 super.include();
12111 this.module.needsExportShim = true;
12112 }
12113}
12114
12115class NamespaceVariable extends Variable {
12116 constructor(context) {
12117 super(context.getModuleName());
12118 this.memberVariables = null;
12119 this.mergedNamespaces = [];
12120 this.referencedEarly = false;
12121 this.references = [];
12122 this.context = context;
12123 this.module = context.module;
12124 }
12125 addReference(identifier) {
12126 this.references.push(identifier);
12127 this.name = identifier.name;
12128 }
12129 getMemberVariables() {
12130 if (this.memberVariables) {
12131 return this.memberVariables;
12132 }
12133 const memberVariables = Object.create(null);
12134 for (const name of this.context.getExports().concat(this.context.getReexports())) {
12135 if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
12136 const exportedVariable = this.context.traceExport(name);
12137 if (exportedVariable) {
12138 memberVariables[name] = exportedVariable;
12139 }
12140 }
12141 }
12142 return (this.memberVariables = memberVariables);
12143 }
12144 include() {
12145 this.included = true;
12146 this.context.includeAllExports();
12147 }
12148 prepare(accessedGlobalsByScope) {
12149 if (this.mergedNamespaces.length > 0) {
12150 this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
12151 }
12152 }
12153 renderBlock(options) {
12154 const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
12155 const memberVariables = this.getMemberVariables();
12156 const members = Object.entries(memberVariables).map(([name, original]) => {
12157 if (this.referencedEarly || original.isReassigned) {
12158 return [
12159 null,
12160 `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
12161 ];
12162 }
12163 return [name, original.getName(getPropertyAccess)];
12164 });
12165 members.unshift([null, `__proto__:${_}null`]);
12166 let output = getObject(members, { lineBreakIndent: { base: '', t } });
12167 if (this.mergedNamespaces.length > 0) {
12168 const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
12169 output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
12170 }
12171 else {
12172 // The helper to merge namespaces will also take care of freezing and toStringTag
12173 if (namespaceToStringTag) {
12174 output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
12175 }
12176 if (freeze) {
12177 output = `/*#__PURE__*/Object.freeze(${output})`;
12178 }
12179 }
12180 const name = this.getName(getPropertyAccess);
12181 output = `${cnst} ${name}${_}=${_}${output};`;
12182 if (format === 'system' && exportNamesByVariable.has(this)) {
12183 output += `${n}${getSystemExportStatement([this], options)};`;
12184 }
12185 return output;
12186 }
12187 renderFirst() {
12188 return this.referencedEarly;
12189 }
12190 setMergedNamespaces(mergedNamespaces) {
12191 this.mergedNamespaces = mergedNamespaces;
12192 const moduleExecIndex = this.context.getModuleExecIndex();
12193 for (const identifier of this.references) {
12194 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
12195 this.referencedEarly = true;
12196 break;
12197 }
12198 }
12199 }
12200}
12201NamespaceVariable.prototype.isNamespace = true;
12202
12203class SyntheticNamedExportVariable extends Variable {
12204 constructor(context, name, syntheticNamespace) {
12205 super(name);
12206 this.baseVariable = null;
12207 this.context = context;
12208 this.module = context.module;
12209 this.syntheticNamespace = syntheticNamespace;
12210 }
12211 getBaseVariable() {
12212 if (this.baseVariable)
12213 return this.baseVariable;
12214 let baseVariable = this.syntheticNamespace;
12215 while (baseVariable instanceof ExportDefaultVariable ||
12216 baseVariable instanceof SyntheticNamedExportVariable) {
12217 if (baseVariable instanceof ExportDefaultVariable) {
12218 const original = baseVariable.getOriginalVariable();
12219 if (original === baseVariable)
12220 break;
12221 baseVariable = original;
12222 }
12223 if (baseVariable instanceof SyntheticNamedExportVariable) {
12224 baseVariable = baseVariable.syntheticNamespace;
12225 }
12226 }
12227 return (this.baseVariable = baseVariable);
12228 }
12229 getBaseVariableName() {
12230 return this.syntheticNamespace.getBaseVariableName();
12231 }
12232 getName(getPropertyAccess) {
12233 return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
12234 }
12235 include() {
12236 this.included = true;
12237 this.context.includeVariableInModule(this.syntheticNamespace);
12238 }
12239 setRenderNames(baseName, name) {
12240 super.setRenderNames(baseName, name);
12241 }
12242}
12243
12244var BuildPhase;
12245(function (BuildPhase) {
12246 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
12247 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
12248 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
12249})(BuildPhase || (BuildPhase = {}));
12250
12251function getId(m) {
12252 return m.id;
12253}
12254
12255function getOriginalLocation(sourcemapChain, location) {
12256 const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
12257 traceSourcemap: while (filteredSourcemapChain.length > 0) {
12258 const sourcemap = filteredSourcemapChain.pop();
12259 const line = sourcemap.mappings[location.line - 1];
12260 if (line) {
12261 const filteredLine = line.filter((segment) => segment.length > 1);
12262 const lastSegment = filteredLine[filteredLine.length - 1];
12263 for (const segment of filteredLine) {
12264 if (segment[0] >= location.column || segment === lastSegment) {
12265 location = {
12266 column: segment[3],
12267 line: segment[2] + 1
12268 };
12269 continue traceSourcemap;
12270 }
12271 }
12272 }
12273 throw new Error("Can't resolve original location of error.");
12274 }
12275 return location;
12276}
12277
12278const NOOP = () => { };
12279let timers = new Map();
12280function getPersistedLabel(label, level) {
12281 switch (level) {
12282 case 1:
12283 return `# ${label}`;
12284 case 2:
12285 return `## ${label}`;
12286 case 3:
12287 return label;
12288 default:
12289 return `${' '.repeat(level - 4)}- ${label}`;
12290 }
12291}
12292function timeStartImpl(label, level = 3) {
12293 label = getPersistedLabel(label, level);
12294 const startMemory = process$1.memoryUsage().heapUsed;
12295 const startTime = perf_hooks.performance.now();
12296 const timer = timers.get(label);
12297 if (timer === undefined) {
12298 timers.set(label, {
12299 memory: 0,
12300 startMemory,
12301 startTime,
12302 time: 0,
12303 totalMemory: 0
12304 });
12305 }
12306 else {
12307 timer.startMemory = startMemory;
12308 timer.startTime = startTime;
12309 }
12310}
12311function timeEndImpl(label, level = 3) {
12312 label = getPersistedLabel(label, level);
12313 const timer = timers.get(label);
12314 if (timer !== undefined) {
12315 const currentMemory = process$1.memoryUsage().heapUsed;
12316 timer.memory += currentMemory - timer.startMemory;
12317 timer.time += perf_hooks.performance.now() - timer.startTime;
12318 timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
12319 }
12320}
12321function getTimings() {
12322 const newTimings = {};
12323 for (const [label, { memory, time, totalMemory }] of timers) {
12324 newTimings[label] = [time, memory, totalMemory];
12325 }
12326 return newTimings;
12327}
12328let timeStart = NOOP;
12329let timeEnd = NOOP;
12330const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
12331function getPluginWithTimers(plugin, index) {
12332 for (const hook of TIMED_PLUGIN_HOOKS) {
12333 if (hook in plugin) {
12334 let timerLabel = `plugin ${index}`;
12335 if (plugin.name) {
12336 timerLabel += ` (${plugin.name})`;
12337 }
12338 timerLabel += ` - ${hook}`;
12339 const func = plugin[hook];
12340 plugin[hook] = function (...args) {
12341 timeStart(timerLabel, 4);
12342 const result = func.apply(this, args);
12343 timeEnd(timerLabel, 4);
12344 if (result && typeof result.then === 'function') {
12345 timeStart(`${timerLabel} (async)`, 4);
12346 return result.then((hookResult) => {
12347 timeEnd(`${timerLabel} (async)`, 4);
12348 return hookResult;
12349 });
12350 }
12351 return result;
12352 };
12353 }
12354 }
12355 return plugin;
12356}
12357function initialiseTimers(inputOptions) {
12358 if (inputOptions.perf) {
12359 timers = new Map();
12360 timeStart = timeStartImpl;
12361 timeEnd = timeEndImpl;
12362 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
12363 }
12364 else {
12365 timeStart = NOOP;
12366 timeEnd = NOOP;
12367 }
12368}
12369
12370function markModuleAndImpureDependenciesAsExecuted(baseModule) {
12371 baseModule.isExecuted = true;
12372 const modules = [baseModule];
12373 const visitedModules = new Set();
12374 for (const module of modules) {
12375 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
12376 if (!(dependency instanceof ExternalModule) &&
12377 !dependency.isExecuted &&
12378 (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
12379 !visitedModules.has(dependency.id)) {
12380 dependency.isExecuted = true;
12381 visitedModules.add(dependency.id);
12382 modules.push(dependency);
12383 }
12384 }
12385 }
12386}
12387
12388const MISSING_EXPORT_SHIM_DESCRIPTION = {
12389 identifier: null,
12390 localName: MISSING_EXPORT_SHIM_VARIABLE
12391};
12392function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
12393 const searchedModules = searchedNamesAndModules.get(name);
12394 if (searchedModules) {
12395 if (searchedModules.has(target)) {
12396 return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
12397 }
12398 searchedModules.add(target);
12399 }
12400 else {
12401 searchedNamesAndModules.set(name, new Set([target]));
12402 }
12403 return target.getVariableForExportName(name, {
12404 importerForSideEffects,
12405 isExportAllSearch,
12406 searchedNamesAndModules
12407 });
12408}
12409function getAndExtendSideEffectModules(variable, module) {
12410 const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
12411 let currentVariable = variable;
12412 const referencedVariables = new Set([currentVariable]);
12413 while (true) {
12414 const importingModule = currentVariable.module;
12415 currentVariable =
12416 currentVariable instanceof ExportDefaultVariable
12417 ? currentVariable.getDirectOriginalVariable()
12418 : currentVariable instanceof SyntheticNamedExportVariable
12419 ? currentVariable.syntheticNamespace
12420 : null;
12421 if (!currentVariable || referencedVariables.has(currentVariable)) {
12422 break;
12423 }
12424 referencedVariables.add(currentVariable);
12425 sideEffectModules.add(importingModule);
12426 const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
12427 if (originalSideEffects) {
12428 for (const module of originalSideEffects) {
12429 sideEffectModules.add(module);
12430 }
12431 }
12432 }
12433 return sideEffectModules;
12434}
12435class Module {
12436 constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
12437 this.graph = graph;
12438 this.id = id;
12439 this.options = options;
12440 this.alternativeReexportModules = new Map();
12441 this.chunkFileNames = new Set();
12442 this.chunkNames = [];
12443 this.cycles = new Set();
12444 this.dependencies = new Set();
12445 this.dynamicDependencies = new Set();
12446 this.dynamicImporters = [];
12447 this.dynamicImports = [];
12448 this.execIndex = Infinity;
12449 this.implicitlyLoadedAfter = new Set();
12450 this.implicitlyLoadedBefore = new Set();
12451 this.importDescriptions = new Map();
12452 this.importMetas = [];
12453 this.importedFromNotTreeshaken = false;
12454 this.importers = [];
12455 this.includedDynamicImporters = [];
12456 this.includedImports = new Set();
12457 this.isExecuted = false;
12458 this.isUserDefinedEntryPoint = false;
12459 this.needsExportShim = false;
12460 this.sideEffectDependenciesByVariable = new Map();
12461 this.sources = new Set();
12462 this.usesTopLevelAwait = false;
12463 this.allExportNames = null;
12464 this.ast = null;
12465 this.exportAllModules = [];
12466 this.exportAllSources = new Set();
12467 this.exportNamesByVariable = null;
12468 this.exportShimVariable = new ExportShimVariable(this);
12469 this.exports = new Map();
12470 this.namespaceReexportsByName = new Map();
12471 this.reexportDescriptions = new Map();
12472 this.relevantDependencies = null;
12473 this.syntheticExports = new Map();
12474 this.syntheticNamespace = null;
12475 this.transformDependencies = [];
12476 this.transitiveReexports = null;
12477 this.excludeFromSourcemap = /\0/.test(id);
12478 this.context = options.moduleContext(id);
12479 this.preserveSignature = this.options.preserveEntrySignatures;
12480 // eslint-disable-next-line @typescript-eslint/no-this-alias
12481 const module = this;
12482 const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
12483 this.info = {
12484 ast: null,
12485 code: null,
12486 get dynamicallyImportedIdResolutions() {
12487 return dynamicImports
12488 .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
12489 .filter(Boolean);
12490 },
12491 get dynamicallyImportedIds() {
12492 // We cannot use this.dynamicDependencies because this is needed before
12493 // dynamicDependencies are populated
12494 return dynamicImports.map(({ id }) => id).filter((id) => id != null);
12495 },
12496 get dynamicImporters() {
12497 return dynamicImporters.sort();
12498 },
12499 get hasDefaultExport() {
12500 // This information is only valid after parsing
12501 if (!module.ast) {
12502 return null;
12503 }
12504 return module.exports.has('default') || reexportDescriptions.has('default');
12505 },
12506 get hasModuleSideEffects() {
12507 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
12508 return this.moduleSideEffects;
12509 },
12510 id,
12511 get implicitlyLoadedAfterOneOf() {
12512 return Array.from(implicitlyLoadedAfter, getId).sort();
12513 },
12514 get implicitlyLoadedBefore() {
12515 return Array.from(implicitlyLoadedBefore, getId).sort();
12516 },
12517 get importedIdResolutions() {
12518 return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
12519 },
12520 get importedIds() {
12521 // We cannot use this.dependencies because this is needed before
12522 // dependencies are populated
12523 return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
12524 },
12525 get importers() {
12526 return importers.sort();
12527 },
12528 isEntry,
12529 isExternal: false,
12530 get isIncluded() {
12531 if (graph.phase !== BuildPhase.GENERATE) {
12532 return null;
12533 }
12534 return module.isIncluded();
12535 },
12536 meta: { ...meta },
12537 moduleSideEffects,
12538 syntheticNamedExports
12539 };
12540 // Hide the deprecated key so that it only warns when accessed explicitly
12541 Object.defineProperty(this.info, 'hasModuleSideEffects', {
12542 enumerable: false
12543 });
12544 }
12545 basename() {
12546 const base = require$$0.basename(this.id);
12547 const ext = require$$0.extname(this.id);
12548 return makeLegal(ext ? base.slice(0, -ext.length) : base);
12549 }
12550 bindReferences() {
12551 this.ast.bind();
12552 }
12553 error(props, pos) {
12554 this.addLocationToLogProps(props, pos);
12555 return error(props);
12556 }
12557 getAllExportNames() {
12558 if (this.allExportNames) {
12559 return this.allExportNames;
12560 }
12561 this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
12562 for (const module of this.exportAllModules) {
12563 if (module instanceof ExternalModule) {
12564 this.allExportNames.add(`*${module.id}`);
12565 continue;
12566 }
12567 for (const name of module.getAllExportNames()) {
12568 if (name !== 'default')
12569 this.allExportNames.add(name);
12570 }
12571 }
12572 // We do not count the synthetic namespace as a regular export to hide it
12573 // from entry signatures and namespace objects
12574 if (typeof this.info.syntheticNamedExports === 'string') {
12575 this.allExportNames.delete(this.info.syntheticNamedExports);
12576 }
12577 return this.allExportNames;
12578 }
12579 getDependenciesToBeIncluded() {
12580 if (this.relevantDependencies)
12581 return this.relevantDependencies;
12582 this.relevantDependencies = new Set();
12583 const necessaryDependencies = new Set();
12584 const alwaysCheckedDependencies = new Set();
12585 const dependencyVariables = new Set(this.includedImports);
12586 if (this.info.isEntry ||
12587 this.includedDynamicImporters.length > 0 ||
12588 this.namespace.included ||
12589 this.implicitlyLoadedAfter.size > 0) {
12590 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
12591 const [exportedVariable] = this.getVariableForExportName(exportName);
12592 if (exportedVariable) {
12593 dependencyVariables.add(exportedVariable);
12594 }
12595 }
12596 }
12597 for (let variable of dependencyVariables) {
12598 const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
12599 if (sideEffectDependencies) {
12600 for (const module of sideEffectDependencies) {
12601 alwaysCheckedDependencies.add(module);
12602 }
12603 }
12604 if (variable instanceof SyntheticNamedExportVariable) {
12605 variable = variable.getBaseVariable();
12606 }
12607 else if (variable instanceof ExportDefaultVariable) {
12608 variable = variable.getOriginalVariable();
12609 }
12610 necessaryDependencies.add(variable.module);
12611 }
12612 if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
12613 for (const dependency of this.dependencies) {
12614 this.relevantDependencies.add(dependency);
12615 }
12616 }
12617 else {
12618 this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
12619 }
12620 for (const dependency of necessaryDependencies) {
12621 this.relevantDependencies.add(dependency);
12622 }
12623 return this.relevantDependencies;
12624 }
12625 getExportNamesByVariable() {
12626 if (this.exportNamesByVariable) {
12627 return this.exportNamesByVariable;
12628 }
12629 const exportNamesByVariable = new Map();
12630 for (const exportName of this.getAllExportNames()) {
12631 let [tracedVariable] = this.getVariableForExportName(exportName);
12632 if (tracedVariable instanceof ExportDefaultVariable) {
12633 tracedVariable = tracedVariable.getOriginalVariable();
12634 }
12635 if (!tracedVariable ||
12636 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
12637 continue;
12638 }
12639 const existingExportNames = exportNamesByVariable.get(tracedVariable);
12640 if (existingExportNames) {
12641 existingExportNames.push(exportName);
12642 }
12643 else {
12644 exportNamesByVariable.set(tracedVariable, [exportName]);
12645 }
12646 }
12647 return (this.exportNamesByVariable = exportNamesByVariable);
12648 }
12649 getExports() {
12650 return Array.from(this.exports.keys());
12651 }
12652 getReexports() {
12653 if (this.transitiveReexports) {
12654 return this.transitiveReexports;
12655 }
12656 // to avoid infinite recursion when using circular `export * from X`
12657 this.transitiveReexports = [];
12658 const reexports = new Set(this.reexportDescriptions.keys());
12659 for (const module of this.exportAllModules) {
12660 if (module instanceof ExternalModule) {
12661 reexports.add(`*${module.id}`);
12662 }
12663 else {
12664 for (const name of [...module.getReexports(), ...module.getExports()]) {
12665 if (name !== 'default')
12666 reexports.add(name);
12667 }
12668 }
12669 }
12670 return (this.transitiveReexports = [...reexports]);
12671 }
12672 getRenderedExports() {
12673 // only direct exports are counted here, not reexports at all
12674 const renderedExports = [];
12675 const removedExports = [];
12676 for (const exportName of this.exports.keys()) {
12677 const [variable] = this.getVariableForExportName(exportName);
12678 (variable && variable.included ? renderedExports : removedExports).push(exportName);
12679 }
12680 return { removedExports, renderedExports };
12681 }
12682 getSyntheticNamespace() {
12683 if (this.syntheticNamespace === null) {
12684 this.syntheticNamespace = undefined;
12685 [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
12686 ? this.info.syntheticNamedExports
12687 : 'default', { onlyExplicit: true });
12688 }
12689 if (!this.syntheticNamespace) {
12690 return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
12691 }
12692 return this.syntheticNamespace;
12693 }
12694 getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
12695 var _a;
12696 if (name[0] === '*') {
12697 if (name.length === 1) {
12698 // export * from './other'
12699 return [this.namespace];
12700 }
12701 // export * from 'external'
12702 const module = this.graph.modulesById.get(name.slice(1));
12703 return module.getVariableForExportName('*');
12704 }
12705 // export { foo } from './other'
12706 const reexportDeclaration = this.reexportDescriptions.get(name);
12707 if (reexportDeclaration) {
12708 const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
12709 if (!variable) {
12710 return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
12711 }
12712 if (importerForSideEffects) {
12713 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12714 }
12715 return [variable];
12716 }
12717 const exportDeclaration = this.exports.get(name);
12718 if (exportDeclaration) {
12719 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
12720 return [this.exportShimVariable];
12721 }
12722 const name = exportDeclaration.localName;
12723 const variable = this.traceVariable(name, {
12724 importerForSideEffects,
12725 searchedNamesAndModules
12726 });
12727 if (importerForSideEffects) {
12728 getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
12729 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12730 }
12731 return [variable];
12732 }
12733 if (onlyExplicit) {
12734 return [null];
12735 }
12736 if (name !== 'default') {
12737 const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
12738 this.namespaceReexportsByName.set(name, foundNamespaceReexport);
12739 if (foundNamespaceReexport[0]) {
12740 return foundNamespaceReexport;
12741 }
12742 }
12743 if (this.info.syntheticNamedExports) {
12744 return [
12745 getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
12746 ];
12747 }
12748 // we don't want to create shims when we are just
12749 // probing export * modules for exports
12750 if (!isExportAllSearch) {
12751 if (this.options.shimMissingExports) {
12752 this.shimMissingExport(name);
12753 return [this.exportShimVariable];
12754 }
12755 }
12756 return [null];
12757 }
12758 hasEffects() {
12759 return (this.info.moduleSideEffects === 'no-treeshake' ||
12760 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
12761 }
12762 include() {
12763 const context = createInclusionContext();
12764 if (this.ast.shouldBeIncluded(context))
12765 this.ast.include(context, false);
12766 }
12767 includeAllExports(includeNamespaceMembers) {
12768 if (!this.isExecuted) {
12769 markModuleAndImpureDependenciesAsExecuted(this);
12770 this.graph.needsTreeshakingPass = true;
12771 }
12772 for (const exportName of this.exports.keys()) {
12773 if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
12774 const variable = this.getVariableForExportName(exportName)[0];
12775 variable.deoptimizePath(UNKNOWN_PATH);
12776 if (!variable.included) {
12777 this.includeVariable(variable);
12778 }
12779 }
12780 }
12781 for (const name of this.getReexports()) {
12782 const [variable] = this.getVariableForExportName(name);
12783 if (variable) {
12784 variable.deoptimizePath(UNKNOWN_PATH);
12785 if (!variable.included) {
12786 this.includeVariable(variable);
12787 }
12788 if (variable instanceof ExternalVariable) {
12789 variable.module.reexported = true;
12790 }
12791 }
12792 }
12793 if (includeNamespaceMembers) {
12794 this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
12795 }
12796 }
12797 includeAllInBundle() {
12798 this.ast.include(createInclusionContext(), true);
12799 this.includeAllExports(false);
12800 }
12801 isIncluded() {
12802 return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
12803 }
12804 linkImports() {
12805 this.addModulesToImportDescriptions(this.importDescriptions);
12806 this.addModulesToImportDescriptions(this.reexportDescriptions);
12807 const externalExportAllModules = [];
12808 for (const source of this.exportAllSources) {
12809 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
12810 if (module instanceof ExternalModule) {
12811 externalExportAllModules.push(module);
12812 continue;
12813 }
12814 this.exportAllModules.push(module);
12815 }
12816 this.exportAllModules.push(...externalExportAllModules);
12817 }
12818 render(options) {
12819 const magicString = this.magicString.clone();
12820 this.ast.render(magicString, options);
12821 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
12822 return magicString;
12823 }
12824 setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
12825 this.info.code = code;
12826 this.originalCode = originalCode;
12827 this.originalSourcemap = originalSourcemap;
12828 this.sourcemapChain = sourcemapChain;
12829 if (transformFiles) {
12830 this.transformFiles = transformFiles;
12831 }
12832 this.transformDependencies = transformDependencies;
12833 this.customTransformCache = customTransformCache;
12834 this.updateOptions(moduleOptions);
12835 timeStart('generate ast', 3);
12836 if (!ast) {
12837 ast = this.tryParse();
12838 }
12839 timeEnd('generate ast', 3);
12840 this.resolvedIds = resolvedIds || Object.create(null);
12841 // By default, `id` is the file name. Custom resolvers and loaders
12842 // can change that, but it makes sense to use it for the source file name
12843 const fileName = this.id;
12844 this.magicString = new MagicString(code, {
12845 filename: (this.excludeFromSourcemap ? null : fileName),
12846 indentExclusionRanges: []
12847 });
12848 timeStart('analyse ast', 3);
12849 this.astContext = {
12850 addDynamicImport: this.addDynamicImport.bind(this),
12851 addExport: this.addExport.bind(this),
12852 addImport: this.addImport.bind(this),
12853 addImportMeta: this.addImportMeta.bind(this),
12854 code,
12855 deoptimizationTracker: this.graph.deoptimizationTracker,
12856 error: this.error.bind(this),
12857 fileName,
12858 getExports: this.getExports.bind(this),
12859 getModuleExecIndex: () => this.execIndex,
12860 getModuleName: this.basename.bind(this),
12861 getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
12862 getReexports: this.getReexports.bind(this),
12863 importDescriptions: this.importDescriptions,
12864 includeAllExports: () => this.includeAllExports(true),
12865 includeDynamicImport: this.includeDynamicImport.bind(this),
12866 includeVariableInModule: this.includeVariableInModule.bind(this),
12867 magicString: this.magicString,
12868 module: this,
12869 moduleContext: this.context,
12870 options: this.options,
12871 requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
12872 traceExport: (name) => this.getVariableForExportName(name)[0],
12873 traceVariable: this.traceVariable.bind(this),
12874 usesTopLevelAwait: false,
12875 warn: this.warn.bind(this)
12876 };
12877 this.scope = new ModuleScope(this.graph.scope, this.astContext);
12878 this.namespace = new NamespaceVariable(this.astContext);
12879 this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
12880 this.info.ast = ast;
12881 timeEnd('analyse ast', 3);
12882 }
12883 toJSON() {
12884 return {
12885 ast: this.ast.esTreeNode,
12886 code: this.info.code,
12887 customTransformCache: this.customTransformCache,
12888 dependencies: Array.from(this.dependencies, getId),
12889 id: this.id,
12890 meta: this.info.meta,
12891 moduleSideEffects: this.info.moduleSideEffects,
12892 originalCode: this.originalCode,
12893 originalSourcemap: this.originalSourcemap,
12894 resolvedIds: this.resolvedIds,
12895 sourcemapChain: this.sourcemapChain,
12896 syntheticNamedExports: this.info.syntheticNamedExports,
12897 transformDependencies: this.transformDependencies,
12898 transformFiles: this.transformFiles
12899 };
12900 }
12901 traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
12902 const localVariable = this.scope.variables.get(name);
12903 if (localVariable) {
12904 return localVariable;
12905 }
12906 const importDeclaration = this.importDescriptions.get(name);
12907 if (importDeclaration) {
12908 const otherModule = importDeclaration.module;
12909 if (otherModule instanceof Module && importDeclaration.name === '*') {
12910 return otherModule.namespace;
12911 }
12912 const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
12913 if (!declaration) {
12914 return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
12915 }
12916 return declaration;
12917 }
12918 return null;
12919 }
12920 tryParse() {
12921 try {
12922 return this.graph.contextParse(this.info.code);
12923 }
12924 catch (err) {
12925 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
12926 if (this.id.endsWith('.json')) {
12927 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
12928 }
12929 else if (!this.id.endsWith('.js')) {
12930 message += ' (Note that you need plugins to import files that are not JavaScript)';
12931 }
12932 return this.error({
12933 code: 'PARSE_ERROR',
12934 message,
12935 parserError: err
12936 }, err.pos);
12937 }
12938 }
12939 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
12940 if (moduleSideEffects != null) {
12941 this.info.moduleSideEffects = moduleSideEffects;
12942 }
12943 if (syntheticNamedExports != null) {
12944 this.info.syntheticNamedExports = syntheticNamedExports;
12945 }
12946 if (meta != null) {
12947 Object.assign(this.info.meta, meta);
12948 }
12949 }
12950 warn(props, pos) {
12951 this.addLocationToLogProps(props, pos);
12952 this.options.onwarn(props);
12953 }
12954 addDynamicImport(node) {
12955 let argument = node.source;
12956 if (argument instanceof TemplateLiteral) {
12957 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
12958 argument = argument.quasis[0].value.cooked;
12959 }
12960 }
12961 else if (argument instanceof Literal && typeof argument.value === 'string') {
12962 argument = argument.value;
12963 }
12964 this.dynamicImports.push({ argument, id: null, node, resolution: null });
12965 }
12966 addExport(node) {
12967 if (node instanceof ExportDefaultDeclaration) {
12968 // export default foo;
12969 this.exports.set('default', {
12970 identifier: node.variable.getAssignedVariableName(),
12971 localName: 'default'
12972 });
12973 }
12974 else if (node instanceof ExportAllDeclaration) {
12975 const source = node.source.value;
12976 this.sources.add(source);
12977 if (node.exported) {
12978 // export * as name from './other'
12979 const name = node.exported.name;
12980 this.reexportDescriptions.set(name, {
12981 localName: '*',
12982 module: null,
12983 source,
12984 start: node.start
12985 });
12986 }
12987 else {
12988 // export * from './other'
12989 this.exportAllSources.add(source);
12990 }
12991 }
12992 else if (node.source instanceof Literal) {
12993 // export { name } from './other'
12994 const source = node.source.value;
12995 this.sources.add(source);
12996 for (const specifier of node.specifiers) {
12997 const name = specifier.exported.name;
12998 this.reexportDescriptions.set(name, {
12999 localName: specifier.local.name,
13000 module: null,
13001 source,
13002 start: specifier.start
13003 });
13004 }
13005 }
13006 else if (node.declaration) {
13007 const declaration = node.declaration;
13008 if (declaration instanceof VariableDeclaration) {
13009 // export var { foo, bar } = ...
13010 // export var foo = 1, bar = 2;
13011 for (const declarator of declaration.declarations) {
13012 for (const localName of extractAssignedNames(declarator.id)) {
13013 this.exports.set(localName, { identifier: null, localName });
13014 }
13015 }
13016 }
13017 else {
13018 // export function foo () {}
13019 const localName = declaration.id.name;
13020 this.exports.set(localName, { identifier: null, localName });
13021 }
13022 }
13023 else {
13024 // export { foo, bar, baz }
13025 for (const specifier of node.specifiers) {
13026 const localName = specifier.local.name;
13027 const exportedName = specifier.exported.name;
13028 this.exports.set(exportedName, { identifier: null, localName });
13029 }
13030 }
13031 }
13032 addImport(node) {
13033 const source = node.source.value;
13034 this.sources.add(source);
13035 for (const specifier of node.specifiers) {
13036 const isDefault = specifier.type === ImportDefaultSpecifier$1;
13037 const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
13038 const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
13039 this.importDescriptions.set(specifier.local.name, {
13040 module: null,
13041 name,
13042 source,
13043 start: specifier.start
13044 });
13045 }
13046 }
13047 addImportMeta(node) {
13048 this.importMetas.push(node);
13049 }
13050 addLocationToLogProps(props, pos) {
13051 props.id = this.id;
13052 props.pos = pos;
13053 let code = this.info.code;
13054 const location = locate(code, pos, { offsetLine: 1 });
13055 if (location) {
13056 let { column, line } = location;
13057 try {
13058 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
13059 code = this.originalCode;
13060 }
13061 catch (err) {
13062 this.options.onwarn({
13063 code: 'SOURCEMAP_ERROR',
13064 id: this.id,
13065 loc: {
13066 column,
13067 file: this.id,
13068 line
13069 },
13070 message: `Error when using sourcemap for reporting an error: ${err.message}`,
13071 pos
13072 });
13073 }
13074 augmentCodeLocation(props, { column, line }, code, this.id);
13075 }
13076 }
13077 addModulesToImportDescriptions(importDescription) {
13078 for (const specifier of importDescription.values()) {
13079 const { id } = this.resolvedIds[specifier.source];
13080 specifier.module = this.graph.modulesById.get(id);
13081 }
13082 }
13083 addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
13084 const handledDependencies = new Set();
13085 const addSideEffectDependencies = (possibleDependencies) => {
13086 for (const dependency of possibleDependencies) {
13087 if (handledDependencies.has(dependency)) {
13088 continue;
13089 }
13090 handledDependencies.add(dependency);
13091 if (necessaryDependencies.has(dependency)) {
13092 relevantDependencies.add(dependency);
13093 continue;
13094 }
13095 if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
13096 continue;
13097 }
13098 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
13099 relevantDependencies.add(dependency);
13100 continue;
13101 }
13102 addSideEffectDependencies(dependency.dependencies);
13103 }
13104 };
13105 addSideEffectDependencies(this.dependencies);
13106 addSideEffectDependencies(alwaysCheckedDependencies);
13107 }
13108 getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
13109 let foundSyntheticDeclaration = null;
13110 const foundInternalDeclarations = new Map();
13111 const foundExternalDeclarations = new Set();
13112 for (const module of this.exportAllModules) {
13113 // Synthetic namespaces should not hide "regular" exports of the same name
13114 if (module.info.syntheticNamedExports === name) {
13115 continue;
13116 }
13117 const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
13118 // We are creating a copy to handle the case where the same binding is
13119 // imported through different namespace reexports gracefully
13120 copyNameToModulesMap(searchedNamesAndModules));
13121 if (module instanceof ExternalModule || indirectExternal) {
13122 foundExternalDeclarations.add(variable);
13123 }
13124 else if (variable instanceof SyntheticNamedExportVariable) {
13125 if (!foundSyntheticDeclaration) {
13126 foundSyntheticDeclaration = variable;
13127 }
13128 }
13129 else if (variable) {
13130 foundInternalDeclarations.set(variable, module);
13131 }
13132 }
13133 if (foundInternalDeclarations.size > 0) {
13134 const foundDeclarationList = [...foundInternalDeclarations];
13135 const usedDeclaration = foundDeclarationList[0][0];
13136 if (foundDeclarationList.length === 1) {
13137 return [usedDeclaration];
13138 }
13139 this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
13140 // TODO we are pretending it was not found while it should behave like "undefined"
13141 return [null];
13142 }
13143 if (foundExternalDeclarations.size > 0) {
13144 const foundDeclarationList = [...foundExternalDeclarations];
13145 const usedDeclaration = foundDeclarationList[0];
13146 if (foundDeclarationList.length > 1) {
13147 this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
13148 }
13149 return [usedDeclaration, true];
13150 }
13151 if (foundSyntheticDeclaration) {
13152 return [foundSyntheticDeclaration];
13153 }
13154 return [null];
13155 }
13156 includeAndGetAdditionalMergedNamespaces() {
13157 const externalNamespaces = new Set();
13158 const syntheticNamespaces = new Set();
13159 for (const module of [this, ...this.exportAllModules]) {
13160 if (module instanceof ExternalModule) {
13161 const [externalVariable] = module.getVariableForExportName('*');
13162 externalVariable.include();
13163 this.includedImports.add(externalVariable);
13164 externalNamespaces.add(externalVariable);
13165 }
13166 else if (module.info.syntheticNamedExports) {
13167 const syntheticNamespace = module.getSyntheticNamespace();
13168 syntheticNamespace.include();
13169 this.includedImports.add(syntheticNamespace);
13170 syntheticNamespaces.add(syntheticNamespace);
13171 }
13172 }
13173 return [...syntheticNamespaces, ...externalNamespaces];
13174 }
13175 includeDynamicImport(node) {
13176 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
13177 if (resolution instanceof Module) {
13178 resolution.includedDynamicImporters.push(this);
13179 resolution.includeAllExports(true);
13180 }
13181 }
13182 includeVariable(variable) {
13183 if (!variable.included) {
13184 variable.include();
13185 this.graph.needsTreeshakingPass = true;
13186 const variableModule = variable.module;
13187 if (variableModule instanceof Module) {
13188 if (!variableModule.isExecuted) {
13189 markModuleAndImpureDependenciesAsExecuted(variableModule);
13190 }
13191 if (variableModule !== this) {
13192 const sideEffectModules = getAndExtendSideEffectModules(variable, this);
13193 for (const module of sideEffectModules) {
13194 if (!module.isExecuted) {
13195 markModuleAndImpureDependenciesAsExecuted(module);
13196 }
13197 }
13198 }
13199 }
13200 }
13201 }
13202 includeVariableInModule(variable) {
13203 this.includeVariable(variable);
13204 const variableModule = variable.module;
13205 if (variableModule && variableModule !== this) {
13206 this.includedImports.add(variable);
13207 }
13208 }
13209 shimMissingExport(name) {
13210 this.options.onwarn({
13211 code: 'SHIMMED_EXPORT',
13212 exporter: relativeId(this.id),
13213 exportName: name,
13214 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
13215 });
13216 this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
13217 }
13218}
13219// if there is a cyclic import in the reexport chain, we should not
13220// import from the original module but from the cyclic module to not
13221// mess up execution order.
13222function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
13223 if (variable.module instanceof Module && variable.module !== reexporter) {
13224 const exporterCycles = variable.module.cycles;
13225 if (exporterCycles.size > 0) {
13226 const importerCycles = reexporter.cycles;
13227 for (const cycleSymbol of importerCycles) {
13228 if (exporterCycles.has(cycleSymbol)) {
13229 importer.alternativeReexportModules.set(variable, reexporter);
13230 break;
13231 }
13232 }
13233 }
13234 }
13235}
13236const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
13237 new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
13238
13239function removeJsExtension(name) {
13240 return name.endsWith('.js') ? name.slice(0, -3) : name;
13241}
13242
13243function getCompleteAmdId(options, chunkId) {
13244 if (options.autoId) {
13245 return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
13246 }
13247 return options.id || '';
13248}
13249
13250function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
13251 const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
13252 if (!namedExportsMode) {
13253 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
13254 }
13255 let exportBlock = '';
13256 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13257 if (reexports && namedExportsMode) {
13258 for (const specifier of reexports) {
13259 if (specifier.reexported !== '*') {
13260 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13261 if (exportBlock)
13262 exportBlock += n;
13263 if (specifier.imported !== '*' && specifier.needsLiveBinding) {
13264 const [left, right] = getDirectReturnFunction([], {
13265 functionReturn: true,
13266 lineBreakIndent: null,
13267 name: null
13268 });
13269 exportBlock +=
13270 `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
13271 `${t}enumerable:${_}true,${n}` +
13272 `${t}get:${_}${left}${importName}${right}${n}});`;
13273 }
13274 else {
13275 exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
13276 }
13277 }
13278 }
13279 }
13280 }
13281 for (const { exported, local } of exports) {
13282 const lhs = `exports${getPropertyAccess(exported)}`;
13283 const rhs = local;
13284 if (lhs !== rhs) {
13285 if (exportBlock)
13286 exportBlock += n;
13287 exportBlock += `${lhs}${_}=${_}${rhs};`;
13288 }
13289 }
13290 for (const { name, reexports } of dependencies) {
13291 if (reexports && namedExportsMode) {
13292 for (const specifier of reexports) {
13293 if (specifier.reexported === '*') {
13294 if (exportBlock)
13295 exportBlock += n;
13296 const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
13297 exportBlock +=
13298 cnst === 'var' && specifier.needsLiveBinding
13299 ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
13300 isAsync: false,
13301 name: null
13302 })}${copyPropertyIfNecessary});`
13303 : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
13304 }
13305 }
13306 }
13307 }
13308 if (exportBlock) {
13309 return `${n}${n}${exportBlock}`;
13310 }
13311 return '';
13312}
13313function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
13314 if (exports.length > 0) {
13315 return exports[0].local;
13316 }
13317 else {
13318 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13319 if (reexports) {
13320 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13321 }
13322 }
13323 }
13324}
13325function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
13326 if (imported === 'default') {
13327 if (!isChunk) {
13328 const moduleInterop = String(interop(moduleId));
13329 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
13330 ? defaultVariableName
13331 : moduleVariableName;
13332 return isDefaultAProperty(moduleInterop, externalLiveBindings)
13333 ? `${variableName}${getPropertyAccess('default')}`
13334 : variableName;
13335 }
13336 return depNamedExportsMode
13337 ? `${moduleVariableName}${getPropertyAccess('default')}`
13338 : moduleVariableName;
13339 }
13340 if (imported === '*') {
13341 return (isChunk
13342 ? !depNamedExportsMode
13343 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
13344 ? namespaceVariableName
13345 : moduleVariableName;
13346 }
13347 return `${moduleVariableName}${getPropertyAccess(imported)}`;
13348}
13349function getEsModuleValue(getObject) {
13350 return getObject([['value', 'true']], {
13351 lineBreakIndent: null
13352 });
13353}
13354function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
13355 if (hasNamedExports) {
13356 if (addEsModule) {
13357 if (addNamespaceToStringTag) {
13358 return `Object.defineProperties(exports,${_}${getObject([
13359 ['__esModule', getEsModuleValue(getObject)],
13360 [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
13361 ], {
13362 lineBreakIndent: null
13363 })});`;
13364 }
13365 return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
13366 }
13367 if (addNamespaceToStringTag) {
13368 return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
13369 }
13370 }
13371 return '';
13372}
13373const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
13374 if (needsLiveBinding) {
13375 const [left, right] = getDirectReturnFunction([], {
13376 functionReturn: true,
13377 lineBreakIndent: null,
13378 name: null
13379 });
13380 return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
13381 `${t}${t}enumerable:${_}true,${n}` +
13382 `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
13383 }
13384 return `exports[k]${_}=${_}${name}[k]`;
13385};
13386
13387function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
13388 const { _, cnst, n } = snippets;
13389 const neededInteropHelpers = new Set();
13390 const interopStatements = [];
13391 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
13392 neededInteropHelpers.add(helper);
13393 interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
13394 };
13395 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13396 if (isChunk) {
13397 for (const { imported, reexported } of [
13398 ...(imports || []),
13399 ...(reexports || [])
13400 ]) {
13401 if (imported === '*' && reexported !== '*') {
13402 if (!namedExportsMode) {
13403 addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
13404 }
13405 break;
13406 }
13407 }
13408 }
13409 else {
13410 const moduleInterop = String(interop(id));
13411 let hasDefault = false;
13412 let hasNamespace = false;
13413 for (const { imported, reexported } of [
13414 ...(imports || []),
13415 ...(reexports || [])
13416 ]) {
13417 let helper;
13418 let variableName;
13419 if (imported === 'default') {
13420 if (!hasDefault) {
13421 hasDefault = true;
13422 if (defaultVariableName !== namespaceVariableName) {
13423 variableName = defaultVariableName;
13424 helper = defaultInteropHelpersByInteropType[moduleInterop];
13425 }
13426 }
13427 }
13428 else if (imported === '*' && reexported !== '*') {
13429 if (!hasNamespace) {
13430 hasNamespace = true;
13431 helper = namespaceInteropHelpersByInteropType[moduleInterop];
13432 variableName = namespaceVariableName;
13433 }
13434 }
13435 if (helper) {
13436 addInteropStatement(variableName, helper, name);
13437 }
13438 }
13439 }
13440 }
13441 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
13442}
13443
13444// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
13445// The assumption is that this makes sense for all relative ids:
13446// https://requirejs.org/docs/api.html#jsfiles
13447function removeExtensionFromRelativeAmdId(id) {
13448 return id[0] === '.' ? removeJsExtension(id) : id;
13449}
13450
13451const builtins = {
13452 assert: true,
13453 buffer: true,
13454 console: true,
13455 constants: true,
13456 domain: true,
13457 events: true,
13458 http: true,
13459 https: true,
13460 os: true,
13461 path: true,
13462 process: true,
13463 punycode: true,
13464 querystring: true,
13465 stream: true,
13466 string_decoder: true,
13467 timers: true,
13468 tty: true,
13469 url: true,
13470 util: true,
13471 vm: true,
13472 zlib: true
13473};
13474function warnOnBuiltins(warn, dependencies) {
13475 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
13476 if (!externalBuiltins.length)
13477 return;
13478 warn({
13479 code: 'MISSING_NODE_BUILTINS',
13480 message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`,
13481 modules: externalBuiltins
13482 });
13483}
13484
13485function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13486 warnOnBuiltins(warn, dependencies);
13487 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13488 const args = dependencies.map(m => m.name);
13489 const { n, getNonArrowFunctionIntro, _ } = snippets;
13490 if (namedExportsMode && hasExports) {
13491 args.unshift(`exports`);
13492 deps.unshift(`'exports'`);
13493 }
13494 if (accessedGlobals.has('require')) {
13495 args.unshift('require');
13496 deps.unshift(`'require'`);
13497 }
13498 if (accessedGlobals.has('module')) {
13499 args.unshift('module');
13500 deps.unshift(`'module'`);
13501 }
13502 const completeAmdId = getCompleteAmdId(amd, id);
13503 const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13504 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
13505 const useStrict = strict ? `${_}'use strict';` : '';
13506 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
13507 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13508 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13509 if (namespaceMarkers) {
13510 namespaceMarkers = n + n + namespaceMarkers;
13511 }
13512 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13513 return (magicString
13514 .indent(t)
13515 // factory function should be wrapped by parentheses to avoid lazy parsing,
13516 // cf. https://v8.dev/blog/preparser#pife
13517 .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
13518 isAsync: false,
13519 name: null
13520 })}{${useStrict}${n}${n}`)
13521 .append(`${n}${n}}));`));
13522}
13523
13524function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13525 const { _, n } = snippets;
13526 const useStrict = strict ? `'use strict';${n}${n}` : '';
13527 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13528 if (namespaceMarkers) {
13529 namespaceMarkers += n + n;
13530 }
13531 const importBlock = getImportBlock$1(dependencies, snippets, compact);
13532 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13533 magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
13534 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
13535 return magicString.append(`${exportBlock}${outro}`);
13536}
13537function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
13538 let importBlock = '';
13539 let definingVariable = false;
13540 for (const { id, name, reexports, imports } of dependencies) {
13541 if (!reexports && !imports) {
13542 if (importBlock) {
13543 importBlock += compact && !definingVariable ? ',' : `;${n}`;
13544 }
13545 definingVariable = false;
13546 importBlock += `require('${id}')`;
13547 }
13548 else {
13549 importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
13550 definingVariable = true;
13551 importBlock += `${name}${_}=${_}require('${id}')`;
13552 }
13553 }
13554 if (importBlock) {
13555 return `${importBlock};${n}${n}`;
13556 }
13557 return '';
13558}
13559
13560function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
13561 const { _, n } = snippets;
13562 const importBlock = getImportBlock(dependencies, _);
13563 if (importBlock.length > 0)
13564 intro += importBlock.join(n) + n + n;
13565 intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
13566 if (intro)
13567 magicString.prepend(intro);
13568 const exportBlock = getExportBlock(exports, snippets);
13569 if (exportBlock.length)
13570 magicString.append(n + n + exportBlock.join(n).trim());
13571 if (outro)
13572 magicString.append(outro);
13573 return magicString.trim();
13574}
13575function getImportBlock(dependencies, _) {
13576 const importBlock = [];
13577 for (const { id, reexports, imports, name } of dependencies) {
13578 if (!reexports && !imports) {
13579 importBlock.push(`import${_}'${id}';`);
13580 continue;
13581 }
13582 if (imports) {
13583 let defaultImport = null;
13584 let starImport = null;
13585 const importedNames = [];
13586 for (const specifier of imports) {
13587 if (specifier.imported === 'default') {
13588 defaultImport = specifier;
13589 }
13590 else if (specifier.imported === '*') {
13591 starImport = specifier;
13592 }
13593 else {
13594 importedNames.push(specifier);
13595 }
13596 }
13597 if (starImport) {
13598 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
13599 }
13600 if (defaultImport && importedNames.length === 0) {
13601 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
13602 }
13603 else if (importedNames.length > 0) {
13604 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
13605 .map(specifier => {
13606 if (specifier.imported === specifier.local) {
13607 return specifier.imported;
13608 }
13609 else {
13610 return `${specifier.imported} as ${specifier.local}`;
13611 }
13612 })
13613 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13614 }
13615 }
13616 if (reexports) {
13617 let starExport = null;
13618 const namespaceReexports = [];
13619 const namedReexports = [];
13620 for (const specifier of reexports) {
13621 if (specifier.reexported === '*') {
13622 starExport = specifier;
13623 }
13624 else if (specifier.imported === '*') {
13625 namespaceReexports.push(specifier);
13626 }
13627 else {
13628 namedReexports.push(specifier);
13629 }
13630 }
13631 if (starExport) {
13632 importBlock.push(`export${_}*${_}from${_}'${id}';`);
13633 }
13634 if (namespaceReexports.length > 0) {
13635 if (!imports ||
13636 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
13637 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
13638 }
13639 for (const specifier of namespaceReexports) {
13640 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
13641 }
13642 }
13643 if (namedReexports.length > 0) {
13644 importBlock.push(`export${_}{${_}${namedReexports
13645 .map(specifier => {
13646 if (specifier.imported === specifier.reexported) {
13647 return specifier.imported;
13648 }
13649 else {
13650 return `${specifier.imported} as ${specifier.reexported}`;
13651 }
13652 })
13653 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13654 }
13655 }
13656 }
13657 return importBlock;
13658}
13659function getExportBlock(exports, { _, cnst }) {
13660 const exportBlock = [];
13661 const exportDeclaration = [];
13662 for (const specifier of exports) {
13663 if (specifier.expression) {
13664 exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
13665 }
13666 exportDeclaration.push(specifier.exported === specifier.local
13667 ? specifier.local
13668 : `${specifier.local} as ${specifier.exported}`);
13669 }
13670 if (exportDeclaration.length) {
13671 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
13672 }
13673 return exportBlock;
13674}
13675
13676const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
13677
13678function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
13679 const parts = name.split('.');
13680 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13681 parts.pop();
13682 let propertyPath = root;
13683 return (parts
13684 .map(part => {
13685 propertyPath += getPropertyAccess(part);
13686 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
13687 })
13688 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
13689}
13690function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
13691 const parts = deepName.split('.');
13692 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13693 const last = parts.pop();
13694 let propertyPath = root;
13695 let deepAssignment = parts
13696 .map(part => {
13697 propertyPath += getPropertyAccess(part);
13698 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
13699 })
13700 .concat(`${propertyPath}${getPropertyAccess(last)}`)
13701 .join(`,${_}`) + `${_}=${_}${assignment}`;
13702 if (parts.length > 0) {
13703 deepAssignment = `(${deepAssignment})`;
13704 }
13705 return deepAssignment;
13706}
13707
13708function trimEmptyImports(dependencies) {
13709 let i = dependencies.length;
13710 while (i--) {
13711 const { imports, reexports } = dependencies[i];
13712 if (imports || reexports) {
13713 return dependencies.slice(0, i + 1);
13714 }
13715 }
13716 return [];
13717}
13718
13719function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13720 const { _, cnst, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
13721 const isNamespaced = name && name.includes('.');
13722 const useVariableAssignment = !extend && !isNamespaced;
13723 if (name && useVariableAssignment && !isLegal(name)) {
13724 return error({
13725 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
13726 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
13727 });
13728 }
13729 warnOnBuiltins(warn, dependencies);
13730 const external = trimEmptyImports(dependencies);
13731 const deps = external.map(dep => dep.globalName || 'null');
13732 const args = external.map(m => m.name);
13733 if (hasExports && !name) {
13734 warn({
13735 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13736 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
13737 });
13738 }
13739 if (namedExportsMode && hasExports) {
13740 if (extend) {
13741 deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
13742 args.unshift('exports');
13743 }
13744 else {
13745 deps.unshift('{}');
13746 args.unshift('exports');
13747 }
13748 }
13749 const useStrict = strict ? `${t}'use strict';${n}` : '';
13750 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13751 magicString.prepend(`${intro}${interopBlock}`);
13752 let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
13753 isAsync: false,
13754 name: null
13755 })}{${n}${useStrict}${n}`;
13756 if (hasExports) {
13757 if (name && !(extend && namedExportsMode)) {
13758 wrapperIntro =
13759 (useVariableAssignment ? `${cnst} ${name}` : `this${keypath(name, getPropertyAccess)}`) +
13760 `${_}=${_}${wrapperIntro}`;
13761 }
13762 if (isNamespaced) {
13763 wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
13764 }
13765 }
13766 let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
13767 if (hasExports && !extend && namedExportsMode) {
13768 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
13769 }
13770 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13771 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
13772 if (namespaceMarkers) {
13773 namespaceMarkers = n + n + namespaceMarkers;
13774 }
13775 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13776 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
13777}
13778
13779function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
13780 const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
13781 const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
13782 const registeredName = name ? `'${name}',${_}` : '';
13783 const wrapperParams = accessedGlobals.has('module')
13784 ? ['exports', 'module']
13785 : hasExports
13786 ? ['exports']
13787 : [];
13788 // factory function should be wrapped by parentheses to avoid lazy parsing,
13789 // cf. https://v8.dev/blog/preparser#pife
13790 let wrapperStart = `System.register(${registeredName}[` +
13791 dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
13792 `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13793 getStarExcludesBlock(starExcludes, t, snippets) +
13794 getImportBindingsBlock(importBindings, t, snippets) +
13795 `${n}${t}return${_}{${setters.length
13796 ? `${n}${t}${t}setters:${_}[${setters
13797 .map(setter => setter
13798 ? `${getFunctionIntro(['module'], {
13799 isAsync: false,
13800 name: null
13801 })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
13802 : systemNullSetters
13803 ? `null`
13804 : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
13805 .join(`,${_}`)}],`
13806 : ''}${n}`;
13807 wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
13808 isAsync: usesTopLevelAwait,
13809 name: null
13810 })}{${n}${n}`;
13811 const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
13812 magicString.prepend(intro +
13813 getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
13814 getHoistedExportsBlock(exports, t, snippets));
13815 magicString.append(`${outro}${n}${n}` +
13816 getSyntheticExportsBlock(exports, t, snippets) +
13817 getMissingExportsBlock(exports, t, snippets));
13818 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
13819}
13820function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
13821 const importBindings = [];
13822 const setters = [];
13823 let starExcludes = null;
13824 for (const { imports, reexports } of dependencies) {
13825 const setter = [];
13826 if (imports) {
13827 for (const specifier of imports) {
13828 importBindings.push(specifier.local);
13829 if (specifier.imported === '*') {
13830 setter.push(`${specifier.local}${_}=${_}module;`);
13831 }
13832 else {
13833 setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
13834 }
13835 }
13836 }
13837 if (reexports) {
13838 const reexportedNames = [];
13839 let hasStarReexport = false;
13840 for (const { imported, reexported } of reexports) {
13841 if (reexported === '*') {
13842 hasStarReexport = true;
13843 }
13844 else {
13845 reexportedNames.push([
13846 reexported,
13847 imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
13848 ]);
13849 }
13850 }
13851 if (reexportedNames.length > 1 || hasStarReexport) {
13852 const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
13853 if (hasStarReexport) {
13854 if (!starExcludes) {
13855 starExcludes = getStarExcludes({ dependencies, exports });
13856 }
13857 setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
13858 }
13859 else {
13860 setter.push(`exports(${exportMapping});`);
13861 }
13862 }
13863 else {
13864 const [key, value] = reexportedNames[0];
13865 setter.push(`exports('${key}',${_}${value});`);
13866 }
13867 }
13868 setters.push(setter.join(`${n}${t}${t}${t}`));
13869 }
13870 return { importBindings, setters, starExcludes };
13871}
13872const getStarExcludes = ({ dependencies, exports }) => {
13873 const starExcludes = new Set(exports.map(expt => expt.exported));
13874 starExcludes.add('default');
13875 for (const { reexports } of dependencies) {
13876 if (reexports) {
13877 for (const reexport of reexports) {
13878 if (reexport.reexported !== '*')
13879 starExcludes.add(reexport.reexported);
13880 }
13881 }
13882 }
13883 return starExcludes;
13884};
13885const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
13886 ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
13887 : '';
13888const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
13889const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13890function getExportsBlock(exports, t, { _, n }) {
13891 if (exports.length === 0) {
13892 return '';
13893 }
13894 if (exports.length === 1) {
13895 return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
13896 }
13897 return (`exports({${n}` +
13898 exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
13899 `${n}});${n}${n}`);
13900}
13901const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13902 .filter(expt => expt.expression)
13903 .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13904const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13905 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
13906 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
13907
13908function globalProp(name, globalVar, getPropertyAccess) {
13909 if (!name)
13910 return 'null';
13911 return `${globalVar}${keypath(name, getPropertyAccess)}`;
13912}
13913function safeAccess(name, globalVar, { _, getPropertyAccess }) {
13914 let propertyPath = globalVar;
13915 return name
13916 .split('.')
13917 .map(part => (propertyPath += getPropertyAccess(part)))
13918 .join(`${_}&&${_}`);
13919}
13920function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
13921 const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
13922 const factoryVar = compact ? 'f' : 'factory';
13923 const globalVar = compact ? 'g' : 'global';
13924 if (hasExports && !name) {
13925 return error({
13926 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13927 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
13928 });
13929 }
13930 warnOnBuiltins(warn, dependencies);
13931 const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13932 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
13933 const trimmedImports = trimEmptyImports(dependencies);
13934 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
13935 const factoryParams = trimmedImports.map(m => m.name);
13936 if (namedExportsMode && (hasExports || noConflict)) {
13937 amdDeps.unshift(`'exports'`);
13938 cjsDeps.unshift(`exports`);
13939 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
13940 factoryParams.unshift('exports');
13941 }
13942 const completeAmdId = getCompleteAmdId(amd, id);
13943 const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13944 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
13945 const define = amd.define;
13946 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
13947 const useStrict = strict ? `${_}'use strict';${n}` : ``;
13948 let iifeExport;
13949 if (noConflict) {
13950 const noConflictExportsVar = compact ? 'e' : 'exports';
13951 let factory;
13952 if (!namedExportsMode && hasExports) {
13953 factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
13954 }
13955 else {
13956 const module = globalDeps.shift();
13957 factory =
13958 `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
13959 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
13960 }
13961 iifeExport =
13962 `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
13963 `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
13964 `${t}${t}${factory}${n}` +
13965 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
13966 isAsync: false,
13967 name: null
13968 })}{${_}` +
13969 `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
13970 `${t}})()`;
13971 }
13972 else {
13973 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
13974 if (!namedExportsMode && hasExports) {
13975 iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
13976 }
13977 }
13978 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
13979 const wrapperParams = [factoryVar];
13980 if (iifeNeedsGlobal) {
13981 wrapperParams.unshift(globalVar);
13982 }
13983 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
13984 const iifeStart = iifeNeedsGlobal
13985 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
13986 : '';
13987 const iifeEnd = iifeNeedsGlobal ? ')' : '';
13988 const cjsIntro = iifeNeedsGlobal
13989 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
13990 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
13991 : '';
13992 const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
13993 cjsIntro +
13994 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
13995 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
13996 // factory function should be wrapped by parentheses to avoid lazy parsing,
13997 // cf. https://v8.dev/blog/preparser#pife
13998 `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
13999 isAsync: false,
14000 name: null
14001 })}{${useStrict}${n}`;
14002 const wrapperOutro = n + n + '}));';
14003 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
14004 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
14005 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
14006 if (namespaceMarkers) {
14007 namespaceMarkers = n + n + namespaceMarkers;
14008 }
14009 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
14010 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
14011}
14012
14013const finalisers = { amd, cjs, es, iife, system, umd };
14014
14015class Source {
14016 constructor(filename, content) {
14017 this.isOriginal = true;
14018 this.filename = filename;
14019 this.content = content;
14020 }
14021 traceSegment(line, column, name) {
14022 return { column, line, name, source: this };
14023 }
14024}
14025class Link {
14026 constructor(map, sources) {
14027 this.sources = sources;
14028 this.names = map.names;
14029 this.mappings = map.mappings;
14030 }
14031 traceMappings() {
14032 const sources = [];
14033 const sourceIndexMap = new Map();
14034 const sourcesContent = [];
14035 const names = [];
14036 const nameIndexMap = new Map();
14037 const mappings = [];
14038 for (const line of this.mappings) {
14039 const tracedLine = [];
14040 for (const segment of line) {
14041 if (segment.length === 1)
14042 continue;
14043 const source = this.sources[segment[1]];
14044 if (!source)
14045 continue;
14046 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
14047 if (traced) {
14048 const { column, line, name, source: { content, filename } } = traced;
14049 let sourceIndex = sourceIndexMap.get(filename);
14050 if (sourceIndex === undefined) {
14051 sourceIndex = sources.length;
14052 sources.push(filename);
14053 sourceIndexMap.set(filename, sourceIndex);
14054 sourcesContent[sourceIndex] = content;
14055 }
14056 else if (sourcesContent[sourceIndex] == null) {
14057 sourcesContent[sourceIndex] = content;
14058 }
14059 else if (content != null && sourcesContent[sourceIndex] !== content) {
14060 return error({
14061 message: `Multiple conflicting contents for sourcemap source ${filename}`
14062 });
14063 }
14064 const tracedSegment = [segment[0], sourceIndex, line, column];
14065 if (name) {
14066 let nameIndex = nameIndexMap.get(name);
14067 if (nameIndex === undefined) {
14068 nameIndex = names.length;
14069 names.push(name);
14070 nameIndexMap.set(name, nameIndex);
14071 }
14072 tracedSegment[4] = nameIndex;
14073 }
14074 tracedLine.push(tracedSegment);
14075 }
14076 }
14077 mappings.push(tracedLine);
14078 }
14079 return { mappings, names, sources, sourcesContent };
14080 }
14081 traceSegment(line, column, name) {
14082 const segments = this.mappings[line];
14083 if (!segments)
14084 return null;
14085 // binary search through segments for the given column
14086 let searchStart = 0;
14087 let searchEnd = segments.length - 1;
14088 while (searchStart <= searchEnd) {
14089 const m = (searchStart + searchEnd) >> 1;
14090 const segment = segments[m];
14091 // If a sourcemap does not have sufficient resolution to contain a
14092 // necessary mapping, e.g. because it only contains line information, we
14093 // use the best approximation we could find
14094 if (segment[0] === column || searchStart === searchEnd) {
14095 if (segment.length == 1)
14096 return null;
14097 const source = this.sources[segment[1]];
14098 if (!source)
14099 return null;
14100 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
14101 }
14102 if (segment[0] > column) {
14103 searchEnd = m - 1;
14104 }
14105 else {
14106 searchStart = m + 1;
14107 }
14108 }
14109 return null;
14110 }
14111}
14112function getLinkMap(warn) {
14113 return function linkMap(source, map) {
14114 if (map.mappings) {
14115 return new Link(map, [source]);
14116 }
14117 warn({
14118 code: 'SOURCEMAP_BROKEN',
14119 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
14120 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
14121 'documentation for help',
14122 plugin: map.plugin,
14123 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
14124 });
14125 return new Link({
14126 mappings: [],
14127 names: []
14128 }, [source]);
14129 };
14130}
14131function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
14132 let source;
14133 if (!originalSourcemap) {
14134 source = new Source(id, originalCode);
14135 }
14136 else {
14137 const sources = originalSourcemap.sources;
14138 const sourcesContent = originalSourcemap.sourcesContent || [];
14139 const directory = require$$0.dirname(id) || '.';
14140 const sourceRoot = originalSourcemap.sourceRoot || '.';
14141 const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
14142 source = new Link(originalSourcemap, baseSources);
14143 }
14144 return sourcemapChain.reduce(linkMap, source);
14145}
14146function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
14147 const linkMap = getLinkMap(warn);
14148 const moduleSources = modules
14149 .filter(module => !module.excludeFromSourcemap)
14150 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
14151 const link = new Link(map, moduleSources);
14152 const source = bundleSourcemapChain.reduce(linkMap, link);
14153 let { sources, sourcesContent, names, mappings } = source.traceMappings();
14154 if (file) {
14155 const directory = require$$0.dirname(file);
14156 sources = sources.map((source) => require$$0.relative(directory, source));
14157 file = require$$0.basename(file);
14158 }
14159 sourcesContent = (excludeContent ? null : sourcesContent);
14160 return new SourceMap({ file, mappings, names, sources, sourcesContent });
14161}
14162function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
14163 if (!sourcemapChain.length) {
14164 return originalSourcemap;
14165 }
14166 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
14167 const map = source.traceMappings();
14168 return { version: 3, ...map };
14169}
14170
14171const createHash = () => crypto.createHash('sha256');
14172
14173const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14174 amd: deconflictImportsOther,
14175 cjs: deconflictImportsOther,
14176 es: deconflictImportsEsmOrSystem,
14177 iife: deconflictImportsOther,
14178 system: deconflictImportsEsmOrSystem,
14179 umd: deconflictImportsOther
14180};
14181function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14182 const reversedModules = modules.slice().reverse();
14183 for (const module of reversedModules) {
14184 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14185 }
14186 deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
14187 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
14188 for (const module of reversedModules) {
14189 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
14190 }
14191}
14192function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
14193 // This is needed for namespace reexports
14194 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
14195 if (preserveModules || dependency instanceof ExternalModule) {
14196 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
14197 }
14198 }
14199 for (const variable of imports) {
14200 const module = variable.module;
14201 const name = variable.name;
14202 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
14203 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
14204 }
14205 else if (module instanceof ExternalModule && name === 'default') {
14206 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
14207 ? module.suggestedVariableName + '__default'
14208 : module.suggestedVariableName, usedNames));
14209 }
14210 else {
14211 variable.setRenderNames(null, getSafeName(name, usedNames));
14212 }
14213 }
14214 for (const variable of syntheticExports) {
14215 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14216 }
14217}
14218function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
14219 for (const chunkOrExternalModule of dependencies) {
14220 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
14221 }
14222 for (const externalModuleOrChunk of deconflictedNamespace) {
14223 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
14224 }
14225 for (const externalModule of deconflictedDefault) {
14226 if (deconflictedNamespace.has(externalModule) &&
14227 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
14228 externalModule.defaultVariableName = externalModule.namespaceVariableName;
14229 }
14230 else {
14231 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
14232 }
14233 }
14234 for (const variable of imports) {
14235 const module = variable.module;
14236 if (module instanceof ExternalModule) {
14237 const name = variable.name;
14238 if (name === 'default') {
14239 const moduleInterop = String(interop(module.id));
14240 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
14241 ? module.defaultVariableName
14242 : module.variableName;
14243 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
14244 variable.setRenderNames(variableName, 'default');
14245 }
14246 else {
14247 variable.setRenderNames(null, variableName);
14248 }
14249 }
14250 else if (name === '*') {
14251 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
14252 ? module.namespaceVariableName
14253 : module.variableName);
14254 }
14255 else {
14256 // if the second parameter is `null`, it uses its "name" for the property name
14257 variable.setRenderNames(module.variableName, null);
14258 }
14259 }
14260 else {
14261 const chunk = chunkByModule.get(module);
14262 if (preserveModules && variable.isNamespace) {
14263 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
14264 }
14265 else if (chunk.exportMode === 'default') {
14266 variable.setRenderNames(null, chunk.variableName);
14267 }
14268 else {
14269 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
14270 }
14271 }
14272 }
14273}
14274function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
14275 for (const module of modules) {
14276 for (const variable of module.scope.variables.values()) {
14277 if (variable.included &&
14278 // this will only happen for exports in some formats
14279 !(variable.renderBaseName ||
14280 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
14281 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14282 }
14283 }
14284 if (includedNamespaces.has(module)) {
14285 const namespace = module.namespace;
14286 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
14287 }
14288 }
14289}
14290
14291const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
14292const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
14293const backSlashRegEx = /\\/g;
14294function escapeId(id) {
14295 if (!id.match(needsEscapeRegEx))
14296 return id;
14297 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
14298}
14299
14300function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
14301 let nameIndex = 0;
14302 for (const variable of exports) {
14303 let [exportName] = variable.name;
14304 if (exportsByName.has(exportName)) {
14305 do {
14306 exportName = toBase64(++nameIndex);
14307 // skip past leading number identifiers
14308 if (exportName.charCodeAt(0) === 49 /* '1' */) {
14309 nameIndex += 9 * 64 ** (exportName.length - 1);
14310 exportName = toBase64(nameIndex);
14311 }
14312 } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
14313 }
14314 exportsByName.set(exportName, variable);
14315 exportNamesByVariable.set(variable, [exportName]);
14316 }
14317}
14318function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
14319 for (const variable of exports) {
14320 let nameIndex = 0;
14321 let exportName = variable.name;
14322 while (exportsByName.has(exportName)) {
14323 exportName = variable.name + '$' + ++nameIndex;
14324 }
14325 exportsByName.set(exportName, variable);
14326 exportNamesByVariable.set(variable, [exportName]);
14327 }
14328}
14329
14330function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
14331 const exportKeys = chunk.getExportNames();
14332 if (exportMode === 'default') {
14333 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
14334 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
14335 }
14336 }
14337 else if (exportMode === 'none' && exportKeys.length) {
14338 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
14339 }
14340 if (exportMode === 'auto') {
14341 if (exportKeys.length === 0) {
14342 exportMode = 'none';
14343 }
14344 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
14345 if (format === 'cjs' && unsetOptions.has('exports')) {
14346 warn(errPreferNamedExports(facadeModuleId));
14347 }
14348 exportMode = 'default';
14349 }
14350 else {
14351 if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
14352 warn(errMixedExport(facadeModuleId, name));
14353 }
14354 exportMode = 'named';
14355 }
14356 }
14357 return exportMode;
14358}
14359
14360function guessIndentString(code) {
14361 const lines = code.split('\n');
14362 const tabbed = lines.filter(line => /^\t+/.test(line));
14363 const spaced = lines.filter(line => /^ {2,}/.test(line));
14364 if (tabbed.length === 0 && spaced.length === 0) {
14365 return null;
14366 }
14367 // More lines tabbed than spaced? Assume tabs, and
14368 // default to tabs in the case of a tie (or nothing
14369 // to go on)
14370 if (tabbed.length >= spaced.length) {
14371 return '\t';
14372 }
14373 // Otherwise, we need to guess the multiple
14374 const min = spaced.reduce((previous, current) => {
14375 const numSpaces = /^ +/.exec(current)[0].length;
14376 return Math.min(numSpaces, previous);
14377 }, Infinity);
14378 return new Array(min + 1).join(' ');
14379}
14380function getIndentString(modules, options) {
14381 if (options.indent !== true)
14382 return options.indent;
14383 for (const module of modules) {
14384 const indent = guessIndentString(module.originalCode);
14385 if (indent !== null)
14386 return indent;
14387 }
14388 return '\t';
14389}
14390
14391function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14392 const staticDependencyBlocks = [];
14393 const handledDependencies = new Set();
14394 for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
14395 const module = orderedModules[modulePos];
14396 if (!handledDependencies.has(module)) {
14397 const staticDependencies = [];
14398 addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
14399 staticDependencyBlocks.unshift(staticDependencies);
14400 }
14401 }
14402 const dependencies = new Set();
14403 for (const block of staticDependencyBlocks) {
14404 for (const dependency of block) {
14405 dependencies.add(dependency);
14406 }
14407 }
14408 return dependencies;
14409}
14410function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
14411 const dependencies = module.getDependenciesToBeIncluded();
14412 for (const dependency of dependencies) {
14413 if (dependency instanceof ExternalModule) {
14414 staticDependencies.push(dependency);
14415 continue;
14416 }
14417 const dependencyChunk = chunkByModule.get(dependency);
14418 if (dependencyChunk !== chunk) {
14419 staticDependencies.push(dependencyChunk);
14420 continue;
14421 }
14422 if (!handledModules.has(dependency)) {
14423 handledModules.add(dependency);
14424 addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
14425 }
14426 }
14427}
14428
14429function decodedSourcemap(map) {
14430 if (!map)
14431 return null;
14432 if (typeof map === 'string') {
14433 map = JSON.parse(map);
14434 }
14435 if (map.mappings === '') {
14436 return {
14437 mappings: [],
14438 names: [],
14439 sources: [],
14440 version: 3
14441 };
14442 }
14443 const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
14444 return { ...map, mappings };
14445}
14446
14447function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
14448 const renderChunkReducer = (code, result, plugin) => {
14449 if (result == null)
14450 return code;
14451 if (typeof result === 'string')
14452 result = {
14453 code: result,
14454 map: undefined
14455 };
14456 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14457 if (result.map !== null) {
14458 const map = decodedSourcemap(result.map);
14459 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14460 }
14461 return result.code;
14462 };
14463 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
14464}
14465
14466function renderNamePattern(pattern, patternName, replacements) {
14467 if (isPathFragment(pattern))
14468 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
14469 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14470 if (!replacements.hasOwnProperty(type)) {
14471 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14472 }
14473 const replacement = replacements[type]();
14474 if (isPathFragment(replacement))
14475 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14476 return replacement;
14477 });
14478}
14479function makeUnique(name, existingNames) {
14480 const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
14481 if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
14482 return name;
14483 const ext = require$$0.extname(name);
14484 name = name.substring(0, name.length - ext.length);
14485 let uniqueName, uniqueIndex = 1;
14486 while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14487 ;
14488 return uniqueName;
14489}
14490
14491const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
14492function getGlobalName(module, globals, hasExports, warn) {
14493 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
14494 if (globalName) {
14495 return globalName;
14496 }
14497 if (hasExports) {
14498 warn({
14499 code: 'MISSING_GLOBAL_NAME',
14500 guess: module.variableName,
14501 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14502 source: module.id
14503 });
14504 return module.variableName;
14505 }
14506}
14507class Chunk {
14508 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
14509 this.orderedModules = orderedModules;
14510 this.inputOptions = inputOptions;
14511 this.outputOptions = outputOptions;
14512 this.unsetOptions = unsetOptions;
14513 this.pluginDriver = pluginDriver;
14514 this.modulesById = modulesById;
14515 this.chunkByModule = chunkByModule;
14516 this.facadeChunkByModule = facadeChunkByModule;
14517 this.includedNamespaces = includedNamespaces;
14518 this.manualChunkAlias = manualChunkAlias;
14519 this.entryModules = [];
14520 this.exportMode = 'named';
14521 this.facadeModule = null;
14522 this.id = null;
14523 this.namespaceVariableName = '';
14524 this.needsExportsShim = false;
14525 this.variableName = '';
14526 this.accessedGlobalsByScope = new Map();
14527 this.dependencies = new Set();
14528 this.dynamicDependencies = new Set();
14529 this.dynamicEntryModules = [];
14530 this.dynamicName = null;
14531 this.exportNamesByVariable = new Map();
14532 this.exports = new Set();
14533 this.exportsByName = new Map();
14534 this.fileName = null;
14535 this.implicitEntryModules = [];
14536 this.implicitlyLoadedBefore = new Set();
14537 this.imports = new Set();
14538 this.includedReexportsByModule = new Map();
14539 this.indentString = undefined;
14540 // This may only be updated in the constructor
14541 this.isEmpty = true;
14542 this.name = null;
14543 this.renderedDependencies = null;
14544 this.renderedExports = null;
14545 this.renderedHash = undefined;
14546 this.renderedModuleSources = new Map();
14547 this.renderedModules = Object.create(null);
14548 this.renderedSource = null;
14549 this.sortedExportNames = null;
14550 this.strictFacade = false;
14551 this.usedModules = undefined;
14552 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14553 const chunkModules = new Set(orderedModules);
14554 for (const module of orderedModules) {
14555 if (module.namespace.included) {
14556 includedNamespaces.add(module);
14557 }
14558 if (this.isEmpty && module.isIncluded()) {
14559 this.isEmpty = false;
14560 }
14561 if (module.info.isEntry || outputOptions.preserveModules) {
14562 this.entryModules.push(module);
14563 }
14564 for (const importer of module.includedDynamicImporters) {
14565 if (!chunkModules.has(importer)) {
14566 this.dynamicEntryModules.push(module);
14567 // Modules with synthetic exports need an artificial namespace for dynamic imports
14568 if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
14569 includedNamespaces.add(module);
14570 this.exports.add(module.namespace);
14571 }
14572 }
14573 }
14574 if (module.implicitlyLoadedAfter.size > 0) {
14575 this.implicitEntryModules.push(module);
14576 }
14577 }
14578 this.suggestedVariableName = makeLegal(this.generateVariableName());
14579 }
14580 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
14581 const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
14582 chunk.assignFacadeName(facadeName, facadedModule);
14583 if (!facadeChunkByModule.has(facadedModule)) {
14584 facadeChunkByModule.set(facadedModule, chunk);
14585 }
14586 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
14587 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
14588 }
14589 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
14590 facadedModule.info.moduleSideEffects &&
14591 facadedModule.hasEffects()) {
14592 chunk.dependencies.add(chunkByModule.get(facadedModule));
14593 }
14594 chunk.ensureReexportsAreAvailableForModule(facadedModule);
14595 chunk.facadeModule = facadedModule;
14596 chunk.strictFacade = true;
14597 return chunk;
14598 }
14599 canModuleBeFacade(module, exposedVariables) {
14600 const moduleExportNamesByVariable = module.getExportNamesByVariable();
14601 for (const exposedVariable of this.exports) {
14602 if (!moduleExportNamesByVariable.has(exposedVariable)) {
14603 if (moduleExportNamesByVariable.size === 0 &&
14604 module.isUserDefinedEntryPoint &&
14605 module.preserveSignature === 'strict' &&
14606 this.unsetOptions.has('preserveEntrySignatures')) {
14607 this.inputOptions.onwarn({
14608 code: 'EMPTY_FACADE',
14609 id: module.id,
14610 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.`,
14611 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
14612 });
14613 }
14614 return false;
14615 }
14616 }
14617 for (const exposedVariable of exposedVariables) {
14618 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
14619 return false;
14620 }
14621 }
14622 return true;
14623 }
14624 generateExports() {
14625 this.sortedExportNames = null;
14626 const remainingExports = new Set(this.exports);
14627 if (this.facadeModule !== null &&
14628 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
14629 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
14630 for (const [variable, exportNames] of exportNamesByVariable) {
14631 this.exportNamesByVariable.set(variable, [...exportNames]);
14632 for (const exportName of exportNames) {
14633 this.exportsByName.set(exportName, variable);
14634 }
14635 remainingExports.delete(variable);
14636 }
14637 }
14638 if (this.outputOptions.minifyInternalExports) {
14639 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14640 }
14641 else {
14642 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14643 }
14644 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
14645 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
14646 }
14647 generateFacades() {
14648 var _a;
14649 const facades = [];
14650 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
14651 const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
14652 for (const module of entryModules) {
14653 if (module.preserveSignature) {
14654 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
14655 exposedVariables.add(exportedVariable);
14656 }
14657 }
14658 }
14659 for (const module of entryModules) {
14660 const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
14661 // mapping must run after Set 'name' dedupe
14662 name => ({
14663 name
14664 }));
14665 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
14666 requiredFacades.push({});
14667 }
14668 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
14669 if (requiredFacades.length === 0) {
14670 requiredFacades.push({});
14671 }
14672 if (!this.facadeModule) {
14673 const needsStrictFacade = module.preserveSignature === 'strict' ||
14674 (module.preserveSignature === 'exports-only' &&
14675 module.getExportNamesByVariable().size !== 0);
14676 if (!needsStrictFacade ||
14677 this.outputOptions.preserveModules ||
14678 this.canModuleBeFacade(module, exposedVariables)) {
14679 this.facadeModule = module;
14680 this.facadeChunkByModule.set(module, this);
14681 if (module.preserveSignature) {
14682 this.strictFacade = needsStrictFacade;
14683 }
14684 this.assignFacadeName(requiredFacades.shift(), module);
14685 }
14686 }
14687 for (const facadeName of requiredFacades) {
14688 facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
14689 }
14690 }
14691 for (const module of this.dynamicEntryModules) {
14692 if (module.info.syntheticNamedExports)
14693 continue;
14694 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
14695 this.facadeModule = module;
14696 this.facadeChunkByModule.set(module, this);
14697 this.strictFacade = true;
14698 this.dynamicName = getChunkNameFromModule(module);
14699 }
14700 else if (this.facadeModule === module &&
14701 !this.strictFacade &&
14702 this.canModuleBeFacade(module, exposedVariables)) {
14703 this.strictFacade = true;
14704 }
14705 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
14706 this.includedNamespaces.add(module);
14707 this.exports.add(module.namespace);
14708 }
14709 }
14710 if (!this.outputOptions.preserveModules) {
14711 this.addNecessaryImportsForFacades();
14712 }
14713 return facades;
14714 }
14715 generateId(addons, options, existingNames, includeHash) {
14716 if (this.fileName !== null) {
14717 return this.fileName;
14718 }
14719 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14720 ? [options.entryFileNames, 'output.entryFileNames']
14721 : [options.chunkFileNames, 'output.chunkFileNames'];
14722 return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
14723 format: () => options.format,
14724 hash: () => includeHash
14725 ? this.computeContentHashWithDependencies(addons, options, existingNames)
14726 : '[hash]',
14727 name: () => this.getChunkName()
14728 }), existingNames);
14729 }
14730 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
14731 const [{ id }] = this.orderedModules;
14732 const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14733 let path;
14734 const patternOpt = unsetOptions.has('entryFileNames')
14735 ? '[name][assetExtname].js'
14736 : options.entryFileNames;
14737 const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
14738 if (isAbsolute(sanitizedId)) {
14739 const currentDir = require$$0.dirname(sanitizedId);
14740 const extension = require$$0.extname(sanitizedId);
14741 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14742 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14743 ext: () => extension.substring(1),
14744 extname: () => extension,
14745 format: () => options.format,
14746 name: () => this.getChunkName()
14747 });
14748 const currentPath = `${currentDir}/${fileName}`;
14749 const { preserveModulesRoot } = options;
14750 if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
14751 path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14752 }
14753 else {
14754 path = relative(preserveModulesRelativeDir, currentPath);
14755 }
14756 }
14757 else {
14758 const extension = require$$0.extname(sanitizedId);
14759 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14760 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14761 ext: () => extension.substring(1),
14762 extname: () => extension,
14763 format: () => options.format,
14764 name: () => getAliasName(sanitizedId)
14765 });
14766 path = `_virtual/${fileName}`;
14767 }
14768 return makeUnique(normalize(path), existingNames);
14769 }
14770 getChunkInfo() {
14771 const facadeModule = this.facadeModule;
14772 const getChunkName = this.getChunkName.bind(this);
14773 return {
14774 exports: this.getExportNames(),
14775 facadeModuleId: facadeModule && facadeModule.id,
14776 isDynamicEntry: this.dynamicEntryModules.length > 0,
14777 isEntry: facadeModule !== null && facadeModule.info.isEntry,
14778 isImplicitEntry: this.implicitEntryModules.length > 0,
14779 modules: this.renderedModules,
14780 get name() {
14781 return getChunkName();
14782 },
14783 type: 'chunk'
14784 };
14785 }
14786 getChunkInfoWithFileNames() {
14787 return Object.assign(this.getChunkInfo(), {
14788 code: undefined,
14789 dynamicImports: Array.from(this.dynamicDependencies, getId),
14790 fileName: this.id,
14791 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
14792 importedBindings: this.getImportedBindingsPerDependency(),
14793 imports: Array.from(this.dependencies, getId),
14794 map: undefined,
14795 referencedFiles: this.getReferencedFiles()
14796 });
14797 }
14798 getChunkName() {
14799 var _a;
14800 return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
14801 }
14802 getExportNames() {
14803 var _a;
14804 return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14805 }
14806 getRenderedHash() {
14807 if (this.renderedHash)
14808 return this.renderedHash;
14809 const hash = createHash();
14810 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
14811 if (pluginHash) {
14812 augmentation += pluginHash;
14813 }
14814 return augmentation;
14815 });
14816 hash.update(hashAugmentation);
14817 hash.update(this.renderedSource.toString());
14818 hash.update(this.getExportNames()
14819 .map(exportName => {
14820 const variable = this.exportsByName.get(exportName);
14821 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14822 })
14823 .join(','));
14824 return (this.renderedHash = hash.digest('hex'));
14825 }
14826 getVariableExportName(variable) {
14827 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
14828 return '*';
14829 }
14830 return this.exportNamesByVariable.get(variable)[0];
14831 }
14832 link() {
14833 this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
14834 for (const module of this.orderedModules) {
14835 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
14836 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
14837 this.setUpChunkImportsAndExportsForModule(module);
14838 }
14839 }
14840 // prerender allows chunk hashes and names to be generated before finalizing
14841 preRender(options, inputBase, snippets) {
14842 const { _, getPropertyAccess, n } = snippets;
14843 const magicString = new Bundle$1({ separator: `${n}${n}` });
14844 this.usedModules = [];
14845 this.indentString = getIndentString(this.orderedModules, options);
14846 const renderOptions = {
14847 dynamicImportFunction: options.dynamicImportFunction,
14848 exportNamesByVariable: this.exportNamesByVariable,
14849 format: options.format,
14850 freeze: options.freeze,
14851 indent: this.indentString,
14852 namespaceToStringTag: options.namespaceToStringTag,
14853 outputPluginDriver: this.pluginDriver,
14854 snippets
14855 };
14856 // for static and dynamic entry points, inline the execution list to avoid loading latency
14857 if (options.hoistTransitiveImports &&
14858 !this.outputOptions.preserveModules &&
14859 this.facadeModule !== null) {
14860 for (const dep of this.dependencies) {
14861 if (dep instanceof Chunk)
14862 this.inlineChunkDependencies(dep);
14863 }
14864 }
14865 this.prepareModulesForRendering(snippets);
14866 this.setIdentifierRenderResolutions(options);
14867 let hoistedSource = '';
14868 const renderedModules = this.renderedModules;
14869 for (const module of this.orderedModules) {
14870 let renderedLength = 0;
14871 if (module.isIncluded() || this.includedNamespaces.has(module)) {
14872 const source = module.render(renderOptions).trim();
14873 renderedLength = source.length();
14874 if (renderedLength) {
14875 if (options.compact && source.lastLine().includes('//'))
14876 source.append('\n');
14877 this.renderedModuleSources.set(module, source);
14878 magicString.addSource(source);
14879 this.usedModules.push(module);
14880 }
14881 const namespace = module.namespace;
14882 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
14883 const rendered = namespace.renderBlock(renderOptions);
14884 if (namespace.renderFirst())
14885 hoistedSource += n + rendered;
14886 else
14887 magicString.addSource(new MagicString(rendered));
14888 }
14889 }
14890 const { renderedExports, removedExports } = module.getRenderedExports();
14891 const { renderedModuleSources } = this;
14892 renderedModules[module.id] = {
14893 get code() {
14894 var _a, _b;
14895 return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
14896 },
14897 originalLength: module.originalCode.length,
14898 removedExports,
14899 renderedExports,
14900 renderedLength
14901 };
14902 }
14903 if (hoistedSource)
14904 magicString.prepend(hoistedSource + n + n);
14905 if (this.needsExportsShim) {
14906 magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14907 }
14908 if (options.compact) {
14909 this.renderedSource = magicString;
14910 }
14911 else {
14912 this.renderedSource = magicString.trim();
14913 }
14914 this.renderedHash = undefined;
14915 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
14916 const chunkName = this.getChunkName();
14917 this.inputOptions.onwarn({
14918 chunkName,
14919 code: 'EMPTY_BUNDLE',
14920 message: `Generated an empty chunk: "${chunkName}"`
14921 });
14922 }
14923 this.setExternalRenderPaths(options, inputBase);
14924 this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
14925 this.renderedExports =
14926 this.exportMode === 'none'
14927 ? []
14928 : this.getChunkExportDeclarations(options.format, getPropertyAccess);
14929 }
14930 async render(options, addons, outputChunk, snippets) {
14931 timeStart('render format', 2);
14932 const format = options.format;
14933 const finalise = finalisers[format];
14934 if (options.dynamicImportFunction && format !== 'es') {
14935 this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
14936 }
14937 // populate ids in the rendered declarations only here
14938 // as chunk ids known only after prerender
14939 for (const dependency of this.dependencies) {
14940 const renderedDependency = this.renderedDependencies.get(dependency);
14941 if (dependency instanceof ExternalModule) {
14942 const originalId = dependency.renderPath;
14943 renderedDependency.id = escapeId(dependency.renormalizeRenderPath
14944 ? getImportPath(this.id, originalId, false, false)
14945 : originalId);
14946 }
14947 else {
14948 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
14949 renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
14950 }
14951 }
14952 this.finaliseDynamicImports(options, snippets);
14953 this.finaliseImportMetas(format, snippets);
14954 const hasExports = this.renderedExports.length !== 0 ||
14955 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
14956 let topLevelAwaitModule = null;
14957 const accessedGlobals = new Set();
14958 for (const module of this.orderedModules) {
14959 if (module.usesTopLevelAwait) {
14960 topLevelAwaitModule = module.id;
14961 }
14962 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
14963 if (accessedGlobalVariables) {
14964 for (const name of accessedGlobalVariables) {
14965 accessedGlobals.add(name);
14966 }
14967 }
14968 }
14969 if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
14970 return error({
14971 code: 'INVALID_TLA_FORMAT',
14972 id: topLevelAwaitModule,
14973 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
14974 });
14975 }
14976 /* istanbul ignore next */
14977 if (!this.id) {
14978 throw new Error('Internal Error: expecting chunk id');
14979 }
14980 const magicString = finalise(this.renderedSource, {
14981 accessedGlobals,
14982 dependencies: [...this.renderedDependencies.values()],
14983 exports: this.renderedExports,
14984 hasExports,
14985 id: this.id,
14986 indent: this.indentString,
14987 intro: addons.intro,
14988 isEntryFacade: this.outputOptions.preserveModules ||
14989 (this.facadeModule !== null && this.facadeModule.info.isEntry),
14990 isModuleFacade: this.facadeModule !== null,
14991 namedExportsMode: this.exportMode !== 'default',
14992 outro: addons.outro,
14993 snippets,
14994 usesTopLevelAwait: topLevelAwaitModule !== null,
14995 warn: this.inputOptions.onwarn
14996 }, options);
14997 if (addons.banner)
14998 magicString.prepend(addons.banner);
14999 if (addons.footer)
15000 magicString.append(addons.footer);
15001 const prevCode = magicString.toString();
15002 timeEnd('render format', 2);
15003 let map = null;
15004 const chunkSourcemapChain = [];
15005 let code = await renderChunk({
15006 code: prevCode,
15007 options,
15008 outputPluginDriver: this.pluginDriver,
15009 renderChunk: outputChunk,
15010 sourcemapChain: chunkSourcemapChain
15011 });
15012 if (options.sourcemap) {
15013 timeStart('sourcemap', 2);
15014 let file;
15015 if (options.file)
15016 file = require$$0.resolve(options.sourcemapFile || options.file);
15017 else if (options.dir)
15018 file = require$$0.resolve(options.dir, this.id);
15019 else
15020 file = require$$0.resolve(this.id);
15021 const decodedMap = magicString.generateDecodedMap({});
15022 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
15023 map.sources = map.sources
15024 .map(sourcePath => {
15025 const { sourcemapPathTransform } = options;
15026 if (sourcemapPathTransform) {
15027 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
15028 if (typeof newSourcePath !== 'string') {
15029 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
15030 }
15031 return newSourcePath;
15032 }
15033 return sourcePath;
15034 })
15035 .map(normalize);
15036 timeEnd('sourcemap', 2);
15037 }
15038 if (!options.compact && code[code.length - 1] !== '\n')
15039 code += '\n';
15040 return { code, map };
15041 }
15042 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
15043 for (const module of moduleDependencies) {
15044 if (module instanceof Module) {
15045 const chunk = this.chunkByModule.get(module);
15046 if (chunk && chunk !== this) {
15047 chunkDependencies.add(chunk);
15048 }
15049 }
15050 else {
15051 chunkDependencies.add(module);
15052 }
15053 }
15054 }
15055 addNecessaryImportsForFacades() {
15056 for (const [module, variables] of this.includedReexportsByModule) {
15057 if (this.includedNamespaces.has(module)) {
15058 for (const variable of variables) {
15059 this.imports.add(variable);
15060 }
15061 }
15062 }
15063 }
15064 assignFacadeName({ fileName, name }, facadedModule) {
15065 if (fileName) {
15066 this.fileName = fileName;
15067 }
15068 else {
15069 this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
15070 }
15071 }
15072 checkCircularDependencyImport(variable, importingModule) {
15073 const variableModule = variable.module;
15074 if (variableModule instanceof Module) {
15075 const exportChunk = this.chunkByModule.get(variableModule);
15076 let alternativeReexportModule;
15077 do {
15078 alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
15079 if (alternativeReexportModule) {
15080 const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
15081 if (exportingChunk && exportingChunk !== exportChunk) {
15082 this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
15083 }
15084 importingModule = alternativeReexportModule;
15085 }
15086 } while (alternativeReexportModule);
15087 }
15088 }
15089 computeContentHashWithDependencies(addons, options, existingNames) {
15090 const hash = createHash();
15091 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
15092 hash.update(options.format);
15093 const dependenciesForHashing = new Set([this]);
15094 for (const current of dependenciesForHashing) {
15095 if (current instanceof ExternalModule) {
15096 hash.update(`:${current.renderPath}`);
15097 }
15098 else {
15099 hash.update(current.getRenderedHash());
15100 hash.update(current.generateId(addons, options, existingNames, false));
15101 }
15102 if (current instanceof ExternalModule)
15103 continue;
15104 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
15105 dependenciesForHashing.add(dependency);
15106 }
15107 }
15108 return hash.digest('hex').substr(0, 8);
15109 }
15110 ensureReexportsAreAvailableForModule(module) {
15111 const includedReexports = [];
15112 const map = module.getExportNamesByVariable();
15113 for (const exportedVariable of map.keys()) {
15114 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
15115 const importedVariable = isSynthetic
15116 ? exportedVariable.getBaseVariable()
15117 : exportedVariable;
15118 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
15119 this.checkCircularDependencyImport(importedVariable, module);
15120 const exportingModule = importedVariable.module;
15121 if (exportingModule instanceof Module) {
15122 const chunk = this.chunkByModule.get(exportingModule);
15123 if (chunk && chunk !== this) {
15124 chunk.exports.add(importedVariable);
15125 includedReexports.push(importedVariable);
15126 if (isSynthetic) {
15127 this.imports.add(importedVariable);
15128 }
15129 }
15130 }
15131 }
15132 }
15133 if (includedReexports.length) {
15134 this.includedReexportsByModule.set(module, includedReexports);
15135 }
15136 }
15137 finaliseDynamicImports(options, snippets) {
15138 const stripKnownJsExtensions = options.format === 'amd';
15139 for (const [module, code] of this.renderedModuleSources) {
15140 for (const { node, resolution } of module.dynamicImports) {
15141 const chunk = this.chunkByModule.get(resolution);
15142 const facadeChunk = this.facadeChunkByModule.get(resolution);
15143 if (!resolution || !node.included || chunk === this) {
15144 continue;
15145 }
15146 const renderedResolution = resolution instanceof Module
15147 ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
15148 : resolution instanceof ExternalModule
15149 ? `'${escapeId(resolution.renormalizeRenderPath
15150 ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
15151 : resolution.renderPath)}'`
15152 : resolution;
15153 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
15154 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
15155 chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
15156 }
15157 }
15158 }
15159 finaliseImportMetas(format, snippets) {
15160 for (const [module, code] of this.renderedModuleSources) {
15161 for (const importMeta of module.importMetas) {
15162 importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
15163 }
15164 }
15165 }
15166 generateVariableName() {
15167 if (this.manualChunkAlias) {
15168 return this.manualChunkAlias;
15169 }
15170 const moduleForNaming = this.entryModules[0] ||
15171 this.implicitEntryModules[0] ||
15172 this.dynamicEntryModules[0] ||
15173 this.orderedModules[this.orderedModules.length - 1];
15174 if (moduleForNaming) {
15175 return getChunkNameFromModule(moduleForNaming);
15176 }
15177 return 'chunk';
15178 }
15179 getChunkDependencyDeclarations(options, getPropertyAccess) {
15180 const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
15181 const reexportSpecifiers = this.getReexportSpecifiers();
15182 const dependencyDeclaration = new Map();
15183 for (const dep of this.dependencies) {
15184 const imports = importSpecifiers.get(dep) || null;
15185 const reexports = reexportSpecifiers.get(dep) || null;
15186 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
15187 dependencyDeclaration.set(dep, {
15188 defaultVariableName: dep.defaultVariableName,
15189 globalName: (dep instanceof ExternalModule &&
15190 (options.format === 'umd' || options.format === 'iife') &&
15191 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
15192 id: undefined,
15193 imports,
15194 isChunk: dep instanceof Chunk,
15195 name: dep.variableName,
15196 namedExportsMode,
15197 namespaceVariableName: dep.namespaceVariableName,
15198 reexports
15199 });
15200 }
15201 return dependencyDeclaration;
15202 }
15203 getChunkExportDeclarations(format, getPropertyAccess) {
15204 const exports = [];
15205 for (const exportName of this.getExportNames()) {
15206 if (exportName[0] === '*')
15207 continue;
15208 const variable = this.exportsByName.get(exportName);
15209 if (!(variable instanceof SyntheticNamedExportVariable)) {
15210 const module = variable.module;
15211 if (module && this.chunkByModule.get(module) !== this)
15212 continue;
15213 }
15214 let expression = null;
15215 let hoisted = false;
15216 let local = variable.getName(getPropertyAccess);
15217 if (variable instanceof LocalVariable) {
15218 for (const declaration of variable.declarations) {
15219 if (declaration.parent instanceof FunctionDeclaration ||
15220 (declaration instanceof ExportDefaultDeclaration &&
15221 declaration.declaration instanceof FunctionDeclaration)) {
15222 hoisted = true;
15223 break;
15224 }
15225 }
15226 }
15227 else if (variable instanceof SyntheticNamedExportVariable) {
15228 expression = local;
15229 if (format === 'es') {
15230 local = variable.renderName;
15231 }
15232 }
15233 exports.push({
15234 exported: exportName,
15235 expression,
15236 hoisted,
15237 local
15238 });
15239 }
15240 return exports;
15241 }
15242 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
15243 const dependencies = new Set();
15244 const deconflictedDefault = new Set();
15245 const deconflictedNamespace = new Set();
15246 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
15247 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
15248 const module = variable.module;
15249 if (module instanceof ExternalModule) {
15250 dependencies.add(module);
15251 if (addNonNamespacesAndInteropHelpers) {
15252 if (variable.name === 'default') {
15253 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
15254 deconflictedDefault.add(module);
15255 }
15256 }
15257 else if (variable.name === '*') {
15258 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
15259 deconflictedNamespace.add(module);
15260 }
15261 }
15262 }
15263 }
15264 else {
15265 const chunk = this.chunkByModule.get(module);
15266 if (chunk !== this) {
15267 dependencies.add(chunk);
15268 if (addNonNamespacesAndInteropHelpers &&
15269 chunk.exportMode === 'default' &&
15270 variable.isNamespace) {
15271 deconflictedNamespace.add(chunk);
15272 }
15273 }
15274 }
15275 }
15276 }
15277 if (addDependenciesWithoutBindings) {
15278 for (const dependency of this.dependencies) {
15279 dependencies.add(dependency);
15280 }
15281 }
15282 return { deconflictedDefault, deconflictedNamespace, dependencies };
15283 }
15284 getFallbackChunkName() {
15285 if (this.manualChunkAlias) {
15286 return this.manualChunkAlias;
15287 }
15288 if (this.dynamicName) {
15289 return this.dynamicName;
15290 }
15291 if (this.fileName) {
15292 return getAliasName(this.fileName);
15293 }
15294 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15295 }
15296 getImportSpecifiers(getPropertyAccess) {
15297 const { interop } = this.outputOptions;
15298 const importsByDependency = new Map();
15299 for (const variable of this.imports) {
15300 const module = variable.module;
15301 let dependency;
15302 let imported;
15303 if (module instanceof ExternalModule) {
15304 dependency = module;
15305 imported = variable.name;
15306 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15307 return error(errUnexpectedNamedImport(module.id, imported, false));
15308 }
15309 }
15310 else {
15311 dependency = this.chunkByModule.get(module);
15312 imported = dependency.getVariableExportName(variable);
15313 }
15314 getOrCreate(importsByDependency, dependency, () => []).push({
15315 imported,
15316 local: variable.getName(getPropertyAccess)
15317 });
15318 }
15319 return importsByDependency;
15320 }
15321 getImportedBindingsPerDependency() {
15322 const importSpecifiers = {};
15323 for (const [dependency, declaration] of this.renderedDependencies) {
15324 const specifiers = new Set();
15325 if (declaration.imports) {
15326 for (const { imported } of declaration.imports) {
15327 specifiers.add(imported);
15328 }
15329 }
15330 if (declaration.reexports) {
15331 for (const { imported } of declaration.reexports) {
15332 specifiers.add(imported);
15333 }
15334 }
15335 importSpecifiers[dependency.id] = [...specifiers];
15336 }
15337 return importSpecifiers;
15338 }
15339 getReexportSpecifiers() {
15340 const { externalLiveBindings, interop } = this.outputOptions;
15341 const reexportSpecifiers = new Map();
15342 for (let exportName of this.getExportNames()) {
15343 let dependency;
15344 let imported;
15345 let needsLiveBinding = false;
15346 if (exportName[0] === '*') {
15347 const id = exportName.substring(1);
15348 if (interop(id) === 'defaultOnly') {
15349 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15350 }
15351 needsLiveBinding = externalLiveBindings;
15352 dependency = this.modulesById.get(id);
15353 imported = exportName = '*';
15354 }
15355 else {
15356 const variable = this.exportsByName.get(exportName);
15357 if (variable instanceof SyntheticNamedExportVariable)
15358 continue;
15359 const module = variable.module;
15360 if (module instanceof Module) {
15361 dependency = this.chunkByModule.get(module);
15362 if (dependency === this)
15363 continue;
15364 imported = dependency.getVariableExportName(variable);
15365 needsLiveBinding = variable.isReassigned;
15366 }
15367 else {
15368 dependency = module;
15369 imported = variable.name;
15370 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15371 return error(errUnexpectedNamedImport(module.id, imported, true));
15372 }
15373 needsLiveBinding =
15374 externalLiveBindings &&
15375 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
15376 }
15377 }
15378 getOrCreate(reexportSpecifiers, dependency, () => []).push({
15379 imported,
15380 needsLiveBinding,
15381 reexported: exportName
15382 });
15383 }
15384 return reexportSpecifiers;
15385 }
15386 getReferencedFiles() {
15387 const referencedFiles = [];
15388 for (const module of this.orderedModules) {
15389 for (const meta of module.importMetas) {
15390 const fileName = meta.getReferencedFileName(this.pluginDriver);
15391 if (fileName) {
15392 referencedFiles.push(fileName);
15393 }
15394 }
15395 }
15396 return referencedFiles;
15397 }
15398 inlineChunkDependencies(chunk) {
15399 for (const dep of chunk.dependencies) {
15400 if (this.dependencies.has(dep))
15401 continue;
15402 this.dependencies.add(dep);
15403 if (dep instanceof Chunk) {
15404 this.inlineChunkDependencies(dep);
15405 }
15406 }
15407 }
15408 prepareModulesForRendering(snippets) {
15409 var _a;
15410 const accessedGlobalsByScope = this.accessedGlobalsByScope;
15411 for (const module of this.orderedModules) {
15412 for (const { node, resolution } of module.dynamicImports) {
15413 if (node.included) {
15414 if (resolution instanceof Module) {
15415 const chunk = this.chunkByModule.get(resolution);
15416 if (chunk === this) {
15417 node.setInternalResolution(resolution.namespace);
15418 }
15419 else {
15420 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15421 }
15422 }
15423 else {
15424 node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15425 }
15426 }
15427 }
15428 for (const importMeta of module.importMetas) {
15429 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
15430 }
15431 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
15432 module.namespace.prepare(accessedGlobalsByScope);
15433 }
15434 }
15435 }
15436 setExternalRenderPaths(options, inputBase) {
15437 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
15438 if (dependency instanceof ExternalModule) {
15439 dependency.setRenderPath(options, inputBase);
15440 }
15441 }
15442 }
15443 setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
15444 const syntheticExports = new Set();
15445 for (const exportName of this.getExportNames()) {
15446 const exportVariable = this.exportsByName.get(exportName);
15447 if (format !== 'es' &&
15448 format !== 'system' &&
15449 exportVariable.isReassigned &&
15450 !exportVariable.isId) {
15451 exportVariable.setRenderNames('exports', exportName);
15452 }
15453 else if (exportVariable instanceof SyntheticNamedExportVariable) {
15454 syntheticExports.add(exportVariable);
15455 }
15456 else {
15457 exportVariable.setRenderNames(null, null);
15458 }
15459 }
15460 for (const module of this.orderedModules) {
15461 if (module.needsExportShim) {
15462 this.needsExportsShim = true;
15463 break;
15464 }
15465 }
15466 const usedNames = new Set(['Object', 'Promise']);
15467 if (this.needsExportsShim) {
15468 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
15469 }
15470 if (namespaceToStringTag) {
15471 usedNames.add('Symbol');
15472 }
15473 switch (format) {
15474 case 'system':
15475 usedNames.add('module').add('exports');
15476 break;
15477 case 'es':
15478 break;
15479 case 'cjs':
15480 usedNames.add('module').add('require').add('__filename').add('__dirname');
15481 // fallthrough
15482 default:
15483 usedNames.add('exports');
15484 for (const helper of HELPER_NAMES) {
15485 usedNames.add(helper);
15486 }
15487 }
15488 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);
15489 }
15490 setUpChunkImportsAndExportsForModule(module) {
15491 const moduleImports = new Set(module.includedImports);
15492 // when we are not preserving modules, we need to make all namespace variables available for
15493 // rendering the namespace object
15494 if (!this.outputOptions.preserveModules) {
15495 if (this.includedNamespaces.has(module)) {
15496 const memberVariables = module.namespace.getMemberVariables();
15497 for (const variable of Object.values(memberVariables)) {
15498 moduleImports.add(variable);
15499 }
15500 }
15501 }
15502 for (let variable of moduleImports) {
15503 if (variable instanceof ExportDefaultVariable) {
15504 variable = variable.getOriginalVariable();
15505 }
15506 if (variable instanceof SyntheticNamedExportVariable) {
15507 variable = variable.getBaseVariable();
15508 }
15509 const chunk = this.chunkByModule.get(variable.module);
15510 if (chunk !== this) {
15511 this.imports.add(variable);
15512 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
15513 variable.module instanceof Module) {
15514 chunk.exports.add(variable);
15515 this.checkCircularDependencyImport(variable, module);
15516 }
15517 }
15518 }
15519 if (this.includedNamespaces.has(module) ||
15520 (module.info.isEntry && module.preserveSignature !== false) ||
15521 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
15522 this.ensureReexportsAreAvailableForModule(module);
15523 }
15524 for (const { node, resolution } of module.dynamicImports) {
15525 if (node.included &&
15526 resolution instanceof Module &&
15527 this.chunkByModule.get(resolution) === this &&
15528 !this.includedNamespaces.has(resolution)) {
15529 this.includedNamespaces.add(resolution);
15530 this.ensureReexportsAreAvailableForModule(resolution);
15531 }
15532 }
15533 }
15534}
15535function getChunkNameFromModule(module) {
15536 var _a, _b, _c, _d;
15537 return ((_d = (_b = (_a = module.chunkNames.find(({ isUserDefined }) => isUserDefined)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (_c = module.chunkNames[0]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : getAliasName(module.id));
15538}
15539const QUERY_HASH_REGEX = /[?#]/;
15540
15541function generateAssetFileName(name, source, outputOptions, bundle) {
15542 const emittedName = outputOptions.sanitizeFileName(name || 'asset');
15543 return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
15544 ? outputOptions.assetFileNames({ name, source, type: 'asset' })
15545 : outputOptions.assetFileNames, 'output.assetFileNames', {
15546 ext: () => require$$0.extname(emittedName).substring(1),
15547 extname: () => require$$0.extname(emittedName),
15548 hash() {
15549 return createHash()
15550 .update(emittedName)
15551 .update(':')
15552 .update(source)
15553 .digest('hex')
15554 .substring(0, 8);
15555 },
15556 name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
15557 }), bundle);
15558}
15559function reserveFileNameInBundle(fileName, bundle, warn) {
15560 if (fileName in bundle) {
15561 warn(errFileNameConflict(fileName));
15562 }
15563 bundle[fileName] = FILE_PLACEHOLDER;
15564}
15565const FILE_PLACEHOLDER = {
15566 type: 'placeholder'
15567};
15568function hasValidType(emittedFile) {
15569 return Boolean(emittedFile &&
15570 (emittedFile.type === 'asset' ||
15571 emittedFile.type === 'chunk'));
15572}
15573function hasValidName(emittedFile) {
15574 const validatedName = emittedFile.fileName || emittedFile.name;
15575 return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
15576}
15577function getValidSource(source, emittedFile, fileReferenceId) {
15578 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
15579 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
15580 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.`));
15581 }
15582 return source;
15583}
15584function getAssetFileName(file, referenceId) {
15585 if (typeof file.fileName !== 'string') {
15586 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
15587 }
15588 return file.fileName;
15589}
15590function getChunkFileName(file, facadeChunkByModule) {
15591 var _a;
15592 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));
15593 if (!fileName)
15594 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
15595 return fileName;
15596}
15597class FileEmitter {
15598 constructor(graph, options, baseFileEmitter) {
15599 this.graph = graph;
15600 this.options = options;
15601 this.bundle = null;
15602 this.facadeChunkByModule = null;
15603 this.outputOptions = null;
15604 this.assertAssetsFinalized = () => {
15605 for (const [referenceId, emittedFile] of this.filesByReferenceId) {
15606 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
15607 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
15608 }
15609 };
15610 this.emitFile = (emittedFile) => {
15611 if (!hasValidType(emittedFile)) {
15612 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
15613 }
15614 if (!hasValidName(emittedFile)) {
15615 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}".`));
15616 }
15617 if (emittedFile.type === 'chunk') {
15618 return this.emitChunk(emittedFile);
15619 }
15620 return this.emitAsset(emittedFile);
15621 };
15622 this.getFileName = (fileReferenceId) => {
15623 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
15624 if (!emittedFile)
15625 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
15626 if (emittedFile.type === 'chunk') {
15627 return getChunkFileName(emittedFile, this.facadeChunkByModule);
15628 }
15629 return getAssetFileName(emittedFile, fileReferenceId);
15630 };
15631 this.setAssetSource = (referenceId, requestedSource) => {
15632 const consumedFile = this.filesByReferenceId.get(referenceId);
15633 if (!consumedFile)
15634 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
15635 if (consumedFile.type !== 'asset') {
15636 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
15637 }
15638 if (consumedFile.source !== undefined) {
15639 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
15640 }
15641 const source = getValidSource(requestedSource, consumedFile, referenceId);
15642 if (this.bundle) {
15643 this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
15644 }
15645 else {
15646 consumedFile.source = source;
15647 }
15648 };
15649 this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
15650 this.outputOptions = outputOptions;
15651 this.bundle = outputBundle;
15652 this.facadeChunkByModule = facadeChunkByModule;
15653 for (const emittedFile of this.filesByReferenceId.values()) {
15654 if (emittedFile.fileName) {
15655 reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
15656 }
15657 }
15658 for (const [referenceId, consumedFile] of this.filesByReferenceId) {
15659 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
15660 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
15661 }
15662 }
15663 };
15664 this.filesByReferenceId = baseFileEmitter
15665 ? new Map(baseFileEmitter.filesByReferenceId)
15666 : new Map();
15667 }
15668 assignReferenceId(file, idBase) {
15669 let referenceId;
15670 do {
15671 referenceId = createHash()
15672 .update(referenceId || idBase)
15673 .digest('hex')
15674 .substring(0, 8);
15675 } while (this.filesByReferenceId.has(referenceId));
15676 this.filesByReferenceId.set(referenceId, file);
15677 return referenceId;
15678 }
15679 emitAsset(emittedAsset) {
15680 const source = typeof emittedAsset.source !== 'undefined'
15681 ? getValidSource(emittedAsset.source, emittedAsset, null)
15682 : undefined;
15683 const consumedAsset = {
15684 fileName: emittedAsset.fileName,
15685 name: emittedAsset.name,
15686 source,
15687 type: 'asset'
15688 };
15689 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
15690 if (this.bundle) {
15691 if (emittedAsset.fileName) {
15692 reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
15693 }
15694 if (source !== undefined) {
15695 this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
15696 }
15697 }
15698 return referenceId;
15699 }
15700 emitChunk(emittedChunk) {
15701 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
15702 return error(errInvalidRollupPhaseForChunkEmission());
15703 }
15704 if (typeof emittedChunk.id !== 'string') {
15705 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
15706 }
15707 const consumedChunk = {
15708 fileName: emittedChunk.fileName,
15709 module: null,
15710 name: emittedChunk.name || emittedChunk.id,
15711 type: 'chunk'
15712 };
15713 this.graph.moduleLoader
15714 .emitChunk(emittedChunk)
15715 .then(module => (consumedChunk.module = module))
15716 .catch(() => {
15717 // Avoid unhandled Promise rejection as the error will be thrown later
15718 // once module loading has finished
15719 });
15720 return this.assignReferenceId(consumedChunk, emittedChunk.id);
15721 }
15722 finalizeAsset(consumedFile, source, referenceId, bundle) {
15723 const fileName = consumedFile.fileName ||
15724 findExistingAssetFileNameWithSource(bundle, source) ||
15725 generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
15726 // We must not modify the original assets to avoid interaction between outputs
15727 const assetWithFileName = { ...consumedFile, fileName, source };
15728 this.filesByReferenceId.set(referenceId, assetWithFileName);
15729 const { options } = this;
15730 bundle[fileName] = {
15731 fileName,
15732 get isAsset() {
15733 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
15734 return true;
15735 },
15736 name: consumedFile.name,
15737 source,
15738 type: 'asset'
15739 };
15740 }
15741}
15742function findExistingAssetFileNameWithSource(bundle, source) {
15743 for (const [fileName, outputFile] of Object.entries(bundle)) {
15744 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
15745 return fileName;
15746 }
15747 return null;
15748}
15749function areSourcesEqual(sourceA, sourceB) {
15750 if (typeof sourceA === 'string') {
15751 return sourceA === sourceB;
15752 }
15753 if (typeof sourceB === 'string') {
15754 return false;
15755 }
15756 if ('equals' in sourceA) {
15757 return sourceA.equals(sourceB);
15758 }
15759 if (sourceA.length !== sourceB.length) {
15760 return false;
15761 }
15762 for (let index = 0; index < sourceA.length; index++) {
15763 if (sourceA[index] !== sourceB[index]) {
15764 return false;
15765 }
15766 }
15767 return true;
15768}
15769
15770const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
15771const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
15772async function createAddons(options, outputPluginDriver) {
15773 try {
15774 let [banner, footer, intro, outro] = await Promise.all([
15775 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
15776 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
15777 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
15778 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
15779 ]);
15780 if (intro)
15781 intro += '\n\n';
15782 if (outro)
15783 outro = `\n\n${outro}`;
15784 if (banner.length)
15785 banner += '\n';
15786 if (footer.length)
15787 footer = '\n' + footer;
15788 return { banner, footer, intro, outro };
15789 }
15790 catch (err) {
15791 return error({
15792 code: 'ADDON_ERROR',
15793 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
15794\tError Message: ${err.message}`
15795 });
15796 }
15797}
15798
15799function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15800 const chunkDefinitions = [];
15801 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15802 const manualChunkModulesByAlias = Object.create(null);
15803 for (const [entry, alias] of manualChunkAliasByEntry) {
15804 const chunkModules = (manualChunkModulesByAlias[alias] =
15805 manualChunkModulesByAlias[alias] || []);
15806 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15807 }
15808 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15809 chunkDefinitions.push({ alias, modules });
15810 }
15811 const assignedEntryPointsByModule = new Map();
15812 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15813 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15814 const staticEntries = new Set(entryModules);
15815 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15816 const modulesToHandle = new Set([entry]);
15817 for (const module of modulesToHandle) {
15818 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15819 if (dynamicDependentEntryPoints &&
15820 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15821 continue;
15822 }
15823 else {
15824 assignedEntryPoints.add(entry);
15825 }
15826 for (const dependency of module.getDependenciesToBeIncluded()) {
15827 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15828 modulesToHandle.add(dependency);
15829 }
15830 }
15831 }
15832 }
15833 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15834 const entriesToCheck = new Set(entryPoints);
15835 for (const entry of entriesToCheck) {
15836 if (!containedIn.has(entry)) {
15837 if (staticEntries.has(entry))
15838 return false;
15839 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15840 for (const dependentEntry of dynamicallyDependentEntryPoints) {
15841 entriesToCheck.add(dependentEntry);
15842 }
15843 }
15844 }
15845 return true;
15846 }
15847 for (const entry of entryModules) {
15848 if (!modulesInManualChunks.has(entry)) {
15849 assignEntryToStaticDependencies(entry, null);
15850 }
15851 }
15852 for (const entry of dynamicEntryModules) {
15853 if (!modulesInManualChunks.has(entry)) {
15854 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
15855 }
15856 }
15857 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
15858 return chunkDefinitions;
15859}
15860function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
15861 const modulesToHandle = new Set([entry]);
15862 for (const module of modulesToHandle) {
15863 modulesInManualChunks.add(module);
15864 manualChunkModules.push(module);
15865 for (const dependency of module.dependencies) {
15866 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15867 modulesToHandle.add(dependency);
15868 }
15869 }
15870 }
15871}
15872function analyzeModuleGraph(entryModules) {
15873 const dynamicEntryModules = new Set();
15874 const dependentEntryPointsByModule = new Map();
15875 const entriesToHandle = new Set(entryModules);
15876 for (const currentEntry of entriesToHandle) {
15877 const modulesToHandle = new Set([currentEntry]);
15878 for (const module of modulesToHandle) {
15879 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
15880 for (const dependency of module.getDependenciesToBeIncluded()) {
15881 if (!(dependency instanceof ExternalModule)) {
15882 modulesToHandle.add(dependency);
15883 }
15884 }
15885 for (const { resolution } of module.dynamicImports) {
15886 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
15887 dynamicEntryModules.add(resolution);
15888 entriesToHandle.add(resolution);
15889 }
15890 }
15891 for (const dependency of module.implicitlyLoadedBefore) {
15892 dynamicEntryModules.add(dependency);
15893 entriesToHandle.add(dependency);
15894 }
15895 }
15896 }
15897 return { dependentEntryPointsByModule, dynamicEntryModules };
15898}
15899function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15900 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15901 for (const dynamicEntry of dynamicEntryModules) {
15902 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15903 for (const importer of [
15904 ...dynamicEntry.includedDynamicImporters,
15905 ...dynamicEntry.implicitlyLoadedAfter
15906 ]) {
15907 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15908 dynamicDependentEntryPoints.add(entryPoint);
15909 }
15910 }
15911 }
15912 return dynamicallyDependentEntryPointsByDynamicEntry;
15913}
15914function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15915 const chunkModules = Object.create(null);
15916 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15917 let chunkSignature = '';
15918 for (const entry of allEntryPoints) {
15919 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15920 }
15921 const chunk = chunkModules[chunkSignature];
15922 if (chunk) {
15923 chunk.push(module);
15924 }
15925 else {
15926 chunkModules[chunkSignature] = [module];
15927 }
15928 }
15929 return Object.values(chunkModules).map(modules => ({
15930 alias: null,
15931 modules
15932 }));
15933}
15934
15935// ported from https://github.com/substack/node-commondir
15936function commondir(files) {
15937 if (files.length === 0)
15938 return '/';
15939 if (files.length === 1)
15940 return require$$0.dirname(files[0]);
15941 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15942 const pathSegements = file.split(/\/+|\\+/);
15943 let i;
15944 for (i = 0; commonSegments[i] === pathSegements[i] &&
15945 i < Math.min(commonSegments.length, pathSegements.length); i++)
15946 ;
15947 return commonSegments.slice(0, i);
15948 }, files[0].split(/\/+|\\+/));
15949 // Windows correctly handles paths with forward-slashes
15950 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15951}
15952
15953const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15954function sortByExecutionOrder(units) {
15955 units.sort(compareExecIndex);
15956}
15957function analyseModuleExecution(entryModules) {
15958 let nextExecIndex = 0;
15959 const cyclePaths = [];
15960 const analysedModules = new Set();
15961 const dynamicImports = new Set();
15962 const parents = new Map();
15963 const orderedModules = [];
15964 const analyseModule = (module) => {
15965 if (module instanceof Module) {
15966 for (const dependency of module.dependencies) {
15967 if (parents.has(dependency)) {
15968 if (!analysedModules.has(dependency)) {
15969 cyclePaths.push(getCyclePath(dependency, module, parents));
15970 }
15971 continue;
15972 }
15973 parents.set(dependency, module);
15974 analyseModule(dependency);
15975 }
15976 for (const dependency of module.implicitlyLoadedBefore) {
15977 dynamicImports.add(dependency);
15978 }
15979 for (const { resolution } of module.dynamicImports) {
15980 if (resolution instanceof Module) {
15981 dynamicImports.add(resolution);
15982 }
15983 }
15984 orderedModules.push(module);
15985 }
15986 module.execIndex = nextExecIndex++;
15987 analysedModules.add(module);
15988 };
15989 for (const curEntry of entryModules) {
15990 if (!parents.has(curEntry)) {
15991 parents.set(curEntry, null);
15992 analyseModule(curEntry);
15993 }
15994 }
15995 for (const curEntry of dynamicImports) {
15996 if (!parents.has(curEntry)) {
15997 parents.set(curEntry, null);
15998 analyseModule(curEntry);
15999 }
16000 }
16001 return { cyclePaths, orderedModules };
16002}
16003function getCyclePath(module, parent, parents) {
16004 const cycleSymbol = Symbol(module.id);
16005 const path = [relativeId(module.id)];
16006 let nextModule = parent;
16007 module.cycles.add(cycleSymbol);
16008 while (nextModule !== module) {
16009 nextModule.cycles.add(cycleSymbol);
16010 path.push(relativeId(nextModule.id));
16011 nextModule = parents.get(nextModule);
16012 }
16013 path.push(path[0]);
16014 path.reverse();
16015 return path;
16016}
16017
16018function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
16019 const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
16020 const cnst = constBindings ? 'const' : 'var';
16021 const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
16022 const getFunctionIntro = arrowFunctions
16023 ? (params, { isAsync, name }) => {
16024 const singleParam = params.length === 1;
16025 const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
16026 return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
16027 }
16028 : getNonArrowFunctionIntro;
16029 const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
16030 `${getFunctionIntro(params, {
16031 isAsync: false,
16032 name
16033 })}${arrowFunctions
16034 ? lineBreakIndent
16035 ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
16036 : ''
16037 : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
16038 arrowFunctions
16039 ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
16040 : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
16041 ];
16042 const isValidPropName = reservedNamesAsProps
16043 ? (name) => validPropName.test(name)
16044 : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
16045 return {
16046 _,
16047 cnst,
16048 getDirectReturnFunction,
16049 getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
16050 const [left, right] = getDirectReturnFunction(params, {
16051 functionReturn: true,
16052 lineBreakIndent: null,
16053 name: null
16054 });
16055 return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
16056 },
16057 getFunctionIntro,
16058 getNonArrowFunctionIntro,
16059 getObject(fields, { lineBreakIndent }) {
16060 const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
16061 return `{${fields
16062 .map(([key, value]) => {
16063 if (key === null)
16064 return `${prefix}${value}`;
16065 const needsQuotes = !isValidPropName(key);
16066 return key === value && objectShorthand && !needsQuotes
16067 ? prefix + key
16068 : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
16069 })
16070 .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
16071 },
16072 getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
16073 n,
16074 s
16075 };
16076}
16077const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
16078const validPropName = /^(?!\d)[\w$]+$/;
16079
16080class Bundle {
16081 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
16082 this.outputOptions = outputOptions;
16083 this.unsetOptions = unsetOptions;
16084 this.inputOptions = inputOptions;
16085 this.pluginDriver = pluginDriver;
16086 this.graph = graph;
16087 this.facadeChunkByModule = new Map();
16088 this.includedNamespaces = new Set();
16089 }
16090 async generate(isWrite) {
16091 timeStart('GENERATE', 1);
16092 const outputBundle = Object.create(null);
16093 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
16094 try {
16095 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
16096 timeStart('generate chunks', 2);
16097 const chunks = await this.generateChunks();
16098 if (chunks.length > 1) {
16099 validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
16100 }
16101 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
16102 timeEnd('generate chunks', 2);
16103 timeStart('render modules', 2);
16104 // We need to create addons before prerender because at the moment, there
16105 // can be no async code between prerender and render due to internal state
16106 const addons = await createAddons(this.outputOptions, this.pluginDriver);
16107 const snippets = getGenerateCodeSnippets(this.outputOptions);
16108 this.prerenderChunks(chunks, inputBase, snippets);
16109 timeEnd('render modules', 2);
16110 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
16111 }
16112 catch (err) {
16113 await this.pluginDriver.hookParallel('renderError', [err]);
16114 throw err;
16115 }
16116 await this.pluginDriver.hookSeq('generateBundle', [
16117 this.outputOptions,
16118 outputBundle,
16119 isWrite
16120 ]);
16121 this.finaliseAssets(outputBundle);
16122 timeEnd('GENERATE', 1);
16123 return outputBundle;
16124 }
16125 async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
16126 this.assignChunkIds(chunks, inputBase, addons, outputBundle);
16127 for (const chunk of chunks) {
16128 outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
16129 }
16130 await Promise.all(chunks.map(async (chunk) => {
16131 const outputChunk = outputBundle[chunk.id];
16132 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
16133 }));
16134 }
16135 async addManualChunks(manualChunks) {
16136 const manualChunkAliasByEntry = new Map();
16137 const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
16138 alias,
16139 entries: await this.graph.moduleLoader.addAdditionalModules(files)
16140 })));
16141 for (const { alias, entries } of chunkEntries) {
16142 for (const entry of entries) {
16143 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
16144 }
16145 }
16146 return manualChunkAliasByEntry;
16147 }
16148 assignChunkIds(chunks, inputBase, addons, bundle) {
16149 const entryChunks = [];
16150 const otherChunks = [];
16151 for (const chunk of chunks) {
16152 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
16153 ? entryChunks
16154 : otherChunks).push(chunk);
16155 }
16156 // make sure entry chunk names take precedence with regard to deconflicting
16157 const chunksForNaming = entryChunks.concat(otherChunks);
16158 for (const chunk of chunksForNaming) {
16159 if (this.outputOptions.file) {
16160 chunk.id = require$$0.basename(this.outputOptions.file);
16161 }
16162 else if (this.outputOptions.preserveModules) {
16163 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
16164 }
16165 else {
16166 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
16167 }
16168 bundle[chunk.id] = FILE_PLACEHOLDER;
16169 }
16170 }
16171 assignManualChunks(getManualChunk) {
16172 const manualChunkAliasesWithEntry = [];
16173 const manualChunksApi = {
16174 getModuleIds: () => this.graph.modulesById.keys(),
16175 getModuleInfo: this.graph.getModuleInfo
16176 };
16177 for (const module of this.graph.modulesById.values()) {
16178 if (module instanceof Module) {
16179 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
16180 if (typeof manualChunkAlias === 'string') {
16181 manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
16182 }
16183 }
16184 }
16185 manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
16186 const manualChunkAliasByEntry = new Map();
16187 for (const [alias, module] of manualChunkAliasesWithEntry) {
16188 addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
16189 }
16190 return manualChunkAliasByEntry;
16191 }
16192 finaliseAssets(outputBundle) {
16193 for (const file of Object.values(outputBundle)) {
16194 if (!file.type) {
16195 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);
16196 file.type = 'asset';
16197 }
16198 if (this.outputOptions.validate && 'code' in file) {
16199 try {
16200 this.graph.contextParse(file.code, {
16201 allowHashBang: true,
16202 ecmaVersion: 'latest'
16203 });
16204 }
16205 catch (err) {
16206 this.inputOptions.onwarn(errChunkInvalid(file, err));
16207 }
16208 }
16209 }
16210 this.pluginDriver.finaliseAssets();
16211 }
16212 async generateChunks() {
16213 const { manualChunks } = this.outputOptions;
16214 const manualChunkAliasByEntry = typeof manualChunks === 'object'
16215 ? await this.addManualChunks(manualChunks)
16216 : this.assignManualChunks(manualChunks);
16217 const chunks = [];
16218 const chunkByModule = new Map();
16219 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
16220 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
16221 : this.outputOptions.preserveModules
16222 ? getIncludedModules(this.graph.modulesById).map(module => ({
16223 alias: null,
16224 modules: [module]
16225 }))
16226 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
16227 sortByExecutionOrder(modules);
16228 const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
16229 chunks.push(chunk);
16230 for (const module of modules) {
16231 chunkByModule.set(module, chunk);
16232 }
16233 }
16234 for (const chunk of chunks) {
16235 chunk.link();
16236 }
16237 const facades = [];
16238 for (const chunk of chunks) {
16239 facades.push(...chunk.generateFacades());
16240 }
16241 return [...chunks, ...facades];
16242 }
16243 prerenderChunks(chunks, inputBase, snippets) {
16244 for (const chunk of chunks) {
16245 chunk.generateExports();
16246 }
16247 for (const chunk of chunks) {
16248 chunk.preRender(this.outputOptions, inputBase, snippets);
16249 }
16250 }
16251}
16252function getAbsoluteEntryModulePaths(chunks) {
16253 const absoluteEntryModulePaths = [];
16254 for (const chunk of chunks) {
16255 for (const entryModule of chunk.entryModules) {
16256 if (isAbsolute(entryModule.id)) {
16257 absoluteEntryModulePaths.push(entryModule.id);
16258 }
16259 }
16260 }
16261 return absoluteEntryModulePaths;
16262}
16263function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16264 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
16265 return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
16266 if (typeof outputOptions.file === 'string')
16267 return error(errInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
16268 if (outputOptions.sourcemapFile)
16269 return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
16270 if (!outputOptions.amd.autoId && outputOptions.amd.id)
16271 onWarn(errInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
16272}
16273function getIncludedModules(modulesById) {
16274 return [...modulesById.values()].filter((module) => module instanceof Module &&
16275 (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
16276}
16277function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
16278 const existingAlias = manualChunkAliasByEntry.get(module);
16279 if (typeof existingAlias === 'string' && existingAlias !== alias) {
16280 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
16281 }
16282 manualChunkAliasByEntry.set(module, alias);
16283}
16284
16285// This file was generated. Do not modify manually!
16286var 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, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 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, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 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, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
16287
16288// This file was generated. Do not modify manually!
16289var 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, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 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, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 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, 38, 6, 186, 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, 19, 72, 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, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 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, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 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, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 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, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
16290
16291// This file was generated. Do not modify manually!
16292var 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\u0898-\u089f\u08ca-\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\u0c3c\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-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\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-\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";
16293
16294// This file was generated. Do not modify manually!
16295var 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\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\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-\u1711\u171f-\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-\u1b4c\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-\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-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\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";
16296
16297// These are a run-length and offset encoded representation of the
16298
16299// Reserved word lists for various dialects of the language
16300
16301var reservedWords = {
16302 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",
16303 5: "class enum extends super const export import",
16304 6: "enum",
16305 strict: "implements interface let package private protected public static yield",
16306 strictBind: "eval arguments"
16307};
16308
16309// And the keywords
16310
16311var 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";
16312
16313var keywords$1 = {
16314 5: ecma5AndLessKeywords,
16315 "5module": ecma5AndLessKeywords + " export import",
16316 6: ecma5AndLessKeywords + " const class extends export import super"
16317};
16318
16319var keywordRelationalOperator = /^in(stanceof)?$/;
16320
16321// ## Character categories
16322
16323var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
16324var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
16325
16326// This has a complexity linear to the value of the code. The
16327// assumption is that looking up astral identifier characters is
16328// rare.
16329function isInAstralSet(code, set) {
16330 var pos = 0x10000;
16331 for (var i = 0; i < set.length; i += 2) {
16332 pos += set[i];
16333 if (pos > code) { return false }
16334 pos += set[i + 1];
16335 if (pos >= code) { return true }
16336 }
16337}
16338
16339// Test whether a given character code starts an identifier.
16340
16341function isIdentifierStart(code, astral) {
16342 if (code < 65) { return code === 36 }
16343 if (code < 91) { return true }
16344 if (code < 97) { return code === 95 }
16345 if (code < 123) { return true }
16346 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
16347 if (astral === false) { return false }
16348 return isInAstralSet(code, astralIdentifierStartCodes)
16349}
16350
16351// Test whether a given character is part of an identifier.
16352
16353function isIdentifierChar(code, astral) {
16354 if (code < 48) { return code === 36 }
16355 if (code < 58) { return true }
16356 if (code < 65) { return false }
16357 if (code < 91) { return true }
16358 if (code < 97) { return code === 95 }
16359 if (code < 123) { return true }
16360 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
16361 if (astral === false) { return false }
16362 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
16363}
16364
16365// ## Token types
16366
16367// The assignment of fine-grained, information-carrying type objects
16368// allows the tokenizer to store the information it has about a
16369// token in a way that is very cheap for the parser to look up.
16370
16371// All token type variables start with an underscore, to make them
16372// easy to recognize.
16373
16374// The `beforeExpr` property is used to disambiguate between regular
16375// expressions and divisions. It is set on all token types that can
16376// be followed by an expression (thus, a slash after them would be a
16377// regular expression).
16378//
16379// The `startsExpr` property is used to check if the token ends a
16380// `yield` expression. It is set on all token types that either can
16381// directly start an expression (like a quotation mark) or can
16382// continue an expression (like the body of a string).
16383//
16384// `isLoop` marks a keyword as starting a loop, which is important
16385// to know when parsing a label, in order to allow or disallow
16386// continue jumps to that label.
16387
16388var TokenType = function TokenType(label, conf) {
16389 if ( conf === void 0 ) conf = {};
16390
16391 this.label = label;
16392 this.keyword = conf.keyword;
16393 this.beforeExpr = !!conf.beforeExpr;
16394 this.startsExpr = !!conf.startsExpr;
16395 this.isLoop = !!conf.isLoop;
16396 this.isAssign = !!conf.isAssign;
16397 this.prefix = !!conf.prefix;
16398 this.postfix = !!conf.postfix;
16399 this.binop = conf.binop || null;
16400 this.updateContext = null;
16401};
16402
16403function binop(name, prec) {
16404 return new TokenType(name, {beforeExpr: true, binop: prec})
16405}
16406var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
16407
16408// Map keyword names to token types.
16409
16410var keywords = {};
16411
16412// Succinct definitions of keyword token types
16413function kw(name, options) {
16414 if ( options === void 0 ) options = {};
16415
16416 options.keyword = name;
16417 return keywords[name] = new TokenType(name, options)
16418}
16419
16420var types$1 = {
16421 num: new TokenType("num", startsExpr),
16422 regexp: new TokenType("regexp", startsExpr),
16423 string: new TokenType("string", startsExpr),
16424 name: new TokenType("name", startsExpr),
16425 privateId: new TokenType("privateId", startsExpr),
16426 eof: new TokenType("eof"),
16427
16428 // Punctuation token types.
16429 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
16430 bracketR: new TokenType("]"),
16431 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
16432 braceR: new TokenType("}"),
16433 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
16434 parenR: new TokenType(")"),
16435 comma: new TokenType(",", beforeExpr),
16436 semi: new TokenType(";", beforeExpr),
16437 colon: new TokenType(":", beforeExpr),
16438 dot: new TokenType("."),
16439 question: new TokenType("?", beforeExpr),
16440 questionDot: new TokenType("?."),
16441 arrow: new TokenType("=>", beforeExpr),
16442 template: new TokenType("template"),
16443 invalidTemplate: new TokenType("invalidTemplate"),
16444 ellipsis: new TokenType("...", beforeExpr),
16445 backQuote: new TokenType("`", startsExpr),
16446 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
16447
16448 // Operators. These carry several kinds of properties to help the
16449 // parser use them properly (the presence of these properties is
16450 // what categorizes them as operators).
16451 //
16452 // `binop`, when present, specifies that this operator is a binary
16453 // operator, and will refer to its precedence.
16454 //
16455 // `prefix` and `postfix` mark the operator as a prefix or postfix
16456 // unary operator.
16457 //
16458 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
16459 // binary operators with a very low precedence, that should result
16460 // in AssignmentExpression nodes.
16461
16462 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
16463 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
16464 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
16465 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
16466 logicalOR: binop("||", 1),
16467 logicalAND: binop("&&", 2),
16468 bitwiseOR: binop("|", 3),
16469 bitwiseXOR: binop("^", 4),
16470 bitwiseAND: binop("&", 5),
16471 equality: binop("==/!=/===/!==", 6),
16472 relational: binop("</>/<=/>=", 7),
16473 bitShift: binop("<</>>/>>>", 8),
16474 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
16475 modulo: binop("%", 10),
16476 star: binop("*", 10),
16477 slash: binop("/", 10),
16478 starstar: new TokenType("**", {beforeExpr: true}),
16479 coalesce: binop("??", 1),
16480
16481 // Keyword token types.
16482 _break: kw("break"),
16483 _case: kw("case", beforeExpr),
16484 _catch: kw("catch"),
16485 _continue: kw("continue"),
16486 _debugger: kw("debugger"),
16487 _default: kw("default", beforeExpr),
16488 _do: kw("do", {isLoop: true, beforeExpr: true}),
16489 _else: kw("else", beforeExpr),
16490 _finally: kw("finally"),
16491 _for: kw("for", {isLoop: true}),
16492 _function: kw("function", startsExpr),
16493 _if: kw("if"),
16494 _return: kw("return", beforeExpr),
16495 _switch: kw("switch"),
16496 _throw: kw("throw", beforeExpr),
16497 _try: kw("try"),
16498 _var: kw("var"),
16499 _const: kw("const"),
16500 _while: kw("while", {isLoop: true}),
16501 _with: kw("with"),
16502 _new: kw("new", {beforeExpr: true, startsExpr: true}),
16503 _this: kw("this", startsExpr),
16504 _super: kw("super", startsExpr),
16505 _class: kw("class", startsExpr),
16506 _extends: kw("extends", beforeExpr),
16507 _export: kw("export"),
16508 _import: kw("import", startsExpr),
16509 _null: kw("null", startsExpr),
16510 _true: kw("true", startsExpr),
16511 _false: kw("false", startsExpr),
16512 _in: kw("in", {beforeExpr: true, binop: 7}),
16513 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
16514 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
16515 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
16516 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
16517};
16518
16519// Matches a whole line break (where CRLF is considered a single
16520// line break). Used to count lines.
16521
16522var lineBreak = /\r\n?|\n|\u2028|\u2029/;
16523var lineBreakG = new RegExp(lineBreak.source, "g");
16524
16525function isNewLine(code) {
16526 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
16527}
16528
16529function nextLineBreak(code, from, end) {
16530 if ( end === void 0 ) end = code.length;
16531
16532 for (var i = from; i < end; i++) {
16533 var next = code.charCodeAt(i);
16534 if (isNewLine(next))
16535 { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
16536 }
16537 return -1
16538}
16539
16540var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
16541
16542var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
16543
16544var ref = Object.prototype;
16545var hasOwnProperty = ref.hasOwnProperty;
16546var toString = ref.toString;
16547
16548var hasOwn = Object.hasOwn || (function (obj, propName) { return (
16549 hasOwnProperty.call(obj, propName)
16550); });
16551
16552var isArray = Array.isArray || (function (obj) { return (
16553 toString.call(obj) === "[object Array]"
16554); });
16555
16556function wordsRegexp(words) {
16557 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
16558}
16559
16560function codePointToString(code) {
16561 // UTF-16 Decoding
16562 if (code <= 0xFFFF) { return String.fromCharCode(code) }
16563 code -= 0x10000;
16564 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
16565}
16566
16567var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
16568
16569// These are used when `options.locations` is on, for the
16570// `startLoc` and `endLoc` properties.
16571
16572var Position = function Position(line, col) {
16573 this.line = line;
16574 this.column = col;
16575};
16576
16577Position.prototype.offset = function offset (n) {
16578 return new Position(this.line, this.column + n)
16579};
16580
16581var SourceLocation = function SourceLocation(p, start, end) {
16582 this.start = start;
16583 this.end = end;
16584 if (p.sourceFile !== null) { this.source = p.sourceFile; }
16585};
16586
16587// The `getLineInfo` function is mostly useful when the
16588// `locations` option is off (for performance reasons) and you
16589// want to find the line/column position for a given character
16590// offset. `input` should be the code string that the offset refers
16591// into.
16592
16593function getLineInfo(input, offset) {
16594 for (var line = 1, cur = 0;;) {
16595 var nextBreak = nextLineBreak(input, cur, offset);
16596 if (nextBreak < 0) { return new Position(line, offset - cur) }
16597 ++line;
16598 cur = nextBreak;
16599 }
16600}
16601
16602// A second argument must be given to configure the parser process.
16603// These options are recognized (only `ecmaVersion` is required):
16604
16605var defaultOptions = {
16606 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
16607 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
16608 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
16609 // latest version the library supports). This influences support
16610 // for strict mode, the set of reserved words, and support for
16611 // new syntax features.
16612 ecmaVersion: null,
16613 // `sourceType` indicates the mode the code should be parsed in.
16614 // Can be either `"script"` or `"module"`. This influences global
16615 // strict mode and parsing of `import` and `export` declarations.
16616 sourceType: "script",
16617 // `onInsertedSemicolon` can be a callback that will be called
16618 // when a semicolon is automatically inserted. It will be passed
16619 // the position of the comma as an offset, and if `locations` is
16620 // enabled, it is given the location as a `{line, column}` object
16621 // as second argument.
16622 onInsertedSemicolon: null,
16623 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
16624 // trailing commas.
16625 onTrailingComma: null,
16626 // By default, reserved words are only enforced if ecmaVersion >= 5.
16627 // Set `allowReserved` to a boolean value to explicitly turn this on
16628 // an off. When this option has the value "never", reserved words
16629 // and keywords can also not be used as property names.
16630 allowReserved: null,
16631 // When enabled, a return at the top level is not considered an
16632 // error.
16633 allowReturnOutsideFunction: false,
16634 // When enabled, import/export statements are not constrained to
16635 // appearing at the top of the program, and an import.meta expression
16636 // in a script isn't considered an error.
16637 allowImportExportEverywhere: false,
16638 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
16639 // When enabled, await identifiers are allowed to appear at the top-level scope,
16640 // but they are still not allowed in non-async functions.
16641 allowAwaitOutsideFunction: null,
16642 // When enabled, super identifiers are not constrained to
16643 // appearing in methods and do not raise an error when they appear elsewhere.
16644 allowSuperOutsideMethod: null,
16645 // When enabled, hashbang directive in the beginning of file
16646 // is allowed and treated as a line comment.
16647 allowHashBang: false,
16648 // When `locations` is on, `loc` properties holding objects with
16649 // `start` and `end` properties in `{line, column}` form (with
16650 // line being 1-based and column 0-based) will be attached to the
16651 // nodes.
16652 locations: false,
16653 // A function can be passed as `onToken` option, which will
16654 // cause Acorn to call that function with object in the same
16655 // format as tokens returned from `tokenizer().getToken()`. Note
16656 // that you are not allowed to call the parser from the
16657 // callback—that will corrupt its internal state.
16658 onToken: null,
16659 // A function can be passed as `onComment` option, which will
16660 // cause Acorn to call that function with `(block, text, start,
16661 // end)` parameters whenever a comment is skipped. `block` is a
16662 // boolean indicating whether this is a block (`/* */`) comment,
16663 // `text` is the content of the comment, and `start` and `end` are
16664 // character offsets that denote the start and end of the comment.
16665 // When the `locations` option is on, two more parameters are
16666 // passed, the full `{line, column}` locations of the start and
16667 // end of the comments. Note that you are not allowed to call the
16668 // parser from the callback—that will corrupt its internal state.
16669 onComment: null,
16670 // Nodes have their start and end characters offsets recorded in
16671 // `start` and `end` properties (directly on the node, rather than
16672 // the `loc` object, which holds line/column data. To also add a
16673 // [semi-standardized][range] `range` property holding a `[start,
16674 // end]` array with the same numbers, set the `ranges` option to
16675 // `true`.
16676 //
16677 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
16678 ranges: false,
16679 // It is possible to parse multiple files into a single AST by
16680 // passing the tree produced by parsing the first file as
16681 // `program` option in subsequent parses. This will add the
16682 // toplevel forms of the parsed file to the `Program` (top) node
16683 // of an existing parse tree.
16684 program: null,
16685 // When `locations` is on, you can pass this to record the source
16686 // file in every node's `loc` object.
16687 sourceFile: null,
16688 // This value, if given, is stored in every node, whether
16689 // `locations` is on or off.
16690 directSourceFile: null,
16691 // When enabled, parenthesized expressions are represented by
16692 // (non-standard) ParenthesizedExpression nodes
16693 preserveParens: false
16694};
16695
16696// Interpret and default an options object
16697
16698var warnedAboutEcmaVersion = false;
16699
16700function getOptions(opts) {
16701 var options = {};
16702
16703 for (var opt in defaultOptions)
16704 { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
16705
16706 if (options.ecmaVersion === "latest") {
16707 options.ecmaVersion = 1e8;
16708 } else if (options.ecmaVersion == null) {
16709 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
16710 warnedAboutEcmaVersion = true;
16711 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
16712 }
16713 options.ecmaVersion = 11;
16714 } else if (options.ecmaVersion >= 2015) {
16715 options.ecmaVersion -= 2009;
16716 }
16717
16718 if (options.allowReserved == null)
16719 { options.allowReserved = options.ecmaVersion < 5; }
16720
16721 if (isArray(options.onToken)) {
16722 var tokens = options.onToken;
16723 options.onToken = function (token) { return tokens.push(token); };
16724 }
16725 if (isArray(options.onComment))
16726 { options.onComment = pushComment(options, options.onComment); }
16727
16728 return options
16729}
16730
16731function pushComment(options, array) {
16732 return function(block, text, start, end, startLoc, endLoc) {
16733 var comment = {
16734 type: block ? "Block" : "Line",
16735 value: text,
16736 start: start,
16737 end: end
16738 };
16739 if (options.locations)
16740 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
16741 if (options.ranges)
16742 { comment.range = [start, end]; }
16743 array.push(comment);
16744 }
16745}
16746
16747// Each scope gets a bitset that may contain these flags
16748var
16749 SCOPE_TOP = 1,
16750 SCOPE_FUNCTION = 2,
16751 SCOPE_ASYNC = 4,
16752 SCOPE_GENERATOR = 8,
16753 SCOPE_ARROW = 16,
16754 SCOPE_SIMPLE_CATCH = 32,
16755 SCOPE_SUPER = 64,
16756 SCOPE_DIRECT_SUPER = 128,
16757 SCOPE_CLASS_STATIC_BLOCK = 256,
16758 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
16759
16760function functionFlags(async, generator) {
16761 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
16762}
16763
16764// Used in checkLVal* and declareName to determine the type of a binding
16765var
16766 BIND_NONE = 0, // Not a binding
16767 BIND_VAR = 1, // Var-style binding
16768 BIND_LEXICAL = 2, // Let- or const-style binding
16769 BIND_FUNCTION = 3, // Function declaration
16770 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
16771 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
16772
16773var Parser = function Parser(options, input, startPos) {
16774 this.options = options = getOptions(options);
16775 this.sourceFile = options.sourceFile;
16776 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
16777 var reserved = "";
16778 if (options.allowReserved !== true) {
16779 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
16780 if (options.sourceType === "module") { reserved += " await"; }
16781 }
16782 this.reservedWords = wordsRegexp(reserved);
16783 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
16784 this.reservedWordsStrict = wordsRegexp(reservedStrict);
16785 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
16786 this.input = String(input);
16787
16788 // Used to signal to callers of `readWord1` whether the word
16789 // contained any escape sequences. This is needed because words with
16790 // escape sequences must not be interpreted as keywords.
16791 this.containsEsc = false;
16792
16793 // Set up token state
16794
16795 // The current position of the tokenizer in the input.
16796 if (startPos) {
16797 this.pos = startPos;
16798 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
16799 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
16800 } else {
16801 this.pos = this.lineStart = 0;
16802 this.curLine = 1;
16803 }
16804
16805 // Properties of the current token:
16806 // Its type
16807 this.type = types$1.eof;
16808 // For tokens that include more information than their type, the value
16809 this.value = null;
16810 // Its start and end offset
16811 this.start = this.end = this.pos;
16812 // And, if locations are used, the {line, column} object
16813 // corresponding to those offsets
16814 this.startLoc = this.endLoc = this.curPosition();
16815
16816 // Position information for the previous token
16817 this.lastTokEndLoc = this.lastTokStartLoc = null;
16818 this.lastTokStart = this.lastTokEnd = this.pos;
16819
16820 // The context stack is used to superficially track syntactic
16821 // context to predict whether a regular expression is allowed in a
16822 // given position.
16823 this.context = this.initialContext();
16824 this.exprAllowed = true;
16825
16826 // Figure out if it's a module code.
16827 this.inModule = options.sourceType === "module";
16828 this.strict = this.inModule || this.strictDirective(this.pos);
16829
16830 // Used to signify the start of a potential arrow function
16831 this.potentialArrowAt = -1;
16832 this.potentialArrowInForAwait = false;
16833
16834 // Positions to delayed-check that yield/await does not exist in default parameters.
16835 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
16836 // Labels in scope.
16837 this.labels = [];
16838 // Thus-far undefined exports.
16839 this.undefinedExports = Object.create(null);
16840
16841 // If enabled, skip leading hashbang line.
16842 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
16843 { this.skipLineComment(2); }
16844
16845 // Scope tracking for duplicate variable names (see scope.js)
16846 this.scopeStack = [];
16847 this.enterScope(SCOPE_TOP);
16848
16849 // For RegExp validation
16850 this.regexpState = null;
16851
16852 // The stack of private names.
16853 // Each element has two properties: 'declared' and 'used'.
16854 // When it exited from the outermost class definition, all used private names must be declared.
16855 this.privateNameStack = [];
16856};
16857
16858var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
16859
16860Parser.prototype.parse = function parse () {
16861 var node = this.options.program || this.startNode();
16862 this.nextToken();
16863 return this.parseTopLevel(node)
16864};
16865
16866prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
16867
16868prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
16869
16870prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
16871
16872prototypeAccessors.canAwait.get = function () {
16873 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
16874 var scope = this.scopeStack[i];
16875 if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
16876 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
16877 }
16878 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
16879};
16880
16881prototypeAccessors.allowSuper.get = function () {
16882 var ref = this.currentThisScope();
16883 var flags = ref.flags;
16884 var inClassFieldInit = ref.inClassFieldInit;
16885 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
16886};
16887
16888prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
16889
16890prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
16891
16892prototypeAccessors.allowNewDotTarget.get = function () {
16893 var ref = this.currentThisScope();
16894 var flags = ref.flags;
16895 var inClassFieldInit = ref.inClassFieldInit;
16896 return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
16897};
16898
16899prototypeAccessors.inClassStaticBlock.get = function () {
16900 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
16901};
16902
16903Parser.extend = function extend () {
16904 var plugins = [], len = arguments.length;
16905 while ( len-- ) plugins[ len ] = arguments[ len ];
16906
16907 var cls = this;
16908 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
16909 return cls
16910};
16911
16912Parser.parse = function parse (input, options) {
16913 return new this(options, input).parse()
16914};
16915
16916Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
16917 var parser = new this(options, input, pos);
16918 parser.nextToken();
16919 return parser.parseExpression()
16920};
16921
16922Parser.tokenizer = function tokenizer (input, options) {
16923 return new this(options, input)
16924};
16925
16926Object.defineProperties( Parser.prototype, prototypeAccessors );
16927
16928var pp$9 = Parser.prototype;
16929
16930// ## Parser utilities
16931
16932var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
16933pp$9.strictDirective = function(start) {
16934 if (this.options.ecmaVersion < 5) { return false }
16935 for (;;) {
16936 // Try to find string literal.
16937 skipWhiteSpace.lastIndex = start;
16938 start += skipWhiteSpace.exec(this.input)[0].length;
16939 var match = literal.exec(this.input.slice(start));
16940 if (!match) { return false }
16941 if ((match[1] || match[2]) === "use strict") {
16942 skipWhiteSpace.lastIndex = start + match[0].length;
16943 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
16944 var next = this.input.charAt(end);
16945 return next === ";" || next === "}" ||
16946 (lineBreak.test(spaceAfter[0]) &&
16947 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
16948 }
16949 start += match[0].length;
16950
16951 // Skip semicolon, if any.
16952 skipWhiteSpace.lastIndex = start;
16953 start += skipWhiteSpace.exec(this.input)[0].length;
16954 if (this.input[start] === ";")
16955 { start++; }
16956 }
16957};
16958
16959// Predicate that tests whether the next token is of the given
16960// type, and if yes, consumes it as a side effect.
16961
16962pp$9.eat = function(type) {
16963 if (this.type === type) {
16964 this.next();
16965 return true
16966 } else {
16967 return false
16968 }
16969};
16970
16971// Tests whether parsed token is a contextual keyword.
16972
16973pp$9.isContextual = function(name) {
16974 return this.type === types$1.name && this.value === name && !this.containsEsc
16975};
16976
16977// Consumes contextual keyword if possible.
16978
16979pp$9.eatContextual = function(name) {
16980 if (!this.isContextual(name)) { return false }
16981 this.next();
16982 return true
16983};
16984
16985// Asserts that following token is given contextual keyword.
16986
16987pp$9.expectContextual = function(name) {
16988 if (!this.eatContextual(name)) { this.unexpected(); }
16989};
16990
16991// Test whether a semicolon can be inserted at the current position.
16992
16993pp$9.canInsertSemicolon = function() {
16994 return this.type === types$1.eof ||
16995 this.type === types$1.braceR ||
16996 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
16997};
16998
16999pp$9.insertSemicolon = function() {
17000 if (this.canInsertSemicolon()) {
17001 if (this.options.onInsertedSemicolon)
17002 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
17003 return true
17004 }
17005};
17006
17007// Consume a semicolon, or, failing that, see if we are allowed to
17008// pretend that there is a semicolon at this position.
17009
17010pp$9.semicolon = function() {
17011 if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
17012};
17013
17014pp$9.afterTrailingComma = function(tokType, notNext) {
17015 if (this.type === tokType) {
17016 if (this.options.onTrailingComma)
17017 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
17018 if (!notNext)
17019 { this.next(); }
17020 return true
17021 }
17022};
17023
17024// Expect a token of a given type. If found, consume it, otherwise,
17025// raise an unexpected token error.
17026
17027pp$9.expect = function(type) {
17028 this.eat(type) || this.unexpected();
17029};
17030
17031// Raise an unexpected token error.
17032
17033pp$9.unexpected = function(pos) {
17034 this.raise(pos != null ? pos : this.start, "Unexpected token");
17035};
17036
17037var DestructuringErrors = function DestructuringErrors() {
17038 this.shorthandAssign =
17039 this.trailingComma =
17040 this.parenthesizedAssign =
17041 this.parenthesizedBind =
17042 this.doubleProto =
17043 -1;
17044};
17045
17046pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
17047 if (!refDestructuringErrors) { return }
17048 if (refDestructuringErrors.trailingComma > -1)
17049 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
17050 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
17051 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
17052};
17053
17054pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
17055 if (!refDestructuringErrors) { return false }
17056 var shorthandAssign = refDestructuringErrors.shorthandAssign;
17057 var doubleProto = refDestructuringErrors.doubleProto;
17058 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
17059 if (shorthandAssign >= 0)
17060 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
17061 if (doubleProto >= 0)
17062 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
17063};
17064
17065pp$9.checkYieldAwaitInDefaultParams = function() {
17066 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
17067 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
17068 if (this.awaitPos)
17069 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
17070};
17071
17072pp$9.isSimpleAssignTarget = function(expr) {
17073 if (expr.type === "ParenthesizedExpression")
17074 { return this.isSimpleAssignTarget(expr.expression) }
17075 return expr.type === "Identifier" || expr.type === "MemberExpression"
17076};
17077
17078var pp$8 = Parser.prototype;
17079
17080// ### Statement parsing
17081
17082// Parse a program. Initializes the parser, reads any number of
17083// statements, and wraps them in a Program node. Optionally takes a
17084// `program` argument. If present, the statements will be appended
17085// to its body instead of creating a new node.
17086
17087pp$8.parseTopLevel = function(node) {
17088 var exports = Object.create(null);
17089 if (!node.body) { node.body = []; }
17090 while (this.type !== types$1.eof) {
17091 var stmt = this.parseStatement(null, true, exports);
17092 node.body.push(stmt);
17093 }
17094 if (this.inModule)
17095 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
17096 {
17097 var name = list[i];
17098
17099 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
17100 } }
17101 this.adaptDirectivePrologue(node.body);
17102 this.next();
17103 node.sourceType = this.options.sourceType;
17104 return this.finishNode(node, "Program")
17105};
17106
17107var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
17108
17109pp$8.isLet = function(context) {
17110 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
17111 skipWhiteSpace.lastIndex = this.pos;
17112 var skip = skipWhiteSpace.exec(this.input);
17113 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
17114 // For ambiguous cases, determine if a LexicalDeclaration (or only a
17115 // Statement) is allowed here. If context is not empty then only a Statement
17116 // is allowed. However, `let [` is an explicit negative lookahead for
17117 // ExpressionStatement, so special-case it first.
17118 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
17119 if (context) { return false }
17120
17121 if (nextCh === 123) { return true } // '{'
17122 if (isIdentifierStart(nextCh, true)) {
17123 var pos = next + 1;
17124 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
17125 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
17126 var ident = this.input.slice(next, pos);
17127 if (!keywordRelationalOperator.test(ident)) { return true }
17128 }
17129 return false
17130};
17131
17132// check 'async [no LineTerminator here] function'
17133// - 'async /*foo*/ function' is OK.
17134// - 'async /*\n*/ function' is invalid.
17135pp$8.isAsyncFunction = function() {
17136 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
17137 { return false }
17138
17139 skipWhiteSpace.lastIndex = this.pos;
17140 var skip = skipWhiteSpace.exec(this.input);
17141 var next = this.pos + skip[0].length, after;
17142 return !lineBreak.test(this.input.slice(this.pos, next)) &&
17143 this.input.slice(next, next + 8) === "function" &&
17144 (next + 8 === this.input.length ||
17145 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
17146};
17147
17148// Parse a single statement.
17149//
17150// If expecting a statement and finding a slash operator, parse a
17151// regular expression literal. This is to handle cases like
17152// `if (foo) /blah/.exec(foo)`, where looking at the previous token
17153// does not help.
17154
17155pp$8.parseStatement = function(context, topLevel, exports) {
17156 var starttype = this.type, node = this.startNode(), kind;
17157
17158 if (this.isLet(context)) {
17159 starttype = types$1._var;
17160 kind = "let";
17161 }
17162
17163 // Most types of statements are recognized by the keyword they
17164 // start with. Many are trivial to parse, some require a bit of
17165 // complexity.
17166
17167 switch (starttype) {
17168 case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
17169 case types$1._debugger: return this.parseDebuggerStatement(node)
17170 case types$1._do: return this.parseDoStatement(node)
17171 case types$1._for: return this.parseForStatement(node)
17172 case types$1._function:
17173 // Function as sole body of either an if statement or a labeled statement
17174 // works, but not when it is part of a labeled statement that is the sole
17175 // body of an if statement.
17176 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
17177 return this.parseFunctionStatement(node, false, !context)
17178 case types$1._class:
17179 if (context) { this.unexpected(); }
17180 return this.parseClass(node, true)
17181 case types$1._if: return this.parseIfStatement(node)
17182 case types$1._return: return this.parseReturnStatement(node)
17183 case types$1._switch: return this.parseSwitchStatement(node)
17184 case types$1._throw: return this.parseThrowStatement(node)
17185 case types$1._try: return this.parseTryStatement(node)
17186 case types$1._const: case types$1._var:
17187 kind = kind || this.value;
17188 if (context && kind !== "var") { this.unexpected(); }
17189 return this.parseVarStatement(node, kind)
17190 case types$1._while: return this.parseWhileStatement(node)
17191 case types$1._with: return this.parseWithStatement(node)
17192 case types$1.braceL: return this.parseBlock(true, node)
17193 case types$1.semi: return this.parseEmptyStatement(node)
17194 case types$1._export:
17195 case types$1._import:
17196 if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
17197 skipWhiteSpace.lastIndex = this.pos;
17198 var skip = skipWhiteSpace.exec(this.input);
17199 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
17200 if (nextCh === 40 || nextCh === 46) // '(' or '.'
17201 { return this.parseExpressionStatement(node, this.parseExpression()) }
17202 }
17203
17204 if (!this.options.allowImportExportEverywhere) {
17205 if (!topLevel)
17206 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
17207 if (!this.inModule)
17208 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
17209 }
17210 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
17211
17212 // If the statement does not start with a statement keyword or a
17213 // brace, it's an ExpressionStatement or LabeledStatement. We
17214 // simply start parsing an expression, and afterwards, if the
17215 // next token is a colon and the expression was a simple
17216 // Identifier node, we switch to interpreting it as a label.
17217 default:
17218 if (this.isAsyncFunction()) {
17219 if (context) { this.unexpected(); }
17220 this.next();
17221 return this.parseFunctionStatement(node, true, !context)
17222 }
17223
17224 var maybeName = this.value, expr = this.parseExpression();
17225 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
17226 { return this.parseLabeledStatement(node, maybeName, expr, context) }
17227 else { return this.parseExpressionStatement(node, expr) }
17228 }
17229};
17230
17231pp$8.parseBreakContinueStatement = function(node, keyword) {
17232 var isBreak = keyword === "break";
17233 this.next();
17234 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
17235 else if (this.type !== types$1.name) { this.unexpected(); }
17236 else {
17237 node.label = this.parseIdent();
17238 this.semicolon();
17239 }
17240
17241 // Verify that there is an actual destination to break or
17242 // continue to.
17243 var i = 0;
17244 for (; i < this.labels.length; ++i) {
17245 var lab = this.labels[i];
17246 if (node.label == null || lab.name === node.label.name) {
17247 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
17248 if (node.label && isBreak) { break }
17249 }
17250 }
17251 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
17252 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
17253};
17254
17255pp$8.parseDebuggerStatement = function(node) {
17256 this.next();
17257 this.semicolon();
17258 return this.finishNode(node, "DebuggerStatement")
17259};
17260
17261pp$8.parseDoStatement = function(node) {
17262 this.next();
17263 this.labels.push(loopLabel);
17264 node.body = this.parseStatement("do");
17265 this.labels.pop();
17266 this.expect(types$1._while);
17267 node.test = this.parseParenExpression();
17268 if (this.options.ecmaVersion >= 6)
17269 { this.eat(types$1.semi); }
17270 else
17271 { this.semicolon(); }
17272 return this.finishNode(node, "DoWhileStatement")
17273};
17274
17275// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
17276// loop is non-trivial. Basically, we have to parse the init `var`
17277// statement or expression, disallowing the `in` operator (see
17278// the second parameter to `parseExpression`), and then check
17279// whether the next token is `in` or `of`. When there is no init
17280// part (semicolon immediately after the opening parenthesis), it
17281// is a regular `for` loop.
17282
17283pp$8.parseForStatement = function(node) {
17284 this.next();
17285 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
17286 this.labels.push(loopLabel);
17287 this.enterScope(0);
17288 this.expect(types$1.parenL);
17289 if (this.type === types$1.semi) {
17290 if (awaitAt > -1) { this.unexpected(awaitAt); }
17291 return this.parseFor(node, null)
17292 }
17293 var isLet = this.isLet();
17294 if (this.type === types$1._var || this.type === types$1._const || isLet) {
17295 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
17296 this.next();
17297 this.parseVar(init$1, true, kind);
17298 this.finishNode(init$1, "VariableDeclaration");
17299 if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
17300 if (this.options.ecmaVersion >= 9) {
17301 if (this.type === types$1._in) {
17302 if (awaitAt > -1) { this.unexpected(awaitAt); }
17303 } else { node.await = awaitAt > -1; }
17304 }
17305 return this.parseForIn(node, init$1)
17306 }
17307 if (awaitAt > -1) { this.unexpected(awaitAt); }
17308 return this.parseFor(node, init$1)
17309 }
17310 var startsWithLet = this.isContextual("let"), isForOf = false;
17311 var refDestructuringErrors = new DestructuringErrors;
17312 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
17313 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
17314 if (this.options.ecmaVersion >= 9) {
17315 if (this.type === types$1._in) {
17316 if (awaitAt > -1) { this.unexpected(awaitAt); }
17317 } else { node.await = awaitAt > -1; }
17318 }
17319 if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
17320 this.toAssignable(init, false, refDestructuringErrors);
17321 this.checkLValPattern(init);
17322 return this.parseForIn(node, init)
17323 } else {
17324 this.checkExpressionErrors(refDestructuringErrors, true);
17325 }
17326 if (awaitAt > -1) { this.unexpected(awaitAt); }
17327 return this.parseFor(node, init)
17328};
17329
17330pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
17331 this.next();
17332 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
17333};
17334
17335pp$8.parseIfStatement = function(node) {
17336 this.next();
17337 node.test = this.parseParenExpression();
17338 // allow function declarations in branches, but only in non-strict mode
17339 node.consequent = this.parseStatement("if");
17340 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
17341 return this.finishNode(node, "IfStatement")
17342};
17343
17344pp$8.parseReturnStatement = function(node) {
17345 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
17346 { this.raise(this.start, "'return' outside of function"); }
17347 this.next();
17348
17349 // In `return` (and `break`/`continue`), the keywords with
17350 // optional arguments, we eagerly look for a semicolon or the
17351 // possibility to insert one.
17352
17353 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
17354 else { node.argument = this.parseExpression(); this.semicolon(); }
17355 return this.finishNode(node, "ReturnStatement")
17356};
17357
17358pp$8.parseSwitchStatement = function(node) {
17359 this.next();
17360 node.discriminant = this.parseParenExpression();
17361 node.cases = [];
17362 this.expect(types$1.braceL);
17363 this.labels.push(switchLabel);
17364 this.enterScope(0);
17365
17366 // Statements under must be grouped (by label) in SwitchCase
17367 // nodes. `cur` is used to keep the node that we are currently
17368 // adding statements to.
17369
17370 var cur;
17371 for (var sawDefault = false; this.type !== types$1.braceR;) {
17372 if (this.type === types$1._case || this.type === types$1._default) {
17373 var isCase = this.type === types$1._case;
17374 if (cur) { this.finishNode(cur, "SwitchCase"); }
17375 node.cases.push(cur = this.startNode());
17376 cur.consequent = [];
17377 this.next();
17378 if (isCase) {
17379 cur.test = this.parseExpression();
17380 } else {
17381 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
17382 sawDefault = true;
17383 cur.test = null;
17384 }
17385 this.expect(types$1.colon);
17386 } else {
17387 if (!cur) { this.unexpected(); }
17388 cur.consequent.push(this.parseStatement(null));
17389 }
17390 }
17391 this.exitScope();
17392 if (cur) { this.finishNode(cur, "SwitchCase"); }
17393 this.next(); // Closing brace
17394 this.labels.pop();
17395 return this.finishNode(node, "SwitchStatement")
17396};
17397
17398pp$8.parseThrowStatement = function(node) {
17399 this.next();
17400 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
17401 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
17402 node.argument = this.parseExpression();
17403 this.semicolon();
17404 return this.finishNode(node, "ThrowStatement")
17405};
17406
17407// Reused empty array added for node fields that are always empty.
17408
17409var empty$1 = [];
17410
17411pp$8.parseTryStatement = function(node) {
17412 this.next();
17413 node.block = this.parseBlock();
17414 node.handler = null;
17415 if (this.type === types$1._catch) {
17416 var clause = this.startNode();
17417 this.next();
17418 if (this.eat(types$1.parenL)) {
17419 clause.param = this.parseBindingAtom();
17420 var simple = clause.param.type === "Identifier";
17421 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
17422 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
17423 this.expect(types$1.parenR);
17424 } else {
17425 if (this.options.ecmaVersion < 10) { this.unexpected(); }
17426 clause.param = null;
17427 this.enterScope(0);
17428 }
17429 clause.body = this.parseBlock(false);
17430 this.exitScope();
17431 node.handler = this.finishNode(clause, "CatchClause");
17432 }
17433 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
17434 if (!node.handler && !node.finalizer)
17435 { this.raise(node.start, "Missing catch or finally clause"); }
17436 return this.finishNode(node, "TryStatement")
17437};
17438
17439pp$8.parseVarStatement = function(node, kind) {
17440 this.next();
17441 this.parseVar(node, false, kind);
17442 this.semicolon();
17443 return this.finishNode(node, "VariableDeclaration")
17444};
17445
17446pp$8.parseWhileStatement = function(node) {
17447 this.next();
17448 node.test = this.parseParenExpression();
17449 this.labels.push(loopLabel);
17450 node.body = this.parseStatement("while");
17451 this.labels.pop();
17452 return this.finishNode(node, "WhileStatement")
17453};
17454
17455pp$8.parseWithStatement = function(node) {
17456 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
17457 this.next();
17458 node.object = this.parseParenExpression();
17459 node.body = this.parseStatement("with");
17460 return this.finishNode(node, "WithStatement")
17461};
17462
17463pp$8.parseEmptyStatement = function(node) {
17464 this.next();
17465 return this.finishNode(node, "EmptyStatement")
17466};
17467
17468pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
17469 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
17470 {
17471 var label = list[i$1];
17472
17473 if (label.name === maybeName)
17474 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
17475 } }
17476 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
17477 for (var i = this.labels.length - 1; i >= 0; i--) {
17478 var label$1 = this.labels[i];
17479 if (label$1.statementStart === node.start) {
17480 // Update information about previous labels on this node
17481 label$1.statementStart = this.start;
17482 label$1.kind = kind;
17483 } else { break }
17484 }
17485 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
17486 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
17487 this.labels.pop();
17488 node.label = expr;
17489 return this.finishNode(node, "LabeledStatement")
17490};
17491
17492pp$8.parseExpressionStatement = function(node, expr) {
17493 node.expression = expr;
17494 this.semicolon();
17495 return this.finishNode(node, "ExpressionStatement")
17496};
17497
17498// Parse a semicolon-enclosed block of statements, handling `"use
17499// strict"` declarations when `allowStrict` is true (used for
17500// function bodies).
17501
17502pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
17503 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
17504 if ( node === void 0 ) node = this.startNode();
17505
17506 node.body = [];
17507 this.expect(types$1.braceL);
17508 if (createNewLexicalScope) { this.enterScope(0); }
17509 while (this.type !== types$1.braceR) {
17510 var stmt = this.parseStatement(null);
17511 node.body.push(stmt);
17512 }
17513 if (exitStrict) { this.strict = false; }
17514 this.next();
17515 if (createNewLexicalScope) { this.exitScope(); }
17516 return this.finishNode(node, "BlockStatement")
17517};
17518
17519// Parse a regular `for` loop. The disambiguation code in
17520// `parseStatement` will already have parsed the init statement or
17521// expression.
17522
17523pp$8.parseFor = function(node, init) {
17524 node.init = init;
17525 this.expect(types$1.semi);
17526 node.test = this.type === types$1.semi ? null : this.parseExpression();
17527 this.expect(types$1.semi);
17528 node.update = this.type === types$1.parenR ? null : this.parseExpression();
17529 this.expect(types$1.parenR);
17530 node.body = this.parseStatement("for");
17531 this.exitScope();
17532 this.labels.pop();
17533 return this.finishNode(node, "ForStatement")
17534};
17535
17536// Parse a `for`/`in` and `for`/`of` loop, which are almost
17537// same from parser's perspective.
17538
17539pp$8.parseForIn = function(node, init) {
17540 var isForIn = this.type === types$1._in;
17541 this.next();
17542
17543 if (
17544 init.type === "VariableDeclaration" &&
17545 init.declarations[0].init != null &&
17546 (
17547 !isForIn ||
17548 this.options.ecmaVersion < 8 ||
17549 this.strict ||
17550 init.kind !== "var" ||
17551 init.declarations[0].id.type !== "Identifier"
17552 )
17553 ) {
17554 this.raise(
17555 init.start,
17556 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
17557 );
17558 }
17559 node.left = init;
17560 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
17561 this.expect(types$1.parenR);
17562 node.body = this.parseStatement("for");
17563 this.exitScope();
17564 this.labels.pop();
17565 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
17566};
17567
17568// Parse a list of variable declarations.
17569
17570pp$8.parseVar = function(node, isFor, kind) {
17571 node.declarations = [];
17572 node.kind = kind;
17573 for (;;) {
17574 var decl = this.startNode();
17575 this.parseVarId(decl, kind);
17576 if (this.eat(types$1.eq)) {
17577 decl.init = this.parseMaybeAssign(isFor);
17578 } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
17579 this.unexpected();
17580 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
17581 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
17582 } else {
17583 decl.init = null;
17584 }
17585 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
17586 if (!this.eat(types$1.comma)) { break }
17587 }
17588 return node
17589};
17590
17591pp$8.parseVarId = function(decl, kind) {
17592 decl.id = this.parseBindingAtom();
17593 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
17594};
17595
17596var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
17597
17598// Parse a function declaration or literal (depending on the
17599// `statement & FUNC_STATEMENT`).
17600
17601// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
17602pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
17603 this.initFunction(node);
17604 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
17605 if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
17606 { this.unexpected(); }
17607 node.generator = this.eat(types$1.star);
17608 }
17609 if (this.options.ecmaVersion >= 8)
17610 { node.async = !!isAsync; }
17611
17612 if (statement & FUNC_STATEMENT) {
17613 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
17614 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
17615 // If it is a regular function declaration in sloppy mode, then it is
17616 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
17617 // mode depends on properties of the current scope (see
17618 // treatFunctionsAsVar).
17619 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
17620 }
17621
17622 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
17623 this.yieldPos = 0;
17624 this.awaitPos = 0;
17625 this.awaitIdentPos = 0;
17626 this.enterScope(functionFlags(node.async, node.generator));
17627
17628 if (!(statement & FUNC_STATEMENT))
17629 { node.id = this.type === types$1.name ? this.parseIdent() : null; }
17630
17631 this.parseFunctionParams(node);
17632 this.parseFunctionBody(node, allowExpressionBody, false, forInit);
17633
17634 this.yieldPos = oldYieldPos;
17635 this.awaitPos = oldAwaitPos;
17636 this.awaitIdentPos = oldAwaitIdentPos;
17637 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
17638};
17639
17640pp$8.parseFunctionParams = function(node) {
17641 this.expect(types$1.parenL);
17642 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
17643 this.checkYieldAwaitInDefaultParams();
17644};
17645
17646// Parse a class declaration or literal (depending on the
17647// `isStatement` parameter).
17648
17649pp$8.parseClass = function(node, isStatement) {
17650 this.next();
17651
17652 // ecma-262 14.6 Class Definitions
17653 // A class definition is always strict mode code.
17654 var oldStrict = this.strict;
17655 this.strict = true;
17656
17657 this.parseClassId(node, isStatement);
17658 this.parseClassSuper(node);
17659 var privateNameMap = this.enterClassBody();
17660 var classBody = this.startNode();
17661 var hadConstructor = false;
17662 classBody.body = [];
17663 this.expect(types$1.braceL);
17664 while (this.type !== types$1.braceR) {
17665 var element = this.parseClassElement(node.superClass !== null);
17666 if (element) {
17667 classBody.body.push(element);
17668 if (element.type === "MethodDefinition" && element.kind === "constructor") {
17669 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
17670 hadConstructor = true;
17671 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
17672 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
17673 }
17674 }
17675 }
17676 this.strict = oldStrict;
17677 this.next();
17678 node.body = this.finishNode(classBody, "ClassBody");
17679 this.exitClassBody();
17680 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
17681};
17682
17683pp$8.parseClassElement = function(constructorAllowsSuper) {
17684 if (this.eat(types$1.semi)) { return null }
17685
17686 var ecmaVersion = this.options.ecmaVersion;
17687 var node = this.startNode();
17688 var keyName = "";
17689 var isGenerator = false;
17690 var isAsync = false;
17691 var kind = "method";
17692 var isStatic = false;
17693
17694 if (this.eatContextual("static")) {
17695 // Parse static init block
17696 if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
17697 this.parseClassStaticBlock(node);
17698 return node
17699 }
17700 if (this.isClassElementNameStart() || this.type === types$1.star) {
17701 isStatic = true;
17702 } else {
17703 keyName = "static";
17704 }
17705 }
17706 node.static = isStatic;
17707 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
17708 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
17709 isAsync = true;
17710 } else {
17711 keyName = "async";
17712 }
17713 }
17714 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
17715 isGenerator = true;
17716 }
17717 if (!keyName && !isAsync && !isGenerator) {
17718 var lastValue = this.value;
17719 if (this.eatContextual("get") || this.eatContextual("set")) {
17720 if (this.isClassElementNameStart()) {
17721 kind = lastValue;
17722 } else {
17723 keyName = lastValue;
17724 }
17725 }
17726 }
17727
17728 // Parse element name
17729 if (keyName) {
17730 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
17731 // The last token is any of those. Make it the element name.
17732 node.computed = false;
17733 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
17734 node.key.name = keyName;
17735 this.finishNode(node.key, "Identifier");
17736 } else {
17737 this.parseClassElementName(node);
17738 }
17739
17740 // Parse element value
17741 if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
17742 var isConstructor = !node.static && checkKeyName(node, "constructor");
17743 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
17744 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
17745 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
17746 node.kind = isConstructor ? "constructor" : kind;
17747 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
17748 } else {
17749 this.parseClassField(node);
17750 }
17751
17752 return node
17753};
17754
17755pp$8.isClassElementNameStart = function() {
17756 return (
17757 this.type === types$1.name ||
17758 this.type === types$1.privateId ||
17759 this.type === types$1.num ||
17760 this.type === types$1.string ||
17761 this.type === types$1.bracketL ||
17762 this.type.keyword
17763 )
17764};
17765
17766pp$8.parseClassElementName = function(element) {
17767 if (this.type === types$1.privateId) {
17768 if (this.value === "constructor") {
17769 this.raise(this.start, "Classes can't have an element named '#constructor'");
17770 }
17771 element.computed = false;
17772 element.key = this.parsePrivateIdent();
17773 } else {
17774 this.parsePropertyName(element);
17775 }
17776};
17777
17778pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
17779 // Check key and flags
17780 var key = method.key;
17781 if (method.kind === "constructor") {
17782 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
17783 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
17784 } else if (method.static && checkKeyName(method, "prototype")) {
17785 this.raise(key.start, "Classes may not have a static property named prototype");
17786 }
17787
17788 // Parse value
17789 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
17790
17791 // Check value
17792 if (method.kind === "get" && value.params.length !== 0)
17793 { this.raiseRecoverable(value.start, "getter should have no params"); }
17794 if (method.kind === "set" && value.params.length !== 1)
17795 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
17796 if (method.kind === "set" && value.params[0].type === "RestElement")
17797 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
17798
17799 return this.finishNode(method, "MethodDefinition")
17800};
17801
17802pp$8.parseClassField = function(field) {
17803 if (checkKeyName(field, "constructor")) {
17804 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
17805 } else if (field.static && checkKeyName(field, "prototype")) {
17806 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
17807 }
17808
17809 if (this.eat(types$1.eq)) {
17810 // To raise SyntaxError if 'arguments' exists in the initializer.
17811 var scope = this.currentThisScope();
17812 var inClassFieldInit = scope.inClassFieldInit;
17813 scope.inClassFieldInit = true;
17814 field.value = this.parseMaybeAssign();
17815 scope.inClassFieldInit = inClassFieldInit;
17816 } else {
17817 field.value = null;
17818 }
17819 this.semicolon();
17820
17821 return this.finishNode(field, "PropertyDefinition")
17822};
17823
17824pp$8.parseClassStaticBlock = function(node) {
17825 node.body = [];
17826
17827 var oldLabels = this.labels;
17828 this.labels = [];
17829 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
17830 while (this.type !== types$1.braceR) {
17831 var stmt = this.parseStatement(null);
17832 node.body.push(stmt);
17833 }
17834 this.next();
17835 this.exitScope();
17836 this.labels = oldLabels;
17837
17838 return this.finishNode(node, "StaticBlock")
17839};
17840
17841pp$8.parseClassId = function(node, isStatement) {
17842 if (this.type === types$1.name) {
17843 node.id = this.parseIdent();
17844 if (isStatement)
17845 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
17846 } else {
17847 if (isStatement === true)
17848 { this.unexpected(); }
17849 node.id = null;
17850 }
17851};
17852
17853pp$8.parseClassSuper = function(node) {
17854 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
17855};
17856
17857pp$8.enterClassBody = function() {
17858 var element = {declared: Object.create(null), used: []};
17859 this.privateNameStack.push(element);
17860 return element.declared
17861};
17862
17863pp$8.exitClassBody = function() {
17864 var ref = this.privateNameStack.pop();
17865 var declared = ref.declared;
17866 var used = ref.used;
17867 var len = this.privateNameStack.length;
17868 var parent = len === 0 ? null : this.privateNameStack[len - 1];
17869 for (var i = 0; i < used.length; ++i) {
17870 var id = used[i];
17871 if (!hasOwn(declared, id.name)) {
17872 if (parent) {
17873 parent.used.push(id);
17874 } else {
17875 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
17876 }
17877 }
17878 }
17879};
17880
17881function isPrivateNameConflicted(privateNameMap, element) {
17882 var name = element.key.name;
17883 var curr = privateNameMap[name];
17884
17885 var next = "true";
17886 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
17887 next = (element.static ? "s" : "i") + element.kind;
17888 }
17889
17890 // `class { get #a(){}; static set #a(_){} }` is also conflict.
17891 if (
17892 curr === "iget" && next === "iset" ||
17893 curr === "iset" && next === "iget" ||
17894 curr === "sget" && next === "sset" ||
17895 curr === "sset" && next === "sget"
17896 ) {
17897 privateNameMap[name] = "true";
17898 return false
17899 } else if (!curr) {
17900 privateNameMap[name] = next;
17901 return false
17902 } else {
17903 return true
17904 }
17905}
17906
17907function checkKeyName(node, name) {
17908 var computed = node.computed;
17909 var key = node.key;
17910 return !computed && (
17911 key.type === "Identifier" && key.name === name ||
17912 key.type === "Literal" && key.value === name
17913 )
17914}
17915
17916// Parses module export declaration.
17917
17918pp$8.parseExport = function(node, exports) {
17919 this.next();
17920 // export * from '...'
17921 if (this.eat(types$1.star)) {
17922 if (this.options.ecmaVersion >= 11) {
17923 if (this.eatContextual("as")) {
17924 node.exported = this.parseModuleExportName();
17925 this.checkExport(exports, node.exported, this.lastTokStart);
17926 } else {
17927 node.exported = null;
17928 }
17929 }
17930 this.expectContextual("from");
17931 if (this.type !== types$1.string) { this.unexpected(); }
17932 node.source = this.parseExprAtom();
17933 this.semicolon();
17934 return this.finishNode(node, "ExportAllDeclaration")
17935 }
17936 if (this.eat(types$1._default)) { // export default ...
17937 this.checkExport(exports, "default", this.lastTokStart);
17938 var isAsync;
17939 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
17940 var fNode = this.startNode();
17941 this.next();
17942 if (isAsync) { this.next(); }
17943 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
17944 } else if (this.type === types$1._class) {
17945 var cNode = this.startNode();
17946 node.declaration = this.parseClass(cNode, "nullableID");
17947 } else {
17948 node.declaration = this.parseMaybeAssign();
17949 this.semicolon();
17950 }
17951 return this.finishNode(node, "ExportDefaultDeclaration")
17952 }
17953 // export var|const|let|function|class ...
17954 if (this.shouldParseExportStatement()) {
17955 node.declaration = this.parseStatement(null);
17956 if (node.declaration.type === "VariableDeclaration")
17957 { this.checkVariableExport(exports, node.declaration.declarations); }
17958 else
17959 { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
17960 node.specifiers = [];
17961 node.source = null;
17962 } else { // export { x, y as z } [from '...']
17963 node.declaration = null;
17964 node.specifiers = this.parseExportSpecifiers(exports);
17965 if (this.eatContextual("from")) {
17966 if (this.type !== types$1.string) { this.unexpected(); }
17967 node.source = this.parseExprAtom();
17968 } else {
17969 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
17970 // check for keywords used as local names
17971 var spec = list[i];
17972
17973 this.checkUnreserved(spec.local);
17974 // check if export is defined
17975 this.checkLocalExport(spec.local);
17976
17977 if (spec.local.type === "Literal") {
17978 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
17979 }
17980 }
17981
17982 node.source = null;
17983 }
17984 this.semicolon();
17985 }
17986 return this.finishNode(node, "ExportNamedDeclaration")
17987};
17988
17989pp$8.checkExport = function(exports, name, pos) {
17990 if (!exports) { return }
17991 if (typeof name !== "string")
17992 { name = name.type === "Identifier" ? name.name : name.value; }
17993 if (hasOwn(exports, name))
17994 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
17995 exports[name] = true;
17996};
17997
17998pp$8.checkPatternExport = function(exports, pat) {
17999 var type = pat.type;
18000 if (type === "Identifier")
18001 { this.checkExport(exports, pat, pat.start); }
18002 else if (type === "ObjectPattern")
18003 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
18004 {
18005 var prop = list[i];
18006
18007 this.checkPatternExport(exports, prop);
18008 } }
18009 else if (type === "ArrayPattern")
18010 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
18011 var elt = list$1[i$1];
18012
18013 if (elt) { this.checkPatternExport(exports, elt); }
18014 } }
18015 else if (type === "Property")
18016 { this.checkPatternExport(exports, pat.value); }
18017 else if (type === "AssignmentPattern")
18018 { this.checkPatternExport(exports, pat.left); }
18019 else if (type === "RestElement")
18020 { this.checkPatternExport(exports, pat.argument); }
18021 else if (type === "ParenthesizedExpression")
18022 { this.checkPatternExport(exports, pat.expression); }
18023};
18024
18025pp$8.checkVariableExport = function(exports, decls) {
18026 if (!exports) { return }
18027 for (var i = 0, list = decls; i < list.length; i += 1)
18028 {
18029 var decl = list[i];
18030
18031 this.checkPatternExport(exports, decl.id);
18032 }
18033};
18034
18035pp$8.shouldParseExportStatement = function() {
18036 return this.type.keyword === "var" ||
18037 this.type.keyword === "const" ||
18038 this.type.keyword === "class" ||
18039 this.type.keyword === "function" ||
18040 this.isLet() ||
18041 this.isAsyncFunction()
18042};
18043
18044// Parses a comma-separated list of module exports.
18045
18046pp$8.parseExportSpecifiers = function(exports) {
18047 var nodes = [], first = true;
18048 // export { x, y as z } [from '...']
18049 this.expect(types$1.braceL);
18050 while (!this.eat(types$1.braceR)) {
18051 if (!first) {
18052 this.expect(types$1.comma);
18053 if (this.afterTrailingComma(types$1.braceR)) { break }
18054 } else { first = false; }
18055
18056 var node = this.startNode();
18057 node.local = this.parseModuleExportName();
18058 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
18059 this.checkExport(
18060 exports,
18061 node.exported,
18062 node.exported.start
18063 );
18064 nodes.push(this.finishNode(node, "ExportSpecifier"));
18065 }
18066 return nodes
18067};
18068
18069// Parses import declaration.
18070
18071pp$8.parseImport = function(node) {
18072 this.next();
18073 // import '...'
18074 if (this.type === types$1.string) {
18075 node.specifiers = empty$1;
18076 node.source = this.parseExprAtom();
18077 } else {
18078 node.specifiers = this.parseImportSpecifiers();
18079 this.expectContextual("from");
18080 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
18081 }
18082 this.semicolon();
18083 return this.finishNode(node, "ImportDeclaration")
18084};
18085
18086// Parses a comma-separated list of module imports.
18087
18088pp$8.parseImportSpecifiers = function() {
18089 var nodes = [], first = true;
18090 if (this.type === types$1.name) {
18091 // import defaultObj, { x, y as z } from '...'
18092 var node = this.startNode();
18093 node.local = this.parseIdent();
18094 this.checkLValSimple(node.local, BIND_LEXICAL);
18095 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
18096 if (!this.eat(types$1.comma)) { return nodes }
18097 }
18098 if (this.type === types$1.star) {
18099 var node$1 = this.startNode();
18100 this.next();
18101 this.expectContextual("as");
18102 node$1.local = this.parseIdent();
18103 this.checkLValSimple(node$1.local, BIND_LEXICAL);
18104 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
18105 return nodes
18106 }
18107 this.expect(types$1.braceL);
18108 while (!this.eat(types$1.braceR)) {
18109 if (!first) {
18110 this.expect(types$1.comma);
18111 if (this.afterTrailingComma(types$1.braceR)) { break }
18112 } else { first = false; }
18113
18114 var node$2 = this.startNode();
18115 node$2.imported = this.parseModuleExportName();
18116 if (this.eatContextual("as")) {
18117 node$2.local = this.parseIdent();
18118 } else {
18119 this.checkUnreserved(node$2.imported);
18120 node$2.local = node$2.imported;
18121 }
18122 this.checkLValSimple(node$2.local, BIND_LEXICAL);
18123 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
18124 }
18125 return nodes
18126};
18127
18128pp$8.parseModuleExportName = function() {
18129 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
18130 var stringLiteral = this.parseLiteral(this.value);
18131 if (loneSurrogate.test(stringLiteral.value)) {
18132 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
18133 }
18134 return stringLiteral
18135 }
18136 return this.parseIdent(true)
18137};
18138
18139// Set `ExpressionStatement#directive` property for directive prologues.
18140pp$8.adaptDirectivePrologue = function(statements) {
18141 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
18142 statements[i].directive = statements[i].expression.raw.slice(1, -1);
18143 }
18144};
18145pp$8.isDirectiveCandidate = function(statement) {
18146 return (
18147 statement.type === "ExpressionStatement" &&
18148 statement.expression.type === "Literal" &&
18149 typeof statement.expression.value === "string" &&
18150 // Reject parenthesized strings.
18151 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
18152 )
18153};
18154
18155var pp$7 = Parser.prototype;
18156
18157// Convert existing expression atom to assignable pattern
18158// if possible.
18159
18160pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
18161 if (this.options.ecmaVersion >= 6 && node) {
18162 switch (node.type) {
18163 case "Identifier":
18164 if (this.inAsync && node.name === "await")
18165 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
18166 break
18167
18168 case "ObjectPattern":
18169 case "ArrayPattern":
18170 case "AssignmentPattern":
18171 case "RestElement":
18172 break
18173
18174 case "ObjectExpression":
18175 node.type = "ObjectPattern";
18176 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18177 for (var i = 0, list = node.properties; i < list.length; i += 1) {
18178 var prop = list[i];
18179
18180 this.toAssignable(prop, isBinding);
18181 // Early error:
18182 // AssignmentRestProperty[Yield, Await] :
18183 // `...` DestructuringAssignmentTarget[Yield, Await]
18184 //
18185 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
18186 if (
18187 prop.type === "RestElement" &&
18188 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
18189 ) {
18190 this.raise(prop.argument.start, "Unexpected token");
18191 }
18192 }
18193 break
18194
18195 case "Property":
18196 // AssignmentProperty has type === "Property"
18197 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
18198 this.toAssignable(node.value, isBinding);
18199 break
18200
18201 case "ArrayExpression":
18202 node.type = "ArrayPattern";
18203 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18204 this.toAssignableList(node.elements, isBinding);
18205 break
18206
18207 case "SpreadElement":
18208 node.type = "RestElement";
18209 this.toAssignable(node.argument, isBinding);
18210 if (node.argument.type === "AssignmentPattern")
18211 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
18212 break
18213
18214 case "AssignmentExpression":
18215 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
18216 node.type = "AssignmentPattern";
18217 delete node.operator;
18218 this.toAssignable(node.left, isBinding);
18219 break
18220
18221 case "ParenthesizedExpression":
18222 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
18223 break
18224
18225 case "ChainExpression":
18226 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
18227 break
18228
18229 case "MemberExpression":
18230 if (!isBinding) { break }
18231
18232 default:
18233 this.raise(node.start, "Assigning to rvalue");
18234 }
18235 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18236 return node
18237};
18238
18239// Convert list of expression atoms to binding list.
18240
18241pp$7.toAssignableList = function(exprList, isBinding) {
18242 var end = exprList.length;
18243 for (var i = 0; i < end; i++) {
18244 var elt = exprList[i];
18245 if (elt) { this.toAssignable(elt, isBinding); }
18246 }
18247 if (end) {
18248 var last = exprList[end - 1];
18249 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
18250 { this.unexpected(last.argument.start); }
18251 }
18252 return exprList
18253};
18254
18255// Parses spread element.
18256
18257pp$7.parseSpread = function(refDestructuringErrors) {
18258 var node = this.startNode();
18259 this.next();
18260 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
18261 return this.finishNode(node, "SpreadElement")
18262};
18263
18264pp$7.parseRestBinding = function() {
18265 var node = this.startNode();
18266 this.next();
18267
18268 // RestElement inside of a function parameter must be an identifier
18269 if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
18270 { this.unexpected(); }
18271
18272 node.argument = this.parseBindingAtom();
18273
18274 return this.finishNode(node, "RestElement")
18275};
18276
18277// Parses lvalue (assignable) atom.
18278
18279pp$7.parseBindingAtom = function() {
18280 if (this.options.ecmaVersion >= 6) {
18281 switch (this.type) {
18282 case types$1.bracketL:
18283 var node = this.startNode();
18284 this.next();
18285 node.elements = this.parseBindingList(types$1.bracketR, true, true);
18286 return this.finishNode(node, "ArrayPattern")
18287
18288 case types$1.braceL:
18289 return this.parseObj(true)
18290 }
18291 }
18292 return this.parseIdent()
18293};
18294
18295pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
18296 var elts = [], first = true;
18297 while (!this.eat(close)) {
18298 if (first) { first = false; }
18299 else { this.expect(types$1.comma); }
18300 if (allowEmpty && this.type === types$1.comma) {
18301 elts.push(null);
18302 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
18303 break
18304 } else if (this.type === types$1.ellipsis) {
18305 var rest = this.parseRestBinding();
18306 this.parseBindingListItem(rest);
18307 elts.push(rest);
18308 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
18309 this.expect(close);
18310 break
18311 } else {
18312 var elem = this.parseMaybeDefault(this.start, this.startLoc);
18313 this.parseBindingListItem(elem);
18314 elts.push(elem);
18315 }
18316 }
18317 return elts
18318};
18319
18320pp$7.parseBindingListItem = function(param) {
18321 return param
18322};
18323
18324// Parses assignment pattern around given atom if possible.
18325
18326pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
18327 left = left || this.parseBindingAtom();
18328 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
18329 var node = this.startNodeAt(startPos, startLoc);
18330 node.left = left;
18331 node.right = this.parseMaybeAssign();
18332 return this.finishNode(node, "AssignmentPattern")
18333};
18334
18335// The following three functions all verify that a node is an lvalue —
18336// something that can be bound, or assigned to. In order to do so, they perform
18337// a variety of checks:
18338//
18339// - Check that none of the bound/assigned-to identifiers are reserved words.
18340// - Record name declarations for bindings in the appropriate scope.
18341// - Check duplicate argument names, if checkClashes is set.
18342//
18343// If a complex binding pattern is encountered (e.g., object and array
18344// destructuring), the entire pattern is recursively checked.
18345//
18346// There are three versions of checkLVal*() appropriate for different
18347// circumstances:
18348//
18349// - checkLValSimple() shall be used if the syntactic construct supports
18350// nothing other than identifiers and member expressions. Parenthesized
18351// expressions are also correctly handled. This is generally appropriate for
18352// constructs for which the spec says
18353//
18354// > It is a Syntax Error if AssignmentTargetType of [the production] is not
18355// > simple.
18356//
18357// It is also appropriate for checking if an identifier is valid and not
18358// defined elsewhere, like import declarations or function/class identifiers.
18359//
18360// Examples where this is used include:
18361// a += …;
18362// import a from '…';
18363// where a is the node to be checked.
18364//
18365// - checkLValPattern() shall be used if the syntactic construct supports
18366// anything checkLValSimple() supports, as well as object and array
18367// destructuring patterns. This is generally appropriate for constructs for
18368// which the spec says
18369//
18370// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
18371// > an ArrayLiteral and AssignmentTargetType of [the production] is not
18372// > simple.
18373//
18374// Examples where this is used include:
18375// (a = …);
18376// const a = …;
18377// try { … } catch (a) { … }
18378// where a is the node to be checked.
18379//
18380// - checkLValInnerPattern() shall be used if the syntactic construct supports
18381// anything checkLValPattern() supports, as well as default assignment
18382// patterns, rest elements, and other constructs that may appear within an
18383// object or array destructuring pattern.
18384//
18385// As a special case, function parameters also use checkLValInnerPattern(),
18386// as they also support defaults and rest constructs.
18387//
18388// These functions deliberately support both assignment and binding constructs,
18389// as the logic for both is exceedingly similar. If the node is the target of
18390// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
18391// should be set to the appropriate BIND_* constant, like BIND_VAR or
18392// BIND_LEXICAL.
18393//
18394// If the function is called with a non-BIND_NONE bindingType, then
18395// additionally a checkClashes object may be specified to allow checking for
18396// duplicate argument names. checkClashes is ignored if the provided construct
18397// is an assignment (i.e., bindingType is BIND_NONE).
18398
18399pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
18400 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18401
18402 var isBind = bindingType !== BIND_NONE;
18403
18404 switch (expr.type) {
18405 case "Identifier":
18406 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
18407 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
18408 if (isBind) {
18409 if (bindingType === BIND_LEXICAL && expr.name === "let")
18410 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
18411 if (checkClashes) {
18412 if (hasOwn(checkClashes, expr.name))
18413 { this.raiseRecoverable(expr.start, "Argument name clash"); }
18414 checkClashes[expr.name] = true;
18415 }
18416 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
18417 }
18418 break
18419
18420 case "ChainExpression":
18421 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
18422 break
18423
18424 case "MemberExpression":
18425 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
18426 break
18427
18428 case "ParenthesizedExpression":
18429 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
18430 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
18431
18432 default:
18433 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
18434 }
18435};
18436
18437pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
18438 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18439
18440 switch (expr.type) {
18441 case "ObjectPattern":
18442 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
18443 var prop = list[i];
18444
18445 this.checkLValInnerPattern(prop, bindingType, checkClashes);
18446 }
18447 break
18448
18449 case "ArrayPattern":
18450 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
18451 var elem = list$1[i$1];
18452
18453 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
18454 }
18455 break
18456
18457 default:
18458 this.checkLValSimple(expr, bindingType, checkClashes);
18459 }
18460};
18461
18462pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
18463 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18464
18465 switch (expr.type) {
18466 case "Property":
18467 // AssignmentProperty has type === "Property"
18468 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
18469 break
18470
18471 case "AssignmentPattern":
18472 this.checkLValPattern(expr.left, bindingType, checkClashes);
18473 break
18474
18475 case "RestElement":
18476 this.checkLValPattern(expr.argument, bindingType, checkClashes);
18477 break
18478
18479 default:
18480 this.checkLValPattern(expr, bindingType, checkClashes);
18481 }
18482};
18483
18484// The algorithm used to determine whether a regexp can appear at a
18485
18486var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
18487 this.token = token;
18488 this.isExpr = !!isExpr;
18489 this.preserveSpace = !!preserveSpace;
18490 this.override = override;
18491 this.generator = !!generator;
18492};
18493
18494var types = {
18495 b_stat: new TokContext("{", false),
18496 b_expr: new TokContext("{", true),
18497 b_tmpl: new TokContext("${", false),
18498 p_stat: new TokContext("(", false),
18499 p_expr: new TokContext("(", true),
18500 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
18501 f_stat: new TokContext("function", false),
18502 f_expr: new TokContext("function", true),
18503 f_expr_gen: new TokContext("function", true, false, null, true),
18504 f_gen: new TokContext("function", false, false, null, true)
18505};
18506
18507var pp$6 = Parser.prototype;
18508
18509pp$6.initialContext = function() {
18510 return [types.b_stat]
18511};
18512
18513pp$6.curContext = function() {
18514 return this.context[this.context.length - 1]
18515};
18516
18517pp$6.braceIsBlock = function(prevType) {
18518 var parent = this.curContext();
18519 if (parent === types.f_expr || parent === types.f_stat)
18520 { return true }
18521 if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
18522 { return !parent.isExpr }
18523
18524 // The check for `tt.name && exprAllowed` detects whether we are
18525 // after a `yield` or `of` construct. See the `updateContext` for
18526 // `tt.name`.
18527 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
18528 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
18529 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
18530 { return true }
18531 if (prevType === types$1.braceL)
18532 { return parent === types.b_stat }
18533 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
18534 { return false }
18535 return !this.exprAllowed
18536};
18537
18538pp$6.inGeneratorContext = function() {
18539 for (var i = this.context.length - 1; i >= 1; i--) {
18540 var context = this.context[i];
18541 if (context.token === "function")
18542 { return context.generator }
18543 }
18544 return false
18545};
18546
18547pp$6.updateContext = function(prevType) {
18548 var update, type = this.type;
18549 if (type.keyword && prevType === types$1.dot)
18550 { this.exprAllowed = false; }
18551 else if (update = type.updateContext)
18552 { update.call(this, prevType); }
18553 else
18554 { this.exprAllowed = type.beforeExpr; }
18555};
18556
18557// Used to handle egde case when token context could not be inferred correctly in tokenize phase
18558pp$6.overrideContext = function(tokenCtx) {
18559 if (this.curContext() !== tokenCtx) {
18560 this.context[this.context.length - 1] = tokenCtx;
18561 }
18562};
18563
18564// Token-specific context update code
18565
18566types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
18567 if (this.context.length === 1) {
18568 this.exprAllowed = true;
18569 return
18570 }
18571 var out = this.context.pop();
18572 if (out === types.b_stat && this.curContext().token === "function") {
18573 out = this.context.pop();
18574 }
18575 this.exprAllowed = !out.isExpr;
18576};
18577
18578types$1.braceL.updateContext = function(prevType) {
18579 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
18580 this.exprAllowed = true;
18581};
18582
18583types$1.dollarBraceL.updateContext = function() {
18584 this.context.push(types.b_tmpl);
18585 this.exprAllowed = true;
18586};
18587
18588types$1.parenL.updateContext = function(prevType) {
18589 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
18590 this.context.push(statementParens ? types.p_stat : types.p_expr);
18591 this.exprAllowed = true;
18592};
18593
18594types$1.incDec.updateContext = function() {
18595 // tokExprAllowed stays unchanged
18596};
18597
18598types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
18599 if (prevType.beforeExpr && prevType !== types$1._else &&
18600 !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
18601 !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
18602 !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
18603 { this.context.push(types.f_expr); }
18604 else
18605 { this.context.push(types.f_stat); }
18606 this.exprAllowed = false;
18607};
18608
18609types$1.backQuote.updateContext = function() {
18610 if (this.curContext() === types.q_tmpl)
18611 { this.context.pop(); }
18612 else
18613 { this.context.push(types.q_tmpl); }
18614 this.exprAllowed = false;
18615};
18616
18617types$1.star.updateContext = function(prevType) {
18618 if (prevType === types$1._function) {
18619 var index = this.context.length - 1;
18620 if (this.context[index] === types.f_expr)
18621 { this.context[index] = types.f_expr_gen; }
18622 else
18623 { this.context[index] = types.f_gen; }
18624 }
18625 this.exprAllowed = true;
18626};
18627
18628types$1.name.updateContext = function(prevType) {
18629 var allowed = false;
18630 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
18631 if (this.value === "of" && !this.exprAllowed ||
18632 this.value === "yield" && this.inGeneratorContext())
18633 { allowed = true; }
18634 }
18635 this.exprAllowed = allowed;
18636};
18637
18638// A recursive descent parser operates by defining functions for all
18639
18640var pp$5 = Parser.prototype;
18641
18642// Check if property name clashes with already added.
18643// Object/class getters and setters are not allowed to clash —
18644// either with each other or with an init property — and in
18645// strict mode, init properties are also not allowed to be repeated.
18646
18647pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
18648 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
18649 { return }
18650 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
18651 { return }
18652 var key = prop.key;
18653 var name;
18654 switch (key.type) {
18655 case "Identifier": name = key.name; break
18656 case "Literal": name = String(key.value); break
18657 default: return
18658 }
18659 var kind = prop.kind;
18660 if (this.options.ecmaVersion >= 6) {
18661 if (name === "__proto__" && kind === "init") {
18662 if (propHash.proto) {
18663 if (refDestructuringErrors) {
18664 if (refDestructuringErrors.doubleProto < 0) {
18665 refDestructuringErrors.doubleProto = key.start;
18666 }
18667 } else {
18668 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
18669 }
18670 }
18671 propHash.proto = true;
18672 }
18673 return
18674 }
18675 name = "$" + name;
18676 var other = propHash[name];
18677 if (other) {
18678 var redefinition;
18679 if (kind === "init") {
18680 redefinition = this.strict && other.init || other.get || other.set;
18681 } else {
18682 redefinition = other.init || other[kind];
18683 }
18684 if (redefinition)
18685 { this.raiseRecoverable(key.start, "Redefinition of property"); }
18686 } else {
18687 other = propHash[name] = {
18688 init: false,
18689 get: false,
18690 set: false
18691 };
18692 }
18693 other[kind] = true;
18694};
18695
18696// ### Expression parsing
18697
18698// These nest, from the most general expression type at the top to
18699// 'atomic', nondivisible expression types at the bottom. Most of
18700// the functions will simply let the function(s) below them parse,
18701// and, *if* the syntactic construct they handle is present, wrap
18702// the AST node that the inner parser gave them in another node.
18703
18704// Parse a full expression. The optional arguments are used to
18705// forbid the `in` operator (in for loops initalization expressions)
18706// and provide reference for storing '=' operator inside shorthand
18707// property assignment in contexts where both object expression
18708// and object pattern might appear (so it's possible to raise
18709// delayed syntax error at correct position).
18710
18711pp$5.parseExpression = function(forInit, refDestructuringErrors) {
18712 var startPos = this.start, startLoc = this.startLoc;
18713 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
18714 if (this.type === types$1.comma) {
18715 var node = this.startNodeAt(startPos, startLoc);
18716 node.expressions = [expr];
18717 while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
18718 return this.finishNode(node, "SequenceExpression")
18719 }
18720 return expr
18721};
18722
18723// Parse an assignment expression. This includes applications of
18724// operators like `+=`.
18725
18726pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
18727 if (this.isContextual("yield")) {
18728 if (this.inGenerator) { return this.parseYield(forInit) }
18729 // The tokenizer will assume an expression is allowed after
18730 // `yield`, but this isn't that kind of yield
18731 else { this.exprAllowed = false; }
18732 }
18733
18734 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
18735 if (refDestructuringErrors) {
18736 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
18737 oldTrailingComma = refDestructuringErrors.trailingComma;
18738 oldDoubleProto = refDestructuringErrors.doubleProto;
18739 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
18740 } else {
18741 refDestructuringErrors = new DestructuringErrors;
18742 ownDestructuringErrors = true;
18743 }
18744
18745 var startPos = this.start, startLoc = this.startLoc;
18746 if (this.type === types$1.parenL || this.type === types$1.name) {
18747 this.potentialArrowAt = this.start;
18748 this.potentialArrowInForAwait = forInit === "await";
18749 }
18750 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
18751 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
18752 if (this.type.isAssign) {
18753 var node = this.startNodeAt(startPos, startLoc);
18754 node.operator = this.value;
18755 if (this.type === types$1.eq)
18756 { left = this.toAssignable(left, false, refDestructuringErrors); }
18757 if (!ownDestructuringErrors) {
18758 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
18759 }
18760 if (refDestructuringErrors.shorthandAssign >= left.start)
18761 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
18762 if (this.type === types$1.eq)
18763 { this.checkLValPattern(left); }
18764 else
18765 { this.checkLValSimple(left); }
18766 node.left = left;
18767 this.next();
18768 node.right = this.parseMaybeAssign(forInit);
18769 if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
18770 return this.finishNode(node, "AssignmentExpression")
18771 } else {
18772 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
18773 }
18774 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
18775 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
18776 return left
18777};
18778
18779// Parse a ternary conditional (`?:`) operator.
18780
18781pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
18782 var startPos = this.start, startLoc = this.startLoc;
18783 var expr = this.parseExprOps(forInit, refDestructuringErrors);
18784 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18785 if (this.eat(types$1.question)) {
18786 var node = this.startNodeAt(startPos, startLoc);
18787 node.test = expr;
18788 node.consequent = this.parseMaybeAssign();
18789 this.expect(types$1.colon);
18790 node.alternate = this.parseMaybeAssign(forInit);
18791 return this.finishNode(node, "ConditionalExpression")
18792 }
18793 return expr
18794};
18795
18796// Start the precedence parser.
18797
18798pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
18799 var startPos = this.start, startLoc = this.startLoc;
18800 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
18801 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18802 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
18803};
18804
18805// Parse binary operators with the operator precedence parsing
18806// algorithm. `left` is the left-hand side of the operator.
18807// `minPrec` provides context that allows the function to stop and
18808// defer further parser to one of its callers when it encounters an
18809// operator that has a lower precedence than the set it is parsing.
18810
18811pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
18812 var prec = this.type.binop;
18813 if (prec != null && (!forInit || this.type !== types$1._in)) {
18814 if (prec > minPrec) {
18815 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
18816 var coalesce = this.type === types$1.coalesce;
18817 if (coalesce) {
18818 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
18819 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
18820 prec = types$1.logicalAND.binop;
18821 }
18822 var op = this.value;
18823 this.next();
18824 var startPos = this.start, startLoc = this.startLoc;
18825 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
18826 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
18827 if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
18828 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
18829 }
18830 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
18831 }
18832 }
18833 return left
18834};
18835
18836pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
18837 if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
18838 var node = this.startNodeAt(startPos, startLoc);
18839 node.left = left;
18840 node.operator = op;
18841 node.right = right;
18842 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
18843};
18844
18845// Parse unary operators, both prefix and postfix.
18846
18847pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
18848 var startPos = this.start, startLoc = this.startLoc, expr;
18849 if (this.isContextual("await") && this.canAwait) {
18850 expr = this.parseAwait(forInit);
18851 sawUnary = true;
18852 } else if (this.type.prefix) {
18853 var node = this.startNode(), update = this.type === types$1.incDec;
18854 node.operator = this.value;
18855 node.prefix = true;
18856 this.next();
18857 node.argument = this.parseMaybeUnary(null, true, update, forInit);
18858 this.checkExpressionErrors(refDestructuringErrors, true);
18859 if (update) { this.checkLValSimple(node.argument); }
18860 else if (this.strict && node.operator === "delete" &&
18861 node.argument.type === "Identifier")
18862 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
18863 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
18864 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
18865 else { sawUnary = true; }
18866 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
18867 } else if (!sawUnary && this.type === types$1.privateId) {
18868 if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
18869 expr = this.parsePrivateIdent();
18870 // only could be private fields in 'in', such as #x in obj
18871 if (this.type !== types$1._in) { this.unexpected(); }
18872 } else {
18873 expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
18874 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18875 while (this.type.postfix && !this.canInsertSemicolon()) {
18876 var node$1 = this.startNodeAt(startPos, startLoc);
18877 node$1.operator = this.value;
18878 node$1.prefix = false;
18879 node$1.argument = expr;
18880 this.checkLValSimple(expr);
18881 this.next();
18882 expr = this.finishNode(node$1, "UpdateExpression");
18883 }
18884 }
18885
18886 if (!incDec && this.eat(types$1.starstar)) {
18887 if (sawUnary)
18888 { this.unexpected(this.lastTokStart); }
18889 else
18890 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
18891 } else {
18892 return expr
18893 }
18894};
18895
18896function isPrivateFieldAccess(node) {
18897 return (
18898 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
18899 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
18900 )
18901}
18902
18903// Parse call, dot, and `[]`-subscript expressions.
18904
18905pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
18906 var startPos = this.start, startLoc = this.startLoc;
18907 var expr = this.parseExprAtom(refDestructuringErrors, forInit);
18908 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
18909 { return expr }
18910 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
18911 if (refDestructuringErrors && result.type === "MemberExpression") {
18912 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
18913 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
18914 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
18915 }
18916 return result
18917};
18918
18919pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
18920 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
18921 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
18922 this.potentialArrowAt === base.start;
18923 var optionalChained = false;
18924
18925 while (true) {
18926 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
18927
18928 if (element.optional) { optionalChained = true; }
18929 if (element === base || element.type === "ArrowFunctionExpression") {
18930 if (optionalChained) {
18931 var chainNode = this.startNodeAt(startPos, startLoc);
18932 chainNode.expression = element;
18933 element = this.finishNode(chainNode, "ChainExpression");
18934 }
18935 return element
18936 }
18937
18938 base = element;
18939 }
18940};
18941
18942pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
18943 var optionalSupported = this.options.ecmaVersion >= 11;
18944 var optional = optionalSupported && this.eat(types$1.questionDot);
18945 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
18946
18947 var computed = this.eat(types$1.bracketL);
18948 if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
18949 var node = this.startNodeAt(startPos, startLoc);
18950 node.object = base;
18951 if (computed) {
18952 node.property = this.parseExpression();
18953 this.expect(types$1.bracketR);
18954 } else if (this.type === types$1.privateId && base.type !== "Super") {
18955 node.property = this.parsePrivateIdent();
18956 } else {
18957 node.property = this.parseIdent(this.options.allowReserved !== "never");
18958 }
18959 node.computed = !!computed;
18960 if (optionalSupported) {
18961 node.optional = optional;
18962 }
18963 base = this.finishNode(node, "MemberExpression");
18964 } else if (!noCalls && this.eat(types$1.parenL)) {
18965 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
18966 this.yieldPos = 0;
18967 this.awaitPos = 0;
18968 this.awaitIdentPos = 0;
18969 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
18970 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
18971 this.checkPatternErrors(refDestructuringErrors, false);
18972 this.checkYieldAwaitInDefaultParams();
18973 if (this.awaitIdentPos > 0)
18974 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
18975 this.yieldPos = oldYieldPos;
18976 this.awaitPos = oldAwaitPos;
18977 this.awaitIdentPos = oldAwaitIdentPos;
18978 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
18979 }
18980 this.checkExpressionErrors(refDestructuringErrors, true);
18981 this.yieldPos = oldYieldPos || this.yieldPos;
18982 this.awaitPos = oldAwaitPos || this.awaitPos;
18983 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
18984 var node$1 = this.startNodeAt(startPos, startLoc);
18985 node$1.callee = base;
18986 node$1.arguments = exprList;
18987 if (optionalSupported) {
18988 node$1.optional = optional;
18989 }
18990 base = this.finishNode(node$1, "CallExpression");
18991 } else if (this.type === types$1.backQuote) {
18992 if (optional || optionalChained) {
18993 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
18994 }
18995 var node$2 = this.startNodeAt(startPos, startLoc);
18996 node$2.tag = base;
18997 node$2.quasi = this.parseTemplate({isTagged: true});
18998 base = this.finishNode(node$2, "TaggedTemplateExpression");
18999 }
19000 return base
19001};
19002
19003// Parse an atomic expression — either a single token that is an
19004// expression, an expression started by a keyword like `function` or
19005// `new`, or an expression wrapped in punctuation like `()`, `[]`,
19006// or `{}`.
19007
19008pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
19009 // If a division operator appears in an expression position, the
19010 // tokenizer got confused, and we force it to read a regexp instead.
19011 if (this.type === types$1.slash) { this.readRegexp(); }
19012
19013 var node, canBeArrow = this.potentialArrowAt === this.start;
19014 switch (this.type) {
19015 case types$1._super:
19016 if (!this.allowSuper)
19017 { this.raise(this.start, "'super' keyword outside a method"); }
19018 node = this.startNode();
19019 this.next();
19020 if (this.type === types$1.parenL && !this.allowDirectSuper)
19021 { this.raise(node.start, "super() call outside constructor of a subclass"); }
19022 // The `super` keyword can appear at below:
19023 // SuperProperty:
19024 // super [ Expression ]
19025 // super . IdentifierName
19026 // SuperCall:
19027 // super ( Arguments )
19028 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
19029 { this.unexpected(); }
19030 return this.finishNode(node, "Super")
19031
19032 case types$1._this:
19033 node = this.startNode();
19034 this.next();
19035 return this.finishNode(node, "ThisExpression")
19036
19037 case types$1.name:
19038 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
19039 var id = this.parseIdent(false);
19040 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
19041 this.overrideContext(types.f_expr);
19042 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
19043 }
19044 if (canBeArrow && !this.canInsertSemicolon()) {
19045 if (this.eat(types$1.arrow))
19046 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
19047 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
19048 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
19049 id = this.parseIdent(false);
19050 if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
19051 { this.unexpected(); }
19052 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
19053 }
19054 }
19055 return id
19056
19057 case types$1.regexp:
19058 var value = this.value;
19059 node = this.parseLiteral(value.value);
19060 node.regex = {pattern: value.pattern, flags: value.flags};
19061 return node
19062
19063 case types$1.num: case types$1.string:
19064 return this.parseLiteral(this.value)
19065
19066 case types$1._null: case types$1._true: case types$1._false:
19067 node = this.startNode();
19068 node.value = this.type === types$1._null ? null : this.type === types$1._true;
19069 node.raw = this.type.keyword;
19070 this.next();
19071 return this.finishNode(node, "Literal")
19072
19073 case types$1.parenL:
19074 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
19075 if (refDestructuringErrors) {
19076 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
19077 { refDestructuringErrors.parenthesizedAssign = start; }
19078 if (refDestructuringErrors.parenthesizedBind < 0)
19079 { refDestructuringErrors.parenthesizedBind = start; }
19080 }
19081 return expr
19082
19083 case types$1.bracketL:
19084 node = this.startNode();
19085 this.next();
19086 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
19087 return this.finishNode(node, "ArrayExpression")
19088
19089 case types$1.braceL:
19090 this.overrideContext(types.b_expr);
19091 return this.parseObj(false, refDestructuringErrors)
19092
19093 case types$1._function:
19094 node = this.startNode();
19095 this.next();
19096 return this.parseFunction(node, 0)
19097
19098 case types$1._class:
19099 return this.parseClass(this.startNode(), false)
19100
19101 case types$1._new:
19102 return this.parseNew()
19103
19104 case types$1.backQuote:
19105 return this.parseTemplate()
19106
19107 case types$1._import:
19108 if (this.options.ecmaVersion >= 11) {
19109 return this.parseExprImport()
19110 } else {
19111 return this.unexpected()
19112 }
19113
19114 default:
19115 this.unexpected();
19116 }
19117};
19118
19119pp$5.parseExprImport = function() {
19120 var node = this.startNode();
19121
19122 // Consume `import` as an identifier for `import.meta`.
19123 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
19124 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
19125 var meta = this.parseIdent(true);
19126
19127 switch (this.type) {
19128 case types$1.parenL:
19129 return this.parseDynamicImport(node)
19130 case types$1.dot:
19131 node.meta = meta;
19132 return this.parseImportMeta(node)
19133 default:
19134 this.unexpected();
19135 }
19136};
19137
19138pp$5.parseDynamicImport = function(node) {
19139 this.next(); // skip `(`
19140
19141 // Parse node.source.
19142 node.source = this.parseMaybeAssign();
19143
19144 // Verify ending.
19145 if (!this.eat(types$1.parenR)) {
19146 var errorPos = this.start;
19147 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
19148 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
19149 } else {
19150 this.unexpected(errorPos);
19151 }
19152 }
19153
19154 return this.finishNode(node, "ImportExpression")
19155};
19156
19157pp$5.parseImportMeta = function(node) {
19158 this.next(); // skip `.`
19159
19160 var containsEsc = this.containsEsc;
19161 node.property = this.parseIdent(true);
19162
19163 if (node.property.name !== "meta")
19164 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
19165 if (containsEsc)
19166 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
19167 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
19168 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
19169
19170 return this.finishNode(node, "MetaProperty")
19171};
19172
19173pp$5.parseLiteral = function(value) {
19174 var node = this.startNode();
19175 node.value = value;
19176 node.raw = this.input.slice(this.start, this.end);
19177 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
19178 this.next();
19179 return this.finishNode(node, "Literal")
19180};
19181
19182pp$5.parseParenExpression = function() {
19183 this.expect(types$1.parenL);
19184 var val = this.parseExpression();
19185 this.expect(types$1.parenR);
19186 return val
19187};
19188
19189pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
19190 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
19191 if (this.options.ecmaVersion >= 6) {
19192 this.next();
19193
19194 var innerStartPos = this.start, innerStartLoc = this.startLoc;
19195 var exprList = [], first = true, lastIsComma = false;
19196 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
19197 this.yieldPos = 0;
19198 this.awaitPos = 0;
19199 // Do not save awaitIdentPos to allow checking awaits nested in parameters
19200 while (this.type !== types$1.parenR) {
19201 first ? first = false : this.expect(types$1.comma);
19202 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
19203 lastIsComma = true;
19204 break
19205 } else if (this.type === types$1.ellipsis) {
19206 spreadStart = this.start;
19207 exprList.push(this.parseParenItem(this.parseRestBinding()));
19208 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
19209 break
19210 } else {
19211 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
19212 }
19213 }
19214 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
19215 this.expect(types$1.parenR);
19216
19217 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
19218 this.checkPatternErrors(refDestructuringErrors, false);
19219 this.checkYieldAwaitInDefaultParams();
19220 this.yieldPos = oldYieldPos;
19221 this.awaitPos = oldAwaitPos;
19222 return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
19223 }
19224
19225 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
19226 if (spreadStart) { this.unexpected(spreadStart); }
19227 this.checkExpressionErrors(refDestructuringErrors, true);
19228 this.yieldPos = oldYieldPos || this.yieldPos;
19229 this.awaitPos = oldAwaitPos || this.awaitPos;
19230
19231 if (exprList.length > 1) {
19232 val = this.startNodeAt(innerStartPos, innerStartLoc);
19233 val.expressions = exprList;
19234 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
19235 } else {
19236 val = exprList[0];
19237 }
19238 } else {
19239 val = this.parseParenExpression();
19240 }
19241
19242 if (this.options.preserveParens) {
19243 var par = this.startNodeAt(startPos, startLoc);
19244 par.expression = val;
19245 return this.finishNode(par, "ParenthesizedExpression")
19246 } else {
19247 return val
19248 }
19249};
19250
19251pp$5.parseParenItem = function(item) {
19252 return item
19253};
19254
19255pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
19256 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
19257};
19258
19259// New's precedence is slightly tricky. It must allow its argument to
19260// be a `[]` or dot subscript expression, but not a call — at least,
19261// not without wrapping it in parentheses. Thus, it uses the noCalls
19262// argument to parseSubscripts to prevent it from consuming the
19263// argument list.
19264
19265var empty = [];
19266
19267pp$5.parseNew = function() {
19268 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
19269 var node = this.startNode();
19270 var meta = this.parseIdent(true);
19271 if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
19272 node.meta = meta;
19273 var containsEsc = this.containsEsc;
19274 node.property = this.parseIdent(true);
19275 if (node.property.name !== "target")
19276 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
19277 if (containsEsc)
19278 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
19279 if (!this.allowNewDotTarget)
19280 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
19281 return this.finishNode(node, "MetaProperty")
19282 }
19283 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
19284 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
19285 if (isImport && node.callee.type === "ImportExpression") {
19286 this.raise(startPos, "Cannot use new with import()");
19287 }
19288 if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
19289 else { node.arguments = empty; }
19290 return this.finishNode(node, "NewExpression")
19291};
19292
19293// Parse template expression.
19294
19295pp$5.parseTemplateElement = function(ref) {
19296 var isTagged = ref.isTagged;
19297
19298 var elem = this.startNode();
19299 if (this.type === types$1.invalidTemplate) {
19300 if (!isTagged) {
19301 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
19302 }
19303 elem.value = {
19304 raw: this.value,
19305 cooked: null
19306 };
19307 } else {
19308 elem.value = {
19309 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
19310 cooked: this.value
19311 };
19312 }
19313 this.next();
19314 elem.tail = this.type === types$1.backQuote;
19315 return this.finishNode(elem, "TemplateElement")
19316};
19317
19318pp$5.parseTemplate = function(ref) {
19319 if ( ref === void 0 ) ref = {};
19320 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
19321
19322 var node = this.startNode();
19323 this.next();
19324 node.expressions = [];
19325 var curElt = this.parseTemplateElement({isTagged: isTagged});
19326 node.quasis = [curElt];
19327 while (!curElt.tail) {
19328 if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
19329 this.expect(types$1.dollarBraceL);
19330 node.expressions.push(this.parseExpression());
19331 this.expect(types$1.braceR);
19332 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
19333 }
19334 this.next();
19335 return this.finishNode(node, "TemplateLiteral")
19336};
19337
19338pp$5.isAsyncProp = function(prop) {
19339 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
19340 (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
19341 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
19342};
19343
19344// Parse an object literal or binding pattern.
19345
19346pp$5.parseObj = function(isPattern, refDestructuringErrors) {
19347 var node = this.startNode(), first = true, propHash = {};
19348 node.properties = [];
19349 this.next();
19350 while (!this.eat(types$1.braceR)) {
19351 if (!first) {
19352 this.expect(types$1.comma);
19353 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
19354 } else { first = false; }
19355
19356 var prop = this.parseProperty(isPattern, refDestructuringErrors);
19357 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
19358 node.properties.push(prop);
19359 }
19360 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
19361};
19362
19363pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
19364 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
19365 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
19366 if (isPattern) {
19367 prop.argument = this.parseIdent(false);
19368 if (this.type === types$1.comma) {
19369 this.raise(this.start, "Comma is not permitted after the rest element");
19370 }
19371 return this.finishNode(prop, "RestElement")
19372 }
19373 // To disallow parenthesized identifier via `this.toAssignable()`.
19374 if (this.type === types$1.parenL && refDestructuringErrors) {
19375 if (refDestructuringErrors.parenthesizedAssign < 0) {
19376 refDestructuringErrors.parenthesizedAssign = this.start;
19377 }
19378 if (refDestructuringErrors.parenthesizedBind < 0) {
19379 refDestructuringErrors.parenthesizedBind = this.start;
19380 }
19381 }
19382 // Parse argument.
19383 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
19384 // To disallow trailing comma via `this.toAssignable()`.
19385 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
19386 refDestructuringErrors.trailingComma = this.start;
19387 }
19388 // Finish
19389 return this.finishNode(prop, "SpreadElement")
19390 }
19391 if (this.options.ecmaVersion >= 6) {
19392 prop.method = false;
19393 prop.shorthand = false;
19394 if (isPattern || refDestructuringErrors) {
19395 startPos = this.start;
19396 startLoc = this.startLoc;
19397 }
19398 if (!isPattern)
19399 { isGenerator = this.eat(types$1.star); }
19400 }
19401 var containsEsc = this.containsEsc;
19402 this.parsePropertyName(prop);
19403 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
19404 isAsync = true;
19405 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
19406 this.parsePropertyName(prop, refDestructuringErrors);
19407 } else {
19408 isAsync = false;
19409 }
19410 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
19411 return this.finishNode(prop, "Property")
19412};
19413
19414pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
19415 if ((isGenerator || isAsync) && this.type === types$1.colon)
19416 { this.unexpected(); }
19417
19418 if (this.eat(types$1.colon)) {
19419 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
19420 prop.kind = "init";
19421 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
19422 if (isPattern) { this.unexpected(); }
19423 prop.kind = "init";
19424 prop.method = true;
19425 prop.value = this.parseMethod(isGenerator, isAsync);
19426 } else if (!isPattern && !containsEsc &&
19427 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
19428 (prop.key.name === "get" || prop.key.name === "set") &&
19429 (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
19430 if (isGenerator || isAsync) { this.unexpected(); }
19431 prop.kind = prop.key.name;
19432 this.parsePropertyName(prop);
19433 prop.value = this.parseMethod(false);
19434 var paramCount = prop.kind === "get" ? 0 : 1;
19435 if (prop.value.params.length !== paramCount) {
19436 var start = prop.value.start;
19437 if (prop.kind === "get")
19438 { this.raiseRecoverable(start, "getter should have no params"); }
19439 else
19440 { this.raiseRecoverable(start, "setter should have exactly one param"); }
19441 } else {
19442 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
19443 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
19444 }
19445 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
19446 if (isGenerator || isAsync) { this.unexpected(); }
19447 this.checkUnreserved(prop.key);
19448 if (prop.key.name === "await" && !this.awaitIdentPos)
19449 { this.awaitIdentPos = startPos; }
19450 prop.kind = "init";
19451 if (isPattern) {
19452 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19453 } else if (this.type === types$1.eq && refDestructuringErrors) {
19454 if (refDestructuringErrors.shorthandAssign < 0)
19455 { refDestructuringErrors.shorthandAssign = this.start; }
19456 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19457 } else {
19458 prop.value = this.copyNode(prop.key);
19459 }
19460 prop.shorthand = true;
19461 } else { this.unexpected(); }
19462};
19463
19464pp$5.parsePropertyName = function(prop) {
19465 if (this.options.ecmaVersion >= 6) {
19466 if (this.eat(types$1.bracketL)) {
19467 prop.computed = true;
19468 prop.key = this.parseMaybeAssign();
19469 this.expect(types$1.bracketR);
19470 return prop.key
19471 } else {
19472 prop.computed = false;
19473 }
19474 }
19475 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
19476};
19477
19478// Initialize empty function node.
19479
19480pp$5.initFunction = function(node) {
19481 node.id = null;
19482 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
19483 if (this.options.ecmaVersion >= 8) { node.async = false; }
19484};
19485
19486// Parse object or class method.
19487
19488pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
19489 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19490
19491 this.initFunction(node);
19492 if (this.options.ecmaVersion >= 6)
19493 { node.generator = isGenerator; }
19494 if (this.options.ecmaVersion >= 8)
19495 { node.async = !!isAsync; }
19496
19497 this.yieldPos = 0;
19498 this.awaitPos = 0;
19499 this.awaitIdentPos = 0;
19500 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
19501
19502 this.expect(types$1.parenL);
19503 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
19504 this.checkYieldAwaitInDefaultParams();
19505 this.parseFunctionBody(node, false, true, false);
19506
19507 this.yieldPos = oldYieldPos;
19508 this.awaitPos = oldAwaitPos;
19509 this.awaitIdentPos = oldAwaitIdentPos;
19510 return this.finishNode(node, "FunctionExpression")
19511};
19512
19513// Parse arrow function expression with given parameters.
19514
19515pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
19516 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19517
19518 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
19519 this.initFunction(node);
19520 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
19521
19522 this.yieldPos = 0;
19523 this.awaitPos = 0;
19524 this.awaitIdentPos = 0;
19525
19526 node.params = this.toAssignableList(params, true);
19527 this.parseFunctionBody(node, true, false, forInit);
19528
19529 this.yieldPos = oldYieldPos;
19530 this.awaitPos = oldAwaitPos;
19531 this.awaitIdentPos = oldAwaitIdentPos;
19532 return this.finishNode(node, "ArrowFunctionExpression")
19533};
19534
19535// Parse function body and check parameters.
19536
19537pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
19538 var isExpression = isArrowFunction && this.type !== types$1.braceL;
19539 var oldStrict = this.strict, useStrict = false;
19540
19541 if (isExpression) {
19542 node.body = this.parseMaybeAssign(forInit);
19543 node.expression = true;
19544 this.checkParams(node, false);
19545 } else {
19546 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
19547 if (!oldStrict || nonSimple) {
19548 useStrict = this.strictDirective(this.end);
19549 // If this is a strict mode function, verify that argument names
19550 // are not repeated, and it does not try to bind the words `eval`
19551 // or `arguments`.
19552 if (useStrict && nonSimple)
19553 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
19554 }
19555 // Start a new scope with regard to labels and the `inFunction`
19556 // flag (restore them to their old value afterwards).
19557 var oldLabels = this.labels;
19558 this.labels = [];
19559 if (useStrict) { this.strict = true; }
19560
19561 // Add the params to varDeclaredNames to ensure that an error is thrown
19562 // if a let/const declaration in the function clashes with one of the params.
19563 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
19564 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
19565 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
19566 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
19567 node.expression = false;
19568 this.adaptDirectivePrologue(node.body.body);
19569 this.labels = oldLabels;
19570 }
19571 this.exitScope();
19572};
19573
19574pp$5.isSimpleParamList = function(params) {
19575 for (var i = 0, list = params; i < list.length; i += 1)
19576 {
19577 var param = list[i];
19578
19579 if (param.type !== "Identifier") { return false
19580 } }
19581 return true
19582};
19583
19584// Checks function params for various disallowed patterns such as using "eval"
19585// or "arguments" and duplicate parameters.
19586
19587pp$5.checkParams = function(node, allowDuplicates) {
19588 var nameHash = Object.create(null);
19589 for (var i = 0, list = node.params; i < list.length; i += 1)
19590 {
19591 var param = list[i];
19592
19593 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
19594 }
19595};
19596
19597// Parses a comma-separated list of expressions, and returns them as
19598// an array. `close` is the token type that ends the list, and
19599// `allowEmpty` can be turned on to allow subsequent commas with
19600// nothing in between them to be parsed as `null` (which is needed
19601// for array literals).
19602
19603pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
19604 var elts = [], first = true;
19605 while (!this.eat(close)) {
19606 if (!first) {
19607 this.expect(types$1.comma);
19608 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
19609 } else { first = false; }
19610
19611 var elt = (void 0);
19612 if (allowEmpty && this.type === types$1.comma)
19613 { elt = null; }
19614 else if (this.type === types$1.ellipsis) {
19615 elt = this.parseSpread(refDestructuringErrors);
19616 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
19617 { refDestructuringErrors.trailingComma = this.start; }
19618 } else {
19619 elt = this.parseMaybeAssign(false, refDestructuringErrors);
19620 }
19621 elts.push(elt);
19622 }
19623 return elts
19624};
19625
19626pp$5.checkUnreserved = function(ref) {
19627 var start = ref.start;
19628 var end = ref.end;
19629 var name = ref.name;
19630
19631 if (this.inGenerator && name === "yield")
19632 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
19633 if (this.inAsync && name === "await")
19634 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
19635 if (this.currentThisScope().inClassFieldInit && name === "arguments")
19636 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
19637 if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
19638 { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
19639 if (this.keywords.test(name))
19640 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
19641 if (this.options.ecmaVersion < 6 &&
19642 this.input.slice(start, end).indexOf("\\") !== -1) { return }
19643 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
19644 if (re.test(name)) {
19645 if (!this.inAsync && name === "await")
19646 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
19647 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
19648 }
19649};
19650
19651// Parse the next token as an identifier. If `liberal` is true (used
19652// when parsing properties), it will also convert keywords into
19653// identifiers.
19654
19655pp$5.parseIdent = function(liberal, isBinding) {
19656 var node = this.startNode();
19657 if (this.type === types$1.name) {
19658 node.name = this.value;
19659 } else if (this.type.keyword) {
19660 node.name = this.type.keyword;
19661
19662 // To fix https://github.com/acornjs/acorn/issues/575
19663 // `class` and `function` keywords push new context into this.context.
19664 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
19665 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
19666 if ((node.name === "class" || node.name === "function") &&
19667 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
19668 this.context.pop();
19669 }
19670 } else {
19671 this.unexpected();
19672 }
19673 this.next(!!liberal);
19674 this.finishNode(node, "Identifier");
19675 if (!liberal) {
19676 this.checkUnreserved(node);
19677 if (node.name === "await" && !this.awaitIdentPos)
19678 { this.awaitIdentPos = node.start; }
19679 }
19680 return node
19681};
19682
19683pp$5.parsePrivateIdent = function() {
19684 var node = this.startNode();
19685 if (this.type === types$1.privateId) {
19686 node.name = this.value;
19687 } else {
19688 this.unexpected();
19689 }
19690 this.next();
19691 this.finishNode(node, "PrivateIdentifier");
19692
19693 // For validating existence
19694 if (this.privateNameStack.length === 0) {
19695 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
19696 } else {
19697 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
19698 }
19699
19700 return node
19701};
19702
19703// Parses yield expression inside generator.
19704
19705pp$5.parseYield = function(forInit) {
19706 if (!this.yieldPos) { this.yieldPos = this.start; }
19707
19708 var node = this.startNode();
19709 this.next();
19710 if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
19711 node.delegate = false;
19712 node.argument = null;
19713 } else {
19714 node.delegate = this.eat(types$1.star);
19715 node.argument = this.parseMaybeAssign(forInit);
19716 }
19717 return this.finishNode(node, "YieldExpression")
19718};
19719
19720pp$5.parseAwait = function(forInit) {
19721 if (!this.awaitPos) { this.awaitPos = this.start; }
19722
19723 var node = this.startNode();
19724 this.next();
19725 node.argument = this.parseMaybeUnary(null, true, false, forInit);
19726 return this.finishNode(node, "AwaitExpression")
19727};
19728
19729var pp$4 = Parser.prototype;
19730
19731// This function is used to raise exceptions on parse errors. It
19732// takes an offset integer (into the current `input`) to indicate
19733// the location of the error, attaches the position to the end
19734// of the error message, and then raises a `SyntaxError` with that
19735// message.
19736
19737pp$4.raise = function(pos, message) {
19738 var loc = getLineInfo(this.input, pos);
19739 message += " (" + loc.line + ":" + loc.column + ")";
19740 var err = new SyntaxError(message);
19741 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
19742 throw err
19743};
19744
19745pp$4.raiseRecoverable = pp$4.raise;
19746
19747pp$4.curPosition = function() {
19748 if (this.options.locations) {
19749 return new Position(this.curLine, this.pos - this.lineStart)
19750 }
19751};
19752
19753var pp$3 = Parser.prototype;
19754
19755var Scope = function Scope(flags) {
19756 this.flags = flags;
19757 // A list of var-declared names in the current lexical scope
19758 this.var = [];
19759 // A list of lexically-declared names in the current lexical scope
19760 this.lexical = [];
19761 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
19762 this.functions = [];
19763 // A switch to disallow the identifier reference 'arguments'
19764 this.inClassFieldInit = false;
19765};
19766
19767// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
19768
19769pp$3.enterScope = function(flags) {
19770 this.scopeStack.push(new Scope(flags));
19771};
19772
19773pp$3.exitScope = function() {
19774 this.scopeStack.pop();
19775};
19776
19777// The spec says:
19778// > At the top level of a function, or script, function declarations are
19779// > treated like var declarations rather than like lexical declarations.
19780pp$3.treatFunctionsAsVarInScope = function(scope) {
19781 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
19782};
19783
19784pp$3.declareName = function(name, bindingType, pos) {
19785 var redeclared = false;
19786 if (bindingType === BIND_LEXICAL) {
19787 var scope = this.currentScope();
19788 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
19789 scope.lexical.push(name);
19790 if (this.inModule && (scope.flags & SCOPE_TOP))
19791 { delete this.undefinedExports[name]; }
19792 } else if (bindingType === BIND_SIMPLE_CATCH) {
19793 var scope$1 = this.currentScope();
19794 scope$1.lexical.push(name);
19795 } else if (bindingType === BIND_FUNCTION) {
19796 var scope$2 = this.currentScope();
19797 if (this.treatFunctionsAsVar)
19798 { redeclared = scope$2.lexical.indexOf(name) > -1; }
19799 else
19800 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
19801 scope$2.functions.push(name);
19802 } else {
19803 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
19804 var scope$3 = this.scopeStack[i];
19805 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
19806 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
19807 redeclared = true;
19808 break
19809 }
19810 scope$3.var.push(name);
19811 if (this.inModule && (scope$3.flags & SCOPE_TOP))
19812 { delete this.undefinedExports[name]; }
19813 if (scope$3.flags & SCOPE_VAR) { break }
19814 }
19815 }
19816 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
19817};
19818
19819pp$3.checkLocalExport = function(id) {
19820 // scope.functions must be empty as Module code is always strict.
19821 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
19822 this.scopeStack[0].var.indexOf(id.name) === -1) {
19823 this.undefinedExports[id.name] = id;
19824 }
19825};
19826
19827pp$3.currentScope = function() {
19828 return this.scopeStack[this.scopeStack.length - 1]
19829};
19830
19831pp$3.currentVarScope = function() {
19832 for (var i = this.scopeStack.length - 1;; i--) {
19833 var scope = this.scopeStack[i];
19834 if (scope.flags & SCOPE_VAR) { return scope }
19835 }
19836};
19837
19838// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
19839pp$3.currentThisScope = function() {
19840 for (var i = this.scopeStack.length - 1;; i--) {
19841 var scope = this.scopeStack[i];
19842 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
19843 }
19844};
19845
19846var Node = function Node(parser, pos, loc) {
19847 this.type = "";
19848 this.start = pos;
19849 this.end = 0;
19850 if (parser.options.locations)
19851 { this.loc = new SourceLocation(parser, loc); }
19852 if (parser.options.directSourceFile)
19853 { this.sourceFile = parser.options.directSourceFile; }
19854 if (parser.options.ranges)
19855 { this.range = [pos, 0]; }
19856};
19857
19858// Start an AST node, attaching a start offset.
19859
19860var pp$2 = Parser.prototype;
19861
19862pp$2.startNode = function() {
19863 return new Node(this, this.start, this.startLoc)
19864};
19865
19866pp$2.startNodeAt = function(pos, loc) {
19867 return new Node(this, pos, loc)
19868};
19869
19870// Finish an AST node, adding `type` and `end` properties.
19871
19872function finishNodeAt(node, type, pos, loc) {
19873 node.type = type;
19874 node.end = pos;
19875 if (this.options.locations)
19876 { node.loc.end = loc; }
19877 if (this.options.ranges)
19878 { node.range[1] = pos; }
19879 return node
19880}
19881
19882pp$2.finishNode = function(node, type) {
19883 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
19884};
19885
19886// Finish node at given position
19887
19888pp$2.finishNodeAt = function(node, type, pos, loc) {
19889 return finishNodeAt.call(this, node, type, pos, loc)
19890};
19891
19892pp$2.copyNode = function(node) {
19893 var newNode = new Node(this, node.start, this.startLoc);
19894 for (var prop in node) { newNode[prop] = node[prop]; }
19895 return newNode
19896};
19897
19898// This file contains Unicode properties extracted from the ECMAScript
19899// specification. The lists are extracted like so:
19900// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
19901
19902// #table-binary-unicode-properties
19903var 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";
19904var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
19905var ecma11BinaryProperties = ecma10BinaryProperties;
19906var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
19907var ecma13BinaryProperties = ecma12BinaryProperties;
19908var unicodeBinaryProperties = {
19909 9: ecma9BinaryProperties,
19910 10: ecma10BinaryProperties,
19911 11: ecma11BinaryProperties,
19912 12: ecma12BinaryProperties,
19913 13: ecma13BinaryProperties
19914};
19915
19916// #table-unicode-general-category-values
19917var 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";
19918
19919// #table-unicode-script-values
19920var ecma9ScriptValues = "Adlam Adlm 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 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";
19921var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
19922var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
19923var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
19924var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
19925var unicodeScriptValues = {
19926 9: ecma9ScriptValues,
19927 10: ecma10ScriptValues,
19928 11: ecma11ScriptValues,
19929 12: ecma12ScriptValues,
19930 13: ecma13ScriptValues
19931};
19932
19933var data = {};
19934function buildUnicodeData(ecmaVersion) {
19935 var d = data[ecmaVersion] = {
19936 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
19937 nonBinary: {
19938 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
19939 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
19940 }
19941 };
19942 d.nonBinary.Script_Extensions = d.nonBinary.Script;
19943
19944 d.nonBinary.gc = d.nonBinary.General_Category;
19945 d.nonBinary.sc = d.nonBinary.Script;
19946 d.nonBinary.scx = d.nonBinary.Script_Extensions;
19947}
19948
19949for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
19950 var ecmaVersion = list[i];
19951
19952 buildUnicodeData(ecmaVersion);
19953}
19954
19955var pp$1 = Parser.prototype;
19956
19957var RegExpValidationState = function RegExpValidationState(parser) {
19958 this.parser = parser;
19959 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
19960 this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
19961 this.source = "";
19962 this.flags = "";
19963 this.start = 0;
19964 this.switchU = false;
19965 this.switchN = false;
19966 this.pos = 0;
19967 this.lastIntValue = 0;
19968 this.lastStringValue = "";
19969 this.lastAssertionIsQuantifiable = false;
19970 this.numCapturingParens = 0;
19971 this.maxBackReference = 0;
19972 this.groupNames = [];
19973 this.backReferenceNames = [];
19974};
19975
19976RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
19977 var unicode = flags.indexOf("u") !== -1;
19978 this.start = start | 0;
19979 this.source = pattern + "";
19980 this.flags = flags;
19981 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
19982 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
19983};
19984
19985RegExpValidationState.prototype.raise = function raise (message) {
19986 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
19987};
19988
19989// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
19990// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
19991RegExpValidationState.prototype.at = function at (i, forceU) {
19992 if ( forceU === void 0 ) forceU = false;
19993
19994 var s = this.source;
19995 var l = s.length;
19996 if (i >= l) {
19997 return -1
19998 }
19999 var c = s.charCodeAt(i);
20000 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
20001 return c
20002 }
20003 var next = s.charCodeAt(i + 1);
20004 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
20005};
20006
20007RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
20008 if ( forceU === void 0 ) forceU = false;
20009
20010 var s = this.source;
20011 var l = s.length;
20012 if (i >= l) {
20013 return l
20014 }
20015 var c = s.charCodeAt(i), next;
20016 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
20017 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
20018 return i + 1
20019 }
20020 return i + 2
20021};
20022
20023RegExpValidationState.prototype.current = function current (forceU) {
20024 if ( forceU === void 0 ) forceU = false;
20025
20026 return this.at(this.pos, forceU)
20027};
20028
20029RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
20030 if ( forceU === void 0 ) forceU = false;
20031
20032 return this.at(this.nextIndex(this.pos, forceU), forceU)
20033};
20034
20035RegExpValidationState.prototype.advance = function advance (forceU) {
20036 if ( forceU === void 0 ) forceU = false;
20037
20038 this.pos = this.nextIndex(this.pos, forceU);
20039};
20040
20041RegExpValidationState.prototype.eat = function eat (ch, forceU) {
20042 if ( forceU === void 0 ) forceU = false;
20043
20044 if (this.current(forceU) === ch) {
20045 this.advance(forceU);
20046 return true
20047 }
20048 return false
20049};
20050
20051/**
20052 * Validate the flags part of a given RegExpLiteral.
20053 *
20054 * @param {RegExpValidationState} state The state to validate RegExp.
20055 * @returns {void}
20056 */
20057pp$1.validateRegExpFlags = function(state) {
20058 var validFlags = state.validFlags;
20059 var flags = state.flags;
20060
20061 for (var i = 0; i < flags.length; i++) {
20062 var flag = flags.charAt(i);
20063 if (validFlags.indexOf(flag) === -1) {
20064 this.raise(state.start, "Invalid regular expression flag");
20065 }
20066 if (flags.indexOf(flag, i + 1) > -1) {
20067 this.raise(state.start, "Duplicate regular expression flag");
20068 }
20069 }
20070};
20071
20072/**
20073 * Validate the pattern part of a given RegExpLiteral.
20074 *
20075 * @param {RegExpValidationState} state The state to validate RegExp.
20076 * @returns {void}
20077 */
20078pp$1.validateRegExpPattern = function(state) {
20079 this.regexp_pattern(state);
20080
20081 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
20082 // parsing contains a |GroupName|, reparse with the goal symbol
20083 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
20084 // exception if _P_ did not conform to the grammar, if any elements of _P_
20085 // were not matched by the parse, or if any Early Error conditions exist.
20086 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
20087 state.switchN = true;
20088 this.regexp_pattern(state);
20089 }
20090};
20091
20092// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
20093pp$1.regexp_pattern = function(state) {
20094 state.pos = 0;
20095 state.lastIntValue = 0;
20096 state.lastStringValue = "";
20097 state.lastAssertionIsQuantifiable = false;
20098 state.numCapturingParens = 0;
20099 state.maxBackReference = 0;
20100 state.groupNames.length = 0;
20101 state.backReferenceNames.length = 0;
20102
20103 this.regexp_disjunction(state);
20104
20105 if (state.pos !== state.source.length) {
20106 // Make the same messages as V8.
20107 if (state.eat(0x29 /* ) */)) {
20108 state.raise("Unmatched ')'");
20109 }
20110 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
20111 state.raise("Lone quantifier brackets");
20112 }
20113 }
20114 if (state.maxBackReference > state.numCapturingParens) {
20115 state.raise("Invalid escape");
20116 }
20117 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
20118 var name = list[i];
20119
20120 if (state.groupNames.indexOf(name) === -1) {
20121 state.raise("Invalid named capture referenced");
20122 }
20123 }
20124};
20125
20126// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
20127pp$1.regexp_disjunction = function(state) {
20128 this.regexp_alternative(state);
20129 while (state.eat(0x7C /* | */)) {
20130 this.regexp_alternative(state);
20131 }
20132
20133 // Make the same message as V8.
20134 if (this.regexp_eatQuantifier(state, true)) {
20135 state.raise("Nothing to repeat");
20136 }
20137 if (state.eat(0x7B /* { */)) {
20138 state.raise("Lone quantifier brackets");
20139 }
20140};
20141
20142// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
20143pp$1.regexp_alternative = function(state) {
20144 while (state.pos < state.source.length && this.regexp_eatTerm(state))
20145 { }
20146};
20147
20148// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
20149pp$1.regexp_eatTerm = function(state) {
20150 if (this.regexp_eatAssertion(state)) {
20151 // Handle `QuantifiableAssertion Quantifier` alternative.
20152 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
20153 // is a QuantifiableAssertion.
20154 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
20155 // Make the same message as V8.
20156 if (state.switchU) {
20157 state.raise("Invalid quantifier");
20158 }
20159 }
20160 return true
20161 }
20162
20163 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
20164 this.regexp_eatQuantifier(state);
20165 return true
20166 }
20167
20168 return false
20169};
20170
20171// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
20172pp$1.regexp_eatAssertion = function(state) {
20173 var start = state.pos;
20174 state.lastAssertionIsQuantifiable = false;
20175
20176 // ^, $
20177 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
20178 return true
20179 }
20180
20181 // \b \B
20182 if (state.eat(0x5C /* \ */)) {
20183 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
20184 return true
20185 }
20186 state.pos = start;
20187 }
20188
20189 // Lookahead / Lookbehind
20190 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
20191 var lookbehind = false;
20192 if (this.options.ecmaVersion >= 9) {
20193 lookbehind = state.eat(0x3C /* < */);
20194 }
20195 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
20196 this.regexp_disjunction(state);
20197 if (!state.eat(0x29 /* ) */)) {
20198 state.raise("Unterminated group");
20199 }
20200 state.lastAssertionIsQuantifiable = !lookbehind;
20201 return true
20202 }
20203 }
20204
20205 state.pos = start;
20206 return false
20207};
20208
20209// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
20210pp$1.regexp_eatQuantifier = function(state, noError) {
20211 if ( noError === void 0 ) noError = false;
20212
20213 if (this.regexp_eatQuantifierPrefix(state, noError)) {
20214 state.eat(0x3F /* ? */);
20215 return true
20216 }
20217 return false
20218};
20219
20220// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
20221pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
20222 return (
20223 state.eat(0x2A /* * */) ||
20224 state.eat(0x2B /* + */) ||
20225 state.eat(0x3F /* ? */) ||
20226 this.regexp_eatBracedQuantifier(state, noError)
20227 )
20228};
20229pp$1.regexp_eatBracedQuantifier = function(state, noError) {
20230 var start = state.pos;
20231 if (state.eat(0x7B /* { */)) {
20232 var min = 0, max = -1;
20233 if (this.regexp_eatDecimalDigits(state)) {
20234 min = state.lastIntValue;
20235 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
20236 max = state.lastIntValue;
20237 }
20238 if (state.eat(0x7D /* } */)) {
20239 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
20240 if (max !== -1 && max < min && !noError) {
20241 state.raise("numbers out of order in {} quantifier");
20242 }
20243 return true
20244 }
20245 }
20246 if (state.switchU && !noError) {
20247 state.raise("Incomplete quantifier");
20248 }
20249 state.pos = start;
20250 }
20251 return false
20252};
20253
20254// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
20255pp$1.regexp_eatAtom = function(state) {
20256 return (
20257 this.regexp_eatPatternCharacters(state) ||
20258 state.eat(0x2E /* . */) ||
20259 this.regexp_eatReverseSolidusAtomEscape(state) ||
20260 this.regexp_eatCharacterClass(state) ||
20261 this.regexp_eatUncapturingGroup(state) ||
20262 this.regexp_eatCapturingGroup(state)
20263 )
20264};
20265pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
20266 var start = state.pos;
20267 if (state.eat(0x5C /* \ */)) {
20268 if (this.regexp_eatAtomEscape(state)) {
20269 return true
20270 }
20271 state.pos = start;
20272 }
20273 return false
20274};
20275pp$1.regexp_eatUncapturingGroup = function(state) {
20276 var start = state.pos;
20277 if (state.eat(0x28 /* ( */)) {
20278 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
20279 this.regexp_disjunction(state);
20280 if (state.eat(0x29 /* ) */)) {
20281 return true
20282 }
20283 state.raise("Unterminated group");
20284 }
20285 state.pos = start;
20286 }
20287 return false
20288};
20289pp$1.regexp_eatCapturingGroup = function(state) {
20290 if (state.eat(0x28 /* ( */)) {
20291 if (this.options.ecmaVersion >= 9) {
20292 this.regexp_groupSpecifier(state);
20293 } else if (state.current() === 0x3F /* ? */) {
20294 state.raise("Invalid group");
20295 }
20296 this.regexp_disjunction(state);
20297 if (state.eat(0x29 /* ) */)) {
20298 state.numCapturingParens += 1;
20299 return true
20300 }
20301 state.raise("Unterminated group");
20302 }
20303 return false
20304};
20305
20306// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
20307pp$1.regexp_eatExtendedAtom = function(state) {
20308 return (
20309 state.eat(0x2E /* . */) ||
20310 this.regexp_eatReverseSolidusAtomEscape(state) ||
20311 this.regexp_eatCharacterClass(state) ||
20312 this.regexp_eatUncapturingGroup(state) ||
20313 this.regexp_eatCapturingGroup(state) ||
20314 this.regexp_eatInvalidBracedQuantifier(state) ||
20315 this.regexp_eatExtendedPatternCharacter(state)
20316 )
20317};
20318
20319// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
20320pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
20321 if (this.regexp_eatBracedQuantifier(state, true)) {
20322 state.raise("Nothing to repeat");
20323 }
20324 return false
20325};
20326
20327// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
20328pp$1.regexp_eatSyntaxCharacter = function(state) {
20329 var ch = state.current();
20330 if (isSyntaxCharacter(ch)) {
20331 state.lastIntValue = ch;
20332 state.advance();
20333 return true
20334 }
20335 return false
20336};
20337function isSyntaxCharacter(ch) {
20338 return (
20339 ch === 0x24 /* $ */ ||
20340 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
20341 ch === 0x2E /* . */ ||
20342 ch === 0x3F /* ? */ ||
20343 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
20344 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
20345 )
20346}
20347
20348// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
20349// But eat eager.
20350pp$1.regexp_eatPatternCharacters = function(state) {
20351 var start = state.pos;
20352 var ch = 0;
20353 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
20354 state.advance();
20355 }
20356 return state.pos !== start
20357};
20358
20359// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
20360pp$1.regexp_eatExtendedPatternCharacter = function(state) {
20361 var ch = state.current();
20362 if (
20363 ch !== -1 &&
20364 ch !== 0x24 /* $ */ &&
20365 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
20366 ch !== 0x2E /* . */ &&
20367 ch !== 0x3F /* ? */ &&
20368 ch !== 0x5B /* [ */ &&
20369 ch !== 0x5E /* ^ */ &&
20370 ch !== 0x7C /* | */
20371 ) {
20372 state.advance();
20373 return true
20374 }
20375 return false
20376};
20377
20378// GroupSpecifier ::
20379// [empty]
20380// `?` GroupName
20381pp$1.regexp_groupSpecifier = function(state) {
20382 if (state.eat(0x3F /* ? */)) {
20383 if (this.regexp_eatGroupName(state)) {
20384 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
20385 state.raise("Duplicate capture group name");
20386 }
20387 state.groupNames.push(state.lastStringValue);
20388 return
20389 }
20390 state.raise("Invalid group");
20391 }
20392};
20393
20394// GroupName ::
20395// `<` RegExpIdentifierName `>`
20396// Note: this updates `state.lastStringValue` property with the eaten name.
20397pp$1.regexp_eatGroupName = function(state) {
20398 state.lastStringValue = "";
20399 if (state.eat(0x3C /* < */)) {
20400 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
20401 return true
20402 }
20403 state.raise("Invalid capture group name");
20404 }
20405 return false
20406};
20407
20408// RegExpIdentifierName ::
20409// RegExpIdentifierStart
20410// RegExpIdentifierName RegExpIdentifierPart
20411// Note: this updates `state.lastStringValue` property with the eaten name.
20412pp$1.regexp_eatRegExpIdentifierName = function(state) {
20413 state.lastStringValue = "";
20414 if (this.regexp_eatRegExpIdentifierStart(state)) {
20415 state.lastStringValue += codePointToString(state.lastIntValue);
20416 while (this.regexp_eatRegExpIdentifierPart(state)) {
20417 state.lastStringValue += codePointToString(state.lastIntValue);
20418 }
20419 return true
20420 }
20421 return false
20422};
20423
20424// RegExpIdentifierStart ::
20425// UnicodeIDStart
20426// `$`
20427// `_`
20428// `\` RegExpUnicodeEscapeSequence[+U]
20429pp$1.regexp_eatRegExpIdentifierStart = function(state) {
20430 var start = state.pos;
20431 var forceU = this.options.ecmaVersion >= 11;
20432 var ch = state.current(forceU);
20433 state.advance(forceU);
20434
20435 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20436 ch = state.lastIntValue;
20437 }
20438 if (isRegExpIdentifierStart(ch)) {
20439 state.lastIntValue = ch;
20440 return true
20441 }
20442
20443 state.pos = start;
20444 return false
20445};
20446function isRegExpIdentifierStart(ch) {
20447 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
20448}
20449
20450// RegExpIdentifierPart ::
20451// UnicodeIDContinue
20452// `$`
20453// `_`
20454// `\` RegExpUnicodeEscapeSequence[+U]
20455// <ZWNJ>
20456// <ZWJ>
20457pp$1.regexp_eatRegExpIdentifierPart = function(state) {
20458 var start = state.pos;
20459 var forceU = this.options.ecmaVersion >= 11;
20460 var ch = state.current(forceU);
20461 state.advance(forceU);
20462
20463 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20464 ch = state.lastIntValue;
20465 }
20466 if (isRegExpIdentifierPart(ch)) {
20467 state.lastIntValue = ch;
20468 return true
20469 }
20470
20471 state.pos = start;
20472 return false
20473};
20474function isRegExpIdentifierPart(ch) {
20475 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
20476}
20477
20478// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
20479pp$1.regexp_eatAtomEscape = function(state) {
20480 if (
20481 this.regexp_eatBackReference(state) ||
20482 this.regexp_eatCharacterClassEscape(state) ||
20483 this.regexp_eatCharacterEscape(state) ||
20484 (state.switchN && this.regexp_eatKGroupName(state))
20485 ) {
20486 return true
20487 }
20488 if (state.switchU) {
20489 // Make the same message as V8.
20490 if (state.current() === 0x63 /* c */) {
20491 state.raise("Invalid unicode escape");
20492 }
20493 state.raise("Invalid escape");
20494 }
20495 return false
20496};
20497pp$1.regexp_eatBackReference = function(state) {
20498 var start = state.pos;
20499 if (this.regexp_eatDecimalEscape(state)) {
20500 var n = state.lastIntValue;
20501 if (state.switchU) {
20502 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
20503 if (n > state.maxBackReference) {
20504 state.maxBackReference = n;
20505 }
20506 return true
20507 }
20508 if (n <= state.numCapturingParens) {
20509 return true
20510 }
20511 state.pos = start;
20512 }
20513 return false
20514};
20515pp$1.regexp_eatKGroupName = function(state) {
20516 if (state.eat(0x6B /* k */)) {
20517 if (this.regexp_eatGroupName(state)) {
20518 state.backReferenceNames.push(state.lastStringValue);
20519 return true
20520 }
20521 state.raise("Invalid named reference");
20522 }
20523 return false
20524};
20525
20526// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
20527pp$1.regexp_eatCharacterEscape = function(state) {
20528 return (
20529 this.regexp_eatControlEscape(state) ||
20530 this.regexp_eatCControlLetter(state) ||
20531 this.regexp_eatZero(state) ||
20532 this.regexp_eatHexEscapeSequence(state) ||
20533 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
20534 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
20535 this.regexp_eatIdentityEscape(state)
20536 )
20537};
20538pp$1.regexp_eatCControlLetter = function(state) {
20539 var start = state.pos;
20540 if (state.eat(0x63 /* c */)) {
20541 if (this.regexp_eatControlLetter(state)) {
20542 return true
20543 }
20544 state.pos = start;
20545 }
20546 return false
20547};
20548pp$1.regexp_eatZero = function(state) {
20549 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
20550 state.lastIntValue = 0;
20551 state.advance();
20552 return true
20553 }
20554 return false
20555};
20556
20557// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
20558pp$1.regexp_eatControlEscape = function(state) {
20559 var ch = state.current();
20560 if (ch === 0x74 /* t */) {
20561 state.lastIntValue = 0x09; /* \t */
20562 state.advance();
20563 return true
20564 }
20565 if (ch === 0x6E /* n */) {
20566 state.lastIntValue = 0x0A; /* \n */
20567 state.advance();
20568 return true
20569 }
20570 if (ch === 0x76 /* v */) {
20571 state.lastIntValue = 0x0B; /* \v */
20572 state.advance();
20573 return true
20574 }
20575 if (ch === 0x66 /* f */) {
20576 state.lastIntValue = 0x0C; /* \f */
20577 state.advance();
20578 return true
20579 }
20580 if (ch === 0x72 /* r */) {
20581 state.lastIntValue = 0x0D; /* \r */
20582 state.advance();
20583 return true
20584 }
20585 return false
20586};
20587
20588// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
20589pp$1.regexp_eatControlLetter = function(state) {
20590 var ch = state.current();
20591 if (isControlLetter(ch)) {
20592 state.lastIntValue = ch % 0x20;
20593 state.advance();
20594 return true
20595 }
20596 return false
20597};
20598function isControlLetter(ch) {
20599 return (
20600 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
20601 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
20602 )
20603}
20604
20605// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
20606pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
20607 if ( forceU === void 0 ) forceU = false;
20608
20609 var start = state.pos;
20610 var switchU = forceU || state.switchU;
20611
20612 if (state.eat(0x75 /* u */)) {
20613 if (this.regexp_eatFixedHexDigits(state, 4)) {
20614 var lead = state.lastIntValue;
20615 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
20616 var leadSurrogateEnd = state.pos;
20617 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
20618 var trail = state.lastIntValue;
20619 if (trail >= 0xDC00 && trail <= 0xDFFF) {
20620 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
20621 return true
20622 }
20623 }
20624 state.pos = leadSurrogateEnd;
20625 state.lastIntValue = lead;
20626 }
20627 return true
20628 }
20629 if (
20630 switchU &&
20631 state.eat(0x7B /* { */) &&
20632 this.regexp_eatHexDigits(state) &&
20633 state.eat(0x7D /* } */) &&
20634 isValidUnicode(state.lastIntValue)
20635 ) {
20636 return true
20637 }
20638 if (switchU) {
20639 state.raise("Invalid unicode escape");
20640 }
20641 state.pos = start;
20642 }
20643
20644 return false
20645};
20646function isValidUnicode(ch) {
20647 return ch >= 0 && ch <= 0x10FFFF
20648}
20649
20650// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
20651pp$1.regexp_eatIdentityEscape = function(state) {
20652 if (state.switchU) {
20653 if (this.regexp_eatSyntaxCharacter(state)) {
20654 return true
20655 }
20656 if (state.eat(0x2F /* / */)) {
20657 state.lastIntValue = 0x2F; /* / */
20658 return true
20659 }
20660 return false
20661 }
20662
20663 var ch = state.current();
20664 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
20665 state.lastIntValue = ch;
20666 state.advance();
20667 return true
20668 }
20669
20670 return false
20671};
20672
20673// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
20674pp$1.regexp_eatDecimalEscape = function(state) {
20675 state.lastIntValue = 0;
20676 var ch = state.current();
20677 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
20678 do {
20679 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20680 state.advance();
20681 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
20682 return true
20683 }
20684 return false
20685};
20686
20687// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
20688pp$1.regexp_eatCharacterClassEscape = function(state) {
20689 var ch = state.current();
20690
20691 if (isCharacterClassEscape(ch)) {
20692 state.lastIntValue = -1;
20693 state.advance();
20694 return true
20695 }
20696
20697 if (
20698 state.switchU &&
20699 this.options.ecmaVersion >= 9 &&
20700 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
20701 ) {
20702 state.lastIntValue = -1;
20703 state.advance();
20704 if (
20705 state.eat(0x7B /* { */) &&
20706 this.regexp_eatUnicodePropertyValueExpression(state) &&
20707 state.eat(0x7D /* } */)
20708 ) {
20709 return true
20710 }
20711 state.raise("Invalid property name");
20712 }
20713
20714 return false
20715};
20716function isCharacterClassEscape(ch) {
20717 return (
20718 ch === 0x64 /* d */ ||
20719 ch === 0x44 /* D */ ||
20720 ch === 0x73 /* s */ ||
20721 ch === 0x53 /* S */ ||
20722 ch === 0x77 /* w */ ||
20723 ch === 0x57 /* W */
20724 )
20725}
20726
20727// UnicodePropertyValueExpression ::
20728// UnicodePropertyName `=` UnicodePropertyValue
20729// LoneUnicodePropertyNameOrValue
20730pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
20731 var start = state.pos;
20732
20733 // UnicodePropertyName `=` UnicodePropertyValue
20734 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
20735 var name = state.lastStringValue;
20736 if (this.regexp_eatUnicodePropertyValue(state)) {
20737 var value = state.lastStringValue;
20738 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
20739 return true
20740 }
20741 }
20742 state.pos = start;
20743
20744 // LoneUnicodePropertyNameOrValue
20745 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
20746 var nameOrValue = state.lastStringValue;
20747 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
20748 return true
20749 }
20750 return false
20751};
20752pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
20753 if (!hasOwn(state.unicodeProperties.nonBinary, name))
20754 { state.raise("Invalid property name"); }
20755 if (!state.unicodeProperties.nonBinary[name].test(value))
20756 { state.raise("Invalid property value"); }
20757};
20758pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
20759 if (!state.unicodeProperties.binary.test(nameOrValue))
20760 { state.raise("Invalid property name"); }
20761};
20762
20763// UnicodePropertyName ::
20764// UnicodePropertyNameCharacters
20765pp$1.regexp_eatUnicodePropertyName = function(state) {
20766 var ch = 0;
20767 state.lastStringValue = "";
20768 while (isUnicodePropertyNameCharacter(ch = state.current())) {
20769 state.lastStringValue += codePointToString(ch);
20770 state.advance();
20771 }
20772 return state.lastStringValue !== ""
20773};
20774function isUnicodePropertyNameCharacter(ch) {
20775 return isControlLetter(ch) || ch === 0x5F /* _ */
20776}
20777
20778// UnicodePropertyValue ::
20779// UnicodePropertyValueCharacters
20780pp$1.regexp_eatUnicodePropertyValue = function(state) {
20781 var ch = 0;
20782 state.lastStringValue = "";
20783 while (isUnicodePropertyValueCharacter(ch = state.current())) {
20784 state.lastStringValue += codePointToString(ch);
20785 state.advance();
20786 }
20787 return state.lastStringValue !== ""
20788};
20789function isUnicodePropertyValueCharacter(ch) {
20790 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
20791}
20792
20793// LoneUnicodePropertyNameOrValue ::
20794// UnicodePropertyValueCharacters
20795pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
20796 return this.regexp_eatUnicodePropertyValue(state)
20797};
20798
20799// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
20800pp$1.regexp_eatCharacterClass = function(state) {
20801 if (state.eat(0x5B /* [ */)) {
20802 state.eat(0x5E /* ^ */);
20803 this.regexp_classRanges(state);
20804 if (state.eat(0x5D /* ] */)) {
20805 return true
20806 }
20807 // Unreachable since it threw "unterminated regular expression" error before.
20808 state.raise("Unterminated character class");
20809 }
20810 return false
20811};
20812
20813// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
20814// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
20815// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
20816pp$1.regexp_classRanges = function(state) {
20817 while (this.regexp_eatClassAtom(state)) {
20818 var left = state.lastIntValue;
20819 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
20820 var right = state.lastIntValue;
20821 if (state.switchU && (left === -1 || right === -1)) {
20822 state.raise("Invalid character class");
20823 }
20824 if (left !== -1 && right !== -1 && left > right) {
20825 state.raise("Range out of order in character class");
20826 }
20827 }
20828 }
20829};
20830
20831// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
20832// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
20833pp$1.regexp_eatClassAtom = function(state) {
20834 var start = state.pos;
20835
20836 if (state.eat(0x5C /* \ */)) {
20837 if (this.regexp_eatClassEscape(state)) {
20838 return true
20839 }
20840 if (state.switchU) {
20841 // Make the same message as V8.
20842 var ch$1 = state.current();
20843 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
20844 state.raise("Invalid class escape");
20845 }
20846 state.raise("Invalid escape");
20847 }
20848 state.pos = start;
20849 }
20850
20851 var ch = state.current();
20852 if (ch !== 0x5D /* ] */) {
20853 state.lastIntValue = ch;
20854 state.advance();
20855 return true
20856 }
20857
20858 return false
20859};
20860
20861// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
20862pp$1.regexp_eatClassEscape = function(state) {
20863 var start = state.pos;
20864
20865 if (state.eat(0x62 /* b */)) {
20866 state.lastIntValue = 0x08; /* <BS> */
20867 return true
20868 }
20869
20870 if (state.switchU && state.eat(0x2D /* - */)) {
20871 state.lastIntValue = 0x2D; /* - */
20872 return true
20873 }
20874
20875 if (!state.switchU && state.eat(0x63 /* c */)) {
20876 if (this.regexp_eatClassControlLetter(state)) {
20877 return true
20878 }
20879 state.pos = start;
20880 }
20881
20882 return (
20883 this.regexp_eatCharacterClassEscape(state) ||
20884 this.regexp_eatCharacterEscape(state)
20885 )
20886};
20887
20888// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
20889pp$1.regexp_eatClassControlLetter = function(state) {
20890 var ch = state.current();
20891 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
20892 state.lastIntValue = ch % 0x20;
20893 state.advance();
20894 return true
20895 }
20896 return false
20897};
20898
20899// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20900pp$1.regexp_eatHexEscapeSequence = function(state) {
20901 var start = state.pos;
20902 if (state.eat(0x78 /* x */)) {
20903 if (this.regexp_eatFixedHexDigits(state, 2)) {
20904 return true
20905 }
20906 if (state.switchU) {
20907 state.raise("Invalid escape");
20908 }
20909 state.pos = start;
20910 }
20911 return false
20912};
20913
20914// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
20915pp$1.regexp_eatDecimalDigits = function(state) {
20916 var start = state.pos;
20917 var ch = 0;
20918 state.lastIntValue = 0;
20919 while (isDecimalDigit(ch = state.current())) {
20920 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20921 state.advance();
20922 }
20923 return state.pos !== start
20924};
20925function isDecimalDigit(ch) {
20926 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
20927}
20928
20929// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
20930pp$1.regexp_eatHexDigits = function(state) {
20931 var start = state.pos;
20932 var ch = 0;
20933 state.lastIntValue = 0;
20934 while (isHexDigit(ch = state.current())) {
20935 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
20936 state.advance();
20937 }
20938 return state.pos !== start
20939};
20940function isHexDigit(ch) {
20941 return (
20942 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
20943 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
20944 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
20945 )
20946}
20947function hexToInt(ch) {
20948 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
20949 return 10 + (ch - 0x41 /* A */)
20950 }
20951 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
20952 return 10 + (ch - 0x61 /* a */)
20953 }
20954 return ch - 0x30 /* 0 */
20955}
20956
20957// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
20958// Allows only 0-377(octal) i.e. 0-255(decimal).
20959pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
20960 if (this.regexp_eatOctalDigit(state)) {
20961 var n1 = state.lastIntValue;
20962 if (this.regexp_eatOctalDigit(state)) {
20963 var n2 = state.lastIntValue;
20964 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
20965 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
20966 } else {
20967 state.lastIntValue = n1 * 8 + n2;
20968 }
20969 } else {
20970 state.lastIntValue = n1;
20971 }
20972 return true
20973 }
20974 return false
20975};
20976
20977// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
20978pp$1.regexp_eatOctalDigit = function(state) {
20979 var ch = state.current();
20980 if (isOctalDigit(ch)) {
20981 state.lastIntValue = ch - 0x30; /* 0 */
20982 state.advance();
20983 return true
20984 }
20985 state.lastIntValue = 0;
20986 return false
20987};
20988function isOctalDigit(ch) {
20989 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
20990}
20991
20992// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
20993// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
20994// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20995pp$1.regexp_eatFixedHexDigits = function(state, length) {
20996 var start = state.pos;
20997 state.lastIntValue = 0;
20998 for (var i = 0; i < length; ++i) {
20999 var ch = state.current();
21000 if (!isHexDigit(ch)) {
21001 state.pos = start;
21002 return false
21003 }
21004 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
21005 state.advance();
21006 }
21007 return true
21008};
21009
21010// Object type used to represent tokens. Note that normally, tokens
21011// simply exist as properties on the parser object. This is only
21012// used for the onToken callback and the external tokenizer.
21013
21014var Token = function Token(p) {
21015 this.type = p.type;
21016 this.value = p.value;
21017 this.start = p.start;
21018 this.end = p.end;
21019 if (p.options.locations)
21020 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
21021 if (p.options.ranges)
21022 { this.range = [p.start, p.end]; }
21023};
21024
21025// ## Tokenizer
21026
21027var pp = Parser.prototype;
21028
21029// Move to the next token
21030
21031pp.next = function(ignoreEscapeSequenceInKeyword) {
21032 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
21033 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
21034 if (this.options.onToken)
21035 { this.options.onToken(new Token(this)); }
21036
21037 this.lastTokEnd = this.end;
21038 this.lastTokStart = this.start;
21039 this.lastTokEndLoc = this.endLoc;
21040 this.lastTokStartLoc = this.startLoc;
21041 this.nextToken();
21042};
21043
21044pp.getToken = function() {
21045 this.next();
21046 return new Token(this)
21047};
21048
21049// If we're in an ES6 environment, make parsers iterable
21050if (typeof Symbol !== "undefined")
21051 { pp[Symbol.iterator] = function() {
21052 var this$1$1 = this;
21053
21054 return {
21055 next: function () {
21056 var token = this$1$1.getToken();
21057 return {
21058 done: token.type === types$1.eof,
21059 value: token
21060 }
21061 }
21062 }
21063 }; }
21064
21065// Toggle strict mode. Re-reads the next number or string to please
21066// pedantic tests (`"use strict"; 010;` should fail).
21067
21068// Read a single token, updating the parser object's token-related
21069// properties.
21070
21071pp.nextToken = function() {
21072 var curContext = this.curContext();
21073 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
21074
21075 this.start = this.pos;
21076 if (this.options.locations) { this.startLoc = this.curPosition(); }
21077 if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
21078
21079 if (curContext.override) { return curContext.override(this) }
21080 else { this.readToken(this.fullCharCodeAtPos()); }
21081};
21082
21083pp.readToken = function(code) {
21084 // Identifier or keyword. '\uXXXX' sequences are allowed in
21085 // identifiers, so '\' also dispatches to that.
21086 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
21087 { return this.readWord() }
21088
21089 return this.getTokenFromCode(code)
21090};
21091
21092pp.fullCharCodeAtPos = function() {
21093 var code = this.input.charCodeAt(this.pos);
21094 if (code <= 0xd7ff || code >= 0xdc00) { return code }
21095 var next = this.input.charCodeAt(this.pos + 1);
21096 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
21097};
21098
21099pp.skipBlockComment = function() {
21100 var startLoc = this.options.onComment && this.curPosition();
21101 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
21102 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
21103 this.pos = end + 2;
21104 if (this.options.locations) {
21105 for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
21106 ++this.curLine;
21107 pos = this.lineStart = nextBreak;
21108 }
21109 }
21110 if (this.options.onComment)
21111 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
21112 startLoc, this.curPosition()); }
21113};
21114
21115pp.skipLineComment = function(startSkip) {
21116 var start = this.pos;
21117 var startLoc = this.options.onComment && this.curPosition();
21118 var ch = this.input.charCodeAt(this.pos += startSkip);
21119 while (this.pos < this.input.length && !isNewLine(ch)) {
21120 ch = this.input.charCodeAt(++this.pos);
21121 }
21122 if (this.options.onComment)
21123 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
21124 startLoc, this.curPosition()); }
21125};
21126
21127// Called at the start of the parse and after every token. Skips
21128// whitespace and comments, and.
21129
21130pp.skipSpace = function() {
21131 loop: while (this.pos < this.input.length) {
21132 var ch = this.input.charCodeAt(this.pos);
21133 switch (ch) {
21134 case 32: case 160: // ' '
21135 ++this.pos;
21136 break
21137 case 13:
21138 if (this.input.charCodeAt(this.pos + 1) === 10) {
21139 ++this.pos;
21140 }
21141 case 10: case 8232: case 8233:
21142 ++this.pos;
21143 if (this.options.locations) {
21144 ++this.curLine;
21145 this.lineStart = this.pos;
21146 }
21147 break
21148 case 47: // '/'
21149 switch (this.input.charCodeAt(this.pos + 1)) {
21150 case 42: // '*'
21151 this.skipBlockComment();
21152 break
21153 case 47:
21154 this.skipLineComment(2);
21155 break
21156 default:
21157 break loop
21158 }
21159 break
21160 default:
21161 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
21162 ++this.pos;
21163 } else {
21164 break loop
21165 }
21166 }
21167 }
21168};
21169
21170// Called at the end of every token. Sets `end`, `val`, and
21171// maintains `context` and `exprAllowed`, and skips the space after
21172// the token, so that the next one's `start` will point at the
21173// right position.
21174
21175pp.finishToken = function(type, val) {
21176 this.end = this.pos;
21177 if (this.options.locations) { this.endLoc = this.curPosition(); }
21178 var prevType = this.type;
21179 this.type = type;
21180 this.value = val;
21181
21182 this.updateContext(prevType);
21183};
21184
21185// ### Token reading
21186
21187// This is the function that is called to fetch the next token. It
21188// is somewhat obscure, because it works in character codes rather
21189// than characters, and because operator parsing has been inlined
21190// into it.
21191//
21192// All in the name of speed.
21193//
21194pp.readToken_dot = function() {
21195 var next = this.input.charCodeAt(this.pos + 1);
21196 if (next >= 48 && next <= 57) { return this.readNumber(true) }
21197 var next2 = this.input.charCodeAt(this.pos + 2);
21198 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
21199 this.pos += 3;
21200 return this.finishToken(types$1.ellipsis)
21201 } else {
21202 ++this.pos;
21203 return this.finishToken(types$1.dot)
21204 }
21205};
21206
21207pp.readToken_slash = function() { // '/'
21208 var next = this.input.charCodeAt(this.pos + 1);
21209 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
21210 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21211 return this.finishOp(types$1.slash, 1)
21212};
21213
21214pp.readToken_mult_modulo_exp = function(code) { // '%*'
21215 var next = this.input.charCodeAt(this.pos + 1);
21216 var size = 1;
21217 var tokentype = code === 42 ? types$1.star : types$1.modulo;
21218
21219 // exponentiation operator ** and **=
21220 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
21221 ++size;
21222 tokentype = types$1.starstar;
21223 next = this.input.charCodeAt(this.pos + 2);
21224 }
21225
21226 if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
21227 return this.finishOp(tokentype, size)
21228};
21229
21230pp.readToken_pipe_amp = function(code) { // '|&'
21231 var next = this.input.charCodeAt(this.pos + 1);
21232 if (next === code) {
21233 if (this.options.ecmaVersion >= 12) {
21234 var next2 = this.input.charCodeAt(this.pos + 2);
21235 if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
21236 }
21237 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
21238 }
21239 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21240 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
21241};
21242
21243pp.readToken_caret = function() { // '^'
21244 var next = this.input.charCodeAt(this.pos + 1);
21245 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21246 return this.finishOp(types$1.bitwiseXOR, 1)
21247};
21248
21249pp.readToken_plus_min = function(code) { // '+-'
21250 var next = this.input.charCodeAt(this.pos + 1);
21251 if (next === code) {
21252 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
21253 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
21254 // A `-->` line comment
21255 this.skipLineComment(3);
21256 this.skipSpace();
21257 return this.nextToken()
21258 }
21259 return this.finishOp(types$1.incDec, 2)
21260 }
21261 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21262 return this.finishOp(types$1.plusMin, 1)
21263};
21264
21265pp.readToken_lt_gt = function(code) { // '<>'
21266 var next = this.input.charCodeAt(this.pos + 1);
21267 var size = 1;
21268 if (next === code) {
21269 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
21270 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
21271 return this.finishOp(types$1.bitShift, size)
21272 }
21273 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
21274 this.input.charCodeAt(this.pos + 3) === 45) {
21275 // `<!--`, an XML-style comment that should be interpreted as a line comment
21276 this.skipLineComment(4);
21277 this.skipSpace();
21278 return this.nextToken()
21279 }
21280 if (next === 61) { size = 2; }
21281 return this.finishOp(types$1.relational, size)
21282};
21283
21284pp.readToken_eq_excl = function(code) { // '=!'
21285 var next = this.input.charCodeAt(this.pos + 1);
21286 if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
21287 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
21288 this.pos += 2;
21289 return this.finishToken(types$1.arrow)
21290 }
21291 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
21292};
21293
21294pp.readToken_question = function() { // '?'
21295 var ecmaVersion = this.options.ecmaVersion;
21296 if (ecmaVersion >= 11) {
21297 var next = this.input.charCodeAt(this.pos + 1);
21298 if (next === 46) {
21299 var next2 = this.input.charCodeAt(this.pos + 2);
21300 if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
21301 }
21302 if (next === 63) {
21303 if (ecmaVersion >= 12) {
21304 var next2$1 = this.input.charCodeAt(this.pos + 2);
21305 if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
21306 }
21307 return this.finishOp(types$1.coalesce, 2)
21308 }
21309 }
21310 return this.finishOp(types$1.question, 1)
21311};
21312
21313pp.readToken_numberSign = function() { // '#'
21314 var ecmaVersion = this.options.ecmaVersion;
21315 var code = 35; // '#'
21316 if (ecmaVersion >= 13) {
21317 ++this.pos;
21318 code = this.fullCharCodeAtPos();
21319 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
21320 return this.finishToken(types$1.privateId, this.readWord1())
21321 }
21322 }
21323
21324 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21325};
21326
21327pp.getTokenFromCode = function(code) {
21328 switch (code) {
21329 // The interpretation of a dot depends on whether it is followed
21330 // by a digit or another two dots.
21331 case 46: // '.'
21332 return this.readToken_dot()
21333
21334 // Punctuation tokens.
21335 case 40: ++this.pos; return this.finishToken(types$1.parenL)
21336 case 41: ++this.pos; return this.finishToken(types$1.parenR)
21337 case 59: ++this.pos; return this.finishToken(types$1.semi)
21338 case 44: ++this.pos; return this.finishToken(types$1.comma)
21339 case 91: ++this.pos; return this.finishToken(types$1.bracketL)
21340 case 93: ++this.pos; return this.finishToken(types$1.bracketR)
21341 case 123: ++this.pos; return this.finishToken(types$1.braceL)
21342 case 125: ++this.pos; return this.finishToken(types$1.braceR)
21343 case 58: ++this.pos; return this.finishToken(types$1.colon)
21344
21345 case 96: // '`'
21346 if (this.options.ecmaVersion < 6) { break }
21347 ++this.pos;
21348 return this.finishToken(types$1.backQuote)
21349
21350 case 48: // '0'
21351 var next = this.input.charCodeAt(this.pos + 1);
21352 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
21353 if (this.options.ecmaVersion >= 6) {
21354 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
21355 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
21356 }
21357
21358 // Anything else beginning with a digit is an integer, octal
21359 // number, or float.
21360 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
21361 return this.readNumber(false)
21362
21363 // Quotes produce strings.
21364 case 34: case 39: // '"', "'"
21365 return this.readString(code)
21366
21367 // Operators are parsed inline in tiny state machines. '=' (61) is
21368 // often referred to. `finishOp` simply skips the amount of
21369 // characters it is given as second argument, and returns a token
21370 // of the type given by its first argument.
21371 case 47: // '/'
21372 return this.readToken_slash()
21373
21374 case 37: case 42: // '%*'
21375 return this.readToken_mult_modulo_exp(code)
21376
21377 case 124: case 38: // '|&'
21378 return this.readToken_pipe_amp(code)
21379
21380 case 94: // '^'
21381 return this.readToken_caret()
21382
21383 case 43: case 45: // '+-'
21384 return this.readToken_plus_min(code)
21385
21386 case 60: case 62: // '<>'
21387 return this.readToken_lt_gt(code)
21388
21389 case 61: case 33: // '=!'
21390 return this.readToken_eq_excl(code)
21391
21392 case 63: // '?'
21393 return this.readToken_question()
21394
21395 case 126: // '~'
21396 return this.finishOp(types$1.prefix, 1)
21397
21398 case 35: // '#'
21399 return this.readToken_numberSign()
21400 }
21401
21402 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21403};
21404
21405pp.finishOp = function(type, size) {
21406 var str = this.input.slice(this.pos, this.pos + size);
21407 this.pos += size;
21408 return this.finishToken(type, str)
21409};
21410
21411pp.readRegexp = function() {
21412 var escaped, inClass, start = this.pos;
21413 for (;;) {
21414 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
21415 var ch = this.input.charAt(this.pos);
21416 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
21417 if (!escaped) {
21418 if (ch === "[") { inClass = true; }
21419 else if (ch === "]" && inClass) { inClass = false; }
21420 else if (ch === "/" && !inClass) { break }
21421 escaped = ch === "\\";
21422 } else { escaped = false; }
21423 ++this.pos;
21424 }
21425 var pattern = this.input.slice(start, this.pos);
21426 ++this.pos;
21427 var flagsStart = this.pos;
21428 var flags = this.readWord1();
21429 if (this.containsEsc) { this.unexpected(flagsStart); }
21430
21431 // Validate pattern
21432 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
21433 state.reset(start, pattern, flags);
21434 this.validateRegExpFlags(state);
21435 this.validateRegExpPattern(state);
21436
21437 // Create Literal#value property value.
21438 var value = null;
21439 try {
21440 value = new RegExp(pattern, flags);
21441 } catch (e) {
21442 // ESTree requires null if it failed to instantiate RegExp object.
21443 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
21444 }
21445
21446 return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
21447};
21448
21449// Read an integer in the given radix. Return null if zero digits
21450// were read, the integer value otherwise. When `len` is given, this
21451// will return `null` unless the integer has exactly `len` digits.
21452
21453pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
21454 // `len` is used for character escape sequences. In that case, disallow separators.
21455 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
21456
21457 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
21458 // and isn't fraction part nor exponent part. In that case, if the first digit
21459 // is zero then disallow separators.
21460 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
21461
21462 var start = this.pos, total = 0, lastCode = 0;
21463 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
21464 var code = this.input.charCodeAt(this.pos), val = (void 0);
21465
21466 if (allowSeparators && code === 95) {
21467 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
21468 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
21469 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
21470 lastCode = code;
21471 continue
21472 }
21473
21474 if (code >= 97) { val = code - 97 + 10; } // a
21475 else if (code >= 65) { val = code - 65 + 10; } // A
21476 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
21477 else { val = Infinity; }
21478 if (val >= radix) { break }
21479 lastCode = code;
21480 total = total * radix + val;
21481 }
21482
21483 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
21484 if (this.pos === start || len != null && this.pos - start !== len) { return null }
21485
21486 return total
21487};
21488
21489function stringToNumber(str, isLegacyOctalNumericLiteral) {
21490 if (isLegacyOctalNumericLiteral) {
21491 return parseInt(str, 8)
21492 }
21493
21494 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
21495 return parseFloat(str.replace(/_/g, ""))
21496}
21497
21498function stringToBigInt(str) {
21499 if (typeof BigInt !== "function") {
21500 return null
21501 }
21502
21503 // `BigInt(value)` throws syntax error if the string contains numeric separators.
21504 return BigInt(str.replace(/_/g, ""))
21505}
21506
21507pp.readRadixNumber = function(radix) {
21508 var start = this.pos;
21509 this.pos += 2; // 0x
21510 var val = this.readInt(radix);
21511 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
21512 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
21513 val = stringToBigInt(this.input.slice(start, this.pos));
21514 ++this.pos;
21515 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21516 return this.finishToken(types$1.num, val)
21517};
21518
21519// Read an integer, octal integer, or floating-point number.
21520
21521pp.readNumber = function(startsWithDot) {
21522 var start = this.pos;
21523 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
21524 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
21525 if (octal && this.strict) { this.raise(start, "Invalid number"); }
21526 var next = this.input.charCodeAt(this.pos);
21527 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
21528 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
21529 ++this.pos;
21530 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21531 return this.finishToken(types$1.num, val$1)
21532 }
21533 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
21534 if (next === 46 && !octal) { // '.'
21535 ++this.pos;
21536 this.readInt(10);
21537 next = this.input.charCodeAt(this.pos);
21538 }
21539 if ((next === 69 || next === 101) && !octal) { // 'eE'
21540 next = this.input.charCodeAt(++this.pos);
21541 if (next === 43 || next === 45) { ++this.pos; } // '+-'
21542 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
21543 }
21544 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21545
21546 var val = stringToNumber(this.input.slice(start, this.pos), octal);
21547 return this.finishToken(types$1.num, val)
21548};
21549
21550// Read a string value, interpreting backslash-escapes.
21551
21552pp.readCodePoint = function() {
21553 var ch = this.input.charCodeAt(this.pos), code;
21554
21555 if (ch === 123) { // '{'
21556 if (this.options.ecmaVersion < 6) { this.unexpected(); }
21557 var codePos = ++this.pos;
21558 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
21559 ++this.pos;
21560 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
21561 } else {
21562 code = this.readHexChar(4);
21563 }
21564 return code
21565};
21566
21567pp.readString = function(quote) {
21568 var out = "", chunkStart = ++this.pos;
21569 for (;;) {
21570 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
21571 var ch = this.input.charCodeAt(this.pos);
21572 if (ch === quote) { break }
21573 if (ch === 92) { // '\'
21574 out += this.input.slice(chunkStart, this.pos);
21575 out += this.readEscapedChar(false);
21576 chunkStart = this.pos;
21577 } else if (ch === 0x2028 || ch === 0x2029) {
21578 if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
21579 ++this.pos;
21580 if (this.options.locations) {
21581 this.curLine++;
21582 this.lineStart = this.pos;
21583 }
21584 } else {
21585 if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
21586 ++this.pos;
21587 }
21588 }
21589 out += this.input.slice(chunkStart, this.pos++);
21590 return this.finishToken(types$1.string, out)
21591};
21592
21593// Reads template string tokens.
21594
21595var INVALID_TEMPLATE_ESCAPE_ERROR = {};
21596
21597pp.tryReadTemplateToken = function() {
21598 this.inTemplateElement = true;
21599 try {
21600 this.readTmplToken();
21601 } catch (err) {
21602 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
21603 this.readInvalidTemplateToken();
21604 } else {
21605 throw err
21606 }
21607 }
21608
21609 this.inTemplateElement = false;
21610};
21611
21612pp.invalidStringToken = function(position, message) {
21613 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
21614 throw INVALID_TEMPLATE_ESCAPE_ERROR
21615 } else {
21616 this.raise(position, message);
21617 }
21618};
21619
21620pp.readTmplToken = function() {
21621 var out = "", chunkStart = this.pos;
21622 for (;;) {
21623 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
21624 var ch = this.input.charCodeAt(this.pos);
21625 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
21626 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
21627 if (ch === 36) {
21628 this.pos += 2;
21629 return this.finishToken(types$1.dollarBraceL)
21630 } else {
21631 ++this.pos;
21632 return this.finishToken(types$1.backQuote)
21633 }
21634 }
21635 out += this.input.slice(chunkStart, this.pos);
21636 return this.finishToken(types$1.template, out)
21637 }
21638 if (ch === 92) { // '\'
21639 out += this.input.slice(chunkStart, this.pos);
21640 out += this.readEscapedChar(true);
21641 chunkStart = this.pos;
21642 } else if (isNewLine(ch)) {
21643 out += this.input.slice(chunkStart, this.pos);
21644 ++this.pos;
21645 switch (ch) {
21646 case 13:
21647 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
21648 case 10:
21649 out += "\n";
21650 break
21651 default:
21652 out += String.fromCharCode(ch);
21653 break
21654 }
21655 if (this.options.locations) {
21656 ++this.curLine;
21657 this.lineStart = this.pos;
21658 }
21659 chunkStart = this.pos;
21660 } else {
21661 ++this.pos;
21662 }
21663 }
21664};
21665
21666// Reads a template token to search for the end, without validating any escape sequences
21667pp.readInvalidTemplateToken = function() {
21668 for (; this.pos < this.input.length; this.pos++) {
21669 switch (this.input[this.pos]) {
21670 case "\\":
21671 ++this.pos;
21672 break
21673
21674 case "$":
21675 if (this.input[this.pos + 1] !== "{") {
21676 break
21677 }
21678
21679 // falls through
21680 case "`":
21681 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
21682
21683 // no default
21684 }
21685 }
21686 this.raise(this.start, "Unterminated template");
21687};
21688
21689// Used to read escaped characters
21690
21691pp.readEscapedChar = function(inTemplate) {
21692 var ch = this.input.charCodeAt(++this.pos);
21693 ++this.pos;
21694 switch (ch) {
21695 case 110: return "\n" // 'n' -> '\n'
21696 case 114: return "\r" // 'r' -> '\r'
21697 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
21698 case 117: return codePointToString(this.readCodePoint()) // 'u'
21699 case 116: return "\t" // 't' -> '\t'
21700 case 98: return "\b" // 'b' -> '\b'
21701 case 118: return "\u000b" // 'v' -> '\u000b'
21702 case 102: return "\f" // 'f' -> '\f'
21703 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
21704 case 10: // ' \n'
21705 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
21706 return ""
21707 case 56:
21708 case 57:
21709 if (this.strict) {
21710 this.invalidStringToken(
21711 this.pos - 1,
21712 "Invalid escape sequence"
21713 );
21714 }
21715 if (inTemplate) {
21716 var codePos = this.pos - 1;
21717
21718 this.invalidStringToken(
21719 codePos,
21720 "Invalid escape sequence in template string"
21721 );
21722
21723 return null
21724 }
21725 default:
21726 if (ch >= 48 && ch <= 55) {
21727 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
21728 var octal = parseInt(octalStr, 8);
21729 if (octal > 255) {
21730 octalStr = octalStr.slice(0, -1);
21731 octal = parseInt(octalStr, 8);
21732 }
21733 this.pos += octalStr.length - 1;
21734 ch = this.input.charCodeAt(this.pos);
21735 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
21736 this.invalidStringToken(
21737 this.pos - 1 - octalStr.length,
21738 inTemplate
21739 ? "Octal literal in template string"
21740 : "Octal literal in strict mode"
21741 );
21742 }
21743 return String.fromCharCode(octal)
21744 }
21745 if (isNewLine(ch)) {
21746 // Unicode new line characters after \ get removed from output in both
21747 // template literals and strings
21748 return ""
21749 }
21750 return String.fromCharCode(ch)
21751 }
21752};
21753
21754// Used to read character escape sequences ('\x', '\u', '\U').
21755
21756pp.readHexChar = function(len) {
21757 var codePos = this.pos;
21758 var n = this.readInt(16, len);
21759 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
21760 return n
21761};
21762
21763// Read an identifier, and return it as a string. Sets `this.containsEsc`
21764// to whether the word contained a '\u' escape.
21765//
21766// Incrementally adds only escaped chars, adding other chunks as-is
21767// as a micro-optimization.
21768
21769pp.readWord1 = function() {
21770 this.containsEsc = false;
21771 var word = "", first = true, chunkStart = this.pos;
21772 var astral = this.options.ecmaVersion >= 6;
21773 while (this.pos < this.input.length) {
21774 var ch = this.fullCharCodeAtPos();
21775 if (isIdentifierChar(ch, astral)) {
21776 this.pos += ch <= 0xffff ? 1 : 2;
21777 } else if (ch === 92) { // "\"
21778 this.containsEsc = true;
21779 word += this.input.slice(chunkStart, this.pos);
21780 var escStart = this.pos;
21781 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
21782 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
21783 ++this.pos;
21784 var esc = this.readCodePoint();
21785 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
21786 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
21787 word += codePointToString(esc);
21788 chunkStart = this.pos;
21789 } else {
21790 break
21791 }
21792 first = false;
21793 }
21794 return word + this.input.slice(chunkStart, this.pos)
21795};
21796
21797// Read an identifier or keyword token. Will check for reserved
21798// words when necessary.
21799
21800pp.readWord = function() {
21801 var word = this.readWord1();
21802 var type = types$1.name;
21803 if (this.keywords.test(word)) {
21804 type = keywords[word];
21805 }
21806 return this.finishToken(type, word)
21807};
21808
21809// Acorn is a tiny, fast JavaScript parser written in JavaScript.
21810
21811var version = "8.7.1";
21812
21813Parser.acorn = {
21814 Parser: Parser,
21815 version: version,
21816 defaultOptions: defaultOptions,
21817 Position: Position,
21818 SourceLocation: SourceLocation,
21819 getLineInfo: getLineInfo,
21820 Node: Node,
21821 TokenType: TokenType,
21822 tokTypes: types$1,
21823 keywordTypes: keywords,
21824 TokContext: TokContext,
21825 tokContexts: types,
21826 isIdentifierChar: isIdentifierChar,
21827 isIdentifierStart: isIdentifierStart,
21828 Token: Token,
21829 isNewLine: isNewLine,
21830 lineBreak: lineBreak,
21831 lineBreakG: lineBreakG,
21832 nonASCIIwhitespace: nonASCIIwhitespace
21833};
21834
21835class Queue {
21836 constructor(maxParallel) {
21837 this.maxParallel = maxParallel;
21838 this.queue = [];
21839 this.workerCount = 0;
21840 }
21841 run(task) {
21842 return new Promise((resolve, reject) => {
21843 this.queue.push({ reject, resolve, task });
21844 this.work();
21845 });
21846 }
21847 async work() {
21848 if (this.workerCount >= this.maxParallel)
21849 return;
21850 this.workerCount++;
21851 let entry;
21852 while ((entry = this.queue.shift())) {
21853 const { reject, resolve, task } = entry;
21854 try {
21855 const result = await task();
21856 resolve(result);
21857 }
21858 catch (err) {
21859 reject(err);
21860 }
21861 }
21862 this.workerCount--;
21863 }
21864}
21865
21866function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21867 let skipped = null;
21868 let replaceContext = null;
21869 if (skip) {
21870 skipped = new Set();
21871 for (const skippedCall of skip) {
21872 if (source === skippedCall.source && importer === skippedCall.importer) {
21873 skipped.add(skippedCall.plugin);
21874 }
21875 }
21876 replaceContext = (pluginContext, plugin) => ({
21877 ...pluginContext,
21878 resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
21879 return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
21880 }
21881 });
21882 }
21883 return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
21884}
21885
21886async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21887 const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
21888 if (pluginResult != null)
21889 return pluginResult;
21890 // external modules (non-entry modules that start with neither '.' or '/')
21891 // are skipped at this stage.
21892 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
21893 return null;
21894 // `resolve` processes paths from right to left, prepending them until an
21895 // absolute path is created. Absolute importees therefore shortcircuit the
21896 // resolve call and require no special handing on our part.
21897 // See https://nodejs.org/api/path.html#path_path_resolve_paths
21898 return addJsExtensionIfNecessary(importer ? require$$0.resolve(require$$0.dirname(importer), source) : require$$0.resolve(source), preserveSymlinks);
21899}
21900async function addJsExtensionIfNecessary(file, preserveSymlinks) {
21901 var _a, _b;
21902 return ((_b = (_a = (await findFile(file, preserveSymlinks))) !== null && _a !== void 0 ? _a : (await findFile(file + '.mjs', preserveSymlinks))) !== null && _b !== void 0 ? _b : (await findFile(file + '.js', preserveSymlinks)));
21903}
21904async function findFile(file, preserveSymlinks) {
21905 try {
21906 const stats = await require$$0$1.promises.lstat(file);
21907 if (!preserveSymlinks && stats.isSymbolicLink())
21908 return await findFile(await require$$0$1.promises.realpath(file), preserveSymlinks);
21909 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
21910 // check case
21911 const name = require$$0.basename(file);
21912 const files = await require$$0$1.promises.readdir(require$$0.dirname(file));
21913 if (files.includes(name))
21914 return file;
21915 }
21916 }
21917 catch (_a) {
21918 // suppress
21919 }
21920}
21921
21922const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
21923const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
21924function throwPluginError(err, plugin, { hook, id } = {}) {
21925 if (typeof err === 'string')
21926 err = { message: err };
21927 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
21928 err.pluginCode = err.code;
21929 }
21930 err.code = Errors.PLUGIN_ERROR;
21931 err.plugin = plugin;
21932 if (hook) {
21933 err.hook = hook;
21934 }
21935 if (id) {
21936 err.id = id;
21937 }
21938 return error(err);
21939}
21940const deprecatedHooks = [
21941 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
21942];
21943function warnDeprecatedHooks(plugins, options) {
21944 for (const { active, deprecated, replacement } of deprecatedHooks) {
21945 for (const plugin of plugins) {
21946 if (deprecated in plugin) {
21947 warnDeprecation({
21948 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
21949 plugin: plugin.name
21950 }, active, options);
21951 }
21952 }
21953 }
21954}
21955
21956function createPluginCache(cache) {
21957 return {
21958 delete(id) {
21959 return delete cache[id];
21960 },
21961 get(id) {
21962 const item = cache[id];
21963 if (!item)
21964 return undefined;
21965 item[0] = 0;
21966 return item[1];
21967 },
21968 has(id) {
21969 const item = cache[id];
21970 if (!item)
21971 return false;
21972 item[0] = 0;
21973 return true;
21974 },
21975 set(id, value) {
21976 cache[id] = [0, value];
21977 }
21978 };
21979}
21980function getTrackedPluginCache(pluginCache, onUse) {
21981 return {
21982 delete(id) {
21983 onUse();
21984 return pluginCache.delete(id);
21985 },
21986 get(id) {
21987 onUse();
21988 return pluginCache.get(id);
21989 },
21990 has(id) {
21991 onUse();
21992 return pluginCache.has(id);
21993 },
21994 set(id, value) {
21995 onUse();
21996 return pluginCache.set(id, value);
21997 }
21998 };
21999}
22000const NO_CACHE = {
22001 delete() {
22002 return false;
22003 },
22004 get() {
22005 return undefined;
22006 },
22007 has() {
22008 return false;
22009 },
22010 set() { }
22011};
22012function uncacheablePluginError(pluginName) {
22013 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
22014 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
22015 return error({
22016 code: 'ANONYMOUS_PLUGIN_CACHE',
22017 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
22018 });
22019 }
22020 return error({
22021 code: 'DUPLICATE_PLUGIN_NAME',
22022 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).`
22023 });
22024}
22025function getCacheForUncacheablePlugin(pluginName) {
22026 return {
22027 delete() {
22028 return uncacheablePluginError(pluginName);
22029 },
22030 get() {
22031 return uncacheablePluginError(pluginName);
22032 },
22033 has() {
22034 return uncacheablePluginError(pluginName);
22035 },
22036 set() {
22037 return uncacheablePluginError(pluginName);
22038 }
22039 };
22040}
22041
22042async function transform(source, module, pluginDriver, warn) {
22043 const id = module.id;
22044 const sourcemapChain = [];
22045 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
22046 const originalCode = source.code;
22047 let ast = source.ast;
22048 const transformDependencies = [];
22049 const emittedFiles = [];
22050 let customTransformCache = false;
22051 const useCustomTransformCache = () => (customTransformCache = true);
22052 let pluginName = '';
22053 const curSource = source.code;
22054 function transformReducer(previousCode, result, plugin) {
22055 let code;
22056 let map;
22057 if (typeof result === 'string') {
22058 code = result;
22059 }
22060 else if (result && typeof result === 'object') {
22061 module.updateOptions(result);
22062 if (result.code == null) {
22063 if (result.map || result.ast) {
22064 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
22065 }
22066 return previousCode;
22067 }
22068 ({ code, map, ast } = result);
22069 }
22070 else {
22071 return previousCode;
22072 }
22073 // strict null check allows 'null' maps to not be pushed to the chain,
22074 // while 'undefined' gets the missing map warning
22075 if (map !== null) {
22076 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
22077 missing: true,
22078 plugin: plugin.name
22079 });
22080 }
22081 return code;
22082 }
22083 let code;
22084 try {
22085 code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
22086 pluginName = plugin.name;
22087 return {
22088 ...pluginContext,
22089 addWatchFile(id) {
22090 transformDependencies.push(id);
22091 pluginContext.addWatchFile(id);
22092 },
22093 cache: customTransformCache
22094 ? pluginContext.cache
22095 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
22096 emitAsset(name, source) {
22097 emittedFiles.push({ name, source, type: 'asset' });
22098 return pluginContext.emitAsset(name, source);
22099 },
22100 emitChunk(id, options) {
22101 emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
22102 return pluginContext.emitChunk(id, options);
22103 },
22104 emitFile(emittedFile) {
22105 emittedFiles.push(emittedFile);
22106 return pluginDriver.emitFile(emittedFile);
22107 },
22108 error(err, pos) {
22109 if (typeof err === 'string')
22110 err = { message: err };
22111 if (pos)
22112 augmentCodeLocation(err, pos, curSource, id);
22113 err.id = id;
22114 err.hook = 'transform';
22115 return pluginContext.error(err);
22116 },
22117 getCombinedSourcemap() {
22118 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
22119 if (!combinedMap) {
22120 const magicString = new MagicString(originalCode);
22121 return magicString.generateMap({ hires: true, includeContent: true, source: id });
22122 }
22123 if (originalSourcemap !== combinedMap) {
22124 originalSourcemap = combinedMap;
22125 sourcemapChain.length = 0;
22126 }
22127 return new SourceMap({
22128 ...combinedMap,
22129 file: null,
22130 sourcesContent: combinedMap.sourcesContent
22131 });
22132 },
22133 setAssetSource() {
22134 return this.error({
22135 code: 'INVALID_SETASSETSOURCE',
22136 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
22137 });
22138 },
22139 warn(warning, pos) {
22140 if (typeof warning === 'string')
22141 warning = { message: warning };
22142 if (pos)
22143 augmentCodeLocation(warning, pos, curSource, id);
22144 warning.id = id;
22145 warning.hook = 'transform';
22146 pluginContext.warn(warning);
22147 }
22148 };
22149 });
22150 }
22151 catch (err) {
22152 throwPluginError(err, pluginName, { hook: 'transform', id });
22153 }
22154 if (!customTransformCache) {
22155 // files emitted by a transform hook need to be emitted again if the hook is skipped
22156 if (emittedFiles.length)
22157 module.transformFiles = emittedFiles;
22158 }
22159 return {
22160 ast,
22161 code,
22162 customTransformCache,
22163 originalCode,
22164 originalSourcemap,
22165 sourcemapChain,
22166 transformDependencies
22167 };
22168}
22169
22170const RESOLVE_DEPENDENCIES = 'resolveDependencies';
22171class ModuleLoader {
22172 constructor(graph, modulesById, options, pluginDriver) {
22173 this.graph = graph;
22174 this.modulesById = modulesById;
22175 this.options = options;
22176 this.pluginDriver = pluginDriver;
22177 this.implicitEntryModules = new Set();
22178 this.indexedEntryModules = [];
22179 this.latestLoadModulesPromise = Promise.resolve();
22180 this.moduleLoadPromises = new Map();
22181 this.modulesWithLoadedDependencies = new Set();
22182 this.nextChunkNamePriority = 0;
22183 this.nextEntryModuleIndex = 0;
22184 this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
22185 return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
22186 ? false
22187 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
22188 };
22189 this.hasModuleSideEffects = options.treeshake
22190 ? options.treeshake.moduleSideEffects
22191 : () => true;
22192 this.readQueue = new Queue(options.maxParallelFileReads);
22193 }
22194 async addAdditionalModules(unresolvedModules) {
22195 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
22196 await this.awaitLoadModulesPromise();
22197 return result;
22198 }
22199 async addEntryModules(unresolvedEntryModules, isUserDefined) {
22200 const firstEntryModuleIndex = this.nextEntryModuleIndex;
22201 this.nextEntryModuleIndex += unresolvedEntryModules.length;
22202 const firstChunkNamePriority = this.nextChunkNamePriority;
22203 this.nextChunkNamePriority += unresolvedEntryModules.length;
22204 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
22205 for (let index = 0; index < entryModules.length; index++) {
22206 const entryModule = entryModules[index];
22207 entryModule.isUserDefinedEntryPoint =
22208 entryModule.isUserDefinedEntryPoint || isUserDefined;
22209 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
22210 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
22211 if (!existingIndexedModule) {
22212 this.indexedEntryModules.push({
22213 index: firstEntryModuleIndex + index,
22214 module: entryModule
22215 });
22216 }
22217 else {
22218 existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
22219 }
22220 }
22221 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
22222 return entryModules;
22223 }));
22224 await this.awaitLoadModulesPromise();
22225 return {
22226 entryModules: this.indexedEntryModules.map(({ module }) => module),
22227 implicitEntryModules: [...this.implicitEntryModules],
22228 newEntryModules
22229 };
22230 }
22231 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
22232 const unresolvedModule = {
22233 fileName: fileName || null,
22234 id,
22235 importer,
22236 name: name || null
22237 };
22238 const module = implicitlyLoadedAfterOneOf
22239 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
22240 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
22241 if (preserveSignature != null) {
22242 module.preserveSignature = preserveSignature;
22243 }
22244 return module;
22245 }
22246 async preloadModule(resolvedId) {
22247 const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
22248 return module.info;
22249 }
22250 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
22251 const chunkNamePriority = this.nextChunkNamePriority++;
22252 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
22253 addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
22254 if (!entryModule.info.isEntry) {
22255 this.implicitEntryModules.add(entryModule);
22256 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
22257 for (const module of implicitlyLoadedAfterModules) {
22258 entryModule.implicitlyLoadedAfter.add(module);
22259 }
22260 for (const dependant of entryModule.implicitlyLoadedAfter) {
22261 dependant.implicitlyLoadedBefore.add(entryModule);
22262 }
22263 }
22264 return entryModule;
22265 }));
22266 }
22267 async addModuleSource(id, importer, module) {
22268 timeStart('load modules', 3);
22269 let source;
22270 try {
22271 source = await this.readQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await require$$0$1.promises.readFile(id, 'utf8')); });
22272 }
22273 catch (err) {
22274 timeEnd('load modules', 3);
22275 let msg = `Could not load ${id}`;
22276 if (importer)
22277 msg += ` (imported by ${relativeId(importer)})`;
22278 msg += `: ${err.message}`;
22279 err.message = msg;
22280 throw err;
22281 }
22282 timeEnd('load modules', 3);
22283 const sourceDescription = typeof source === 'string'
22284 ? { code: source }
22285 : source != null && typeof source === 'object' && typeof source.code === 'string'
22286 ? source
22287 : error(errBadLoader(id));
22288 const cachedModule = this.graph.cachedModules.get(id);
22289 if (cachedModule &&
22290 !cachedModule.customTransformCache &&
22291 cachedModule.originalCode === sourceDescription.code &&
22292 !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
22293 {
22294 ast: cachedModule.ast,
22295 code: cachedModule.code,
22296 id: cachedModule.id,
22297 meta: cachedModule.meta,
22298 moduleSideEffects: cachedModule.moduleSideEffects,
22299 resolvedSources: cachedModule.resolvedIds,
22300 syntheticNamedExports: cachedModule.syntheticNamedExports
22301 }
22302 ]))) {
22303 if (cachedModule.transformFiles) {
22304 for (const emittedFile of cachedModule.transformFiles)
22305 this.pluginDriver.emitFile(emittedFile);
22306 }
22307 module.setSource(cachedModule);
22308 }
22309 else {
22310 module.updateOptions(sourceDescription);
22311 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
22312 }
22313 }
22314 async awaitLoadModulesPromise() {
22315 let startingPromise;
22316 do {
22317 startingPromise = this.latestLoadModulesPromise;
22318 await startingPromise;
22319 } while (startingPromise !== this.latestLoadModulesPromise);
22320 }
22321 extendLoadModulesPromise(loadNewModulesPromise) {
22322 this.latestLoadModulesPromise = Promise.all([
22323 loadNewModulesPromise,
22324 this.latestLoadModulesPromise
22325 ]);
22326 this.latestLoadModulesPromise.catch(() => {
22327 /* Avoid unhandled Promise rejections */
22328 });
22329 return loadNewModulesPromise;
22330 }
22331 async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
22332 const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
22333 if (resolvedId === null)
22334 return null;
22335 if (typeof resolvedId === 'string') {
22336 dynamicImport.resolution = resolvedId;
22337 return null;
22338 }
22339 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
22340 })));
22341 for (const dependency of dependencies) {
22342 if (dependency) {
22343 module.dynamicDependencies.add(dependency);
22344 dependency.dynamicImporters.push(module.id);
22345 }
22346 }
22347 }
22348 // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
22349 // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
22350 // Otherwise it returns immediately.
22351 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
22352 const existingModule = this.modulesById.get(id);
22353 if (existingModule instanceof Module) {
22354 await this.handleExistingModule(existingModule, isEntry, isPreload);
22355 return existingModule;
22356 }
22357 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
22358 this.modulesById.set(id, module);
22359 this.graph.watchFiles[id] = true;
22360 const loadPromise = this.addModuleSource(id, importer, module).then(() => [
22361 this.getResolveStaticDependencyPromises(module),
22362 this.getResolveDynamicImportPromises(module),
22363 loadAndResolveDependenciesPromise
22364 ]);
22365 const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
22366 loadAndResolveDependenciesPromise.catch(() => {
22367 /* avoid unhandled promise rejections */
22368 });
22369 this.moduleLoadPromises.set(module, loadPromise);
22370 const resolveDependencyPromises = await loadPromise;
22371 if (!isPreload) {
22372 await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
22373 }
22374 else if (isPreload === RESOLVE_DEPENDENCIES) {
22375 await loadAndResolveDependenciesPromise;
22376 }
22377 return module;
22378 }
22379 async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
22380 if (this.modulesWithLoadedDependencies.has(module)) {
22381 return;
22382 }
22383 this.modulesWithLoadedDependencies.add(module);
22384 await Promise.all([
22385 this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
22386 this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
22387 ]);
22388 module.linkImports();
22389 // To handle errors when resolving dependencies or in moduleParsed
22390 await loadAndResolveDependenciesPromise;
22391 }
22392 fetchResolvedDependency(source, importer, resolvedId) {
22393 if (resolvedId.external) {
22394 const { external, id, moduleSideEffects, meta } = resolvedId;
22395 if (!this.modulesById.has(id)) {
22396 this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
22397 }
22398 const externalModule = this.modulesById.get(id);
22399 if (!(externalModule instanceof ExternalModule)) {
22400 return error(errInternalIdCannotBeExternal(source, importer));
22401 }
22402 return Promise.resolve(externalModule);
22403 }
22404 return this.fetchModule(resolvedId, importer, false, false);
22405 }
22406 async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
22407 for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
22408 module.dependencies.add(dependency);
22409 dependency.importers.push(module.id);
22410 }
22411 if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
22412 for (const dependency of module.dependencies) {
22413 if (dependency instanceof Module) {
22414 dependency.importedFromNotTreeshaken = true;
22415 }
22416 }
22417 }
22418 }
22419 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
22420 const { makeAbsoluteExternalsRelative } = this.options;
22421 if (resolveIdResult) {
22422 if (typeof resolveIdResult === 'object') {
22423 const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
22424 return {
22425 ...resolveIdResult,
22426 external: external &&
22427 (external === 'relative' ||
22428 !isAbsolute(resolveIdResult.id) ||
22429 (external === true &&
22430 isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
22431 'absolute')
22432 };
22433 }
22434 const external = this.options.external(resolveIdResult, importer, true);
22435 return {
22436 external: external &&
22437 (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
22438 'absolute'),
22439 id: external && makeAbsoluteExternalsRelative
22440 ? normalizeRelativeExternalId(resolveIdResult, importer)
22441 : resolveIdResult
22442 };
22443 }
22444 const id = makeAbsoluteExternalsRelative
22445 ? normalizeRelativeExternalId(source, importer)
22446 : source;
22447 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
22448 return null;
22449 }
22450 return {
22451 external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
22452 id
22453 };
22454 }
22455 getResolveDynamicImportPromises(module) {
22456 return module.dynamicImports.map(async (dynamicImport) => {
22457 const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
22458 ? dynamicImport.argument
22459 : dynamicImport.argument.esTreeNode, module.id);
22460 if (resolvedId && typeof resolvedId === 'object') {
22461 dynamicImport.id = resolvedId.id;
22462 }
22463 return [dynamicImport, resolvedId];
22464 });
22465 }
22466 getResolveStaticDependencyPromises(module) {
22467 return Array.from(module.sources, async (source) => [
22468 source,
22469 (module.resolvedIds[source] =
22470 module.resolvedIds[source] ||
22471 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
22472 ]);
22473 }
22474 getResolvedIdWithDefaults(resolvedId) {
22475 var _a, _b;
22476 if (!resolvedId) {
22477 return null;
22478 }
22479 const external = resolvedId.external || false;
22480 return {
22481 external,
22482 id: resolvedId.id,
22483 meta: resolvedId.meta || {},
22484 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
22485 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
22486 };
22487 }
22488 async handleExistingModule(module, isEntry, isPreload) {
22489 const loadPromise = this.moduleLoadPromises.get(module);
22490 if (isPreload) {
22491 return isPreload === RESOLVE_DEPENDENCIES
22492 ? waitForDependencyResolution(loadPromise)
22493 : loadPromise;
22494 }
22495 if (isEntry) {
22496 module.info.isEntry = true;
22497 this.implicitEntryModules.delete(module);
22498 for (const dependant of module.implicitlyLoadedAfter) {
22499 dependant.implicitlyLoadedBefore.delete(module);
22500 }
22501 module.implicitlyLoadedAfter.clear();
22502 }
22503 return this.fetchModuleDependencies(module, ...(await loadPromise));
22504 }
22505 handleResolveId(resolvedId, source, importer) {
22506 if (resolvedId === null) {
22507 if (isRelative(source)) {
22508 return error(errUnresolvedImport(source, importer));
22509 }
22510 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
22511 return {
22512 external: true,
22513 id: source,
22514 meta: {},
22515 moduleSideEffects: this.hasModuleSideEffects(source, true),
22516 syntheticNamedExports: false
22517 };
22518 }
22519 else if (resolvedId.external && resolvedId.syntheticNamedExports) {
22520 this.options.onwarn(errExternalSyntheticExports(source, importer));
22521 }
22522 return resolvedId;
22523 }
22524 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
22525 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
22526 if (resolveIdResult == null) {
22527 return error(implicitlyLoadedBefore === null
22528 ? errUnresolvedEntry(unresolvedId)
22529 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
22530 }
22531 if (resolveIdResult === false ||
22532 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
22533 return error(implicitlyLoadedBefore === null
22534 ? errEntryCannotBeExternal(unresolvedId)
22535 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
22536 }
22537 return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
22538 ? resolveIdResult
22539 : { id: resolveIdResult }), undefined, isEntry, false);
22540 }
22541 async resolveDynamicImport(module, specifier, importer) {
22542 var _a;
22543 var _b;
22544 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
22545 specifier,
22546 importer
22547 ]);
22548 if (typeof specifier !== 'string') {
22549 if (typeof resolution === 'string') {
22550 return resolution;
22551 }
22552 if (!resolution) {
22553 return null;
22554 }
22555 return {
22556 external: false,
22557 moduleSideEffects: true,
22558 ...resolution
22559 };
22560 }
22561 if (resolution == null) {
22562 return ((_a = (_b = module.resolvedIds)[specifier]) !== null && _a !== void 0 ? _a : (_b[specifier] = this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false), specifier, module.id)));
22563 }
22564 return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
22565 }
22566}
22567function normalizeRelativeExternalId(source, importer) {
22568 return isRelative(source)
22569 ? importer
22570 ? require$$0.resolve(importer, '..', source)
22571 : require$$0.resolve(source)
22572 : source;
22573}
22574function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
22575 var _a;
22576 if (fileName !== null) {
22577 module.chunkFileNames.add(fileName);
22578 }
22579 else if (name !== null) {
22580 // Always keep chunkNames sorted by priority
22581 let namePosition = 0;
22582 while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
22583 namePosition++;
22584 module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
22585 }
22586}
22587function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
22588 return (makeAbsoluteExternalsRelative === true ||
22589 (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
22590 !isAbsolute(id));
22591}
22592async function waitForDependencyResolution(loadPromise) {
22593 const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
22594 return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
22595}
22596
22597class GlobalScope extends Scope$1 {
22598 constructor() {
22599 super();
22600 this.parent = null;
22601 this.variables.set('undefined', new UndefinedVariable());
22602 }
22603 findVariable(name) {
22604 let variable = this.variables.get(name);
22605 if (!variable) {
22606 variable = new GlobalVariable(name);
22607 this.variables.set(name, variable);
22608 }
22609 return variable;
22610 }
22611}
22612
22613function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
22614 let deprecationWarningShown = false;
22615 return ((...args) => {
22616 if (!deprecationWarningShown) {
22617 deprecationWarningShown = true;
22618 warnDeprecation({
22619 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
22620 plugin: pluginName
22621 }, activeDeprecation, options);
22622 }
22623 return handler(...args);
22624 });
22625}
22626function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
22627 let cacheable = true;
22628 if (typeof plugin.cacheKey !== 'string') {
22629 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
22630 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
22631 existingPluginNames.has(plugin.name)) {
22632 cacheable = false;
22633 }
22634 else {
22635 existingPluginNames.add(plugin.name);
22636 }
22637 }
22638 let cacheInstance;
22639 if (!pluginCache) {
22640 cacheInstance = NO_CACHE;
22641 }
22642 else if (cacheable) {
22643 const cacheKey = plugin.cacheKey || plugin.name;
22644 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
22645 }
22646 else {
22647 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
22648 }
22649 const context = {
22650 addWatchFile(id) {
22651 if (graph.phase >= BuildPhase.GENERATE) {
22652 return this.error(errInvalidRollupPhaseForAddWatchFile());
22653 }
22654 graph.watchFiles[id] = true;
22655 },
22656 cache: cacheInstance,
22657 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
22658 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
22659 emitFile: fileEmitter.emitFile.bind(fileEmitter),
22660 error(err) {
22661 return throwPluginError(err, plugin.name);
22662 },
22663 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
22664 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
22665 getFileName: fileEmitter.getFileName,
22666 getModuleIds: () => graph.modulesById.keys(),
22667 getModuleInfo: graph.getModuleInfo,
22668 getWatchFiles: () => Object.keys(graph.watchFiles),
22669 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
22670 load(resolvedId) {
22671 return graph.moduleLoader.preloadModule(resolvedId);
22672 },
22673 meta: {
22674 rollupVersion: version$1,
22675 watchMode: graph.watchMode
22676 },
22677 get moduleIds() {
22678 function* wrappedModuleIds() {
22679 // We are wrapping this in a generator to only show the message once we are actually iterating
22680 warnDeprecation({
22681 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
22682 plugin: plugin.name
22683 }, false, options);
22684 yield* moduleIds;
22685 }
22686 const moduleIds = graph.modulesById.keys();
22687 return wrappedModuleIds();
22688 },
22689 parse: graph.contextParse.bind(graph),
22690 resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
22691 return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
22692 },
22693 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
22694 .resolveId(source, importer, BLANK, undefined)
22695 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
22696 setAssetSource: fileEmitter.setAssetSource,
22697 warn(warning) {
22698 if (typeof warning === 'string')
22699 warning = { message: warning };
22700 if (warning.code)
22701 warning.pluginCode = warning.code;
22702 warning.code = 'PLUGIN_WARNING';
22703 warning.plugin = plugin.name;
22704 options.onwarn(warning);
22705 }
22706 };
22707 return context;
22708}
22709
22710const inputHookNames = {
22711 buildEnd: 1,
22712 buildStart: 1,
22713 closeBundle: 1,
22714 closeWatcher: 1,
22715 load: 1,
22716 moduleParsed: 1,
22717 options: 1,
22718 resolveDynamicImport: 1,
22719 resolveId: 1,
22720 shouldTransformCachedModule: 1,
22721 transform: 1,
22722 watchChange: 1
22723};
22724const inputHooks = Object.keys(inputHookNames);
22725function throwInvalidHookError(hookName, pluginName) {
22726 return error({
22727 code: 'INVALID_PLUGIN_HOOK',
22728 message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
22729 });
22730}
22731class PluginDriver {
22732 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
22733 this.graph = graph;
22734 this.options = options;
22735 this.unfulfilledActions = new Set();
22736 warnDeprecatedHooks(userPlugins, options);
22737 this.pluginCache = pluginCache;
22738 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
22739 this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
22740 this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
22741 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
22742 this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22743 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
22744 const existingPluginNames = new Set();
22745 this.pluginContexts = new Map(this.plugins.map(plugin => [
22746 plugin,
22747 getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
22748 ]));
22749 if (basePluginDriver) {
22750 for (const plugin of userPlugins) {
22751 for (const hook of inputHooks) {
22752 if (hook in plugin) {
22753 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
22754 }
22755 }
22756 }
22757 }
22758 }
22759 createOutputPluginDriver(plugins) {
22760 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
22761 }
22762 getUnfulfilledHookActions() {
22763 return this.unfulfilledActions;
22764 }
22765 // chains, first non-null result stops and returns
22766 hookFirst(hookName, args, replaceContext, skipped) {
22767 let promise = Promise.resolve(undefined);
22768 for (const plugin of this.plugins) {
22769 if (skipped && skipped.has(plugin))
22770 continue;
22771 promise = promise.then(result => {
22772 if (result != null)
22773 return result;
22774 return this.runHook(hookName, args, plugin, false, replaceContext);
22775 });
22776 }
22777 return promise;
22778 }
22779 // chains synchronously, first non-null result stops and returns
22780 hookFirstSync(hookName, args, replaceContext) {
22781 for (const plugin of this.plugins) {
22782 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22783 if (result != null)
22784 return result;
22785 }
22786 return null;
22787 }
22788 // parallel, ignores returns
22789 hookParallel(hookName, args, replaceContext) {
22790 const promises = [];
22791 for (const plugin of this.plugins) {
22792 const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
22793 if (!hookPromise)
22794 continue;
22795 promises.push(hookPromise);
22796 }
22797 return Promise.all(promises).then(() => { });
22798 }
22799 // chains, reduces returned value, handling the reduced value as the first hook argument
22800 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
22801 let promise = Promise.resolve(arg0);
22802 for (const plugin of this.plugins) {
22803 promise = promise.then(arg0 => {
22804 const args = [arg0, ...rest];
22805 const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
22806 if (!hookPromise)
22807 return arg0;
22808 return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
22809 });
22810 }
22811 return promise;
22812 }
22813 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
22814 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
22815 for (const plugin of this.plugins) {
22816 const args = [arg0, ...rest];
22817 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22818 arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
22819 }
22820 return arg0;
22821 }
22822 // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
22823 hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
22824 let promise = Promise.resolve(initialValue);
22825 for (const plugin of this.plugins) {
22826 promise = promise.then(value => {
22827 const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
22828 if (!hookPromise)
22829 return value;
22830 return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
22831 });
22832 }
22833 return promise;
22834 }
22835 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
22836 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
22837 let acc = initialValue;
22838 for (const plugin of this.plugins) {
22839 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22840 acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
22841 }
22842 return acc;
22843 }
22844 // chains, ignores returns
22845 hookSeq(hookName, args, replaceContext) {
22846 let promise = Promise.resolve();
22847 for (const plugin of this.plugins) {
22848 promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
22849 }
22850 return promise;
22851 }
22852 runHook(hookName, args, plugin, permitValues, hookContext) {
22853 const hook = plugin[hookName];
22854 if (!hook)
22855 return undefined;
22856 let context = this.pluginContexts.get(plugin);
22857 if (hookContext) {
22858 context = hookContext(context, plugin);
22859 }
22860 let action = null;
22861 return Promise.resolve()
22862 .then(() => {
22863 // permit values allows values to be returned instead of a functional hook
22864 if (typeof hook !== 'function') {
22865 if (permitValues)
22866 return hook;
22867 return throwInvalidHookError(hookName, plugin.name);
22868 }
22869 // eslint-disable-next-line @typescript-eslint/ban-types
22870 const hookResult = hook.apply(context, args);
22871 if (!hookResult || !hookResult.then) {
22872 // short circuit for non-thenables and non-Promises
22873 return hookResult;
22874 }
22875 // Track pending hook actions to properly error out when
22876 // unfulfilled promises cause rollup to abruptly and confusingly
22877 // exit with a successful 0 return code but without producing any
22878 // output, errors or warnings.
22879 action = [plugin.name, hookName, args];
22880 this.unfulfilledActions.add(action);
22881 // Although it would be more elegant to just return hookResult here
22882 // and put the .then() handler just above the .catch() handler below,
22883 // doing so would subtly change the defacto async event dispatch order
22884 // which at least one test and some plugins in the wild may depend on.
22885 return Promise.resolve(hookResult).then(result => {
22886 // action was fulfilled
22887 this.unfulfilledActions.delete(action);
22888 return result;
22889 });
22890 })
22891 .catch(err => {
22892 if (action !== null) {
22893 // action considered to be fulfilled since error being handled
22894 this.unfulfilledActions.delete(action);
22895 }
22896 return throwPluginError(err, plugin.name, { hook: hookName });
22897 });
22898 }
22899 /**
22900 * Run a sync plugin hook and return the result.
22901 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
22902 * @param args Arguments passed to the plugin hook.
22903 * @param plugin The acutal plugin
22904 * @param hookContext When passed, the plugin context can be overridden.
22905 */
22906 runHookSync(hookName, args, plugin, hookContext) {
22907 const hook = plugin[hookName];
22908 if (!hook)
22909 return undefined;
22910 let context = this.pluginContexts.get(plugin);
22911 if (hookContext) {
22912 context = hookContext(context, plugin);
22913 }
22914 try {
22915 // permit values allows values to be returned instead of a functional hook
22916 if (typeof hook !== 'function') {
22917 return throwInvalidHookError(hookName, plugin.name);
22918 }
22919 // eslint-disable-next-line @typescript-eslint/ban-types
22920 return hook.apply(context, args);
22921 }
22922 catch (err) {
22923 return throwPluginError(err, plugin.name, { hook: hookName });
22924 }
22925 }
22926}
22927
22928function normalizeEntryModules(entryModules) {
22929 if (Array.isArray(entryModules)) {
22930 return entryModules.map(id => ({
22931 fileName: null,
22932 id,
22933 implicitlyLoadedAfter: [],
22934 importer: undefined,
22935 name: null
22936 }));
22937 }
22938 return Object.entries(entryModules).map(([name, id]) => ({
22939 fileName: null,
22940 id,
22941 implicitlyLoadedAfter: [],
22942 importer: undefined,
22943 name
22944 }));
22945}
22946class Graph {
22947 constructor(options, watcher) {
22948 var _a, _b;
22949 this.options = options;
22950 this.cachedModules = new Map();
22951 this.deoptimizationTracker = new PathTracker();
22952 this.entryModules = [];
22953 this.modulesById = new Map();
22954 this.needsTreeshakingPass = false;
22955 this.phase = BuildPhase.LOAD_AND_PARSE;
22956 this.scope = new GlobalScope();
22957 this.watchFiles = Object.create(null);
22958 this.watchMode = false;
22959 this.externalModules = [];
22960 this.implicitEntryModules = [];
22961 this.modules = [];
22962 this.getModuleInfo = (moduleId) => {
22963 const foundModule = this.modulesById.get(moduleId);
22964 if (!foundModule)
22965 return null;
22966 return foundModule.info;
22967 };
22968 if (options.cache !== false) {
22969 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
22970 for (const module of options.cache.modules)
22971 this.cachedModules.set(module.id, module);
22972 }
22973 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
22974 // increment access counter
22975 for (const name in this.pluginCache) {
22976 const cache = this.pluginCache[name];
22977 for (const value of Object.values(cache))
22978 value[0]++;
22979 }
22980 }
22981 if (watcher) {
22982 this.watchMode = true;
22983 const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
22984 const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
22985 watcher.onCurrentAwaited('change', handleChange);
22986 watcher.onCurrentAwaited('close', handleClose);
22987 }
22988 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
22989 this.acornParser = Parser.extend(...options.acornInjectPlugins);
22990 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
22991 }
22992 async build() {
22993 timeStart('generate module graph', 2);
22994 await this.generateModuleGraph();
22995 timeEnd('generate module graph', 2);
22996 timeStart('sort modules', 2);
22997 this.phase = BuildPhase.ANALYSE;
22998 this.sortModules();
22999 timeEnd('sort modules', 2);
23000 timeStart('mark included statements', 2);
23001 this.includeStatements();
23002 timeEnd('mark included statements', 2);
23003 this.phase = BuildPhase.GENERATE;
23004 }
23005 contextParse(code, options = {}) {
23006 const onCommentOrig = options.onComment;
23007 const comments = [];
23008 if (onCommentOrig && typeof onCommentOrig == 'function') {
23009 options.onComment = (block, text, start, end, ...args) => {
23010 comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
23011 return onCommentOrig.call(options, block, text, start, end, ...args);
23012 };
23013 }
23014 else {
23015 options.onComment = comments;
23016 }
23017 const ast = this.acornParser.parse(code, {
23018 ...this.options.acorn,
23019 ...options
23020 });
23021 if (typeof onCommentOrig == 'object') {
23022 onCommentOrig.push(...comments);
23023 }
23024 options.onComment = onCommentOrig;
23025 addAnnotations(comments, ast, code);
23026 return ast;
23027 }
23028 getCache() {
23029 // handle plugin cache eviction
23030 for (const name in this.pluginCache) {
23031 const cache = this.pluginCache[name];
23032 let allDeleted = true;
23033 for (const [key, value] of Object.entries(cache)) {
23034 if (value[0] >= this.options.experimentalCacheExpiry)
23035 delete cache[key];
23036 else
23037 allDeleted = false;
23038 }
23039 if (allDeleted)
23040 delete this.pluginCache[name];
23041 }
23042 return {
23043 modules: this.modules.map(module => module.toJSON()),
23044 plugins: this.pluginCache
23045 };
23046 }
23047 async generateModuleGraph() {
23048 ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
23049 await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
23050 if (this.entryModules.length === 0) {
23051 throw new Error('You must supply options.input to rollup');
23052 }
23053 for (const module of this.modulesById.values()) {
23054 if (module instanceof Module) {
23055 this.modules.push(module);
23056 }
23057 else {
23058 this.externalModules.push(module);
23059 }
23060 }
23061 }
23062 includeStatements() {
23063 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23064 markModuleAndImpureDependenciesAsExecuted(module);
23065 }
23066 if (this.options.treeshake) {
23067 let treeshakingPass = 1;
23068 do {
23069 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
23070 this.needsTreeshakingPass = false;
23071 for (const module of this.modules) {
23072 if (module.isExecuted) {
23073 if (module.info.moduleSideEffects === 'no-treeshake') {
23074 module.includeAllInBundle();
23075 }
23076 else {
23077 module.include();
23078 }
23079 }
23080 }
23081 if (treeshakingPass === 1) {
23082 // We only include exports after the first pass to avoid issues with
23083 // the TDZ detection logic
23084 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23085 if (module.preserveSignature !== false) {
23086 module.includeAllExports(false);
23087 this.needsTreeshakingPass = true;
23088 }
23089 }
23090 }
23091 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
23092 } while (this.needsTreeshakingPass);
23093 }
23094 else {
23095 for (const module of this.modules)
23096 module.includeAllInBundle();
23097 }
23098 for (const externalModule of this.externalModules)
23099 externalModule.warnUnusedImports();
23100 for (const module of this.implicitEntryModules) {
23101 for (const dependant of module.implicitlyLoadedAfter) {
23102 if (!(dependant.info.isEntry || dependant.isIncluded())) {
23103 error(errImplicitDependantIsNotIncluded(dependant));
23104 }
23105 }
23106 }
23107 }
23108 sortModules() {
23109 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
23110 for (const cyclePath of cyclePaths) {
23111 this.options.onwarn({
23112 code: 'CIRCULAR_DEPENDENCY',
23113 cycle: cyclePath,
23114 importer: cyclePath[0],
23115 message: `Circular dependency: ${cyclePath.join(' -> ')}`
23116 });
23117 }
23118 this.modules = orderedModules;
23119 for (const module of this.modules) {
23120 module.bindReferences();
23121 }
23122 this.warnForMissingExports();
23123 }
23124 warnForMissingExports() {
23125 for (const module of this.modules) {
23126 for (const importDescription of module.importDescriptions.values()) {
23127 if (importDescription.name !== '*' &&
23128 !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
23129 module.warn({
23130 code: 'NON_EXISTENT_EXPORT',
23131 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
23132 name: importDescription.name,
23133 source: importDescription.module.id
23134 }, importDescription.start);
23135 }
23136 }
23137 }
23138 }
23139}
23140
23141function formatAction([pluginName, hookName, args]) {
23142 const action = `(${pluginName}) ${hookName}`;
23143 const s = JSON.stringify;
23144 switch (hookName) {
23145 case 'resolveId':
23146 return `${action} ${s(args[0])} ${s(args[1])}`;
23147 case 'load':
23148 return `${action} ${s(args[0])}`;
23149 case 'transform':
23150 return `${action} ${s(args[1])}`;
23151 case 'shouldTransformCachedModule':
23152 return `${action} ${s(args[0].id)}`;
23153 case 'moduleParsed':
23154 return `${action} ${s(args[0].id)}`;
23155 }
23156 return action;
23157}
23158// We do not directly listen on process to avoid max listeners warnings for
23159// complicated build processes
23160const beforeExitEvent = 'beforeExit';
23161const beforeExitEmitter = new require$$0$2.EventEmitter();
23162beforeExitEmitter.setMaxListeners(0);
23163process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
23164async function catchUnfinishedHookActions(pluginDriver, callback) {
23165 let handleEmptyEventLoop;
23166 const emptyEventLoopPromise = new Promise((_, reject) => {
23167 handleEmptyEventLoop = () => {
23168 const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
23169 reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
23170 [...unfulfilledActions].map(formatAction).join('\n')));
23171 };
23172 beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
23173 });
23174 const result = await Promise.race([callback(), emptyEventLoopPromise]);
23175 beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
23176 return result;
23177}
23178
23179function normalizeInputOptions(config) {
23180 var _a, _b, _c;
23181 // These are options that may trigger special warnings or behaviour later
23182 // if the user did not select an explicit value
23183 const unsetOptions = new Set();
23184 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
23185 const onwarn = getOnwarn(config);
23186 const strictDeprecations = config.strictDeprecations || false;
23187 const options = {
23188 acorn: getAcorn(config),
23189 acornInjectPlugins: getAcornInjectPlugins(config),
23190 cache: getCache(config),
23191 context,
23192 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
23193 external: getIdMatcher(config.external),
23194 inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
23195 input: getInput(config),
23196 makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
23197 manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
23198 maxParallelFileReads: getMaxParallelFileReads(config),
23199 moduleContext: getModuleContext(config, context),
23200 onwarn,
23201 perf: config.perf || false,
23202 plugins: ensureArray$1(config.plugins),
23203 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
23204 preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
23205 preserveSymlinks: config.preserveSymlinks || false,
23206 shimMissingExports: config.shimMissingExports || false,
23207 strictDeprecations,
23208 treeshake: getTreeshake(config, onwarn, strictDeprecations)
23209 };
23210 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
23211 return { options, unsetOptions };
23212}
23213const getOnwarn = (config) => {
23214 const { onwarn } = config;
23215 return onwarn
23216 ? warning => {
23217 warning.toString = () => {
23218 let str = '';
23219 if (warning.plugin)
23220 str += `(${warning.plugin} plugin) `;
23221 if (warning.loc)
23222 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
23223 str += warning.message;
23224 return str;
23225 };
23226 onwarn(warning, defaultOnWarn);
23227 }
23228 : defaultOnWarn;
23229};
23230const getAcorn = (config) => ({
23231 allowAwaitOutsideFunction: true,
23232 ecmaVersion: 'latest',
23233 preserveParens: false,
23234 sourceType: 'module',
23235 ...config.acorn
23236});
23237const getAcornInjectPlugins = (config) => ensureArray$1(config.acornInjectPlugins);
23238const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
23239const getIdMatcher = (option) => {
23240 if (option === true) {
23241 return () => true;
23242 }
23243 if (typeof option === 'function') {
23244 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
23245 }
23246 if (option) {
23247 const ids = new Set();
23248 const matchers = [];
23249 for (const value of ensureArray$1(option)) {
23250 if (value instanceof RegExp) {
23251 matchers.push(value);
23252 }
23253 else {
23254 ids.add(value);
23255 }
23256 }
23257 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
23258 }
23259 return () => false;
23260};
23261const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
23262 const configInlineDynamicImports = config.inlineDynamicImports;
23263 if (configInlineDynamicImports) {
23264 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
23265 }
23266 return configInlineDynamicImports;
23267};
23268const getInput = (config) => {
23269 const configInput = config.input;
23270 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
23271};
23272const getManualChunks$1 = (config, warn, strictDeprecations) => {
23273 const configManualChunks = config.manualChunks;
23274 if (configManualChunks) {
23275 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
23276 }
23277 return configManualChunks;
23278};
23279const getMaxParallelFileReads = (config) => {
23280 const maxParallelFileReads = config.maxParallelFileReads;
23281 if (typeof maxParallelFileReads === 'number') {
23282 if (maxParallelFileReads <= 0)
23283 return Infinity;
23284 return maxParallelFileReads;
23285 }
23286 return 20;
23287};
23288const getModuleContext = (config, context) => {
23289 const configModuleContext = config.moduleContext;
23290 if (typeof configModuleContext === 'function') {
23291 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
23292 }
23293 if (configModuleContext) {
23294 const contextByModuleId = Object.create(null);
23295 for (const [key, moduleContext] of Object.entries(configModuleContext)) {
23296 contextByModuleId[require$$0.resolve(key)] = moduleContext;
23297 }
23298 return id => contextByModuleId[id] || context;
23299 }
23300 return () => context;
23301};
23302const getPreserveEntrySignatures = (config, unsetOptions) => {
23303 const configPreserveEntrySignatures = config.preserveEntrySignatures;
23304 if (configPreserveEntrySignatures == null) {
23305 unsetOptions.add('preserveEntrySignatures');
23306 }
23307 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
23308};
23309const getPreserveModules$1 = (config, warn, strictDeprecations) => {
23310 const configPreserveModules = config.preserveModules;
23311 if (configPreserveModules) {
23312 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
23313 }
23314 return configPreserveModules;
23315};
23316const getTreeshake = (config, warn, strictDeprecations) => {
23317 const configTreeshake = config.treeshake;
23318 if (configTreeshake === false) {
23319 return false;
23320 }
23321 const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
23322 if (typeof configWithPreset.pureExternalModules !== 'undefined') {
23323 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);
23324 }
23325 return {
23326 annotations: configWithPreset.annotations !== false,
23327 correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
23328 moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
23329 ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
23330 : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
23331 propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
23332 ? 'always'
23333 : configWithPreset.propertyReadSideEffects !== false,
23334 tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
23335 unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
23336 };
23337};
23338const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
23339 if (typeof moduleSideEffectsOption === 'boolean') {
23340 return () => moduleSideEffectsOption;
23341 }
23342 if (moduleSideEffectsOption === 'no-external') {
23343 return (_id, external) => !external;
23344 }
23345 if (typeof moduleSideEffectsOption === 'function') {
23346 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
23347 }
23348 if (Array.isArray(moduleSideEffectsOption)) {
23349 const ids = new Set(moduleSideEffectsOption);
23350 return id => ids.has(id);
23351 }
23352 if (moduleSideEffectsOption) {
23353 error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23354 }
23355 const isPureExternalModule = getIdMatcher(pureExternalModules);
23356 return (id, external) => !(external && isPureExternalModule(id));
23357};
23358
23359// https://datatracker.ietf.org/doc/html/rfc2396
23360// eslint-disable-next-line no-control-regex
23361const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
23362const DRIVE_LETTER_REGEX = /^[a-z]:/i;
23363function sanitizeFileName(name) {
23364 const match = DRIVE_LETTER_REGEX.exec(name);
23365 const driveLetter = match ? match[0] : '';
23366 // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
23367 // Otherwise, avoid them because they can refer to NTFS alternate data streams.
23368 return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
23369}
23370
23371function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23372 var _a, _b, _c, _d, _e, _f, _g;
23373 // These are options that may trigger special warnings or behaviour later
23374 // if the user did not select an explicit value
23375 const unsetOptions = new Set(unsetInputOptions);
23376 const compact = config.compact || false;
23377 const format = getFormat(config);
23378 const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
23379 const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
23380 const file = getFile(config, preserveModules, inputOptions);
23381 const preferConst = getPreferConst(config, inputOptions);
23382 const generatedCode = getGeneratedCode(config, preferConst);
23383 const outputOptions = {
23384 amd: getAmd(config),
23385 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
23386 banner: getAddon(config, 'banner'),
23387 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
23388 compact,
23389 dir: getDir(config, file),
23390 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
23391 entryFileNames: getEntryFileNames(config, unsetOptions),
23392 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
23393 exports: getExports(config, unsetOptions),
23394 extend: config.extend || false,
23395 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
23396 file,
23397 footer: getAddon(config, 'footer'),
23398 format,
23399 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
23400 generatedCode,
23401 globals: config.globals || {},
23402 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
23403 indent: getIndent(config, compact),
23404 inlineDynamicImports,
23405 interop: getInterop(config, inputOptions),
23406 intro: getAddon(config, 'intro'),
23407 manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
23408 minifyInternalExports: getMinifyInternalExports(config, format, compact),
23409 name: config.name,
23410 namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
23411 noConflict: config.noConflict || false,
23412 outro: getAddon(config, 'outro'),
23413 paths: config.paths || {},
23414 plugins: ensureArray$1(config.plugins),
23415 preferConst,
23416 preserveModules,
23417 preserveModulesRoot: getPreserveModulesRoot(config),
23418 sanitizeFileName: typeof config.sanitizeFileName === 'function'
23419 ? config.sanitizeFileName
23420 : config.sanitizeFileName === false
23421 ? id => id
23422 : sanitizeFileName,
23423 sourcemap: config.sourcemap || false,
23424 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
23425 sourcemapFile: config.sourcemapFile,
23426 sourcemapPathTransform: config.sourcemapPathTransform,
23427 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
23428 systemNullSetters: config.systemNullSetters || false,
23429 validate: config.validate || false
23430 };
23431 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
23432 return { options: outputOptions, unsetOptions };
23433}
23434const getFile = (config, preserveModules, inputOptions) => {
23435 const { file } = config;
23436 if (typeof file === 'string') {
23437 if (preserveModules) {
23438 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
23439 }
23440 if (!Array.isArray(inputOptions.input))
23441 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
23442 }
23443 return file;
23444};
23445const getFormat = (config) => {
23446 const configFormat = config.format;
23447 switch (configFormat) {
23448 case undefined:
23449 case 'es':
23450 case 'esm':
23451 case 'module':
23452 return 'es';
23453 case 'cjs':
23454 case 'commonjs':
23455 return 'cjs';
23456 case 'system':
23457 case 'systemjs':
23458 return 'system';
23459 case 'amd':
23460 case 'iife':
23461 case 'umd':
23462 return configFormat;
23463 default:
23464 return error({
23465 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
23466 url: `https://rollupjs.org/guide/en/#outputformat`
23467 });
23468 }
23469};
23470const getInlineDynamicImports = (config, inputOptions) => {
23471 var _a;
23472 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
23473 const { input } = inputOptions;
23474 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
23475 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
23476 }
23477 return inlineDynamicImports;
23478};
23479const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
23480 var _a;
23481 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
23482 if (preserveModules) {
23483 if (inlineDynamicImports) {
23484 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
23485 }
23486 if (inputOptions.preserveEntrySignatures === false) {
23487 return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
23488 }
23489 }
23490 return preserveModules;
23491};
23492const getPreferConst = (config, inputOptions) => {
23493 const configPreferConst = config.preferConst;
23494 if (configPreferConst != null) {
23495 warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
23496 }
23497 return !!configPreferConst;
23498};
23499const getPreserveModulesRoot = (config) => {
23500 const { preserveModulesRoot } = config;
23501 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
23502 return undefined;
23503 }
23504 return require$$0.resolve(preserveModulesRoot);
23505};
23506const getAmd = (config) => {
23507 const mergedOption = {
23508 autoId: false,
23509 basePath: '',
23510 define: 'define',
23511 ...config.amd
23512 };
23513 if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
23514 return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
23515 }
23516 if (mergedOption.basePath && !mergedOption.autoId) {
23517 return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
23518 }
23519 let normalized;
23520 if (mergedOption.autoId) {
23521 normalized = {
23522 autoId: true,
23523 basePath: mergedOption.basePath,
23524 define: mergedOption.define
23525 };
23526 }
23527 else {
23528 normalized = {
23529 autoId: false,
23530 define: mergedOption.define,
23531 id: mergedOption.id
23532 };
23533 }
23534 return normalized;
23535};
23536const getAddon = (config, name) => {
23537 const configAddon = config[name];
23538 if (typeof configAddon === 'function') {
23539 return configAddon;
23540 }
23541 return () => configAddon || '';
23542};
23543const getDir = (config, file) => {
23544 const { dir } = config;
23545 if (typeof dir === 'string' && typeof file === 'string') {
23546 return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
23547 }
23548 return dir;
23549};
23550const getDynamicImportFunction = (config, inputOptions) => {
23551 const configDynamicImportFunction = config.dynamicImportFunction;
23552 if (configDynamicImportFunction) {
23553 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
23554 }
23555 return configDynamicImportFunction;
23556};
23557const getEntryFileNames = (config, unsetOptions) => {
23558 const configEntryFileNames = config.entryFileNames;
23559 if (configEntryFileNames == null) {
23560 unsetOptions.add('entryFileNames');
23561 }
23562 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
23563};
23564function getExports(config, unsetOptions) {
23565 const configExports = config.exports;
23566 if (configExports == null) {
23567 unsetOptions.add('exports');
23568 }
23569 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
23570 return error(errInvalidExportOptionValue(configExports));
23571 }
23572 return configExports || 'auto';
23573}
23574const getGeneratedCode = (config, preferConst) => {
23575 const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
23576 return {
23577 arrowFunctions: configWithPreset.arrowFunctions === true,
23578 constBindings: configWithPreset.constBindings === true || preferConst,
23579 objectShorthand: configWithPreset.objectShorthand === true,
23580 reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
23581 symbols: configWithPreset.symbols === true
23582 };
23583};
23584const getIndent = (config, compact) => {
23585 if (compact) {
23586 return '';
23587 }
23588 const configIndent = config.indent;
23589 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
23590};
23591const ALLOWED_INTEROP_TYPES = new Set([
23592 'auto',
23593 'esModule',
23594 'default',
23595 'defaultOnly',
23596 true,
23597 false
23598]);
23599const getInterop = (config, inputOptions) => {
23600 const configInterop = config.interop;
23601 const validatedInteropTypes = new Set();
23602 const validateInterop = (interop) => {
23603 if (!validatedInteropTypes.has(interop)) {
23604 validatedInteropTypes.add(interop);
23605 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
23606 return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
23607 }
23608 if (typeof interop === 'boolean') {
23609 warnDeprecation({
23610 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
23611 url: 'https://rollupjs.org/guide/en/#outputinterop'
23612 }, false, inputOptions);
23613 }
23614 }
23615 return interop;
23616 };
23617 if (typeof configInterop === 'function') {
23618 const interopPerId = Object.create(null);
23619 let defaultInterop = null;
23620 return id => id === null
23621 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
23622 : id in interopPerId
23623 ? interopPerId[id]
23624 : validateInterop((interopPerId[id] = configInterop(id)));
23625 }
23626 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
23627};
23628const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
23629 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
23630 if (configManualChunks) {
23631 if (inlineDynamicImports) {
23632 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
23633 }
23634 if (preserveModules) {
23635 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
23636 }
23637 }
23638 return configManualChunks || {};
23639};
23640const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
23641const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
23642 const configNamespaceToStringTag = config.namespaceToStringTag;
23643 if (configNamespaceToStringTag != null) {
23644 warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
23645 return configNamespaceToStringTag;
23646 }
23647 return generatedCode.symbols || false;
23648};
23649
23650function rollup(rawInputOptions) {
23651 return rollupInternal(rawInputOptions, null);
23652}
23653async function rollupInternal(rawInputOptions, watcher) {
23654 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
23655 initialiseTimers(inputOptions);
23656 const graph = new Graph(inputOptions, watcher);
23657 // remove the cache option from the memory after graph creation (cache is not used anymore)
23658 const useCache = rawInputOptions.cache !== false;
23659 delete inputOptions.cache;
23660 delete rawInputOptions.cache;
23661 timeStart('BUILD', 1);
23662 await catchUnfinishedHookActions(graph.pluginDriver, async () => {
23663 try {
23664 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
23665 await graph.build();
23666 }
23667 catch (err) {
23668 const watchFiles = Object.keys(graph.watchFiles);
23669 if (watchFiles.length > 0) {
23670 err.watchFiles = watchFiles;
23671 }
23672 await graph.pluginDriver.hookParallel('buildEnd', [err]);
23673 await graph.pluginDriver.hookParallel('closeBundle', []);
23674 throw err;
23675 }
23676 await graph.pluginDriver.hookParallel('buildEnd', []);
23677 });
23678 timeEnd('BUILD', 1);
23679 const result = {
23680 cache: useCache ? graph.getCache() : undefined,
23681 async close() {
23682 if (result.closed)
23683 return;
23684 result.closed = true;
23685 await graph.pluginDriver.hookParallel('closeBundle', []);
23686 },
23687 closed: false,
23688 async generate(rawOutputOptions) {
23689 if (result.closed)
23690 return error(errAlreadyClosed());
23691 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23692 },
23693 watchFiles: Object.keys(graph.watchFiles),
23694 async write(rawOutputOptions) {
23695 if (result.closed)
23696 return error(errAlreadyClosed());
23697 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23698 }
23699 };
23700 if (inputOptions.perf)
23701 result.getTimings = getTimings;
23702 return result;
23703}
23704async function getInputOptions(rawInputOptions, watchMode) {
23705 if (!rawInputOptions) {
23706 throw new Error('You must supply an options object to rollup');
23707 }
23708 const rawPlugins = ensureArray$1(rawInputOptions.plugins);
23709 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
23710 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
23711 return { options, unsetOptions };
23712}
23713function applyOptionHook(watchMode) {
23714 return async (inputOptions, plugin) => {
23715 if (plugin.options) {
23716 return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
23717 }
23718 return inputOptions;
23719 };
23720}
23721function normalizePlugins(plugins, anonymousPrefix) {
23722 plugins.forEach((plugin, index) => {
23723 if (!plugin.name) {
23724 plugin.name = `${anonymousPrefix}${index + 1}`;
23725 }
23726 });
23727}
23728function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
23729 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
23730 return catchUnfinishedHookActions(outputPluginDriver, async () => {
23731 const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
23732 const generated = await bundle.generate(isWrite);
23733 if (isWrite) {
23734 if (!outputOptions.dir && !outputOptions.file) {
23735 return error({
23736 code: 'MISSING_OPTION',
23737 message: 'You must specify "output.file" or "output.dir" for the build.'
23738 });
23739 }
23740 await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions)));
23741 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
23742 }
23743 return createOutput(generated);
23744 });
23745}
23746function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
23747 if (!rawOutputOptions) {
23748 throw new Error('You must supply an options object');
23749 }
23750 const rawPlugins = ensureArray$1(rawOutputOptions.plugins);
23751 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
23752 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
23753 return {
23754 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
23755 outputPluginDriver
23756 };
23757}
23758function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
23759 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
23760 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
23761 return {
23762 ...pluginContext,
23763 emitFile: emitError,
23764 setAssetSource: emitError
23765 };
23766 }), inputOptions, unsetInputOptions);
23767}
23768function createOutput(outputBundle) {
23769 return {
23770 output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
23771 const fileTypeA = getSortingFileType(outputFileA);
23772 const fileTypeB = getSortingFileType(outputFileB);
23773 if (fileTypeA === fileTypeB)
23774 return 0;
23775 return fileTypeA < fileTypeB ? -1 : 1;
23776 })
23777 };
23778}
23779var SortingFileType;
23780(function (SortingFileType) {
23781 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
23782 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
23783 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
23784})(SortingFileType || (SortingFileType = {}));
23785function getSortingFileType(file) {
23786 if (file.type === 'asset') {
23787 return SortingFileType.ASSET;
23788 }
23789 if (file.isEntry) {
23790 return SortingFileType.ENTRY_CHUNK;
23791 }
23792 return SortingFileType.SECONDARY_CHUNK;
23793}
23794async function writeOutputFile(outputFile, outputOptions) {
23795 const fileName = require$$0.resolve(outputOptions.dir || require$$0.dirname(outputOptions.file), outputFile.fileName);
23796 // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
23797 await require$$0$1.promises.mkdir(require$$0.dirname(fileName), { recursive: true });
23798 let writeSourceMapPromise;
23799 let source;
23800 if (outputFile.type === 'asset') {
23801 source = outputFile.source;
23802 }
23803 else {
23804 source = outputFile.code;
23805 if (outputOptions.sourcemap && outputFile.map) {
23806 let url;
23807 if (outputOptions.sourcemap === 'inline') {
23808 url = outputFile.map.toUrl();
23809 }
23810 else {
23811 url = `${require$$0.basename(outputFile.fileName)}.map`;
23812 writeSourceMapPromise = require$$0$1.promises.writeFile(`${fileName}.map`, outputFile.map.toString());
23813 }
23814 if (outputOptions.sourcemap !== 'hidden') {
23815 source += `//# ${exports.SOURCEMAPPING_URL}=${url}\n`;
23816 }
23817 }
23818 }
23819 return Promise.all([require$$0$1.promises.writeFile(fileName, source), writeSourceMapPromise]);
23820}
23821/**
23822 * Auxiliary function for defining rollup configuration
23823 * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
23824 * @param options
23825 */
23826function defineConfig(options) {
23827 return options;
23828}
23829
23830class WatchEmitter extends require$$0$2.EventEmitter {
23831 constructor() {
23832 super();
23833 this.awaitedHandlers = Object.create(null);
23834 // Allows more than 10 bundles to be watched without
23835 // showing the `MaxListenersExceededWarning` to the user.
23836 this.setMaxListeners(Infinity);
23837 }
23838 // Will be overwritten by Rollup
23839 async close() { }
23840 emitAndAwait(event, ...args) {
23841 this.emit(event, ...args);
23842 return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
23843 }
23844 onCurrentAwaited(event, listener) {
23845 this.getHandlers(event).push(listener);
23846 return this;
23847 }
23848 removeAwaited() {
23849 this.awaitedHandlers = {};
23850 return this;
23851 }
23852 getHandlers(event) {
23853 return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
23854 }
23855}
23856
23857function watch(configs) {
23858 const emitter = new WatchEmitter();
23859 const configArray = ensureArray$1(configs);
23860 const watchConfigs = configArray.filter(config => config.watch !== false);
23861 if (watchConfigs.length === 0) {
23862 return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
23863 }
23864 loadFsEvents()
23865 .then(() => Promise.resolve().then(() => require('./watch.js')))
23866 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
23867 return emitter;
23868}
23869
23870exports.commonjsGlobal = commonjsGlobal;
23871exports.createFilter = createFilter;
23872exports.defaultOnWarn = defaultOnWarn;
23873exports.defineConfig = defineConfig;
23874exports.ensureArray = ensureArray$1;
23875exports.error = error;
23876exports.fseventsImporter = fseventsImporter;
23877exports.generatedCodePresets = generatedCodePresets;
23878exports.getAliasName = getAliasName;
23879exports.getAugmentedNamespace = getAugmentedNamespace;
23880exports.getOrCreate = getOrCreate;
23881exports.loadFsEvents = loadFsEvents;
23882exports.objectifyOption = objectifyOption;
23883exports.objectifyOptionWithPresets = objectifyOptionWithPresets;
23884exports.picomatch = picomatch$1;
23885exports.printQuotedStringList = printQuotedStringList;
23886exports.relativeId = relativeId;
23887exports.rollup = rollup;
23888exports.rollupInternal = rollupInternal;
23889exports.treeshakePresets = treeshakePresets;
23890exports.version = version$1;
23891exports.warnUnknownOptions = warnUnknownOptions;
23892exports.watch = watch;
23893//# sourceMappingURL=rollup.js.map