source: frontend/node_modules/rollup/dist/shared/rollup.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 876.1 KB
Line 
1/*
2 @license
3 Rollup.js v2.80.0
4 Sun, 22 Feb 2026 06:16:40 GMT - commit d17ae15336a45c3c59b2a4aacac2b14186035d28
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.80.0";
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_NAME_OUTSIDE_OUTPUT_DIRECTORY"] = "FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY";
233 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
234 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
235 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
236 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
237 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
238 Errors["INVALID_OPTION"] = "INVALID_OPTION";
239 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
240 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
241 Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
242 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
243 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
244 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
245 Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
246 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
247 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
248 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
249 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
250 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
251 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
252 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
253 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
254})(Errors || (Errors = {}));
255function errAssetNotFinalisedForFileName(name) {
256 return {
257 code: Errors.ASSET_NOT_FINALISED,
258 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
259 };
260}
261function errCannotEmitFromOptionsHook() {
262 return {
263 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
264 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
265 };
266}
267function errChunkNotGeneratedForFileName(name) {
268 return {
269 code: Errors.CHUNK_NOT_GENERATED,
270 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
271 };
272}
273function errChunkInvalid({ fileName, code }, exception) {
274 const errorProps = {
275 code: Errors.CHUNK_INVALID,
276 message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
277 };
278 augmentCodeLocation(errorProps, exception.loc, code, fileName);
279 return errorProps;
280}
281function errCircularReexport(exportName, importedModule) {
282 return {
283 code: Errors.CIRCULAR_REEXPORT,
284 id: importedModule,
285 message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
286 };
287}
288function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
289 return {
290 code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
291 exporter,
292 importer,
293 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.`,
294 reexporter
295 };
296}
297function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
298 return {
299 code: Errors.ASSET_NOT_FOUND,
300 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
301 };
302}
303function errAssetSourceAlreadySet(name) {
304 return {
305 code: Errors.ASSET_SOURCE_ALREADY_SET,
306 message: `Unable to set the source for asset "${name}", source already set.`
307 };
308}
309function errNoAssetSourceSet(assetName) {
310 return {
311 code: Errors.ASSET_SOURCE_MISSING,
312 message: `Plugin error creating asset "${assetName}" - no asset source set.`
313 };
314}
315function errBadLoader(id) {
316 return {
317 code: Errors.BAD_LOADER,
318 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
319 };
320}
321function errDeprecation(deprecation) {
322 return {
323 code: Errors.DEPRECATED_FEATURE,
324 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
325 };
326}
327function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
328 return {
329 code: Errors.FILE_NOT_FOUND,
330 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
331 };
332}
333function errFileNameConflict(fileName) {
334 return {
335 code: Errors.FILE_NAME_CONFLICT,
336 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
337 };
338}
339function errFileNameOutsideOutputDirectory(fileName) {
340 return {
341 code: Errors.FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY,
342 message: `The output file name "${fileName}" is not contained in the output directory. Make sure all file names are relative paths without ".." segments.`
343 };
344}
345function errInputHookInOutputPlugin(pluginName, hookName) {
346 return {
347 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
348 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.`
349 };
350}
351function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
352 return {
353 code: Errors.INVALID_CHUNK,
354 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
355 };
356}
357function errInvalidExportOptionValue(optionValue) {
358 return {
359 code: Errors.INVALID_EXPORT_OPTION,
360 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
361 url: `https://rollupjs.org/guide/en/#outputexports`
362 };
363}
364function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
365 return {
366 code: 'INVALID_EXPORT_OPTION',
367 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
368 };
369}
370function errInternalIdCannotBeExternal(source, importer) {
371 return {
372 code: Errors.INVALID_EXTERNAL_ID,
373 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
374 };
375}
376function errInvalidOption(option, urlHash, explanation, value) {
377 return {
378 code: Errors.INVALID_OPTION,
379 message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
380 url: `https://rollupjs.org/guide/en/#${urlHash}`
381 };
382}
383function errInvalidAddonPluginHook(hook, plugin) {
384 return {
385 code: Errors.INVALID_PLUGIN_HOOK,
386 hook,
387 message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a string, a function hook or an object with a "handler" string or function.`,
388 plugin
389 };
390}
391function errInvalidFunctionPluginHook(hook, plugin) {
392 return {
393 code: Errors.INVALID_PLUGIN_HOOK,
394 hook,
395 message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a function hook or an object with a "handler" function.`,
396 plugin
397 };
398}
399function errInvalidRollupPhaseForAddWatchFile() {
400 return {
401 code: Errors.INVALID_ROLLUP_PHASE,
402 message: `Cannot call addWatchFile after the build has finished.`
403 };
404}
405function errInvalidRollupPhaseForChunkEmission() {
406 return {
407 code: Errors.INVALID_ROLLUP_PHASE,
408 message: `Cannot emit chunks after module loading has finished.`
409 };
410}
411function errMissingExport(exportName, importingModule, importedModule) {
412 return {
413 code: Errors.MISSING_EXPORT,
414 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
415 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
416 };
417}
418function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
419 return {
420 code: Errors.MISSING_IMPLICIT_DEPENDANT,
421 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
422 };
423}
424function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
425 return {
426 code: Errors.MISSING_IMPLICIT_DEPENDANT,
427 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
428 };
429}
430function errImplicitDependantIsNotIncluded(module) {
431 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
432 return {
433 code: Errors.MISSING_IMPLICIT_DEPENDANT,
434 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.`
435 };
436}
437function errMixedExport(facadeModuleId, name) {
438 return {
439 code: Errors.MIXED_EXPORTS,
440 id: facadeModuleId,
441 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`,
442 url: `https://rollupjs.org/guide/en/#outputexports`
443 };
444}
445function errNamespaceConflict(name, reexportingModuleId, sources) {
446 return {
447 code: Errors.NAMESPACE_CONFLICT,
448 message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
449 name,
450 reexporter: reexportingModuleId,
451 sources
452 };
453}
454function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
455 return {
456 code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
457 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)}".`,
458 name,
459 reexporter: reexportingModule,
460 sources
461 };
462}
463function errNoTransformMapOrAstWithoutCode(pluginName) {
464 return {
465 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
466 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
467 'a "code". This will be ignored.'
468 };
469}
470function errPreferNamedExports(facadeModuleId) {
471 const file = relativeId(facadeModuleId);
472 return {
473 code: Errors.PREFER_NAMED_EXPORTS,
474 id: facadeModuleId,
475 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.`,
476 url: `https://rollupjs.org/guide/en/#outputexports`
477 };
478}
479function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
480 return {
481 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
482 id,
483 message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
484 ? `an explicit export named "${syntheticNamedExportsOption}"`
485 : 'a default export'} that does not reexport an unresolved named export of the same module.`
486 };
487}
488function errUnexpectedNamedImport(id, imported, isReexport) {
489 const importType = isReexport ? 'reexport' : 'import';
490 return {
491 code: Errors.UNEXPECTED_NAMED_IMPORT,
492 id,
493 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.`,
494 url: 'https://rollupjs.org/guide/en/#outputinterop'
495 };
496}
497function errUnexpectedNamespaceReexport(id) {
498 return {
499 code: Errors.UNEXPECTED_NAMED_IMPORT,
500 id,
501 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.`,
502 url: 'https://rollupjs.org/guide/en/#outputinterop'
503 };
504}
505function errEntryCannotBeExternal(unresolvedId) {
506 return {
507 code: Errors.UNRESOLVED_ENTRY,
508 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
509 };
510}
511function errUnresolvedEntry(unresolvedId) {
512 return {
513 code: Errors.UNRESOLVED_ENTRY,
514 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
515 };
516}
517function errUnresolvedImport(source, importer) {
518 return {
519 code: Errors.UNRESOLVED_IMPORT,
520 message: `Could not resolve '${source}' from ${relativeId(importer)}`
521 };
522}
523function errUnresolvedImportTreatedAsExternal(source, importer) {
524 return {
525 code: Errors.UNRESOLVED_IMPORT,
526 importer: relativeId(importer),
527 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
528 source,
529 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
530 };
531}
532function errExternalSyntheticExports(source, importer) {
533 return {
534 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
535 importer: relativeId(importer),
536 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
537 source
538 };
539}
540function errFailedValidation(message) {
541 return {
542 code: Errors.VALIDATION_ERROR,
543 message
544 };
545}
546function errAlreadyClosed() {
547 return {
548 code: Errors.ALREADY_CLOSED,
549 message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
550 };
551}
552function warnDeprecation(deprecation, activeDeprecation, options) {
553 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
554}
555function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
556 if (activeDeprecation || strictDeprecations) {
557 const warning = errDeprecation(deprecation);
558 if (strictDeprecations) {
559 return error(warning);
560 }
561 warn(warning);
562 }
563}
564
565const defaultOnWarn = warning => console.warn(warning.message || warning);
566function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
567 const validOptionSet = new Set(validOptions);
568 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
569 if (unknownOptions.length > 0) {
570 warn({
571 code: 'UNKNOWN_OPTION',
572 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
573 ...validOptionSet
574 ]
575 .sort()
576 .join(', ')}`
577 });
578 }
579}
580const treeshakePresets = {
581 recommended: {
582 annotations: true,
583 correctVarValueBeforeDeclaration: false,
584 moduleSideEffects: () => true,
585 propertyReadSideEffects: true,
586 tryCatchDeoptimization: true,
587 unknownGlobalSideEffects: false
588 },
589 safest: {
590 annotations: true,
591 correctVarValueBeforeDeclaration: true,
592 moduleSideEffects: () => true,
593 propertyReadSideEffects: true,
594 tryCatchDeoptimization: true,
595 unknownGlobalSideEffects: true
596 },
597 smallest: {
598 annotations: true,
599 correctVarValueBeforeDeclaration: false,
600 moduleSideEffects: () => false,
601 propertyReadSideEffects: false,
602 tryCatchDeoptimization: false,
603 unknownGlobalSideEffects: false
604 }
605};
606const generatedCodePresets = {
607 es2015: {
608 arrowFunctions: true,
609 constBindings: true,
610 objectShorthand: true,
611 reservedNamesAsProps: true,
612 symbols: true
613 },
614 es5: {
615 arrowFunctions: false,
616 constBindings: false,
617 objectShorthand: false,
618 reservedNamesAsProps: true,
619 symbols: false
620 }
621};
622const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
623const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
624 if (typeof value === 'string') {
625 const preset = presets[value];
626 if (preset) {
627 return preset;
628 }
629 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));
630 }
631 return objectifyOption(value);
632};
633const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
634 const presetName = value === null || value === void 0 ? void 0 : value.preset;
635 if (presetName) {
636 const preset = presets[presetName];
637 if (preset) {
638 return { ...preset, ...value };
639 }
640 else {
641 error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
642 }
643 }
644 return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
645};
646const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
647
648let fsEvents;
649let fsEventsImportError;
650async function loadFsEvents() {
651 try {
652 ({ default: fsEvents } = await Promise.resolve().then(() => /*#__PURE__*/_interopNamespaceDefault(require('fsevents'))));
653 }
654 catch (err) {
655 fsEventsImportError = err;
656 }
657}
658// A call to this function will be injected into the chokidar code
659function getFsEvents() {
660 if (fsEventsImportError)
661 throw fsEventsImportError;
662 return fsEvents;
663}
664
665const fseventsImporter = /*#__PURE__*/Object.defineProperty({
666 __proto__: null,
667 loadFsEvents,
668 getFsEvents
669}, Symbol.toStringTag, { value: 'Module' });
670
671var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
672
673function getDefaultExportFromCjs (x) {
674 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
675}
676
677function getAugmentedNamespace(n) {
678 var f = n.default;
679 if (typeof f == "function") {
680 var a = function () {
681 return f.apply(this, arguments);
682 };
683 a.prototype = f.prototype;
684 } else a = {};
685 Object.defineProperty(a, '__esModule', {value: true});
686 Object.keys(n).forEach(function (k) {
687 var d = Object.getOwnPropertyDescriptor(n, k);
688 Object.defineProperty(a, k, d.get ? d : {
689 enumerable: true,
690 get: function () {
691 return n[k];
692 }
693 });
694 });
695 return a;
696}
697
698var charToInteger = {};
699var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
700for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
701 charToInteger[chars$1.charCodeAt(i$1)] = i$1;
702}
703function decode(mappings) {
704 var decoded = [];
705 var line = [];
706 var segment = [
707 0,
708 0,
709 0,
710 0,
711 0,
712 ];
713 var j = 0;
714 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
715 var c = mappings.charCodeAt(i);
716 if (c === 44) { // ","
717 segmentify(line, segment, j);
718 j = 0;
719 }
720 else if (c === 59) { // ";"
721 segmentify(line, segment, j);
722 j = 0;
723 decoded.push(line);
724 line = [];
725 segment[0] = 0;
726 }
727 else {
728 var integer = charToInteger[c];
729 if (integer === undefined) {
730 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
731 }
732 var hasContinuationBit = integer & 32;
733 integer &= 31;
734 value += integer << shift;
735 if (hasContinuationBit) {
736 shift += 5;
737 }
738 else {
739 var shouldNegate = value & 1;
740 value >>>= 1;
741 if (shouldNegate) {
742 value = value === 0 ? -0x80000000 : -value;
743 }
744 segment[j] += value;
745 j++;
746 value = shift = 0; // reset
747 }
748 }
749 }
750 segmentify(line, segment, j);
751 decoded.push(line);
752 return decoded;
753}
754function segmentify(line, segment, j) {
755 // This looks ugly, but we're creating specialized arrays with a specific
756 // length. This is much faster than creating a new array (which v8 expands to
757 // a capacity of 17 after pushing the first item), or slicing out a subarray
758 // (which is slow). Length 4 is assumed to be the most frequent, followed by
759 // length 5 (since not everything will have an associated name), followed by
760 // length 1 (it's probably rare for a source substring to not have an
761 // associated segment data).
762 if (j === 4)
763 line.push([segment[0], segment[1], segment[2], segment[3]]);
764 else if (j === 5)
765 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
766 else if (j === 1)
767 line.push([segment[0]]);
768}
769function encode(decoded) {
770 var sourceFileIndex = 0; // second field
771 var sourceCodeLine = 0; // third field
772 var sourceCodeColumn = 0; // fourth field
773 var nameIndex = 0; // fifth field
774 var mappings = '';
775 for (var i = 0; i < decoded.length; i++) {
776 var line = decoded[i];
777 if (i > 0)
778 mappings += ';';
779 if (line.length === 0)
780 continue;
781 var generatedCodeColumn = 0; // first field
782 var lineMappings = [];
783 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
784 var segment = line_1[_i];
785 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
786 generatedCodeColumn = segment[0];
787 if (segment.length > 1) {
788 segmentMappings +=
789 encodeInteger(segment[1] - sourceFileIndex) +
790 encodeInteger(segment[2] - sourceCodeLine) +
791 encodeInteger(segment[3] - sourceCodeColumn);
792 sourceFileIndex = segment[1];
793 sourceCodeLine = segment[2];
794 sourceCodeColumn = segment[3];
795 }
796 if (segment.length === 5) {
797 segmentMappings += encodeInteger(segment[4] - nameIndex);
798 nameIndex = segment[4];
799 }
800 lineMappings.push(segmentMappings);
801 }
802 mappings += lineMappings.join(',');
803 }
804 return mappings;
805}
806function encodeInteger(num) {
807 var result = '';
808 num = num < 0 ? (-num << 1) | 1 : num << 1;
809 do {
810 var clamped = num & 31;
811 num >>>= 5;
812 if (num > 0) {
813 clamped |= 32;
814 }
815 result += chars$1[clamped];
816 } while (num > 0);
817 return result;
818}
819
820class BitSet {
821 constructor(arg) {
822 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
823 }
824
825 add(n) {
826 this.bits[n >> 5] |= 1 << (n & 31);
827 }
828
829 has(n) {
830 return !!(this.bits[n >> 5] & (1 << (n & 31)));
831 }
832}
833
834class Chunk$1 {
835 constructor(start, end, content) {
836 this.start = start;
837 this.end = end;
838 this.original = content;
839
840 this.intro = '';
841 this.outro = '';
842
843 this.content = content;
844 this.storeName = false;
845 this.edited = false;
846
847 // we make these non-enumerable, for sanity while debugging
848 Object.defineProperties(this, {
849 previous: { writable: true, value: null },
850 next: { writable: true, value: null },
851 });
852 }
853
854 appendLeft(content) {
855 this.outro += content;
856 }
857
858 appendRight(content) {
859 this.intro = this.intro + content;
860 }
861
862 clone() {
863 const chunk = new Chunk$1(this.start, this.end, this.original);
864
865 chunk.intro = this.intro;
866 chunk.outro = this.outro;
867 chunk.content = this.content;
868 chunk.storeName = this.storeName;
869 chunk.edited = this.edited;
870
871 return chunk;
872 }
873
874 contains(index) {
875 return this.start < index && index < this.end;
876 }
877
878 eachNext(fn) {
879 let chunk = this;
880 while (chunk) {
881 fn(chunk);
882 chunk = chunk.next;
883 }
884 }
885
886 eachPrevious(fn) {
887 let chunk = this;
888 while (chunk) {
889 fn(chunk);
890 chunk = chunk.previous;
891 }
892 }
893
894 edit(content, storeName, contentOnly) {
895 this.content = content;
896 if (!contentOnly) {
897 this.intro = '';
898 this.outro = '';
899 }
900 this.storeName = storeName;
901
902 this.edited = true;
903
904 return this;
905 }
906
907 prependLeft(content) {
908 this.outro = content + this.outro;
909 }
910
911 prependRight(content) {
912 this.intro = content + this.intro;
913 }
914
915 split(index) {
916 const sliceIndex = index - this.start;
917
918 const originalBefore = this.original.slice(0, sliceIndex);
919 const originalAfter = this.original.slice(sliceIndex);
920
921 this.original = originalBefore;
922
923 const newChunk = new Chunk$1(index, this.end, originalAfter);
924 newChunk.outro = this.outro;
925 this.outro = '';
926
927 this.end = index;
928
929 if (this.edited) {
930 // TODO is this block necessary?...
931 newChunk.edit('', false);
932 this.content = '';
933 } else {
934 this.content = originalBefore;
935 }
936
937 newChunk.next = this.next;
938 if (newChunk.next) newChunk.next.previous = newChunk;
939 newChunk.previous = this;
940 this.next = newChunk;
941
942 return newChunk;
943 }
944
945 toString() {
946 return this.intro + this.content + this.outro;
947 }
948
949 trimEnd(rx) {
950 this.outro = this.outro.replace(rx, '');
951 if (this.outro.length) return true;
952
953 const trimmed = this.content.replace(rx, '');
954
955 if (trimmed.length) {
956 if (trimmed !== this.content) {
957 this.split(this.start + trimmed.length).edit('', undefined, true);
958 }
959 return true;
960 } else {
961 this.edit('', undefined, true);
962
963 this.intro = this.intro.replace(rx, '');
964 if (this.intro.length) return true;
965 }
966 }
967
968 trimStart(rx) {
969 this.intro = this.intro.replace(rx, '');
970 if (this.intro.length) return true;
971
972 const trimmed = this.content.replace(rx, '');
973
974 if (trimmed.length) {
975 if (trimmed !== this.content) {
976 this.split(this.end - trimmed.length);
977 this.edit('', undefined, true);
978 }
979 return true;
980 } else {
981 this.edit('', undefined, true);
982
983 this.outro = this.outro.replace(rx, '');
984 if (this.outro.length) return true;
985 }
986 }
987}
988
989let btoa = () => {
990 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
991};
992if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
993 btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
994} else if (typeof Buffer === 'function') {
995 btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
996}
997
998class SourceMap {
999 constructor(properties) {
1000 this.version = 3;
1001 this.file = properties.file;
1002 this.sources = properties.sources;
1003 this.sourcesContent = properties.sourcesContent;
1004 this.names = properties.names;
1005 this.mappings = encode(properties.mappings);
1006 }
1007
1008 toString() {
1009 return JSON.stringify(this);
1010 }
1011
1012 toUrl() {
1013 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
1014 }
1015}
1016
1017function guessIndent(code) {
1018 const lines = code.split('\n');
1019
1020 const tabbed = lines.filter((line) => /^\t+/.test(line));
1021 const spaced = lines.filter((line) => /^ {2,}/.test(line));
1022
1023 if (tabbed.length === 0 && spaced.length === 0) {
1024 return null;
1025 }
1026
1027 // More lines tabbed than spaced? Assume tabs, and
1028 // default to tabs in the case of a tie (or nothing
1029 // to go on)
1030 if (tabbed.length >= spaced.length) {
1031 return '\t';
1032 }
1033
1034 // Otherwise, we need to guess the multiple
1035 const min = spaced.reduce((previous, current) => {
1036 const numSpaces = /^ +/.exec(current)[0].length;
1037 return Math.min(numSpaces, previous);
1038 }, Infinity);
1039
1040 return new Array(min + 1).join(' ');
1041}
1042
1043function getRelativePath(from, to) {
1044 const fromParts = from.split(/[/\\]/);
1045 const toParts = to.split(/[/\\]/);
1046
1047 fromParts.pop(); // get dirname
1048
1049 while (fromParts[0] === toParts[0]) {
1050 fromParts.shift();
1051 toParts.shift();
1052 }
1053
1054 if (fromParts.length) {
1055 let i = fromParts.length;
1056 while (i--) fromParts[i] = '..';
1057 }
1058
1059 return fromParts.concat(toParts).join('/');
1060}
1061
1062const toString$1 = Object.prototype.toString;
1063
1064function isObject$1(thing) {
1065 return toString$1.call(thing) === '[object Object]';
1066}
1067
1068function getLocator(source) {
1069 const originalLines = source.split('\n');
1070 const lineOffsets = [];
1071
1072 for (let i = 0, pos = 0; i < originalLines.length; i++) {
1073 lineOffsets.push(pos);
1074 pos += originalLines[i].length + 1;
1075 }
1076
1077 return function locate(index) {
1078 let i = 0;
1079 let j = lineOffsets.length;
1080 while (i < j) {
1081 const m = (i + j) >> 1;
1082 if (index < lineOffsets[m]) {
1083 j = m;
1084 } else {
1085 i = m + 1;
1086 }
1087 }
1088 const line = i - 1;
1089 const column = index - lineOffsets[line];
1090 return { line, column };
1091 };
1092}
1093
1094class Mappings {
1095 constructor(hires) {
1096 this.hires = hires;
1097 this.generatedCodeLine = 0;
1098 this.generatedCodeColumn = 0;
1099 this.raw = [];
1100 this.rawSegments = this.raw[this.generatedCodeLine] = [];
1101 this.pending = null;
1102 }
1103
1104 addEdit(sourceIndex, content, loc, nameIndex) {
1105 if (content.length) {
1106 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1107 if (nameIndex >= 0) {
1108 segment.push(nameIndex);
1109 }
1110 this.rawSegments.push(segment);
1111 } else if (this.pending) {
1112 this.rawSegments.push(this.pending);
1113 }
1114
1115 this.advance(content);
1116 this.pending = null;
1117 }
1118
1119 addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
1120 let originalCharIndex = chunk.start;
1121 let first = true;
1122
1123 while (originalCharIndex < chunk.end) {
1124 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
1125 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
1126 }
1127
1128 if (original[originalCharIndex] === '\n') {
1129 loc.line += 1;
1130 loc.column = 0;
1131 this.generatedCodeLine += 1;
1132 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1133 this.generatedCodeColumn = 0;
1134 first = true;
1135 } else {
1136 loc.column += 1;
1137 this.generatedCodeColumn += 1;
1138 first = false;
1139 }
1140
1141 originalCharIndex += 1;
1142 }
1143
1144 this.pending = null;
1145 }
1146
1147 advance(str) {
1148 if (!str) return;
1149
1150 const lines = str.split('\n');
1151
1152 if (lines.length > 1) {
1153 for (let i = 0; i < lines.length - 1; i++) {
1154 this.generatedCodeLine++;
1155 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1156 }
1157 this.generatedCodeColumn = 0;
1158 }
1159
1160 this.generatedCodeColumn += lines[lines.length - 1].length;
1161 }
1162}
1163
1164const n = '\n';
1165
1166const warned = {
1167 insertLeft: false,
1168 insertRight: false,
1169 storeName: false,
1170};
1171
1172class MagicString {
1173 constructor(string, options = {}) {
1174 const chunk = new Chunk$1(0, string.length, string);
1175
1176 Object.defineProperties(this, {
1177 original: { writable: true, value: string },
1178 outro: { writable: true, value: '' },
1179 intro: { writable: true, value: '' },
1180 firstChunk: { writable: true, value: chunk },
1181 lastChunk: { writable: true, value: chunk },
1182 lastSearchedChunk: { writable: true, value: chunk },
1183 byStart: { writable: true, value: {} },
1184 byEnd: { writable: true, value: {} },
1185 filename: { writable: true, value: options.filename },
1186 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1187 sourcemapLocations: { writable: true, value: new BitSet() },
1188 storedNames: { writable: true, value: {} },
1189 indentStr: { writable: true, value: guessIndent(string) },
1190 });
1191
1192 this.byStart[0] = chunk;
1193 this.byEnd[string.length] = chunk;
1194 }
1195
1196 addSourcemapLocation(char) {
1197 this.sourcemapLocations.add(char);
1198 }
1199
1200 append(content) {
1201 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1202
1203 this.outro += content;
1204 return this;
1205 }
1206
1207 appendLeft(index, content) {
1208 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1209
1210 this._split(index);
1211
1212 const chunk = this.byEnd[index];
1213
1214 if (chunk) {
1215 chunk.appendLeft(content);
1216 } else {
1217 this.intro += content;
1218 }
1219 return this;
1220 }
1221
1222 appendRight(index, content) {
1223 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1224
1225 this._split(index);
1226
1227 const chunk = this.byStart[index];
1228
1229 if (chunk) {
1230 chunk.appendRight(content);
1231 } else {
1232 this.outro += content;
1233 }
1234 return this;
1235 }
1236
1237 clone() {
1238 const cloned = new MagicString(this.original, { filename: this.filename });
1239
1240 let originalChunk = this.firstChunk;
1241 let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1242
1243 while (originalChunk) {
1244 cloned.byStart[clonedChunk.start] = clonedChunk;
1245 cloned.byEnd[clonedChunk.end] = clonedChunk;
1246
1247 const nextOriginalChunk = originalChunk.next;
1248 const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1249
1250 if (nextClonedChunk) {
1251 clonedChunk.next = nextClonedChunk;
1252 nextClonedChunk.previous = clonedChunk;
1253
1254 clonedChunk = nextClonedChunk;
1255 }
1256
1257 originalChunk = nextOriginalChunk;
1258 }
1259
1260 cloned.lastChunk = clonedChunk;
1261
1262 if (this.indentExclusionRanges) {
1263 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1264 }
1265
1266 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
1267
1268 cloned.intro = this.intro;
1269 cloned.outro = this.outro;
1270
1271 return cloned;
1272 }
1273
1274 generateDecodedMap(options) {
1275 options = options || {};
1276
1277 const sourceIndex = 0;
1278 const names = Object.keys(this.storedNames);
1279 const mappings = new Mappings(options.hires);
1280
1281 const locate = getLocator(this.original);
1282
1283 if (this.intro) {
1284 mappings.advance(this.intro);
1285 }
1286
1287 this.firstChunk.eachNext((chunk) => {
1288 const loc = locate(chunk.start);
1289
1290 if (chunk.intro.length) mappings.advance(chunk.intro);
1291
1292 if (chunk.edited) {
1293 mappings.addEdit(
1294 sourceIndex,
1295 chunk.content,
1296 loc,
1297 chunk.storeName ? names.indexOf(chunk.original) : -1
1298 );
1299 } else {
1300 mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
1301 }
1302
1303 if (chunk.outro.length) mappings.advance(chunk.outro);
1304 });
1305
1306 return {
1307 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1308 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1309 sourcesContent: options.includeContent ? [this.original] : [null],
1310 names,
1311 mappings: mappings.raw,
1312 };
1313 }
1314
1315 generateMap(options) {
1316 return new SourceMap(this.generateDecodedMap(options));
1317 }
1318
1319 getIndentString() {
1320 return this.indentStr === null ? '\t' : this.indentStr;
1321 }
1322
1323 indent(indentStr, options) {
1324 const pattern = /^[^\r\n]/gm;
1325
1326 if (isObject$1(indentStr)) {
1327 options = indentStr;
1328 indentStr = undefined;
1329 }
1330
1331 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1332
1333 if (indentStr === '') return this; // noop
1334
1335 options = options || {};
1336
1337 // Process exclusion ranges
1338 const isExcluded = {};
1339
1340 if (options.exclude) {
1341 const exclusions =
1342 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1343 exclusions.forEach((exclusion) => {
1344 for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
1345 isExcluded[i] = true;
1346 }
1347 });
1348 }
1349
1350 let shouldIndentNextCharacter = options.indentStart !== false;
1351 const replacer = (match) => {
1352 if (shouldIndentNextCharacter) return `${indentStr}${match}`;
1353 shouldIndentNextCharacter = true;
1354 return match;
1355 };
1356
1357 this.intro = this.intro.replace(pattern, replacer);
1358
1359 let charIndex = 0;
1360 let chunk = this.firstChunk;
1361
1362 while (chunk) {
1363 const end = chunk.end;
1364
1365 if (chunk.edited) {
1366 if (!isExcluded[charIndex]) {
1367 chunk.content = chunk.content.replace(pattern, replacer);
1368
1369 if (chunk.content.length) {
1370 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1371 }
1372 }
1373 } else {
1374 charIndex = chunk.start;
1375
1376 while (charIndex < end) {
1377 if (!isExcluded[charIndex]) {
1378 const char = this.original[charIndex];
1379
1380 if (char === '\n') {
1381 shouldIndentNextCharacter = true;
1382 } else if (char !== '\r' && shouldIndentNextCharacter) {
1383 shouldIndentNextCharacter = false;
1384
1385 if (charIndex === chunk.start) {
1386 chunk.prependRight(indentStr);
1387 } else {
1388 this._splitChunk(chunk, charIndex);
1389 chunk = chunk.next;
1390 chunk.prependRight(indentStr);
1391 }
1392 }
1393 }
1394
1395 charIndex += 1;
1396 }
1397 }
1398
1399 charIndex = chunk.end;
1400 chunk = chunk.next;
1401 }
1402
1403 this.outro = this.outro.replace(pattern, replacer);
1404
1405 return this;
1406 }
1407
1408 insert() {
1409 throw new Error(
1410 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
1411 );
1412 }
1413
1414 insertLeft(index, content) {
1415 if (!warned.insertLeft) {
1416 console.warn(
1417 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
1418 ); // eslint-disable-line no-console
1419 warned.insertLeft = true;
1420 }
1421
1422 return this.appendLeft(index, content);
1423 }
1424
1425 insertRight(index, content) {
1426 if (!warned.insertRight) {
1427 console.warn(
1428 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
1429 ); // eslint-disable-line no-console
1430 warned.insertRight = true;
1431 }
1432
1433 return this.prependRight(index, content);
1434 }
1435
1436 move(start, end, index) {
1437 if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
1438
1439 this._split(start);
1440 this._split(end);
1441 this._split(index);
1442
1443 const first = this.byStart[start];
1444 const last = this.byEnd[end];
1445
1446 const oldLeft = first.previous;
1447 const oldRight = last.next;
1448
1449 const newRight = this.byStart[index];
1450 if (!newRight && last === this.lastChunk) return this;
1451 const newLeft = newRight ? newRight.previous : this.lastChunk;
1452
1453 if (oldLeft) oldLeft.next = oldRight;
1454 if (oldRight) oldRight.previous = oldLeft;
1455
1456 if (newLeft) newLeft.next = first;
1457 if (newRight) newRight.previous = last;
1458
1459 if (!first.previous) this.firstChunk = last.next;
1460 if (!last.next) {
1461 this.lastChunk = first.previous;
1462 this.lastChunk.next = null;
1463 }
1464
1465 first.previous = newLeft;
1466 last.next = newRight || null;
1467
1468 if (!newLeft) this.firstChunk = first;
1469 if (!newRight) this.lastChunk = last;
1470 return this;
1471 }
1472
1473 overwrite(start, end, content, options) {
1474 if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
1475
1476 while (start < 0) start += this.original.length;
1477 while (end < 0) end += this.original.length;
1478
1479 if (end > this.original.length) throw new Error('end is out of bounds');
1480 if (start === end)
1481 throw new Error(
1482 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
1483 );
1484
1485 this._split(start);
1486 this._split(end);
1487
1488 if (options === true) {
1489 if (!warned.storeName) {
1490 console.warn(
1491 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
1492 ); // eslint-disable-line no-console
1493 warned.storeName = true;
1494 }
1495
1496 options = { storeName: true };
1497 }
1498 const storeName = options !== undefined ? options.storeName : false;
1499 const contentOnly = options !== undefined ? options.contentOnly : false;
1500
1501 if (storeName) {
1502 const original = this.original.slice(start, end);
1503 Object.defineProperty(this.storedNames, original, {
1504 writable: true,
1505 value: true,
1506 enumerable: true,
1507 });
1508 }
1509
1510 const first = this.byStart[start];
1511 const last = this.byEnd[end];
1512
1513 if (first) {
1514 let chunk = first;
1515 while (chunk !== last) {
1516 if (chunk.next !== this.byStart[chunk.end]) {
1517 throw new Error('Cannot overwrite across a split point');
1518 }
1519 chunk = chunk.next;
1520 chunk.edit('', false);
1521 }
1522
1523 first.edit(content, storeName, contentOnly);
1524 } else {
1525 // must be inserting at the end
1526 const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
1527
1528 // TODO last chunk in the array may not be the last chunk, if it's moved...
1529 last.next = newChunk;
1530 newChunk.previous = last;
1531 }
1532 return this;
1533 }
1534
1535 prepend(content) {
1536 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1537
1538 this.intro = content + this.intro;
1539 return this;
1540 }
1541
1542 prependLeft(index, content) {
1543 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1544
1545 this._split(index);
1546
1547 const chunk = this.byEnd[index];
1548
1549 if (chunk) {
1550 chunk.prependLeft(content);
1551 } else {
1552 this.intro = content + this.intro;
1553 }
1554 return this;
1555 }
1556
1557 prependRight(index, content) {
1558 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1559
1560 this._split(index);
1561
1562 const chunk = this.byStart[index];
1563
1564 if (chunk) {
1565 chunk.prependRight(content);
1566 } else {
1567 this.outro = content + this.outro;
1568 }
1569 return this;
1570 }
1571
1572 remove(start, end) {
1573 while (start < 0) start += this.original.length;
1574 while (end < 0) end += this.original.length;
1575
1576 if (start === end) return this;
1577
1578 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1579 if (start > end) throw new Error('end must be greater than start');
1580
1581 this._split(start);
1582 this._split(end);
1583
1584 let chunk = this.byStart[start];
1585
1586 while (chunk) {
1587 chunk.intro = '';
1588 chunk.outro = '';
1589 chunk.edit('');
1590
1591 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1592 }
1593 return this;
1594 }
1595
1596 lastChar() {
1597 if (this.outro.length) return this.outro[this.outro.length - 1];
1598 let chunk = this.lastChunk;
1599 do {
1600 if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1601 if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1602 if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1603 } while ((chunk = chunk.previous));
1604 if (this.intro.length) return this.intro[this.intro.length - 1];
1605 return '';
1606 }
1607
1608 lastLine() {
1609 let lineIndex = this.outro.lastIndexOf(n);
1610 if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1611 let lineStr = this.outro;
1612 let chunk = this.lastChunk;
1613 do {
1614 if (chunk.outro.length > 0) {
1615 lineIndex = chunk.outro.lastIndexOf(n);
1616 if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1617 lineStr = chunk.outro + lineStr;
1618 }
1619
1620 if (chunk.content.length > 0) {
1621 lineIndex = chunk.content.lastIndexOf(n);
1622 if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1623 lineStr = chunk.content + lineStr;
1624 }
1625
1626 if (chunk.intro.length > 0) {
1627 lineIndex = chunk.intro.lastIndexOf(n);
1628 if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1629 lineStr = chunk.intro + lineStr;
1630 }
1631 } while ((chunk = chunk.previous));
1632 lineIndex = this.intro.lastIndexOf(n);
1633 if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1634 return this.intro + lineStr;
1635 }
1636
1637 slice(start = 0, end = this.original.length) {
1638 while (start < 0) start += this.original.length;
1639 while (end < 0) end += this.original.length;
1640
1641 let result = '';
1642
1643 // find start chunk
1644 let chunk = this.firstChunk;
1645 while (chunk && (chunk.start > start || chunk.end <= start)) {
1646 // found end chunk before start
1647 if (chunk.start < end && chunk.end >= end) {
1648 return result;
1649 }
1650
1651 chunk = chunk.next;
1652 }
1653
1654 if (chunk && chunk.edited && chunk.start !== start)
1655 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1656
1657 const startChunk = chunk;
1658 while (chunk) {
1659 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1660 result += chunk.intro;
1661 }
1662
1663 const containsEnd = chunk.start < end && chunk.end >= end;
1664 if (containsEnd && chunk.edited && chunk.end !== end)
1665 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1666
1667 const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1668 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1669
1670 result += chunk.content.slice(sliceStart, sliceEnd);
1671
1672 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1673 result += chunk.outro;
1674 }
1675
1676 if (containsEnd) {
1677 break;
1678 }
1679
1680 chunk = chunk.next;
1681 }
1682
1683 return result;
1684 }
1685
1686 // TODO deprecate this? not really very useful
1687 snip(start, end) {
1688 const clone = this.clone();
1689 clone.remove(0, start);
1690 clone.remove(end, clone.original.length);
1691
1692 return clone;
1693 }
1694
1695 _split(index) {
1696 if (this.byStart[index] || this.byEnd[index]) return;
1697
1698 let chunk = this.lastSearchedChunk;
1699 const searchForward = index > chunk.end;
1700
1701 while (chunk) {
1702 if (chunk.contains(index)) return this._splitChunk(chunk, index);
1703
1704 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1705 }
1706 }
1707
1708 _splitChunk(chunk, index) {
1709 if (chunk.edited && chunk.content.length) {
1710 // zero-length edited chunks are a special case (overlapping replacements)
1711 const loc = getLocator(this.original)(index);
1712 throw new Error(
1713 `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
1714 );
1715 }
1716
1717 const newChunk = chunk.split(index);
1718
1719 this.byEnd[index] = chunk;
1720 this.byStart[index] = newChunk;
1721 this.byEnd[newChunk.end] = newChunk;
1722
1723 if (chunk === this.lastChunk) this.lastChunk = newChunk;
1724
1725 this.lastSearchedChunk = chunk;
1726 return true;
1727 }
1728
1729 toString() {
1730 let str = this.intro;
1731
1732 let chunk = this.firstChunk;
1733 while (chunk) {
1734 str += chunk.toString();
1735 chunk = chunk.next;
1736 }
1737
1738 return str + this.outro;
1739 }
1740
1741 isEmpty() {
1742 let chunk = this.firstChunk;
1743 do {
1744 if (
1745 (chunk.intro.length && chunk.intro.trim()) ||
1746 (chunk.content.length && chunk.content.trim()) ||
1747 (chunk.outro.length && chunk.outro.trim())
1748 )
1749 return false;
1750 } while ((chunk = chunk.next));
1751 return true;
1752 }
1753
1754 length() {
1755 let chunk = this.firstChunk;
1756 let length = 0;
1757 do {
1758 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1759 } while ((chunk = chunk.next));
1760 return length;
1761 }
1762
1763 trimLines() {
1764 return this.trim('[\\r\\n]');
1765 }
1766
1767 trim(charType) {
1768 return this.trimStart(charType).trimEnd(charType);
1769 }
1770
1771 trimEndAborted(charType) {
1772 const rx = new RegExp((charType || '\\s') + '+$');
1773
1774 this.outro = this.outro.replace(rx, '');
1775 if (this.outro.length) return true;
1776
1777 let chunk = this.lastChunk;
1778
1779 do {
1780 const end = chunk.end;
1781 const aborted = chunk.trimEnd(rx);
1782
1783 // if chunk was trimmed, we have a new lastChunk
1784 if (chunk.end !== end) {
1785 if (this.lastChunk === chunk) {
1786 this.lastChunk = chunk.next;
1787 }
1788
1789 this.byEnd[chunk.end] = chunk;
1790 this.byStart[chunk.next.start] = chunk.next;
1791 this.byEnd[chunk.next.end] = chunk.next;
1792 }
1793
1794 if (aborted) return true;
1795 chunk = chunk.previous;
1796 } while (chunk);
1797
1798 return false;
1799 }
1800
1801 trimEnd(charType) {
1802 this.trimEndAborted(charType);
1803 return this;
1804 }
1805 trimStartAborted(charType) {
1806 const rx = new RegExp('^' + (charType || '\\s') + '+');
1807
1808 this.intro = this.intro.replace(rx, '');
1809 if (this.intro.length) return true;
1810
1811 let chunk = this.firstChunk;
1812
1813 do {
1814 const end = chunk.end;
1815 const aborted = chunk.trimStart(rx);
1816
1817 if (chunk.end !== end) {
1818 // special case...
1819 if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1820
1821 this.byEnd[chunk.end] = chunk;
1822 this.byStart[chunk.next.start] = chunk.next;
1823 this.byEnd[chunk.next.end] = chunk.next;
1824 }
1825
1826 if (aborted) return true;
1827 chunk = chunk.next;
1828 } while (chunk);
1829
1830 return false;
1831 }
1832
1833 trimStart(charType) {
1834 this.trimStartAborted(charType);
1835 return this;
1836 }
1837
1838 hasChanged() {
1839 return this.original !== this.toString();
1840 }
1841
1842 replace(searchValue, replacement) {
1843 function getReplacement(match, str) {
1844 if (typeof replacement === 'string') {
1845 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1846 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1847 if (i === '$') return '$';
1848 if (i === '&') return match[0];
1849 const num = +i;
1850 if (num < match.length) return match[+i];
1851 return `$${i}`;
1852 });
1853 } else {
1854 return replacement(...match, match.index, str, match.groups);
1855 }
1856 }
1857 function matchAll(re, str) {
1858 let match;
1859 const matches = [];
1860 while ((match = re.exec(str))) {
1861 matches.push(match);
1862 }
1863 return matches;
1864 }
1865 if (typeof searchValue !== 'string' && searchValue.global) {
1866 const matches = matchAll(searchValue, this.original);
1867 matches.forEach((match) => {
1868 if (match.index != null)
1869 this.overwrite(
1870 match.index,
1871 match.index + match[0].length,
1872 getReplacement(match, this.original)
1873 );
1874 });
1875 } else {
1876 const match = this.original.match(searchValue);
1877 if (match && match.index != null)
1878 this.overwrite(
1879 match.index,
1880 match.index + match[0].length,
1881 getReplacement(match, this.original)
1882 );
1883 }
1884 return this;
1885 }
1886}
1887
1888const hasOwnProp = Object.prototype.hasOwnProperty;
1889
1890class Bundle$1 {
1891 constructor(options = {}) {
1892 this.intro = options.intro || '';
1893 this.separator = options.separator !== undefined ? options.separator : '\n';
1894 this.sources = [];
1895 this.uniqueSources = [];
1896 this.uniqueSourceIndexByFilename = {};
1897 }
1898
1899 addSource(source) {
1900 if (source instanceof MagicString) {
1901 return this.addSource({
1902 content: source,
1903 filename: source.filename,
1904 separator: this.separator,
1905 });
1906 }
1907
1908 if (!isObject$1(source) || !source.content) {
1909 throw new Error(
1910 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
1911 );
1912 }
1913
1914 ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
1915 if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
1916 });
1917
1918 if (source.separator === undefined) {
1919 // TODO there's a bunch of this sort of thing, needs cleaning up
1920 source.separator = this.separator;
1921 }
1922
1923 if (source.filename) {
1924 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1925 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1926 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1927 } else {
1928 const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1929 if (source.content.original !== uniqueSource.content) {
1930 throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
1931 }
1932 }
1933 }
1934
1935 this.sources.push(source);
1936 return this;
1937 }
1938
1939 append(str, options) {
1940 this.addSource({
1941 content: new MagicString(str),
1942 separator: (options && options.separator) || '',
1943 });
1944
1945 return this;
1946 }
1947
1948 clone() {
1949 const bundle = new Bundle$1({
1950 intro: this.intro,
1951 separator: this.separator,
1952 });
1953
1954 this.sources.forEach((source) => {
1955 bundle.addSource({
1956 filename: source.filename,
1957 content: source.content.clone(),
1958 separator: source.separator,
1959 });
1960 });
1961
1962 return bundle;
1963 }
1964
1965 generateDecodedMap(options = {}) {
1966 const names = [];
1967 this.sources.forEach((source) => {
1968 Object.keys(source.content.storedNames).forEach((name) => {
1969 if (!~names.indexOf(name)) names.push(name);
1970 });
1971 });
1972
1973 const mappings = new Mappings(options.hires);
1974
1975 if (this.intro) {
1976 mappings.advance(this.intro);
1977 }
1978
1979 this.sources.forEach((source, i) => {
1980 if (i > 0) {
1981 mappings.advance(this.separator);
1982 }
1983
1984 const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
1985 const magicString = source.content;
1986 const locate = getLocator(magicString.original);
1987
1988 if (magicString.intro) {
1989 mappings.advance(magicString.intro);
1990 }
1991
1992 magicString.firstChunk.eachNext((chunk) => {
1993 const loc = locate(chunk.start);
1994
1995 if (chunk.intro.length) mappings.advance(chunk.intro);
1996
1997 if (source.filename) {
1998 if (chunk.edited) {
1999 mappings.addEdit(
2000 sourceIndex,
2001 chunk.content,
2002 loc,
2003 chunk.storeName ? names.indexOf(chunk.original) : -1
2004 );
2005 } else {
2006 mappings.addUneditedChunk(
2007 sourceIndex,
2008 chunk,
2009 magicString.original,
2010 loc,
2011 magicString.sourcemapLocations
2012 );
2013 }
2014 } else {
2015 mappings.advance(chunk.content);
2016 }
2017
2018 if (chunk.outro.length) mappings.advance(chunk.outro);
2019 });
2020
2021 if (magicString.outro) {
2022 mappings.advance(magicString.outro);
2023 }
2024 });
2025
2026 return {
2027 file: options.file ? options.file.split(/[/\\]/).pop() : null,
2028 sources: this.uniqueSources.map((source) => {
2029 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
2030 }),
2031 sourcesContent: this.uniqueSources.map((source) => {
2032 return options.includeContent ? source.content : null;
2033 }),
2034 names,
2035 mappings: mappings.raw,
2036 };
2037 }
2038
2039 generateMap(options) {
2040 return new SourceMap(this.generateDecodedMap(options));
2041 }
2042
2043 getIndentString() {
2044 const indentStringCounts = {};
2045
2046 this.sources.forEach((source) => {
2047 const indentStr = source.content.indentStr;
2048
2049 if (indentStr === null) return;
2050
2051 if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
2052 indentStringCounts[indentStr] += 1;
2053 });
2054
2055 return (
2056 Object.keys(indentStringCounts).sort((a, b) => {
2057 return indentStringCounts[a] - indentStringCounts[b];
2058 })[0] || '\t'
2059 );
2060 }
2061
2062 indent(indentStr) {
2063 if (!arguments.length) {
2064 indentStr = this.getIndentString();
2065 }
2066
2067 if (indentStr === '') return this; // noop
2068
2069 let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
2070
2071 this.sources.forEach((source, i) => {
2072 const separator = source.separator !== undefined ? source.separator : this.separator;
2073 const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
2074
2075 source.content.indent(indentStr, {
2076 exclude: source.indentExclusionRanges,
2077 indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
2078 });
2079
2080 trailingNewline = source.content.lastChar() === '\n';
2081 });
2082
2083 if (this.intro) {
2084 this.intro =
2085 indentStr +
2086 this.intro.replace(/^[^\n]/gm, (match, index) => {
2087 return index > 0 ? indentStr + match : match;
2088 });
2089 }
2090
2091 return this;
2092 }
2093
2094 prepend(str) {
2095 this.intro = str + this.intro;
2096 return this;
2097 }
2098
2099 toString() {
2100 const body = this.sources
2101 .map((source, i) => {
2102 const separator = source.separator !== undefined ? source.separator : this.separator;
2103 const str = (i > 0 ? separator : '') + source.content.toString();
2104
2105 return str;
2106 })
2107 .join('');
2108
2109 return this.intro + body;
2110 }
2111
2112 isEmpty() {
2113 if (this.intro.length && this.intro.trim()) return false;
2114 if (this.sources.some((source) => !source.content.isEmpty())) return false;
2115 return true;
2116 }
2117
2118 length() {
2119 return this.sources.reduce(
2120 (length, source) => length + source.content.length(),
2121 this.intro.length
2122 );
2123 }
2124
2125 trimLines() {
2126 return this.trim('[\\r\\n]');
2127 }
2128
2129 trim(charType) {
2130 return this.trimStart(charType).trimEnd(charType);
2131 }
2132
2133 trimStart(charType) {
2134 const rx = new RegExp('^' + (charType || '\\s') + '+');
2135 this.intro = this.intro.replace(rx, '');
2136
2137 if (!this.intro) {
2138 let source;
2139 let i = 0;
2140
2141 do {
2142 source = this.sources[i++];
2143 if (!source) {
2144 break;
2145 }
2146 } while (!source.content.trimStartAborted(charType));
2147 }
2148
2149 return this;
2150 }
2151
2152 trimEnd(charType) {
2153 const rx = new RegExp((charType || '\\s') + '+$');
2154
2155 let source;
2156 let i = this.sources.length - 1;
2157
2158 do {
2159 source = this.sources[i--];
2160 if (!source) {
2161 this.intro = this.intro.replace(rx, '');
2162 break;
2163 }
2164 } while (!source.content.trimEndAborted(charType));
2165
2166 return this;
2167 }
2168}
2169
2170function getOrCreate(map, key, init) {
2171 const existing = map.get(key);
2172 if (existing) {
2173 return existing;
2174 }
2175 const value = init();
2176 map.set(key, value);
2177 return value;
2178}
2179
2180const UnknownKey = Symbol('Unknown Key');
2181const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
2182const UnknownInteger = Symbol('Unknown Integer');
2183const EMPTY_PATH = [];
2184const UNKNOWN_PATH = [UnknownKey];
2185// For deoptimizations, this means we are modifying an unknown property but did
2186// not lose track of the object or are creating a setter/getter;
2187// For assignment effects it means we do not check for setter/getter effects
2188// but only if something is mutated that is included, which is relevant for
2189// Object.defineProperty
2190const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
2191const UNKNOWN_INTEGER_PATH = [UnknownInteger];
2192const EntitiesKey = Symbol('Entities');
2193class PathTracker {
2194 constructor() {
2195 this.entityPaths = Object.create(null, {
2196 [EntitiesKey]: { value: new Set() }
2197 });
2198 }
2199 trackEntityAtPathAndGetIfTracked(path, entity) {
2200 const trackedEntities = this.getEntities(path);
2201 if (trackedEntities.has(entity))
2202 return true;
2203 trackedEntities.add(entity);
2204 return false;
2205 }
2206 withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
2207 const trackedEntities = this.getEntities(path);
2208 if (trackedEntities.has(entity))
2209 return returnIfTracked;
2210 trackedEntities.add(entity);
2211 const result = onUntracked();
2212 trackedEntities.delete(entity);
2213 return result;
2214 }
2215 getEntities(path) {
2216 let currentPaths = this.entityPaths;
2217 for (const pathSegment of path) {
2218 currentPaths = currentPaths[pathSegment] =
2219 currentPaths[pathSegment] ||
2220 Object.create(null, { [EntitiesKey]: { value: new Set() } });
2221 }
2222 return currentPaths[EntitiesKey];
2223 }
2224}
2225const SHARED_RECURSION_TRACKER = new PathTracker();
2226class DiscriminatedPathTracker {
2227 constructor() {
2228 this.entityPaths = Object.create(null, {
2229 [EntitiesKey]: { value: new Map() }
2230 });
2231 }
2232 trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
2233 let currentPaths = this.entityPaths;
2234 for (const pathSegment of path) {
2235 currentPaths = currentPaths[pathSegment] =
2236 currentPaths[pathSegment] ||
2237 Object.create(null, { [EntitiesKey]: { value: new Map() } });
2238 }
2239 const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
2240 if (trackedEntities.has(entity))
2241 return true;
2242 trackedEntities.add(entity);
2243 return false;
2244 }
2245}
2246
2247const UnknownValue = Symbol('Unknown Value');
2248const UnknownTruthyValue = Symbol('Unknown Truthy Value');
2249class ExpressionEntity {
2250 constructor() {
2251 this.included = false;
2252 }
2253 deoptimizePath(_path) { }
2254 deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
2255 thisArg.deoptimizePath(UNKNOWN_PATH);
2256 }
2257 /**
2258 * If possible it returns a stringifyable literal value for this node that can be used
2259 * for inlining or comparing values.
2260 * Otherwise it should return UnknownValue.
2261 */
2262 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2263 return UnknownValue;
2264 }
2265 getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
2266 return UNKNOWN_EXPRESSION;
2267 }
2268 hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
2269 return true;
2270 }
2271 include(_context, _includeChildrenRecursively, _options) {
2272 this.included = true;
2273 }
2274 includeCallArguments(context, args) {
2275 for (const arg of args) {
2276 arg.include(context, false);
2277 }
2278 }
2279 shouldBeIncluded(_context) {
2280 return true;
2281 }
2282}
2283const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
2284})();
2285
2286const INTERACTION_ACCESSED = 0;
2287const INTERACTION_ASSIGNED = 1;
2288const INTERACTION_CALLED = 2;
2289const NODE_INTERACTION_UNKNOWN_ACCESS = {
2290 thisArg: null,
2291 type: INTERACTION_ACCESSED
2292};
2293const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
2294const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
2295 args: UNKNOWN_ARG,
2296 thisArg: null,
2297 type: INTERACTION_ASSIGNED
2298};
2299const NO_ARGS = [];
2300// While this is technically a call without arguments, we can compare against
2301// this reference in places where precise values or thisArg would make a
2302// difference
2303const NODE_INTERACTION_UNKNOWN_CALL = {
2304 args: NO_ARGS,
2305 thisArg: null,
2306 type: INTERACTION_CALLED,
2307 withNew: false
2308};
2309
2310class Variable extends ExpressionEntity {
2311 constructor(name) {
2312 super();
2313 this.name = name;
2314 this.alwaysRendered = false;
2315 this.initReached = false;
2316 this.isId = false;
2317 this.isReassigned = false;
2318 this.kind = null;
2319 this.renderBaseName = null;
2320 this.renderName = null;
2321 }
2322 /**
2323 * Binds identifiers that reference this variable to this variable.
2324 * Necessary to be able to change variable names.
2325 */
2326 addReference(_identifier) { }
2327 getBaseVariableName() {
2328 return this.renderBaseName || this.renderName || this.name;
2329 }
2330 getName(getPropertyAccess) {
2331 const name = this.renderName || this.name;
2332 return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
2333 }
2334 hasEffectsOnInteractionAtPath(path, { type }, _context) {
2335 return type !== INTERACTION_ACCESSED || path.length > 0;
2336 }
2337 /**
2338 * Marks this variable as being part of the bundle, which is usually the case when one of
2339 * its identifiers becomes part of the bundle. Returns true if it has not been included
2340 * previously.
2341 * Once a variable is included, it should take care all its declarations are included.
2342 */
2343 include() {
2344 this.included = true;
2345 }
2346 markCalledFromTryStatement() { }
2347 setRenderNames(baseName, name) {
2348 this.renderBaseName = baseName;
2349 this.renderName = name;
2350 }
2351}
2352
2353class ExternalVariable extends Variable {
2354 constructor(module, name) {
2355 super(name);
2356 this.referenced = false;
2357 this.module = module;
2358 this.isNamespace = name === '*';
2359 }
2360 addReference(identifier) {
2361 this.referenced = true;
2362 if (this.name === 'default' || this.name === '*') {
2363 this.module.suggestName(identifier.name);
2364 }
2365 }
2366 hasEffectsOnInteractionAtPath(path, { type }) {
2367 return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
2368 }
2369 include() {
2370 if (!this.included) {
2371 this.included = true;
2372 this.module.used = true;
2373 }
2374 }
2375}
2376
2377const BLANK = Object.freeze(Object.create(null));
2378const EMPTY_OBJECT = Object.freeze({});
2379const EMPTY_ARRAY = Object.freeze([]);
2380
2381const RESERVED_NAMES = new Set([
2382 'await',
2383 'break',
2384 'case',
2385 'catch',
2386 'class',
2387 'const',
2388 'continue',
2389 'debugger',
2390 'default',
2391 'delete',
2392 'do',
2393 'else',
2394 'enum',
2395 'eval',
2396 'export',
2397 'extends',
2398 'false',
2399 'finally',
2400 'for',
2401 'function',
2402 'if',
2403 'implements',
2404 'import',
2405 'in',
2406 'instanceof',
2407 'interface',
2408 'let',
2409 'NaN',
2410 'new',
2411 'null',
2412 'package',
2413 'private',
2414 'protected',
2415 'public',
2416 'return',
2417 'static',
2418 'super',
2419 'switch',
2420 'this',
2421 'throw',
2422 'true',
2423 'try',
2424 'typeof',
2425 'undefined',
2426 'var',
2427 'void',
2428 'while',
2429 'with',
2430 'yield'
2431]);
2432const RESERVED_NAMES$1 = RESERVED_NAMES;
2433
2434const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2435const startsWithDigit = (str) => /\d/.test(str[0]);
2436const needsEscape = (str) => startsWithDigit(str) || RESERVED_NAMES$1.has(str) || str === 'arguments';
2437function isLegal(str) {
2438 if (needsEscape(str)) {
2439 return false;
2440 }
2441 return !illegalCharacters.test(str);
2442}
2443function makeLegal(str) {
2444 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2445 if (needsEscape(str))
2446 str = `_${str}`;
2447 return str || '_';
2448}
2449
2450class ExternalModule {
2451 constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
2452 this.options = options;
2453 this.id = id;
2454 this.renormalizeRenderPath = renormalizeRenderPath;
2455 this.declarations = new Map();
2456 this.defaultVariableName = '';
2457 this.dynamicImporters = [];
2458 this.execIndex = Infinity;
2459 this.exportedVariables = new Map();
2460 this.importers = [];
2461 this.mostCommonSuggestion = 0;
2462 this.nameSuggestions = new Map();
2463 this.namespaceVariableName = '';
2464 this.reexported = false;
2465 this.renderPath = undefined;
2466 this.used = false;
2467 this.variableName = '';
2468 this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2469 const { importers, dynamicImporters } = this;
2470 const info = (this.info = {
2471 ast: null,
2472 code: null,
2473 dynamicallyImportedIdResolutions: EMPTY_ARRAY,
2474 dynamicallyImportedIds: EMPTY_ARRAY,
2475 get dynamicImporters() {
2476 return dynamicImporters.sort();
2477 },
2478 hasDefaultExport: null,
2479 get hasModuleSideEffects() {
2480 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
2481 return info.moduleSideEffects;
2482 },
2483 id,
2484 implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
2485 implicitlyLoadedBefore: EMPTY_ARRAY,
2486 importedIdResolutions: EMPTY_ARRAY,
2487 importedIds: EMPTY_ARRAY,
2488 get importers() {
2489 return importers.sort();
2490 },
2491 isEntry: false,
2492 isExternal: true,
2493 isIncluded: null,
2494 meta,
2495 moduleSideEffects,
2496 syntheticNamedExports: false
2497 });
2498 // Hide the deprecated key so that it only warns when accessed explicitly
2499 Object.defineProperty(this.info, 'hasModuleSideEffects', {
2500 enumerable: false
2501 });
2502 }
2503 getVariableForExportName(name) {
2504 const declaration = this.declarations.get(name);
2505 if (declaration)
2506 return [declaration];
2507 const externalVariable = new ExternalVariable(this, name);
2508 this.declarations.set(name, externalVariable);
2509 this.exportedVariables.set(externalVariable, name);
2510 return [externalVariable];
2511 }
2512 setRenderPath(options, inputBase) {
2513 this.renderPath =
2514 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2515 if (!this.renderPath) {
2516 this.renderPath = this.renormalizeRenderPath
2517 ? normalize(require$$0.relative(inputBase, this.id))
2518 : this.id;
2519 }
2520 }
2521 suggestName(name) {
2522 var _a;
2523 const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
2524 this.nameSuggestions.set(name, value);
2525 if (value > this.mostCommonSuggestion) {
2526 this.mostCommonSuggestion = value;
2527 this.suggestedVariableName = name;
2528 }
2529 }
2530 warnUnusedImports() {
2531 const unused = Array.from(this.declarations)
2532 .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
2533 .map(([name]) => name);
2534 if (unused.length === 0)
2535 return;
2536 const importersSet = new Set();
2537 for (const name of unused) {
2538 for (const importer of this.declarations.get(name).module.importers) {
2539 importersSet.add(importer);
2540 }
2541 }
2542 const importersArray = [...importersSet];
2543 this.options.onwarn({
2544 code: 'UNUSED_EXTERNAL_IMPORT',
2545 message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
2546 names: unused,
2547 source: this.id,
2548 sources: importersArray
2549 });
2550 }
2551}
2552
2553var picomatch$1 = {exports: {}};
2554
2555var utils$3 = {};
2556
2557const path$1 = require$$0;
2558const WIN_SLASH = '\\\\/';
2559const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
2560
2561/**
2562 * Posix glob regex
2563 */
2564
2565const DOT_LITERAL = '\\.';
2566const PLUS_LITERAL = '\\+';
2567const QMARK_LITERAL = '\\?';
2568const SLASH_LITERAL = '\\/';
2569const ONE_CHAR = '(?=.)';
2570const QMARK = '[^/]';
2571const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
2572const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
2573const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
2574const NO_DOT = `(?!${DOT_LITERAL})`;
2575const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
2576const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
2577const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
2578const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
2579const STAR = `${QMARK}*?`;
2580
2581const POSIX_CHARS = {
2582 DOT_LITERAL,
2583 PLUS_LITERAL,
2584 QMARK_LITERAL,
2585 SLASH_LITERAL,
2586 ONE_CHAR,
2587 QMARK,
2588 END_ANCHOR,
2589 DOTS_SLASH,
2590 NO_DOT,
2591 NO_DOTS,
2592 NO_DOT_SLASH,
2593 NO_DOTS_SLASH,
2594 QMARK_NO_DOT,
2595 STAR,
2596 START_ANCHOR
2597};
2598
2599/**
2600 * Windows glob regex
2601 */
2602
2603const WINDOWS_CHARS = {
2604 ...POSIX_CHARS,
2605
2606 SLASH_LITERAL: `[${WIN_SLASH}]`,
2607 QMARK: WIN_NO_SLASH,
2608 STAR: `${WIN_NO_SLASH}*?`,
2609 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
2610 NO_DOT: `(?!${DOT_LITERAL})`,
2611 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2612 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
2613 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
2614 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
2615 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
2616 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
2617};
2618
2619/**
2620 * POSIX Bracket Regex
2621 */
2622
2623const POSIX_REGEX_SOURCE$1 = {
2624 alnum: 'a-zA-Z0-9',
2625 alpha: 'a-zA-Z',
2626 ascii: '\\x00-\\x7F',
2627 blank: ' \\t',
2628 cntrl: '\\x00-\\x1F\\x7F',
2629 digit: '0-9',
2630 graph: '\\x21-\\x7E',
2631 lower: 'a-z',
2632 print: '\\x20-\\x7E ',
2633 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
2634 space: ' \\t\\r\\n\\v\\f',
2635 upper: 'A-Z',
2636 word: 'A-Za-z0-9_',
2637 xdigit: 'A-Fa-f0-9'
2638};
2639
2640var constants$2 = {
2641 MAX_LENGTH: 1024 * 64,
2642 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
2643
2644 // regular expressions
2645 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
2646 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
2647 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
2648 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
2649 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
2650 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
2651
2652 // Replace globs with equivalent patterns to reduce parsing time.
2653 REPLACEMENTS: {
2654 '***': '*',
2655 '**/**': '**',
2656 '**/**/**': '**'
2657 },
2658
2659 // Digits
2660 CHAR_0: 48, /* 0 */
2661 CHAR_9: 57, /* 9 */
2662
2663 // Alphabet chars.
2664 CHAR_UPPERCASE_A: 65, /* A */
2665 CHAR_LOWERCASE_A: 97, /* a */
2666 CHAR_UPPERCASE_Z: 90, /* Z */
2667 CHAR_LOWERCASE_Z: 122, /* z */
2668
2669 CHAR_LEFT_PARENTHESES: 40, /* ( */
2670 CHAR_RIGHT_PARENTHESES: 41, /* ) */
2671
2672 CHAR_ASTERISK: 42, /* * */
2673
2674 // Non-alphabetic chars.
2675 CHAR_AMPERSAND: 38, /* & */
2676 CHAR_AT: 64, /* @ */
2677 CHAR_BACKWARD_SLASH: 92, /* \ */
2678 CHAR_CARRIAGE_RETURN: 13, /* \r */
2679 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
2680 CHAR_COLON: 58, /* : */
2681 CHAR_COMMA: 44, /* , */
2682 CHAR_DOT: 46, /* . */
2683 CHAR_DOUBLE_QUOTE: 34, /* " */
2684 CHAR_EQUAL: 61, /* = */
2685 CHAR_EXCLAMATION_MARK: 33, /* ! */
2686 CHAR_FORM_FEED: 12, /* \f */
2687 CHAR_FORWARD_SLASH: 47, /* / */
2688 CHAR_GRAVE_ACCENT: 96, /* ` */
2689 CHAR_HASH: 35, /* # */
2690 CHAR_HYPHEN_MINUS: 45, /* - */
2691 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
2692 CHAR_LEFT_CURLY_BRACE: 123, /* { */
2693 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
2694 CHAR_LINE_FEED: 10, /* \n */
2695 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
2696 CHAR_PERCENT: 37, /* % */
2697 CHAR_PLUS: 43, /* + */
2698 CHAR_QUESTION_MARK: 63, /* ? */
2699 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
2700 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
2701 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
2702 CHAR_SEMICOLON: 59, /* ; */
2703 CHAR_SINGLE_QUOTE: 39, /* ' */
2704 CHAR_SPACE: 32, /* */
2705 CHAR_TAB: 9, /* \t */
2706 CHAR_UNDERSCORE: 95, /* _ */
2707 CHAR_VERTICAL_LINE: 124, /* | */
2708 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
2709
2710 SEP: path$1.sep,
2711
2712 /**
2713 * Create EXTGLOB_CHARS
2714 */
2715
2716 extglobChars(chars) {
2717 return {
2718 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
2719 '?': { type: 'qmark', open: '(?:', close: ')?' },
2720 '+': { type: 'plus', open: '(?:', close: ')+' },
2721 '*': { type: 'star', open: '(?:', close: ')*' },
2722 '@': { type: 'at', open: '(?:', close: ')' }
2723 };
2724 },
2725
2726 /**
2727 * Create GLOB_CHARS
2728 */
2729
2730 globChars(win32) {
2731 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
2732 }
2733};
2734
2735(function (exports) {
2736
2737 const path = require$$0;
2738 const win32 = process.platform === 'win32';
2739 const {
2740 REGEX_BACKSLASH,
2741 REGEX_REMOVE_BACKSLASH,
2742 REGEX_SPECIAL_CHARS,
2743 REGEX_SPECIAL_CHARS_GLOBAL
2744 } = constants$2;
2745
2746 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
2747 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
2748 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
2749 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
2750 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
2751
2752 exports.removeBackslashes = str => {
2753 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
2754 return match === '\\' ? '' : match;
2755 });
2756 };
2757
2758 exports.supportsLookbehinds = () => {
2759 const segs = process.version.slice(1).split('.').map(Number);
2760 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
2761 return true;
2762 }
2763 return false;
2764 };
2765
2766 exports.isWindows = options => {
2767 if (options && typeof options.windows === 'boolean') {
2768 return options.windows;
2769 }
2770 return win32 === true || path.sep === '\\';
2771 };
2772
2773 exports.escapeLast = (input, char, lastIdx) => {
2774 const idx = input.lastIndexOf(char, lastIdx);
2775 if (idx === -1) return input;
2776 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
2777 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
2778 };
2779
2780 exports.removePrefix = (input, state = {}) => {
2781 let output = input;
2782 if (output.startsWith('./')) {
2783 output = output.slice(2);
2784 state.prefix = './';
2785 }
2786 return output;
2787 };
2788
2789 exports.wrapOutput = (input, state = {}, options = {}) => {
2790 const prepend = options.contains ? '' : '^';
2791 const append = options.contains ? '' : '$';
2792
2793 let output = `${prepend}(?:${input})${append}`;
2794 if (state.negated === true) {
2795 output = `(?:^(?!${output}).*$)`;
2796 }
2797 return output;
2798 };
2799} (utils$3));
2800
2801const utils$2 = utils$3;
2802const {
2803 CHAR_ASTERISK, /* * */
2804 CHAR_AT, /* @ */
2805 CHAR_BACKWARD_SLASH, /* \ */
2806 CHAR_COMMA, /* , */
2807 CHAR_DOT, /* . */
2808 CHAR_EXCLAMATION_MARK, /* ! */
2809 CHAR_FORWARD_SLASH, /* / */
2810 CHAR_LEFT_CURLY_BRACE, /* { */
2811 CHAR_LEFT_PARENTHESES, /* ( */
2812 CHAR_LEFT_SQUARE_BRACKET, /* [ */
2813 CHAR_PLUS, /* + */
2814 CHAR_QUESTION_MARK, /* ? */
2815 CHAR_RIGHT_CURLY_BRACE, /* } */
2816 CHAR_RIGHT_PARENTHESES, /* ) */
2817 CHAR_RIGHT_SQUARE_BRACKET /* ] */
2818} = constants$2;
2819
2820const isPathSeparator = code => {
2821 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
2822};
2823
2824const depth = token => {
2825 if (token.isPrefix !== true) {
2826 token.depth = token.isGlobstar ? Infinity : 1;
2827 }
2828};
2829
2830/**
2831 * Quickly scans a glob pattern and returns an object with a handful of
2832 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
2833 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
2834 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
2835 *
2836 * ```js
2837 * const pm = require('picomatch');
2838 * console.log(pm.scan('foo/bar/*.js'));
2839 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
2840 * ```
2841 * @param {String} `str`
2842 * @param {Object} `options`
2843 * @return {Object} Returns an object with tokens and regex source string.
2844 * @api public
2845 */
2846
2847const scan$1 = (input, options) => {
2848 const opts = options || {};
2849
2850 const length = input.length - 1;
2851 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
2852 const slashes = [];
2853 const tokens = [];
2854 const parts = [];
2855
2856 let str = input;
2857 let index = -1;
2858 let start = 0;
2859 let lastIndex = 0;
2860 let isBrace = false;
2861 let isBracket = false;
2862 let isGlob = false;
2863 let isExtglob = false;
2864 let isGlobstar = false;
2865 let braceEscaped = false;
2866 let backslashes = false;
2867 let negated = false;
2868 let negatedExtglob = false;
2869 let finished = false;
2870 let braces = 0;
2871 let prev;
2872 let code;
2873 let token = { value: '', depth: 0, isGlob: false };
2874
2875 const eos = () => index >= length;
2876 const peek = () => str.charCodeAt(index + 1);
2877 const advance = () => {
2878 prev = code;
2879 return str.charCodeAt(++index);
2880 };
2881
2882 while (index < length) {
2883 code = advance();
2884 let next;
2885
2886 if (code === CHAR_BACKWARD_SLASH) {
2887 backslashes = token.backslashes = true;
2888 code = advance();
2889
2890 if (code === CHAR_LEFT_CURLY_BRACE) {
2891 braceEscaped = true;
2892 }
2893 continue;
2894 }
2895
2896 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
2897 braces++;
2898
2899 while (eos() !== true && (code = advance())) {
2900 if (code === CHAR_BACKWARD_SLASH) {
2901 backslashes = token.backslashes = true;
2902 advance();
2903 continue;
2904 }
2905
2906 if (code === CHAR_LEFT_CURLY_BRACE) {
2907 braces++;
2908 continue;
2909 }
2910
2911 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
2912 isBrace = token.isBrace = true;
2913 isGlob = token.isGlob = true;
2914 finished = true;
2915
2916 if (scanToEnd === true) {
2917 continue;
2918 }
2919
2920 break;
2921 }
2922
2923 if (braceEscaped !== true && code === CHAR_COMMA) {
2924 isBrace = token.isBrace = true;
2925 isGlob = token.isGlob = true;
2926 finished = true;
2927
2928 if (scanToEnd === true) {
2929 continue;
2930 }
2931
2932 break;
2933 }
2934
2935 if (code === CHAR_RIGHT_CURLY_BRACE) {
2936 braces--;
2937
2938 if (braces === 0) {
2939 braceEscaped = false;
2940 isBrace = token.isBrace = true;
2941 finished = true;
2942 break;
2943 }
2944 }
2945 }
2946
2947 if (scanToEnd === true) {
2948 continue;
2949 }
2950
2951 break;
2952 }
2953
2954 if (code === CHAR_FORWARD_SLASH) {
2955 slashes.push(index);
2956 tokens.push(token);
2957 token = { value: '', depth: 0, isGlob: false };
2958
2959 if (finished === true) continue;
2960 if (prev === CHAR_DOT && index === (start + 1)) {
2961 start += 2;
2962 continue;
2963 }
2964
2965 lastIndex = index + 1;
2966 continue;
2967 }
2968
2969 if (opts.noext !== true) {
2970 const isExtglobChar = code === CHAR_PLUS
2971 || code === CHAR_AT
2972 || code === CHAR_ASTERISK
2973 || code === CHAR_QUESTION_MARK
2974 || code === CHAR_EXCLAMATION_MARK;
2975
2976 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
2977 isGlob = token.isGlob = true;
2978 isExtglob = token.isExtglob = true;
2979 finished = true;
2980 if (code === CHAR_EXCLAMATION_MARK && index === start) {
2981 negatedExtglob = true;
2982 }
2983
2984 if (scanToEnd === true) {
2985 while (eos() !== true && (code = advance())) {
2986 if (code === CHAR_BACKWARD_SLASH) {
2987 backslashes = token.backslashes = true;
2988 code = advance();
2989 continue;
2990 }
2991
2992 if (code === CHAR_RIGHT_PARENTHESES) {
2993 isGlob = token.isGlob = true;
2994 finished = true;
2995 break;
2996 }
2997 }
2998 continue;
2999 }
3000 break;
3001 }
3002 }
3003
3004 if (code === CHAR_ASTERISK) {
3005 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
3006 isGlob = token.isGlob = true;
3007 finished = true;
3008
3009 if (scanToEnd === true) {
3010 continue;
3011 }
3012 break;
3013 }
3014
3015 if (code === CHAR_QUESTION_MARK) {
3016 isGlob = token.isGlob = true;
3017 finished = true;
3018
3019 if (scanToEnd === true) {
3020 continue;
3021 }
3022 break;
3023 }
3024
3025 if (code === CHAR_LEFT_SQUARE_BRACKET) {
3026 while (eos() !== true && (next = advance())) {
3027 if (next === CHAR_BACKWARD_SLASH) {
3028 backslashes = token.backslashes = true;
3029 advance();
3030 continue;
3031 }
3032
3033 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
3034 isBracket = token.isBracket = true;
3035 isGlob = token.isGlob = true;
3036 finished = true;
3037 break;
3038 }
3039 }
3040
3041 if (scanToEnd === true) {
3042 continue;
3043 }
3044
3045 break;
3046 }
3047
3048 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
3049 negated = token.negated = true;
3050 start++;
3051 continue;
3052 }
3053
3054 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
3055 isGlob = token.isGlob = true;
3056
3057 if (scanToEnd === true) {
3058 while (eos() !== true && (code = advance())) {
3059 if (code === CHAR_LEFT_PARENTHESES) {
3060 backslashes = token.backslashes = true;
3061 code = advance();
3062 continue;
3063 }
3064
3065 if (code === CHAR_RIGHT_PARENTHESES) {
3066 finished = true;
3067 break;
3068 }
3069 }
3070 continue;
3071 }
3072 break;
3073 }
3074
3075 if (isGlob === true) {
3076 finished = true;
3077
3078 if (scanToEnd === true) {
3079 continue;
3080 }
3081
3082 break;
3083 }
3084 }
3085
3086 if (opts.noext === true) {
3087 isExtglob = false;
3088 isGlob = false;
3089 }
3090
3091 let base = str;
3092 let prefix = '';
3093 let glob = '';
3094
3095 if (start > 0) {
3096 prefix = str.slice(0, start);
3097 str = str.slice(start);
3098 lastIndex -= start;
3099 }
3100
3101 if (base && isGlob === true && lastIndex > 0) {
3102 base = str.slice(0, lastIndex);
3103 glob = str.slice(lastIndex);
3104 } else if (isGlob === true) {
3105 base = '';
3106 glob = str;
3107 } else {
3108 base = str;
3109 }
3110
3111 if (base && base !== '' && base !== '/' && base !== str) {
3112 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
3113 base = base.slice(0, -1);
3114 }
3115 }
3116
3117 if (opts.unescape === true) {
3118 if (glob) glob = utils$2.removeBackslashes(glob);
3119
3120 if (base && backslashes === true) {
3121 base = utils$2.removeBackslashes(base);
3122 }
3123 }
3124
3125 const state = {
3126 prefix,
3127 input,
3128 start,
3129 base,
3130 glob,
3131 isBrace,
3132 isBracket,
3133 isGlob,
3134 isExtglob,
3135 isGlobstar,
3136 negated,
3137 negatedExtglob
3138 };
3139
3140 if (opts.tokens === true) {
3141 state.maxDepth = 0;
3142 if (!isPathSeparator(code)) {
3143 tokens.push(token);
3144 }
3145 state.tokens = tokens;
3146 }
3147
3148 if (opts.parts === true || opts.tokens === true) {
3149 let prevIndex;
3150
3151 for (let idx = 0; idx < slashes.length; idx++) {
3152 const n = prevIndex ? prevIndex + 1 : start;
3153 const i = slashes[idx];
3154 const value = input.slice(n, i);
3155 if (opts.tokens) {
3156 if (idx === 0 && start !== 0) {
3157 tokens[idx].isPrefix = true;
3158 tokens[idx].value = prefix;
3159 } else {
3160 tokens[idx].value = value;
3161 }
3162 depth(tokens[idx]);
3163 state.maxDepth += tokens[idx].depth;
3164 }
3165 if (idx !== 0 || value !== '') {
3166 parts.push(value);
3167 }
3168 prevIndex = i;
3169 }
3170
3171 if (prevIndex && prevIndex + 1 < input.length) {
3172 const value = input.slice(prevIndex + 1);
3173 parts.push(value);
3174
3175 if (opts.tokens) {
3176 tokens[tokens.length - 1].value = value;
3177 depth(tokens[tokens.length - 1]);
3178 state.maxDepth += tokens[tokens.length - 1].depth;
3179 }
3180 }
3181
3182 state.slashes = slashes;
3183 state.parts = parts;
3184 }
3185
3186 return state;
3187};
3188
3189var scan_1 = scan$1;
3190
3191const constants$1 = constants$2;
3192const utils$1 = utils$3;
3193
3194/**
3195 * Constants
3196 */
3197
3198const {
3199 MAX_LENGTH,
3200 POSIX_REGEX_SOURCE,
3201 REGEX_NON_SPECIAL_CHARS,
3202 REGEX_SPECIAL_CHARS_BACKREF,
3203 REPLACEMENTS
3204} = constants$1;
3205
3206/**
3207 * Helpers
3208 */
3209
3210const expandRange = (args, options) => {
3211 if (typeof options.expandRange === 'function') {
3212 return options.expandRange(...args, options);
3213 }
3214
3215 args.sort();
3216 const value = `[${args.join('-')}]`;
3217
3218 return value;
3219};
3220
3221/**
3222 * Create the message for a syntax error
3223 */
3224
3225const syntaxError = (type, char) => {
3226 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
3227};
3228
3229/**
3230 * Parse the given input string.
3231 * @param {String} input
3232 * @param {Object} options
3233 * @return {Object}
3234 */
3235
3236const parse$1 = (input, options) => {
3237 if (typeof input !== 'string') {
3238 throw new TypeError('Expected a string');
3239 }
3240
3241 input = REPLACEMENTS[input] || input;
3242
3243 const opts = { ...options };
3244 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
3245
3246 let len = input.length;
3247 if (len > max) {
3248 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
3249 }
3250
3251 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
3252 const tokens = [bos];
3253
3254 const capture = opts.capture ? '' : '?:';
3255 const win32 = utils$1.isWindows(options);
3256
3257 // create constants based on platform, for windows or posix
3258 const PLATFORM_CHARS = constants$1.globChars(win32);
3259 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
3260
3261 const {
3262 DOT_LITERAL,
3263 PLUS_LITERAL,
3264 SLASH_LITERAL,
3265 ONE_CHAR,
3266 DOTS_SLASH,
3267 NO_DOT,
3268 NO_DOT_SLASH,
3269 NO_DOTS_SLASH,
3270 QMARK,
3271 QMARK_NO_DOT,
3272 STAR,
3273 START_ANCHOR
3274 } = PLATFORM_CHARS;
3275
3276 const globstar = opts => {
3277 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
3278 };
3279
3280 const nodot = opts.dot ? '' : NO_DOT;
3281 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
3282 let star = opts.bash === true ? globstar(opts) : STAR;
3283
3284 if (opts.capture) {
3285 star = `(${star})`;
3286 }
3287
3288 // minimatch options support
3289 if (typeof opts.noext === 'boolean') {
3290 opts.noextglob = opts.noext;
3291 }
3292
3293 const state = {
3294 input,
3295 index: -1,
3296 start: 0,
3297 dot: opts.dot === true,
3298 consumed: '',
3299 output: '',
3300 prefix: '',
3301 backtrack: false,
3302 negated: false,
3303 brackets: 0,
3304 braces: 0,
3305 parens: 0,
3306 quotes: 0,
3307 globstar: false,
3308 tokens
3309 };
3310
3311 input = utils$1.removePrefix(input, state);
3312 len = input.length;
3313
3314 const extglobs = [];
3315 const braces = [];
3316 const stack = [];
3317 let prev = bos;
3318 let value;
3319
3320 /**
3321 * Tokenizing helpers
3322 */
3323
3324 const eos = () => state.index === len - 1;
3325 const peek = state.peek = (n = 1) => input[state.index + n];
3326 const advance = state.advance = () => input[++state.index] || '';
3327 const remaining = () => input.slice(state.index + 1);
3328 const consume = (value = '', num = 0) => {
3329 state.consumed += value;
3330 state.index += num;
3331 };
3332
3333 const append = token => {
3334 state.output += token.output != null ? token.output : token.value;
3335 consume(token.value);
3336 };
3337
3338 const negate = () => {
3339 let count = 1;
3340
3341 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
3342 advance();
3343 state.start++;
3344 count++;
3345 }
3346
3347 if (count % 2 === 0) {
3348 return false;
3349 }
3350
3351 state.negated = true;
3352 state.start++;
3353 return true;
3354 };
3355
3356 const increment = type => {
3357 state[type]++;
3358 stack.push(type);
3359 };
3360
3361 const decrement = type => {
3362 state[type]--;
3363 stack.pop();
3364 };
3365
3366 /**
3367 * Push tokens onto the tokens array. This helper speeds up
3368 * tokenizing by 1) helping us avoid backtracking as much as possible,
3369 * and 2) helping us avoid creating extra tokens when consecutive
3370 * characters are plain text. This improves performance and simplifies
3371 * lookbehinds.
3372 */
3373
3374 const push = tok => {
3375 if (prev.type === 'globstar') {
3376 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
3377 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
3378
3379 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
3380 state.output = state.output.slice(0, -prev.output.length);
3381 prev.type = 'star';
3382 prev.value = '*';
3383 prev.output = star;
3384 state.output += prev.output;
3385 }
3386 }
3387
3388 if (extglobs.length && tok.type !== 'paren') {
3389 extglobs[extglobs.length - 1].inner += tok.value;
3390 }
3391
3392 if (tok.value || tok.output) append(tok);
3393 if (prev && prev.type === 'text' && tok.type === 'text') {
3394 prev.value += tok.value;
3395 prev.output = (prev.output || '') + tok.value;
3396 return;
3397 }
3398
3399 tok.prev = prev;
3400 tokens.push(tok);
3401 prev = tok;
3402 };
3403
3404 const extglobOpen = (type, value) => {
3405 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
3406
3407 token.prev = prev;
3408 token.parens = state.parens;
3409 token.output = state.output;
3410 const output = (opts.capture ? '(' : '') + token.open;
3411
3412 increment('parens');
3413 push({ type, value, output: state.output ? '' : ONE_CHAR });
3414 push({ type: 'paren', extglob: true, value: advance(), output });
3415 extglobs.push(token);
3416 };
3417
3418 const extglobClose = token => {
3419 let output = token.close + (opts.capture ? ')' : '');
3420 let rest;
3421
3422 if (token.type === 'negate') {
3423 let extglobStar = star;
3424
3425 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
3426 extglobStar = globstar(opts);
3427 }
3428
3429 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
3430 output = token.close = `)$))${extglobStar}`;
3431 }
3432
3433 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
3434 // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
3435 // In this case, we need to parse the string and use it in the output of the original pattern.
3436 // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
3437 //
3438 // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
3439 const expression = parse$1(rest, { ...options, fastpaths: false }).output;
3440
3441 output = token.close = `)${expression})${extglobStar})`;
3442 }
3443
3444 if (token.prev.type === 'bos') {
3445 state.negatedExtglob = true;
3446 }
3447 }
3448
3449 push({ type: 'paren', extglob: true, value, output });
3450 decrement('parens');
3451 };
3452
3453 /**
3454 * Fast paths
3455 */
3456
3457 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
3458 let backslashes = false;
3459
3460 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
3461 if (first === '\\') {
3462 backslashes = true;
3463 return m;
3464 }
3465
3466 if (first === '?') {
3467 if (esc) {
3468 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
3469 }
3470 if (index === 0) {
3471 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
3472 }
3473 return QMARK.repeat(chars.length);
3474 }
3475
3476 if (first === '.') {
3477 return DOT_LITERAL.repeat(chars.length);
3478 }
3479
3480 if (first === '*') {
3481 if (esc) {
3482 return esc + first + (rest ? star : '');
3483 }
3484 return star;
3485 }
3486 return esc ? m : `\\${m}`;
3487 });
3488
3489 if (backslashes === true) {
3490 if (opts.unescape === true) {
3491 output = output.replace(/\\/g, '');
3492 } else {
3493 output = output.replace(/\\+/g, m => {
3494 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
3495 });
3496 }
3497 }
3498
3499 if (output === input && opts.contains === true) {
3500 state.output = input;
3501 return state;
3502 }
3503
3504 state.output = utils$1.wrapOutput(output, state, options);
3505 return state;
3506 }
3507
3508 /**
3509 * Tokenize input until we reach end-of-string
3510 */
3511
3512 while (!eos()) {
3513 value = advance();
3514
3515 if (value === '\u0000') {
3516 continue;
3517 }
3518
3519 /**
3520 * Escaped characters
3521 */
3522
3523 if (value === '\\') {
3524 const next = peek();
3525
3526 if (next === '/' && opts.bash !== true) {
3527 continue;
3528 }
3529
3530 if (next === '.' || next === ';') {
3531 continue;
3532 }
3533
3534 if (!next) {
3535 value += '\\';
3536 push({ type: 'text', value });
3537 continue;
3538 }
3539
3540 // collapse slashes to reduce potential for exploits
3541 const match = /^\\+/.exec(remaining());
3542 let slashes = 0;
3543
3544 if (match && match[0].length > 2) {
3545 slashes = match[0].length;
3546 state.index += slashes;
3547 if (slashes % 2 !== 0) {
3548 value += '\\';
3549 }
3550 }
3551
3552 if (opts.unescape === true) {
3553 value = advance();
3554 } else {
3555 value += advance();
3556 }
3557
3558 if (state.brackets === 0) {
3559 push({ type: 'text', value });
3560 continue;
3561 }
3562 }
3563
3564 /**
3565 * If we're inside a regex character class, continue
3566 * until we reach the closing bracket.
3567 */
3568
3569 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
3570 if (opts.posix !== false && value === ':') {
3571 const inner = prev.value.slice(1);
3572 if (inner.includes('[')) {
3573 prev.posix = true;
3574
3575 if (inner.includes(':')) {
3576 const idx = prev.value.lastIndexOf('[');
3577 const pre = prev.value.slice(0, idx);
3578 const rest = prev.value.slice(idx + 2);
3579 const posix = POSIX_REGEX_SOURCE[rest];
3580 if (posix) {
3581 prev.value = pre + posix;
3582 state.backtrack = true;
3583 advance();
3584
3585 if (!bos.output && tokens.indexOf(prev) === 1) {
3586 bos.output = ONE_CHAR;
3587 }
3588 continue;
3589 }
3590 }
3591 }
3592 }
3593
3594 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
3595 value = `\\${value}`;
3596 }
3597
3598 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
3599 value = `\\${value}`;
3600 }
3601
3602 if (opts.posix === true && value === '!' && prev.value === '[') {
3603 value = '^';
3604 }
3605
3606 prev.value += value;
3607 append({ value });
3608 continue;
3609 }
3610
3611 /**
3612 * If we're inside a quoted string, continue
3613 * until we reach the closing double quote.
3614 */
3615
3616 if (state.quotes === 1 && value !== '"') {
3617 value = utils$1.escapeRegex(value);
3618 prev.value += value;
3619 append({ value });
3620 continue;
3621 }
3622
3623 /**
3624 * Double quotes
3625 */
3626
3627 if (value === '"') {
3628 state.quotes = state.quotes === 1 ? 0 : 1;
3629 if (opts.keepQuotes === true) {
3630 push({ type: 'text', value });
3631 }
3632 continue;
3633 }
3634
3635 /**
3636 * Parentheses
3637 */
3638
3639 if (value === '(') {
3640 increment('parens');
3641 push({ type: 'paren', value });
3642 continue;
3643 }
3644
3645 if (value === ')') {
3646 if (state.parens === 0 && opts.strictBrackets === true) {
3647 throw new SyntaxError(syntaxError('opening', '('));
3648 }
3649
3650 const extglob = extglobs[extglobs.length - 1];
3651 if (extglob && state.parens === extglob.parens + 1) {
3652 extglobClose(extglobs.pop());
3653 continue;
3654 }
3655
3656 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
3657 decrement('parens');
3658 continue;
3659 }
3660
3661 /**
3662 * Square brackets
3663 */
3664
3665 if (value === '[') {
3666 if (opts.nobracket === true || !remaining().includes(']')) {
3667 if (opts.nobracket !== true && opts.strictBrackets === true) {
3668 throw new SyntaxError(syntaxError('closing', ']'));
3669 }
3670
3671 value = `\\${value}`;
3672 } else {
3673 increment('brackets');
3674 }
3675
3676 push({ type: 'bracket', value });
3677 continue;
3678 }
3679
3680 if (value === ']') {
3681 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
3682 push({ type: 'text', value, output: `\\${value}` });
3683 continue;
3684 }
3685
3686 if (state.brackets === 0) {
3687 if (opts.strictBrackets === true) {
3688 throw new SyntaxError(syntaxError('opening', '['));
3689 }
3690
3691 push({ type: 'text', value, output: `\\${value}` });
3692 continue;
3693 }
3694
3695 decrement('brackets');
3696
3697 const prevValue = prev.value.slice(1);
3698 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
3699 value = `/${value}`;
3700 }
3701
3702 prev.value += value;
3703 append({ value });
3704
3705 // when literal brackets are explicitly disabled
3706 // assume we should match with a regex character class
3707 if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
3708 continue;
3709 }
3710
3711 const escaped = utils$1.escapeRegex(prev.value);
3712 state.output = state.output.slice(0, -prev.value.length);
3713
3714 // when literal brackets are explicitly enabled
3715 // assume we should escape the brackets to match literal characters
3716 if (opts.literalBrackets === true) {
3717 state.output += escaped;
3718 prev.value = escaped;
3719 continue;
3720 }
3721
3722 // when the user specifies nothing, try to match both
3723 prev.value = `(${capture}${escaped}|${prev.value})`;
3724 state.output += prev.value;
3725 continue;
3726 }
3727
3728 /**
3729 * Braces
3730 */
3731
3732 if (value === '{' && opts.nobrace !== true) {
3733 increment('braces');
3734
3735 const open = {
3736 type: 'brace',
3737 value,
3738 output: '(',
3739 outputIndex: state.output.length,
3740 tokensIndex: state.tokens.length
3741 };
3742
3743 braces.push(open);
3744 push(open);
3745 continue;
3746 }
3747
3748 if (value === '}') {
3749 const brace = braces[braces.length - 1];
3750
3751 if (opts.nobrace === true || !brace) {
3752 push({ type: 'text', value, output: value });
3753 continue;
3754 }
3755
3756 let output = ')';
3757
3758 if (brace.dots === true) {
3759 const arr = tokens.slice();
3760 const range = [];
3761
3762 for (let i = arr.length - 1; i >= 0; i--) {
3763 tokens.pop();
3764 if (arr[i].type === 'brace') {
3765 break;
3766 }
3767 if (arr[i].type !== 'dots') {
3768 range.unshift(arr[i].value);
3769 }
3770 }
3771
3772 output = expandRange(range, opts);
3773 state.backtrack = true;
3774 }
3775
3776 if (brace.comma !== true && brace.dots !== true) {
3777 const out = state.output.slice(0, brace.outputIndex);
3778 const toks = state.tokens.slice(brace.tokensIndex);
3779 brace.value = brace.output = '\\{';
3780 value = output = '\\}';
3781 state.output = out;
3782 for (const t of toks) {
3783 state.output += (t.output || t.value);
3784 }
3785 }
3786
3787 push({ type: 'brace', value, output });
3788 decrement('braces');
3789 braces.pop();
3790 continue;
3791 }
3792
3793 /**
3794 * Pipes
3795 */
3796
3797 if (value === '|') {
3798 if (extglobs.length > 0) {
3799 extglobs[extglobs.length - 1].conditions++;
3800 }
3801 push({ type: 'text', value });
3802 continue;
3803 }
3804
3805 /**
3806 * Commas
3807 */
3808
3809 if (value === ',') {
3810 let output = value;
3811
3812 const brace = braces[braces.length - 1];
3813 if (brace && stack[stack.length - 1] === 'braces') {
3814 brace.comma = true;
3815 output = '|';
3816 }
3817
3818 push({ type: 'comma', value, output });
3819 continue;
3820 }
3821
3822 /**
3823 * Slashes
3824 */
3825
3826 if (value === '/') {
3827 // if the beginning of the glob is "./", advance the start
3828 // to the current index, and don't add the "./" characters
3829 // to the state. This greatly simplifies lookbehinds when
3830 // checking for BOS characters like "!" and "." (not "./")
3831 if (prev.type === 'dot' && state.index === state.start + 1) {
3832 state.start = state.index + 1;
3833 state.consumed = '';
3834 state.output = '';
3835 tokens.pop();
3836 prev = bos; // reset "prev" to the first token
3837 continue;
3838 }
3839
3840 push({ type: 'slash', value, output: SLASH_LITERAL });
3841 continue;
3842 }
3843
3844 /**
3845 * Dots
3846 */
3847
3848 if (value === '.') {
3849 if (state.braces > 0 && prev.type === 'dot') {
3850 if (prev.value === '.') prev.output = DOT_LITERAL;
3851 const brace = braces[braces.length - 1];
3852 prev.type = 'dots';
3853 prev.output += value;
3854 prev.value += value;
3855 brace.dots = true;
3856 continue;
3857 }
3858
3859 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
3860 push({ type: 'text', value, output: DOT_LITERAL });
3861 continue;
3862 }
3863
3864 push({ type: 'dot', value, output: DOT_LITERAL });
3865 continue;
3866 }
3867
3868 /**
3869 * Question marks
3870 */
3871
3872 if (value === '?') {
3873 const isGroup = prev && prev.value === '(';
3874 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3875 extglobOpen('qmark', value);
3876 continue;
3877 }
3878
3879 if (prev && prev.type === 'paren') {
3880 const next = peek();
3881 let output = value;
3882
3883 if (next === '<' && !utils$1.supportsLookbehinds()) {
3884 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
3885 }
3886
3887 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
3888 output = `\\${value}`;
3889 }
3890
3891 push({ type: 'text', value, output });
3892 continue;
3893 }
3894
3895 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
3896 push({ type: 'qmark', value, output: QMARK_NO_DOT });
3897 continue;
3898 }
3899
3900 push({ type: 'qmark', value, output: QMARK });
3901 continue;
3902 }
3903
3904 /**
3905 * Exclamation
3906 */
3907
3908 if (value === '!') {
3909 if (opts.noextglob !== true && peek() === '(') {
3910 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
3911 extglobOpen('negate', value);
3912 continue;
3913 }
3914 }
3915
3916 if (opts.nonegate !== true && state.index === 0) {
3917 negate();
3918 continue;
3919 }
3920 }
3921
3922 /**
3923 * Plus
3924 */
3925
3926 if (value === '+') {
3927 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3928 extglobOpen('plus', value);
3929 continue;
3930 }
3931
3932 if ((prev && prev.value === '(') || opts.regex === false) {
3933 push({ type: 'plus', value, output: PLUS_LITERAL });
3934 continue;
3935 }
3936
3937 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
3938 push({ type: 'plus', value });
3939 continue;
3940 }
3941
3942 push({ type: 'plus', value: PLUS_LITERAL });
3943 continue;
3944 }
3945
3946 /**
3947 * Plain text
3948 */
3949
3950 if (value === '@') {
3951 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
3952 push({ type: 'at', extglob: true, value, output: '' });
3953 continue;
3954 }
3955
3956 push({ type: 'text', value });
3957 continue;
3958 }
3959
3960 /**
3961 * Plain text
3962 */
3963
3964 if (value !== '*') {
3965 if (value === '$' || value === '^') {
3966 value = `\\${value}`;
3967 }
3968
3969 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
3970 if (match) {
3971 value += match[0];
3972 state.index += match[0].length;
3973 }
3974
3975 push({ type: 'text', value });
3976 continue;
3977 }
3978
3979 /**
3980 * Stars
3981 */
3982
3983 if (prev && (prev.type === 'globstar' || prev.star === true)) {
3984 prev.type = 'star';
3985 prev.star = true;
3986 prev.value += value;
3987 prev.output = star;
3988 state.backtrack = true;
3989 state.globstar = true;
3990 consume(value);
3991 continue;
3992 }
3993
3994 let rest = remaining();
3995 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
3996 extglobOpen('star', value);
3997 continue;
3998 }
3999
4000 if (prev.type === 'star') {
4001 if (opts.noglobstar === true) {
4002 consume(value);
4003 continue;
4004 }
4005
4006 const prior = prev.prev;
4007 const before = prior.prev;
4008 const isStart = prior.type === 'slash' || prior.type === 'bos';
4009 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
4010
4011 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
4012 push({ type: 'star', value, output: '' });
4013 continue;
4014 }
4015
4016 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
4017 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
4018 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
4019 push({ type: 'star', value, output: '' });
4020 continue;
4021 }
4022
4023 // strip consecutive `/**/`
4024 while (rest.slice(0, 3) === '/**') {
4025 const after = input[state.index + 4];
4026 if (after && after !== '/') {
4027 break;
4028 }
4029 rest = rest.slice(3);
4030 consume('/**', 3);
4031 }
4032
4033 if (prior.type === 'bos' && eos()) {
4034 prev.type = 'globstar';
4035 prev.value += value;
4036 prev.output = globstar(opts);
4037 state.output = prev.output;
4038 state.globstar = true;
4039 consume(value);
4040 continue;
4041 }
4042
4043 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
4044 state.output = state.output.slice(0, -(prior.output + prev.output).length);
4045 prior.output = `(?:${prior.output}`;
4046
4047 prev.type = 'globstar';
4048 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
4049 prev.value += value;
4050 state.globstar = true;
4051 state.output += prior.output + prev.output;
4052 consume(value);
4053 continue;
4054 }
4055
4056 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
4057 const end = rest[1] !== void 0 ? '|$' : '';
4058
4059 state.output = state.output.slice(0, -(prior.output + prev.output).length);
4060 prior.output = `(?:${prior.output}`;
4061
4062 prev.type = 'globstar';
4063 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
4064 prev.value += value;
4065
4066 state.output += prior.output + prev.output;
4067 state.globstar = true;
4068
4069 consume(value + advance());
4070
4071 push({ type: 'slash', value: '/', output: '' });
4072 continue;
4073 }
4074
4075 if (prior.type === 'bos' && rest[0] === '/') {
4076 prev.type = 'globstar';
4077 prev.value += value;
4078 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
4079 state.output = prev.output;
4080 state.globstar = true;
4081 consume(value + advance());
4082 push({ type: 'slash', value: '/', output: '' });
4083 continue;
4084 }
4085
4086 // remove single star from output
4087 state.output = state.output.slice(0, -prev.output.length);
4088
4089 // reset previous token to globstar
4090 prev.type = 'globstar';
4091 prev.output = globstar(opts);
4092 prev.value += value;
4093
4094 // reset output with globstar
4095 state.output += prev.output;
4096 state.globstar = true;
4097 consume(value);
4098 continue;
4099 }
4100
4101 const token = { type: 'star', value, output: star };
4102
4103 if (opts.bash === true) {
4104 token.output = '.*?';
4105 if (prev.type === 'bos' || prev.type === 'slash') {
4106 token.output = nodot + token.output;
4107 }
4108 push(token);
4109 continue;
4110 }
4111
4112 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
4113 token.output = value;
4114 push(token);
4115 continue;
4116 }
4117
4118 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
4119 if (prev.type === 'dot') {
4120 state.output += NO_DOT_SLASH;
4121 prev.output += NO_DOT_SLASH;
4122
4123 } else if (opts.dot === true) {
4124 state.output += NO_DOTS_SLASH;
4125 prev.output += NO_DOTS_SLASH;
4126
4127 } else {
4128 state.output += nodot;
4129 prev.output += nodot;
4130 }
4131
4132 if (peek() !== '*') {
4133 state.output += ONE_CHAR;
4134 prev.output += ONE_CHAR;
4135 }
4136 }
4137
4138 push(token);
4139 }
4140
4141 while (state.brackets > 0) {
4142 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
4143 state.output = utils$1.escapeLast(state.output, '[');
4144 decrement('brackets');
4145 }
4146
4147 while (state.parens > 0) {
4148 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
4149 state.output = utils$1.escapeLast(state.output, '(');
4150 decrement('parens');
4151 }
4152
4153 while (state.braces > 0) {
4154 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
4155 state.output = utils$1.escapeLast(state.output, '{');
4156 decrement('braces');
4157 }
4158
4159 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
4160 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
4161 }
4162
4163 // rebuild the output if we had to backtrack at any point
4164 if (state.backtrack === true) {
4165 state.output = '';
4166
4167 for (const token of state.tokens) {
4168 state.output += token.output != null ? token.output : token.value;
4169
4170 if (token.suffix) {
4171 state.output += token.suffix;
4172 }
4173 }
4174 }
4175
4176 return state;
4177};
4178
4179/**
4180 * Fast paths for creating regular expressions for common glob patterns.
4181 * This can significantly speed up processing and has very little downside
4182 * impact when none of the fast paths match.
4183 */
4184
4185parse$1.fastpaths = (input, options) => {
4186 const opts = { ...options };
4187 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
4188 const len = input.length;
4189 if (len > max) {
4190 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
4191 }
4192
4193 input = REPLACEMENTS[input] || input;
4194 const win32 = utils$1.isWindows(options);
4195
4196 // create constants based on platform, for windows or posix
4197 const {
4198 DOT_LITERAL,
4199 SLASH_LITERAL,
4200 ONE_CHAR,
4201 DOTS_SLASH,
4202 NO_DOT,
4203 NO_DOTS,
4204 NO_DOTS_SLASH,
4205 STAR,
4206 START_ANCHOR
4207 } = constants$1.globChars(win32);
4208
4209 const nodot = opts.dot ? NO_DOTS : NO_DOT;
4210 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
4211 const capture = opts.capture ? '' : '?:';
4212 const state = { negated: false, prefix: '' };
4213 let star = opts.bash === true ? '.*?' : STAR;
4214
4215 if (opts.capture) {
4216 star = `(${star})`;
4217 }
4218
4219 const globstar = opts => {
4220 if (opts.noglobstar === true) return star;
4221 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
4222 };
4223
4224 const create = str => {
4225 switch (str) {
4226 case '*':
4227 return `${nodot}${ONE_CHAR}${star}`;
4228
4229 case '.*':
4230 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
4231
4232 case '*.*':
4233 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4234
4235 case '*/*':
4236 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
4237
4238 case '**':
4239 return nodot + globstar(opts);
4240
4241 case '**/*':
4242 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
4243
4244 case '**/*.*':
4245 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
4246
4247 case '**/.*':
4248 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
4249
4250 default: {
4251 const match = /^(.*?)\.(\w+)$/.exec(str);
4252 if (!match) return;
4253
4254 const source = create(match[1]);
4255 if (!source) return;
4256
4257 return source + DOT_LITERAL + match[2];
4258 }
4259 }
4260 };
4261
4262 const output = utils$1.removePrefix(input, state);
4263 let source = create(output);
4264
4265 if (source && opts.strictSlashes !== true) {
4266 source += `${SLASH_LITERAL}?`;
4267 }
4268
4269 return source;
4270};
4271
4272var parse_1 = parse$1;
4273
4274const path = require$$0;
4275const scan = scan_1;
4276const parse = parse_1;
4277const utils = utils$3;
4278const constants = constants$2;
4279const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
4280
4281/**
4282 * Creates a matcher function from one or more glob patterns. The
4283 * returned function takes a string to match as its first argument,
4284 * and returns true if the string is a match. The returned matcher
4285 * function also takes a boolean as the second argument that, when true,
4286 * returns an object with additional information.
4287 *
4288 * ```js
4289 * const picomatch = require('picomatch');
4290 * // picomatch(glob[, options]);
4291 *
4292 * const isMatch = picomatch('*.!(*a)');
4293 * console.log(isMatch('a.a')); //=> false
4294 * console.log(isMatch('a.b')); //=> true
4295 * ```
4296 * @name picomatch
4297 * @param {String|Array} `globs` One or more glob patterns.
4298 * @param {Object=} `options`
4299 * @return {Function=} Returns a matcher function.
4300 * @api public
4301 */
4302
4303const picomatch = (glob, options, returnState = false) => {
4304 if (Array.isArray(glob)) {
4305 const fns = glob.map(input => picomatch(input, options, returnState));
4306 const arrayMatcher = str => {
4307 for (const isMatch of fns) {
4308 const state = isMatch(str);
4309 if (state) return state;
4310 }
4311 return false;
4312 };
4313 return arrayMatcher;
4314 }
4315
4316 const isState = isObject(glob) && glob.tokens && glob.input;
4317
4318 if (glob === '' || (typeof glob !== 'string' && !isState)) {
4319 throw new TypeError('Expected pattern to be a non-empty string');
4320 }
4321
4322 const opts = options || {};
4323 const posix = utils.isWindows(options);
4324 const regex = isState
4325 ? picomatch.compileRe(glob, options)
4326 : picomatch.makeRe(glob, options, false, true);
4327
4328 const state = regex.state;
4329 delete regex.state;
4330
4331 let isIgnored = () => false;
4332 if (opts.ignore) {
4333 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
4334 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
4335 }
4336
4337 const matcher = (input, returnObject = false) => {
4338 const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
4339 const result = { glob, state, regex, posix, input, output, match, isMatch };
4340
4341 if (typeof opts.onResult === 'function') {
4342 opts.onResult(result);
4343 }
4344
4345 if (isMatch === false) {
4346 result.isMatch = false;
4347 return returnObject ? result : false;
4348 }
4349
4350 if (isIgnored(input)) {
4351 if (typeof opts.onIgnore === 'function') {
4352 opts.onIgnore(result);
4353 }
4354 result.isMatch = false;
4355 return returnObject ? result : false;
4356 }
4357
4358 if (typeof opts.onMatch === 'function') {
4359 opts.onMatch(result);
4360 }
4361 return returnObject ? result : true;
4362 };
4363
4364 if (returnState) {
4365 matcher.state = state;
4366 }
4367
4368 return matcher;
4369};
4370
4371/**
4372 * Test `input` with the given `regex`. This is used by the main
4373 * `picomatch()` function to test the input string.
4374 *
4375 * ```js
4376 * const picomatch = require('picomatch');
4377 * // picomatch.test(input, regex[, options]);
4378 *
4379 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
4380 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
4381 * ```
4382 * @param {String} `input` String to test.
4383 * @param {RegExp} `regex`
4384 * @return {Object} Returns an object with matching info.
4385 * @api public
4386 */
4387
4388picomatch.test = (input, regex, options, { glob, posix } = {}) => {
4389 if (typeof input !== 'string') {
4390 throw new TypeError('Expected input to be a string');
4391 }
4392
4393 if (input === '') {
4394 return { isMatch: false, output: '' };
4395 }
4396
4397 const opts = options || {};
4398 const format = opts.format || (posix ? utils.toPosixSlashes : null);
4399 let match = input === glob;
4400 let output = (match && format) ? format(input) : input;
4401
4402 if (match === false) {
4403 output = format ? format(input) : input;
4404 match = output === glob;
4405 }
4406
4407 if (match === false || opts.capture === true) {
4408 if (opts.matchBase === true || opts.basename === true) {
4409 match = picomatch.matchBase(input, regex, options, posix);
4410 } else {
4411 match = regex.exec(output);
4412 }
4413 }
4414
4415 return { isMatch: Boolean(match), match, output };
4416};
4417
4418/**
4419 * Match the basename of a filepath.
4420 *
4421 * ```js
4422 * const picomatch = require('picomatch');
4423 * // picomatch.matchBase(input, glob[, options]);
4424 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
4425 * ```
4426 * @param {String} `input` String to test.
4427 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
4428 * @return {Boolean}
4429 * @api public
4430 */
4431
4432picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
4433 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
4434 return regex.test(path.basename(input));
4435};
4436
4437/**
4438 * Returns true if **any** of the given glob `patterns` match the specified `string`.
4439 *
4440 * ```js
4441 * const picomatch = require('picomatch');
4442 * // picomatch.isMatch(string, patterns[, options]);
4443 *
4444 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
4445 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
4446 * ```
4447 * @param {String|Array} str The string to test.
4448 * @param {String|Array} patterns One or more glob patterns to use for matching.
4449 * @param {Object} [options] See available [options](#options).
4450 * @return {Boolean} Returns true if any patterns match `str`
4451 * @api public
4452 */
4453
4454picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
4455
4456/**
4457 * Parse a glob pattern to create the source string for a regular
4458 * expression.
4459 *
4460 * ```js
4461 * const picomatch = require('picomatch');
4462 * const result = picomatch.parse(pattern[, options]);
4463 * ```
4464 * @param {String} `pattern`
4465 * @param {Object} `options`
4466 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
4467 * @api public
4468 */
4469
4470picomatch.parse = (pattern, options) => {
4471 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
4472 return parse(pattern, { ...options, fastpaths: false });
4473};
4474
4475/**
4476 * Scan a glob pattern to separate the pattern into segments.
4477 *
4478 * ```js
4479 * const picomatch = require('picomatch');
4480 * // picomatch.scan(input[, options]);
4481 *
4482 * const result = picomatch.scan('!./foo/*.js');
4483 * console.log(result);
4484 * { prefix: '!./',
4485 * input: '!./foo/*.js',
4486 * start: 3,
4487 * base: 'foo',
4488 * glob: '*.js',
4489 * isBrace: false,
4490 * isBracket: false,
4491 * isGlob: true,
4492 * isExtglob: false,
4493 * isGlobstar: false,
4494 * negated: true }
4495 * ```
4496 * @param {String} `input` Glob pattern to scan.
4497 * @param {Object} `options`
4498 * @return {Object} Returns an object with
4499 * @api public
4500 */
4501
4502picomatch.scan = (input, options) => scan(input, options);
4503
4504/**
4505 * Compile a regular expression from the `state` object returned by the
4506 * [parse()](#parse) method.
4507 *
4508 * @param {Object} `state`
4509 * @param {Object} `options`
4510 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
4511 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
4512 * @return {RegExp}
4513 * @api public
4514 */
4515
4516picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
4517 if (returnOutput === true) {
4518 return state.output;
4519 }
4520
4521 const opts = options || {};
4522 const prepend = opts.contains ? '' : '^';
4523 const append = opts.contains ? '' : '$';
4524
4525 let source = `${prepend}(?:${state.output})${append}`;
4526 if (state && state.negated === true) {
4527 source = `^(?!${source}).*$`;
4528 }
4529
4530 const regex = picomatch.toRegex(source, options);
4531 if (returnState === true) {
4532 regex.state = state;
4533 }
4534
4535 return regex;
4536};
4537
4538/**
4539 * Create a regular expression from a parsed glob pattern.
4540 *
4541 * ```js
4542 * const picomatch = require('picomatch');
4543 * const state = picomatch.parse('*.js');
4544 * // picomatch.compileRe(state[, options]);
4545 *
4546 * console.log(picomatch.compileRe(state));
4547 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4548 * ```
4549 * @param {String} `state` The object returned from the `.parse` method.
4550 * @param {Object} `options`
4551 * @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.
4552 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
4553 * @return {RegExp} Returns a regex created from the given pattern.
4554 * @api public
4555 */
4556
4557picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
4558 if (!input || typeof input !== 'string') {
4559 throw new TypeError('Expected a non-empty string');
4560 }
4561
4562 let parsed = { negated: false, fastpaths: true };
4563
4564 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
4565 parsed.output = parse.fastpaths(input, options);
4566 }
4567
4568 if (!parsed.output) {
4569 parsed = parse(input, options);
4570 }
4571
4572 return picomatch.compileRe(parsed, options, returnOutput, returnState);
4573};
4574
4575/**
4576 * Create a regular expression from the given regex source string.
4577 *
4578 * ```js
4579 * const picomatch = require('picomatch');
4580 * // picomatch.toRegex(source[, options]);
4581 *
4582 * const { output } = picomatch.parse('*.js');
4583 * console.log(picomatch.toRegex(output));
4584 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
4585 * ```
4586 * @param {String} `source` Regular expression source string.
4587 * @param {Object} `options`
4588 * @return {RegExp}
4589 * @api public
4590 */
4591
4592picomatch.toRegex = (source, options) => {
4593 try {
4594 const opts = options || {};
4595 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
4596 } catch (err) {
4597 if (options && options.debug === true) throw err;
4598 return /$^/;
4599 }
4600};
4601
4602/**
4603 * Picomatch constants.
4604 * @return {Object}
4605 */
4606
4607picomatch.constants = constants;
4608
4609/**
4610 * Expose "picomatch"
4611 */
4612
4613var picomatch_1 = picomatch;
4614
4615(function (module) {
4616
4617 module.exports = picomatch_1;
4618} (picomatch$1));
4619
4620const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
4621
4622const extractors = {
4623 ArrayPattern(names, param) {
4624 for (const element of param.elements) {
4625 if (element)
4626 extractors[element.type](names, element);
4627 }
4628 },
4629 AssignmentPattern(names, param) {
4630 extractors[param.left.type](names, param.left);
4631 },
4632 Identifier(names, param) {
4633 names.push(param.name);
4634 },
4635 MemberExpression() { },
4636 ObjectPattern(names, param) {
4637 for (const prop of param.properties) {
4638 // @ts-ignore Typescript reports that this is not a valid type
4639 if (prop.type === 'RestElement') {
4640 extractors.RestElement(names, prop);
4641 }
4642 else {
4643 extractors[prop.value.type](names, prop.value);
4644 }
4645 }
4646 },
4647 RestElement(names, param) {
4648 extractors[param.argument.type](names, param.argument);
4649 }
4650};
4651const extractAssignedNames = function extractAssignedNames(param) {
4652 const names = [];
4653 extractors[param.type](names, param);
4654 return names;
4655};
4656
4657// Helper since Typescript can't detect readonly arrays with Array.isArray
4658function isArray$1(arg) {
4659 return Array.isArray(arg);
4660}
4661function ensureArray(thing) {
4662 if (isArray$1(thing))
4663 return thing;
4664 if (thing == null)
4665 return [];
4666 return [thing];
4667}
4668
4669const normalizePath = function normalizePath(filename) {
4670 return filename.split(require$$0.win32.sep).join(require$$0.posix.sep);
4671};
4672
4673function getMatcherString(id, resolutionBase) {
4674 if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('*')) {
4675 return normalizePath(id);
4676 }
4677 // resolve('') is valid and will default to process.cwd()
4678 const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
4679 // escape all possible (posix + win) path characters that might interfere with regex
4680 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
4681 // Note that we use posix.join because:
4682 // 1. the basePath has been normalized to use /
4683 // 2. the incoming glob (id) matcher, also uses /
4684 // otherwise Node will force backslash (\) on windows
4685 return require$$0.posix.join(basePath, normalizePath(id));
4686}
4687const createFilter = function createFilter(include, exclude, options) {
4688 const resolutionBase = options && options.resolve;
4689 const getMatcher = (id) => id instanceof RegExp
4690 ? id
4691 : {
4692 test: (what) => {
4693 // this refactor is a tad overly verbose but makes for easy debugging
4694 const pattern = getMatcherString(id, resolutionBase);
4695 const fn = pm(pattern, { dot: true });
4696 const result = fn(what);
4697 return result;
4698 }
4699 };
4700 const includeMatchers = ensureArray(include).map(getMatcher);
4701 const excludeMatchers = ensureArray(exclude).map(getMatcher);
4702 return function result(id) {
4703 if (typeof id !== 'string')
4704 return false;
4705 if (/\0/.test(id))
4706 return false;
4707 const pathId = normalizePath(id);
4708 for (let i = 0; i < excludeMatchers.length; ++i) {
4709 const matcher = excludeMatchers[i];
4710 if (matcher.test(pathId))
4711 return false;
4712 }
4713 for (let i = 0; i < includeMatchers.length; ++i) {
4714 const matcher = includeMatchers[i];
4715 if (matcher.test(pathId))
4716 return true;
4717 }
4718 return !includeMatchers.length;
4719 };
4720};
4721
4722const 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';
4723const 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';
4724const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
4725forbiddenIdentifiers.add('');
4726
4727const BROKEN_FLOW_NONE = 0;
4728const BROKEN_FLOW_BREAK_CONTINUE = 1;
4729const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
4730function createInclusionContext() {
4731 return {
4732 brokenFlow: BROKEN_FLOW_NONE,
4733 includedCallArguments: new Set(),
4734 includedLabels: new Set()
4735 };
4736}
4737function createHasEffectsContext() {
4738 return {
4739 accessed: new PathTracker(),
4740 assigned: new PathTracker(),
4741 brokenFlow: BROKEN_FLOW_NONE,
4742 called: new DiscriminatedPathTracker(),
4743 ignore: {
4744 breaks: false,
4745 continues: false,
4746 labels: new Set(),
4747 returnYield: false
4748 },
4749 includedLabels: new Set(),
4750 instantiated: new DiscriminatedPathTracker(),
4751 replacedVariableInits: new Map()
4752 };
4753}
4754
4755function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
4756 return Object.create(inheritedDescriptions, memberDescriptions);
4757}
4758const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
4759 getLiteralValueAtPath() {
4760 return undefined;
4761 }
4762})();
4763const returnsUnknown = {
4764 value: {
4765 hasEffectsWhenCalled: null,
4766 returns: UNKNOWN_EXPRESSION
4767 }
4768};
4769const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
4770 getReturnExpressionWhenCalledAtPath(path) {
4771 if (path.length === 1) {
4772 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
4773 }
4774 return UNKNOWN_EXPRESSION;
4775 }
4776 hasEffectsOnInteractionAtPath(path, interaction, context) {
4777 if (interaction.type === INTERACTION_ACCESSED) {
4778 return path.length > 1;
4779 }
4780 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4781 return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
4782 }
4783 return true;
4784 }
4785})();
4786const returnsBoolean = {
4787 value: {
4788 hasEffectsWhenCalled: null,
4789 returns: UNKNOWN_LITERAL_BOOLEAN
4790 }
4791};
4792const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
4793 getReturnExpressionWhenCalledAtPath(path) {
4794 if (path.length === 1) {
4795 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
4796 }
4797 return UNKNOWN_EXPRESSION;
4798 }
4799 hasEffectsOnInteractionAtPath(path, interaction, context) {
4800 if (interaction.type === INTERACTION_ACCESSED) {
4801 return path.length > 1;
4802 }
4803 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4804 return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
4805 }
4806 return true;
4807 }
4808})();
4809const returnsNumber = {
4810 value: {
4811 hasEffectsWhenCalled: null,
4812 returns: UNKNOWN_LITERAL_NUMBER
4813 }
4814};
4815const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
4816 getReturnExpressionWhenCalledAtPath(path) {
4817 if (path.length === 1) {
4818 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
4819 }
4820 return UNKNOWN_EXPRESSION;
4821 }
4822 hasEffectsOnInteractionAtPath(path, interaction, context) {
4823 if (interaction.type === INTERACTION_ACCESSED) {
4824 return path.length > 1;
4825 }
4826 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
4827 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
4828 }
4829 return true;
4830 }
4831})();
4832const returnsString = {
4833 value: {
4834 hasEffectsWhenCalled: null,
4835 returns: UNKNOWN_LITERAL_STRING
4836 }
4837};
4838const stringReplace = {
4839 value: {
4840 hasEffectsWhenCalled({ args }, context) {
4841 const arg1 = args[1];
4842 return (args.length < 2 ||
4843 (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4844 deoptimizeCache() { }
4845 }) === 'symbol' &&
4846 arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
4847 },
4848 returns: UNKNOWN_LITERAL_STRING
4849 }
4850};
4851const objectMembers = assembleMemberDescriptions({
4852 hasOwnProperty: returnsBoolean,
4853 isPrototypeOf: returnsBoolean,
4854 propertyIsEnumerable: returnsBoolean,
4855 toLocaleString: returnsString,
4856 toString: returnsString,
4857 valueOf: returnsUnknown
4858});
4859const literalBooleanMembers = assembleMemberDescriptions({
4860 valueOf: returnsBoolean
4861}, objectMembers);
4862const literalNumberMembers = assembleMemberDescriptions({
4863 toExponential: returnsString,
4864 toFixed: returnsString,
4865 toLocaleString: returnsString,
4866 toPrecision: returnsString,
4867 valueOf: returnsNumber
4868}, objectMembers);
4869const literalStringMembers = assembleMemberDescriptions({
4870 anchor: returnsString,
4871 at: returnsUnknown,
4872 big: returnsString,
4873 blink: returnsString,
4874 bold: returnsString,
4875 charAt: returnsString,
4876 charCodeAt: returnsNumber,
4877 codePointAt: returnsUnknown,
4878 concat: returnsString,
4879 endsWith: returnsBoolean,
4880 fixed: returnsString,
4881 fontcolor: returnsString,
4882 fontsize: returnsString,
4883 includes: returnsBoolean,
4884 indexOf: returnsNumber,
4885 italics: returnsString,
4886 lastIndexOf: returnsNumber,
4887 link: returnsString,
4888 localeCompare: returnsNumber,
4889 match: returnsUnknown,
4890 matchAll: returnsUnknown,
4891 normalize: returnsString,
4892 padEnd: returnsString,
4893 padStart: returnsString,
4894 repeat: returnsString,
4895 replace: stringReplace,
4896 replaceAll: stringReplace,
4897 search: returnsNumber,
4898 slice: returnsString,
4899 small: returnsString,
4900 split: returnsUnknown,
4901 startsWith: returnsBoolean,
4902 strike: returnsString,
4903 sub: returnsString,
4904 substr: returnsString,
4905 substring: returnsString,
4906 sup: returnsString,
4907 toLocaleLowerCase: returnsString,
4908 toLocaleUpperCase: returnsString,
4909 toLowerCase: returnsString,
4910 toString: returnsString,
4911 toUpperCase: returnsString,
4912 trim: returnsString,
4913 trimEnd: returnsString,
4914 trimLeft: returnsString,
4915 trimRight: returnsString,
4916 trimStart: returnsString,
4917 valueOf: returnsString
4918}, objectMembers);
4919function getLiteralMembersForValue(value) {
4920 switch (typeof value) {
4921 case 'boolean':
4922 return literalBooleanMembers;
4923 case 'number':
4924 return literalNumberMembers;
4925 case 'string':
4926 return literalStringMembers;
4927 }
4928 return Object.create(null);
4929}
4930function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
4931 var _a, _b;
4932 if (typeof memberName !== 'string' || !members[memberName]) {
4933 return true;
4934 }
4935 return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
4936}
4937function getMemberReturnExpressionWhenCalled(members, memberName) {
4938 if (typeof memberName !== 'string' || !members[memberName])
4939 return UNKNOWN_EXPRESSION;
4940 return members[memberName].returns;
4941}
4942
4943// AST walker module for Mozilla Parser API compatible trees
4944
4945function skipThrough(node, st, c) { c(node, st); }
4946function ignore(_node, _st, _c) {}
4947
4948// Node walkers.
4949
4950var base$1 = {};
4951
4952base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
4953 for (var i = 0, list = node.body; i < list.length; i += 1)
4954 {
4955 var stmt = list[i];
4956
4957 c(stmt, st, "Statement");
4958 }
4959};
4960base$1.Statement = skipThrough;
4961base$1.EmptyStatement = ignore;
4962base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
4963 function (node, st, c) { return c(node.expression, st, "Expression"); };
4964base$1.IfStatement = function (node, st, c) {
4965 c(node.test, st, "Expression");
4966 c(node.consequent, st, "Statement");
4967 if (node.alternate) { c(node.alternate, st, "Statement"); }
4968};
4969base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
4970base$1.BreakStatement = base$1.ContinueStatement = ignore;
4971base$1.WithStatement = function (node, st, c) {
4972 c(node.object, st, "Expression");
4973 c(node.body, st, "Statement");
4974};
4975base$1.SwitchStatement = function (node, st, c) {
4976 c(node.discriminant, st, "Expression");
4977 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
4978 var cs = list$1[i$1];
4979
4980 if (cs.test) { c(cs.test, st, "Expression"); }
4981 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
4982 {
4983 var cons = list[i];
4984
4985 c(cons, st, "Statement");
4986 }
4987 }
4988};
4989base$1.SwitchCase = function (node, st, c) {
4990 if (node.test) { c(node.test, st, "Expression"); }
4991 for (var i = 0, list = node.consequent; i < list.length; i += 1)
4992 {
4993 var cons = list[i];
4994
4995 c(cons, st, "Statement");
4996 }
4997};
4998base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
4999 if (node.argument) { c(node.argument, st, "Expression"); }
5000};
5001base$1.ThrowStatement = base$1.SpreadElement =
5002 function (node, st, c) { return c(node.argument, st, "Expression"); };
5003base$1.TryStatement = function (node, st, c) {
5004 c(node.block, st, "Statement");
5005 if (node.handler) { c(node.handler, st); }
5006 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
5007};
5008base$1.CatchClause = function (node, st, c) {
5009 if (node.param) { c(node.param, st, "Pattern"); }
5010 c(node.body, st, "Statement");
5011};
5012base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
5013 c(node.test, st, "Expression");
5014 c(node.body, st, "Statement");
5015};
5016base$1.ForStatement = function (node, st, c) {
5017 if (node.init) { c(node.init, st, "ForInit"); }
5018 if (node.test) { c(node.test, st, "Expression"); }
5019 if (node.update) { c(node.update, st, "Expression"); }
5020 c(node.body, st, "Statement");
5021};
5022base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
5023 c(node.left, st, "ForInit");
5024 c(node.right, st, "Expression");
5025 c(node.body, st, "Statement");
5026};
5027base$1.ForInit = function (node, st, c) {
5028 if (node.type === "VariableDeclaration") { c(node, st); }
5029 else { c(node, st, "Expression"); }
5030};
5031base$1.DebuggerStatement = ignore;
5032
5033base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
5034base$1.VariableDeclaration = function (node, st, c) {
5035 for (var i = 0, list = node.declarations; i < list.length; i += 1)
5036 {
5037 var decl = list[i];
5038
5039 c(decl, st);
5040 }
5041};
5042base$1.VariableDeclarator = function (node, st, c) {
5043 c(node.id, st, "Pattern");
5044 if (node.init) { c(node.init, st, "Expression"); }
5045};
5046
5047base$1.Function = function (node, st, c) {
5048 if (node.id) { c(node.id, st, "Pattern"); }
5049 for (var i = 0, list = node.params; i < list.length; i += 1)
5050 {
5051 var param = list[i];
5052
5053 c(param, st, "Pattern");
5054 }
5055 c(node.body, st, node.expression ? "Expression" : "Statement");
5056};
5057
5058base$1.Pattern = function (node, st, c) {
5059 if (node.type === "Identifier")
5060 { c(node, st, "VariablePattern"); }
5061 else if (node.type === "MemberExpression")
5062 { c(node, st, "MemberPattern"); }
5063 else
5064 { c(node, st); }
5065};
5066base$1.VariablePattern = ignore;
5067base$1.MemberPattern = skipThrough;
5068base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
5069base$1.ArrayPattern = function (node, st, c) {
5070 for (var i = 0, list = node.elements; i < list.length; i += 1) {
5071 var elt = list[i];
5072
5073 if (elt) { c(elt, st, "Pattern"); }
5074 }
5075};
5076base$1.ObjectPattern = function (node, st, c) {
5077 for (var i = 0, list = node.properties; i < list.length; i += 1) {
5078 var prop = list[i];
5079
5080 if (prop.type === "Property") {
5081 if (prop.computed) { c(prop.key, st, "Expression"); }
5082 c(prop.value, st, "Pattern");
5083 } else if (prop.type === "RestElement") {
5084 c(prop.argument, st, "Pattern");
5085 }
5086 }
5087};
5088
5089base$1.Expression = skipThrough;
5090base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
5091base$1.ArrayExpression = function (node, st, c) {
5092 for (var i = 0, list = node.elements; i < list.length; i += 1) {
5093 var elt = list[i];
5094
5095 if (elt) { c(elt, st, "Expression"); }
5096 }
5097};
5098base$1.ObjectExpression = function (node, st, c) {
5099 for (var i = 0, list = node.properties; i < list.length; i += 1)
5100 {
5101 var prop = list[i];
5102
5103 c(prop, st);
5104 }
5105};
5106base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
5107base$1.SequenceExpression = function (node, st, c) {
5108 for (var i = 0, list = node.expressions; i < list.length; i += 1)
5109 {
5110 var expr = list[i];
5111
5112 c(expr, st, "Expression");
5113 }
5114};
5115base$1.TemplateLiteral = function (node, st, c) {
5116 for (var i = 0, list = node.quasis; i < list.length; i += 1)
5117 {
5118 var quasi = list[i];
5119
5120 c(quasi, st);
5121 }
5122
5123 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
5124 {
5125 var expr = list$1[i$1];
5126
5127 c(expr, st, "Expression");
5128 }
5129};
5130base$1.TemplateElement = ignore;
5131base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
5132 c(node.argument, st, "Expression");
5133};
5134base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
5135 c(node.left, st, "Expression");
5136 c(node.right, st, "Expression");
5137};
5138base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
5139 c(node.left, st, "Pattern");
5140 c(node.right, st, "Expression");
5141};
5142base$1.ConditionalExpression = function (node, st, c) {
5143 c(node.test, st, "Expression");
5144 c(node.consequent, st, "Expression");
5145 c(node.alternate, st, "Expression");
5146};
5147base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
5148 c(node.callee, st, "Expression");
5149 if (node.arguments)
5150 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
5151 {
5152 var arg = list[i];
5153
5154 c(arg, st, "Expression");
5155 } }
5156};
5157base$1.MemberExpression = function (node, st, c) {
5158 c(node.object, st, "Expression");
5159 if (node.computed) { c(node.property, st, "Expression"); }
5160};
5161base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
5162 if (node.declaration)
5163 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
5164 if (node.source) { c(node.source, st, "Expression"); }
5165};
5166base$1.ExportAllDeclaration = function (node, st, c) {
5167 if (node.exported)
5168 { c(node.exported, st); }
5169 c(node.source, st, "Expression");
5170};
5171base$1.ImportDeclaration = function (node, st, c) {
5172 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
5173 {
5174 var spec = list[i];
5175
5176 c(spec, st);
5177 }
5178 c(node.source, st, "Expression");
5179};
5180base$1.ImportExpression = function (node, st, c) {
5181 c(node.source, st, "Expression");
5182};
5183base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
5184
5185base$1.TaggedTemplateExpression = function (node, st, c) {
5186 c(node.tag, st, "Expression");
5187 c(node.quasi, st, "Expression");
5188};
5189base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
5190base$1.Class = function (node, st, c) {
5191 if (node.id) { c(node.id, st, "Pattern"); }
5192 if (node.superClass) { c(node.superClass, st, "Expression"); }
5193 c(node.body, st);
5194};
5195base$1.ClassBody = function (node, st, c) {
5196 for (var i = 0, list = node.body; i < list.length; i += 1)
5197 {
5198 var elt = list[i];
5199
5200 c(elt, st);
5201 }
5202};
5203base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
5204 if (node.computed) { c(node.key, st, "Expression"); }
5205 if (node.value) { c(node.value, st, "Expression"); }
5206};
5207
5208const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
5209const BinaryExpression$1 = 'BinaryExpression';
5210const BlockStatement$1 = 'BlockStatement';
5211const CallExpression$1 = 'CallExpression';
5212const ChainExpression$1 = 'ChainExpression';
5213const ConditionalExpression$1 = 'ConditionalExpression';
5214const ExpressionStatement$1 = 'ExpressionStatement';
5215const Identifier$1 = 'Identifier';
5216const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
5217const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
5218const LogicalExpression$1 = 'LogicalExpression';
5219const NewExpression$1 = 'NewExpression';
5220const Program$1 = 'Program';
5221const Property$1 = 'Property';
5222const ReturnStatement$1 = 'ReturnStatement';
5223const SequenceExpression$1 = 'SequenceExpression';
5224
5225// this looks ridiculous, but it prevents sourcemap tooling from mistaking
5226// this for an actual sourceMappingURL
5227exports.SOURCEMAPPING_URL = 'sourceMa';
5228exports.SOURCEMAPPING_URL += 'ppingURL';
5229const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
5230const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${exports.SOURCEMAPPING_URL}=.+`);
5231
5232const ANNOTATION_KEY = '_rollupAnnotations';
5233const INVALID_COMMENT_KEY = '_rollupRemoved';
5234function handlePureAnnotationsOfNode(node, state, type = node.type) {
5235 const { annotations } = state;
5236 let comment = annotations[state.annotationIndex];
5237 while (comment && node.start >= comment.end) {
5238 markPureNode(node, comment, state.code);
5239 comment = annotations[++state.annotationIndex];
5240 }
5241 if (comment && comment.end <= node.end) {
5242 base$1[type](node, state, handlePureAnnotationsOfNode);
5243 while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
5244 ++state.annotationIndex;
5245 annotateNode(node, comment, false);
5246 }
5247 }
5248}
5249const neitherWithespaceNorBrackets = /[^\s(]/g;
5250const noWhitespace = /\S/g;
5251function markPureNode(node, comment, code) {
5252 const annotatedNodes = [];
5253 let invalidAnnotation;
5254 const codeInBetween = code.slice(comment.end, node.start);
5255 if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
5256 const parentStart = node.start;
5257 while (true) {
5258 annotatedNodes.push(node);
5259 switch (node.type) {
5260 case ExpressionStatement$1:
5261 case ChainExpression$1:
5262 node = node.expression;
5263 continue;
5264 case SequenceExpression$1:
5265 // if there are parentheses, the annotation would apply to the entire expression
5266 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5267 node = node.expressions[0];
5268 continue;
5269 }
5270 invalidAnnotation = true;
5271 break;
5272 case ConditionalExpression$1:
5273 // if there are parentheses, the annotation would apply to the entire expression
5274 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5275 node = node.test;
5276 continue;
5277 }
5278 invalidAnnotation = true;
5279 break;
5280 case LogicalExpression$1:
5281 case BinaryExpression$1:
5282 // if there are parentheses, the annotation would apply to the entire expression
5283 if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5284 node = node.left;
5285 continue;
5286 }
5287 invalidAnnotation = true;
5288 break;
5289 case CallExpression$1:
5290 case NewExpression$1:
5291 break;
5292 default:
5293 invalidAnnotation = true;
5294 }
5295 break;
5296 }
5297 }
5298 else {
5299 invalidAnnotation = true;
5300 }
5301 if (invalidAnnotation) {
5302 annotateNode(node, comment, false);
5303 }
5304 else {
5305 for (const node of annotatedNodes) {
5306 annotateNode(node, comment, true);
5307 }
5308 }
5309}
5310function doesNotMatchOutsideComment(code, forbiddenChars) {
5311 let nextMatch;
5312 while ((nextMatch = forbiddenChars.exec(code)) !== null) {
5313 if (nextMatch[0] === '/') {
5314 const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
5315 if (charCodeAfterSlash === 42 /*"*"*/) {
5316 forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
5317 continue;
5318 }
5319 else if (charCodeAfterSlash === 47 /*"/"*/) {
5320 forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
5321 continue;
5322 }
5323 }
5324 forbiddenChars.lastIndex = 0;
5325 return false;
5326 }
5327 return true;
5328}
5329const pureCommentRegex = /[@#]__PURE__/;
5330function addAnnotations(comments, esTreeAst, code) {
5331 const annotations = [];
5332 const sourceMappingComments = [];
5333 for (const comment of comments) {
5334 if (pureCommentRegex.test(comment.value)) {
5335 annotations.push(comment);
5336 }
5337 else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
5338 sourceMappingComments.push(comment);
5339 }
5340 }
5341 for (const comment of sourceMappingComments) {
5342 annotateNode(esTreeAst, comment, false);
5343 }
5344 handlePureAnnotationsOfNode(esTreeAst, {
5345 annotationIndex: 0,
5346 annotations,
5347 code
5348 });
5349}
5350function annotateNode(node, comment, valid) {
5351 const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
5352 const property = node[key];
5353 if (property) {
5354 property.push(comment);
5355 }
5356 else {
5357 node[key] = [comment];
5358 }
5359}
5360
5361const keys = {
5362 Literal: [],
5363 Program: ['body']
5364};
5365function getAndCreateKeys(esTreeNode) {
5366 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
5367 return keys[esTreeNode.type];
5368}
5369
5370const INCLUDE_PARAMETERS = 'variables';
5371class NodeBase extends ExpressionEntity {
5372 constructor(esTreeNode, parent, parentScope) {
5373 super();
5374 /**
5375 * Nodes can apply custom deoptimizations once they become part of the
5376 * executed code. To do this, they must initialize this as false, implement
5377 * applyDeoptimizations and call this from include and hasEffects if they have
5378 * custom handlers
5379 */
5380 this.deoptimized = false;
5381 this.esTreeNode = esTreeNode;
5382 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
5383 this.parent = parent;
5384 this.context = parent.context;
5385 this.createScope(parentScope);
5386 this.parseNode(esTreeNode);
5387 this.initialise();
5388 this.context.magicString.addSourcemapLocation(this.start);
5389 this.context.magicString.addSourcemapLocation(this.end);
5390 }
5391 addExportedVariables(_variables, _exportNamesByVariable) { }
5392 /**
5393 * Override this to bind assignments to variables and do any initialisations that
5394 * require the scopes to be populated with variables.
5395 */
5396 bind() {
5397 for (const key of this.keys) {
5398 const value = this[key];
5399 if (value === null)
5400 continue;
5401 if (Array.isArray(value)) {
5402 for (const child of value) {
5403 child === null || child === void 0 ? void 0 : child.bind();
5404 }
5405 }
5406 else {
5407 value.bind();
5408 }
5409 }
5410 }
5411 /**
5412 * Override if this node should receive a different scope than the parent scope.
5413 */
5414 createScope(parentScope) {
5415 this.scope = parentScope;
5416 }
5417 hasEffects(context) {
5418 if (!this.deoptimized)
5419 this.applyDeoptimizations();
5420 for (const key of this.keys) {
5421 const value = this[key];
5422 if (value === null)
5423 continue;
5424 if (Array.isArray(value)) {
5425 for (const child of value) {
5426 if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
5427 return true;
5428 }
5429 }
5430 else if (value.hasEffects(context))
5431 return true;
5432 }
5433 return false;
5434 }
5435 hasEffectsAsAssignmentTarget(context, _checkAccess) {
5436 return (this.hasEffects(context) ||
5437 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
5438 }
5439 include(context, includeChildrenRecursively, _options) {
5440 if (!this.deoptimized)
5441 this.applyDeoptimizations();
5442 this.included = true;
5443 for (const key of this.keys) {
5444 const value = this[key];
5445 if (value === null)
5446 continue;
5447 if (Array.isArray(value)) {
5448 for (const child of value) {
5449 child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
5450 }
5451 }
5452 else {
5453 value.include(context, includeChildrenRecursively);
5454 }
5455 }
5456 }
5457 includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
5458 this.include(context, includeChildrenRecursively);
5459 }
5460 /**
5461 * Override to perform special initialisation steps after the scope is initialised
5462 */
5463 initialise() { }
5464 insertSemicolon(code) {
5465 if (code.original[this.end - 1] !== ';') {
5466 code.appendLeft(this.end, ';');
5467 }
5468 }
5469 parseNode(esTreeNode) {
5470 for (const [key, value] of Object.entries(esTreeNode)) {
5471 // That way, we can override this function to add custom initialisation and then call super.parseNode
5472 if (this.hasOwnProperty(key))
5473 continue;
5474 if (key.charCodeAt(0) === 95 /* _ */) {
5475 if (key === ANNOTATION_KEY) {
5476 this.annotations = value;
5477 }
5478 else if (key === INVALID_COMMENT_KEY) {
5479 for (const { start, end } of value)
5480 this.context.magicString.remove(start, end);
5481 }
5482 }
5483 else if (typeof value !== 'object' || value === null) {
5484 this[key] = value;
5485 }
5486 else if (Array.isArray(value)) {
5487 this[key] = [];
5488 for (const child of value) {
5489 this[key].push(child === null
5490 ? null
5491 : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
5492 }
5493 }
5494 else {
5495 this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
5496 }
5497 }
5498 }
5499 render(code, options) {
5500 for (const key of this.keys) {
5501 const value = this[key];
5502 if (value === null)
5503 continue;
5504 if (Array.isArray(value)) {
5505 for (const child of value) {
5506 child === null || child === void 0 ? void 0 : child.render(code, options);
5507 }
5508 }
5509 else {
5510 value.render(code, options);
5511 }
5512 }
5513 }
5514 setAssignedValue(value) {
5515 this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
5516 }
5517 shouldBeIncluded(context) {
5518 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
5519 }
5520 /**
5521 * Just deoptimize everything by default so that when e.g. we do not track
5522 * something properly, it is deoptimized.
5523 * @protected
5524 */
5525 applyDeoptimizations() {
5526 this.deoptimized = true;
5527 for (const key of this.keys) {
5528 const value = this[key];
5529 if (value === null)
5530 continue;
5531 if (Array.isArray(value)) {
5532 for (const child of value) {
5533 child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
5534 }
5535 }
5536 else {
5537 value.deoptimizePath(UNKNOWN_PATH);
5538 }
5539 }
5540 this.context.requestTreeshakingPass();
5541 }
5542}
5543
5544class SpreadElement extends NodeBase {
5545 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5546 if (path.length > 0) {
5547 this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
5548 }
5549 }
5550 hasEffects(context) {
5551 if (!this.deoptimized)
5552 this.applyDeoptimizations();
5553 const { propertyReadSideEffects } = this.context.options
5554 .treeshake;
5555 return (this.argument.hasEffects(context) ||
5556 (propertyReadSideEffects &&
5557 (propertyReadSideEffects === 'always' ||
5558 this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
5559 }
5560 applyDeoptimizations() {
5561 this.deoptimized = true;
5562 // Only properties of properties of the argument could become subject to reassignment
5563 // This will also reassign the return values of iterators
5564 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
5565 this.context.requestTreeshakingPass();
5566 }
5567}
5568
5569class Method extends ExpressionEntity {
5570 constructor(description) {
5571 super();
5572 this.description = description;
5573 }
5574 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5575 if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
5576 thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
5577 }
5578 }
5579 getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
5580 if (path.length > 0) {
5581 return UNKNOWN_EXPRESSION;
5582 }
5583 return (this.description.returnsPrimitive ||
5584 (this.description.returns === 'self'
5585 ? thisArg || UNKNOWN_EXPRESSION
5586 : this.description.returns()));
5587 }
5588 hasEffectsOnInteractionAtPath(path, interaction, context) {
5589 var _a, _b;
5590 const { type } = interaction;
5591 if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
5592 return true;
5593 }
5594 if (type === INTERACTION_CALLED) {
5595 if (this.description.mutatesSelfAsArray === true &&
5596 ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
5597 return true;
5598 }
5599 if (this.description.callsArgs) {
5600 for (const argIndex of this.description.callsArgs) {
5601 if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
5602 return true;
5603 }
5604 }
5605 }
5606 }
5607 return false;
5608 }
5609}
5610const METHOD_RETURNS_BOOLEAN = [
5611 new Method({
5612 callsArgs: null,
5613 mutatesSelfAsArray: false,
5614 returns: null,
5615 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
5616 })
5617];
5618const METHOD_RETURNS_STRING = [
5619 new Method({
5620 callsArgs: null,
5621 mutatesSelfAsArray: false,
5622 returns: null,
5623 returnsPrimitive: UNKNOWN_LITERAL_STRING
5624 })
5625];
5626const METHOD_RETURNS_NUMBER = [
5627 new Method({
5628 callsArgs: null,
5629 mutatesSelfAsArray: false,
5630 returns: null,
5631 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
5632 })
5633];
5634const METHOD_RETURNS_UNKNOWN = [
5635 new Method({
5636 callsArgs: null,
5637 mutatesSelfAsArray: false,
5638 returns: null,
5639 returnsPrimitive: UNKNOWN_EXPRESSION
5640 })
5641];
5642
5643const INTEGER_REG_EXP = /^\d+$/;
5644class ObjectEntity extends ExpressionEntity {
5645 // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
5646 // and we assume there are no setters or getters
5647 constructor(properties, prototypeExpression, immutable = false) {
5648 super();
5649 this.prototypeExpression = prototypeExpression;
5650 this.immutable = immutable;
5651 this.allProperties = [];
5652 this.deoptimizedPaths = Object.create(null);
5653 this.expressionsToBeDeoptimizedByKey = Object.create(null);
5654 this.gettersByKey = Object.create(null);
5655 this.hasLostTrack = false;
5656 this.hasUnknownDeoptimizedInteger = false;
5657 this.hasUnknownDeoptimizedProperty = false;
5658 this.propertiesAndGettersByKey = Object.create(null);
5659 this.propertiesAndSettersByKey = Object.create(null);
5660 this.settersByKey = Object.create(null);
5661 this.thisParametersToBeDeoptimized = new Set();
5662 this.unknownIntegerProps = [];
5663 this.unmatchableGetters = [];
5664 this.unmatchablePropertiesAndGetters = [];
5665 this.unmatchableSetters = [];
5666 if (Array.isArray(properties)) {
5667 this.buildPropertyMaps(properties);
5668 }
5669 else {
5670 this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
5671 for (const propertiesForKey of Object.values(properties)) {
5672 this.allProperties.push(...propertiesForKey);
5673 }
5674 }
5675 }
5676 deoptimizeAllProperties(noAccessors) {
5677 var _a;
5678 const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
5679 if (noAccessors) {
5680 this.hasUnknownDeoptimizedProperty = true;
5681 }
5682 else {
5683 this.hasLostTrack = true;
5684 }
5685 if (isDeoptimized) {
5686 return;
5687 }
5688 for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
5689 for (const property of properties) {
5690 property.deoptimizePath(UNKNOWN_PATH);
5691 }
5692 }
5693 // While the prototype itself cannot be mutated, each property can
5694 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
5695 this.deoptimizeCachedEntities();
5696 }
5697 deoptimizeIntegerProperties() {
5698 if (this.hasLostTrack ||
5699 this.hasUnknownDeoptimizedProperty ||
5700 this.hasUnknownDeoptimizedInteger) {
5701 return;
5702 }
5703 this.hasUnknownDeoptimizedInteger = true;
5704 for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
5705 if (INTEGER_REG_EXP.test(key)) {
5706 for (const property of propertiesAndGetters) {
5707 property.deoptimizePath(UNKNOWN_PATH);
5708 }
5709 }
5710 }
5711 this.deoptimizeCachedIntegerEntities();
5712 }
5713 // Assumption: If only a specific path is deoptimized, no accessors are created
5714 deoptimizePath(path) {
5715 var _a;
5716 if (this.hasLostTrack || this.immutable) {
5717 return;
5718 }
5719 const key = path[0];
5720 if (path.length === 1) {
5721 if (typeof key !== 'string') {
5722 if (key === UnknownInteger) {
5723 return this.deoptimizeIntegerProperties();
5724 }
5725 return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
5726 }
5727 if (!this.deoptimizedPaths[key]) {
5728 this.deoptimizedPaths[key] = true;
5729 // we only deoptimizeCache exact matches as in all other cases,
5730 // we do not return a literal value or return expression
5731 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
5732 if (expressionsToBeDeoptimized) {
5733 for (const expression of expressionsToBeDeoptimized) {
5734 expression.deoptimizeCache();
5735 }
5736 }
5737 }
5738 }
5739 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
5740 for (const property of typeof key === 'string'
5741 ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
5742 : this.allProperties) {
5743 property.deoptimizePath(subPath);
5744 }
5745 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
5746 }
5747 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
5748 var _a;
5749 const [key, ...subPath] = path;
5750 if (this.hasLostTrack ||
5751 // single paths that are deoptimized will not become getters or setters
5752 ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
5753 (this.hasUnknownDeoptimizedProperty ||
5754 (typeof key === 'string' && this.deoptimizedPaths[key])))) {
5755 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
5756 return;
5757 }
5758 const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
5759 ? [
5760 this.propertiesAndGettersByKey,
5761 this.propertiesAndGettersByKey,
5762 this.unmatchablePropertiesAndGetters
5763 ]
5764 : interaction.type === INTERACTION_ACCESSED
5765 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5766 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5767 if (typeof key === 'string') {
5768 if (propertiesForExactMatchByKey[key]) {
5769 const properties = relevantPropertiesByKey[key];
5770 if (properties) {
5771 for (const property of properties) {
5772 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5773 }
5774 }
5775 if (!this.immutable) {
5776 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5777 }
5778 return;
5779 }
5780 for (const property of relevantUnmatchableProperties) {
5781 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5782 }
5783 if (INTEGER_REG_EXP.test(key)) {
5784 for (const property of this.unknownIntegerProps) {
5785 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5786 }
5787 }
5788 }
5789 else {
5790 for (const properties of Object.values(relevantPropertiesByKey).concat([
5791 relevantUnmatchableProperties
5792 ])) {
5793 for (const property of properties) {
5794 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5795 }
5796 }
5797 for (const property of this.unknownIntegerProps) {
5798 property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5799 }
5800 }
5801 if (!this.immutable) {
5802 this.thisParametersToBeDeoptimized.add(interaction.thisArg);
5803 }
5804 (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
5805 }
5806 getLiteralValueAtPath(path, recursionTracker, origin) {
5807 if (path.length === 0) {
5808 return UnknownTruthyValue;
5809 }
5810 const key = path[0];
5811 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5812 if (expressionAtPath) {
5813 return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
5814 }
5815 if (this.prototypeExpression) {
5816 return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
5817 }
5818 if (path.length === 1) {
5819 return undefined;
5820 }
5821 return UnknownValue;
5822 }
5823 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
5824 if (path.length === 0) {
5825 return UNKNOWN_EXPRESSION;
5826 }
5827 const [key, ...subPath] = path;
5828 const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
5829 if (expressionAtPath) {
5830 return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
5831 }
5832 if (this.prototypeExpression) {
5833 return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
5834 }
5835 return UNKNOWN_EXPRESSION;
5836 }
5837 hasEffectsOnInteractionAtPath(path, interaction, context) {
5838 const [key, ...subPath] = path;
5839 if (subPath.length || interaction.type === INTERACTION_CALLED) {
5840 const expressionAtPath = this.getMemberExpression(key);
5841 if (expressionAtPath) {
5842 return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
5843 }
5844 if (this.prototypeExpression) {
5845 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5846 }
5847 return true;
5848 }
5849 if (key === UnknownNonAccessorKey)
5850 return false;
5851 if (this.hasLostTrack)
5852 return true;
5853 const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
5854 ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
5855 : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
5856 if (typeof key === 'string') {
5857 if (propertiesAndAccessorsByKey[key]) {
5858 const accessors = accessorsByKey[key];
5859 if (accessors) {
5860 for (const accessor of accessors) {
5861 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5862 return true;
5863 }
5864 }
5865 return false;
5866 }
5867 for (const accessor of unmatchableAccessors) {
5868 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
5869 return true;
5870 }
5871 }
5872 }
5873 else {
5874 for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
5875 for (const accessor of accessors) {
5876 if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
5877 return true;
5878 }
5879 }
5880 }
5881 if (this.prototypeExpression) {
5882 return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
5883 }
5884 return false;
5885 }
5886 buildPropertyMaps(properties) {
5887 const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
5888 const unmatchablePropertiesAndSetters = [];
5889 for (let index = properties.length - 1; index >= 0; index--) {
5890 const { key, kind, property } = properties[index];
5891 allProperties.push(property);
5892 if (typeof key !== 'string') {
5893 if (key === UnknownInteger) {
5894 unknownIntegerProps.push(property);
5895 continue;
5896 }
5897 if (kind === 'set')
5898 unmatchableSetters.push(property);
5899 if (kind === 'get')
5900 unmatchableGetters.push(property);
5901 if (kind !== 'get')
5902 unmatchablePropertiesAndSetters.push(property);
5903 if (kind !== 'set')
5904 unmatchablePropertiesAndGetters.push(property);
5905 }
5906 else {
5907 if (kind === 'set') {
5908 if (!propertiesAndSettersByKey[key]) {
5909 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5910 settersByKey[key] = [property, ...unmatchableSetters];
5911 }
5912 }
5913 else if (kind === 'get') {
5914 if (!propertiesAndGettersByKey[key]) {
5915 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5916 gettersByKey[key] = [property, ...unmatchableGetters];
5917 }
5918 }
5919 else {
5920 if (!propertiesAndSettersByKey[key]) {
5921 propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
5922 }
5923 if (!propertiesAndGettersByKey[key]) {
5924 propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
5925 }
5926 }
5927 }
5928 }
5929 }
5930 deoptimizeCachedEntities() {
5931 for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
5932 for (const expression of expressionsToBeDeoptimized) {
5933 expression.deoptimizeCache();
5934 }
5935 }
5936 for (const expression of this.thisParametersToBeDeoptimized) {
5937 expression.deoptimizePath(UNKNOWN_PATH);
5938 }
5939 }
5940 deoptimizeCachedIntegerEntities() {
5941 for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
5942 if (INTEGER_REG_EXP.test(key)) {
5943 for (const expression of expressionsToBeDeoptimized) {
5944 expression.deoptimizeCache();
5945 }
5946 }
5947 }
5948 for (const expression of this.thisParametersToBeDeoptimized) {
5949 expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
5950 }
5951 }
5952 getMemberExpression(key) {
5953 if (this.hasLostTrack ||
5954 this.hasUnknownDeoptimizedProperty ||
5955 typeof key !== 'string' ||
5956 (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
5957 this.deoptimizedPaths[key]) {
5958 return UNKNOWN_EXPRESSION;
5959 }
5960 const properties = this.propertiesAndGettersByKey[key];
5961 if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
5962 return properties[0];
5963 }
5964 if (properties ||
5965 this.unmatchablePropertiesAndGetters.length > 0 ||
5966 (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
5967 return UNKNOWN_EXPRESSION;
5968 }
5969 return null;
5970 }
5971 getMemberExpressionAndTrackDeopt(key, origin) {
5972 if (typeof key !== 'string') {
5973 return UNKNOWN_EXPRESSION;
5974 }
5975 const expression = this.getMemberExpression(key);
5976 if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
5977 const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
5978 this.expressionsToBeDeoptimizedByKey[key] || []);
5979 expressionsToBeDeoptimized.push(origin);
5980 }
5981 return expression;
5982 }
5983}
5984
5985const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
5986// This makes sure unknown properties are not handled as "undefined" but as
5987// "unknown" but without access side effects. An exception is done for numeric
5988// properties as we do not expect new builtin properties to be numbers, this
5989// will improve tree-shaking for out-of-bounds array properties
5990const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
5991 deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
5992 if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
5993 thisArg.deoptimizePath(UNKNOWN_PATH);
5994 }
5995 }
5996 getLiteralValueAtPath(path) {
5997 // We ignore number properties as we do not expect new properties to be
5998 // numbers and also want to keep handling out-of-bound array elements as
5999 // "undefined"
6000 return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
6001 }
6002 hasEffectsOnInteractionAtPath(path, { type }) {
6003 return path.length > 1 || type === INTERACTION_CALLED;
6004 }
6005})();
6006const OBJECT_PROTOTYPE = new ObjectEntity({
6007 __proto__: null,
6008 hasOwnProperty: METHOD_RETURNS_BOOLEAN,
6009 isPrototypeOf: METHOD_RETURNS_BOOLEAN,
6010 propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
6011 toLocaleString: METHOD_RETURNS_STRING,
6012 toString: METHOD_RETURNS_STRING,
6013 valueOf: METHOD_RETURNS_UNKNOWN
6014}, OBJECT_PROTOTYPE_FALLBACK, true);
6015
6016const NEW_ARRAY_PROPERTIES = [
6017 { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
6018 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6019];
6020const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
6021 new Method({
6022 callsArgs: [0],
6023 mutatesSelfAsArray: 'deopt-only',
6024 returns: null,
6025 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
6026 })
6027];
6028const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
6029 new Method({
6030 callsArgs: [0],
6031 mutatesSelfAsArray: 'deopt-only',
6032 returns: null,
6033 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6034 })
6035];
6036const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
6037 new Method({
6038 callsArgs: null,
6039 mutatesSelfAsArray: true,
6040 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6041 returnsPrimitive: null
6042 })
6043];
6044const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6045 new Method({
6046 callsArgs: null,
6047 mutatesSelfAsArray: 'deopt-only',
6048 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6049 returnsPrimitive: null
6050 })
6051];
6052const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
6053 new Method({
6054 callsArgs: [0],
6055 mutatesSelfAsArray: 'deopt-only',
6056 returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
6057 returnsPrimitive: null
6058 })
6059];
6060const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
6061 new Method({
6062 callsArgs: null,
6063 mutatesSelfAsArray: true,
6064 returns: null,
6065 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
6066 })
6067];
6068const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
6069 new Method({
6070 callsArgs: null,
6071 mutatesSelfAsArray: true,
6072 returns: null,
6073 returnsPrimitive: UNKNOWN_EXPRESSION
6074 })
6075];
6076const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
6077 new Method({
6078 callsArgs: null,
6079 mutatesSelfAsArray: 'deopt-only',
6080 returns: null,
6081 returnsPrimitive: UNKNOWN_EXPRESSION
6082 })
6083];
6084const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
6085 new Method({
6086 callsArgs: [0],
6087 mutatesSelfAsArray: 'deopt-only',
6088 returns: null,
6089 returnsPrimitive: UNKNOWN_EXPRESSION
6090 })
6091];
6092const METHOD_MUTATES_SELF_RETURNS_SELF = [
6093 new Method({
6094 callsArgs: null,
6095 mutatesSelfAsArray: true,
6096 returns: 'self',
6097 returnsPrimitive: null
6098 })
6099];
6100const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
6101 new Method({
6102 callsArgs: [0],
6103 mutatesSelfAsArray: true,
6104 returns: 'self',
6105 returnsPrimitive: null
6106 })
6107];
6108const ARRAY_PROTOTYPE = new ObjectEntity({
6109 __proto__: null,
6110 // We assume that accessors have effects as we do not track the accessed value afterwards
6111 at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
6112 concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6113 copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
6114 entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6115 every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6116 fill: METHOD_MUTATES_SELF_RETURNS_SELF,
6117 filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6118 find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6119 findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
6120 findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6121 findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
6122 flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6123 flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6124 forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6125 group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6126 groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6127 includes: METHOD_RETURNS_BOOLEAN,
6128 indexOf: METHOD_RETURNS_NUMBER,
6129 join: METHOD_RETURNS_STRING,
6130 keys: METHOD_RETURNS_UNKNOWN,
6131 lastIndexOf: METHOD_RETURNS_NUMBER,
6132 map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6133 pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6134 push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6135 reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6136 reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
6137 reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
6138 shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
6139 slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
6140 some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
6141 sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
6142 splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
6143 toLocaleString: METHOD_RETURNS_STRING,
6144 toString: METHOD_RETURNS_STRING,
6145 unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
6146 values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
6147}, OBJECT_PROTOTYPE, true);
6148
6149class ArrayExpression extends NodeBase {
6150 constructor() {
6151 super(...arguments);
6152 this.objectEntity = null;
6153 }
6154 deoptimizePath(path) {
6155 this.getObjectEntity().deoptimizePath(path);
6156 }
6157 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6158 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
6159 }
6160 getLiteralValueAtPath(path, recursionTracker, origin) {
6161 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
6162 }
6163 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6164 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6165 }
6166 hasEffectsOnInteractionAtPath(path, interaction, context) {
6167 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
6168 }
6169 applyDeoptimizations() {
6170 this.deoptimized = true;
6171 let hasSpread = false;
6172 for (let index = 0; index < this.elements.length; index++) {
6173 const element = this.elements[index];
6174 if (element) {
6175 if (hasSpread || element instanceof SpreadElement) {
6176 hasSpread = true;
6177 element.deoptimizePath(UNKNOWN_PATH);
6178 }
6179 }
6180 }
6181 this.context.requestTreeshakingPass();
6182 }
6183 getObjectEntity() {
6184 if (this.objectEntity !== null) {
6185 return this.objectEntity;
6186 }
6187 const properties = [
6188 { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
6189 ];
6190 let hasSpread = false;
6191 for (let index = 0; index < this.elements.length; index++) {
6192 const element = this.elements[index];
6193 if (hasSpread || element instanceof SpreadElement) {
6194 if (element) {
6195 hasSpread = true;
6196 properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
6197 }
6198 }
6199 else if (!element) {
6200 properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
6201 }
6202 else {
6203 properties.push({ key: String(index), kind: 'init', property: element });
6204 }
6205 }
6206 return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
6207 }
6208}
6209
6210class ArrayPattern extends NodeBase {
6211 addExportedVariables(variables, exportNamesByVariable) {
6212 for (const element of this.elements) {
6213 element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
6214 }
6215 }
6216 declare(kind) {
6217 const variables = [];
6218 for (const element of this.elements) {
6219 if (element !== null) {
6220 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
6221 }
6222 }
6223 return variables;
6224 }
6225 // Patterns can only be deoptimized at the empty path at the moment
6226 deoptimizePath() {
6227 for (const element of this.elements) {
6228 element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
6229 }
6230 }
6231 // Patterns are only checked at the emtpy path at the moment
6232 hasEffectsOnInteractionAtPath(_path, interaction, context) {
6233 for (const element of this.elements) {
6234 if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
6235 return true;
6236 }
6237 return false;
6238 }
6239 markDeclarationReached() {
6240 for (const element of this.elements) {
6241 element === null || element === void 0 ? void 0 : element.markDeclarationReached();
6242 }
6243 }
6244}
6245
6246class LocalVariable extends Variable {
6247 constructor(name, declarator, init, context) {
6248 super(name);
6249 this.calledFromTryStatement = false;
6250 this.additionalInitializers = null;
6251 this.expressionsToBeDeoptimized = [];
6252 this.declarations = declarator ? [declarator] : [];
6253 this.init = init;
6254 this.deoptimizationTracker = context.deoptimizationTracker;
6255 this.module = context.module;
6256 }
6257 addDeclaration(identifier, init) {
6258 this.declarations.push(identifier);
6259 const additionalInitializers = this.markInitializersForDeoptimization();
6260 if (init !== null) {
6261 additionalInitializers.push(init);
6262 }
6263 }
6264 consolidateInitializers() {
6265 if (this.additionalInitializers !== null) {
6266 for (const initializer of this.additionalInitializers) {
6267 initializer.deoptimizePath(UNKNOWN_PATH);
6268 }
6269 this.additionalInitializers = null;
6270 }
6271 }
6272 deoptimizePath(path) {
6273 var _a, _b;
6274 if (this.isReassigned ||
6275 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
6276 return;
6277 }
6278 if (path.length === 0) {
6279 if (!this.isReassigned) {
6280 this.isReassigned = true;
6281 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6282 this.expressionsToBeDeoptimized = [];
6283 for (const expression of expressionsToBeDeoptimized) {
6284 expression.deoptimizeCache();
6285 }
6286 (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
6287 }
6288 }
6289 else {
6290 (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
6291 }
6292 }
6293 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
6294 if (this.isReassigned || !this.init) {
6295 return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
6296 }
6297 recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
6298 }
6299 getLiteralValueAtPath(path, recursionTracker, origin) {
6300 if (this.isReassigned || !this.init) {
6301 return UnknownValue;
6302 }
6303 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6304 this.expressionsToBeDeoptimized.push(origin);
6305 return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
6306 }, UnknownValue);
6307 }
6308 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6309 if (this.isReassigned || !this.init) {
6310 return UNKNOWN_EXPRESSION;
6311 }
6312 return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
6313 this.expressionsToBeDeoptimized.push(origin);
6314 return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6315 }, UNKNOWN_EXPRESSION);
6316 }
6317 hasEffectsOnInteractionAtPath(path, interaction, context) {
6318 switch (interaction.type) {
6319 case INTERACTION_ACCESSED:
6320 if (this.isReassigned)
6321 return true;
6322 return (this.init &&
6323 !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
6324 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6325 case INTERACTION_ASSIGNED:
6326 if (this.included)
6327 return true;
6328 if (path.length === 0)
6329 return false;
6330 if (this.isReassigned)
6331 return true;
6332 return (this.init &&
6333 !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
6334 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6335 case INTERACTION_CALLED:
6336 if (this.isReassigned)
6337 return true;
6338 return (this.init &&
6339 !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
6340 this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6341 }
6342 }
6343 include() {
6344 if (!this.included) {
6345 this.included = true;
6346 for (const declaration of this.declarations) {
6347 // If node is a default export, it can save a tree-shaking run to include the full declaration now
6348 if (!declaration.included)
6349 declaration.include(createInclusionContext(), false);
6350 let node = declaration.parent;
6351 while (!node.included) {
6352 // We do not want to properly include parents in case they are part of a dead branch
6353 // in which case .include() might pull in more dead code
6354 node.included = true;
6355 if (node.type === Program$1)
6356 break;
6357 node = node.parent;
6358 }
6359 }
6360 }
6361 }
6362 includeCallArguments(context, args) {
6363 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
6364 for (const arg of args) {
6365 arg.include(context, false);
6366 }
6367 }
6368 else if (this.init) {
6369 context.includedCallArguments.add(this.init);
6370 this.init.includeCallArguments(context, args);
6371 context.includedCallArguments.delete(this.init);
6372 }
6373 }
6374 markCalledFromTryStatement() {
6375 this.calledFromTryStatement = true;
6376 }
6377 markInitializersForDeoptimization() {
6378 if (this.additionalInitializers === null) {
6379 this.additionalInitializers = this.init === null ? [] : [this.init];
6380 this.init = UNKNOWN_EXPRESSION;
6381 this.isReassigned = true;
6382 }
6383 return this.additionalInitializers;
6384 }
6385}
6386
6387const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
6388const base = 64;
6389function toBase64(num) {
6390 let outStr = '';
6391 do {
6392 const curDigit = num % base;
6393 num = Math.floor(num / base);
6394 outStr = chars[curDigit] + outStr;
6395 } while (num !== 0);
6396 return outStr;
6397}
6398
6399function getSafeName(baseName, usedNames) {
6400 let safeName = baseName;
6401 let count = 1;
6402 while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
6403 safeName = `${baseName}$${toBase64(count++)}`;
6404 }
6405 usedNames.add(safeName);
6406 return safeName;
6407}
6408
6409class Scope$1 {
6410 constructor() {
6411 this.children = [];
6412 this.variables = new Map();
6413 }
6414 addDeclaration(identifier, context, init, _isHoisted) {
6415 const name = identifier.name;
6416 let variable = this.variables.get(name);
6417 if (variable) {
6418 variable.addDeclaration(identifier, init);
6419 }
6420 else {
6421 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
6422 this.variables.set(name, variable);
6423 }
6424 return variable;
6425 }
6426 contains(name) {
6427 return this.variables.has(name);
6428 }
6429 findVariable(_name) {
6430 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
6431 }
6432}
6433
6434class ChildScope extends Scope$1 {
6435 constructor(parent) {
6436 super();
6437 this.accessedOutsideVariables = new Map();
6438 this.parent = parent;
6439 parent.children.push(this);
6440 }
6441 addAccessedDynamicImport(importExpression) {
6442 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
6443 if (this.parent instanceof ChildScope) {
6444 this.parent.addAccessedDynamicImport(importExpression);
6445 }
6446 }
6447 addAccessedGlobals(globals, accessedGlobalsByScope) {
6448 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
6449 for (const name of globals) {
6450 accessedGlobals.add(name);
6451 }
6452 accessedGlobalsByScope.set(this, accessedGlobals);
6453 if (this.parent instanceof ChildScope) {
6454 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
6455 }
6456 }
6457 addNamespaceMemberAccess(name, variable) {
6458 this.accessedOutsideVariables.set(name, variable);
6459 this.parent.addNamespaceMemberAccess(name, variable);
6460 }
6461 addReturnExpression(expression) {
6462 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
6463 }
6464 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
6465 for (const variable of this.accessedOutsideVariables.values()) {
6466 if (variable.included) {
6467 usedNames.add(variable.getBaseVariableName());
6468 if (format === 'system' && exportNamesByVariable.has(variable)) {
6469 usedNames.add('exports');
6470 }
6471 }
6472 }
6473 const accessedGlobals = accessedGlobalsByScope.get(this);
6474 if (accessedGlobals) {
6475 for (const name of accessedGlobals) {
6476 usedNames.add(name);
6477 }
6478 }
6479 }
6480 contains(name) {
6481 return this.variables.has(name) || this.parent.contains(name);
6482 }
6483 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
6484 const usedNames = new Set();
6485 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
6486 if (this.accessedDynamicImports) {
6487 for (const importExpression of this.accessedDynamicImports) {
6488 if (importExpression.inlineNamespace) {
6489 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
6490 }
6491 }
6492 }
6493 for (const [name, variable] of this.variables) {
6494 if (variable.included || variable.alwaysRendered) {
6495 variable.setRenderNames(null, getSafeName(name, usedNames));
6496 }
6497 }
6498 for (const scope of this.children) {
6499 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
6500 }
6501 }
6502 findLexicalBoundary() {
6503 return this.parent.findLexicalBoundary();
6504 }
6505 findVariable(name) {
6506 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
6507 if (knownVariable) {
6508 return knownVariable;
6509 }
6510 const variable = this.parent.findVariable(name);
6511 this.accessedOutsideVariables.set(name, variable);
6512 return variable;
6513 }
6514}
6515
6516class ParameterScope extends ChildScope {
6517 constructor(parent, context) {
6518 super(parent);
6519 this.parameters = [];
6520 this.hasRest = false;
6521 this.context = context;
6522 this.hoistedBodyVarScope = new ChildScope(this);
6523 }
6524 /**
6525 * Adds a parameter to this scope. Parameters must be added in the correct
6526 * order, e.g. from left to right.
6527 */
6528 addParameterDeclaration(identifier) {
6529 const name = identifier.name;
6530 let variable = this.hoistedBodyVarScope.variables.get(name);
6531 if (variable) {
6532 variable.addDeclaration(identifier, null);
6533 }
6534 else {
6535 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
6536 }
6537 this.variables.set(name, variable);
6538 return variable;
6539 }
6540 addParameterVariables(parameters, hasRest) {
6541 this.parameters = parameters;
6542 for (const parameterList of parameters) {
6543 for (const parameter of parameterList) {
6544 parameter.alwaysRendered = true;
6545 }
6546 }
6547 this.hasRest = hasRest;
6548 }
6549 includeCallArguments(context, args) {
6550 let calledFromTryStatement = false;
6551 let argIncluded = false;
6552 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
6553 for (const checkedArg of args) {
6554 if (checkedArg instanceof SpreadElement) {
6555 for (const arg of args) {
6556 arg.include(context, false);
6557 }
6558 break;
6559 }
6560 }
6561 for (let index = args.length - 1; index >= 0; index--) {
6562 const paramVars = this.parameters[index] || restParam;
6563 const arg = args[index];
6564 if (paramVars) {
6565 calledFromTryStatement = false;
6566 if (paramVars.length === 0) {
6567 // handle empty destructuring
6568 argIncluded = true;
6569 }
6570 else {
6571 for (const variable of paramVars) {
6572 if (variable.included) {
6573 argIncluded = true;
6574 }
6575 if (variable.calledFromTryStatement) {
6576 calledFromTryStatement = true;
6577 }
6578 }
6579 }
6580 }
6581 if (!argIncluded && arg.shouldBeIncluded(context)) {
6582 argIncluded = true;
6583 }
6584 if (argIncluded) {
6585 arg.include(context, calledFromTryStatement);
6586 }
6587 }
6588 }
6589}
6590
6591class ReturnValueScope extends ParameterScope {
6592 constructor() {
6593 super(...arguments);
6594 this.returnExpression = null;
6595 this.returnExpressions = [];
6596 }
6597 addReturnExpression(expression) {
6598 this.returnExpressions.push(expression);
6599 }
6600 getReturnExpression() {
6601 if (this.returnExpression === null)
6602 this.updateReturnExpression();
6603 return this.returnExpression;
6604 }
6605 updateReturnExpression() {
6606 if (this.returnExpressions.length === 1) {
6607 this.returnExpression = this.returnExpressions[0];
6608 }
6609 else {
6610 this.returnExpression = UNKNOWN_EXPRESSION;
6611 for (const expression of this.returnExpressions) {
6612 expression.deoptimizePath(UNKNOWN_PATH);
6613 }
6614 }
6615 }
6616}
6617
6618//@ts-check
6619/** @typedef { import('estree').Node} Node */
6620/** @typedef {Node | {
6621 * type: 'PropertyDefinition';
6622 * computed: boolean;
6623 * value: Node
6624 * }} NodeWithPropertyDefinition */
6625
6626/**
6627 *
6628 * @param {NodeWithPropertyDefinition} node
6629 * @param {NodeWithPropertyDefinition} parent
6630 * @returns boolean
6631 */
6632function is_reference (node, parent) {
6633 if (node.type === 'MemberExpression') {
6634 return !node.computed && is_reference(node.object, node);
6635 }
6636
6637 if (node.type === 'Identifier') {
6638 if (!parent) return true;
6639
6640 switch (parent.type) {
6641 // disregard `bar` in `foo.bar`
6642 case 'MemberExpression': return parent.computed || node === parent.object;
6643
6644 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
6645 case 'MethodDefinition': return parent.computed;
6646
6647 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
6648 case 'PropertyDefinition': return parent.computed || node === parent.value;
6649
6650 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6651 case 'Property': return parent.computed || node === parent.value;
6652
6653 // disregard the `bar` in `export { foo as bar }` or
6654 // the foo in `import { foo as bar }`
6655 case 'ExportSpecifier':
6656 case 'ImportSpecifier': return node === parent.local;
6657
6658 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
6659 case 'LabeledStatement':
6660 case 'BreakStatement':
6661 case 'ContinueStatement': return false;
6662 default: return true;
6663 }
6664 }
6665
6666 return false;
6667}
6668
6669/* eslint sort-keys: "off" */
6670const ValueProperties = Symbol('Value Properties');
6671const PURE = {
6672 hasEffectsWhenCalled() {
6673 return false;
6674 }
6675};
6676const IMPURE = {
6677 hasEffectsWhenCalled() {
6678 return true;
6679 }
6680};
6681// We use shortened variables to reduce file size here
6682/* OBJECT */
6683const O = {
6684 __proto__: null,
6685 [ValueProperties]: IMPURE
6686};
6687/* PURE FUNCTION */
6688const PF = {
6689 __proto__: null,
6690 [ValueProperties]: PURE
6691};
6692/* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
6693const MUTATES_ARG_WITHOUT_ACCESSOR = {
6694 __proto__: null,
6695 [ValueProperties]: {
6696 hasEffectsWhenCalled({ args }, context) {
6697 return (!args.length ||
6698 args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
6699 }
6700 }
6701};
6702/* CONSTRUCTOR */
6703const C = {
6704 __proto__: null,
6705 [ValueProperties]: IMPURE,
6706 prototype: O
6707};
6708/* PURE CONSTRUCTOR */
6709const PC = {
6710 __proto__: null,
6711 [ValueProperties]: PURE,
6712 prototype: O
6713};
6714const ARRAY_TYPE = {
6715 __proto__: null,
6716 [ValueProperties]: PURE,
6717 from: PF,
6718 of: PF,
6719 prototype: O
6720};
6721const INTL_MEMBER = {
6722 __proto__: null,
6723 [ValueProperties]: PURE,
6724 supportedLocalesOf: PC
6725};
6726const knownGlobals = {
6727 // Placeholders for global objects to avoid shape mutations
6728 global: O,
6729 globalThis: O,
6730 self: O,
6731 window: O,
6732 // Common globals
6733 __proto__: null,
6734 [ValueProperties]: IMPURE,
6735 Array: {
6736 __proto__: null,
6737 [ValueProperties]: IMPURE,
6738 from: O,
6739 isArray: PF,
6740 of: PF,
6741 prototype: O
6742 },
6743 ArrayBuffer: {
6744 __proto__: null,
6745 [ValueProperties]: PURE,
6746 isView: PF,
6747 prototype: O
6748 },
6749 Atomics: O,
6750 BigInt: C,
6751 BigInt64Array: C,
6752 BigUint64Array: C,
6753 Boolean: PC,
6754 constructor: C,
6755 DataView: PC,
6756 Date: {
6757 __proto__: null,
6758 [ValueProperties]: PURE,
6759 now: PF,
6760 parse: PF,
6761 prototype: O,
6762 UTC: PF
6763 },
6764 decodeURI: PF,
6765 decodeURIComponent: PF,
6766 encodeURI: PF,
6767 encodeURIComponent: PF,
6768 Error: PC,
6769 escape: PF,
6770 eval: O,
6771 EvalError: PC,
6772 Float32Array: ARRAY_TYPE,
6773 Float64Array: ARRAY_TYPE,
6774 Function: C,
6775 hasOwnProperty: O,
6776 Infinity: O,
6777 Int16Array: ARRAY_TYPE,
6778 Int32Array: ARRAY_TYPE,
6779 Int8Array: ARRAY_TYPE,
6780 isFinite: PF,
6781 isNaN: PF,
6782 isPrototypeOf: O,
6783 JSON: O,
6784 Map: PC,
6785 Math: {
6786 __proto__: null,
6787 [ValueProperties]: IMPURE,
6788 abs: PF,
6789 acos: PF,
6790 acosh: PF,
6791 asin: PF,
6792 asinh: PF,
6793 atan: PF,
6794 atan2: PF,
6795 atanh: PF,
6796 cbrt: PF,
6797 ceil: PF,
6798 clz32: PF,
6799 cos: PF,
6800 cosh: PF,
6801 exp: PF,
6802 expm1: PF,
6803 floor: PF,
6804 fround: PF,
6805 hypot: PF,
6806 imul: PF,
6807 log: PF,
6808 log10: PF,
6809 log1p: PF,
6810 log2: PF,
6811 max: PF,
6812 min: PF,
6813 pow: PF,
6814 random: PF,
6815 round: PF,
6816 sign: PF,
6817 sin: PF,
6818 sinh: PF,
6819 sqrt: PF,
6820 tan: PF,
6821 tanh: PF,
6822 trunc: PF
6823 },
6824 NaN: O,
6825 Number: {
6826 __proto__: null,
6827 [ValueProperties]: PURE,
6828 isFinite: PF,
6829 isInteger: PF,
6830 isNaN: PF,
6831 isSafeInteger: PF,
6832 parseFloat: PF,
6833 parseInt: PF,
6834 prototype: O
6835 },
6836 Object: {
6837 __proto__: null,
6838 [ValueProperties]: PURE,
6839 create: PF,
6840 // Technically those can throw in certain situations, but we ignore this as
6841 // code that relies on this will hopefully wrap this in a try-catch, which
6842 // deoptimizes everything anyway
6843 defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
6844 defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
6845 getOwnPropertyDescriptor: PF,
6846 getOwnPropertyNames: PF,
6847 getOwnPropertySymbols: PF,
6848 getPrototypeOf: PF,
6849 hasOwn: PF,
6850 is: PF,
6851 isExtensible: PF,
6852 isFrozen: PF,
6853 isSealed: PF,
6854 keys: PF,
6855 fromEntries: PF,
6856 entries: PF,
6857 prototype: O
6858 },
6859 parseFloat: PF,
6860 parseInt: PF,
6861 Promise: {
6862 __proto__: null,
6863 [ValueProperties]: IMPURE,
6864 all: O,
6865 prototype: O,
6866 race: O,
6867 reject: O,
6868 resolve: O
6869 },
6870 propertyIsEnumerable: O,
6871 Proxy: O,
6872 RangeError: PC,
6873 ReferenceError: PC,
6874 Reflect: O,
6875 RegExp: PC,
6876 Set: PC,
6877 SharedArrayBuffer: C,
6878 String: {
6879 __proto__: null,
6880 [ValueProperties]: PURE,
6881 fromCharCode: PF,
6882 fromCodePoint: PF,
6883 prototype: O,
6884 raw: PF
6885 },
6886 Symbol: {
6887 __proto__: null,
6888 [ValueProperties]: PURE,
6889 for: PF,
6890 keyFor: PF,
6891 prototype: O
6892 },
6893 SyntaxError: PC,
6894 toLocaleString: O,
6895 toString: O,
6896 TypeError: PC,
6897 Uint16Array: ARRAY_TYPE,
6898 Uint32Array: ARRAY_TYPE,
6899 Uint8Array: ARRAY_TYPE,
6900 Uint8ClampedArray: ARRAY_TYPE,
6901 // Technically, this is a global, but it needs special handling
6902 // undefined: ?,
6903 unescape: PF,
6904 URIError: PC,
6905 valueOf: O,
6906 WeakMap: PC,
6907 WeakSet: PC,
6908 // Additional globals shared by Node and Browser that are not strictly part of the language
6909 clearInterval: C,
6910 clearTimeout: C,
6911 console: O,
6912 Intl: {
6913 __proto__: null,
6914 [ValueProperties]: IMPURE,
6915 Collator: INTL_MEMBER,
6916 DateTimeFormat: INTL_MEMBER,
6917 ListFormat: INTL_MEMBER,
6918 NumberFormat: INTL_MEMBER,
6919 PluralRules: INTL_MEMBER,
6920 RelativeTimeFormat: INTL_MEMBER
6921 },
6922 setInterval: C,
6923 setTimeout: C,
6924 TextDecoder: C,
6925 TextEncoder: C,
6926 URL: C,
6927 URLSearchParams: C,
6928 // Browser specific globals
6929 AbortController: C,
6930 AbortSignal: C,
6931 addEventListener: O,
6932 alert: O,
6933 AnalyserNode: C,
6934 Animation: C,
6935 AnimationEvent: C,
6936 applicationCache: O,
6937 ApplicationCache: C,
6938 ApplicationCacheErrorEvent: C,
6939 atob: O,
6940 Attr: C,
6941 Audio: C,
6942 AudioBuffer: C,
6943 AudioBufferSourceNode: C,
6944 AudioContext: C,
6945 AudioDestinationNode: C,
6946 AudioListener: C,
6947 AudioNode: C,
6948 AudioParam: C,
6949 AudioProcessingEvent: C,
6950 AudioScheduledSourceNode: C,
6951 AudioWorkletNode: C,
6952 BarProp: C,
6953 BaseAudioContext: C,
6954 BatteryManager: C,
6955 BeforeUnloadEvent: C,
6956 BiquadFilterNode: C,
6957 Blob: C,
6958 BlobEvent: C,
6959 blur: O,
6960 BroadcastChannel: C,
6961 btoa: O,
6962 ByteLengthQueuingStrategy: C,
6963 Cache: C,
6964 caches: O,
6965 CacheStorage: C,
6966 cancelAnimationFrame: O,
6967 cancelIdleCallback: O,
6968 CanvasCaptureMediaStreamTrack: C,
6969 CanvasGradient: C,
6970 CanvasPattern: C,
6971 CanvasRenderingContext2D: C,
6972 ChannelMergerNode: C,
6973 ChannelSplitterNode: C,
6974 CharacterData: C,
6975 clientInformation: O,
6976 ClipboardEvent: C,
6977 close: O,
6978 closed: O,
6979 CloseEvent: C,
6980 Comment: C,
6981 CompositionEvent: C,
6982 confirm: O,
6983 ConstantSourceNode: C,
6984 ConvolverNode: C,
6985 CountQueuingStrategy: C,
6986 createImageBitmap: O,
6987 Credential: C,
6988 CredentialsContainer: C,
6989 crypto: O,
6990 Crypto: C,
6991 CryptoKey: C,
6992 CSS: C,
6993 CSSConditionRule: C,
6994 CSSFontFaceRule: C,
6995 CSSGroupingRule: C,
6996 CSSImportRule: C,
6997 CSSKeyframeRule: C,
6998 CSSKeyframesRule: C,
6999 CSSMediaRule: C,
7000 CSSNamespaceRule: C,
7001 CSSPageRule: C,
7002 CSSRule: C,
7003 CSSRuleList: C,
7004 CSSStyleDeclaration: C,
7005 CSSStyleRule: C,
7006 CSSStyleSheet: C,
7007 CSSSupportsRule: C,
7008 CustomElementRegistry: C,
7009 customElements: O,
7010 CustomEvent: C,
7011 DataTransfer: C,
7012 DataTransferItem: C,
7013 DataTransferItemList: C,
7014 defaultstatus: O,
7015 defaultStatus: O,
7016 DelayNode: C,
7017 DeviceMotionEvent: C,
7018 DeviceOrientationEvent: C,
7019 devicePixelRatio: O,
7020 dispatchEvent: O,
7021 document: O,
7022 Document: C,
7023 DocumentFragment: C,
7024 DocumentType: C,
7025 DOMError: C,
7026 DOMException: C,
7027 DOMImplementation: C,
7028 DOMMatrix: C,
7029 DOMMatrixReadOnly: C,
7030 DOMParser: C,
7031 DOMPoint: C,
7032 DOMPointReadOnly: C,
7033 DOMQuad: C,
7034 DOMRect: C,
7035 DOMRectReadOnly: C,
7036 DOMStringList: C,
7037 DOMStringMap: C,
7038 DOMTokenList: C,
7039 DragEvent: C,
7040 DynamicsCompressorNode: C,
7041 Element: C,
7042 ErrorEvent: C,
7043 Event: C,
7044 EventSource: C,
7045 EventTarget: C,
7046 external: O,
7047 fetch: O,
7048 File: C,
7049 FileList: C,
7050 FileReader: C,
7051 find: O,
7052 focus: O,
7053 FocusEvent: C,
7054 FontFace: C,
7055 FontFaceSetLoadEvent: C,
7056 FormData: C,
7057 frames: O,
7058 GainNode: C,
7059 Gamepad: C,
7060 GamepadButton: C,
7061 GamepadEvent: C,
7062 getComputedStyle: O,
7063 getSelection: O,
7064 HashChangeEvent: C,
7065 Headers: C,
7066 history: O,
7067 History: C,
7068 HTMLAllCollection: C,
7069 HTMLAnchorElement: C,
7070 HTMLAreaElement: C,
7071 HTMLAudioElement: C,
7072 HTMLBaseElement: C,
7073 HTMLBodyElement: C,
7074 HTMLBRElement: C,
7075 HTMLButtonElement: C,
7076 HTMLCanvasElement: C,
7077 HTMLCollection: C,
7078 HTMLContentElement: C,
7079 HTMLDataElement: C,
7080 HTMLDataListElement: C,
7081 HTMLDetailsElement: C,
7082 HTMLDialogElement: C,
7083 HTMLDirectoryElement: C,
7084 HTMLDivElement: C,
7085 HTMLDListElement: C,
7086 HTMLDocument: C,
7087 HTMLElement: C,
7088 HTMLEmbedElement: C,
7089 HTMLFieldSetElement: C,
7090 HTMLFontElement: C,
7091 HTMLFormControlsCollection: C,
7092 HTMLFormElement: C,
7093 HTMLFrameElement: C,
7094 HTMLFrameSetElement: C,
7095 HTMLHeadElement: C,
7096 HTMLHeadingElement: C,
7097 HTMLHRElement: C,
7098 HTMLHtmlElement: C,
7099 HTMLIFrameElement: C,
7100 HTMLImageElement: C,
7101 HTMLInputElement: C,
7102 HTMLLabelElement: C,
7103 HTMLLegendElement: C,
7104 HTMLLIElement: C,
7105 HTMLLinkElement: C,
7106 HTMLMapElement: C,
7107 HTMLMarqueeElement: C,
7108 HTMLMediaElement: C,
7109 HTMLMenuElement: C,
7110 HTMLMetaElement: C,
7111 HTMLMeterElement: C,
7112 HTMLModElement: C,
7113 HTMLObjectElement: C,
7114 HTMLOListElement: C,
7115 HTMLOptGroupElement: C,
7116 HTMLOptionElement: C,
7117 HTMLOptionsCollection: C,
7118 HTMLOutputElement: C,
7119 HTMLParagraphElement: C,
7120 HTMLParamElement: C,
7121 HTMLPictureElement: C,
7122 HTMLPreElement: C,
7123 HTMLProgressElement: C,
7124 HTMLQuoteElement: C,
7125 HTMLScriptElement: C,
7126 HTMLSelectElement: C,
7127 HTMLShadowElement: C,
7128 HTMLSlotElement: C,
7129 HTMLSourceElement: C,
7130 HTMLSpanElement: C,
7131 HTMLStyleElement: C,
7132 HTMLTableCaptionElement: C,
7133 HTMLTableCellElement: C,
7134 HTMLTableColElement: C,
7135 HTMLTableElement: C,
7136 HTMLTableRowElement: C,
7137 HTMLTableSectionElement: C,
7138 HTMLTemplateElement: C,
7139 HTMLTextAreaElement: C,
7140 HTMLTimeElement: C,
7141 HTMLTitleElement: C,
7142 HTMLTrackElement: C,
7143 HTMLUListElement: C,
7144 HTMLUnknownElement: C,
7145 HTMLVideoElement: C,
7146 IDBCursor: C,
7147 IDBCursorWithValue: C,
7148 IDBDatabase: C,
7149 IDBFactory: C,
7150 IDBIndex: C,
7151 IDBKeyRange: C,
7152 IDBObjectStore: C,
7153 IDBOpenDBRequest: C,
7154 IDBRequest: C,
7155 IDBTransaction: C,
7156 IDBVersionChangeEvent: C,
7157 IdleDeadline: C,
7158 IIRFilterNode: C,
7159 Image: C,
7160 ImageBitmap: C,
7161 ImageBitmapRenderingContext: C,
7162 ImageCapture: C,
7163 ImageData: C,
7164 indexedDB: O,
7165 innerHeight: O,
7166 innerWidth: O,
7167 InputEvent: C,
7168 IntersectionObserver: C,
7169 IntersectionObserverEntry: C,
7170 isSecureContext: O,
7171 KeyboardEvent: C,
7172 KeyframeEffect: C,
7173 length: O,
7174 localStorage: O,
7175 location: O,
7176 Location: C,
7177 locationbar: O,
7178 matchMedia: O,
7179 MediaDeviceInfo: C,
7180 MediaDevices: C,
7181 MediaElementAudioSourceNode: C,
7182 MediaEncryptedEvent: C,
7183 MediaError: C,
7184 MediaKeyMessageEvent: C,
7185 MediaKeySession: C,
7186 MediaKeyStatusMap: C,
7187 MediaKeySystemAccess: C,
7188 MediaList: C,
7189 MediaQueryList: C,
7190 MediaQueryListEvent: C,
7191 MediaRecorder: C,
7192 MediaSettingsRange: C,
7193 MediaSource: C,
7194 MediaStream: C,
7195 MediaStreamAudioDestinationNode: C,
7196 MediaStreamAudioSourceNode: C,
7197 MediaStreamEvent: C,
7198 MediaStreamTrack: C,
7199 MediaStreamTrackEvent: C,
7200 menubar: O,
7201 MessageChannel: C,
7202 MessageEvent: C,
7203 MessagePort: C,
7204 MIDIAccess: C,
7205 MIDIConnectionEvent: C,
7206 MIDIInput: C,
7207 MIDIInputMap: C,
7208 MIDIMessageEvent: C,
7209 MIDIOutput: C,
7210 MIDIOutputMap: C,
7211 MIDIPort: C,
7212 MimeType: C,
7213 MimeTypeArray: C,
7214 MouseEvent: C,
7215 moveBy: O,
7216 moveTo: O,
7217 MutationEvent: C,
7218 MutationObserver: C,
7219 MutationRecord: C,
7220 name: O,
7221 NamedNodeMap: C,
7222 NavigationPreloadManager: C,
7223 navigator: O,
7224 Navigator: C,
7225 NetworkInformation: C,
7226 Node: C,
7227 NodeFilter: O,
7228 NodeIterator: C,
7229 NodeList: C,
7230 Notification: C,
7231 OfflineAudioCompletionEvent: C,
7232 OfflineAudioContext: C,
7233 offscreenBuffering: O,
7234 OffscreenCanvas: C,
7235 open: O,
7236 openDatabase: O,
7237 Option: C,
7238 origin: O,
7239 OscillatorNode: C,
7240 outerHeight: O,
7241 outerWidth: O,
7242 PageTransitionEvent: C,
7243 pageXOffset: O,
7244 pageYOffset: O,
7245 PannerNode: C,
7246 parent: O,
7247 Path2D: C,
7248 PaymentAddress: C,
7249 PaymentRequest: C,
7250 PaymentRequestUpdateEvent: C,
7251 PaymentResponse: C,
7252 performance: O,
7253 Performance: C,
7254 PerformanceEntry: C,
7255 PerformanceLongTaskTiming: C,
7256 PerformanceMark: C,
7257 PerformanceMeasure: C,
7258 PerformanceNavigation: C,
7259 PerformanceNavigationTiming: C,
7260 PerformanceObserver: C,
7261 PerformanceObserverEntryList: C,
7262 PerformancePaintTiming: C,
7263 PerformanceResourceTiming: C,
7264 PerformanceTiming: C,
7265 PeriodicWave: C,
7266 Permissions: C,
7267 PermissionStatus: C,
7268 personalbar: O,
7269 PhotoCapabilities: C,
7270 Plugin: C,
7271 PluginArray: C,
7272 PointerEvent: C,
7273 PopStateEvent: C,
7274 postMessage: O,
7275 Presentation: C,
7276 PresentationAvailability: C,
7277 PresentationConnection: C,
7278 PresentationConnectionAvailableEvent: C,
7279 PresentationConnectionCloseEvent: C,
7280 PresentationConnectionList: C,
7281 PresentationReceiver: C,
7282 PresentationRequest: C,
7283 print: O,
7284 ProcessingInstruction: C,
7285 ProgressEvent: C,
7286 PromiseRejectionEvent: C,
7287 prompt: O,
7288 PushManager: C,
7289 PushSubscription: C,
7290 PushSubscriptionOptions: C,
7291 queueMicrotask: O,
7292 RadioNodeList: C,
7293 Range: C,
7294 ReadableStream: C,
7295 RemotePlayback: C,
7296 removeEventListener: O,
7297 Request: C,
7298 requestAnimationFrame: O,
7299 requestIdleCallback: O,
7300 resizeBy: O,
7301 ResizeObserver: C,
7302 ResizeObserverEntry: C,
7303 resizeTo: O,
7304 Response: C,
7305 RTCCertificate: C,
7306 RTCDataChannel: C,
7307 RTCDataChannelEvent: C,
7308 RTCDtlsTransport: C,
7309 RTCIceCandidate: C,
7310 RTCIceTransport: C,
7311 RTCPeerConnection: C,
7312 RTCPeerConnectionIceEvent: C,
7313 RTCRtpReceiver: C,
7314 RTCRtpSender: C,
7315 RTCSctpTransport: C,
7316 RTCSessionDescription: C,
7317 RTCStatsReport: C,
7318 RTCTrackEvent: C,
7319 screen: O,
7320 Screen: C,
7321 screenLeft: O,
7322 ScreenOrientation: C,
7323 screenTop: O,
7324 screenX: O,
7325 screenY: O,
7326 ScriptProcessorNode: C,
7327 scroll: O,
7328 scrollbars: O,
7329 scrollBy: O,
7330 scrollTo: O,
7331 scrollX: O,
7332 scrollY: O,
7333 SecurityPolicyViolationEvent: C,
7334 Selection: C,
7335 ServiceWorker: C,
7336 ServiceWorkerContainer: C,
7337 ServiceWorkerRegistration: C,
7338 sessionStorage: O,
7339 ShadowRoot: C,
7340 SharedWorker: C,
7341 SourceBuffer: C,
7342 SourceBufferList: C,
7343 speechSynthesis: O,
7344 SpeechSynthesisEvent: C,
7345 SpeechSynthesisUtterance: C,
7346 StaticRange: C,
7347 status: O,
7348 statusbar: O,
7349 StereoPannerNode: C,
7350 stop: O,
7351 Storage: C,
7352 StorageEvent: C,
7353 StorageManager: C,
7354 styleMedia: O,
7355 StyleSheet: C,
7356 StyleSheetList: C,
7357 SubtleCrypto: C,
7358 SVGAElement: C,
7359 SVGAngle: C,
7360 SVGAnimatedAngle: C,
7361 SVGAnimatedBoolean: C,
7362 SVGAnimatedEnumeration: C,
7363 SVGAnimatedInteger: C,
7364 SVGAnimatedLength: C,
7365 SVGAnimatedLengthList: C,
7366 SVGAnimatedNumber: C,
7367 SVGAnimatedNumberList: C,
7368 SVGAnimatedPreserveAspectRatio: C,
7369 SVGAnimatedRect: C,
7370 SVGAnimatedString: C,
7371 SVGAnimatedTransformList: C,
7372 SVGAnimateElement: C,
7373 SVGAnimateMotionElement: C,
7374 SVGAnimateTransformElement: C,
7375 SVGAnimationElement: C,
7376 SVGCircleElement: C,
7377 SVGClipPathElement: C,
7378 SVGComponentTransferFunctionElement: C,
7379 SVGDefsElement: C,
7380 SVGDescElement: C,
7381 SVGDiscardElement: C,
7382 SVGElement: C,
7383 SVGEllipseElement: C,
7384 SVGFEBlendElement: C,
7385 SVGFEColorMatrixElement: C,
7386 SVGFEComponentTransferElement: C,
7387 SVGFECompositeElement: C,
7388 SVGFEConvolveMatrixElement: C,
7389 SVGFEDiffuseLightingElement: C,
7390 SVGFEDisplacementMapElement: C,
7391 SVGFEDistantLightElement: C,
7392 SVGFEDropShadowElement: C,
7393 SVGFEFloodElement: C,
7394 SVGFEFuncAElement: C,
7395 SVGFEFuncBElement: C,
7396 SVGFEFuncGElement: C,
7397 SVGFEFuncRElement: C,
7398 SVGFEGaussianBlurElement: C,
7399 SVGFEImageElement: C,
7400 SVGFEMergeElement: C,
7401 SVGFEMergeNodeElement: C,
7402 SVGFEMorphologyElement: C,
7403 SVGFEOffsetElement: C,
7404 SVGFEPointLightElement: C,
7405 SVGFESpecularLightingElement: C,
7406 SVGFESpotLightElement: C,
7407 SVGFETileElement: C,
7408 SVGFETurbulenceElement: C,
7409 SVGFilterElement: C,
7410 SVGForeignObjectElement: C,
7411 SVGGElement: C,
7412 SVGGeometryElement: C,
7413 SVGGradientElement: C,
7414 SVGGraphicsElement: C,
7415 SVGImageElement: C,
7416 SVGLength: C,
7417 SVGLengthList: C,
7418 SVGLinearGradientElement: C,
7419 SVGLineElement: C,
7420 SVGMarkerElement: C,
7421 SVGMaskElement: C,
7422 SVGMatrix: C,
7423 SVGMetadataElement: C,
7424 SVGMPathElement: C,
7425 SVGNumber: C,
7426 SVGNumberList: C,
7427 SVGPathElement: C,
7428 SVGPatternElement: C,
7429 SVGPoint: C,
7430 SVGPointList: C,
7431 SVGPolygonElement: C,
7432 SVGPolylineElement: C,
7433 SVGPreserveAspectRatio: C,
7434 SVGRadialGradientElement: C,
7435 SVGRect: C,
7436 SVGRectElement: C,
7437 SVGScriptElement: C,
7438 SVGSetElement: C,
7439 SVGStopElement: C,
7440 SVGStringList: C,
7441 SVGStyleElement: C,
7442 SVGSVGElement: C,
7443 SVGSwitchElement: C,
7444 SVGSymbolElement: C,
7445 SVGTextContentElement: C,
7446 SVGTextElement: C,
7447 SVGTextPathElement: C,
7448 SVGTextPositioningElement: C,
7449 SVGTitleElement: C,
7450 SVGTransform: C,
7451 SVGTransformList: C,
7452 SVGTSpanElement: C,
7453 SVGUnitTypes: C,
7454 SVGUseElement: C,
7455 SVGViewElement: C,
7456 TaskAttributionTiming: C,
7457 Text: C,
7458 TextEvent: C,
7459 TextMetrics: C,
7460 TextTrack: C,
7461 TextTrackCue: C,
7462 TextTrackCueList: C,
7463 TextTrackList: C,
7464 TimeRanges: C,
7465 toolbar: O,
7466 top: O,
7467 Touch: C,
7468 TouchEvent: C,
7469 TouchList: C,
7470 TrackEvent: C,
7471 TransitionEvent: C,
7472 TreeWalker: C,
7473 UIEvent: C,
7474 ValidityState: C,
7475 visualViewport: O,
7476 VisualViewport: C,
7477 VTTCue: C,
7478 WaveShaperNode: C,
7479 WebAssembly: O,
7480 WebGL2RenderingContext: C,
7481 WebGLActiveInfo: C,
7482 WebGLBuffer: C,
7483 WebGLContextEvent: C,
7484 WebGLFramebuffer: C,
7485 WebGLProgram: C,
7486 WebGLQuery: C,
7487 WebGLRenderbuffer: C,
7488 WebGLRenderingContext: C,
7489 WebGLSampler: C,
7490 WebGLShader: C,
7491 WebGLShaderPrecisionFormat: C,
7492 WebGLSync: C,
7493 WebGLTexture: C,
7494 WebGLTransformFeedback: C,
7495 WebGLUniformLocation: C,
7496 WebGLVertexArrayObject: C,
7497 WebSocket: C,
7498 WheelEvent: C,
7499 Window: C,
7500 Worker: C,
7501 WritableStream: C,
7502 XMLDocument: C,
7503 XMLHttpRequest: C,
7504 XMLHttpRequestEventTarget: C,
7505 XMLHttpRequestUpload: C,
7506 XMLSerializer: C,
7507 XPathEvaluator: C,
7508 XPathExpression: C,
7509 XPathResult: C,
7510 XSLTProcessor: C
7511};
7512for (const global of ['window', 'global', 'self', 'globalThis']) {
7513 knownGlobals[global] = knownGlobals;
7514}
7515function getGlobalAtPath(path) {
7516 let currentGlobal = knownGlobals;
7517 for (const pathSegment of path) {
7518 if (typeof pathSegment !== 'string') {
7519 return null;
7520 }
7521 currentGlobal = currentGlobal[pathSegment];
7522 if (!currentGlobal) {
7523 return null;
7524 }
7525 }
7526 return currentGlobal[ValueProperties];
7527}
7528
7529class GlobalVariable extends Variable {
7530 constructor() {
7531 super(...arguments);
7532 // Ensure we use live-bindings for globals as we do not know if they have
7533 // been reassigned
7534 this.isReassigned = true;
7535 }
7536 getLiteralValueAtPath(path, _recursionTracker, _origin) {
7537 return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
7538 }
7539 hasEffectsOnInteractionAtPath(path, interaction, context) {
7540 switch (interaction.type) {
7541 case INTERACTION_ACCESSED:
7542 if (path.length === 0) {
7543 // Technically, "undefined" is a global variable of sorts
7544 return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
7545 }
7546 return !getGlobalAtPath([this.name, ...path].slice(0, -1));
7547 case INTERACTION_ASSIGNED:
7548 return true;
7549 case INTERACTION_CALLED: {
7550 const globalAtPath = getGlobalAtPath([this.name, ...path]);
7551 return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
7552 }
7553 }
7554 }
7555}
7556
7557const tdzVariableKinds = {
7558 __proto__: null,
7559 class: true,
7560 const: true,
7561 let: true,
7562 var: true
7563};
7564class Identifier extends NodeBase {
7565 constructor() {
7566 super(...arguments);
7567 this.variable = null;
7568 this.isTDZAccess = null;
7569 }
7570 addExportedVariables(variables, exportNamesByVariable) {
7571 if (exportNamesByVariable.has(this.variable)) {
7572 variables.push(this.variable);
7573 }
7574 }
7575 bind() {
7576 if (!this.variable && is_reference(this, this.parent)) {
7577 this.variable = this.scope.findVariable(this.name);
7578 this.variable.addReference(this);
7579 }
7580 }
7581 declare(kind, init) {
7582 let variable;
7583 const { treeshake } = this.context.options;
7584 switch (kind) {
7585 case 'var':
7586 variable = this.scope.addDeclaration(this, this.context, init, true);
7587 if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
7588 // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
7589 variable.markInitializersForDeoptimization();
7590 }
7591 break;
7592 case 'function':
7593 // in strict mode, functions are only hoisted within a scope but not across block scopes
7594 variable = this.scope.addDeclaration(this, this.context, init, false);
7595 break;
7596 case 'let':
7597 case 'const':
7598 case 'class':
7599 variable = this.scope.addDeclaration(this, this.context, init, false);
7600 break;
7601 case 'parameter':
7602 variable = this.scope.addParameterDeclaration(this);
7603 break;
7604 /* istanbul ignore next */
7605 default:
7606 /* istanbul ignore next */
7607 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
7608 }
7609 variable.kind = kind;
7610 return [(this.variable = variable)];
7611 }
7612 deoptimizePath(path) {
7613 var _a;
7614 if (path.length === 0 && !this.scope.contains(this.name)) {
7615 this.disallowImportReassignment();
7616 }
7617 // We keep conditional chaining because an unknown Node could have an
7618 // Identifier as property that might be deoptimized by default
7619 (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
7620 }
7621 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
7622 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
7623 }
7624 getLiteralValueAtPath(path, recursionTracker, origin) {
7625 return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
7626 }
7627 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
7628 return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
7629 }
7630 hasEffects(context) {
7631 if (!this.deoptimized)
7632 this.applyDeoptimizations();
7633 if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
7634 return true;
7635 }
7636 return (this.context.options.treeshake.unknownGlobalSideEffects &&
7637 this.variable instanceof GlobalVariable &&
7638 this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
7639 }
7640 hasEffectsOnInteractionAtPath(path, interaction, context) {
7641 switch (interaction.type) {
7642 case INTERACTION_ACCESSED:
7643 return (this.variable !== null &&
7644 this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
7645 case INTERACTION_ASSIGNED:
7646 return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
7647 case INTERACTION_CALLED:
7648 return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
7649 }
7650 }
7651 include() {
7652 if (!this.deoptimized)
7653 this.applyDeoptimizations();
7654 if (!this.included) {
7655 this.included = true;
7656 if (this.variable !== null) {
7657 this.context.includeVariableInModule(this.variable);
7658 }
7659 }
7660 }
7661 includeCallArguments(context, args) {
7662 this.variable.includeCallArguments(context, args);
7663 }
7664 isPossibleTDZ() {
7665 // return cached value to avoid issues with the next tree-shaking pass
7666 if (this.isTDZAccess !== null)
7667 return this.isTDZAccess;
7668 if (!(this.variable instanceof LocalVariable) ||
7669 !this.variable.kind ||
7670 !(this.variable.kind in tdzVariableKinds)) {
7671 return (this.isTDZAccess = false);
7672 }
7673 let decl_id;
7674 if (this.variable.declarations &&
7675 this.variable.declarations.length === 1 &&
7676 (decl_id = this.variable.declarations[0]) &&
7677 this.start < decl_id.start &&
7678 closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
7679 // a variable accessed before its declaration
7680 // in the same function or at top level of module
7681 return (this.isTDZAccess = true);
7682 }
7683 if (!this.variable.initReached) {
7684 // Either a const/let TDZ violation or
7685 // var use before declaration was encountered.
7686 return (this.isTDZAccess = true);
7687 }
7688 return (this.isTDZAccess = false);
7689 }
7690 markDeclarationReached() {
7691 this.variable.initReached = true;
7692 }
7693 render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
7694 if (this.variable) {
7695 const name = this.variable.getName(getPropertyAccess);
7696 if (name !== this.name) {
7697 code.overwrite(this.start, this.end, name, {
7698 contentOnly: true,
7699 storeName: true
7700 });
7701 if (isShorthandProperty) {
7702 code.prependRight(this.start, `${this.name}: `);
7703 }
7704 }
7705 // In strict mode, any variable named "eval" must be the actual "eval" function
7706 if (name === 'eval' &&
7707 renderedParentType === CallExpression$1 &&
7708 isCalleeOfRenderedParent) {
7709 code.appendRight(this.start, '0, ');
7710 }
7711 }
7712 }
7713 applyDeoptimizations() {
7714 this.deoptimized = true;
7715 if (this.variable instanceof LocalVariable) {
7716 this.variable.consolidateInitializers();
7717 this.context.requestTreeshakingPass();
7718 }
7719 }
7720 disallowImportReassignment() {
7721 return this.context.error({
7722 code: 'ILLEGAL_REASSIGNMENT',
7723 message: `Illegal reassignment to import '${this.name}'`
7724 }, this.start);
7725 }
7726 getVariableRespectingTDZ() {
7727 if (this.isPossibleTDZ()) {
7728 return UNKNOWN_EXPRESSION;
7729 }
7730 return this.variable;
7731 }
7732}
7733function closestParentFunctionOrProgram(node) {
7734 while (node && !/^Program|Function/.test(node.type)) {
7735 node = node.parent;
7736 }
7737 // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
7738 return node;
7739}
7740
7741function treeshakeNode(node, code, start, end) {
7742 code.remove(start, end);
7743 if (node.annotations) {
7744 for (const annotation of node.annotations) {
7745 if (annotation.start < start) {
7746 code.remove(annotation.start, annotation.end);
7747 }
7748 else {
7749 return;
7750 }
7751 }
7752 }
7753}
7754function removeAnnotations(node, code) {
7755 if (!node.annotations && node.parent.type === ExpressionStatement$1) {
7756 node = node.parent;
7757 }
7758 if (node.annotations) {
7759 for (const annotation of node.annotations) {
7760 code.remove(annotation.start, annotation.end);
7761 }
7762 }
7763}
7764
7765const NO_SEMICOLON = { isNoStatement: true };
7766// This assumes there are only white-space and comments between start and the string we are looking for
7767function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
7768 let searchPos, charCodeAfterSlash;
7769 searchPos = code.indexOf(searchString, start);
7770 while (true) {
7771 start = code.indexOf('/', start);
7772 if (start === -1 || start >= searchPos)
7773 return searchPos;
7774 charCodeAfterSlash = code.charCodeAt(++start);
7775 ++start;
7776 // With our assumption, '/' always starts a comment. Determine comment type:
7777 start =
7778 charCodeAfterSlash === 47 /*"/"*/
7779 ? code.indexOf('\n', start) + 1
7780 : code.indexOf('*/', start) + 2;
7781 if (start > searchPos) {
7782 searchPos = code.indexOf(searchString, start);
7783 }
7784 }
7785}
7786const NON_WHITESPACE = /\S/g;
7787function findNonWhiteSpace(code, index) {
7788 NON_WHITESPACE.lastIndex = index;
7789 const result = NON_WHITESPACE.exec(code);
7790 return result.index;
7791}
7792// This assumes "code" only contains white-space and comments
7793// Returns position of line-comment if applicable
7794function findFirstLineBreakOutsideComment(code) {
7795 let lineBreakPos, charCodeAfterSlash, start = 0;
7796 lineBreakPos = code.indexOf('\n', start);
7797 while (true) {
7798 start = code.indexOf('/', start);
7799 if (start === -1 || start > lineBreakPos)
7800 return [lineBreakPos, lineBreakPos + 1];
7801 // With our assumption, '/' always starts a comment. Determine comment type:
7802 charCodeAfterSlash = code.charCodeAt(start + 1);
7803 if (charCodeAfterSlash === 47 /*"/"*/)
7804 return [start, lineBreakPos + 1];
7805 start = code.indexOf('*/', start + 3) + 2;
7806 if (start > lineBreakPos) {
7807 lineBreakPos = code.indexOf('\n', start);
7808 }
7809 }
7810}
7811function renderStatementList(statements, code, start, end, options) {
7812 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
7813 let nextNode = statements[0];
7814 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
7815 if (nextNodeNeedsBoundaries) {
7816 nextNodeStart =
7817 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
7818 }
7819 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
7820 currentNode = nextNode;
7821 currentNodeStart = nextNodeStart;
7822 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
7823 nextNode = statements[nextIndex];
7824 nextNodeNeedsBoundaries =
7825 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
7826 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
7827 nextNodeStart =
7828 currentNode.end +
7829 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
7830 if (currentNode.included) {
7831 currentNodeNeedsBoundaries
7832 ? currentNode.render(code, options, {
7833 end: nextNodeStart,
7834 start: currentNodeStart
7835 })
7836 : currentNode.render(code, options);
7837 }
7838 else {
7839 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
7840 }
7841 }
7842 else {
7843 currentNode.render(code, options);
7844 }
7845 }
7846}
7847// This assumes that the first character is not part of the first node
7848function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
7849 const splitUpNodes = [];
7850 let node, nextNode, nextNodeStart, contentEnd, char;
7851 let separator = start - 1;
7852 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
7853 nextNode = nodes[nextIndex];
7854 if (node !== undefined) {
7855 separator =
7856 node.end +
7857 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
7858 }
7859 nextNodeStart = contentEnd =
7860 separator +
7861 1 +
7862 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
7863 while (((char = code.original.charCodeAt(nextNodeStart)),
7864 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
7865 nextNodeStart++;
7866 if (node !== undefined) {
7867 splitUpNodes.push({
7868 contentEnd,
7869 end: nextNodeStart,
7870 node,
7871 separator,
7872 start
7873 });
7874 }
7875 node = nextNode;
7876 start = nextNodeStart;
7877 }
7878 splitUpNodes.push({
7879 contentEnd: end,
7880 end,
7881 node: node,
7882 separator: null,
7883 start
7884 });
7885 return splitUpNodes;
7886}
7887// This assumes there are only white-space and comments between start and end
7888function removeLineBreaks(code, start, end) {
7889 while (true) {
7890 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
7891 if (removeStart === -1) {
7892 break;
7893 }
7894 code.remove(start + removeStart, (start += removeEnd));
7895 }
7896}
7897
7898class BlockScope extends ChildScope {
7899 addDeclaration(identifier, context, init, isHoisted) {
7900 if (isHoisted) {
7901 const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
7902 // Necessary to make sure the init is deoptimized for conditional declarations.
7903 // We cannot call deoptimizePath here.
7904 variable.markInitializersForDeoptimization();
7905 return variable;
7906 }
7907 else {
7908 return super.addDeclaration(identifier, context, init, false);
7909 }
7910 }
7911}
7912
7913class ExpressionStatement extends NodeBase {
7914 initialise() {
7915 if (this.directive &&
7916 this.directive !== 'use strict' &&
7917 this.parent.type === Program$1) {
7918 this.context.warn(
7919 // This is necessary, because either way (deleting or not) can lead to errors.
7920 {
7921 code: 'MODULE_LEVEL_DIRECTIVE',
7922 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
7923 }, this.start);
7924 }
7925 }
7926 render(code, options) {
7927 super.render(code, options);
7928 if (this.included)
7929 this.insertSemicolon(code);
7930 }
7931 shouldBeIncluded(context) {
7932 if (this.directive && this.directive !== 'use strict')
7933 return this.parent.type !== Program$1;
7934 return super.shouldBeIncluded(context);
7935 }
7936 applyDeoptimizations() { }
7937}
7938
7939class BlockStatement extends NodeBase {
7940 constructor() {
7941 super(...arguments);
7942 this.directlyIncluded = false;
7943 }
7944 addImplicitReturnExpressionToScope() {
7945 const lastStatement = this.body[this.body.length - 1];
7946 if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
7947 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
7948 }
7949 }
7950 createScope(parentScope) {
7951 this.scope = this.parent.preventChildBlockScope
7952 ? parentScope
7953 : new BlockScope(parentScope);
7954 }
7955 hasEffects(context) {
7956 if (this.deoptimizeBody)
7957 return true;
7958 for (const node of this.body) {
7959 if (context.brokenFlow)
7960 break;
7961 if (node.hasEffects(context))
7962 return true;
7963 }
7964 return false;
7965 }
7966 include(context, includeChildrenRecursively) {
7967 if (!(this.deoptimizeBody && this.directlyIncluded)) {
7968 this.included = true;
7969 this.directlyIncluded = true;
7970 if (this.deoptimizeBody)
7971 includeChildrenRecursively = true;
7972 for (const node of this.body) {
7973 if (includeChildrenRecursively || node.shouldBeIncluded(context))
7974 node.include(context, includeChildrenRecursively);
7975 }
7976 }
7977 }
7978 initialise() {
7979 const firstBodyStatement = this.body[0];
7980 this.deoptimizeBody =
7981 firstBodyStatement instanceof ExpressionStatement &&
7982 firstBodyStatement.directive === 'use asm';
7983 }
7984 render(code, options) {
7985 if (this.body.length) {
7986 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
7987 }
7988 else {
7989 super.render(code, options);
7990 }
7991 }
7992}
7993
7994class RestElement extends NodeBase {
7995 constructor() {
7996 super(...arguments);
7997 this.declarationInit = null;
7998 }
7999 addExportedVariables(variables, exportNamesByVariable) {
8000 this.argument.addExportedVariables(variables, exportNamesByVariable);
8001 }
8002 declare(kind, init) {
8003 this.declarationInit = init;
8004 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
8005 }
8006 deoptimizePath(path) {
8007 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
8008 }
8009 hasEffectsOnInteractionAtPath(path, interaction, context) {
8010 return (path.length > 0 ||
8011 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
8012 }
8013 markDeclarationReached() {
8014 this.argument.markDeclarationReached();
8015 }
8016 applyDeoptimizations() {
8017 this.deoptimized = true;
8018 if (this.declarationInit !== null) {
8019 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8020 this.context.requestTreeshakingPass();
8021 }
8022 }
8023}
8024
8025class FunctionBase extends NodeBase {
8026 constructor() {
8027 super(...arguments);
8028 this.objectEntity = null;
8029 this.deoptimizedReturn = false;
8030 }
8031 deoptimizePath(path) {
8032 this.getObjectEntity().deoptimizePath(path);
8033 if (path.length === 1 && path[0] === UnknownKey) {
8034 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
8035 // which means the return expression needs to be reassigned
8036 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
8037 }
8038 }
8039 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8040 if (path.length > 0) {
8041 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8042 }
8043 }
8044 getLiteralValueAtPath(path, recursionTracker, origin) {
8045 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
8046 }
8047 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8048 if (path.length > 0) {
8049 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8050 }
8051 if (this.async) {
8052 if (!this.deoptimizedReturn) {
8053 this.deoptimizedReturn = true;
8054 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
8055 this.context.requestTreeshakingPass();
8056 }
8057 return UNKNOWN_EXPRESSION;
8058 }
8059 return this.scope.getReturnExpression();
8060 }
8061 hasEffectsOnInteractionAtPath(path, interaction, context) {
8062 if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
8063 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
8064 }
8065 if (this.async) {
8066 const { propertyReadSideEffects } = this.context.options
8067 .treeshake;
8068 const returnExpression = this.scope.getReturnExpression();
8069 if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
8070 (propertyReadSideEffects &&
8071 (propertyReadSideEffects === 'always' ||
8072 returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
8073 return true;
8074 }
8075 }
8076 for (const param of this.params) {
8077 if (param.hasEffects(context))
8078 return true;
8079 }
8080 return false;
8081 }
8082 include(context, includeChildrenRecursively) {
8083 if (!this.deoptimized)
8084 this.applyDeoptimizations();
8085 this.included = true;
8086 const { brokenFlow } = context;
8087 context.brokenFlow = BROKEN_FLOW_NONE;
8088 this.body.include(context, includeChildrenRecursively);
8089 context.brokenFlow = brokenFlow;
8090 }
8091 includeCallArguments(context, args) {
8092 this.scope.includeCallArguments(context, args);
8093 }
8094 initialise() {
8095 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
8096 if (this.body instanceof BlockStatement) {
8097 this.body.addImplicitReturnExpressionToScope();
8098 }
8099 else {
8100 this.scope.addReturnExpression(this.body);
8101 }
8102 }
8103 parseNode(esTreeNode) {
8104 if (esTreeNode.body.type === BlockStatement$1) {
8105 this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
8106 }
8107 super.parseNode(esTreeNode);
8108 }
8109 applyDeoptimizations() { }
8110}
8111FunctionBase.prototype.preventChildBlockScope = true;
8112
8113class ArrowFunctionExpression extends FunctionBase {
8114 constructor() {
8115 super(...arguments);
8116 this.objectEntity = null;
8117 }
8118 createScope(parentScope) {
8119 this.scope = new ReturnValueScope(parentScope, this.context);
8120 }
8121 hasEffects() {
8122 if (!this.deoptimized)
8123 this.applyDeoptimizations();
8124 return false;
8125 }
8126 hasEffectsOnInteractionAtPath(path, interaction, context) {
8127 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
8128 return true;
8129 if (interaction.type === INTERACTION_CALLED) {
8130 const { ignore, brokenFlow } = context;
8131 context.ignore = {
8132 breaks: false,
8133 continues: false,
8134 labels: new Set(),
8135 returnYield: true
8136 };
8137 if (this.body.hasEffects(context))
8138 return true;
8139 context.ignore = ignore;
8140 context.brokenFlow = brokenFlow;
8141 }
8142 return false;
8143 }
8144 include(context, includeChildrenRecursively) {
8145 super.include(context, includeChildrenRecursively);
8146 for (const param of this.params) {
8147 if (!(param instanceof Identifier)) {
8148 param.include(context, includeChildrenRecursively);
8149 }
8150 }
8151 }
8152 getObjectEntity() {
8153 if (this.objectEntity !== null) {
8154 return this.objectEntity;
8155 }
8156 return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
8157 }
8158}
8159
8160function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
8161 if (exportedVariables.length === 1 &&
8162 exportNamesByVariable.get(exportedVariables[0]).length === 1) {
8163 const variable = exportedVariables[0];
8164 return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
8165 }
8166 else {
8167 const fields = [];
8168 for (const variable of exportedVariables) {
8169 for (const exportName of exportNamesByVariable.get(variable)) {
8170 fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
8171 }
8172 }
8173 return `exports(${getObject(fields, { lineBreakIndent: null })})`;
8174 }
8175}
8176function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
8177 code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
8178 code.appendLeft(expressionEnd, ')');
8179}
8180function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
8181 const { _, getDirectReturnIifeLeft } = options.snippets;
8182 code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
8183 code.appendLeft(expressionEnd, ')');
8184}
8185function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
8186 const { _, getPropertyAccess } = options.snippets;
8187 code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
8188 if (needsParens) {
8189 code.prependRight(expressionStart, '(');
8190 code.appendLeft(expressionEnd, ')');
8191 }
8192}
8193function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
8194 const { _ } = options.snippets;
8195 code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
8196 if (needsParens) {
8197 code.prependRight(expressionStart, '(');
8198 code.appendLeft(expressionEnd, ')');
8199 }
8200}
8201
8202class ObjectPattern extends NodeBase {
8203 addExportedVariables(variables, exportNamesByVariable) {
8204 for (const property of this.properties) {
8205 if (property.type === Property$1) {
8206 property.value.addExportedVariables(variables, exportNamesByVariable);
8207 }
8208 else {
8209 property.argument.addExportedVariables(variables, exportNamesByVariable);
8210 }
8211 }
8212 }
8213 declare(kind, init) {
8214 const variables = [];
8215 for (const property of this.properties) {
8216 variables.push(...property.declare(kind, init));
8217 }
8218 return variables;
8219 }
8220 deoptimizePath(path) {
8221 if (path.length === 0) {
8222 for (const property of this.properties) {
8223 property.deoptimizePath(path);
8224 }
8225 }
8226 }
8227 hasEffectsOnInteractionAtPath(
8228 // At the moment, this is only triggered for assignment left-hand sides,
8229 // where the path is empty
8230 _path, interaction, context) {
8231 for (const property of this.properties) {
8232 if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
8233 return true;
8234 }
8235 return false;
8236 }
8237 markDeclarationReached() {
8238 for (const property of this.properties) {
8239 property.markDeclarationReached();
8240 }
8241 }
8242}
8243
8244class AssignmentExpression extends NodeBase {
8245 hasEffects(context) {
8246 const { deoptimized, left, right } = this;
8247 if (!deoptimized)
8248 this.applyDeoptimizations();
8249 // MemberExpressions do not access the property before assignments if the
8250 // operator is '='.
8251 return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
8252 }
8253 hasEffectsOnInteractionAtPath(path, interaction, context) {
8254 return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
8255 }
8256 include(context, includeChildrenRecursively) {
8257 const { deoptimized, left, right, operator } = this;
8258 if (!deoptimized)
8259 this.applyDeoptimizations();
8260 this.included = true;
8261 if (includeChildrenRecursively ||
8262 operator !== '=' ||
8263 left.included ||
8264 left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
8265 left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
8266 }
8267 right.include(context, includeChildrenRecursively);
8268 }
8269 initialise() {
8270 this.left.setAssignedValue(this.right);
8271 }
8272 render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
8273 const { left, right, start, end, parent } = this;
8274 if (left.included) {
8275 left.render(code, options);
8276 right.render(code, options);
8277 }
8278 else {
8279 const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
8280 code.remove(start, inclusionStart);
8281 if (preventASI) {
8282 removeLineBreaks(code, inclusionStart, right.start);
8283 }
8284 right.render(code, options, {
8285 renderedParentType: renderedParentType || parent.type,
8286 renderedSurroundingElement: renderedSurroundingElement || parent.type
8287 });
8288 }
8289 if (options.format === 'system') {
8290 if (left instanceof Identifier) {
8291 const variable = left.variable;
8292 const exportNames = options.exportNamesByVariable.get(variable);
8293 if (exportNames) {
8294 if (exportNames.length === 1) {
8295 renderSystemExportExpression(variable, start, end, code, options);
8296 }
8297 else {
8298 renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
8299 }
8300 return;
8301 }
8302 }
8303 else {
8304 const systemPatternExports = [];
8305 left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
8306 if (systemPatternExports.length > 0) {
8307 renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
8308 return;
8309 }
8310 }
8311 }
8312 if (left.included &&
8313 left instanceof ObjectPattern &&
8314 (renderedSurroundingElement === ExpressionStatement$1 ||
8315 renderedSurroundingElement === ArrowFunctionExpression$1)) {
8316 code.appendRight(start, '(');
8317 code.prependLeft(end, ')');
8318 }
8319 }
8320 applyDeoptimizations() {
8321 this.deoptimized = true;
8322 this.left.deoptimizePath(EMPTY_PATH);
8323 this.right.deoptimizePath(UNKNOWN_PATH);
8324 this.context.requestTreeshakingPass();
8325 }
8326}
8327
8328class AssignmentPattern extends NodeBase {
8329 addExportedVariables(variables, exportNamesByVariable) {
8330 this.left.addExportedVariables(variables, exportNamesByVariable);
8331 }
8332 declare(kind, init) {
8333 return this.left.declare(kind, init);
8334 }
8335 deoptimizePath(path) {
8336 path.length === 0 && this.left.deoptimizePath(path);
8337 }
8338 hasEffectsOnInteractionAtPath(path, interaction, context) {
8339 return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
8340 }
8341 markDeclarationReached() {
8342 this.left.markDeclarationReached();
8343 }
8344 render(code, options, { isShorthandProperty } = BLANK) {
8345 this.left.render(code, options, { isShorthandProperty });
8346 this.right.render(code, options);
8347 }
8348 applyDeoptimizations() {
8349 this.deoptimized = true;
8350 this.left.deoptimizePath(EMPTY_PATH);
8351 this.right.deoptimizePath(UNKNOWN_PATH);
8352 this.context.requestTreeshakingPass();
8353 }
8354}
8355
8356class ArgumentsVariable extends LocalVariable {
8357 constructor(context) {
8358 super('arguments', null, UNKNOWN_EXPRESSION, context);
8359 }
8360 hasEffectsOnInteractionAtPath(path, { type }) {
8361 return type !== INTERACTION_ACCESSED || path.length > 1;
8362 }
8363}
8364
8365class ThisVariable extends LocalVariable {
8366 constructor(context) {
8367 super('this', null, null, context);
8368 this.deoptimizedPaths = [];
8369 this.entitiesToBeDeoptimized = new Set();
8370 this.thisDeoptimizationList = [];
8371 this.thisDeoptimizations = new DiscriminatedPathTracker();
8372 }
8373 addEntityToBeDeoptimized(entity) {
8374 for (const path of this.deoptimizedPaths) {
8375 entity.deoptimizePath(path);
8376 }
8377 for (const { interaction, path } of this.thisDeoptimizationList) {
8378 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8379 }
8380 this.entitiesToBeDeoptimized.add(entity);
8381 }
8382 deoptimizePath(path) {
8383 if (path.length === 0 ||
8384 this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
8385 return;
8386 }
8387 this.deoptimizedPaths.push(path);
8388 for (const entity of this.entitiesToBeDeoptimized) {
8389 entity.deoptimizePath(path);
8390 }
8391 }
8392 deoptimizeThisOnInteractionAtPath(interaction, path) {
8393 const thisDeoptimization = {
8394 interaction,
8395 path
8396 };
8397 if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
8398 for (const entity of this.entitiesToBeDeoptimized) {
8399 entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
8400 }
8401 this.thisDeoptimizationList.push(thisDeoptimization);
8402 }
8403 }
8404 hasEffectsOnInteractionAtPath(path, interaction, context) {
8405 return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
8406 super.hasEffectsOnInteractionAtPath(path, interaction, context));
8407 }
8408 getInit(context) {
8409 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
8410 }
8411}
8412
8413class FunctionScope extends ReturnValueScope {
8414 constructor(parent, context) {
8415 super(parent, context);
8416 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
8417 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
8418 }
8419 findLexicalBoundary() {
8420 return this;
8421 }
8422 includeCallArguments(context, args) {
8423 super.includeCallArguments(context, args);
8424 if (this.argumentsVariable.included) {
8425 for (const arg of args) {
8426 if (!arg.included) {
8427 arg.include(context, false);
8428 }
8429 }
8430 }
8431 }
8432}
8433
8434class FunctionNode extends FunctionBase {
8435 constructor() {
8436 super(...arguments);
8437 this.objectEntity = null;
8438 }
8439 createScope(parentScope) {
8440 this.scope = new FunctionScope(parentScope, this.context);
8441 }
8442 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8443 super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8444 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
8445 this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
8446 }
8447 }
8448 hasEffects(context) {
8449 var _a;
8450 if (!this.deoptimized)
8451 this.applyDeoptimizations();
8452 return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
8453 }
8454 hasEffectsOnInteractionAtPath(path, interaction, context) {
8455 if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
8456 return true;
8457 if (interaction.type === INTERACTION_CALLED) {
8458 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
8459 context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
8460 ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
8461 : UNKNOWN_EXPRESSION);
8462 const { brokenFlow, ignore } = context;
8463 context.ignore = {
8464 breaks: false,
8465 continues: false,
8466 labels: new Set(),
8467 returnYield: true
8468 };
8469 if (this.body.hasEffects(context))
8470 return true;
8471 context.brokenFlow = brokenFlow;
8472 if (thisInit) {
8473 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
8474 }
8475 else {
8476 context.replacedVariableInits.delete(this.scope.thisVariable);
8477 }
8478 context.ignore = ignore;
8479 }
8480 return false;
8481 }
8482 include(context, includeChildrenRecursively) {
8483 var _a;
8484 super.include(context, includeChildrenRecursively);
8485 (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
8486 const hasArguments = this.scope.argumentsVariable.included;
8487 for (const param of this.params) {
8488 if (!(param instanceof Identifier) || hasArguments) {
8489 param.include(context, includeChildrenRecursively);
8490 }
8491 }
8492 }
8493 initialise() {
8494 var _a;
8495 super.initialise();
8496 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
8497 }
8498 getObjectEntity() {
8499 if (this.objectEntity !== null) {
8500 return this.objectEntity;
8501 }
8502 return (this.objectEntity = new ObjectEntity([
8503 {
8504 key: 'prototype',
8505 kind: 'init',
8506 property: new ObjectEntity([], OBJECT_PROTOTYPE)
8507 }
8508 ], OBJECT_PROTOTYPE));
8509 }
8510}
8511
8512class AwaitExpression extends NodeBase {
8513 hasEffects() {
8514 if (!this.deoptimized)
8515 this.applyDeoptimizations();
8516 return true;
8517 }
8518 include(context, includeChildrenRecursively) {
8519 if (!this.deoptimized)
8520 this.applyDeoptimizations();
8521 if (!this.included) {
8522 this.included = true;
8523 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
8524 let parent = this.parent;
8525 do {
8526 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
8527 break checkTopLevelAwait;
8528 } while ((parent = parent.parent));
8529 this.context.usesTopLevelAwait = true;
8530 }
8531 }
8532 this.argument.include(context, includeChildrenRecursively);
8533 }
8534}
8535
8536const binaryOperators = {
8537 '!=': (left, right) => left != right,
8538 '!==': (left, right) => left !== right,
8539 '%': (left, right) => left % right,
8540 '&': (left, right) => left & right,
8541 '*': (left, right) => left * right,
8542 // At the moment, "**" will be transpiled to Math.pow
8543 '**': (left, right) => left ** right,
8544 '+': (left, right) => left + right,
8545 '-': (left, right) => left - right,
8546 '/': (left, right) => left / right,
8547 '<': (left, right) => left < right,
8548 '<<': (left, right) => left << right,
8549 '<=': (left, right) => left <= right,
8550 '==': (left, right) => left == right,
8551 '===': (left, right) => left === right,
8552 '>': (left, right) => left > right,
8553 '>=': (left, right) => left >= right,
8554 '>>': (left, right) => left >> right,
8555 '>>>': (left, right) => left >>> right,
8556 '^': (left, right) => left ^ right,
8557 '|': (left, right) => left | right
8558 // We use the fallback for cases where we return something unknown
8559 // in: () => UnknownValue,
8560 // instanceof: () => UnknownValue,
8561};
8562class BinaryExpression extends NodeBase {
8563 deoptimizeCache() { }
8564 getLiteralValueAtPath(path, recursionTracker, origin) {
8565 if (path.length > 0)
8566 return UnknownValue;
8567 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8568 if (typeof leftValue === 'symbol')
8569 return UnknownValue;
8570 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8571 if (typeof rightValue === 'symbol')
8572 return UnknownValue;
8573 const operatorFn = binaryOperators[this.operator];
8574 if (!operatorFn)
8575 return UnknownValue;
8576 return operatorFn(leftValue, rightValue);
8577 }
8578 hasEffects(context) {
8579 // support some implicit type coercion runtime errors
8580 if (this.operator === '+' &&
8581 this.parent instanceof ExpressionStatement &&
8582 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
8583 return true;
8584 }
8585 return super.hasEffects(context);
8586 }
8587 hasEffectsOnInteractionAtPath(path, { type }) {
8588 return type !== INTERACTION_ACCESSED || path.length > 1;
8589 }
8590 render(code, options, { renderedSurroundingElement } = BLANK) {
8591 this.left.render(code, options, { renderedSurroundingElement });
8592 this.right.render(code, options);
8593 }
8594}
8595
8596class BreakStatement extends NodeBase {
8597 hasEffects(context) {
8598 if (this.label) {
8599 if (!context.ignore.labels.has(this.label.name))
8600 return true;
8601 context.includedLabels.add(this.label.name);
8602 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8603 }
8604 else {
8605 if (!context.ignore.breaks)
8606 return true;
8607 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
8608 }
8609 return false;
8610 }
8611 include(context) {
8612 this.included = true;
8613 if (this.label) {
8614 this.label.include();
8615 context.includedLabels.add(this.label.name);
8616 }
8617 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
8618 }
8619}
8620
8621function renderCallArguments(code, options, node) {
8622 if (node.arguments.length > 0) {
8623 if (node.arguments[node.arguments.length - 1].included) {
8624 for (const arg of node.arguments) {
8625 arg.render(code, options);
8626 }
8627 }
8628 else {
8629 let lastIncludedIndex = node.arguments.length - 2;
8630 while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
8631 lastIncludedIndex--;
8632 }
8633 if (lastIncludedIndex >= 0) {
8634 for (let index = 0; index <= lastIncludedIndex; index++) {
8635 node.arguments[index].render(code, options);
8636 }
8637 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
8638 }
8639 else {
8640 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
8641 }
8642 }
8643 }
8644}
8645
8646class Literal extends NodeBase {
8647 deoptimizeThisOnInteractionAtPath() { }
8648 getLiteralValueAtPath(path) {
8649 if (path.length > 0 ||
8650 // unknown literals can also be null but do not start with an "n"
8651 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
8652 typeof this.value === 'bigint' ||
8653 // to support shims for regular expressions
8654 this.context.code.charCodeAt(this.start) === 47) {
8655 return UnknownValue;
8656 }
8657 return this.value;
8658 }
8659 getReturnExpressionWhenCalledAtPath(path) {
8660 if (path.length !== 1)
8661 return UNKNOWN_EXPRESSION;
8662 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
8663 }
8664 hasEffectsOnInteractionAtPath(path, interaction, context) {
8665 switch (interaction.type) {
8666 case INTERACTION_ACCESSED:
8667 return path.length > (this.value === null ? 0 : 1);
8668 case INTERACTION_ASSIGNED:
8669 return true;
8670 case INTERACTION_CALLED:
8671 return (path.length !== 1 ||
8672 hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
8673 }
8674 }
8675 initialise() {
8676 this.members = getLiteralMembersForValue(this.value);
8677 }
8678 parseNode(esTreeNode) {
8679 this.value = esTreeNode.value;
8680 this.regex = esTreeNode.regex;
8681 super.parseNode(esTreeNode);
8682 }
8683 render(code) {
8684 if (typeof this.value === 'string') {
8685 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
8686 }
8687 }
8688}
8689
8690// To avoid infinite recursions
8691const MAX_PATH_DEPTH = 7;
8692function getResolvablePropertyKey(memberExpression) {
8693 return memberExpression.computed
8694 ? getResolvableComputedPropertyKey(memberExpression.property)
8695 : memberExpression.property.name;
8696}
8697function getResolvableComputedPropertyKey(propertyKey) {
8698 if (propertyKey instanceof Literal) {
8699 return String(propertyKey.value);
8700 }
8701 return null;
8702}
8703function getPathIfNotComputed(memberExpression) {
8704 const nextPathKey = memberExpression.propertyKey;
8705 const object = memberExpression.object;
8706 if (typeof nextPathKey === 'string') {
8707 if (object instanceof Identifier) {
8708 return [
8709 { key: object.name, pos: object.start },
8710 { key: nextPathKey, pos: memberExpression.property.start }
8711 ];
8712 }
8713 if (object instanceof MemberExpression) {
8714 const parentPath = getPathIfNotComputed(object);
8715 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
8716 }
8717 }
8718 return null;
8719}
8720function getStringFromPath(path) {
8721 let pathString = path[0].key;
8722 for (let index = 1; index < path.length; index++) {
8723 pathString += '.' + path[index].key;
8724 }
8725 return pathString;
8726}
8727class MemberExpression extends NodeBase {
8728 constructor() {
8729 super(...arguments);
8730 this.variable = null;
8731 this.assignmentDeoptimized = false;
8732 this.bound = false;
8733 this.expressionsToBeDeoptimized = [];
8734 this.replacement = null;
8735 }
8736 bind() {
8737 this.bound = true;
8738 const path = getPathIfNotComputed(this);
8739 const baseVariable = path && this.scope.findVariable(path[0].key);
8740 if (baseVariable && baseVariable.isNamespace) {
8741 const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
8742 if (!resolvedVariable) {
8743 super.bind();
8744 }
8745 else if (typeof resolvedVariable === 'string') {
8746 this.replacement = resolvedVariable;
8747 }
8748 else {
8749 this.variable = resolvedVariable;
8750 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
8751 }
8752 }
8753 else {
8754 super.bind();
8755 }
8756 }
8757 deoptimizeCache() {
8758 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
8759 this.expressionsToBeDeoptimized = [];
8760 this.propertyKey = UnknownKey;
8761 this.object.deoptimizePath(UNKNOWN_PATH);
8762 for (const expression of expressionsToBeDeoptimized) {
8763 expression.deoptimizeCache();
8764 }
8765 }
8766 deoptimizePath(path) {
8767 if (path.length === 0)
8768 this.disallowNamespaceReassignment();
8769 if (this.variable) {
8770 this.variable.deoptimizePath(path);
8771 }
8772 else if (!this.replacement) {
8773 if (path.length < MAX_PATH_DEPTH) {
8774 const propertyKey = this.getPropertyKey();
8775 this.object.deoptimizePath([
8776 propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
8777 ...path
8778 ]);
8779 }
8780 }
8781 }
8782 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
8783 if (this.variable) {
8784 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
8785 }
8786 else if (!this.replacement) {
8787 if (path.length < MAX_PATH_DEPTH) {
8788 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
8789 }
8790 else {
8791 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
8792 }
8793 }
8794 }
8795 getLiteralValueAtPath(path, recursionTracker, origin) {
8796 if (this.variable) {
8797 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
8798 }
8799 if (this.replacement) {
8800 return UnknownValue;
8801 }
8802 this.expressionsToBeDeoptimized.push(origin);
8803 if (path.length < MAX_PATH_DEPTH) {
8804 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
8805 }
8806 return UnknownValue;
8807 }
8808 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
8809 if (this.variable) {
8810 return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
8811 }
8812 if (this.replacement) {
8813 return UNKNOWN_EXPRESSION;
8814 }
8815 this.expressionsToBeDeoptimized.push(origin);
8816 if (path.length < MAX_PATH_DEPTH) {
8817 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
8818 }
8819 return UNKNOWN_EXPRESSION;
8820 }
8821 hasEffects(context) {
8822 if (!this.deoptimized)
8823 this.applyDeoptimizations();
8824 return (this.property.hasEffects(context) ||
8825 this.object.hasEffects(context) ||
8826 this.hasAccessEffect(context));
8827 }
8828 hasEffectsAsAssignmentTarget(context, checkAccess) {
8829 if (checkAccess && !this.deoptimized)
8830 this.applyDeoptimizations();
8831 if (!this.assignmentDeoptimized)
8832 this.applyAssignmentDeoptimization();
8833 return (this.property.hasEffects(context) ||
8834 this.object.hasEffects(context) ||
8835 (checkAccess && this.hasAccessEffect(context)) ||
8836 this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
8837 }
8838 hasEffectsOnInteractionAtPath(path, interaction, context) {
8839 if (this.variable) {
8840 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
8841 }
8842 if (this.replacement) {
8843 return true;
8844 }
8845 if (path.length < MAX_PATH_DEPTH) {
8846 return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
8847 }
8848 return true;
8849 }
8850 include(context, includeChildrenRecursively) {
8851 if (!this.deoptimized)
8852 this.applyDeoptimizations();
8853 this.includeProperties(context, includeChildrenRecursively);
8854 }
8855 includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
8856 if (!this.assignmentDeoptimized)
8857 this.applyAssignmentDeoptimization();
8858 if (deoptimizeAccess) {
8859 this.include(context, includeChildrenRecursively);
8860 }
8861 else {
8862 this.includeProperties(context, includeChildrenRecursively);
8863 }
8864 }
8865 includeCallArguments(context, args) {
8866 if (this.variable) {
8867 this.variable.includeCallArguments(context, args);
8868 }
8869 else {
8870 super.includeCallArguments(context, args);
8871 }
8872 }
8873 initialise() {
8874 this.propertyKey = getResolvablePropertyKey(this);
8875 this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
8876 }
8877 render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
8878 if (this.variable || this.replacement) {
8879 const { snippets: { getPropertyAccess } } = options;
8880 let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
8881 if (renderedParentType && isCalleeOfRenderedParent)
8882 replacement = '0, ' + replacement;
8883 code.overwrite(this.start, this.end, replacement, {
8884 contentOnly: true,
8885 storeName: true
8886 });
8887 }
8888 else {
8889 if (renderedParentType && isCalleeOfRenderedParent) {
8890 code.appendRight(this.start, '0, ');
8891 }
8892 this.object.render(code, options, { renderedSurroundingElement });
8893 this.property.render(code, options);
8894 }
8895 }
8896 setAssignedValue(value) {
8897 this.assignmentInteraction = {
8898 args: [value],
8899 thisArg: this.object,
8900 type: INTERACTION_ASSIGNED
8901 };
8902 }
8903 applyDeoptimizations() {
8904 this.deoptimized = true;
8905 const { propertyReadSideEffects } = this.context.options
8906 .treeshake;
8907 if (
8908 // Namespaces are not bound and should not be deoptimized
8909 this.bound &&
8910 propertyReadSideEffects &&
8911 !(this.variable || this.replacement)) {
8912 const propertyKey = this.getPropertyKey();
8913 this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
8914 this.context.requestTreeshakingPass();
8915 }
8916 }
8917 applyAssignmentDeoptimization() {
8918 this.assignmentDeoptimized = true;
8919 const { propertyReadSideEffects } = this.context.options
8920 .treeshake;
8921 if (
8922 // Namespaces are not bound and should not be deoptimized
8923 this.bound &&
8924 propertyReadSideEffects &&
8925 !(this.variable || this.replacement)) {
8926 this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
8927 this.context.requestTreeshakingPass();
8928 }
8929 }
8930 disallowNamespaceReassignment() {
8931 if (this.object instanceof Identifier) {
8932 const variable = this.scope.findVariable(this.object.name);
8933 if (variable.isNamespace) {
8934 if (this.variable) {
8935 this.context.includeVariableInModule(this.variable);
8936 }
8937 this.context.warn({
8938 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
8939 message: `Illegal reassignment to import '${this.object.name}'`
8940 }, this.start);
8941 }
8942 }
8943 }
8944 getPropertyKey() {
8945 if (this.propertyKey === null) {
8946 this.propertyKey = UnknownKey;
8947 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8948 return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
8949 }
8950 return this.propertyKey;
8951 }
8952 hasAccessEffect(context) {
8953 const { propertyReadSideEffects } = this.context.options
8954 .treeshake;
8955 return (!(this.variable || this.replacement) &&
8956 propertyReadSideEffects &&
8957 (propertyReadSideEffects === 'always' ||
8958 this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
8959 }
8960 includeProperties(context, includeChildrenRecursively) {
8961 if (!this.included) {
8962 this.included = true;
8963 if (this.variable) {
8964 this.context.includeVariableInModule(this.variable);
8965 }
8966 }
8967 this.object.include(context, includeChildrenRecursively);
8968 this.property.include(context, includeChildrenRecursively);
8969 }
8970}
8971function resolveNamespaceVariables(baseVariable, path, astContext) {
8972 if (path.length === 0)
8973 return baseVariable;
8974 if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
8975 return null;
8976 const exportName = path[0].key;
8977 const variable = baseVariable.context.traceExport(exportName);
8978 if (!variable) {
8979 const fileName = baseVariable.context.fileName;
8980 astContext.warn({
8981 code: 'MISSING_EXPORT',
8982 exporter: relativeId(fileName),
8983 importer: relativeId(astContext.fileName),
8984 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
8985 missing: exportName,
8986 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
8987 }, path[0].pos);
8988 return 'undefined';
8989 }
8990 return resolveNamespaceVariables(variable, path.slice(1), astContext);
8991}
8992
8993class CallExpressionBase extends NodeBase {
8994 constructor() {
8995 super(...arguments);
8996 this.returnExpression = null;
8997 this.deoptimizableDependentExpressions = [];
8998 this.expressionsToBeDeoptimized = new Set();
8999 }
9000 deoptimizeCache() {
9001 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
9002 this.returnExpression = UNKNOWN_EXPRESSION;
9003 for (const expression of this.deoptimizableDependentExpressions) {
9004 expression.deoptimizeCache();
9005 }
9006 for (const expression of this.expressionsToBeDeoptimized) {
9007 expression.deoptimizePath(UNKNOWN_PATH);
9008 }
9009 }
9010 }
9011 deoptimizePath(path) {
9012 if (path.length === 0 ||
9013 this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
9014 return;
9015 }
9016 const returnExpression = this.getReturnExpression();
9017 if (returnExpression !== UNKNOWN_EXPRESSION) {
9018 returnExpression.deoptimizePath(path);
9019 }
9020 }
9021 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9022 const returnExpression = this.getReturnExpression(recursionTracker);
9023 if (returnExpression === UNKNOWN_EXPRESSION) {
9024 interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
9025 }
9026 else {
9027 recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9028 this.expressionsToBeDeoptimized.add(interaction.thisArg);
9029 returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9030 }, undefined);
9031 }
9032 }
9033 getLiteralValueAtPath(path, recursionTracker, origin) {
9034 const returnExpression = this.getReturnExpression(recursionTracker);
9035 if (returnExpression === UNKNOWN_EXPRESSION) {
9036 return UnknownValue;
9037 }
9038 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9039 this.deoptimizableDependentExpressions.push(origin);
9040 return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
9041 }, UnknownValue);
9042 }
9043 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9044 const returnExpression = this.getReturnExpression(recursionTracker);
9045 if (this.returnExpression === UNKNOWN_EXPRESSION) {
9046 return UNKNOWN_EXPRESSION;
9047 }
9048 return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9049 this.deoptimizableDependentExpressions.push(origin);
9050 return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9051 }, UNKNOWN_EXPRESSION);
9052 }
9053 hasEffectsOnInteractionAtPath(path, interaction, context) {
9054 const { type } = interaction;
9055 if (type === INTERACTION_CALLED) {
9056 if ((interaction.withNew
9057 ? context.instantiated
9058 : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
9059 return false;
9060 }
9061 }
9062 else if ((type === INTERACTION_ASSIGNED
9063 ? context.assigned
9064 : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
9065 return false;
9066 }
9067 return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
9068 }
9069}
9070
9071class CallExpression extends CallExpressionBase {
9072 bind() {
9073 super.bind();
9074 if (this.callee instanceof Identifier) {
9075 const variable = this.scope.findVariable(this.callee.name);
9076 if (variable.isNamespace) {
9077 this.context.warn({
9078 code: 'CANNOT_CALL_NAMESPACE',
9079 message: `Cannot call a namespace ('${this.callee.name}')`
9080 }, this.start);
9081 }
9082 if (this.callee.name === 'eval') {
9083 this.context.warn({
9084 code: 'EVAL',
9085 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
9086 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
9087 }, this.start);
9088 }
9089 }
9090 this.interaction = {
9091 args: this.arguments,
9092 thisArg: this.callee instanceof MemberExpression && !this.callee.variable
9093 ? this.callee.object
9094 : null,
9095 type: INTERACTION_CALLED,
9096 withNew: false
9097 };
9098 }
9099 hasEffects(context) {
9100 try {
9101 for (const argument of this.arguments) {
9102 if (argument.hasEffects(context))
9103 return true;
9104 }
9105 if (this.context.options.treeshake.annotations &&
9106 this.annotations)
9107 return false;
9108 return (this.callee.hasEffects(context) ||
9109 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
9110 }
9111 finally {
9112 if (!this.deoptimized)
9113 this.applyDeoptimizations();
9114 }
9115 }
9116 include(context, includeChildrenRecursively) {
9117 if (!this.deoptimized)
9118 this.applyDeoptimizations();
9119 if (includeChildrenRecursively) {
9120 super.include(context, includeChildrenRecursively);
9121 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
9122 this.callee instanceof Identifier &&
9123 this.callee.variable) {
9124 this.callee.variable.markCalledFromTryStatement();
9125 }
9126 }
9127 else {
9128 this.included = true;
9129 this.callee.include(context, false);
9130 }
9131 this.callee.includeCallArguments(context, this.arguments);
9132 }
9133 render(code, options, { renderedSurroundingElement } = BLANK) {
9134 this.callee.render(code, options, {
9135 isCalleeOfRenderedParent: true,
9136 renderedSurroundingElement
9137 });
9138 renderCallArguments(code, options, this);
9139 }
9140 applyDeoptimizations() {
9141 this.deoptimized = true;
9142 if (this.interaction.thisArg) {
9143 this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
9144 }
9145 for (const argument of this.arguments) {
9146 // This will make sure all properties of parameters behave as "unknown"
9147 argument.deoptimizePath(UNKNOWN_PATH);
9148 }
9149 this.context.requestTreeshakingPass();
9150 }
9151 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
9152 if (this.returnExpression === null) {
9153 this.returnExpression = UNKNOWN_EXPRESSION;
9154 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
9155 }
9156 return this.returnExpression;
9157 }
9158}
9159
9160class CatchScope extends ParameterScope {
9161 addDeclaration(identifier, context, init, isHoisted) {
9162 const existingParameter = this.variables.get(identifier.name);
9163 if (existingParameter) {
9164 // While we still create a hoisted declaration, the initializer goes to
9165 // the parameter. Note that technically, the declaration now belongs to
9166 // two variables, which is not correct but should not cause issues.
9167 this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
9168 existingParameter.addDeclaration(identifier, init);
9169 return existingParameter;
9170 }
9171 return this.parent.addDeclaration(identifier, context, init, isHoisted);
9172 }
9173}
9174
9175class CatchClause extends NodeBase {
9176 createScope(parentScope) {
9177 this.scope = new CatchScope(parentScope, this.context);
9178 }
9179 parseNode(esTreeNode) {
9180 // Parameters need to be declared first as the logic is that initializers
9181 // of hoisted body variables are associated with parameters of the same
9182 // name instead of the variable
9183 const { param } = esTreeNode;
9184 if (param) {
9185 this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
9186 this.param.declare('parameter', UNKNOWN_EXPRESSION);
9187 }
9188 super.parseNode(esTreeNode);
9189 }
9190}
9191
9192class ChainExpression extends NodeBase {
9193}
9194
9195class ClassBodyScope extends ChildScope {
9196 constructor(parent, classNode, context) {
9197 super(parent);
9198 this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
9199 this.instanceScope = new ChildScope(this);
9200 this.instanceScope.variables.set('this', new ThisVariable(context));
9201 }
9202 findLexicalBoundary() {
9203 return this;
9204 }
9205}
9206
9207class ClassBody extends NodeBase {
9208 createScope(parentScope) {
9209 this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
9210 }
9211 include(context, includeChildrenRecursively) {
9212 this.included = true;
9213 this.context.includeVariableInModule(this.scope.thisVariable);
9214 for (const definition of this.body) {
9215 definition.include(context, includeChildrenRecursively);
9216 }
9217 }
9218 parseNode(esTreeNode) {
9219 const body = (this.body = []);
9220 for (const definition of esTreeNode.body) {
9221 body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
9222 }
9223 super.parseNode(esTreeNode);
9224 }
9225 applyDeoptimizations() { }
9226}
9227
9228class MethodBase extends NodeBase {
9229 constructor() {
9230 super(...arguments);
9231 this.accessedValue = null;
9232 }
9233 // As getter properties directly receive their values from fixed function
9234 // expressions, there is no known situation where a getter is deoptimized.
9235 deoptimizeCache() { }
9236 deoptimizePath(path) {
9237 this.getAccessedValue().deoptimizePath(path);
9238 }
9239 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9240 if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
9241 return this.value.deoptimizeThisOnInteractionAtPath({
9242 args: NO_ARGS,
9243 thisArg: interaction.thisArg,
9244 type: INTERACTION_CALLED,
9245 withNew: false
9246 }, EMPTY_PATH, recursionTracker);
9247 }
9248 if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
9249 return this.value.deoptimizeThisOnInteractionAtPath({
9250 args: interaction.args,
9251 thisArg: interaction.thisArg,
9252 type: INTERACTION_CALLED,
9253 withNew: false
9254 }, EMPTY_PATH, recursionTracker);
9255 }
9256 this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9257 }
9258 getLiteralValueAtPath(path, recursionTracker, origin) {
9259 return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
9260 }
9261 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9262 return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9263 }
9264 hasEffects(context) {
9265 return this.key.hasEffects(context);
9266 }
9267 hasEffectsOnInteractionAtPath(path, interaction, context) {
9268 if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
9269 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9270 args: NO_ARGS,
9271 thisArg: interaction.thisArg,
9272 type: INTERACTION_CALLED,
9273 withNew: false
9274 }, context);
9275 }
9276 // setters are only called for empty paths
9277 if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
9278 return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
9279 args: interaction.args,
9280 thisArg: interaction.thisArg,
9281 type: INTERACTION_CALLED,
9282 withNew: false
9283 }, context);
9284 }
9285 return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
9286 }
9287 applyDeoptimizations() { }
9288 getAccessedValue() {
9289 if (this.accessedValue === null) {
9290 if (this.kind === 'get') {
9291 this.accessedValue = UNKNOWN_EXPRESSION;
9292 return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
9293 }
9294 else {
9295 return (this.accessedValue = this.value);
9296 }
9297 }
9298 return this.accessedValue;
9299 }
9300}
9301
9302class MethodDefinition extends MethodBase {
9303 applyDeoptimizations() { }
9304}
9305
9306class ObjectMember extends ExpressionEntity {
9307 constructor(object, key) {
9308 super();
9309 this.object = object;
9310 this.key = key;
9311 }
9312 deoptimizePath(path) {
9313 this.object.deoptimizePath([this.key, ...path]);
9314 }
9315 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9316 this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
9317 }
9318 getLiteralValueAtPath(path, recursionTracker, origin) {
9319 return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
9320 }
9321 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9322 return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
9323 }
9324 hasEffectsOnInteractionAtPath(path, interaction, context) {
9325 return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
9326 }
9327}
9328
9329class ClassNode extends NodeBase {
9330 constructor() {
9331 super(...arguments);
9332 this.objectEntity = null;
9333 }
9334 createScope(parentScope) {
9335 this.scope = new ChildScope(parentScope);
9336 }
9337 deoptimizeCache() {
9338 this.getObjectEntity().deoptimizeAllProperties();
9339 }
9340 deoptimizePath(path) {
9341 this.getObjectEntity().deoptimizePath(path);
9342 }
9343 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9344 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9345 }
9346 getLiteralValueAtPath(path, recursionTracker, origin) {
9347 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
9348 }
9349 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9350 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9351 }
9352 hasEffects(context) {
9353 var _a, _b;
9354 if (!this.deoptimized)
9355 this.applyDeoptimizations();
9356 const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
9357 (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
9358 return initEffect || super.hasEffects(context);
9359 }
9360 hasEffectsOnInteractionAtPath(path, interaction, context) {
9361 var _a;
9362 if (interaction.type === INTERACTION_CALLED && path.length === 0) {
9363 return (!interaction.withNew ||
9364 (this.classConstructor !== null
9365 ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
9366 : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
9367 false);
9368 }
9369 else {
9370 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
9371 }
9372 }
9373 include(context, includeChildrenRecursively) {
9374 var _a;
9375 if (!this.deoptimized)
9376 this.applyDeoptimizations();
9377 this.included = true;
9378 (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
9379 this.body.include(context, includeChildrenRecursively);
9380 if (this.id) {
9381 this.id.markDeclarationReached();
9382 this.id.include();
9383 }
9384 }
9385 initialise() {
9386 var _a;
9387 (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
9388 for (const method of this.body.body) {
9389 if (method instanceof MethodDefinition && method.kind === 'constructor') {
9390 this.classConstructor = method;
9391 return;
9392 }
9393 }
9394 this.classConstructor = null;
9395 }
9396 applyDeoptimizations() {
9397 this.deoptimized = true;
9398 for (const definition of this.body.body) {
9399 if (!(definition.static ||
9400 (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
9401 // Calls to methods are not tracked, ensure that the return value is deoptimized
9402 definition.deoptimizePath(UNKNOWN_PATH);
9403 }
9404 }
9405 this.context.requestTreeshakingPass();
9406 }
9407 getObjectEntity() {
9408 if (this.objectEntity !== null) {
9409 return this.objectEntity;
9410 }
9411 const staticProperties = [];
9412 const dynamicMethods = [];
9413 for (const definition of this.body.body) {
9414 const properties = definition.static ? staticProperties : dynamicMethods;
9415 const definitionKind = definition.kind;
9416 // Note that class fields do not end up on the prototype
9417 if (properties === dynamicMethods && !definitionKind)
9418 continue;
9419 const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
9420 let key;
9421 if (definition.computed) {
9422 const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9423 if (typeof keyValue === 'symbol') {
9424 properties.push({ key: UnknownKey, kind, property: definition });
9425 continue;
9426 }
9427 else {
9428 key = String(keyValue);
9429 }
9430 }
9431 else {
9432 key =
9433 definition.key instanceof Identifier
9434 ? definition.key.name
9435 : String(definition.key.value);
9436 }
9437 properties.push({ key, kind, property: definition });
9438 }
9439 staticProperties.unshift({
9440 key: 'prototype',
9441 kind: 'init',
9442 property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
9443 });
9444 return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
9445 }
9446}
9447
9448class ClassDeclaration extends ClassNode {
9449 initialise() {
9450 super.initialise();
9451 if (this.id !== null) {
9452 this.id.variable.isId = true;
9453 }
9454 }
9455 parseNode(esTreeNode) {
9456 if (esTreeNode.id !== null) {
9457 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9458 }
9459 super.parseNode(esTreeNode);
9460 }
9461 render(code, options) {
9462 const { exportNamesByVariable, format, snippets: { _ } } = options;
9463 if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
9464 code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
9465 }
9466 super.render(code, options);
9467 }
9468}
9469
9470class ClassExpression extends ClassNode {
9471 render(code, options, { renderedSurroundingElement } = BLANK) {
9472 super.render(code, options);
9473 if (renderedSurroundingElement === ExpressionStatement$1) {
9474 code.appendRight(this.start, '(');
9475 code.prependLeft(this.end, ')');
9476 }
9477 }
9478}
9479
9480class MultiExpression extends ExpressionEntity {
9481 constructor(expressions) {
9482 super();
9483 this.expressions = expressions;
9484 this.included = false;
9485 }
9486 deoptimizePath(path) {
9487 for (const expression of this.expressions) {
9488 expression.deoptimizePath(path);
9489 }
9490 }
9491 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9492 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
9493 }
9494 hasEffectsOnInteractionAtPath(path, interaction, context) {
9495 for (const expression of this.expressions) {
9496 if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
9497 return true;
9498 }
9499 return false;
9500 }
9501}
9502
9503class ConditionalExpression extends NodeBase {
9504 constructor() {
9505 super(...arguments);
9506 this.expressionsToBeDeoptimized = [];
9507 this.isBranchResolutionAnalysed = false;
9508 this.usedBranch = null;
9509 }
9510 deoptimizeCache() {
9511 if (this.usedBranch !== null) {
9512 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
9513 this.usedBranch = null;
9514 unusedBranch.deoptimizePath(UNKNOWN_PATH);
9515 for (const expression of this.expressionsToBeDeoptimized) {
9516 expression.deoptimizeCache();
9517 }
9518 }
9519 }
9520 deoptimizePath(path) {
9521 const usedBranch = this.getUsedBranch();
9522 if (!usedBranch) {
9523 this.consequent.deoptimizePath(path);
9524 this.alternate.deoptimizePath(path);
9525 }
9526 else {
9527 usedBranch.deoptimizePath(path);
9528 }
9529 }
9530 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
9531 this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9532 this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9533 }
9534 getLiteralValueAtPath(path, recursionTracker, origin) {
9535 const usedBranch = this.getUsedBranch();
9536 if (!usedBranch)
9537 return UnknownValue;
9538 this.expressionsToBeDeoptimized.push(origin);
9539 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
9540 }
9541 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9542 const usedBranch = this.getUsedBranch();
9543 if (!usedBranch)
9544 return new MultiExpression([
9545 this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
9546 this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
9547 ]);
9548 this.expressionsToBeDeoptimized.push(origin);
9549 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
9550 }
9551 hasEffects(context) {
9552 if (this.test.hasEffects(context))
9553 return true;
9554 const usedBranch = this.getUsedBranch();
9555 if (!usedBranch) {
9556 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
9557 }
9558 return usedBranch.hasEffects(context);
9559 }
9560 hasEffectsOnInteractionAtPath(path, interaction, context) {
9561 const usedBranch = this.getUsedBranch();
9562 if (!usedBranch) {
9563 return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
9564 this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
9565 }
9566 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
9567 }
9568 include(context, includeChildrenRecursively) {
9569 this.included = true;
9570 const usedBranch = this.getUsedBranch();
9571 if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
9572 this.test.include(context, includeChildrenRecursively);
9573 this.consequent.include(context, includeChildrenRecursively);
9574 this.alternate.include(context, includeChildrenRecursively);
9575 }
9576 else {
9577 usedBranch.include(context, includeChildrenRecursively);
9578 }
9579 }
9580 includeCallArguments(context, args) {
9581 const usedBranch = this.getUsedBranch();
9582 if (!usedBranch) {
9583 this.consequent.includeCallArguments(context, args);
9584 this.alternate.includeCallArguments(context, args);
9585 }
9586 else {
9587 usedBranch.includeCallArguments(context, args);
9588 }
9589 }
9590 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
9591 const usedBranch = this.getUsedBranch();
9592 if (!this.test.included) {
9593 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
9594 const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
9595 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
9596 : colonPos) + 1);
9597 if (preventASI) {
9598 removeLineBreaks(code, inclusionStart, usedBranch.start);
9599 }
9600 code.remove(this.start, inclusionStart);
9601 if (this.consequent.included) {
9602 code.remove(colonPos, this.end);
9603 }
9604 removeAnnotations(this, code);
9605 usedBranch.render(code, options, {
9606 isCalleeOfRenderedParent,
9607 preventASI: true,
9608 renderedParentType: renderedParentType || this.parent.type,
9609 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
9610 });
9611 }
9612 else {
9613 this.test.render(code, options, { renderedSurroundingElement });
9614 this.consequent.render(code, options);
9615 this.alternate.render(code, options);
9616 }
9617 }
9618 getUsedBranch() {
9619 if (this.isBranchResolutionAnalysed) {
9620 return this.usedBranch;
9621 }
9622 this.isBranchResolutionAnalysed = true;
9623 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
9624 return typeof testValue === 'symbol'
9625 ? null
9626 : (this.usedBranch = testValue ? this.consequent : this.alternate);
9627 }
9628}
9629
9630class ContinueStatement extends NodeBase {
9631 hasEffects(context) {
9632 if (this.label) {
9633 if (!context.ignore.labels.has(this.label.name))
9634 return true;
9635 context.includedLabels.add(this.label.name);
9636 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
9637 }
9638 else {
9639 if (!context.ignore.continues)
9640 return true;
9641 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
9642 }
9643 return false;
9644 }
9645 include(context) {
9646 this.included = true;
9647 if (this.label) {
9648 this.label.include();
9649 context.includedLabels.add(this.label.name);
9650 }
9651 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
9652 }
9653}
9654
9655class DoWhileStatement extends NodeBase {
9656 hasEffects(context) {
9657 if (this.test.hasEffects(context))
9658 return true;
9659 const { brokenFlow, ignore: { breaks, continues } } = context;
9660 context.ignore.breaks = true;
9661 context.ignore.continues = true;
9662 if (this.body.hasEffects(context))
9663 return true;
9664 context.ignore.breaks = breaks;
9665 context.ignore.continues = continues;
9666 context.brokenFlow = brokenFlow;
9667 return false;
9668 }
9669 include(context, includeChildrenRecursively) {
9670 this.included = true;
9671 this.test.include(context, includeChildrenRecursively);
9672 const { brokenFlow } = context;
9673 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9674 context.brokenFlow = brokenFlow;
9675 }
9676}
9677
9678class EmptyStatement extends NodeBase {
9679 hasEffects() {
9680 return false;
9681 }
9682}
9683
9684class ExportAllDeclaration extends NodeBase {
9685 hasEffects() {
9686 return false;
9687 }
9688 initialise() {
9689 this.context.addExport(this);
9690 }
9691 render(code, _options, nodeRenderOptions) {
9692 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
9693 }
9694 applyDeoptimizations() { }
9695}
9696ExportAllDeclaration.prototype.needsBoundaries = true;
9697
9698class FunctionDeclaration extends FunctionNode {
9699 initialise() {
9700 super.initialise();
9701 if (this.id !== null) {
9702 this.id.variable.isId = true;
9703 }
9704 }
9705 parseNode(esTreeNode) {
9706 if (esTreeNode.id !== null) {
9707 this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
9708 }
9709 super.parseNode(esTreeNode);
9710 }
9711}
9712
9713// The header ends at the first non-white-space after "default"
9714function getDeclarationStart(code, start) {
9715 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
9716}
9717function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
9718 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
9719 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
9720 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
9721 if (generatorStarPos === -1) {
9722 return declarationEnd;
9723 }
9724 return declarationEnd + generatorStarPos + 1;
9725}
9726class ExportDefaultDeclaration extends NodeBase {
9727 include(context, includeChildrenRecursively) {
9728 super.include(context, includeChildrenRecursively);
9729 if (includeChildrenRecursively) {
9730 this.context.includeVariableInModule(this.variable);
9731 }
9732 }
9733 initialise() {
9734 const declaration = this.declaration;
9735 this.declarationName =
9736 (declaration.id && declaration.id.name) || this.declaration.name;
9737 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
9738 this.context.addExport(this);
9739 }
9740 render(code, options, nodeRenderOptions) {
9741 const { start, end } = nodeRenderOptions;
9742 const declarationStart = getDeclarationStart(code.original, this.start);
9743 if (this.declaration instanceof FunctionDeclaration) {
9744 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
9745 }
9746 else if (this.declaration instanceof ClassDeclaration) {
9747 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
9748 }
9749 else if (this.variable.getOriginalVariable() !== this.variable) {
9750 // Remove altogether to prevent re-declaring the same variable
9751 treeshakeNode(this, code, start, end);
9752 return;
9753 }
9754 else if (this.variable.included) {
9755 this.renderVariableDeclaration(code, declarationStart, options);
9756 }
9757 else {
9758 code.remove(this.start, declarationStart);
9759 this.declaration.render(code, options, {
9760 renderedSurroundingElement: ExpressionStatement$1
9761 });
9762 if (code.original[this.end - 1] !== ';') {
9763 code.appendLeft(this.end, ';');
9764 }
9765 return;
9766 }
9767 this.declaration.render(code, options);
9768 }
9769 applyDeoptimizations() { }
9770 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
9771 const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
9772 const name = this.variable.getName(getPropertyAccess);
9773 // Remove `export default`
9774 code.remove(this.start, declarationStart);
9775 if (needsId) {
9776 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
9777 }
9778 if (format === 'system' &&
9779 this.declaration instanceof ClassDeclaration &&
9780 exportNamesByVariable.has(this.variable)) {
9781 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
9782 }
9783 }
9784 renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
9785 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
9786 const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
9787 if (systemExportNames) {
9788 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
9789 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
9790 }
9791 else {
9792 code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
9793 if (!hasTrailingSemicolon) {
9794 code.appendLeft(this.end, ';');
9795 }
9796 }
9797 }
9798}
9799ExportDefaultDeclaration.prototype.needsBoundaries = true;
9800
9801class ExportNamedDeclaration extends NodeBase {
9802 bind() {
9803 var _a;
9804 // Do not bind specifiers
9805 (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
9806 }
9807 hasEffects(context) {
9808 var _a;
9809 return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
9810 }
9811 initialise() {
9812 this.context.addExport(this);
9813 }
9814 render(code, options, nodeRenderOptions) {
9815 const { start, end } = nodeRenderOptions;
9816 if (this.declaration === null) {
9817 code.remove(start, end);
9818 }
9819 else {
9820 code.remove(this.start, this.declaration.start);
9821 this.declaration.render(code, options, { end, start });
9822 }
9823 }
9824 applyDeoptimizations() { }
9825}
9826ExportNamedDeclaration.prototype.needsBoundaries = true;
9827
9828class ExportSpecifier extends NodeBase {
9829 applyDeoptimizations() { }
9830}
9831
9832class ForInStatement extends NodeBase {
9833 createScope(parentScope) {
9834 this.scope = new BlockScope(parentScope);
9835 }
9836 hasEffects(context) {
9837 const { deoptimized, left, right } = this;
9838 if (!deoptimized)
9839 this.applyDeoptimizations();
9840 if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
9841 return true;
9842 const { brokenFlow, ignore: { breaks, continues } } = context;
9843 context.ignore.breaks = true;
9844 context.ignore.continues = true;
9845 if (this.body.hasEffects(context))
9846 return true;
9847 context.ignore.breaks = breaks;
9848 context.ignore.continues = continues;
9849 context.brokenFlow = brokenFlow;
9850 return false;
9851 }
9852 include(context, includeChildrenRecursively) {
9853 const { body, deoptimized, left, right } = this;
9854 if (!deoptimized)
9855 this.applyDeoptimizations();
9856 this.included = true;
9857 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9858 right.include(context, includeChildrenRecursively);
9859 const { brokenFlow } = context;
9860 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9861 context.brokenFlow = brokenFlow;
9862 }
9863 initialise() {
9864 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9865 }
9866 render(code, options) {
9867 this.left.render(code, options, NO_SEMICOLON);
9868 this.right.render(code, options, NO_SEMICOLON);
9869 // handle no space between "in" and the right side
9870 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
9871 code.prependLeft(this.right.start, ' ');
9872 }
9873 this.body.render(code, options);
9874 }
9875 applyDeoptimizations() {
9876 this.deoptimized = true;
9877 this.left.deoptimizePath(EMPTY_PATH);
9878 this.context.requestTreeshakingPass();
9879 }
9880}
9881
9882class ForOfStatement extends NodeBase {
9883 createScope(parentScope) {
9884 this.scope = new BlockScope(parentScope);
9885 }
9886 hasEffects() {
9887 if (!this.deoptimized)
9888 this.applyDeoptimizations();
9889 // Placeholder until proper Symbol.Iterator support
9890 return true;
9891 }
9892 include(context, includeChildrenRecursively) {
9893 const { body, deoptimized, left, right } = this;
9894 if (!deoptimized)
9895 this.applyDeoptimizations();
9896 this.included = true;
9897 left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
9898 right.include(context, includeChildrenRecursively);
9899 const { brokenFlow } = context;
9900 body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9901 context.brokenFlow = brokenFlow;
9902 }
9903 initialise() {
9904 this.left.setAssignedValue(UNKNOWN_EXPRESSION);
9905 }
9906 render(code, options) {
9907 this.left.render(code, options, NO_SEMICOLON);
9908 this.right.render(code, options, NO_SEMICOLON);
9909 // handle no space between "of" and the right side
9910 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
9911 code.prependLeft(this.right.start, ' ');
9912 }
9913 this.body.render(code, options);
9914 }
9915 applyDeoptimizations() {
9916 this.deoptimized = true;
9917 this.left.deoptimizePath(EMPTY_PATH);
9918 this.context.requestTreeshakingPass();
9919 }
9920}
9921
9922class ForStatement extends NodeBase {
9923 createScope(parentScope) {
9924 this.scope = new BlockScope(parentScope);
9925 }
9926 hasEffects(context) {
9927 var _a, _b, _c;
9928 if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
9929 ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
9930 ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
9931 return true;
9932 const { brokenFlow, ignore: { breaks, continues } } = context;
9933 context.ignore.breaks = true;
9934 context.ignore.continues = true;
9935 if (this.body.hasEffects(context))
9936 return true;
9937 context.ignore.breaks = breaks;
9938 context.ignore.continues = continues;
9939 context.brokenFlow = brokenFlow;
9940 return false;
9941 }
9942 include(context, includeChildrenRecursively) {
9943 var _a, _b, _c;
9944 this.included = true;
9945 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
9946 (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
9947 const { brokenFlow } = context;
9948 (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
9949 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
9950 context.brokenFlow = brokenFlow;
9951 }
9952 render(code, options) {
9953 var _a, _b, _c;
9954 (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
9955 (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
9956 (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
9957 this.body.render(code, options);
9958 }
9959}
9960
9961class FunctionExpression extends FunctionNode {
9962 render(code, options, { renderedSurroundingElement } = BLANK) {
9963 super.render(code, options);
9964 if (renderedSurroundingElement === ExpressionStatement$1) {
9965 code.appendRight(this.start, '(');
9966 code.prependLeft(this.end, ')');
9967 }
9968 }
9969}
9970
9971class TrackingScope extends BlockScope {
9972 constructor() {
9973 super(...arguments);
9974 this.hoistedDeclarations = [];
9975 }
9976 addDeclaration(identifier, context, init, isHoisted) {
9977 this.hoistedDeclarations.push(identifier);
9978 return super.addDeclaration(identifier, context, init, isHoisted);
9979 }
9980}
9981
9982const unset = Symbol('unset');
9983class IfStatement extends NodeBase {
9984 constructor() {
9985 super(...arguments);
9986 this.testValue = unset;
9987 }
9988 deoptimizeCache() {
9989 this.testValue = UnknownValue;
9990 }
9991 hasEffects(context) {
9992 var _a;
9993 if (this.test.hasEffects(context)) {
9994 return true;
9995 }
9996 const testValue = this.getTestValue();
9997 if (typeof testValue === 'symbol') {
9998 const { brokenFlow } = context;
9999 if (this.consequent.hasEffects(context))
10000 return true;
10001 const consequentBrokenFlow = context.brokenFlow;
10002 context.brokenFlow = brokenFlow;
10003 if (this.alternate === null)
10004 return false;
10005 if (this.alternate.hasEffects(context))
10006 return true;
10007 context.brokenFlow =
10008 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
10009 return false;
10010 }
10011 return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
10012 }
10013 include(context, includeChildrenRecursively) {
10014 this.included = true;
10015 if (includeChildrenRecursively) {
10016 this.includeRecursively(includeChildrenRecursively, context);
10017 }
10018 else {
10019 const testValue = this.getTestValue();
10020 if (typeof testValue === 'symbol') {
10021 this.includeUnknownTest(context);
10022 }
10023 else {
10024 this.includeKnownTest(context, testValue);
10025 }
10026 }
10027 }
10028 parseNode(esTreeNode) {
10029 this.consequentScope = new TrackingScope(this.scope);
10030 this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
10031 if (esTreeNode.alternate) {
10032 this.alternateScope = new TrackingScope(this.scope);
10033 this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
10034 }
10035 super.parseNode(esTreeNode);
10036 }
10037 render(code, options) {
10038 const { snippets: { getPropertyAccess } } = options;
10039 // Note that unknown test values are always included
10040 const testValue = this.getTestValue();
10041 const hoistedDeclarations = [];
10042 const includesIfElse = this.test.included;
10043 const noTreeshake = !this.context.options.treeshake;
10044 if (includesIfElse) {
10045 this.test.render(code, options);
10046 }
10047 else {
10048 code.remove(this.start, this.consequent.start);
10049 }
10050 if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
10051 this.consequent.render(code, options);
10052 }
10053 else {
10054 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
10055 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
10056 }
10057 if (this.alternate) {
10058 if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
10059 if (includesIfElse) {
10060 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
10061 code.prependLeft(this.alternate.start, ' ');
10062 }
10063 }
10064 else {
10065 code.remove(this.consequent.end, this.alternate.start);
10066 }
10067 this.alternate.render(code, options);
10068 }
10069 else {
10070 if (includesIfElse && this.shouldKeepAlternateBranch()) {
10071 code.overwrite(this.alternate.start, this.end, ';');
10072 }
10073 else {
10074 code.remove(this.consequent.end, this.end);
10075 }
10076 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
10077 }
10078 }
10079 this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
10080 }
10081 applyDeoptimizations() { }
10082 getTestValue() {
10083 if (this.testValue === unset) {
10084 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
10085 }
10086 return this.testValue;
10087 }
10088 includeKnownTest(context, testValue) {
10089 var _a;
10090 if (this.test.shouldBeIncluded(context)) {
10091 this.test.include(context, false);
10092 }
10093 if (testValue && this.consequent.shouldBeIncluded(context)) {
10094 this.consequent.include(context, false, { asSingleStatement: true });
10095 }
10096 if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
10097 this.alternate.include(context, false, { asSingleStatement: true });
10098 }
10099 }
10100 includeRecursively(includeChildrenRecursively, context) {
10101 var _a;
10102 this.test.include(context, includeChildrenRecursively);
10103 this.consequent.include(context, includeChildrenRecursively);
10104 (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
10105 }
10106 includeUnknownTest(context) {
10107 var _a;
10108 this.test.include(context, false);
10109 const { brokenFlow } = context;
10110 let consequentBrokenFlow = BROKEN_FLOW_NONE;
10111 if (this.consequent.shouldBeIncluded(context)) {
10112 this.consequent.include(context, false, { asSingleStatement: true });
10113 consequentBrokenFlow = context.brokenFlow;
10114 context.brokenFlow = brokenFlow;
10115 }
10116 if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
10117 this.alternate.include(context, false, { asSingleStatement: true });
10118 context.brokenFlow =
10119 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
10120 }
10121 }
10122 renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
10123 const hoistedVars = [
10124 ...new Set(hoistedDeclarations.map(identifier => {
10125 const variable = identifier.variable;
10126 return variable.included ? variable.getName(getPropertyAccess) : '';
10127 }))
10128 ]
10129 .filter(Boolean)
10130 .join(', ');
10131 if (hoistedVars) {
10132 const parentType = this.parent.type;
10133 const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
10134 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
10135 if (needsBraces) {
10136 code.appendLeft(this.end, ` }`);
10137 }
10138 }
10139 }
10140 shouldKeepAlternateBranch() {
10141 let currentParent = this.parent;
10142 do {
10143 if (currentParent instanceof IfStatement && currentParent.alternate) {
10144 return true;
10145 }
10146 if (currentParent instanceof BlockStatement) {
10147 return false;
10148 }
10149 currentParent = currentParent.parent;
10150 } while (currentParent);
10151 return false;
10152 }
10153}
10154
10155class ImportDeclaration extends NodeBase {
10156 // Do not bind specifiers
10157 bind() { }
10158 hasEffects() {
10159 return false;
10160 }
10161 initialise() {
10162 this.context.addImport(this);
10163 }
10164 render(code, _options, nodeRenderOptions) {
10165 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
10166 }
10167 applyDeoptimizations() { }
10168}
10169ImportDeclaration.prototype.needsBoundaries = true;
10170
10171class ImportDefaultSpecifier extends NodeBase {
10172 applyDeoptimizations() { }
10173}
10174
10175const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
10176const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
10177const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
10178const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
10179const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
10180const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
10181const defaultInteropHelpersByInteropType = {
10182 auto: INTEROP_DEFAULT_VARIABLE,
10183 default: null,
10184 defaultOnly: null,
10185 esModule: null,
10186 false: null,
10187 true: INTEROP_DEFAULT_LEGACY_VARIABLE
10188};
10189const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
10190 (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
10191const namespaceInteropHelpersByInteropType = {
10192 auto: INTEROP_NAMESPACE_VARIABLE,
10193 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
10194 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
10195 esModule: null,
10196 false: null,
10197 true: INTEROP_NAMESPACE_VARIABLE
10198};
10199const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
10200 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
10201const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
10202 const usedHelpers = new Set(additionalHelpers);
10203 for (const variable of HELPER_NAMES) {
10204 if (accessedGlobals.has(variable)) {
10205 usedHelpers.add(variable);
10206 }
10207 }
10208 return HELPER_NAMES.map(variable => usedHelpers.has(variable)
10209 ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
10210 : '').join('');
10211};
10212const HELPER_GENERATORS = {
10213 [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
10214 const { _, getDirectReturnFunction, n } = snippets;
10215 const [left, right] = getDirectReturnFunction(['e'], {
10216 functionReturn: true,
10217 lineBreakIndent: null,
10218 name: INTEROP_DEFAULT_LEGACY_VARIABLE
10219 });
10220 return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
10221 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10222 },
10223 [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
10224 const { _, getDirectReturnFunction, n } = snippets;
10225 const [left, right] = getDirectReturnFunction(['e'], {
10226 functionReturn: true,
10227 lineBreakIndent: null,
10228 name: INTEROP_DEFAULT_VARIABLE
10229 });
10230 return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
10231 `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
10232 },
10233 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
10234 const { getDirectReturnFunction, getObject, n } = snippets;
10235 const [left, right] = getDirectReturnFunction(['e'], {
10236 functionReturn: true,
10237 lineBreakIndent: null,
10238 name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10239 });
10240 return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
10241 ['__proto__', 'null'],
10242 ['default', 'e']
10243 ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
10244 },
10245 [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10246 const { _, n } = snippets;
10247 return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
10248 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10249 `}${n}${n}`);
10250 },
10251 [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
10252 const { _, getDirectReturnFunction, n } = snippets;
10253 if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
10254 const [left, right] = getDirectReturnFunction(['e'], {
10255 functionReturn: true,
10256 lineBreakIndent: null,
10257 name: INTEROP_NAMESPACE_VARIABLE
10258 });
10259 return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
10260 }
10261 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
10262 `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
10263 createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
10264 `}${n}${n}`);
10265 },
10266 [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
10267 const { _, cnst, n } = snippets;
10268 const useForEach = cnst === 'var' && liveBindings;
10269 return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
10270 `${t}${loopOverNamespaces(`{${n}` +
10271 `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
10272 (liveBindings
10273 ? useForEach
10274 ? copyOwnPropertyLiveBinding
10275 : copyPropertyLiveBinding
10276 : copyPropertyStatic)(t, t + t + t + t, snippets) +
10277 `${t}${t}${t}}${n}` +
10278 `${t}${t}}`, useForEach, t, snippets)}${n}` +
10279 `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
10280 `}${n}${n}`);
10281 }
10282};
10283const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
10284const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
10285const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
10286 const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
10287 const copyProperty = `{${n}` +
10288 (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
10289 `${i}${t}}`;
10290 return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
10291 ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
10292 : ''});${n}` +
10293 `${i}if${_}(e)${_}{${n}` +
10294 `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
10295 `${i}}${n}` +
10296 `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
10297 `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
10298};
10299const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
10300 ? `for${_}(${cnst} k in e)${_}${body}`
10301 : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
10302 isAsync: false,
10303 name: null
10304 })}${body})${s}`;
10305const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
10306 if (useForEach) {
10307 const [left, right] = getDirectReturnFunction(['e'], {
10308 functionReturn: false,
10309 lineBreakIndent: { base: t, t },
10310 name: null
10311 });
10312 return (`m.forEach(${left}` +
10313 `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
10314 isAsync: false,
10315 name: null
10316 })}${body})${right});`);
10317 }
10318 return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
10319 `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
10320 `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
10321};
10322const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
10323 const { _, n } = snippets;
10324 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
10325 copyOwnPropertyLiveBinding(t, i + t, snippets) +
10326 `${i}}${n}`);
10327};
10328const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10329 const [left, right] = getDirectReturnFunction([], {
10330 functionReturn: true,
10331 lineBreakIndent: null,
10332 name: null
10333 });
10334 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10335 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10336 `${i}${t}enumerable:${_}true,${n}` +
10337 `${i}${t}get:${_}${left}e[k]${right}${n}` +
10338 `${i}});${n}`);
10339};
10340const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10341 const [left, right] = getDirectReturnFunction([], {
10342 functionReturn: true,
10343 lineBreakIndent: null,
10344 name: null
10345 });
10346 return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10347 `${i}if${_}(d)${_}{${n}` +
10348 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10349 `${i}${t}${t}enumerable:${_}true,${n}` +
10350 `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
10351 `${i}${t}});${n}` +
10352 `${i}}${n}`);
10353};
10354const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
10355const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
10356const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
10357 ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
10358 : fragment;
10359const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
10360function getToStringTagValue(getObject) {
10361 return getObject([['value', "'Module'"]], {
10362 lineBreakIndent: null
10363 });
10364}
10365
10366class ImportExpression extends NodeBase {
10367 constructor() {
10368 super(...arguments);
10369 this.inlineNamespace = null;
10370 this.mechanism = null;
10371 this.resolution = null;
10372 }
10373 hasEffects() {
10374 return true;
10375 }
10376 include(context, includeChildrenRecursively) {
10377 if (!this.included) {
10378 this.included = true;
10379 this.context.includeDynamicImport(this);
10380 this.scope.addAccessedDynamicImport(this);
10381 }
10382 this.source.include(context, includeChildrenRecursively);
10383 }
10384 initialise() {
10385 this.context.addDynamicImport(this);
10386 }
10387 render(code, options) {
10388 if (this.inlineNamespace) {
10389 const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10390 const [left, right] = getDirectReturnFunction([], {
10391 functionReturn: true,
10392 lineBreakIndent: null,
10393 name: null
10394 });
10395 code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
10396 return;
10397 }
10398 if (this.mechanism) {
10399 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
10400 code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
10401 }
10402 this.source.render(code, options);
10403 }
10404 renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
10405 code.overwrite(this.source.start, this.source.end, resolution);
10406 if (namespaceExportName) {
10407 const [left, right] = getDirectReturnFunction(['n'], {
10408 functionReturn: true,
10409 lineBreakIndent: null,
10410 name: null
10411 });
10412 code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
10413 }
10414 }
10415 setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
10416 const { format } = options;
10417 this.inlineNamespace = null;
10418 this.resolution = resolution;
10419 const accessedGlobals = [...(accessedImportGlobals[format] || [])];
10420 let helper;
10421 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
10422 if (helper) {
10423 accessedGlobals.push(helper);
10424 }
10425 if (accessedGlobals.length > 0) {
10426 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10427 }
10428 }
10429 setInternalResolution(inlineNamespace) {
10430 this.inlineNamespace = inlineNamespace;
10431 }
10432 applyDeoptimizations() { }
10433 getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
10434 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
10435 {
10436 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
10437 format,
10438 moduleId: this.context.module.id,
10439 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
10440 }
10441 ]);
10442 if (mechanism) {
10443 return { helper: null, mechanism };
10444 }
10445 const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
10446 switch (format) {
10447 case 'cjs': {
10448 const helper = getInteropHelper(resolution, exportMode, interop);
10449 let left = `require(`;
10450 let right = `)`;
10451 if (helper) {
10452 left = `/*#__PURE__*/${helper}(${left}`;
10453 right += ')';
10454 }
10455 const [functionLeft, functionRight] = getDirectReturnFunction([], {
10456 functionReturn: true,
10457 lineBreakIndent: null,
10458 name: null
10459 });
10460 left = `Promise.resolve().then(${functionLeft}${left}`;
10461 right += `${functionRight})`;
10462 if (!arrowFunctions && hasDynamicTarget) {
10463 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10464 needsArrowReturnParens: false,
10465 needsWrappedFunction: true
10466 });
10467 right = ')';
10468 }
10469 return {
10470 helper,
10471 mechanism: { left, right }
10472 };
10473 }
10474 case 'amd': {
10475 const resolve = compact ? 'c' : 'resolve';
10476 const reject = compact ? 'e' : 'reject';
10477 const helper = getInteropHelper(resolution, exportMode, interop);
10478 const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
10479 functionReturn: false,
10480 lineBreakIndent: null,
10481 name: null
10482 });
10483 const resolveNamespace = helper
10484 ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
10485 : resolve;
10486 const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
10487 functionReturn: false,
10488 lineBreakIndent: null,
10489 name: null
10490 });
10491 let left = `new Promise(${handlerLeft}require([`;
10492 let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
10493 if (!arrowFunctions && hasDynamicTarget) {
10494 left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
10495 needsArrowReturnParens: false,
10496 needsWrappedFunction: true
10497 });
10498 right = ')';
10499 }
10500 return {
10501 helper,
10502 mechanism: { left, right }
10503 };
10504 }
10505 case 'system':
10506 return {
10507 helper: null,
10508 mechanism: {
10509 left: 'module.import(',
10510 right: ')'
10511 }
10512 };
10513 case 'es':
10514 if (dynamicImportFunction) {
10515 return {
10516 helper: null,
10517 mechanism: {
10518 left: `${dynamicImportFunction}(`,
10519 right: ')'
10520 }
10521 };
10522 }
10523 }
10524 return { helper: null, mechanism: null };
10525 }
10526}
10527function getInteropHelper(resolution, exportMode, interop) {
10528 return exportMode === 'external'
10529 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
10530 : exportMode === 'default'
10531 ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
10532 : null;
10533}
10534const accessedImportGlobals = {
10535 amd: ['require'],
10536 cjs: ['require'],
10537 system: ['module']
10538};
10539
10540class ImportNamespaceSpecifier extends NodeBase {
10541 applyDeoptimizations() { }
10542}
10543
10544class ImportSpecifier extends NodeBase {
10545 applyDeoptimizations() { }
10546}
10547
10548class LabeledStatement extends NodeBase {
10549 hasEffects(context) {
10550 const brokenFlow = context.brokenFlow;
10551 context.ignore.labels.add(this.label.name);
10552 if (this.body.hasEffects(context))
10553 return true;
10554 context.ignore.labels.delete(this.label.name);
10555 if (context.includedLabels.has(this.label.name)) {
10556 context.includedLabels.delete(this.label.name);
10557 context.brokenFlow = brokenFlow;
10558 }
10559 return false;
10560 }
10561 include(context, includeChildrenRecursively) {
10562 this.included = true;
10563 const brokenFlow = context.brokenFlow;
10564 this.body.include(context, includeChildrenRecursively);
10565 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
10566 this.label.include();
10567 context.includedLabels.delete(this.label.name);
10568 context.brokenFlow = brokenFlow;
10569 }
10570 }
10571 render(code, options) {
10572 if (this.label.included) {
10573 this.label.render(code, options);
10574 }
10575 else {
10576 code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
10577 }
10578 this.body.render(code, options);
10579 }
10580}
10581
10582class LogicalExpression extends NodeBase {
10583 constructor() {
10584 super(...arguments);
10585 // We collect deoptimization information if usedBranch !== null
10586 this.expressionsToBeDeoptimized = [];
10587 this.isBranchResolutionAnalysed = false;
10588 this.usedBranch = null;
10589 }
10590 deoptimizeCache() {
10591 if (this.usedBranch) {
10592 const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
10593 this.usedBranch = null;
10594 unusedBranch.deoptimizePath(UNKNOWN_PATH);
10595 for (const expression of this.expressionsToBeDeoptimized) {
10596 expression.deoptimizeCache();
10597 }
10598 // Request another pass because we need to ensure "include" runs again if
10599 // it is rendered
10600 this.context.requestTreeshakingPass();
10601 }
10602 }
10603 deoptimizePath(path) {
10604 const usedBranch = this.getUsedBranch();
10605 if (!usedBranch) {
10606 this.left.deoptimizePath(path);
10607 this.right.deoptimizePath(path);
10608 }
10609 else {
10610 usedBranch.deoptimizePath(path);
10611 }
10612 }
10613 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10614 this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10615 this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10616 }
10617 getLiteralValueAtPath(path, recursionTracker, origin) {
10618 const usedBranch = this.getUsedBranch();
10619 if (!usedBranch)
10620 return UnknownValue;
10621 this.expressionsToBeDeoptimized.push(origin);
10622 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
10623 }
10624 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10625 const usedBranch = this.getUsedBranch();
10626 if (!usedBranch)
10627 return new MultiExpression([
10628 this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
10629 this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
10630 ]);
10631 this.expressionsToBeDeoptimized.push(origin);
10632 return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10633 }
10634 hasEffects(context) {
10635 if (this.left.hasEffects(context)) {
10636 return true;
10637 }
10638 if (this.getUsedBranch() !== this.left) {
10639 return this.right.hasEffects(context);
10640 }
10641 return false;
10642 }
10643 hasEffectsOnInteractionAtPath(path, interaction, context) {
10644 const usedBranch = this.getUsedBranch();
10645 if (!usedBranch) {
10646 return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
10647 this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
10648 }
10649 return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
10650 }
10651 include(context, includeChildrenRecursively) {
10652 this.included = true;
10653 const usedBranch = this.getUsedBranch();
10654 if (includeChildrenRecursively ||
10655 (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
10656 !usedBranch) {
10657 this.left.include(context, includeChildrenRecursively);
10658 this.right.include(context, includeChildrenRecursively);
10659 }
10660 else {
10661 usedBranch.include(context, includeChildrenRecursively);
10662 }
10663 }
10664 render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
10665 if (!this.left.included || !this.right.included) {
10666 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
10667 if (this.right.included) {
10668 const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
10669 code.remove(this.start, removePos);
10670 if (preventASI) {
10671 removeLineBreaks(code, removePos, this.right.start);
10672 }
10673 }
10674 else {
10675 code.remove(operatorPos, this.end);
10676 }
10677 removeAnnotations(this, code);
10678 this.getUsedBranch().render(code, options, {
10679 isCalleeOfRenderedParent,
10680 preventASI,
10681 renderedParentType: renderedParentType || this.parent.type,
10682 renderedSurroundingElement: renderedSurroundingElement || this.parent.type
10683 });
10684 }
10685 else {
10686 this.left.render(code, options, {
10687 preventASI,
10688 renderedSurroundingElement
10689 });
10690 this.right.render(code, options);
10691 }
10692 }
10693 getUsedBranch() {
10694 if (!this.isBranchResolutionAnalysed) {
10695 this.isBranchResolutionAnalysed = true;
10696 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10697 if (typeof leftValue === 'symbol') {
10698 return null;
10699 }
10700 else {
10701 this.usedBranch =
10702 (this.operator === '||' && leftValue) ||
10703 (this.operator === '&&' && !leftValue) ||
10704 (this.operator === '??' && leftValue != null)
10705 ? this.left
10706 : this.right;
10707 }
10708 }
10709 return this.usedBranch;
10710 }
10711}
10712
10713const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
10714const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
10715const FILE_PREFIX = 'ROLLUP_FILE_URL_';
10716class MetaProperty extends NodeBase {
10717 addAccessedGlobals(format, accessedGlobalsByScope) {
10718 const metaProperty = this.metaProperty;
10719 const accessedGlobals = (metaProperty &&
10720 (metaProperty.startsWith(FILE_PREFIX) ||
10721 metaProperty.startsWith(ASSET_PREFIX) ||
10722 metaProperty.startsWith(CHUNK_PREFIX))
10723 ? accessedFileUrlGlobals
10724 : accessedMetaUrlGlobals)[format];
10725 if (accessedGlobals.length > 0) {
10726 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10727 }
10728 }
10729 getReferencedFileName(outputPluginDriver) {
10730 const metaProperty = this.metaProperty;
10731 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
10732 return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10733 }
10734 return null;
10735 }
10736 hasEffects() {
10737 return false;
10738 }
10739 hasEffectsOnInteractionAtPath(path, { type }) {
10740 return path.length > 1 || type !== INTERACTION_ACCESSED;
10741 }
10742 include() {
10743 if (!this.included) {
10744 this.included = true;
10745 if (this.meta.name === 'import') {
10746 this.context.addImportMeta(this);
10747 const parent = this.parent;
10748 this.metaProperty =
10749 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
10750 ? parent.propertyKey
10751 : null;
10752 }
10753 }
10754 }
10755 renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
10756 var _a;
10757 const parent = this.parent;
10758 const metaProperty = this.metaProperty;
10759 if (metaProperty &&
10760 (metaProperty.startsWith(FILE_PREFIX) ||
10761 metaProperty.startsWith(ASSET_PREFIX) ||
10762 metaProperty.startsWith(CHUNK_PREFIX))) {
10763 let referenceId = null;
10764 let assetReferenceId = null;
10765 let chunkReferenceId = null;
10766 let fileName;
10767 if (metaProperty.startsWith(FILE_PREFIX)) {
10768 referenceId = metaProperty.substring(FILE_PREFIX.length);
10769 fileName = outputPluginDriver.getFileName(referenceId);
10770 }
10771 else if (metaProperty.startsWith(ASSET_PREFIX)) {
10772 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10773 assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
10774 fileName = outputPluginDriver.getFileName(assetReferenceId);
10775 }
10776 else {
10777 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10778 chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
10779 fileName = outputPluginDriver.getFileName(chunkReferenceId);
10780 }
10781 const relativePath = normalize(require$$0.relative(require$$0.dirname(chunkId), fileName));
10782 let replacement;
10783 if (assetReferenceId !== null) {
10784 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
10785 {
10786 assetFileName: fileName,
10787 chunkId,
10788 format,
10789 moduleId: this.context.module.id,
10790 relativeAssetPath: relativePath
10791 }
10792 ]);
10793 }
10794 if (!replacement) {
10795 replacement =
10796 outputPluginDriver.hookFirstSync('resolveFileUrl', [
10797 {
10798 assetReferenceId,
10799 chunkId,
10800 chunkReferenceId,
10801 fileName,
10802 format,
10803 moduleId: this.context.module.id,
10804 referenceId: referenceId || assetReferenceId || chunkReferenceId,
10805 relativePath
10806 }
10807 ]) || relativeUrlMechanisms[format](relativePath);
10808 }
10809 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10810 return;
10811 }
10812 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
10813 metaProperty,
10814 {
10815 chunkId,
10816 format,
10817 moduleId: this.context.module.id
10818 }
10819 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
10820 if (typeof replacement === 'string') {
10821 if (parent instanceof MemberExpression) {
10822 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10823 }
10824 else {
10825 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
10826 }
10827 }
10828 }
10829}
10830const accessedMetaUrlGlobals = {
10831 amd: ['document', 'module', 'URL'],
10832 cjs: ['document', 'require', 'URL'],
10833 es: [],
10834 iife: ['document', 'URL'],
10835 system: ['module'],
10836 umd: ['document', 'require', 'URL']
10837};
10838const accessedFileUrlGlobals = {
10839 amd: ['document', 'require', 'URL'],
10840 cjs: ['document', 'require', 'URL'],
10841 es: [],
10842 iife: ['document', 'URL'],
10843 system: ['module', 'URL'],
10844 umd: ['document', 'require', 'URL']
10845};
10846const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
10847const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
10848const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
10849 const urlMechanism = getUrl(chunkId);
10850 return prop === null
10851 ? `({ url: ${urlMechanism} })`
10852 : prop === 'url'
10853 ? urlMechanism
10854 : 'undefined';
10855};
10856const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
10857const relativeUrlMechanisms = {
10858 amd: relativePath => {
10859 if (relativePath[0] !== '.')
10860 relativePath = './' + relativePath;
10861 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
10862 },
10863 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
10864 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
10865 iife: relativePath => getRelativeUrlFromDocument(relativePath),
10866 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
10867 umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
10868};
10869const importMetaMechanisms = {
10870 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
10871 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
10872 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
10873 system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
10874 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
10875};
10876
10877class NewExpression extends NodeBase {
10878 hasEffects(context) {
10879 try {
10880 for (const argument of this.arguments) {
10881 if (argument.hasEffects(context))
10882 return true;
10883 }
10884 if (this.context.options.treeshake.annotations &&
10885 this.annotations) {
10886 return false;
10887 }
10888 return (this.callee.hasEffects(context) ||
10889 this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
10890 }
10891 finally {
10892 if (!this.deoptimized)
10893 this.applyDeoptimizations();
10894 }
10895 }
10896 hasEffectsOnInteractionAtPath(path, { type }) {
10897 return path.length > 0 || type !== INTERACTION_ACCESSED;
10898 }
10899 include(context, includeChildrenRecursively) {
10900 if (!this.deoptimized)
10901 this.applyDeoptimizations();
10902 if (includeChildrenRecursively) {
10903 super.include(context, includeChildrenRecursively);
10904 }
10905 else {
10906 this.included = true;
10907 this.callee.include(context, false);
10908 }
10909 this.callee.includeCallArguments(context, this.arguments);
10910 }
10911 initialise() {
10912 this.interaction = {
10913 args: this.arguments,
10914 thisArg: null,
10915 type: INTERACTION_CALLED,
10916 withNew: true
10917 };
10918 }
10919 render(code, options) {
10920 this.callee.render(code, options);
10921 renderCallArguments(code, options, this);
10922 }
10923 applyDeoptimizations() {
10924 this.deoptimized = true;
10925 for (const argument of this.arguments) {
10926 // This will make sure all properties of parameters behave as "unknown"
10927 argument.deoptimizePath(UNKNOWN_PATH);
10928 }
10929 this.context.requestTreeshakingPass();
10930 }
10931}
10932
10933class ObjectExpression extends NodeBase {
10934 constructor() {
10935 super(...arguments);
10936 this.objectEntity = null;
10937 }
10938 deoptimizeCache() {
10939 this.getObjectEntity().deoptimizeAllProperties();
10940 }
10941 deoptimizePath(path) {
10942 this.getObjectEntity().deoptimizePath(path);
10943 }
10944 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
10945 this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
10946 }
10947 getLiteralValueAtPath(path, recursionTracker, origin) {
10948 return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
10949 }
10950 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10951 return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10952 }
10953 hasEffectsOnInteractionAtPath(path, interaction, context) {
10954 return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
10955 }
10956 render(code, options, { renderedSurroundingElement } = BLANK) {
10957 super.render(code, options);
10958 if (renderedSurroundingElement === ExpressionStatement$1 ||
10959 renderedSurroundingElement === ArrowFunctionExpression$1) {
10960 code.appendRight(this.start, '(');
10961 code.prependLeft(this.end, ')');
10962 }
10963 }
10964 applyDeoptimizations() { }
10965 getObjectEntity() {
10966 if (this.objectEntity !== null) {
10967 return this.objectEntity;
10968 }
10969 let prototype = OBJECT_PROTOTYPE;
10970 const properties = [];
10971 for (const property of this.properties) {
10972 if (property instanceof SpreadElement) {
10973 properties.push({ key: UnknownKey, kind: 'init', property });
10974 continue;
10975 }
10976 let key;
10977 if (property.computed) {
10978 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
10979 if (typeof keyValue === 'symbol') {
10980 properties.push({ key: UnknownKey, kind: property.kind, property });
10981 continue;
10982 }
10983 else {
10984 key = String(keyValue);
10985 }
10986 }
10987 else {
10988 key =
10989 property.key instanceof Identifier
10990 ? property.key.name
10991 : String(property.key.value);
10992 if (key === '__proto__' && property.kind === 'init') {
10993 prototype =
10994 property.value instanceof Literal && property.value.value === null
10995 ? null
10996 : property.value;
10997 continue;
10998 }
10999 }
11000 properties.push({ key, kind: property.kind, property });
11001 }
11002 return (this.objectEntity = new ObjectEntity(properties, prototype));
11003 }
11004}
11005
11006class PrivateIdentifier extends NodeBase {
11007}
11008
11009class Program extends NodeBase {
11010 constructor() {
11011 super(...arguments);
11012 this.hasCachedEffect = false;
11013 }
11014 hasEffects(context) {
11015 // We are caching here to later more efficiently identify side-effect-free modules
11016 if (this.hasCachedEffect)
11017 return true;
11018 for (const node of this.body) {
11019 if (node.hasEffects(context)) {
11020 return (this.hasCachedEffect = true);
11021 }
11022 }
11023 return false;
11024 }
11025 include(context, includeChildrenRecursively) {
11026 this.included = true;
11027 for (const node of this.body) {
11028 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
11029 node.include(context, includeChildrenRecursively);
11030 }
11031 }
11032 }
11033 render(code, options) {
11034 if (this.body.length) {
11035 renderStatementList(this.body, code, this.start, this.end, options);
11036 }
11037 else {
11038 super.render(code, options);
11039 }
11040 }
11041 applyDeoptimizations() { }
11042}
11043
11044class Property extends MethodBase {
11045 constructor() {
11046 super(...arguments);
11047 this.declarationInit = null;
11048 }
11049 declare(kind, init) {
11050 this.declarationInit = init;
11051 return this.value.declare(kind, UNKNOWN_EXPRESSION);
11052 }
11053 hasEffects(context) {
11054 if (!this.deoptimized)
11055 this.applyDeoptimizations();
11056 const propertyReadSideEffects = this.context.options.treeshake
11057 .propertyReadSideEffects;
11058 return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
11059 this.key.hasEffects(context) ||
11060 this.value.hasEffects(context));
11061 }
11062 markDeclarationReached() {
11063 this.value.markDeclarationReached();
11064 }
11065 render(code, options) {
11066 if (!this.shorthand) {
11067 this.key.render(code, options);
11068 }
11069 this.value.render(code, options, { isShorthandProperty: this.shorthand });
11070 }
11071 applyDeoptimizations() {
11072 this.deoptimized = true;
11073 if (this.declarationInit !== null) {
11074 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
11075 this.context.requestTreeshakingPass();
11076 }
11077 }
11078}
11079
11080class PropertyDefinition extends NodeBase {
11081 deoptimizePath(path) {
11082 var _a;
11083 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
11084 }
11085 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11086 var _a;
11087 (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11088 }
11089 getLiteralValueAtPath(path, recursionTracker, origin) {
11090 return this.value
11091 ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
11092 : UnknownValue;
11093 }
11094 getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
11095 return this.value
11096 ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
11097 : UNKNOWN_EXPRESSION;
11098 }
11099 hasEffects(context) {
11100 var _a;
11101 return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11102 }
11103 hasEffectsOnInteractionAtPath(path, interaction, context) {
11104 return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
11105 }
11106 applyDeoptimizations() { }
11107}
11108
11109class ReturnStatement extends NodeBase {
11110 hasEffects(context) {
11111 var _a;
11112 if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
11113 return true;
11114 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11115 return false;
11116 }
11117 include(context, includeChildrenRecursively) {
11118 var _a;
11119 this.included = true;
11120 (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11121 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11122 }
11123 initialise() {
11124 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
11125 }
11126 render(code, options) {
11127 if (this.argument) {
11128 this.argument.render(code, options, { preventASI: true });
11129 if (this.argument.start === this.start + 6 /* 'return'.length */) {
11130 code.prependLeft(this.start + 6, ' ');
11131 }
11132 }
11133 }
11134}
11135
11136class SequenceExpression extends NodeBase {
11137 deoptimizePath(path) {
11138 this.expressions[this.expressions.length - 1].deoptimizePath(path);
11139 }
11140 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11141 this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11142 }
11143 getLiteralValueAtPath(path, recursionTracker, origin) {
11144 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
11145 }
11146 hasEffects(context) {
11147 for (const expression of this.expressions) {
11148 if (expression.hasEffects(context))
11149 return true;
11150 }
11151 return false;
11152 }
11153 hasEffectsOnInteractionAtPath(path, interaction, context) {
11154 return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
11155 }
11156 include(context, includeChildrenRecursively) {
11157 this.included = true;
11158 const lastExpression = this.expressions[this.expressions.length - 1];
11159 for (const expression of this.expressions) {
11160 if (includeChildrenRecursively ||
11161 (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
11162 expression.shouldBeIncluded(context))
11163 expression.include(context, includeChildrenRecursively);
11164 }
11165 }
11166 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
11167 let includedNodes = 0;
11168 let lastSeparatorPos = null;
11169 const lastNode = this.expressions[this.expressions.length - 1];
11170 for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
11171 if (!node.included) {
11172 treeshakeNode(node, code, start, end);
11173 continue;
11174 }
11175 includedNodes++;
11176 lastSeparatorPos = separator;
11177 if (includedNodes === 1 && preventASI) {
11178 removeLineBreaks(code, start, node.start);
11179 }
11180 if (includedNodes === 1) {
11181 const parentType = renderedParentType || this.parent.type;
11182 node.render(code, options, {
11183 isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
11184 renderedParentType: parentType,
11185 renderedSurroundingElement: parentType
11186 });
11187 }
11188 else {
11189 node.render(code, options);
11190 }
11191 }
11192 if (lastSeparatorPos) {
11193 code.remove(lastSeparatorPos, this.end);
11194 }
11195 }
11196}
11197
11198class StaticBlock extends NodeBase {
11199 createScope(parentScope) {
11200 this.scope = new BlockScope(parentScope);
11201 }
11202 hasEffects(context) {
11203 for (const node of this.body) {
11204 if (node.hasEffects(context))
11205 return true;
11206 }
11207 return false;
11208 }
11209 include(context, includeChildrenRecursively) {
11210 this.included = true;
11211 for (const node of this.body) {
11212 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11213 node.include(context, includeChildrenRecursively);
11214 }
11215 }
11216 render(code, options) {
11217 if (this.body.length) {
11218 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11219 }
11220 else {
11221 super.render(code, options);
11222 }
11223 }
11224}
11225
11226class Super extends NodeBase {
11227 bind() {
11228 this.variable = this.scope.findVariable('this');
11229 }
11230 deoptimizePath(path) {
11231 this.variable.deoptimizePath(path);
11232 }
11233 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11234 this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
11235 }
11236 include() {
11237 if (!this.included) {
11238 this.included = true;
11239 this.context.includeVariableInModule(this.variable);
11240 }
11241 }
11242}
11243
11244class SwitchCase extends NodeBase {
11245 hasEffects(context) {
11246 var _a;
11247 if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
11248 return true;
11249 for (const node of this.consequent) {
11250 if (context.brokenFlow)
11251 break;
11252 if (node.hasEffects(context))
11253 return true;
11254 }
11255 return false;
11256 }
11257 include(context, includeChildrenRecursively) {
11258 var _a;
11259 this.included = true;
11260 (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11261 for (const node of this.consequent) {
11262 if (includeChildrenRecursively || node.shouldBeIncluded(context))
11263 node.include(context, includeChildrenRecursively);
11264 }
11265 }
11266 render(code, options, nodeRenderOptions) {
11267 if (this.consequent.length) {
11268 this.test && this.test.render(code, options);
11269 const testEnd = this.test
11270 ? this.test.end
11271 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
11272 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
11273 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
11274 }
11275 else {
11276 super.render(code, options);
11277 }
11278 }
11279}
11280SwitchCase.prototype.needsBoundaries = true;
11281
11282class SwitchStatement extends NodeBase {
11283 createScope(parentScope) {
11284 this.scope = new BlockScope(parentScope);
11285 }
11286 hasEffects(context) {
11287 if (this.discriminant.hasEffects(context))
11288 return true;
11289 const { brokenFlow, ignore: { breaks } } = context;
11290 let minBrokenFlow = Infinity;
11291 context.ignore.breaks = true;
11292 for (const switchCase of this.cases) {
11293 if (switchCase.hasEffects(context))
11294 return true;
11295 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
11296 context.brokenFlow = brokenFlow;
11297 }
11298 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11299 context.brokenFlow = minBrokenFlow;
11300 }
11301 context.ignore.breaks = breaks;
11302 return false;
11303 }
11304 include(context, includeChildrenRecursively) {
11305 this.included = true;
11306 this.discriminant.include(context, includeChildrenRecursively);
11307 const { brokenFlow } = context;
11308 let minBrokenFlow = Infinity;
11309 let isCaseIncluded = includeChildrenRecursively ||
11310 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
11311 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
11312 const switchCase = this.cases[caseIndex];
11313 if (switchCase.included) {
11314 isCaseIncluded = true;
11315 }
11316 if (!isCaseIncluded) {
11317 const hasEffectsContext = createHasEffectsContext();
11318 hasEffectsContext.ignore.breaks = true;
11319 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
11320 }
11321 if (isCaseIncluded) {
11322 switchCase.include(context, includeChildrenRecursively);
11323 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
11324 context.brokenFlow = brokenFlow;
11325 }
11326 else {
11327 minBrokenFlow = brokenFlow;
11328 }
11329 }
11330 if (isCaseIncluded &&
11331 this.defaultCase !== null &&
11332 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11333 context.brokenFlow = minBrokenFlow;
11334 }
11335 }
11336 initialise() {
11337 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
11338 if (this.cases[caseIndex].test === null) {
11339 this.defaultCase = caseIndex;
11340 return;
11341 }
11342 }
11343 this.defaultCase = null;
11344 }
11345 render(code, options) {
11346 this.discriminant.render(code, options);
11347 if (this.cases.length > 0) {
11348 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
11349 }
11350 }
11351}
11352
11353class TaggedTemplateExpression extends CallExpressionBase {
11354 bind() {
11355 super.bind();
11356 if (this.tag.type === Identifier$1) {
11357 const name = this.tag.name;
11358 const variable = this.scope.findVariable(name);
11359 if (variable.isNamespace) {
11360 this.context.warn({
11361 code: 'CANNOT_CALL_NAMESPACE',
11362 message: `Cannot call a namespace ('${name}')`
11363 }, this.start);
11364 }
11365 }
11366 }
11367 hasEffects(context) {
11368 try {
11369 for (const argument of this.quasi.expressions) {
11370 if (argument.hasEffects(context))
11371 return true;
11372 }
11373 return (this.tag.hasEffects(context) ||
11374 this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
11375 }
11376 finally {
11377 if (!this.deoptimized)
11378 this.applyDeoptimizations();
11379 }
11380 }
11381 include(context, includeChildrenRecursively) {
11382 if (!this.deoptimized)
11383 this.applyDeoptimizations();
11384 if (includeChildrenRecursively) {
11385 super.include(context, includeChildrenRecursively);
11386 }
11387 else {
11388 this.included = true;
11389 this.tag.include(context, includeChildrenRecursively);
11390 this.quasi.include(context, includeChildrenRecursively);
11391 }
11392 this.tag.includeCallArguments(context, this.interaction.args);
11393 const returnExpression = this.getReturnExpression();
11394 if (!returnExpression.included) {
11395 returnExpression.include(context, false);
11396 }
11397 }
11398 initialise() {
11399 this.interaction = {
11400 args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
11401 thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
11402 type: INTERACTION_CALLED,
11403 withNew: false
11404 };
11405 }
11406 render(code, options) {
11407 this.tag.render(code, options, { isCalleeOfRenderedParent: true });
11408 this.quasi.render(code, options);
11409 }
11410 applyDeoptimizations() {
11411 this.deoptimized = true;
11412 if (this.interaction.thisArg) {
11413 this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
11414 }
11415 for (const argument of this.quasi.expressions) {
11416 // This will make sure all properties of parameters behave as "unknown"
11417 argument.deoptimizePath(UNKNOWN_PATH);
11418 }
11419 this.context.requestTreeshakingPass();
11420 }
11421 getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
11422 if (this.returnExpression === null) {
11423 this.returnExpression = UNKNOWN_EXPRESSION;
11424 return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
11425 }
11426 return this.returnExpression;
11427 }
11428}
11429
11430class TemplateElement extends NodeBase {
11431 // Do not try to bind value
11432 bind() { }
11433 hasEffects() {
11434 return false;
11435 }
11436 include() {
11437 this.included = true;
11438 }
11439 parseNode(esTreeNode) {
11440 this.value = esTreeNode.value;
11441 super.parseNode(esTreeNode);
11442 }
11443 render() { }
11444}
11445
11446class TemplateLiteral extends NodeBase {
11447 deoptimizeThisOnInteractionAtPath() { }
11448 getLiteralValueAtPath(path) {
11449 if (path.length > 0 || this.quasis.length !== 1) {
11450 return UnknownValue;
11451 }
11452 return this.quasis[0].value.cooked;
11453 }
11454 getReturnExpressionWhenCalledAtPath(path) {
11455 if (path.length !== 1) {
11456 return UNKNOWN_EXPRESSION;
11457 }
11458 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
11459 }
11460 hasEffectsOnInteractionAtPath(path, interaction, context) {
11461 if (interaction.type === INTERACTION_ACCESSED) {
11462 return path.length > 1;
11463 }
11464 if (interaction.type === INTERACTION_CALLED && path.length === 1) {
11465 return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
11466 }
11467 return true;
11468 }
11469 render(code, options) {
11470 code.indentExclusionRanges.push([this.start, this.end]);
11471 super.render(code, options);
11472 }
11473}
11474
11475class UndefinedVariable extends Variable {
11476 constructor() {
11477 super('undefined');
11478 }
11479 getLiteralValueAtPath() {
11480 return undefined;
11481 }
11482}
11483
11484class ExportDefaultVariable extends LocalVariable {
11485 constructor(name, exportDefaultDeclaration, context) {
11486 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
11487 this.hasId = false;
11488 this.originalId = null;
11489 this.originalVariable = null;
11490 const declaration = exportDefaultDeclaration.declaration;
11491 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
11492 declaration.id) {
11493 this.hasId = true;
11494 this.originalId = declaration.id;
11495 }
11496 else if (declaration instanceof Identifier) {
11497 this.originalId = declaration;
11498 }
11499 }
11500 addReference(identifier) {
11501 if (!this.hasId) {
11502 this.name = identifier.name;
11503 }
11504 }
11505 getAssignedVariableName() {
11506 return (this.originalId && this.originalId.name) || null;
11507 }
11508 getBaseVariableName() {
11509 const original = this.getOriginalVariable();
11510 if (original === this) {
11511 return super.getBaseVariableName();
11512 }
11513 else {
11514 return original.getBaseVariableName();
11515 }
11516 }
11517 getDirectOriginalVariable() {
11518 return this.originalId &&
11519 (this.hasId ||
11520 !(this.originalId.isPossibleTDZ() ||
11521 this.originalId.variable.isReassigned ||
11522 this.originalId.variable instanceof UndefinedVariable ||
11523 // this avoids a circular dependency
11524 'syntheticNamespace' in this.originalId.variable))
11525 ? this.originalId.variable
11526 : null;
11527 }
11528 getName(getPropertyAccess) {
11529 const original = this.getOriginalVariable();
11530 if (original === this) {
11531 return super.getName(getPropertyAccess);
11532 }
11533 else {
11534 return original.getName(getPropertyAccess);
11535 }
11536 }
11537 getOriginalVariable() {
11538 if (this.originalVariable)
11539 return this.originalVariable;
11540 // eslint-disable-next-line @typescript-eslint/no-this-alias
11541 let original = this;
11542 let currentVariable;
11543 const checkedVariables = new Set();
11544 do {
11545 checkedVariables.add(original);
11546 currentVariable = original;
11547 original = currentVariable.getDirectOriginalVariable();
11548 } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
11549 return (this.originalVariable = original || currentVariable);
11550 }
11551}
11552
11553class ModuleScope extends ChildScope {
11554 constructor(parent, context) {
11555 super(parent);
11556 this.context = context;
11557 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
11558 }
11559 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
11560 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
11561 this.variables.set('default', variable);
11562 return variable;
11563 }
11564 addNamespaceMemberAccess() { }
11565 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
11566 // all module level variables are already deconflicted when deconflicting the chunk
11567 for (const scope of this.children)
11568 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
11569 }
11570 findLexicalBoundary() {
11571 return this;
11572 }
11573 findVariable(name) {
11574 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
11575 if (knownVariable) {
11576 return knownVariable;
11577 }
11578 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
11579 if (variable instanceof GlobalVariable) {
11580 this.accessedOutsideVariables.set(name, variable);
11581 }
11582 return variable;
11583 }
11584}
11585
11586class ThisExpression extends NodeBase {
11587 bind() {
11588 this.variable = this.scope.findVariable('this');
11589 }
11590 deoptimizePath(path) {
11591 this.variable.deoptimizePath(path);
11592 }
11593 deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
11594 // We rewrite the parameter so that a ThisVariable can detect self-mutations
11595 this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
11596 }
11597 hasEffectsOnInteractionAtPath(path, interaction, context) {
11598 if (path.length === 0) {
11599 return interaction.type !== INTERACTION_ACCESSED;
11600 }
11601 return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
11602 }
11603 include() {
11604 if (!this.included) {
11605 this.included = true;
11606 this.context.includeVariableInModule(this.variable);
11607 }
11608 }
11609 initialise() {
11610 this.alias =
11611 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
11612 if (this.alias === 'undefined') {
11613 this.context.warn({
11614 code: 'THIS_IS_UNDEFINED',
11615 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
11616 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
11617 }, this.start);
11618 }
11619 }
11620 render(code) {
11621 if (this.alias !== null) {
11622 code.overwrite(this.start, this.end, this.alias, {
11623 contentOnly: false,
11624 storeName: true
11625 });
11626 }
11627 }
11628}
11629
11630class ThrowStatement extends NodeBase {
11631 hasEffects() {
11632 return true;
11633 }
11634 include(context, includeChildrenRecursively) {
11635 this.included = true;
11636 this.argument.include(context, includeChildrenRecursively);
11637 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
11638 }
11639 render(code, options) {
11640 this.argument.render(code, options, { preventASI: true });
11641 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
11642 code.prependLeft(this.start + 5, ' ');
11643 }
11644 }
11645}
11646
11647class TryStatement extends NodeBase {
11648 constructor() {
11649 super(...arguments);
11650 this.directlyIncluded = false;
11651 this.includedLabelsAfterBlock = null;
11652 }
11653 hasEffects(context) {
11654 var _a;
11655 return ((this.context.options.treeshake.tryCatchDeoptimization
11656 ? this.block.body.length > 0
11657 : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
11658 }
11659 include(context, includeChildrenRecursively) {
11660 var _a, _b;
11661 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
11662 const { brokenFlow } = context;
11663 if (!this.directlyIncluded || !tryCatchDeoptimization) {
11664 this.included = true;
11665 this.directlyIncluded = true;
11666 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
11667 if (context.includedLabels.size > 0) {
11668 this.includedLabelsAfterBlock = [...context.includedLabels];
11669 }
11670 context.brokenFlow = brokenFlow;
11671 }
11672 else if (this.includedLabelsAfterBlock) {
11673 for (const label of this.includedLabelsAfterBlock) {
11674 context.includedLabels.add(label);
11675 }
11676 }
11677 if (this.handler !== null) {
11678 this.handler.include(context, includeChildrenRecursively);
11679 context.brokenFlow = brokenFlow;
11680 }
11681 (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
11682 }
11683}
11684
11685const unaryOperators = {
11686 '!': value => !value,
11687 '+': value => +value,
11688 '-': value => -value,
11689 delete: () => UnknownValue,
11690 typeof: value => typeof value,
11691 void: () => undefined,
11692 '~': value => ~value
11693};
11694class UnaryExpression extends NodeBase {
11695 getLiteralValueAtPath(path, recursionTracker, origin) {
11696 if (path.length > 0)
11697 return UnknownValue;
11698 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11699 if (typeof argumentValue === 'symbol')
11700 return UnknownValue;
11701 return unaryOperators[this.operator](argumentValue);
11702 }
11703 hasEffects(context) {
11704 if (!this.deoptimized)
11705 this.applyDeoptimizations();
11706 if (this.operator === 'typeof' && this.argument instanceof Identifier)
11707 return false;
11708 return (this.argument.hasEffects(context) ||
11709 (this.operator === 'delete' &&
11710 this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
11711 }
11712 hasEffectsOnInteractionAtPath(path, { type }) {
11713 return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
11714 }
11715 applyDeoptimizations() {
11716 this.deoptimized = true;
11717 if (this.operator === 'delete') {
11718 this.argument.deoptimizePath(EMPTY_PATH);
11719 this.context.requestTreeshakingPass();
11720 }
11721 }
11722}
11723
11724class UnknownNode extends NodeBase {
11725 hasEffects() {
11726 return true;
11727 }
11728 include(context) {
11729 super.include(context, true);
11730 }
11731}
11732
11733class UpdateExpression extends NodeBase {
11734 hasEffects(context) {
11735 if (!this.deoptimized)
11736 this.applyDeoptimizations();
11737 return this.argument.hasEffectsAsAssignmentTarget(context, true);
11738 }
11739 hasEffectsOnInteractionAtPath(path, { type }) {
11740 return path.length > 1 || type !== INTERACTION_ACCESSED;
11741 }
11742 include(context, includeChildrenRecursively) {
11743 if (!this.deoptimized)
11744 this.applyDeoptimizations();
11745 this.included = true;
11746 this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
11747 }
11748 initialise() {
11749 this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
11750 }
11751 render(code, options) {
11752 const { exportNamesByVariable, format, snippets: { _ } } = options;
11753 this.argument.render(code, options);
11754 if (format === 'system') {
11755 const variable = this.argument.variable;
11756 const exportNames = exportNamesByVariable.get(variable);
11757 if (exportNames) {
11758 if (this.prefix) {
11759 if (exportNames.length === 1) {
11760 renderSystemExportExpression(variable, this.start, this.end, code, options);
11761 }
11762 else {
11763 renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
11764 }
11765 }
11766 else {
11767 const operator = this.operator[0];
11768 renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
11769 }
11770 }
11771 }
11772 }
11773 applyDeoptimizations() {
11774 this.deoptimized = true;
11775 this.argument.deoptimizePath(EMPTY_PATH);
11776 if (this.argument instanceof Identifier) {
11777 const variable = this.scope.findVariable(this.argument.name);
11778 variable.isReassigned = true;
11779 }
11780 this.context.requestTreeshakingPass();
11781 }
11782}
11783
11784function isReassignedExportsMember(variable, exportNamesByVariable) {
11785 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
11786}
11787
11788function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
11789 for (const declarator of declarations) {
11790 if (!declarator.id.included)
11791 return false;
11792 if (declarator.id.type === Identifier$1) {
11793 if (exportNamesByVariable.has(declarator.id.variable))
11794 return false;
11795 }
11796 else {
11797 const exportedVariables = [];
11798 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
11799 if (exportedVariables.length > 0)
11800 return false;
11801 }
11802 }
11803 return true;
11804}
11805class VariableDeclaration extends NodeBase {
11806 deoptimizePath() {
11807 for (const declarator of this.declarations) {
11808 declarator.deoptimizePath(EMPTY_PATH);
11809 }
11810 }
11811 hasEffectsOnInteractionAtPath() {
11812 return false;
11813 }
11814 include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
11815 this.included = true;
11816 for (const declarator of this.declarations) {
11817 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
11818 declarator.include(context, includeChildrenRecursively);
11819 if (asSingleStatement) {
11820 declarator.id.include(context, includeChildrenRecursively);
11821 }
11822 }
11823 }
11824 initialise() {
11825 for (const declarator of this.declarations) {
11826 declarator.declareDeclarator(this.kind);
11827 }
11828 }
11829 render(code, options, nodeRenderOptions = BLANK) {
11830 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
11831 for (const declarator of this.declarations) {
11832 declarator.render(code, options);
11833 }
11834 if (!nodeRenderOptions.isNoStatement &&
11835 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
11836 code.appendLeft(this.end, ';');
11837 }
11838 }
11839 else {
11840 this.renderReplacedDeclarations(code, options);
11841 }
11842 }
11843 applyDeoptimizations() { }
11844 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
11845 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
11846 code.remove(this.end - 1, this.end);
11847 }
11848 separatorString += ';';
11849 if (lastSeparatorPos !== null) {
11850 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
11851 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
11852 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
11853 actualContentEnd--;
11854 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
11855 actualContentEnd--;
11856 }
11857 }
11858 if (actualContentEnd === lastSeparatorPos + 1) {
11859 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
11860 }
11861 else {
11862 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11863 code.remove(actualContentEnd, renderedContentEnd);
11864 }
11865 }
11866 else {
11867 code.appendLeft(renderedContentEnd, separatorString);
11868 }
11869 if (systemPatternExports.length > 0) {
11870 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
11871 }
11872 }
11873 renderReplacedDeclarations(code, options) {
11874 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
11875 let actualContentEnd, renderedContentEnd;
11876 renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
11877 let lastSeparatorPos = renderedContentEnd - 1;
11878 code.remove(this.start, lastSeparatorPos);
11879 let isInDeclaration = false;
11880 let hasRenderedContent = false;
11881 let separatorString = '', leadingString, nextSeparatorString;
11882 const aggregatedSystemExports = [];
11883 const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
11884 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
11885 if (!node.included) {
11886 code.remove(start, end);
11887 continue;
11888 }
11889 node.render(code, options);
11890 leadingString = '';
11891 nextSeparatorString = '';
11892 if (!node.id.included ||
11893 (node.id instanceof Identifier &&
11894 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
11895 if (hasRenderedContent) {
11896 separatorString += ';';
11897 }
11898 isInDeclaration = false;
11899 }
11900 else {
11901 if (singleSystemExport && singleSystemExport === node.id.variable) {
11902 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
11903 renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
11904 }
11905 if (isInDeclaration) {
11906 separatorString += ',';
11907 }
11908 else {
11909 if (hasRenderedContent) {
11910 separatorString += ';';
11911 }
11912 leadingString += `${this.kind} `;
11913 isInDeclaration = true;
11914 }
11915 }
11916 if (renderedContentEnd === lastSeparatorPos + 1) {
11917 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
11918 }
11919 else {
11920 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
11921 code.appendLeft(renderedContentEnd, leadingString);
11922 }
11923 actualContentEnd = contentEnd;
11924 renderedContentEnd = end;
11925 hasRenderedContent = true;
11926 lastSeparatorPos = separator;
11927 separatorString = nextSeparatorString;
11928 }
11929 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
11930 }
11931}
11932function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
11933 var _a;
11934 let singleSystemExport = null;
11935 if (options.format === 'system') {
11936 for (const { node } of separatedNodes) {
11937 if (node.id instanceof Identifier &&
11938 node.init &&
11939 aggregatedSystemExports.length === 0 &&
11940 ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
11941 singleSystemExport = node.id.variable;
11942 aggregatedSystemExports.push(singleSystemExport);
11943 }
11944 else {
11945 node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
11946 }
11947 }
11948 if (aggregatedSystemExports.length > 1) {
11949 singleSystemExport = null;
11950 }
11951 else if (singleSystemExport) {
11952 aggregatedSystemExports.length = 0;
11953 }
11954 }
11955 return singleSystemExport;
11956}
11957
11958class VariableDeclarator extends NodeBase {
11959 declareDeclarator(kind) {
11960 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
11961 }
11962 deoptimizePath(path) {
11963 this.id.deoptimizePath(path);
11964 }
11965 hasEffects(context) {
11966 var _a;
11967 const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
11968 this.id.markDeclarationReached();
11969 return initEffect || this.id.hasEffects(context);
11970 }
11971 include(context, includeChildrenRecursively) {
11972 var _a;
11973 this.included = true;
11974 (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
11975 this.id.markDeclarationReached();
11976 if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
11977 this.id.include(context, includeChildrenRecursively);
11978 }
11979 }
11980 render(code, options) {
11981 const { exportNamesByVariable, snippets: { _ } } = options;
11982 const renderId = this.id.included;
11983 if (renderId) {
11984 this.id.render(code, options);
11985 }
11986 else {
11987 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
11988 code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
11989 }
11990 if (this.init) {
11991 this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
11992 }
11993 else if (this.id instanceof Identifier &&
11994 isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
11995 code.appendLeft(this.end, `${_}=${_}void 0`);
11996 }
11997 }
11998 applyDeoptimizations() { }
11999}
12000
12001class WhileStatement extends NodeBase {
12002 hasEffects(context) {
12003 if (this.test.hasEffects(context))
12004 return true;
12005 const { brokenFlow, ignore: { breaks, continues } } = context;
12006 context.ignore.breaks = true;
12007 context.ignore.continues = true;
12008 if (this.body.hasEffects(context))
12009 return true;
12010 context.ignore.breaks = breaks;
12011 context.ignore.continues = continues;
12012 context.brokenFlow = brokenFlow;
12013 return false;
12014 }
12015 include(context, includeChildrenRecursively) {
12016 this.included = true;
12017 this.test.include(context, includeChildrenRecursively);
12018 const { brokenFlow } = context;
12019 this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
12020 context.brokenFlow = brokenFlow;
12021 }
12022}
12023
12024class YieldExpression extends NodeBase {
12025 hasEffects(context) {
12026 var _a;
12027 if (!this.deoptimized)
12028 this.applyDeoptimizations();
12029 return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
12030 }
12031 render(code, options) {
12032 if (this.argument) {
12033 this.argument.render(code, options, { preventASI: true });
12034 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
12035 code.prependLeft(this.start + 5, ' ');
12036 }
12037 }
12038 }
12039}
12040
12041const nodeConstructors = {
12042 ArrayExpression,
12043 ArrayPattern,
12044 ArrowFunctionExpression,
12045 AssignmentExpression,
12046 AssignmentPattern,
12047 AwaitExpression,
12048 BinaryExpression,
12049 BlockStatement,
12050 BreakStatement,
12051 CallExpression,
12052 CatchClause,
12053 ChainExpression,
12054 ClassBody,
12055 ClassDeclaration,
12056 ClassExpression,
12057 ConditionalExpression,
12058 ContinueStatement,
12059 DoWhileStatement,
12060 EmptyStatement,
12061 ExportAllDeclaration,
12062 ExportDefaultDeclaration,
12063 ExportNamedDeclaration,
12064 ExportSpecifier,
12065 ExpressionStatement,
12066 ForInStatement,
12067 ForOfStatement,
12068 ForStatement,
12069 FunctionDeclaration,
12070 FunctionExpression,
12071 Identifier,
12072 IfStatement,
12073 ImportDeclaration,
12074 ImportDefaultSpecifier,
12075 ImportExpression,
12076 ImportNamespaceSpecifier,
12077 ImportSpecifier,
12078 LabeledStatement,
12079 Literal,
12080 LogicalExpression,
12081 MemberExpression,
12082 MetaProperty,
12083 MethodDefinition,
12084 NewExpression,
12085 ObjectExpression,
12086 ObjectPattern,
12087 PrivateIdentifier,
12088 Program,
12089 Property,
12090 PropertyDefinition,
12091 RestElement,
12092 ReturnStatement,
12093 SequenceExpression,
12094 SpreadElement,
12095 StaticBlock,
12096 Super,
12097 SwitchCase,
12098 SwitchStatement,
12099 TaggedTemplateExpression,
12100 TemplateElement,
12101 TemplateLiteral,
12102 ThisExpression,
12103 ThrowStatement,
12104 TryStatement,
12105 UnaryExpression,
12106 UnknownNode,
12107 UpdateExpression,
12108 VariableDeclaration,
12109 VariableDeclarator,
12110 WhileStatement,
12111 YieldExpression
12112};
12113
12114const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
12115
12116class ExportShimVariable extends Variable {
12117 constructor(module) {
12118 super(MISSING_EXPORT_SHIM_VARIABLE);
12119 this.module = module;
12120 }
12121 include() {
12122 super.include();
12123 this.module.needsExportShim = true;
12124 }
12125}
12126
12127class NamespaceVariable extends Variable {
12128 constructor(context) {
12129 super(context.getModuleName());
12130 this.memberVariables = null;
12131 this.mergedNamespaces = [];
12132 this.referencedEarly = false;
12133 this.references = [];
12134 this.context = context;
12135 this.module = context.module;
12136 }
12137 addReference(identifier) {
12138 this.references.push(identifier);
12139 this.name = identifier.name;
12140 }
12141 getMemberVariables() {
12142 if (this.memberVariables) {
12143 return this.memberVariables;
12144 }
12145 const memberVariables = Object.create(null);
12146 for (const name of this.context.getExports().concat(this.context.getReexports())) {
12147 if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
12148 const exportedVariable = this.context.traceExport(name);
12149 if (exportedVariable) {
12150 memberVariables[name] = exportedVariable;
12151 }
12152 }
12153 }
12154 return (this.memberVariables = memberVariables);
12155 }
12156 include() {
12157 this.included = true;
12158 this.context.includeAllExports();
12159 }
12160 prepare(accessedGlobalsByScope) {
12161 if (this.mergedNamespaces.length > 0) {
12162 this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
12163 }
12164 }
12165 renderBlock(options) {
12166 const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
12167 const memberVariables = this.getMemberVariables();
12168 const members = Object.entries(memberVariables).map(([name, original]) => {
12169 if (this.referencedEarly || original.isReassigned) {
12170 return [
12171 null,
12172 `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
12173 ];
12174 }
12175 return [name, original.getName(getPropertyAccess)];
12176 });
12177 members.unshift([null, `__proto__:${_}null`]);
12178 let output = getObject(members, { lineBreakIndent: { base: '', t } });
12179 if (this.mergedNamespaces.length > 0) {
12180 const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
12181 output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
12182 }
12183 else {
12184 // The helper to merge namespaces will also take care of freezing and toStringTag
12185 if (namespaceToStringTag) {
12186 output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
12187 }
12188 if (freeze) {
12189 output = `/*#__PURE__*/Object.freeze(${output})`;
12190 }
12191 }
12192 const name = this.getName(getPropertyAccess);
12193 output = `${cnst} ${name}${_}=${_}${output};`;
12194 if (format === 'system' && exportNamesByVariable.has(this)) {
12195 output += `${n}${getSystemExportStatement([this], options)};`;
12196 }
12197 return output;
12198 }
12199 renderFirst() {
12200 return this.referencedEarly;
12201 }
12202 setMergedNamespaces(mergedNamespaces) {
12203 this.mergedNamespaces = mergedNamespaces;
12204 const moduleExecIndex = this.context.getModuleExecIndex();
12205 for (const identifier of this.references) {
12206 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
12207 this.referencedEarly = true;
12208 break;
12209 }
12210 }
12211 }
12212}
12213NamespaceVariable.prototype.isNamespace = true;
12214
12215class SyntheticNamedExportVariable extends Variable {
12216 constructor(context, name, syntheticNamespace) {
12217 super(name);
12218 this.baseVariable = null;
12219 this.context = context;
12220 this.module = context.module;
12221 this.syntheticNamespace = syntheticNamespace;
12222 }
12223 getBaseVariable() {
12224 if (this.baseVariable)
12225 return this.baseVariable;
12226 let baseVariable = this.syntheticNamespace;
12227 while (baseVariable instanceof ExportDefaultVariable ||
12228 baseVariable instanceof SyntheticNamedExportVariable) {
12229 if (baseVariable instanceof ExportDefaultVariable) {
12230 const original = baseVariable.getOriginalVariable();
12231 if (original === baseVariable)
12232 break;
12233 baseVariable = original;
12234 }
12235 if (baseVariable instanceof SyntheticNamedExportVariable) {
12236 baseVariable = baseVariable.syntheticNamespace;
12237 }
12238 }
12239 return (this.baseVariable = baseVariable);
12240 }
12241 getBaseVariableName() {
12242 return this.syntheticNamespace.getBaseVariableName();
12243 }
12244 getName(getPropertyAccess) {
12245 return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
12246 }
12247 include() {
12248 this.included = true;
12249 this.context.includeVariableInModule(this.syntheticNamespace);
12250 }
12251 setRenderNames(baseName, name) {
12252 super.setRenderNames(baseName, name);
12253 }
12254}
12255
12256var BuildPhase;
12257(function (BuildPhase) {
12258 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
12259 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
12260 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
12261})(BuildPhase || (BuildPhase = {}));
12262
12263function getId(m) {
12264 return m.id;
12265}
12266
12267function getOriginalLocation(sourcemapChain, location) {
12268 const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
12269 traceSourcemap: while (filteredSourcemapChain.length > 0) {
12270 const sourcemap = filteredSourcemapChain.pop();
12271 const line = sourcemap.mappings[location.line - 1];
12272 if (line) {
12273 const filteredLine = line.filter((segment) => segment.length > 1);
12274 const lastSegment = filteredLine[filteredLine.length - 1];
12275 for (const segment of filteredLine) {
12276 if (segment[0] >= location.column || segment === lastSegment) {
12277 location = {
12278 column: segment[3],
12279 line: segment[2] + 1
12280 };
12281 continue traceSourcemap;
12282 }
12283 }
12284 }
12285 throw new Error("Can't resolve original location of error.");
12286 }
12287 return location;
12288}
12289
12290const NOOP = () => { };
12291let timers = new Map();
12292function getPersistedLabel(label, level) {
12293 switch (level) {
12294 case 1:
12295 return `# ${label}`;
12296 case 2:
12297 return `## ${label}`;
12298 case 3:
12299 return label;
12300 default:
12301 return `${' '.repeat(level - 4)}- ${label}`;
12302 }
12303}
12304function timeStartImpl(label, level = 3) {
12305 label = getPersistedLabel(label, level);
12306 const startMemory = process$1.memoryUsage().heapUsed;
12307 const startTime = perf_hooks.performance.now();
12308 const timer = timers.get(label);
12309 if (timer === undefined) {
12310 timers.set(label, {
12311 memory: 0,
12312 startMemory,
12313 startTime,
12314 time: 0,
12315 totalMemory: 0
12316 });
12317 }
12318 else {
12319 timer.startMemory = startMemory;
12320 timer.startTime = startTime;
12321 }
12322}
12323function timeEndImpl(label, level = 3) {
12324 label = getPersistedLabel(label, level);
12325 const timer = timers.get(label);
12326 if (timer !== undefined) {
12327 const currentMemory = process$1.memoryUsage().heapUsed;
12328 timer.memory += currentMemory - timer.startMemory;
12329 timer.time += perf_hooks.performance.now() - timer.startTime;
12330 timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
12331 }
12332}
12333function getTimings() {
12334 const newTimings = {};
12335 for (const [label, { memory, time, totalMemory }] of timers) {
12336 newTimings[label] = [time, memory, totalMemory];
12337 }
12338 return newTimings;
12339}
12340let timeStart = NOOP;
12341let timeEnd = NOOP;
12342const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
12343function getPluginWithTimers(plugin, index) {
12344 for (const hook of TIMED_PLUGIN_HOOKS) {
12345 if (hook in plugin) {
12346 let timerLabel = `plugin ${index}`;
12347 if (plugin.name) {
12348 timerLabel += ` (${plugin.name})`;
12349 }
12350 timerLabel += ` - ${hook}`;
12351 const func = plugin[hook];
12352 plugin[hook] = function (...args) {
12353 timeStart(timerLabel, 4);
12354 const result = func.apply(this, args);
12355 timeEnd(timerLabel, 4);
12356 if (result && typeof result.then === 'function') {
12357 timeStart(`${timerLabel} (async)`, 4);
12358 return result.then((hookResult) => {
12359 timeEnd(`${timerLabel} (async)`, 4);
12360 return hookResult;
12361 });
12362 }
12363 return result;
12364 };
12365 }
12366 }
12367 return plugin;
12368}
12369function initialiseTimers(inputOptions) {
12370 if (inputOptions.perf) {
12371 timers = new Map();
12372 timeStart = timeStartImpl;
12373 timeEnd = timeEndImpl;
12374 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
12375 }
12376 else {
12377 timeStart = NOOP;
12378 timeEnd = NOOP;
12379 }
12380}
12381
12382function markModuleAndImpureDependenciesAsExecuted(baseModule) {
12383 baseModule.isExecuted = true;
12384 const modules = [baseModule];
12385 const visitedModules = new Set();
12386 for (const module of modules) {
12387 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
12388 if (!(dependency instanceof ExternalModule) &&
12389 !dependency.isExecuted &&
12390 (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
12391 !visitedModules.has(dependency.id)) {
12392 dependency.isExecuted = true;
12393 visitedModules.add(dependency.id);
12394 modules.push(dependency);
12395 }
12396 }
12397 }
12398}
12399
12400const MISSING_EXPORT_SHIM_DESCRIPTION = {
12401 identifier: null,
12402 localName: MISSING_EXPORT_SHIM_VARIABLE
12403};
12404function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
12405 const searchedModules = searchedNamesAndModules.get(name);
12406 if (searchedModules) {
12407 if (searchedModules.has(target)) {
12408 return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
12409 }
12410 searchedModules.add(target);
12411 }
12412 else {
12413 searchedNamesAndModules.set(name, new Set([target]));
12414 }
12415 return target.getVariableForExportName(name, {
12416 importerForSideEffects,
12417 isExportAllSearch,
12418 searchedNamesAndModules
12419 });
12420}
12421function getAndExtendSideEffectModules(variable, module) {
12422 const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
12423 let currentVariable = variable;
12424 const referencedVariables = new Set([currentVariable]);
12425 while (true) {
12426 const importingModule = currentVariable.module;
12427 currentVariable =
12428 currentVariable instanceof ExportDefaultVariable
12429 ? currentVariable.getDirectOriginalVariable()
12430 : currentVariable instanceof SyntheticNamedExportVariable
12431 ? currentVariable.syntheticNamespace
12432 : null;
12433 if (!currentVariable || referencedVariables.has(currentVariable)) {
12434 break;
12435 }
12436 referencedVariables.add(currentVariable);
12437 sideEffectModules.add(importingModule);
12438 const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
12439 if (originalSideEffects) {
12440 for (const module of originalSideEffects) {
12441 sideEffectModules.add(module);
12442 }
12443 }
12444 }
12445 return sideEffectModules;
12446}
12447class Module {
12448 constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
12449 this.graph = graph;
12450 this.id = id;
12451 this.options = options;
12452 this.alternativeReexportModules = new Map();
12453 this.chunkFileNames = new Set();
12454 this.chunkNames = [];
12455 this.cycles = new Set();
12456 this.dependencies = new Set();
12457 this.dynamicDependencies = new Set();
12458 this.dynamicImporters = [];
12459 this.dynamicImports = [];
12460 this.execIndex = Infinity;
12461 this.implicitlyLoadedAfter = new Set();
12462 this.implicitlyLoadedBefore = new Set();
12463 this.importDescriptions = new Map();
12464 this.importMetas = [];
12465 this.importedFromNotTreeshaken = false;
12466 this.importers = [];
12467 this.includedDynamicImporters = [];
12468 this.includedImports = new Set();
12469 this.isExecuted = false;
12470 this.isUserDefinedEntryPoint = false;
12471 this.needsExportShim = false;
12472 this.sideEffectDependenciesByVariable = new Map();
12473 this.sources = new Set();
12474 this.usesTopLevelAwait = false;
12475 this.allExportNames = null;
12476 this.ast = null;
12477 this.exportAllModules = [];
12478 this.exportAllSources = new Set();
12479 this.exportNamesByVariable = null;
12480 this.exportShimVariable = new ExportShimVariable(this);
12481 this.exports = new Map();
12482 this.namespaceReexportsByName = new Map();
12483 this.reexportDescriptions = new Map();
12484 this.relevantDependencies = null;
12485 this.syntheticExports = new Map();
12486 this.syntheticNamespace = null;
12487 this.transformDependencies = [];
12488 this.transitiveReexports = null;
12489 this.excludeFromSourcemap = /\0/.test(id);
12490 this.context = options.moduleContext(id);
12491 this.preserveSignature = this.options.preserveEntrySignatures;
12492 // eslint-disable-next-line @typescript-eslint/no-this-alias
12493 const module = this;
12494 const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
12495 this.info = {
12496 ast: null,
12497 code: null,
12498 get dynamicallyImportedIdResolutions() {
12499 return dynamicImports
12500 .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
12501 .filter(Boolean);
12502 },
12503 get dynamicallyImportedIds() {
12504 // We cannot use this.dynamicDependencies because this is needed before
12505 // dynamicDependencies are populated
12506 return dynamicImports.map(({ id }) => id).filter((id) => id != null);
12507 },
12508 get dynamicImporters() {
12509 return dynamicImporters.sort();
12510 },
12511 get hasDefaultExport() {
12512 // This information is only valid after parsing
12513 if (!module.ast) {
12514 return null;
12515 }
12516 return module.exports.has('default') || reexportDescriptions.has('default');
12517 },
12518 get hasModuleSideEffects() {
12519 warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
12520 return this.moduleSideEffects;
12521 },
12522 id,
12523 get implicitlyLoadedAfterOneOf() {
12524 return Array.from(implicitlyLoadedAfter, getId).sort();
12525 },
12526 get implicitlyLoadedBefore() {
12527 return Array.from(implicitlyLoadedBefore, getId).sort();
12528 },
12529 get importedIdResolutions() {
12530 return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
12531 },
12532 get importedIds() {
12533 // We cannot use this.dependencies because this is needed before
12534 // dependencies are populated
12535 return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
12536 },
12537 get importers() {
12538 return importers.sort();
12539 },
12540 isEntry,
12541 isExternal: false,
12542 get isIncluded() {
12543 if (graph.phase !== BuildPhase.GENERATE) {
12544 return null;
12545 }
12546 return module.isIncluded();
12547 },
12548 meta: { ...meta },
12549 moduleSideEffects,
12550 syntheticNamedExports
12551 };
12552 // Hide the deprecated key so that it only warns when accessed explicitly
12553 Object.defineProperty(this.info, 'hasModuleSideEffects', {
12554 enumerable: false
12555 });
12556 }
12557 basename() {
12558 const base = require$$0.basename(this.id);
12559 const ext = require$$0.extname(this.id);
12560 return makeLegal(ext ? base.slice(0, -ext.length) : base);
12561 }
12562 bindReferences() {
12563 this.ast.bind();
12564 }
12565 error(props, pos) {
12566 this.addLocationToLogProps(props, pos);
12567 return error(props);
12568 }
12569 getAllExportNames() {
12570 if (this.allExportNames) {
12571 return this.allExportNames;
12572 }
12573 this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
12574 for (const module of this.exportAllModules) {
12575 if (module instanceof ExternalModule) {
12576 this.allExportNames.add(`*${module.id}`);
12577 continue;
12578 }
12579 for (const name of module.getAllExportNames()) {
12580 if (name !== 'default')
12581 this.allExportNames.add(name);
12582 }
12583 }
12584 // We do not count the synthetic namespace as a regular export to hide it
12585 // from entry signatures and namespace objects
12586 if (typeof this.info.syntheticNamedExports === 'string') {
12587 this.allExportNames.delete(this.info.syntheticNamedExports);
12588 }
12589 return this.allExportNames;
12590 }
12591 getDependenciesToBeIncluded() {
12592 if (this.relevantDependencies)
12593 return this.relevantDependencies;
12594 this.relevantDependencies = new Set();
12595 const necessaryDependencies = new Set();
12596 const alwaysCheckedDependencies = new Set();
12597 const dependencyVariables = new Set(this.includedImports);
12598 if (this.info.isEntry ||
12599 this.includedDynamicImporters.length > 0 ||
12600 this.namespace.included ||
12601 this.implicitlyLoadedAfter.size > 0) {
12602 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
12603 const [exportedVariable] = this.getVariableForExportName(exportName);
12604 if (exportedVariable) {
12605 dependencyVariables.add(exportedVariable);
12606 }
12607 }
12608 }
12609 for (let variable of dependencyVariables) {
12610 const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
12611 if (sideEffectDependencies) {
12612 for (const module of sideEffectDependencies) {
12613 alwaysCheckedDependencies.add(module);
12614 }
12615 }
12616 if (variable instanceof SyntheticNamedExportVariable) {
12617 variable = variable.getBaseVariable();
12618 }
12619 else if (variable instanceof ExportDefaultVariable) {
12620 variable = variable.getOriginalVariable();
12621 }
12622 necessaryDependencies.add(variable.module);
12623 }
12624 if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
12625 for (const dependency of this.dependencies) {
12626 this.relevantDependencies.add(dependency);
12627 }
12628 }
12629 else {
12630 this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
12631 }
12632 for (const dependency of necessaryDependencies) {
12633 this.relevantDependencies.add(dependency);
12634 }
12635 return this.relevantDependencies;
12636 }
12637 getExportNamesByVariable() {
12638 if (this.exportNamesByVariable) {
12639 return this.exportNamesByVariable;
12640 }
12641 const exportNamesByVariable = new Map();
12642 for (const exportName of this.getAllExportNames()) {
12643 let [tracedVariable] = this.getVariableForExportName(exportName);
12644 if (tracedVariable instanceof ExportDefaultVariable) {
12645 tracedVariable = tracedVariable.getOriginalVariable();
12646 }
12647 if (!tracedVariable ||
12648 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
12649 continue;
12650 }
12651 const existingExportNames = exportNamesByVariable.get(tracedVariable);
12652 if (existingExportNames) {
12653 existingExportNames.push(exportName);
12654 }
12655 else {
12656 exportNamesByVariable.set(tracedVariable, [exportName]);
12657 }
12658 }
12659 return (this.exportNamesByVariable = exportNamesByVariable);
12660 }
12661 getExports() {
12662 return Array.from(this.exports.keys());
12663 }
12664 getReexports() {
12665 if (this.transitiveReexports) {
12666 return this.transitiveReexports;
12667 }
12668 // to avoid infinite recursion when using circular `export * from X`
12669 this.transitiveReexports = [];
12670 const reexports = new Set(this.reexportDescriptions.keys());
12671 for (const module of this.exportAllModules) {
12672 if (module instanceof ExternalModule) {
12673 reexports.add(`*${module.id}`);
12674 }
12675 else {
12676 for (const name of [...module.getReexports(), ...module.getExports()]) {
12677 if (name !== 'default')
12678 reexports.add(name);
12679 }
12680 }
12681 }
12682 return (this.transitiveReexports = [...reexports]);
12683 }
12684 getRenderedExports() {
12685 // only direct exports are counted here, not reexports at all
12686 const renderedExports = [];
12687 const removedExports = [];
12688 for (const exportName of this.exports.keys()) {
12689 const [variable] = this.getVariableForExportName(exportName);
12690 (variable && variable.included ? renderedExports : removedExports).push(exportName);
12691 }
12692 return { removedExports, renderedExports };
12693 }
12694 getSyntheticNamespace() {
12695 if (this.syntheticNamespace === null) {
12696 this.syntheticNamespace = undefined;
12697 [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
12698 ? this.info.syntheticNamedExports
12699 : 'default', { onlyExplicit: true });
12700 }
12701 if (!this.syntheticNamespace) {
12702 return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
12703 }
12704 return this.syntheticNamespace;
12705 }
12706 getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
12707 var _a;
12708 if (name[0] === '*') {
12709 if (name.length === 1) {
12710 // export * from './other'
12711 return [this.namespace];
12712 }
12713 // export * from 'external'
12714 const module = this.graph.modulesById.get(name.slice(1));
12715 return module.getVariableForExportName('*');
12716 }
12717 // export { foo } from './other'
12718 const reexportDeclaration = this.reexportDescriptions.get(name);
12719 if (reexportDeclaration) {
12720 const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
12721 if (!variable) {
12722 return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
12723 }
12724 if (importerForSideEffects) {
12725 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12726 }
12727 return [variable];
12728 }
12729 const exportDeclaration = this.exports.get(name);
12730 if (exportDeclaration) {
12731 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
12732 return [this.exportShimVariable];
12733 }
12734 const name = exportDeclaration.localName;
12735 const variable = this.traceVariable(name, {
12736 importerForSideEffects,
12737 searchedNamesAndModules
12738 });
12739 if (importerForSideEffects) {
12740 getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
12741 setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
12742 }
12743 return [variable];
12744 }
12745 if (onlyExplicit) {
12746 return [null];
12747 }
12748 if (name !== 'default') {
12749 const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
12750 this.namespaceReexportsByName.set(name, foundNamespaceReexport);
12751 if (foundNamespaceReexport[0]) {
12752 return foundNamespaceReexport;
12753 }
12754 }
12755 if (this.info.syntheticNamedExports) {
12756 return [
12757 getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
12758 ];
12759 }
12760 // we don't want to create shims when we are just
12761 // probing export * modules for exports
12762 if (!isExportAllSearch) {
12763 if (this.options.shimMissingExports) {
12764 this.shimMissingExport(name);
12765 return [this.exportShimVariable];
12766 }
12767 }
12768 return [null];
12769 }
12770 hasEffects() {
12771 return (this.info.moduleSideEffects === 'no-treeshake' ||
12772 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
12773 }
12774 include() {
12775 const context = createInclusionContext();
12776 if (this.ast.shouldBeIncluded(context))
12777 this.ast.include(context, false);
12778 }
12779 includeAllExports(includeNamespaceMembers) {
12780 if (!this.isExecuted) {
12781 markModuleAndImpureDependenciesAsExecuted(this);
12782 this.graph.needsTreeshakingPass = true;
12783 }
12784 for (const exportName of this.exports.keys()) {
12785 if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
12786 const variable = this.getVariableForExportName(exportName)[0];
12787 variable.deoptimizePath(UNKNOWN_PATH);
12788 if (!variable.included) {
12789 this.includeVariable(variable);
12790 }
12791 }
12792 }
12793 for (const name of this.getReexports()) {
12794 const [variable] = this.getVariableForExportName(name);
12795 if (variable) {
12796 variable.deoptimizePath(UNKNOWN_PATH);
12797 if (!variable.included) {
12798 this.includeVariable(variable);
12799 }
12800 if (variable instanceof ExternalVariable) {
12801 variable.module.reexported = true;
12802 }
12803 }
12804 }
12805 if (includeNamespaceMembers) {
12806 this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
12807 }
12808 }
12809 includeAllInBundle() {
12810 this.ast.include(createInclusionContext(), true);
12811 this.includeAllExports(false);
12812 }
12813 isIncluded() {
12814 return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
12815 }
12816 linkImports() {
12817 this.addModulesToImportDescriptions(this.importDescriptions);
12818 this.addModulesToImportDescriptions(this.reexportDescriptions);
12819 const externalExportAllModules = [];
12820 for (const source of this.exportAllSources) {
12821 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
12822 if (module instanceof ExternalModule) {
12823 externalExportAllModules.push(module);
12824 continue;
12825 }
12826 this.exportAllModules.push(module);
12827 }
12828 this.exportAllModules.push(...externalExportAllModules);
12829 }
12830 render(options) {
12831 const magicString = this.magicString.clone();
12832 this.ast.render(magicString, options);
12833 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
12834 return magicString;
12835 }
12836 setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
12837 this.info.code = code;
12838 this.originalCode = originalCode;
12839 this.originalSourcemap = originalSourcemap;
12840 this.sourcemapChain = sourcemapChain;
12841 if (transformFiles) {
12842 this.transformFiles = transformFiles;
12843 }
12844 this.transformDependencies = transformDependencies;
12845 this.customTransformCache = customTransformCache;
12846 this.updateOptions(moduleOptions);
12847 timeStart('generate ast', 3);
12848 if (!ast) {
12849 ast = this.tryParse();
12850 }
12851 timeEnd('generate ast', 3);
12852 this.resolvedIds = resolvedIds || Object.create(null);
12853 // By default, `id` is the file name. Custom resolvers and loaders
12854 // can change that, but it makes sense to use it for the source file name
12855 const fileName = this.id;
12856 this.magicString = new MagicString(code, {
12857 filename: (this.excludeFromSourcemap ? null : fileName),
12858 indentExclusionRanges: []
12859 });
12860 timeStart('analyse ast', 3);
12861 this.astContext = {
12862 addDynamicImport: this.addDynamicImport.bind(this),
12863 addExport: this.addExport.bind(this),
12864 addImport: this.addImport.bind(this),
12865 addImportMeta: this.addImportMeta.bind(this),
12866 code,
12867 deoptimizationTracker: this.graph.deoptimizationTracker,
12868 error: this.error.bind(this),
12869 fileName,
12870 getExports: this.getExports.bind(this),
12871 getModuleExecIndex: () => this.execIndex,
12872 getModuleName: this.basename.bind(this),
12873 getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
12874 getReexports: this.getReexports.bind(this),
12875 importDescriptions: this.importDescriptions,
12876 includeAllExports: () => this.includeAllExports(true),
12877 includeDynamicImport: this.includeDynamicImport.bind(this),
12878 includeVariableInModule: this.includeVariableInModule.bind(this),
12879 magicString: this.magicString,
12880 module: this,
12881 moduleContext: this.context,
12882 options: this.options,
12883 requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
12884 traceExport: (name) => this.getVariableForExportName(name)[0],
12885 traceVariable: this.traceVariable.bind(this),
12886 usesTopLevelAwait: false,
12887 warn: this.warn.bind(this)
12888 };
12889 this.scope = new ModuleScope(this.graph.scope, this.astContext);
12890 this.namespace = new NamespaceVariable(this.astContext);
12891 this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
12892 this.info.ast = ast;
12893 timeEnd('analyse ast', 3);
12894 }
12895 toJSON() {
12896 return {
12897 ast: this.ast.esTreeNode,
12898 code: this.info.code,
12899 customTransformCache: this.customTransformCache,
12900 dependencies: Array.from(this.dependencies, getId),
12901 id: this.id,
12902 meta: this.info.meta,
12903 moduleSideEffects: this.info.moduleSideEffects,
12904 originalCode: this.originalCode,
12905 originalSourcemap: this.originalSourcemap,
12906 resolvedIds: this.resolvedIds,
12907 sourcemapChain: this.sourcemapChain,
12908 syntheticNamedExports: this.info.syntheticNamedExports,
12909 transformDependencies: this.transformDependencies,
12910 transformFiles: this.transformFiles
12911 };
12912 }
12913 traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
12914 const localVariable = this.scope.variables.get(name);
12915 if (localVariable) {
12916 return localVariable;
12917 }
12918 const importDeclaration = this.importDescriptions.get(name);
12919 if (importDeclaration) {
12920 const otherModule = importDeclaration.module;
12921 if (otherModule instanceof Module && importDeclaration.name === '*') {
12922 return otherModule.namespace;
12923 }
12924 const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
12925 if (!declaration) {
12926 return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
12927 }
12928 return declaration;
12929 }
12930 return null;
12931 }
12932 tryParse() {
12933 try {
12934 return this.graph.contextParse(this.info.code);
12935 }
12936 catch (err) {
12937 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
12938 if (this.id.endsWith('.json')) {
12939 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
12940 }
12941 else if (!this.id.endsWith('.js')) {
12942 message += ' (Note that you need plugins to import files that are not JavaScript)';
12943 }
12944 return this.error({
12945 code: 'PARSE_ERROR',
12946 message,
12947 parserError: err
12948 }, err.pos);
12949 }
12950 }
12951 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
12952 if (moduleSideEffects != null) {
12953 this.info.moduleSideEffects = moduleSideEffects;
12954 }
12955 if (syntheticNamedExports != null) {
12956 this.info.syntheticNamedExports = syntheticNamedExports;
12957 }
12958 if (meta != null) {
12959 Object.assign(this.info.meta, meta);
12960 }
12961 }
12962 warn(props, pos) {
12963 this.addLocationToLogProps(props, pos);
12964 this.options.onwarn(props);
12965 }
12966 addDynamicImport(node) {
12967 let argument = node.source;
12968 if (argument instanceof TemplateLiteral) {
12969 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
12970 argument = argument.quasis[0].value.cooked;
12971 }
12972 }
12973 else if (argument instanceof Literal && typeof argument.value === 'string') {
12974 argument = argument.value;
12975 }
12976 this.dynamicImports.push({ argument, id: null, node, resolution: null });
12977 }
12978 addExport(node) {
12979 if (node instanceof ExportDefaultDeclaration) {
12980 // export default foo;
12981 this.exports.set('default', {
12982 identifier: node.variable.getAssignedVariableName(),
12983 localName: 'default'
12984 });
12985 }
12986 else if (node instanceof ExportAllDeclaration) {
12987 const source = node.source.value;
12988 this.sources.add(source);
12989 if (node.exported) {
12990 // export * as name from './other'
12991 const name = node.exported.name;
12992 this.reexportDescriptions.set(name, {
12993 localName: '*',
12994 module: null,
12995 source,
12996 start: node.start
12997 });
12998 }
12999 else {
13000 // export * from './other'
13001 this.exportAllSources.add(source);
13002 }
13003 }
13004 else if (node.source instanceof Literal) {
13005 // export { name } from './other'
13006 const source = node.source.value;
13007 this.sources.add(source);
13008 for (const specifier of node.specifiers) {
13009 const name = specifier.exported.name;
13010 this.reexportDescriptions.set(name, {
13011 localName: specifier.local.name,
13012 module: null,
13013 source,
13014 start: specifier.start
13015 });
13016 }
13017 }
13018 else if (node.declaration) {
13019 const declaration = node.declaration;
13020 if (declaration instanceof VariableDeclaration) {
13021 // export var { foo, bar } = ...
13022 // export var foo = 1, bar = 2;
13023 for (const declarator of declaration.declarations) {
13024 for (const localName of extractAssignedNames(declarator.id)) {
13025 this.exports.set(localName, { identifier: null, localName });
13026 }
13027 }
13028 }
13029 else {
13030 // export function foo () {}
13031 const localName = declaration.id.name;
13032 this.exports.set(localName, { identifier: null, localName });
13033 }
13034 }
13035 else {
13036 // export { foo, bar, baz }
13037 for (const specifier of node.specifiers) {
13038 const localName = specifier.local.name;
13039 const exportedName = specifier.exported.name;
13040 this.exports.set(exportedName, { identifier: null, localName });
13041 }
13042 }
13043 }
13044 addImport(node) {
13045 const source = node.source.value;
13046 this.sources.add(source);
13047 for (const specifier of node.specifiers) {
13048 const isDefault = specifier.type === ImportDefaultSpecifier$1;
13049 const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
13050 const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
13051 this.importDescriptions.set(specifier.local.name, {
13052 module: null,
13053 name,
13054 source,
13055 start: specifier.start
13056 });
13057 }
13058 }
13059 addImportMeta(node) {
13060 this.importMetas.push(node);
13061 }
13062 addLocationToLogProps(props, pos) {
13063 props.id = this.id;
13064 props.pos = pos;
13065 let code = this.info.code;
13066 const location = locate(code, pos, { offsetLine: 1 });
13067 if (location) {
13068 let { column, line } = location;
13069 try {
13070 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
13071 code = this.originalCode;
13072 }
13073 catch (err) {
13074 this.options.onwarn({
13075 code: 'SOURCEMAP_ERROR',
13076 id: this.id,
13077 loc: {
13078 column,
13079 file: this.id,
13080 line
13081 },
13082 message: `Error when using sourcemap for reporting an error: ${err.message}`,
13083 pos
13084 });
13085 }
13086 augmentCodeLocation(props, { column, line }, code, this.id);
13087 }
13088 }
13089 addModulesToImportDescriptions(importDescription) {
13090 for (const specifier of importDescription.values()) {
13091 const { id } = this.resolvedIds[specifier.source];
13092 specifier.module = this.graph.modulesById.get(id);
13093 }
13094 }
13095 addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
13096 const handledDependencies = new Set();
13097 const addSideEffectDependencies = (possibleDependencies) => {
13098 for (const dependency of possibleDependencies) {
13099 if (handledDependencies.has(dependency)) {
13100 continue;
13101 }
13102 handledDependencies.add(dependency);
13103 if (necessaryDependencies.has(dependency)) {
13104 relevantDependencies.add(dependency);
13105 continue;
13106 }
13107 if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
13108 continue;
13109 }
13110 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
13111 relevantDependencies.add(dependency);
13112 continue;
13113 }
13114 addSideEffectDependencies(dependency.dependencies);
13115 }
13116 };
13117 addSideEffectDependencies(this.dependencies);
13118 addSideEffectDependencies(alwaysCheckedDependencies);
13119 }
13120 getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
13121 let foundSyntheticDeclaration = null;
13122 const foundInternalDeclarations = new Map();
13123 const foundExternalDeclarations = new Set();
13124 for (const module of this.exportAllModules) {
13125 // Synthetic namespaces should not hide "regular" exports of the same name
13126 if (module.info.syntheticNamedExports === name) {
13127 continue;
13128 }
13129 const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
13130 // We are creating a copy to handle the case where the same binding is
13131 // imported through different namespace reexports gracefully
13132 copyNameToModulesMap(searchedNamesAndModules));
13133 if (module instanceof ExternalModule || indirectExternal) {
13134 foundExternalDeclarations.add(variable);
13135 }
13136 else if (variable instanceof SyntheticNamedExportVariable) {
13137 if (!foundSyntheticDeclaration) {
13138 foundSyntheticDeclaration = variable;
13139 }
13140 }
13141 else if (variable) {
13142 foundInternalDeclarations.set(variable, module);
13143 }
13144 }
13145 if (foundInternalDeclarations.size > 0) {
13146 const foundDeclarationList = [...foundInternalDeclarations];
13147 const usedDeclaration = foundDeclarationList[0][0];
13148 if (foundDeclarationList.length === 1) {
13149 return [usedDeclaration];
13150 }
13151 this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
13152 // TODO we are pretending it was not found while it should behave like "undefined"
13153 return [null];
13154 }
13155 if (foundExternalDeclarations.size > 0) {
13156 const foundDeclarationList = [...foundExternalDeclarations];
13157 const usedDeclaration = foundDeclarationList[0];
13158 if (foundDeclarationList.length > 1) {
13159 this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
13160 }
13161 return [usedDeclaration, true];
13162 }
13163 if (foundSyntheticDeclaration) {
13164 return [foundSyntheticDeclaration];
13165 }
13166 return [null];
13167 }
13168 includeAndGetAdditionalMergedNamespaces() {
13169 const externalNamespaces = new Set();
13170 const syntheticNamespaces = new Set();
13171 for (const module of [this, ...this.exportAllModules]) {
13172 if (module instanceof ExternalModule) {
13173 const [externalVariable] = module.getVariableForExportName('*');
13174 externalVariable.include();
13175 this.includedImports.add(externalVariable);
13176 externalNamespaces.add(externalVariable);
13177 }
13178 else if (module.info.syntheticNamedExports) {
13179 const syntheticNamespace = module.getSyntheticNamespace();
13180 syntheticNamespace.include();
13181 this.includedImports.add(syntheticNamespace);
13182 syntheticNamespaces.add(syntheticNamespace);
13183 }
13184 }
13185 return [...syntheticNamespaces, ...externalNamespaces];
13186 }
13187 includeDynamicImport(node) {
13188 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
13189 if (resolution instanceof Module) {
13190 resolution.includedDynamicImporters.push(this);
13191 resolution.includeAllExports(true);
13192 }
13193 }
13194 includeVariable(variable) {
13195 if (!variable.included) {
13196 variable.include();
13197 this.graph.needsTreeshakingPass = true;
13198 const variableModule = variable.module;
13199 if (variableModule instanceof Module) {
13200 if (!variableModule.isExecuted) {
13201 markModuleAndImpureDependenciesAsExecuted(variableModule);
13202 }
13203 if (variableModule !== this) {
13204 const sideEffectModules = getAndExtendSideEffectModules(variable, this);
13205 for (const module of sideEffectModules) {
13206 if (!module.isExecuted) {
13207 markModuleAndImpureDependenciesAsExecuted(module);
13208 }
13209 }
13210 }
13211 }
13212 }
13213 }
13214 includeVariableInModule(variable) {
13215 this.includeVariable(variable);
13216 const variableModule = variable.module;
13217 if (variableModule && variableModule !== this) {
13218 this.includedImports.add(variable);
13219 }
13220 }
13221 shimMissingExport(name) {
13222 this.options.onwarn({
13223 code: 'SHIMMED_EXPORT',
13224 exporter: relativeId(this.id),
13225 exportName: name,
13226 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
13227 });
13228 this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
13229 }
13230}
13231// if there is a cyclic import in the reexport chain, we should not
13232// import from the original module but from the cyclic module to not
13233// mess up execution order.
13234function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
13235 if (variable.module instanceof Module && variable.module !== reexporter) {
13236 const exporterCycles = variable.module.cycles;
13237 if (exporterCycles.size > 0) {
13238 const importerCycles = reexporter.cycles;
13239 for (const cycleSymbol of importerCycles) {
13240 if (exporterCycles.has(cycleSymbol)) {
13241 importer.alternativeReexportModules.set(variable, reexporter);
13242 break;
13243 }
13244 }
13245 }
13246 }
13247}
13248const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
13249 new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
13250
13251function removeJsExtension(name) {
13252 return name.endsWith('.js') ? name.slice(0, -3) : name;
13253}
13254
13255function getCompleteAmdId(options, chunkId) {
13256 if (options.autoId) {
13257 return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
13258 }
13259 return options.id || '';
13260}
13261
13262function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
13263 const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
13264 if (!namedExportsMode) {
13265 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
13266 }
13267 let exportBlock = '';
13268 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13269 if (reexports && namedExportsMode) {
13270 for (const specifier of reexports) {
13271 if (specifier.reexported !== '*') {
13272 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13273 if (exportBlock)
13274 exportBlock += n;
13275 if (specifier.imported !== '*' && specifier.needsLiveBinding) {
13276 const [left, right] = getDirectReturnFunction([], {
13277 functionReturn: true,
13278 lineBreakIndent: null,
13279 name: null
13280 });
13281 exportBlock +=
13282 `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
13283 `${t}enumerable:${_}true,${n}` +
13284 `${t}get:${_}${left}${importName}${right}${n}});`;
13285 }
13286 else {
13287 exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
13288 }
13289 }
13290 }
13291 }
13292 }
13293 for (const { exported, local } of exports) {
13294 const lhs = `exports${getPropertyAccess(exported)}`;
13295 const rhs = local;
13296 if (lhs !== rhs) {
13297 if (exportBlock)
13298 exportBlock += n;
13299 exportBlock += `${lhs}${_}=${_}${rhs};`;
13300 }
13301 }
13302 for (const { name, reexports } of dependencies) {
13303 if (reexports && namedExportsMode) {
13304 for (const specifier of reexports) {
13305 if (specifier.reexported === '*') {
13306 if (exportBlock)
13307 exportBlock += n;
13308 const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
13309 exportBlock +=
13310 cnst === 'var' && specifier.needsLiveBinding
13311 ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
13312 isAsync: false,
13313 name: null
13314 })}${copyPropertyIfNecessary});`
13315 : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
13316 }
13317 }
13318 }
13319 }
13320 if (exportBlock) {
13321 return `${n}${n}${exportBlock}`;
13322 }
13323 return '';
13324}
13325function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
13326 if (exports.length > 0) {
13327 return exports[0].local;
13328 }
13329 else {
13330 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13331 if (reexports) {
13332 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13333 }
13334 }
13335 }
13336}
13337function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
13338 if (imported === 'default') {
13339 if (!isChunk) {
13340 const moduleInterop = String(interop(moduleId));
13341 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
13342 ? defaultVariableName
13343 : moduleVariableName;
13344 return isDefaultAProperty(moduleInterop, externalLiveBindings)
13345 ? `${variableName}${getPropertyAccess('default')}`
13346 : variableName;
13347 }
13348 return depNamedExportsMode
13349 ? `${moduleVariableName}${getPropertyAccess('default')}`
13350 : moduleVariableName;
13351 }
13352 if (imported === '*') {
13353 return (isChunk
13354 ? !depNamedExportsMode
13355 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
13356 ? namespaceVariableName
13357 : moduleVariableName;
13358 }
13359 return `${moduleVariableName}${getPropertyAccess(imported)}`;
13360}
13361function getEsModuleValue(getObject) {
13362 return getObject([['value', 'true']], {
13363 lineBreakIndent: null
13364 });
13365}
13366function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
13367 if (hasNamedExports) {
13368 if (addEsModule) {
13369 if (addNamespaceToStringTag) {
13370 return `Object.defineProperties(exports,${_}${getObject([
13371 ['__esModule', getEsModuleValue(getObject)],
13372 [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
13373 ], {
13374 lineBreakIndent: null
13375 })});`;
13376 }
13377 return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
13378 }
13379 if (addNamespaceToStringTag) {
13380 return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
13381 }
13382 }
13383 return '';
13384}
13385const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
13386 if (needsLiveBinding) {
13387 const [left, right] = getDirectReturnFunction([], {
13388 functionReturn: true,
13389 lineBreakIndent: null,
13390 name: null
13391 });
13392 return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
13393 `${t}${t}enumerable:${_}true,${n}` +
13394 `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
13395 }
13396 return `exports[k]${_}=${_}${name}[k]`;
13397};
13398
13399function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
13400 const { _, cnst, n } = snippets;
13401 const neededInteropHelpers = new Set();
13402 const interopStatements = [];
13403 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
13404 neededInteropHelpers.add(helper);
13405 interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
13406 };
13407 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13408 if (isChunk) {
13409 for (const { imported, reexported } of [
13410 ...(imports || []),
13411 ...(reexports || [])
13412 ]) {
13413 if (imported === '*' && reexported !== '*') {
13414 if (!namedExportsMode) {
13415 addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
13416 }
13417 break;
13418 }
13419 }
13420 }
13421 else {
13422 const moduleInterop = String(interop(id));
13423 let hasDefault = false;
13424 let hasNamespace = false;
13425 for (const { imported, reexported } of [
13426 ...(imports || []),
13427 ...(reexports || [])
13428 ]) {
13429 let helper;
13430 let variableName;
13431 if (imported === 'default') {
13432 if (!hasDefault) {
13433 hasDefault = true;
13434 if (defaultVariableName !== namespaceVariableName) {
13435 variableName = defaultVariableName;
13436 helper = defaultInteropHelpersByInteropType[moduleInterop];
13437 }
13438 }
13439 }
13440 else if (imported === '*' && reexported !== '*') {
13441 if (!hasNamespace) {
13442 hasNamespace = true;
13443 helper = namespaceInteropHelpersByInteropType[moduleInterop];
13444 variableName = namespaceVariableName;
13445 }
13446 }
13447 if (helper) {
13448 addInteropStatement(variableName, helper, name);
13449 }
13450 }
13451 }
13452 }
13453 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
13454}
13455
13456function addJsExtension(name) {
13457 return name.endsWith('.js') ? name : name + '.js';
13458}
13459
13460// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
13461// The assumption is that this makes sense for all relative ids:
13462// https://requirejs.org/docs/api.html#jsfiles
13463function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
13464 if (id[0] !== '.') {
13465 return id;
13466 }
13467 return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
13468}
13469
13470const builtins = {
13471 assert: true,
13472 buffer: true,
13473 console: true,
13474 constants: true,
13475 domain: true,
13476 events: true,
13477 http: true,
13478 https: true,
13479 os: true,
13480 path: true,
13481 process: true,
13482 punycode: true,
13483 querystring: true,
13484 stream: true,
13485 string_decoder: true,
13486 timers: true,
13487 tty: true,
13488 url: true,
13489 util: true,
13490 vm: true,
13491 zlib: true
13492};
13493function warnOnBuiltins(warn, dependencies) {
13494 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
13495 if (!externalBuiltins.length)
13496 return;
13497 warn({
13498 code: 'MISSING_NODE_BUILTINS',
13499 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`,
13500 modules: externalBuiltins
13501 });
13502}
13503
13504function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13505 warnOnBuiltins(warn, dependencies);
13506 const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
13507 const args = dependencies.map(m => m.name);
13508 const { n, getNonArrowFunctionIntro, _ } = snippets;
13509 if (namedExportsMode && hasExports) {
13510 args.unshift(`exports`);
13511 deps.unshift(`'exports'`);
13512 }
13513 if (accessedGlobals.has('require')) {
13514 args.unshift('require');
13515 deps.unshift(`'require'`);
13516 }
13517 if (accessedGlobals.has('module')) {
13518 args.unshift('module');
13519 deps.unshift(`'module'`);
13520 }
13521 const completeAmdId = getCompleteAmdId(amd, id);
13522 const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13523 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
13524 const useStrict = strict ? `${_}'use strict';` : '';
13525 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
13526 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13527 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13528 if (namespaceMarkers) {
13529 namespaceMarkers = n + n + namespaceMarkers;
13530 }
13531 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13532 return (magicString
13533 .indent(t)
13534 // factory function should be wrapped by parentheses to avoid lazy parsing,
13535 // cf. https://v8.dev/blog/preparser#pife
13536 .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
13537 isAsync: false,
13538 name: null
13539 })}{${useStrict}${n}${n}`)
13540 .append(`${n}${n}}));`));
13541}
13542
13543function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13544 const { _, n } = snippets;
13545 const useStrict = strict ? `'use strict';${n}${n}` : '';
13546 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
13547 if (namespaceMarkers) {
13548 namespaceMarkers += n + n;
13549 }
13550 const importBlock = getImportBlock$1(dependencies, snippets, compact);
13551 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13552 magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
13553 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
13554 return magicString.append(`${exportBlock}${outro}`);
13555}
13556function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
13557 let importBlock = '';
13558 let definingVariable = false;
13559 for (const { id, name, reexports, imports } of dependencies) {
13560 if (!reexports && !imports) {
13561 if (importBlock) {
13562 importBlock += compact && !definingVariable ? ',' : `;${n}`;
13563 }
13564 definingVariable = false;
13565 importBlock += `require('${id}')`;
13566 }
13567 else {
13568 importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
13569 definingVariable = true;
13570 importBlock += `${name}${_}=${_}require('${id}')`;
13571 }
13572 }
13573 if (importBlock) {
13574 return `${importBlock};${n}${n}`;
13575 }
13576 return '';
13577}
13578
13579function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
13580 const { _, n } = snippets;
13581 const importBlock = getImportBlock(dependencies, _);
13582 if (importBlock.length > 0)
13583 intro += importBlock.join(n) + n + n;
13584 intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
13585 if (intro)
13586 magicString.prepend(intro);
13587 const exportBlock = getExportBlock(exports, snippets);
13588 if (exportBlock.length)
13589 magicString.append(n + n + exportBlock.join(n).trim());
13590 if (outro)
13591 magicString.append(outro);
13592 return magicString.trim();
13593}
13594function getImportBlock(dependencies, _) {
13595 const importBlock = [];
13596 for (const { id, reexports, imports, name } of dependencies) {
13597 if (!reexports && !imports) {
13598 importBlock.push(`import${_}'${id}';`);
13599 continue;
13600 }
13601 if (imports) {
13602 let defaultImport = null;
13603 let starImport = null;
13604 const importedNames = [];
13605 for (const specifier of imports) {
13606 if (specifier.imported === 'default') {
13607 defaultImport = specifier;
13608 }
13609 else if (specifier.imported === '*') {
13610 starImport = specifier;
13611 }
13612 else {
13613 importedNames.push(specifier);
13614 }
13615 }
13616 if (starImport) {
13617 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
13618 }
13619 if (defaultImport && importedNames.length === 0) {
13620 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
13621 }
13622 else if (importedNames.length > 0) {
13623 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
13624 .map(specifier => {
13625 if (specifier.imported === specifier.local) {
13626 return specifier.imported;
13627 }
13628 else {
13629 return `${specifier.imported} as ${specifier.local}`;
13630 }
13631 })
13632 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13633 }
13634 }
13635 if (reexports) {
13636 let starExport = null;
13637 const namespaceReexports = [];
13638 const namedReexports = [];
13639 for (const specifier of reexports) {
13640 if (specifier.reexported === '*') {
13641 starExport = specifier;
13642 }
13643 else if (specifier.imported === '*') {
13644 namespaceReexports.push(specifier);
13645 }
13646 else {
13647 namedReexports.push(specifier);
13648 }
13649 }
13650 if (starExport) {
13651 importBlock.push(`export${_}*${_}from${_}'${id}';`);
13652 }
13653 if (namespaceReexports.length > 0) {
13654 if (!imports ||
13655 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
13656 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
13657 }
13658 for (const specifier of namespaceReexports) {
13659 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
13660 }
13661 }
13662 if (namedReexports.length > 0) {
13663 importBlock.push(`export${_}{${_}${namedReexports
13664 .map(specifier => {
13665 if (specifier.imported === specifier.reexported) {
13666 return specifier.imported;
13667 }
13668 else {
13669 return `${specifier.imported} as ${specifier.reexported}`;
13670 }
13671 })
13672 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13673 }
13674 }
13675 }
13676 return importBlock;
13677}
13678function getExportBlock(exports, { _, cnst }) {
13679 const exportBlock = [];
13680 const exportDeclaration = [];
13681 for (const specifier of exports) {
13682 if (specifier.expression) {
13683 exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
13684 }
13685 exportDeclaration.push(specifier.exported === specifier.local
13686 ? specifier.local
13687 : `${specifier.local} as ${specifier.exported}`);
13688 }
13689 if (exportDeclaration.length) {
13690 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
13691 }
13692 return exportBlock;
13693}
13694
13695const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
13696
13697function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
13698 const parts = name.split('.');
13699 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13700 parts.pop();
13701 let propertyPath = root;
13702 return (parts
13703 .map(part => {
13704 propertyPath += getPropertyAccess(part);
13705 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
13706 })
13707 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
13708}
13709function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
13710 const parts = deepName.split('.');
13711 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13712 const last = parts.pop();
13713 let propertyPath = root;
13714 let deepAssignment = parts
13715 .map(part => {
13716 propertyPath += getPropertyAccess(part);
13717 return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
13718 })
13719 .concat(`${propertyPath}${getPropertyAccess(last)}`)
13720 .join(`,${_}`) + `${_}=${_}${assignment}`;
13721 if (parts.length > 0) {
13722 deepAssignment = `(${deepAssignment})`;
13723 }
13724 return deepAssignment;
13725}
13726
13727function trimEmptyImports(dependencies) {
13728 let i = dependencies.length;
13729 while (i--) {
13730 const { imports, reexports } = dependencies[i];
13731 if (imports || reexports) {
13732 return dependencies.slice(0, i + 1);
13733 }
13734 }
13735 return [];
13736}
13737
13738function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13739 const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
13740 const isNamespaced = name && name.includes('.');
13741 const useVariableAssignment = !extend && !isNamespaced;
13742 if (name && useVariableAssignment && !isLegal(name)) {
13743 return error({
13744 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
13745 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
13746 });
13747 }
13748 warnOnBuiltins(warn, dependencies);
13749 const external = trimEmptyImports(dependencies);
13750 const deps = external.map(dep => dep.globalName || 'null');
13751 const args = external.map(m => m.name);
13752 if (hasExports && !name) {
13753 warn({
13754 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13755 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
13756 });
13757 }
13758 if (namedExportsMode && hasExports) {
13759 if (extend) {
13760 deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
13761 args.unshift('exports');
13762 }
13763 else {
13764 deps.unshift('{}');
13765 args.unshift('exports');
13766 }
13767 }
13768 const useStrict = strict ? `${t}'use strict';${n}` : '';
13769 const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13770 magicString.prepend(`${intro}${interopBlock}`);
13771 let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
13772 isAsync: false,
13773 name: null
13774 })}{${n}${useStrict}${n}`;
13775 if (hasExports) {
13776 if (name && !(extend && namedExportsMode)) {
13777 wrapperIntro =
13778 (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
13779 `${_}=${_}${wrapperIntro}`;
13780 }
13781 if (isNamespaced) {
13782 wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
13783 }
13784 }
13785 let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
13786 if (hasExports && !extend && namedExportsMode) {
13787 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
13788 }
13789 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
13790 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
13791 if (namespaceMarkers) {
13792 namespaceMarkers = n + n + namespaceMarkers;
13793 }
13794 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13795 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
13796}
13797
13798function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
13799 const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
13800 const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
13801 const registeredName = name ? `'${name}',${_}` : '';
13802 const wrapperParams = accessedGlobals.has('module')
13803 ? ['exports', 'module']
13804 : hasExports
13805 ? ['exports']
13806 : [];
13807 // factory function should be wrapped by parentheses to avoid lazy parsing,
13808 // cf. https://v8.dev/blog/preparser#pife
13809 let wrapperStart = `System.register(${registeredName}[` +
13810 dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
13811 `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13812 getStarExcludesBlock(starExcludes, t, snippets) +
13813 getImportBindingsBlock(importBindings, t, snippets) +
13814 `${n}${t}return${_}{${setters.length
13815 ? `${n}${t}${t}setters:${_}[${setters
13816 .map(setter => setter
13817 ? `${getFunctionIntro(['module'], {
13818 isAsync: false,
13819 name: null
13820 })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
13821 : systemNullSetters
13822 ? `null`
13823 : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
13824 .join(`,${_}`)}],`
13825 : ''}${n}`;
13826 wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
13827 isAsync: usesTopLevelAwait,
13828 name: null
13829 })}{${n}${n}`;
13830 const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
13831 magicString.prepend(intro +
13832 getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
13833 getHoistedExportsBlock(exports, t, snippets));
13834 magicString.append(`${outro}${n}${n}` +
13835 getSyntheticExportsBlock(exports, t, snippets) +
13836 getMissingExportsBlock(exports, t, snippets));
13837 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
13838}
13839function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
13840 const importBindings = [];
13841 const setters = [];
13842 let starExcludes = null;
13843 for (const { imports, reexports } of dependencies) {
13844 const setter = [];
13845 if (imports) {
13846 for (const specifier of imports) {
13847 importBindings.push(specifier.local);
13848 if (specifier.imported === '*') {
13849 setter.push(`${specifier.local}${_}=${_}module;`);
13850 }
13851 else {
13852 setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
13853 }
13854 }
13855 }
13856 if (reexports) {
13857 const reexportedNames = [];
13858 let hasStarReexport = false;
13859 for (const { imported, reexported } of reexports) {
13860 if (reexported === '*') {
13861 hasStarReexport = true;
13862 }
13863 else {
13864 reexportedNames.push([
13865 reexported,
13866 imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
13867 ]);
13868 }
13869 }
13870 if (reexportedNames.length > 1 || hasStarReexport) {
13871 const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
13872 if (hasStarReexport) {
13873 if (!starExcludes) {
13874 starExcludes = getStarExcludes({ dependencies, exports });
13875 }
13876 setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
13877 }
13878 else {
13879 setter.push(`exports(${exportMapping});`);
13880 }
13881 }
13882 else {
13883 const [key, value] = reexportedNames[0];
13884 setter.push(`exports('${key}',${_}${value});`);
13885 }
13886 }
13887 setters.push(setter.join(`${n}${t}${t}${t}`));
13888 }
13889 return { importBindings, setters, starExcludes };
13890}
13891const getStarExcludes = ({ dependencies, exports }) => {
13892 const starExcludes = new Set(exports.map(expt => expt.exported));
13893 starExcludes.add('default');
13894 for (const { reexports } of dependencies) {
13895 if (reexports) {
13896 for (const reexport of reexports) {
13897 if (reexport.reexported !== '*')
13898 starExcludes.add(reexport.reexported);
13899 }
13900 }
13901 }
13902 return starExcludes;
13903};
13904const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
13905 ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
13906 : '';
13907const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
13908const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13909function getExportsBlock(exports, t, { _, n }) {
13910 if (exports.length === 0) {
13911 return '';
13912 }
13913 if (exports.length === 1) {
13914 return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
13915 }
13916 return (`exports({${n}` +
13917 exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
13918 `${n}});${n}${n}`);
13919}
13920const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13921 .filter(expt => expt.expression)
13922 .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
13923const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
13924 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
13925 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
13926
13927function globalProp(name, globalVar, getPropertyAccess) {
13928 if (!name)
13929 return 'null';
13930 return `${globalVar}${keypath(name, getPropertyAccess)}`;
13931}
13932function safeAccess(name, globalVar, { _, getPropertyAccess }) {
13933 let propertyPath = globalVar;
13934 return name
13935 .split('.')
13936 .map(part => (propertyPath += getPropertyAccess(part)))
13937 .join(`${_}&&${_}`);
13938}
13939function 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 }) {
13940 const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
13941 const factoryVar = compact ? 'f' : 'factory';
13942 const globalVar = compact ? 'g' : 'global';
13943 if (hasExports && !name) {
13944 return error({
13945 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13946 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
13947 });
13948 }
13949 warnOnBuiltins(warn, dependencies);
13950 const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.id, amd.forceJsExtensionForImports)}'`);
13951 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
13952 const trimmedImports = trimEmptyImports(dependencies);
13953 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
13954 const factoryParams = trimmedImports.map(m => m.name);
13955 if (namedExportsMode && (hasExports || noConflict)) {
13956 amdDeps.unshift(`'exports'`);
13957 cjsDeps.unshift(`exports`);
13958 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
13959 factoryParams.unshift('exports');
13960 }
13961 const completeAmdId = getCompleteAmdId(amd, id);
13962 const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13963 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
13964 const define = amd.define;
13965 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
13966 const useStrict = strict ? `${_}'use strict';${n}` : ``;
13967 let iifeExport;
13968 if (noConflict) {
13969 const noConflictExportsVar = compact ? 'e' : 'exports';
13970 let factory;
13971 if (!namedExportsMode && hasExports) {
13972 factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
13973 }
13974 else {
13975 const module = globalDeps.shift();
13976 factory =
13977 `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
13978 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
13979 }
13980 iifeExport =
13981 `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
13982 `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
13983 `${t}${t}${factory}${n}` +
13984 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
13985 isAsync: false,
13986 name: null
13987 })}{${_}` +
13988 `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
13989 `${t}})()`;
13990 }
13991 else {
13992 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
13993 if (!namedExportsMode && hasExports) {
13994 iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
13995 }
13996 }
13997 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
13998 const wrapperParams = [factoryVar];
13999 if (iifeNeedsGlobal) {
14000 wrapperParams.unshift(globalVar);
14001 }
14002 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
14003 const iifeStart = iifeNeedsGlobal
14004 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
14005 : '';
14006 const iifeEnd = iifeNeedsGlobal ? ')' : '';
14007 const cjsIntro = iifeNeedsGlobal
14008 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
14009 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
14010 : '';
14011 const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
14012 cjsIntro +
14013 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
14014 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
14015 // factory function should be wrapped by parentheses to avoid lazy parsing,
14016 // cf. https://v8.dev/blog/preparser#pife
14017 `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
14018 isAsync: false,
14019 name: null
14020 })}{${useStrict}${n}`;
14021 const wrapperOutro = n + n + '}));';
14022 magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
14023 const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
14024 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
14025 if (namespaceMarkers) {
14026 namespaceMarkers = n + n + namespaceMarkers;
14027 }
14028 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
14029 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
14030}
14031
14032const finalisers = { amd, cjs, es, iife, system, umd };
14033
14034class Source {
14035 constructor(filename, content) {
14036 this.isOriginal = true;
14037 this.filename = filename;
14038 this.content = content;
14039 }
14040 traceSegment(line, column, name) {
14041 return { column, line, name, source: this };
14042 }
14043}
14044class Link {
14045 constructor(map, sources) {
14046 this.sources = sources;
14047 this.names = map.names;
14048 this.mappings = map.mappings;
14049 }
14050 traceMappings() {
14051 const sources = [];
14052 const sourceIndexMap = new Map();
14053 const sourcesContent = [];
14054 const names = [];
14055 const nameIndexMap = new Map();
14056 const mappings = [];
14057 for (const line of this.mappings) {
14058 const tracedLine = [];
14059 for (const segment of line) {
14060 if (segment.length === 1)
14061 continue;
14062 const source = this.sources[segment[1]];
14063 if (!source)
14064 continue;
14065 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
14066 if (traced) {
14067 const { column, line, name, source: { content, filename } } = traced;
14068 let sourceIndex = sourceIndexMap.get(filename);
14069 if (sourceIndex === undefined) {
14070 sourceIndex = sources.length;
14071 sources.push(filename);
14072 sourceIndexMap.set(filename, sourceIndex);
14073 sourcesContent[sourceIndex] = content;
14074 }
14075 else if (sourcesContent[sourceIndex] == null) {
14076 sourcesContent[sourceIndex] = content;
14077 }
14078 else if (content != null && sourcesContent[sourceIndex] !== content) {
14079 return error({
14080 message: `Multiple conflicting contents for sourcemap source ${filename}`
14081 });
14082 }
14083 const tracedSegment = [segment[0], sourceIndex, line, column];
14084 if (name) {
14085 let nameIndex = nameIndexMap.get(name);
14086 if (nameIndex === undefined) {
14087 nameIndex = names.length;
14088 names.push(name);
14089 nameIndexMap.set(name, nameIndex);
14090 }
14091 tracedSegment[4] = nameIndex;
14092 }
14093 tracedLine.push(tracedSegment);
14094 }
14095 }
14096 mappings.push(tracedLine);
14097 }
14098 return { mappings, names, sources, sourcesContent };
14099 }
14100 traceSegment(line, column, name) {
14101 const segments = this.mappings[line];
14102 if (!segments)
14103 return null;
14104 // binary search through segments for the given column
14105 let searchStart = 0;
14106 let searchEnd = segments.length - 1;
14107 while (searchStart <= searchEnd) {
14108 const m = (searchStart + searchEnd) >> 1;
14109 const segment = segments[m];
14110 // If a sourcemap does not have sufficient resolution to contain a
14111 // necessary mapping, e.g. because it only contains line information, we
14112 // use the best approximation we could find
14113 if (segment[0] === column || searchStart === searchEnd) {
14114 if (segment.length == 1)
14115 return null;
14116 const source = this.sources[segment[1]];
14117 if (!source)
14118 return null;
14119 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
14120 }
14121 if (segment[0] > column) {
14122 searchEnd = m - 1;
14123 }
14124 else {
14125 searchStart = m + 1;
14126 }
14127 }
14128 return null;
14129 }
14130}
14131function getLinkMap(warn) {
14132 return function linkMap(source, map) {
14133 if (map.mappings) {
14134 return new Link(map, [source]);
14135 }
14136 warn({
14137 code: 'SOURCEMAP_BROKEN',
14138 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
14139 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
14140 'documentation for help',
14141 plugin: map.plugin,
14142 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
14143 });
14144 return new Link({
14145 mappings: [],
14146 names: []
14147 }, [source]);
14148 };
14149}
14150function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
14151 let source;
14152 if (!originalSourcemap) {
14153 source = new Source(id, originalCode);
14154 }
14155 else {
14156 const sources = originalSourcemap.sources;
14157 const sourcesContent = originalSourcemap.sourcesContent || [];
14158 const directory = require$$0.dirname(id) || '.';
14159 const sourceRoot = originalSourcemap.sourceRoot || '.';
14160 const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
14161 source = new Link(originalSourcemap, baseSources);
14162 }
14163 return sourcemapChain.reduce(linkMap, source);
14164}
14165function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
14166 const linkMap = getLinkMap(warn);
14167 const moduleSources = modules
14168 .filter(module => !module.excludeFromSourcemap)
14169 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
14170 const link = new Link(map, moduleSources);
14171 const source = bundleSourcemapChain.reduce(linkMap, link);
14172 let { sources, sourcesContent, names, mappings } = source.traceMappings();
14173 if (file) {
14174 const directory = require$$0.dirname(file);
14175 sources = sources.map((source) => require$$0.relative(directory, source));
14176 file = require$$0.basename(file);
14177 }
14178 sourcesContent = (excludeContent ? null : sourcesContent);
14179 return new SourceMap({ file, mappings, names, sources, sourcesContent });
14180}
14181function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
14182 if (!sourcemapChain.length) {
14183 return originalSourcemap;
14184 }
14185 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
14186 const map = source.traceMappings();
14187 return { version: 3, ...map };
14188}
14189
14190const createHash = () => crypto.createHash('sha256');
14191
14192const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14193 amd: deconflictImportsOther,
14194 cjs: deconflictImportsOther,
14195 es: deconflictImportsEsmOrSystem,
14196 iife: deconflictImportsOther,
14197 system: deconflictImportsEsmOrSystem,
14198 umd: deconflictImportsOther
14199};
14200function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14201 const reversedModules = modules.slice().reverse();
14202 for (const module of reversedModules) {
14203 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14204 }
14205 deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
14206 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
14207 for (const module of reversedModules) {
14208 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
14209 }
14210}
14211function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
14212 // This is needed for namespace reexports
14213 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
14214 if (preserveModules || dependency instanceof ExternalModule) {
14215 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
14216 }
14217 }
14218 for (const variable of imports) {
14219 const module = variable.module;
14220 const name = variable.name;
14221 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
14222 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
14223 }
14224 else if (module instanceof ExternalModule && name === 'default') {
14225 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
14226 ? module.suggestedVariableName + '__default'
14227 : module.suggestedVariableName, usedNames));
14228 }
14229 else {
14230 variable.setRenderNames(null, getSafeName(name, usedNames));
14231 }
14232 }
14233 for (const variable of syntheticExports) {
14234 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14235 }
14236}
14237function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
14238 for (const chunkOrExternalModule of dependencies) {
14239 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
14240 }
14241 for (const externalModuleOrChunk of deconflictedNamespace) {
14242 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
14243 }
14244 for (const externalModule of deconflictedDefault) {
14245 if (deconflictedNamespace.has(externalModule) &&
14246 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
14247 externalModule.defaultVariableName = externalModule.namespaceVariableName;
14248 }
14249 else {
14250 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
14251 }
14252 }
14253 for (const variable of imports) {
14254 const module = variable.module;
14255 if (module instanceof ExternalModule) {
14256 const name = variable.name;
14257 if (name === 'default') {
14258 const moduleInterop = String(interop(module.id));
14259 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
14260 ? module.defaultVariableName
14261 : module.variableName;
14262 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
14263 variable.setRenderNames(variableName, 'default');
14264 }
14265 else {
14266 variable.setRenderNames(null, variableName);
14267 }
14268 }
14269 else if (name === '*') {
14270 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
14271 ? module.namespaceVariableName
14272 : module.variableName);
14273 }
14274 else {
14275 // if the second parameter is `null`, it uses its "name" for the property name
14276 variable.setRenderNames(module.variableName, null);
14277 }
14278 }
14279 else {
14280 const chunk = chunkByModule.get(module);
14281 if (preserveModules && variable.isNamespace) {
14282 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
14283 }
14284 else if (chunk.exportMode === 'default') {
14285 variable.setRenderNames(null, chunk.variableName);
14286 }
14287 else {
14288 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
14289 }
14290 }
14291 }
14292}
14293function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
14294 for (const module of modules) {
14295 for (const variable of module.scope.variables.values()) {
14296 if (variable.included &&
14297 // this will only happen for exports in some formats
14298 !(variable.renderBaseName ||
14299 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
14300 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14301 }
14302 }
14303 if (includedNamespaces.has(module)) {
14304 const namespace = module.namespace;
14305 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
14306 }
14307 }
14308}
14309
14310const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
14311const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
14312const backSlashRegEx = /\\/g;
14313function escapeId(id) {
14314 if (!id.match(needsEscapeRegEx))
14315 return id;
14316 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
14317}
14318
14319function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
14320 let nameIndex = 0;
14321 for (const variable of exports) {
14322 let [exportName] = variable.name;
14323 if (exportsByName.has(exportName)) {
14324 do {
14325 exportName = toBase64(++nameIndex);
14326 // skip past leading number identifiers
14327 if (exportName.charCodeAt(0) === 49 /* '1' */) {
14328 nameIndex += 9 * 64 ** (exportName.length - 1);
14329 exportName = toBase64(nameIndex);
14330 }
14331 } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
14332 }
14333 exportsByName.set(exportName, variable);
14334 exportNamesByVariable.set(variable, [exportName]);
14335 }
14336}
14337function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
14338 for (const variable of exports) {
14339 let nameIndex = 0;
14340 let exportName = variable.name;
14341 while (exportsByName.has(exportName)) {
14342 exportName = variable.name + '$' + ++nameIndex;
14343 }
14344 exportsByName.set(exportName, variable);
14345 exportNamesByVariable.set(variable, [exportName]);
14346 }
14347}
14348
14349function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
14350 const exportKeys = chunk.getExportNames();
14351 if (exportMode === 'default') {
14352 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
14353 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
14354 }
14355 }
14356 else if (exportMode === 'none' && exportKeys.length) {
14357 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
14358 }
14359 if (exportMode === 'auto') {
14360 if (exportKeys.length === 0) {
14361 exportMode = 'none';
14362 }
14363 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
14364 if (format === 'cjs' && unsetOptions.has('exports')) {
14365 warn(errPreferNamedExports(facadeModuleId));
14366 }
14367 exportMode = 'default';
14368 }
14369 else {
14370 if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
14371 warn(errMixedExport(facadeModuleId, name));
14372 }
14373 exportMode = 'named';
14374 }
14375 }
14376 return exportMode;
14377}
14378
14379function guessIndentString(code) {
14380 const lines = code.split('\n');
14381 const tabbed = lines.filter(line => /^\t+/.test(line));
14382 const spaced = lines.filter(line => /^ {2,}/.test(line));
14383 if (tabbed.length === 0 && spaced.length === 0) {
14384 return null;
14385 }
14386 // More lines tabbed than spaced? Assume tabs, and
14387 // default to tabs in the case of a tie (or nothing
14388 // to go on)
14389 if (tabbed.length >= spaced.length) {
14390 return '\t';
14391 }
14392 // Otherwise, we need to guess the multiple
14393 const min = spaced.reduce((previous, current) => {
14394 const numSpaces = /^ +/.exec(current)[0].length;
14395 return Math.min(numSpaces, previous);
14396 }, Infinity);
14397 return new Array(min + 1).join(' ');
14398}
14399function getIndentString(modules, options) {
14400 if (options.indent !== true)
14401 return options.indent;
14402 for (const module of modules) {
14403 const indent = guessIndentString(module.originalCode);
14404 if (indent !== null)
14405 return indent;
14406 }
14407 return '\t';
14408}
14409
14410function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14411 const staticDependencyBlocks = [];
14412 const handledDependencies = new Set();
14413 for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
14414 const module = orderedModules[modulePos];
14415 if (!handledDependencies.has(module)) {
14416 const staticDependencies = [];
14417 addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
14418 staticDependencyBlocks.unshift(staticDependencies);
14419 }
14420 }
14421 const dependencies = new Set();
14422 for (const block of staticDependencyBlocks) {
14423 for (const dependency of block) {
14424 dependencies.add(dependency);
14425 }
14426 }
14427 return dependencies;
14428}
14429function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
14430 const dependencies = module.getDependenciesToBeIncluded();
14431 for (const dependency of dependencies) {
14432 if (dependency instanceof ExternalModule) {
14433 staticDependencies.push(dependency);
14434 continue;
14435 }
14436 const dependencyChunk = chunkByModule.get(dependency);
14437 if (dependencyChunk !== chunk) {
14438 staticDependencies.push(dependencyChunk);
14439 continue;
14440 }
14441 if (!handledModules.has(dependency)) {
14442 handledModules.add(dependency);
14443 addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
14444 }
14445 }
14446}
14447
14448function decodedSourcemap(map) {
14449 if (!map)
14450 return null;
14451 if (typeof map === 'string') {
14452 map = JSON.parse(map);
14453 }
14454 if (map.mappings === '') {
14455 return {
14456 mappings: [],
14457 names: [],
14458 sources: [],
14459 version: 3
14460 };
14461 }
14462 const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
14463 return { ...map, mappings };
14464}
14465
14466function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
14467 const renderChunkReducer = (code, result, plugin) => {
14468 if (result == null)
14469 return code;
14470 if (typeof result === 'string')
14471 result = {
14472 code: result,
14473 map: undefined
14474 };
14475 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14476 if (result.map !== null) {
14477 const map = decodedSourcemap(result.map);
14478 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14479 }
14480 return result.code;
14481 };
14482 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
14483}
14484
14485const lowercaseBundleKeys = Symbol('bundleKeys');
14486const FILE_PLACEHOLDER = {
14487 type: 'placeholder'
14488};
14489const getOutputBundle = (outputBundleBase) => {
14490 const reservedLowercaseBundleKeys = new Set();
14491 return new Proxy(outputBundleBase, {
14492 deleteProperty(target, key) {
14493 if (typeof key === 'string') {
14494 reservedLowercaseBundleKeys.delete(key.toLowerCase());
14495 }
14496 return Reflect.deleteProperty(target, key);
14497 },
14498 get(target, key) {
14499 if (key === lowercaseBundleKeys) {
14500 return reservedLowercaseBundleKeys;
14501 }
14502 return Reflect.get(target, key);
14503 },
14504 set(target, key, value) {
14505 if (typeof key === 'string') {
14506 reservedLowercaseBundleKeys.add(key.toLowerCase());
14507 }
14508 return Reflect.set(target, key, value);
14509 }
14510 });
14511};
14512
14513function renderNamePattern(pattern, patternName, replacements) {
14514 if (isPathFragment(pattern))
14515 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
14516 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14517 if (!replacements.hasOwnProperty(type)) {
14518 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14519 }
14520 const replacement = replacements[type]();
14521 if (isPathFragment(replacement))
14522 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14523 return replacement;
14524 });
14525}
14526function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
14527 if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
14528 return name;
14529 const ext = require$$0.extname(name);
14530 name = name.substring(0, name.length - ext.length);
14531 let uniqueName, uniqueIndex = 1;
14532 while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14533 ;
14534 return uniqueName;
14535}
14536
14537const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
14538function getGlobalName(module, globals, hasExports, warn) {
14539 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
14540 if (globalName) {
14541 return globalName;
14542 }
14543 if (hasExports) {
14544 warn({
14545 code: 'MISSING_GLOBAL_NAME',
14546 guess: module.variableName,
14547 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14548 source: module.id
14549 });
14550 return module.variableName;
14551 }
14552}
14553class Chunk {
14554 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
14555 this.orderedModules = orderedModules;
14556 this.inputOptions = inputOptions;
14557 this.outputOptions = outputOptions;
14558 this.unsetOptions = unsetOptions;
14559 this.pluginDriver = pluginDriver;
14560 this.modulesById = modulesById;
14561 this.chunkByModule = chunkByModule;
14562 this.facadeChunkByModule = facadeChunkByModule;
14563 this.includedNamespaces = includedNamespaces;
14564 this.manualChunkAlias = manualChunkAlias;
14565 this.entryModules = [];
14566 this.exportMode = 'named';
14567 this.facadeModule = null;
14568 this.id = null;
14569 this.namespaceVariableName = '';
14570 this.needsExportsShim = false;
14571 this.variableName = '';
14572 this.accessedGlobalsByScope = new Map();
14573 this.dependencies = new Set();
14574 this.dynamicDependencies = new Set();
14575 this.dynamicEntryModules = [];
14576 this.dynamicName = null;
14577 this.exportNamesByVariable = new Map();
14578 this.exports = new Set();
14579 this.exportsByName = new Map();
14580 this.fileName = null;
14581 this.implicitEntryModules = [];
14582 this.implicitlyLoadedBefore = new Set();
14583 this.imports = new Set();
14584 this.includedReexportsByModule = new Map();
14585 this.indentString = undefined;
14586 // This may only be updated in the constructor
14587 this.isEmpty = true;
14588 this.name = null;
14589 this.renderedDependencies = null;
14590 this.renderedExports = null;
14591 this.renderedHash = undefined;
14592 this.renderedModuleSources = new Map();
14593 this.renderedModules = Object.create(null);
14594 this.renderedSource = null;
14595 this.sortedExportNames = null;
14596 this.strictFacade = false;
14597 this.usedModules = undefined;
14598 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14599 const chunkModules = new Set(orderedModules);
14600 for (const module of orderedModules) {
14601 if (module.namespace.included) {
14602 includedNamespaces.add(module);
14603 }
14604 if (this.isEmpty && module.isIncluded()) {
14605 this.isEmpty = false;
14606 }
14607 if (module.info.isEntry || outputOptions.preserveModules) {
14608 this.entryModules.push(module);
14609 }
14610 for (const importer of module.includedDynamicImporters) {
14611 if (!chunkModules.has(importer)) {
14612 this.dynamicEntryModules.push(module);
14613 // Modules with synthetic exports need an artificial namespace for dynamic imports
14614 if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
14615 includedNamespaces.add(module);
14616 this.exports.add(module.namespace);
14617 }
14618 }
14619 }
14620 if (module.implicitlyLoadedAfter.size > 0) {
14621 this.implicitEntryModules.push(module);
14622 }
14623 }
14624 this.suggestedVariableName = makeLegal(this.generateVariableName());
14625 }
14626 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
14627 const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
14628 chunk.assignFacadeName(facadeName, facadedModule);
14629 if (!facadeChunkByModule.has(facadedModule)) {
14630 facadeChunkByModule.set(facadedModule, chunk);
14631 }
14632 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
14633 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
14634 }
14635 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
14636 facadedModule.info.moduleSideEffects &&
14637 facadedModule.hasEffects()) {
14638 chunk.dependencies.add(chunkByModule.get(facadedModule));
14639 }
14640 chunk.ensureReexportsAreAvailableForModule(facadedModule);
14641 chunk.facadeModule = facadedModule;
14642 chunk.strictFacade = true;
14643 return chunk;
14644 }
14645 canModuleBeFacade(module, exposedVariables) {
14646 const moduleExportNamesByVariable = module.getExportNamesByVariable();
14647 for (const exposedVariable of this.exports) {
14648 if (!moduleExportNamesByVariable.has(exposedVariable)) {
14649 if (moduleExportNamesByVariable.size === 0 &&
14650 module.isUserDefinedEntryPoint &&
14651 module.preserveSignature === 'strict' &&
14652 this.unsetOptions.has('preserveEntrySignatures')) {
14653 this.inputOptions.onwarn({
14654 code: 'EMPTY_FACADE',
14655 id: module.id,
14656 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.`,
14657 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
14658 });
14659 }
14660 return false;
14661 }
14662 }
14663 for (const exposedVariable of exposedVariables) {
14664 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
14665 return false;
14666 }
14667 }
14668 return true;
14669 }
14670 generateExports() {
14671 this.sortedExportNames = null;
14672 const remainingExports = new Set(this.exports);
14673 if (this.facadeModule !== null &&
14674 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
14675 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
14676 for (const [variable, exportNames] of exportNamesByVariable) {
14677 this.exportNamesByVariable.set(variable, [...exportNames]);
14678 for (const exportName of exportNames) {
14679 this.exportsByName.set(exportName, variable);
14680 }
14681 remainingExports.delete(variable);
14682 }
14683 }
14684 if (this.outputOptions.minifyInternalExports) {
14685 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14686 }
14687 else {
14688 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
14689 }
14690 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
14691 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
14692 }
14693 generateFacades() {
14694 var _a;
14695 const facades = [];
14696 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
14697 const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
14698 for (const module of entryModules) {
14699 if (module.preserveSignature) {
14700 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
14701 exposedVariables.add(exportedVariable);
14702 }
14703 }
14704 }
14705 for (const module of entryModules) {
14706 const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
14707 // mapping must run after Set 'name' dedupe
14708 name => ({
14709 name
14710 }));
14711 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
14712 requiredFacades.push({});
14713 }
14714 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
14715 if (requiredFacades.length === 0) {
14716 requiredFacades.push({});
14717 }
14718 if (!this.facadeModule) {
14719 const needsStrictFacade = module.preserveSignature === 'strict' ||
14720 (module.preserveSignature === 'exports-only' &&
14721 module.getExportNamesByVariable().size !== 0);
14722 if (!needsStrictFacade ||
14723 this.outputOptions.preserveModules ||
14724 this.canModuleBeFacade(module, exposedVariables)) {
14725 this.facadeModule = module;
14726 this.facadeChunkByModule.set(module, this);
14727 if (module.preserveSignature) {
14728 this.strictFacade = needsStrictFacade;
14729 }
14730 this.assignFacadeName(requiredFacades.shift(), module);
14731 }
14732 }
14733 for (const facadeName of requiredFacades) {
14734 facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
14735 }
14736 }
14737 for (const module of this.dynamicEntryModules) {
14738 if (module.info.syntheticNamedExports)
14739 continue;
14740 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
14741 this.facadeModule = module;
14742 this.facadeChunkByModule.set(module, this);
14743 this.strictFacade = true;
14744 this.dynamicName = getChunkNameFromModule(module);
14745 }
14746 else if (this.facadeModule === module &&
14747 !this.strictFacade &&
14748 this.canModuleBeFacade(module, exposedVariables)) {
14749 this.strictFacade = true;
14750 }
14751 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
14752 this.includedNamespaces.add(module);
14753 this.exports.add(module.namespace);
14754 }
14755 }
14756 if (!this.outputOptions.preserveModules) {
14757 this.addNecessaryImportsForFacades();
14758 }
14759 return facades;
14760 }
14761 generateId(addons, options, bundle, includeHash) {
14762 if (this.fileName !== null) {
14763 return this.fileName;
14764 }
14765 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14766 ? [options.entryFileNames, 'output.entryFileNames']
14767 : [options.chunkFileNames, 'output.chunkFileNames'];
14768 return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
14769 format: () => options.format,
14770 hash: () => includeHash
14771 ? this.computeContentHashWithDependencies(addons, options, bundle)
14772 : '[hash]',
14773 name: () => this.getChunkName()
14774 }), bundle);
14775 }
14776 generateIdPreserveModules(preserveModulesRelativeDir, options, bundle, unsetOptions) {
14777 const [{ id }] = this.orderedModules;
14778 const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14779 let path;
14780 const patternOpt = unsetOptions.has('entryFileNames')
14781 ? '[name][assetExtname].js'
14782 : options.entryFileNames;
14783 const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
14784 if (isAbsolute(sanitizedId)) {
14785 const currentDir = require$$0.dirname(sanitizedId);
14786 const extension = require$$0.extname(sanitizedId);
14787 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14788 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14789 ext: () => extension.substring(1),
14790 extname: () => extension,
14791 format: () => options.format,
14792 name: () => this.getChunkName()
14793 });
14794 const currentPath = `${currentDir}/${fileName}`;
14795 const { preserveModulesRoot } = options;
14796 if (preserveModulesRoot && require$$0.resolve(currentPath).startsWith(preserveModulesRoot)) {
14797 path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14798 }
14799 else {
14800 path = relative(preserveModulesRelativeDir, currentPath);
14801 }
14802 }
14803 else {
14804 const extension = require$$0.extname(sanitizedId);
14805 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14806 assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14807 ext: () => extension.substring(1),
14808 extname: () => extension,
14809 format: () => options.format,
14810 name: () => getAliasName(sanitizedId)
14811 });
14812 path = `_virtual/${fileName}`;
14813 }
14814 return makeUnique(normalize(path), bundle);
14815 }
14816 getChunkInfo() {
14817 const facadeModule = this.facadeModule;
14818 const getChunkName = this.getChunkName.bind(this);
14819 return {
14820 exports: this.getExportNames(),
14821 facadeModuleId: facadeModule && facadeModule.id,
14822 isDynamicEntry: this.dynamicEntryModules.length > 0,
14823 isEntry: facadeModule !== null && facadeModule.info.isEntry,
14824 isImplicitEntry: this.implicitEntryModules.length > 0,
14825 modules: this.renderedModules,
14826 get name() {
14827 return getChunkName();
14828 },
14829 type: 'chunk'
14830 };
14831 }
14832 getChunkInfoWithFileNames() {
14833 return Object.assign(this.getChunkInfo(), {
14834 code: undefined,
14835 dynamicImports: Array.from(this.dynamicDependencies, getId),
14836 fileName: this.id,
14837 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
14838 importedBindings: this.getImportedBindingsPerDependency(),
14839 imports: Array.from(this.dependencies, getId),
14840 map: undefined,
14841 referencedFiles: this.getReferencedFiles()
14842 });
14843 }
14844 getChunkName() {
14845 var _a;
14846 return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
14847 }
14848 getExportNames() {
14849 var _a;
14850 return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14851 }
14852 getRenderedHash() {
14853 if (this.renderedHash)
14854 return this.renderedHash;
14855 const hash = createHash();
14856 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
14857 if (pluginHash) {
14858 augmentation += pluginHash;
14859 }
14860 return augmentation;
14861 });
14862 hash.update(hashAugmentation);
14863 hash.update(this.renderedSource.toString());
14864 hash.update(this.getExportNames()
14865 .map(exportName => {
14866 const variable = this.exportsByName.get(exportName);
14867 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14868 })
14869 .join(','));
14870 return (this.renderedHash = hash.digest('hex'));
14871 }
14872 getVariableExportName(variable) {
14873 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
14874 return '*';
14875 }
14876 return this.exportNamesByVariable.get(variable)[0];
14877 }
14878 link() {
14879 this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
14880 for (const module of this.orderedModules) {
14881 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
14882 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
14883 this.setUpChunkImportsAndExportsForModule(module);
14884 }
14885 }
14886 // prerender allows chunk hashes and names to be generated before finalizing
14887 preRender(options, inputBase, snippets) {
14888 const { _, getPropertyAccess, n } = snippets;
14889 const magicString = new Bundle$1({ separator: `${n}${n}` });
14890 this.usedModules = [];
14891 this.indentString = getIndentString(this.orderedModules, options);
14892 const renderOptions = {
14893 dynamicImportFunction: options.dynamicImportFunction,
14894 exportNamesByVariable: this.exportNamesByVariable,
14895 format: options.format,
14896 freeze: options.freeze,
14897 indent: this.indentString,
14898 namespaceToStringTag: options.namespaceToStringTag,
14899 outputPluginDriver: this.pluginDriver,
14900 snippets
14901 };
14902 // for static and dynamic entry points, inline the execution list to avoid loading latency
14903 if (options.hoistTransitiveImports &&
14904 !this.outputOptions.preserveModules &&
14905 this.facadeModule !== null) {
14906 for (const dep of this.dependencies) {
14907 if (dep instanceof Chunk)
14908 this.inlineChunkDependencies(dep);
14909 }
14910 }
14911 this.prepareModulesForRendering(snippets);
14912 this.setIdentifierRenderResolutions(options);
14913 let hoistedSource = '';
14914 const renderedModules = this.renderedModules;
14915 for (const module of this.orderedModules) {
14916 let renderedLength = 0;
14917 if (module.isIncluded() || this.includedNamespaces.has(module)) {
14918 const source = module.render(renderOptions).trim();
14919 renderedLength = source.length();
14920 if (renderedLength) {
14921 if (options.compact && source.lastLine().includes('//'))
14922 source.append('\n');
14923 this.renderedModuleSources.set(module, source);
14924 magicString.addSource(source);
14925 this.usedModules.push(module);
14926 }
14927 const namespace = module.namespace;
14928 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
14929 const rendered = namespace.renderBlock(renderOptions);
14930 if (namespace.renderFirst())
14931 hoistedSource += n + rendered;
14932 else
14933 magicString.addSource(new MagicString(rendered));
14934 }
14935 }
14936 const { renderedExports, removedExports } = module.getRenderedExports();
14937 const { renderedModuleSources } = this;
14938 renderedModules[module.id] = {
14939 get code() {
14940 var _a, _b;
14941 return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
14942 },
14943 originalLength: module.originalCode.length,
14944 removedExports,
14945 renderedExports,
14946 renderedLength
14947 };
14948 }
14949 if (hoistedSource)
14950 magicString.prepend(hoistedSource + n + n);
14951 if (this.needsExportsShim) {
14952 magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14953 }
14954 if (options.compact) {
14955 this.renderedSource = magicString;
14956 }
14957 else {
14958 this.renderedSource = magicString.trim();
14959 }
14960 this.renderedHash = undefined;
14961 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
14962 const chunkName = this.getChunkName();
14963 this.inputOptions.onwarn({
14964 chunkName,
14965 code: 'EMPTY_BUNDLE',
14966 message: `Generated an empty chunk: "${chunkName}"`
14967 });
14968 }
14969 this.setExternalRenderPaths(options, inputBase);
14970 this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
14971 this.renderedExports =
14972 this.exportMode === 'none'
14973 ? []
14974 : this.getChunkExportDeclarations(options.format, getPropertyAccess);
14975 }
14976 async render(options, addons, outputChunk, snippets) {
14977 timeStart('render format', 2);
14978 const format = options.format;
14979 const finalise = finalisers[format];
14980 if (options.dynamicImportFunction && format !== 'es') {
14981 this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
14982 }
14983 // populate ids in the rendered declarations only here
14984 // as chunk ids known only after prerender
14985 for (const dependency of this.dependencies) {
14986 const renderedDependency = this.renderedDependencies.get(dependency);
14987 if (dependency instanceof ExternalModule) {
14988 const originalId = dependency.renderPath;
14989 renderedDependency.id = escapeId(dependency.renormalizeRenderPath
14990 ? getImportPath(this.id, originalId, false, false)
14991 : originalId);
14992 }
14993 else {
14994 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
14995 renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
14996 }
14997 }
14998 this.finaliseDynamicImports(options, snippets);
14999 this.finaliseImportMetas(format, snippets);
15000 const hasExports = this.renderedExports.length !== 0 ||
15001 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
15002 let topLevelAwaitModule = null;
15003 const accessedGlobals = new Set();
15004 for (const module of this.orderedModules) {
15005 if (module.usesTopLevelAwait) {
15006 topLevelAwaitModule = module.id;
15007 }
15008 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
15009 if (accessedGlobalVariables) {
15010 for (const name of accessedGlobalVariables) {
15011 accessedGlobals.add(name);
15012 }
15013 }
15014 }
15015 if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
15016 return error({
15017 code: 'INVALID_TLA_FORMAT',
15018 id: topLevelAwaitModule,
15019 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
15020 });
15021 }
15022 /* istanbul ignore next */
15023 if (!this.id) {
15024 throw new Error('Internal Error: expecting chunk id');
15025 }
15026 const magicString = finalise(this.renderedSource, {
15027 accessedGlobals,
15028 dependencies: [...this.renderedDependencies.values()],
15029 exports: this.renderedExports,
15030 hasExports,
15031 id: this.id,
15032 indent: this.indentString,
15033 intro: addons.intro,
15034 isEntryFacade: this.outputOptions.preserveModules ||
15035 (this.facadeModule !== null && this.facadeModule.info.isEntry),
15036 isModuleFacade: this.facadeModule !== null,
15037 namedExportsMode: this.exportMode !== 'default',
15038 outro: addons.outro,
15039 snippets,
15040 usesTopLevelAwait: topLevelAwaitModule !== null,
15041 warn: this.inputOptions.onwarn
15042 }, options);
15043 if (addons.banner)
15044 magicString.prepend(addons.banner);
15045 if (addons.footer)
15046 magicString.append(addons.footer);
15047 const prevCode = magicString.toString();
15048 timeEnd('render format', 2);
15049 let map = null;
15050 const chunkSourcemapChain = [];
15051 let code = await renderChunk({
15052 code: prevCode,
15053 options,
15054 outputPluginDriver: this.pluginDriver,
15055 renderChunk: outputChunk,
15056 sourcemapChain: chunkSourcemapChain
15057 });
15058 if (options.sourcemap) {
15059 timeStart('sourcemap', 2);
15060 let file;
15061 if (options.file)
15062 file = require$$0.resolve(options.sourcemapFile || options.file);
15063 else if (options.dir)
15064 file = require$$0.resolve(options.dir, this.id);
15065 else
15066 file = require$$0.resolve(this.id);
15067 const decodedMap = magicString.generateDecodedMap({});
15068 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
15069 map.sources = map.sources
15070 .map(sourcePath => {
15071 const { sourcemapPathTransform } = options;
15072 if (sourcemapPathTransform) {
15073 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
15074 if (typeof newSourcePath !== 'string') {
15075 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
15076 }
15077 return newSourcePath;
15078 }
15079 return sourcePath;
15080 })
15081 .map(normalize);
15082 timeEnd('sourcemap', 2);
15083 }
15084 if (!options.compact && code[code.length - 1] !== '\n')
15085 code += '\n';
15086 return { code, map };
15087 }
15088 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
15089 for (const module of moduleDependencies) {
15090 if (module instanceof Module) {
15091 const chunk = this.chunkByModule.get(module);
15092 if (chunk && chunk !== this) {
15093 chunkDependencies.add(chunk);
15094 }
15095 }
15096 else {
15097 chunkDependencies.add(module);
15098 }
15099 }
15100 }
15101 addNecessaryImportsForFacades() {
15102 for (const [module, variables] of this.includedReexportsByModule) {
15103 if (this.includedNamespaces.has(module)) {
15104 for (const variable of variables) {
15105 this.imports.add(variable);
15106 }
15107 }
15108 }
15109 }
15110 assignFacadeName({ fileName, name }, facadedModule) {
15111 if (fileName) {
15112 this.fileName = fileName;
15113 }
15114 else {
15115 this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
15116 }
15117 }
15118 checkCircularDependencyImport(variable, importingModule) {
15119 const variableModule = variable.module;
15120 if (variableModule instanceof Module) {
15121 const exportChunk = this.chunkByModule.get(variableModule);
15122 let alternativeReexportModule;
15123 do {
15124 alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
15125 if (alternativeReexportModule) {
15126 const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
15127 if (exportingChunk && exportingChunk !== exportChunk) {
15128 this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
15129 }
15130 importingModule = alternativeReexportModule;
15131 }
15132 } while (alternativeReexportModule);
15133 }
15134 }
15135 computeContentHashWithDependencies(addons, options, bundle) {
15136 const hash = createHash();
15137 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
15138 hash.update(options.format);
15139 const dependenciesForHashing = new Set([this]);
15140 for (const current of dependenciesForHashing) {
15141 if (current instanceof ExternalModule) {
15142 hash.update(`:${current.renderPath}`);
15143 }
15144 else {
15145 hash.update(current.getRenderedHash());
15146 hash.update(current.generateId(addons, options, bundle, false));
15147 }
15148 if (current instanceof ExternalModule)
15149 continue;
15150 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
15151 dependenciesForHashing.add(dependency);
15152 }
15153 }
15154 return hash.digest('hex').substr(0, 8);
15155 }
15156 ensureReexportsAreAvailableForModule(module) {
15157 const includedReexports = [];
15158 const map = module.getExportNamesByVariable();
15159 for (const exportedVariable of map.keys()) {
15160 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
15161 const importedVariable = isSynthetic
15162 ? exportedVariable.getBaseVariable()
15163 : exportedVariable;
15164 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
15165 this.checkCircularDependencyImport(importedVariable, module);
15166 const exportingModule = importedVariable.module;
15167 if (exportingModule instanceof Module) {
15168 const chunk = this.chunkByModule.get(exportingModule);
15169 if (chunk && chunk !== this) {
15170 chunk.exports.add(importedVariable);
15171 includedReexports.push(importedVariable);
15172 if (isSynthetic) {
15173 this.imports.add(importedVariable);
15174 }
15175 }
15176 }
15177 }
15178 }
15179 if (includedReexports.length) {
15180 this.includedReexportsByModule.set(module, includedReexports);
15181 }
15182 }
15183 finaliseDynamicImports(options, snippets) {
15184 const stripKnownJsExtensions = options.format === 'amd' && !options.amd.forceJsExtensionForImports;
15185 for (const [module, code] of this.renderedModuleSources) {
15186 for (const { node, resolution } of module.dynamicImports) {
15187 const chunk = this.chunkByModule.get(resolution);
15188 const facadeChunk = this.facadeChunkByModule.get(resolution);
15189 if (!resolution || !node.included || chunk === this) {
15190 continue;
15191 }
15192 const renderedResolution = resolution instanceof Module
15193 ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
15194 : resolution instanceof ExternalModule
15195 ? `'${escapeId(resolution.renormalizeRenderPath
15196 ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
15197 : resolution.renderPath)}'`
15198 : resolution;
15199 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
15200 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
15201 chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
15202 }
15203 }
15204 }
15205 finaliseImportMetas(format, snippets) {
15206 for (const [module, code] of this.renderedModuleSources) {
15207 for (const importMeta of module.importMetas) {
15208 importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
15209 }
15210 }
15211 }
15212 generateVariableName() {
15213 if (this.manualChunkAlias) {
15214 return this.manualChunkAlias;
15215 }
15216 const moduleForNaming = this.entryModules[0] ||
15217 this.implicitEntryModules[0] ||
15218 this.dynamicEntryModules[0] ||
15219 this.orderedModules[this.orderedModules.length - 1];
15220 if (moduleForNaming) {
15221 return getChunkNameFromModule(moduleForNaming);
15222 }
15223 return 'chunk';
15224 }
15225 getChunkDependencyDeclarations(options, getPropertyAccess) {
15226 const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
15227 const reexportSpecifiers = this.getReexportSpecifiers();
15228 const dependencyDeclaration = new Map();
15229 for (const dep of this.dependencies) {
15230 const imports = importSpecifiers.get(dep) || null;
15231 const reexports = reexportSpecifiers.get(dep) || null;
15232 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
15233 dependencyDeclaration.set(dep, {
15234 defaultVariableName: dep.defaultVariableName,
15235 globalName: (dep instanceof ExternalModule &&
15236 (options.format === 'umd' || options.format === 'iife') &&
15237 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
15238 id: undefined,
15239 imports,
15240 isChunk: dep instanceof Chunk,
15241 name: dep.variableName,
15242 namedExportsMode,
15243 namespaceVariableName: dep.namespaceVariableName,
15244 reexports
15245 });
15246 }
15247 return dependencyDeclaration;
15248 }
15249 getChunkExportDeclarations(format, getPropertyAccess) {
15250 const exports = [];
15251 for (const exportName of this.getExportNames()) {
15252 if (exportName[0] === '*')
15253 continue;
15254 const variable = this.exportsByName.get(exportName);
15255 if (!(variable instanceof SyntheticNamedExportVariable)) {
15256 const module = variable.module;
15257 if (module && this.chunkByModule.get(module) !== this)
15258 continue;
15259 }
15260 let expression = null;
15261 let hoisted = false;
15262 let local = variable.getName(getPropertyAccess);
15263 if (variable instanceof LocalVariable) {
15264 for (const declaration of variable.declarations) {
15265 if (declaration.parent instanceof FunctionDeclaration ||
15266 (declaration instanceof ExportDefaultDeclaration &&
15267 declaration.declaration instanceof FunctionDeclaration)) {
15268 hoisted = true;
15269 break;
15270 }
15271 }
15272 }
15273 else if (variable instanceof SyntheticNamedExportVariable) {
15274 expression = local;
15275 if (format === 'es') {
15276 local = variable.renderName;
15277 }
15278 }
15279 exports.push({
15280 exported: exportName,
15281 expression,
15282 hoisted,
15283 local
15284 });
15285 }
15286 return exports;
15287 }
15288 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
15289 const dependencies = new Set();
15290 const deconflictedDefault = new Set();
15291 const deconflictedNamespace = new Set();
15292 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
15293 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
15294 const module = variable.module;
15295 if (module instanceof ExternalModule) {
15296 dependencies.add(module);
15297 if (addNonNamespacesAndInteropHelpers) {
15298 if (variable.name === 'default') {
15299 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
15300 deconflictedDefault.add(module);
15301 }
15302 }
15303 else if (variable.name === '*') {
15304 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
15305 deconflictedNamespace.add(module);
15306 }
15307 }
15308 }
15309 }
15310 else {
15311 const chunk = this.chunkByModule.get(module);
15312 if (chunk !== this) {
15313 dependencies.add(chunk);
15314 if (addNonNamespacesAndInteropHelpers &&
15315 chunk.exportMode === 'default' &&
15316 variable.isNamespace) {
15317 deconflictedNamespace.add(chunk);
15318 }
15319 }
15320 }
15321 }
15322 }
15323 if (addDependenciesWithoutBindings) {
15324 for (const dependency of this.dependencies) {
15325 dependencies.add(dependency);
15326 }
15327 }
15328 return { deconflictedDefault, deconflictedNamespace, dependencies };
15329 }
15330 getFallbackChunkName() {
15331 if (this.manualChunkAlias) {
15332 return this.manualChunkAlias;
15333 }
15334 if (this.dynamicName) {
15335 return this.dynamicName;
15336 }
15337 if (this.fileName) {
15338 return getAliasName(this.fileName);
15339 }
15340 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15341 }
15342 getImportSpecifiers(getPropertyAccess) {
15343 const { interop } = this.outputOptions;
15344 const importsByDependency = new Map();
15345 for (const variable of this.imports) {
15346 const module = variable.module;
15347 let dependency;
15348 let imported;
15349 if (module instanceof ExternalModule) {
15350 dependency = module;
15351 imported = variable.name;
15352 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15353 return error(errUnexpectedNamedImport(module.id, imported, false));
15354 }
15355 }
15356 else {
15357 dependency = this.chunkByModule.get(module);
15358 imported = dependency.getVariableExportName(variable);
15359 }
15360 getOrCreate(importsByDependency, dependency, () => []).push({
15361 imported,
15362 local: variable.getName(getPropertyAccess)
15363 });
15364 }
15365 return importsByDependency;
15366 }
15367 getImportedBindingsPerDependency() {
15368 const importSpecifiers = {};
15369 for (const [dependency, declaration] of this.renderedDependencies) {
15370 const specifiers = new Set();
15371 if (declaration.imports) {
15372 for (const { imported } of declaration.imports) {
15373 specifiers.add(imported);
15374 }
15375 }
15376 if (declaration.reexports) {
15377 for (const { imported } of declaration.reexports) {
15378 specifiers.add(imported);
15379 }
15380 }
15381 importSpecifiers[dependency.id] = [...specifiers];
15382 }
15383 return importSpecifiers;
15384 }
15385 getReexportSpecifiers() {
15386 const { externalLiveBindings, interop } = this.outputOptions;
15387 const reexportSpecifiers = new Map();
15388 for (let exportName of this.getExportNames()) {
15389 let dependency;
15390 let imported;
15391 let needsLiveBinding = false;
15392 if (exportName[0] === '*') {
15393 const id = exportName.substring(1);
15394 if (interop(id) === 'defaultOnly') {
15395 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15396 }
15397 needsLiveBinding = externalLiveBindings;
15398 dependency = this.modulesById.get(id);
15399 imported = exportName = '*';
15400 }
15401 else {
15402 const variable = this.exportsByName.get(exportName);
15403 if (variable instanceof SyntheticNamedExportVariable)
15404 continue;
15405 const module = variable.module;
15406 if (module instanceof Module) {
15407 dependency = this.chunkByModule.get(module);
15408 if (dependency === this)
15409 continue;
15410 imported = dependency.getVariableExportName(variable);
15411 needsLiveBinding = variable.isReassigned;
15412 }
15413 else {
15414 dependency = module;
15415 imported = variable.name;
15416 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15417 return error(errUnexpectedNamedImport(module.id, imported, true));
15418 }
15419 needsLiveBinding =
15420 externalLiveBindings &&
15421 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
15422 }
15423 }
15424 getOrCreate(reexportSpecifiers, dependency, () => []).push({
15425 imported,
15426 needsLiveBinding,
15427 reexported: exportName
15428 });
15429 }
15430 return reexportSpecifiers;
15431 }
15432 getReferencedFiles() {
15433 const referencedFiles = [];
15434 for (const module of this.orderedModules) {
15435 for (const meta of module.importMetas) {
15436 const fileName = meta.getReferencedFileName(this.pluginDriver);
15437 if (fileName) {
15438 referencedFiles.push(fileName);
15439 }
15440 }
15441 }
15442 return referencedFiles;
15443 }
15444 inlineChunkDependencies(chunk) {
15445 for (const dep of chunk.dependencies) {
15446 if (this.dependencies.has(dep))
15447 continue;
15448 this.dependencies.add(dep);
15449 if (dep instanceof Chunk) {
15450 this.inlineChunkDependencies(dep);
15451 }
15452 }
15453 }
15454 prepareModulesForRendering(snippets) {
15455 var _a;
15456 const accessedGlobalsByScope = this.accessedGlobalsByScope;
15457 for (const module of this.orderedModules) {
15458 for (const { node, resolution } of module.dynamicImports) {
15459 if (node.included) {
15460 if (resolution instanceof Module) {
15461 const chunk = this.chunkByModule.get(resolution);
15462 if (chunk === this) {
15463 node.setInternalResolution(resolution.namespace);
15464 }
15465 else {
15466 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15467 }
15468 }
15469 else {
15470 node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15471 }
15472 }
15473 }
15474 for (const importMeta of module.importMetas) {
15475 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
15476 }
15477 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
15478 module.namespace.prepare(accessedGlobalsByScope);
15479 }
15480 }
15481 }
15482 setExternalRenderPaths(options, inputBase) {
15483 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
15484 if (dependency instanceof ExternalModule) {
15485 dependency.setRenderPath(options, inputBase);
15486 }
15487 }
15488 }
15489 setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
15490 const syntheticExports = new Set();
15491 for (const exportName of this.getExportNames()) {
15492 const exportVariable = this.exportsByName.get(exportName);
15493 if (format !== 'es' &&
15494 format !== 'system' &&
15495 exportVariable.isReassigned &&
15496 !exportVariable.isId) {
15497 exportVariable.setRenderNames('exports', exportName);
15498 }
15499 else if (exportVariable instanceof SyntheticNamedExportVariable) {
15500 syntheticExports.add(exportVariable);
15501 }
15502 else {
15503 exportVariable.setRenderNames(null, null);
15504 }
15505 }
15506 for (const module of this.orderedModules) {
15507 if (module.needsExportShim) {
15508 this.needsExportsShim = true;
15509 break;
15510 }
15511 }
15512 const usedNames = new Set(['Object', 'Promise']);
15513 if (this.needsExportsShim) {
15514 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
15515 }
15516 if (namespaceToStringTag) {
15517 usedNames.add('Symbol');
15518 }
15519 switch (format) {
15520 case 'system':
15521 usedNames.add('module').add('exports');
15522 break;
15523 case 'es':
15524 break;
15525 case 'cjs':
15526 usedNames.add('module').add('require').add('__filename').add('__dirname');
15527 // fallthrough
15528 default:
15529 usedNames.add('exports');
15530 for (const helper of HELPER_NAMES) {
15531 usedNames.add(helper);
15532 }
15533 }
15534 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);
15535 }
15536 setUpChunkImportsAndExportsForModule(module) {
15537 const moduleImports = new Set(module.includedImports);
15538 // when we are not preserving modules, we need to make all namespace variables available for
15539 // rendering the namespace object
15540 if (!this.outputOptions.preserveModules) {
15541 if (this.includedNamespaces.has(module)) {
15542 const memberVariables = module.namespace.getMemberVariables();
15543 for (const variable of Object.values(memberVariables)) {
15544 moduleImports.add(variable);
15545 }
15546 }
15547 }
15548 for (let variable of moduleImports) {
15549 if (variable instanceof ExportDefaultVariable) {
15550 variable = variable.getOriginalVariable();
15551 }
15552 if (variable instanceof SyntheticNamedExportVariable) {
15553 variable = variable.getBaseVariable();
15554 }
15555 const chunk = this.chunkByModule.get(variable.module);
15556 if (chunk !== this) {
15557 this.imports.add(variable);
15558 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
15559 variable.module instanceof Module) {
15560 chunk.exports.add(variable);
15561 this.checkCircularDependencyImport(variable, module);
15562 }
15563 }
15564 }
15565 if (this.includedNamespaces.has(module) ||
15566 (module.info.isEntry && module.preserveSignature !== false) ||
15567 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
15568 this.ensureReexportsAreAvailableForModule(module);
15569 }
15570 for (const { node, resolution } of module.dynamicImports) {
15571 if (node.included &&
15572 resolution instanceof Module &&
15573 this.chunkByModule.get(resolution) === this &&
15574 !this.includedNamespaces.has(resolution)) {
15575 this.includedNamespaces.add(resolution);
15576 this.ensureReexportsAreAvailableForModule(resolution);
15577 }
15578 }
15579 }
15580}
15581function getChunkNameFromModule(module) {
15582 var _a, _b, _c, _d;
15583 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));
15584}
15585const QUERY_HASH_REGEX = /[?#]/;
15586
15587const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
15588const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
15589async function createAddons(options, outputPluginDriver) {
15590 try {
15591 let [banner, footer, intro, outro] = await Promise.all([
15592 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
15593 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
15594 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
15595 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
15596 ]);
15597 if (intro)
15598 intro += '\n\n';
15599 if (outro)
15600 outro = `\n\n${outro}`;
15601 if (banner.length)
15602 banner += '\n';
15603 if (footer.length)
15604 footer = '\n' + footer;
15605 return { banner, footer, intro, outro };
15606 }
15607 catch (err) {
15608 return error({
15609 code: 'ADDON_ERROR',
15610 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
15611\tError Message: ${err.message}`
15612 });
15613 }
15614}
15615
15616function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15617 const chunkDefinitions = [];
15618 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15619 const manualChunkModulesByAlias = Object.create(null);
15620 for (const [entry, alias] of manualChunkAliasByEntry) {
15621 const chunkModules = (manualChunkModulesByAlias[alias] =
15622 manualChunkModulesByAlias[alias] || []);
15623 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15624 }
15625 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15626 chunkDefinitions.push({ alias, modules });
15627 }
15628 const assignedEntryPointsByModule = new Map();
15629 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15630 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15631 const staticEntries = new Set(entryModules);
15632 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15633 const modulesToHandle = new Set([entry]);
15634 for (const module of modulesToHandle) {
15635 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15636 if (dynamicDependentEntryPoints &&
15637 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15638 continue;
15639 }
15640 else {
15641 assignedEntryPoints.add(entry);
15642 }
15643 for (const dependency of module.getDependenciesToBeIncluded()) {
15644 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15645 modulesToHandle.add(dependency);
15646 }
15647 }
15648 }
15649 }
15650 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15651 const entriesToCheck = new Set(entryPoints);
15652 for (const entry of entriesToCheck) {
15653 if (!containedIn.has(entry)) {
15654 if (staticEntries.has(entry))
15655 return false;
15656 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15657 for (const dependentEntry of dynamicallyDependentEntryPoints) {
15658 entriesToCheck.add(dependentEntry);
15659 }
15660 }
15661 }
15662 return true;
15663 }
15664 for (const entry of entryModules) {
15665 if (!modulesInManualChunks.has(entry)) {
15666 assignEntryToStaticDependencies(entry, null);
15667 }
15668 }
15669 for (const entry of dynamicEntryModules) {
15670 if (!modulesInManualChunks.has(entry)) {
15671 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
15672 }
15673 }
15674 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
15675 return chunkDefinitions;
15676}
15677function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
15678 const modulesToHandle = new Set([entry]);
15679 for (const module of modulesToHandle) {
15680 modulesInManualChunks.add(module);
15681 manualChunkModules.push(module);
15682 for (const dependency of module.dependencies) {
15683 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15684 modulesToHandle.add(dependency);
15685 }
15686 }
15687 }
15688}
15689function analyzeModuleGraph(entryModules) {
15690 const dynamicEntryModules = new Set();
15691 const dependentEntryPointsByModule = new Map();
15692 const entriesToHandle = new Set(entryModules);
15693 for (const currentEntry of entriesToHandle) {
15694 const modulesToHandle = new Set([currentEntry]);
15695 for (const module of modulesToHandle) {
15696 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
15697 for (const dependency of module.getDependenciesToBeIncluded()) {
15698 if (!(dependency instanceof ExternalModule)) {
15699 modulesToHandle.add(dependency);
15700 }
15701 }
15702 for (const { resolution } of module.dynamicImports) {
15703 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
15704 dynamicEntryModules.add(resolution);
15705 entriesToHandle.add(resolution);
15706 }
15707 }
15708 for (const dependency of module.implicitlyLoadedBefore) {
15709 dynamicEntryModules.add(dependency);
15710 entriesToHandle.add(dependency);
15711 }
15712 }
15713 }
15714 return { dependentEntryPointsByModule, dynamicEntryModules };
15715}
15716function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15717 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15718 for (const dynamicEntry of dynamicEntryModules) {
15719 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15720 for (const importer of [
15721 ...dynamicEntry.includedDynamicImporters,
15722 ...dynamicEntry.implicitlyLoadedAfter
15723 ]) {
15724 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15725 dynamicDependentEntryPoints.add(entryPoint);
15726 }
15727 }
15728 }
15729 return dynamicallyDependentEntryPointsByDynamicEntry;
15730}
15731function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15732 const chunkModules = Object.create(null);
15733 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15734 let chunkSignature = '';
15735 for (const entry of allEntryPoints) {
15736 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15737 }
15738 const chunk = chunkModules[chunkSignature];
15739 if (chunk) {
15740 chunk.push(module);
15741 }
15742 else {
15743 chunkModules[chunkSignature] = [module];
15744 }
15745 }
15746 return Object.values(chunkModules).map(modules => ({
15747 alias: null,
15748 modules
15749 }));
15750}
15751
15752// ported from https://github.com/substack/node-commondir
15753function commondir(files) {
15754 if (files.length === 0)
15755 return '/';
15756 if (files.length === 1)
15757 return require$$0.dirname(files[0]);
15758 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15759 const pathSegements = file.split(/\/+|\\+/);
15760 let i;
15761 for (i = 0; commonSegments[i] === pathSegements[i] &&
15762 i < Math.min(commonSegments.length, pathSegements.length); i++)
15763 ;
15764 return commonSegments.slice(0, i);
15765 }, files[0].split(/\/+|\\+/));
15766 // Windows correctly handles paths with forward-slashes
15767 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15768}
15769
15770const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15771function sortByExecutionOrder(units) {
15772 units.sort(compareExecIndex);
15773}
15774function analyseModuleExecution(entryModules) {
15775 let nextExecIndex = 0;
15776 const cyclePaths = [];
15777 const analysedModules = new Set();
15778 const dynamicImports = new Set();
15779 const parents = new Map();
15780 const orderedModules = [];
15781 const analyseModule = (module) => {
15782 if (module instanceof Module) {
15783 for (const dependency of module.dependencies) {
15784 if (parents.has(dependency)) {
15785 if (!analysedModules.has(dependency)) {
15786 cyclePaths.push(getCyclePath(dependency, module, parents));
15787 }
15788 continue;
15789 }
15790 parents.set(dependency, module);
15791 analyseModule(dependency);
15792 }
15793 for (const dependency of module.implicitlyLoadedBefore) {
15794 dynamicImports.add(dependency);
15795 }
15796 for (const { resolution } of module.dynamicImports) {
15797 if (resolution instanceof Module) {
15798 dynamicImports.add(resolution);
15799 }
15800 }
15801 orderedModules.push(module);
15802 }
15803 module.execIndex = nextExecIndex++;
15804 analysedModules.add(module);
15805 };
15806 for (const curEntry of entryModules) {
15807 if (!parents.has(curEntry)) {
15808 parents.set(curEntry, null);
15809 analyseModule(curEntry);
15810 }
15811 }
15812 for (const curEntry of dynamicImports) {
15813 if (!parents.has(curEntry)) {
15814 parents.set(curEntry, null);
15815 analyseModule(curEntry);
15816 }
15817 }
15818 return { cyclePaths, orderedModules };
15819}
15820function getCyclePath(module, parent, parents) {
15821 const cycleSymbol = Symbol(module.id);
15822 const path = [relativeId(module.id)];
15823 let nextModule = parent;
15824 module.cycles.add(cycleSymbol);
15825 while (nextModule !== module) {
15826 nextModule.cycles.add(cycleSymbol);
15827 path.push(relativeId(nextModule.id));
15828 nextModule = parents.get(nextModule);
15829 }
15830 path.push(path[0]);
15831 path.reverse();
15832 return path;
15833}
15834
15835function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15836 const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15837 const cnst = constBindings ? 'const' : 'var';
15838 const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15839 const getFunctionIntro = arrowFunctions
15840 ? (params, { isAsync, name }) => {
15841 const singleParam = params.length === 1;
15842 const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15843 return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
15844 }
15845 : getNonArrowFunctionIntro;
15846 const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15847 `${getFunctionIntro(params, {
15848 isAsync: false,
15849 name
15850 })}${arrowFunctions
15851 ? lineBreakIndent
15852 ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
15853 : ''
15854 : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
15855 arrowFunctions
15856 ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15857 : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15858 ];
15859 const isValidPropName = reservedNamesAsProps
15860 ? (name) => validPropName.test(name)
15861 : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15862 return {
15863 _,
15864 cnst,
15865 getDirectReturnFunction,
15866 getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15867 const [left, right] = getDirectReturnFunction(params, {
15868 functionReturn: true,
15869 lineBreakIndent: null,
15870 name: null
15871 });
15872 return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
15873 },
15874 getFunctionIntro,
15875 getNonArrowFunctionIntro,
15876 getObject(fields, { lineBreakIndent }) {
15877 const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
15878 return `{${fields
15879 .map(([key, value]) => {
15880 if (key === null)
15881 return `${prefix}${value}`;
15882 const needsQuotes = !isValidPropName(key);
15883 return key === value && objectShorthand && !needsQuotes
15884 ? prefix + key
15885 : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15886 })
15887 .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15888 },
15889 getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15890 n,
15891 s
15892 };
15893}
15894const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15895const validPropName = /^(?!\d)[\w$]+$/;
15896
15897class Bundle {
15898 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
15899 this.outputOptions = outputOptions;
15900 this.unsetOptions = unsetOptions;
15901 this.inputOptions = inputOptions;
15902 this.pluginDriver = pluginDriver;
15903 this.graph = graph;
15904 this.facadeChunkByModule = new Map();
15905 this.includedNamespaces = new Set();
15906 }
15907 async generate(isWrite) {
15908 timeStart('GENERATE', 1);
15909 const outputBundleBase = Object.create(null);
15910 const outputBundle = getOutputBundle(outputBundleBase);
15911 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
15912 try {
15913 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
15914 timeStart('generate chunks', 2);
15915 const chunks = await this.generateChunks();
15916 if (chunks.length > 1) {
15917 validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
15918 }
15919 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
15920 timeEnd('generate chunks', 2);
15921 timeStart('render modules', 2);
15922 // We need to create addons before prerender because at the moment, there
15923 // can be no async code between prerender and render due to internal state
15924 const addons = await createAddons(this.outputOptions, this.pluginDriver);
15925 const snippets = getGenerateCodeSnippets(this.outputOptions);
15926 this.prerenderChunks(chunks, inputBase, snippets);
15927 timeEnd('render modules', 2);
15928 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
15929 }
15930 catch (err) {
15931 await this.pluginDriver.hookParallel('renderError', [err]);
15932 throw err;
15933 }
15934 await this.pluginDriver.hookSeq('generateBundle', [
15935 this.outputOptions,
15936 outputBundle,
15937 isWrite
15938 ]);
15939 this.finaliseAssets(outputBundle);
15940 validateOutputBundleFileNames(outputBundle);
15941 timeEnd('GENERATE', 1);
15942 return outputBundleBase;
15943 }
15944 async addFinalizedChunksToBundle(chunks, inputBase, addons, bundle, snippets) {
15945 this.assignChunkIds(chunks, inputBase, addons, bundle);
15946 for (const chunk of chunks) {
15947 bundle[chunk.id] = chunk.getChunkInfoWithFileNames();
15948 }
15949 await Promise.all(chunks.map(async (chunk) => {
15950 const outputChunk = bundle[chunk.id];
15951 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
15952 }));
15953 }
15954 async addManualChunks(manualChunks) {
15955 const manualChunkAliasByEntry = new Map();
15956 const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
15957 alias,
15958 entries: await this.graph.moduleLoader.addAdditionalModules(files)
15959 })));
15960 for (const { alias, entries } of chunkEntries) {
15961 for (const entry of entries) {
15962 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
15963 }
15964 }
15965 return manualChunkAliasByEntry;
15966 }
15967 assignChunkIds(chunks, inputBase, addons, bundle) {
15968 const entryChunks = [];
15969 const otherChunks = [];
15970 for (const chunk of chunks) {
15971 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
15972 ? entryChunks
15973 : otherChunks).push(chunk);
15974 }
15975 // make sure entry chunk names take precedence with regard to deconflicting
15976 const chunksForNaming = entryChunks.concat(otherChunks);
15977 for (const chunk of chunksForNaming) {
15978 if (this.outputOptions.file) {
15979 chunk.id = require$$0.basename(this.outputOptions.file);
15980 }
15981 else if (this.outputOptions.preserveModules) {
15982 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
15983 }
15984 else {
15985 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
15986 }
15987 bundle[chunk.id] = FILE_PLACEHOLDER;
15988 }
15989 }
15990 assignManualChunks(getManualChunk) {
15991 const manualChunkAliasesWithEntry = [];
15992 const manualChunksApi = {
15993 getModuleIds: () => this.graph.modulesById.keys(),
15994 getModuleInfo: this.graph.getModuleInfo
15995 };
15996 for (const module of this.graph.modulesById.values()) {
15997 if (module instanceof Module) {
15998 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
15999 if (typeof manualChunkAlias === 'string') {
16000 manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
16001 }
16002 }
16003 }
16004 manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
16005 const manualChunkAliasByEntry = new Map();
16006 for (const [alias, module] of manualChunkAliasesWithEntry) {
16007 addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
16008 }
16009 return manualChunkAliasByEntry;
16010 }
16011 finaliseAssets(outputBundle) {
16012 for (const file of Object.values(outputBundle)) {
16013 if (!file.type) {
16014 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);
16015 file.type = 'asset';
16016 }
16017 if (this.outputOptions.validate && 'code' in file) {
16018 try {
16019 this.graph.contextParse(file.code, {
16020 allowHashBang: true,
16021 ecmaVersion: 'latest'
16022 });
16023 }
16024 catch (err) {
16025 this.inputOptions.onwarn(errChunkInvalid(file, err));
16026 }
16027 }
16028 }
16029 this.pluginDriver.finaliseAssets();
16030 }
16031 async generateChunks() {
16032 const { manualChunks } = this.outputOptions;
16033 const manualChunkAliasByEntry = typeof manualChunks === 'object'
16034 ? await this.addManualChunks(manualChunks)
16035 : this.assignManualChunks(manualChunks);
16036 const chunks = [];
16037 const chunkByModule = new Map();
16038 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
16039 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
16040 : this.outputOptions.preserveModules
16041 ? getIncludedModules(this.graph.modulesById).map(module => ({
16042 alias: null,
16043 modules: [module]
16044 }))
16045 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
16046 sortByExecutionOrder(modules);
16047 const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
16048 chunks.push(chunk);
16049 for (const module of modules) {
16050 chunkByModule.set(module, chunk);
16051 }
16052 }
16053 for (const chunk of chunks) {
16054 chunk.link();
16055 }
16056 const facades = [];
16057 for (const chunk of chunks) {
16058 facades.push(...chunk.generateFacades());
16059 }
16060 return [...chunks, ...facades];
16061 }
16062 prerenderChunks(chunks, inputBase, snippets) {
16063 for (const chunk of chunks) {
16064 chunk.generateExports();
16065 }
16066 for (const chunk of chunks) {
16067 chunk.preRender(this.outputOptions, inputBase, snippets);
16068 }
16069 }
16070}
16071function getAbsoluteEntryModulePaths(chunks) {
16072 const absoluteEntryModulePaths = [];
16073 for (const chunk of chunks) {
16074 for (const entryModule of chunk.entryModules) {
16075 if (isAbsolute(entryModule.id)) {
16076 absoluteEntryModulePaths.push(entryModule.id);
16077 }
16078 }
16079 }
16080 return absoluteEntryModulePaths;
16081}
16082function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16083 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
16084 return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
16085 if (typeof outputOptions.file === 'string')
16086 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'));
16087 if (outputOptions.sourcemapFile)
16088 return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
16089 if (!outputOptions.amd.autoId && outputOptions.amd.id)
16090 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'));
16091}
16092function getIncludedModules(modulesById) {
16093 return [...modulesById.values()].filter((module) => module instanceof Module &&
16094 (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
16095}
16096function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
16097 const existingAlias = manualChunkAliasByEntry.get(module);
16098 if (typeof existingAlias === 'string' && existingAlias !== alias) {
16099 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
16100 }
16101 manualChunkAliasByEntry.set(module, alias);
16102}
16103function isFileNameOutsideOutputDirectory(fileName) {
16104 // Use join() to normalize ".." segments, then replace backslashes so the
16105 // string checks below work identically on Windows and POSIX.
16106 const normalized = require$$0.join(fileName).replace(/\\/g, '/');
16107 return (normalized === '..' ||
16108 normalized.startsWith('../') ||
16109 normalized === '.' ||
16110 isAbsolute(normalized));
16111}
16112function validateOutputBundleFileNames(bundle) {
16113 for (const [bundleKey, entry] of Object.entries(bundle)) {
16114 if (isFileNameOutsideOutputDirectory(bundleKey)) {
16115 return error(errFileNameOutsideOutputDirectory(bundleKey));
16116 }
16117 if (entry.type !== 'placeholder') {
16118 const { fileName } = entry;
16119 if (fileName !== bundleKey && isFileNameOutsideOutputDirectory(fileName)) {
16120 return error(errFileNameOutsideOutputDirectory(fileName));
16121 }
16122 }
16123 }
16124}
16125
16126// This file was generated. Do not modify manually!
16127var 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];
16128
16129// This file was generated. Do not modify manually!
16130var 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];
16131
16132// This file was generated. Do not modify manually!
16133var 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";
16134
16135// This file was generated. Do not modify manually!
16136var 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";
16137
16138// These are a run-length and offset encoded representation of the
16139
16140// Reserved word lists for various dialects of the language
16141
16142var reservedWords = {
16143 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",
16144 5: "class enum extends super const export import",
16145 6: "enum",
16146 strict: "implements interface let package private protected public static yield",
16147 strictBind: "eval arguments"
16148};
16149
16150// And the keywords
16151
16152var 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";
16153
16154var keywords$1 = {
16155 5: ecma5AndLessKeywords,
16156 "5module": ecma5AndLessKeywords + " export import",
16157 6: ecma5AndLessKeywords + " const class extends export import super"
16158};
16159
16160var keywordRelationalOperator = /^in(stanceof)?$/;
16161
16162// ## Character categories
16163
16164var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
16165var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
16166
16167// This has a complexity linear to the value of the code. The
16168// assumption is that looking up astral identifier characters is
16169// rare.
16170function isInAstralSet(code, set) {
16171 var pos = 0x10000;
16172 for (var i = 0; i < set.length; i += 2) {
16173 pos += set[i];
16174 if (pos > code) { return false }
16175 pos += set[i + 1];
16176 if (pos >= code) { return true }
16177 }
16178}
16179
16180// Test whether a given character code starts an identifier.
16181
16182function isIdentifierStart(code, astral) {
16183 if (code < 65) { return code === 36 }
16184 if (code < 91) { return true }
16185 if (code < 97) { return code === 95 }
16186 if (code < 123) { return true }
16187 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
16188 if (astral === false) { return false }
16189 return isInAstralSet(code, astralIdentifierStartCodes)
16190}
16191
16192// Test whether a given character is part of an identifier.
16193
16194function isIdentifierChar(code, astral) {
16195 if (code < 48) { return code === 36 }
16196 if (code < 58) { return true }
16197 if (code < 65) { return false }
16198 if (code < 91) { return true }
16199 if (code < 97) { return code === 95 }
16200 if (code < 123) { return true }
16201 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
16202 if (astral === false) { return false }
16203 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
16204}
16205
16206// ## Token types
16207
16208// The assignment of fine-grained, information-carrying type objects
16209// allows the tokenizer to store the information it has about a
16210// token in a way that is very cheap for the parser to look up.
16211
16212// All token type variables start with an underscore, to make them
16213// easy to recognize.
16214
16215// The `beforeExpr` property is used to disambiguate between regular
16216// expressions and divisions. It is set on all token types that can
16217// be followed by an expression (thus, a slash after them would be a
16218// regular expression).
16219//
16220// The `startsExpr` property is used to check if the token ends a
16221// `yield` expression. It is set on all token types that either can
16222// directly start an expression (like a quotation mark) or can
16223// continue an expression (like the body of a string).
16224//
16225// `isLoop` marks a keyword as starting a loop, which is important
16226// to know when parsing a label, in order to allow or disallow
16227// continue jumps to that label.
16228
16229var TokenType = function TokenType(label, conf) {
16230 if ( conf === void 0 ) conf = {};
16231
16232 this.label = label;
16233 this.keyword = conf.keyword;
16234 this.beforeExpr = !!conf.beforeExpr;
16235 this.startsExpr = !!conf.startsExpr;
16236 this.isLoop = !!conf.isLoop;
16237 this.isAssign = !!conf.isAssign;
16238 this.prefix = !!conf.prefix;
16239 this.postfix = !!conf.postfix;
16240 this.binop = conf.binop || null;
16241 this.updateContext = null;
16242};
16243
16244function binop(name, prec) {
16245 return new TokenType(name, {beforeExpr: true, binop: prec})
16246}
16247var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
16248
16249// Map keyword names to token types.
16250
16251var keywords = {};
16252
16253// Succinct definitions of keyword token types
16254function kw(name, options) {
16255 if ( options === void 0 ) options = {};
16256
16257 options.keyword = name;
16258 return keywords[name] = new TokenType(name, options)
16259}
16260
16261var types$1 = {
16262 num: new TokenType("num", startsExpr),
16263 regexp: new TokenType("regexp", startsExpr),
16264 string: new TokenType("string", startsExpr),
16265 name: new TokenType("name", startsExpr),
16266 privateId: new TokenType("privateId", startsExpr),
16267 eof: new TokenType("eof"),
16268
16269 // Punctuation token types.
16270 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
16271 bracketR: new TokenType("]"),
16272 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
16273 braceR: new TokenType("}"),
16274 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
16275 parenR: new TokenType(")"),
16276 comma: new TokenType(",", beforeExpr),
16277 semi: new TokenType(";", beforeExpr),
16278 colon: new TokenType(":", beforeExpr),
16279 dot: new TokenType("."),
16280 question: new TokenType("?", beforeExpr),
16281 questionDot: new TokenType("?."),
16282 arrow: new TokenType("=>", beforeExpr),
16283 template: new TokenType("template"),
16284 invalidTemplate: new TokenType("invalidTemplate"),
16285 ellipsis: new TokenType("...", beforeExpr),
16286 backQuote: new TokenType("`", startsExpr),
16287 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
16288
16289 // Operators. These carry several kinds of properties to help the
16290 // parser use them properly (the presence of these properties is
16291 // what categorizes them as operators).
16292 //
16293 // `binop`, when present, specifies that this operator is a binary
16294 // operator, and will refer to its precedence.
16295 //
16296 // `prefix` and `postfix` mark the operator as a prefix or postfix
16297 // unary operator.
16298 //
16299 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
16300 // binary operators with a very low precedence, that should result
16301 // in AssignmentExpression nodes.
16302
16303 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
16304 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
16305 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
16306 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
16307 logicalOR: binop("||", 1),
16308 logicalAND: binop("&&", 2),
16309 bitwiseOR: binop("|", 3),
16310 bitwiseXOR: binop("^", 4),
16311 bitwiseAND: binop("&", 5),
16312 equality: binop("==/!=/===/!==", 6),
16313 relational: binop("</>/<=/>=", 7),
16314 bitShift: binop("<</>>/>>>", 8),
16315 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
16316 modulo: binop("%", 10),
16317 star: binop("*", 10),
16318 slash: binop("/", 10),
16319 starstar: new TokenType("**", {beforeExpr: true}),
16320 coalesce: binop("??", 1),
16321
16322 // Keyword token types.
16323 _break: kw("break"),
16324 _case: kw("case", beforeExpr),
16325 _catch: kw("catch"),
16326 _continue: kw("continue"),
16327 _debugger: kw("debugger"),
16328 _default: kw("default", beforeExpr),
16329 _do: kw("do", {isLoop: true, beforeExpr: true}),
16330 _else: kw("else", beforeExpr),
16331 _finally: kw("finally"),
16332 _for: kw("for", {isLoop: true}),
16333 _function: kw("function", startsExpr),
16334 _if: kw("if"),
16335 _return: kw("return", beforeExpr),
16336 _switch: kw("switch"),
16337 _throw: kw("throw", beforeExpr),
16338 _try: kw("try"),
16339 _var: kw("var"),
16340 _const: kw("const"),
16341 _while: kw("while", {isLoop: true}),
16342 _with: kw("with"),
16343 _new: kw("new", {beforeExpr: true, startsExpr: true}),
16344 _this: kw("this", startsExpr),
16345 _super: kw("super", startsExpr),
16346 _class: kw("class", startsExpr),
16347 _extends: kw("extends", beforeExpr),
16348 _export: kw("export"),
16349 _import: kw("import", startsExpr),
16350 _null: kw("null", startsExpr),
16351 _true: kw("true", startsExpr),
16352 _false: kw("false", startsExpr),
16353 _in: kw("in", {beforeExpr: true, binop: 7}),
16354 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
16355 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
16356 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
16357 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
16358};
16359
16360// Matches a whole line break (where CRLF is considered a single
16361// line break). Used to count lines.
16362
16363var lineBreak = /\r\n?|\n|\u2028|\u2029/;
16364var lineBreakG = new RegExp(lineBreak.source, "g");
16365
16366function isNewLine(code) {
16367 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
16368}
16369
16370function nextLineBreak(code, from, end) {
16371 if ( end === void 0 ) end = code.length;
16372
16373 for (var i = from; i < end; i++) {
16374 var next = code.charCodeAt(i);
16375 if (isNewLine(next))
16376 { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
16377 }
16378 return -1
16379}
16380
16381var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
16382
16383var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
16384
16385var ref = Object.prototype;
16386var hasOwnProperty = ref.hasOwnProperty;
16387var toString = ref.toString;
16388
16389var hasOwn = Object.hasOwn || (function (obj, propName) { return (
16390 hasOwnProperty.call(obj, propName)
16391); });
16392
16393var isArray = Array.isArray || (function (obj) { return (
16394 toString.call(obj) === "[object Array]"
16395); });
16396
16397function wordsRegexp(words) {
16398 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
16399}
16400
16401function codePointToString(code) {
16402 // UTF-16 Decoding
16403 if (code <= 0xFFFF) { return String.fromCharCode(code) }
16404 code -= 0x10000;
16405 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
16406}
16407
16408var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
16409
16410// These are used when `options.locations` is on, for the
16411// `startLoc` and `endLoc` properties.
16412
16413var Position = function Position(line, col) {
16414 this.line = line;
16415 this.column = col;
16416};
16417
16418Position.prototype.offset = function offset (n) {
16419 return new Position(this.line, this.column + n)
16420};
16421
16422var SourceLocation = function SourceLocation(p, start, end) {
16423 this.start = start;
16424 this.end = end;
16425 if (p.sourceFile !== null) { this.source = p.sourceFile; }
16426};
16427
16428// The `getLineInfo` function is mostly useful when the
16429// `locations` option is off (for performance reasons) and you
16430// want to find the line/column position for a given character
16431// offset. `input` should be the code string that the offset refers
16432// into.
16433
16434function getLineInfo(input, offset) {
16435 for (var line = 1, cur = 0;;) {
16436 var nextBreak = nextLineBreak(input, cur, offset);
16437 if (nextBreak < 0) { return new Position(line, offset - cur) }
16438 ++line;
16439 cur = nextBreak;
16440 }
16441}
16442
16443// A second argument must be given to configure the parser process.
16444// These options are recognized (only `ecmaVersion` is required):
16445
16446var defaultOptions = {
16447 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
16448 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
16449 // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
16450 // latest version the library supports). This influences support
16451 // for strict mode, the set of reserved words, and support for
16452 // new syntax features.
16453 ecmaVersion: null,
16454 // `sourceType` indicates the mode the code should be parsed in.
16455 // Can be either `"script"` or `"module"`. This influences global
16456 // strict mode and parsing of `import` and `export` declarations.
16457 sourceType: "script",
16458 // `onInsertedSemicolon` can be a callback that will be called
16459 // when a semicolon is automatically inserted. It will be passed
16460 // the position of the comma as an offset, and if `locations` is
16461 // enabled, it is given the location as a `{line, column}` object
16462 // as second argument.
16463 onInsertedSemicolon: null,
16464 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
16465 // trailing commas.
16466 onTrailingComma: null,
16467 // By default, reserved words are only enforced if ecmaVersion >= 5.
16468 // Set `allowReserved` to a boolean value to explicitly turn this on
16469 // an off. When this option has the value "never", reserved words
16470 // and keywords can also not be used as property names.
16471 allowReserved: null,
16472 // When enabled, a return at the top level is not considered an
16473 // error.
16474 allowReturnOutsideFunction: false,
16475 // When enabled, import/export statements are not constrained to
16476 // appearing at the top of the program, and an import.meta expression
16477 // in a script isn't considered an error.
16478 allowImportExportEverywhere: false,
16479 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
16480 // When enabled, await identifiers are allowed to appear at the top-level scope,
16481 // but they are still not allowed in non-async functions.
16482 allowAwaitOutsideFunction: null,
16483 // When enabled, super identifiers are not constrained to
16484 // appearing in methods and do not raise an error when they appear elsewhere.
16485 allowSuperOutsideMethod: null,
16486 // When enabled, hashbang directive in the beginning of file
16487 // is allowed and treated as a line comment.
16488 allowHashBang: false,
16489 // When `locations` is on, `loc` properties holding objects with
16490 // `start` and `end` properties in `{line, column}` form (with
16491 // line being 1-based and column 0-based) will be attached to the
16492 // nodes.
16493 locations: false,
16494 // A function can be passed as `onToken` option, which will
16495 // cause Acorn to call that function with object in the same
16496 // format as tokens returned from `tokenizer().getToken()`. Note
16497 // that you are not allowed to call the parser from the
16498 // callback—that will corrupt its internal state.
16499 onToken: null,
16500 // A function can be passed as `onComment` option, which will
16501 // cause Acorn to call that function with `(block, text, start,
16502 // end)` parameters whenever a comment is skipped. `block` is a
16503 // boolean indicating whether this is a block (`/* */`) comment,
16504 // `text` is the content of the comment, and `start` and `end` are
16505 // character offsets that denote the start and end of the comment.
16506 // When the `locations` option is on, two more parameters are
16507 // passed, the full `{line, column}` locations of the start and
16508 // end of the comments. Note that you are not allowed to call the
16509 // parser from the callback—that will corrupt its internal state.
16510 onComment: null,
16511 // Nodes have their start and end characters offsets recorded in
16512 // `start` and `end` properties (directly on the node, rather than
16513 // the `loc` object, which holds line/column data. To also add a
16514 // [semi-standardized][range] `range` property holding a `[start,
16515 // end]` array with the same numbers, set the `ranges` option to
16516 // `true`.
16517 //
16518 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
16519 ranges: false,
16520 // It is possible to parse multiple files into a single AST by
16521 // passing the tree produced by parsing the first file as
16522 // `program` option in subsequent parses. This will add the
16523 // toplevel forms of the parsed file to the `Program` (top) node
16524 // of an existing parse tree.
16525 program: null,
16526 // When `locations` is on, you can pass this to record the source
16527 // file in every node's `loc` object.
16528 sourceFile: null,
16529 // This value, if given, is stored in every node, whether
16530 // `locations` is on or off.
16531 directSourceFile: null,
16532 // When enabled, parenthesized expressions are represented by
16533 // (non-standard) ParenthesizedExpression nodes
16534 preserveParens: false
16535};
16536
16537// Interpret and default an options object
16538
16539var warnedAboutEcmaVersion = false;
16540
16541function getOptions(opts) {
16542 var options = {};
16543
16544 for (var opt in defaultOptions)
16545 { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
16546
16547 if (options.ecmaVersion === "latest") {
16548 options.ecmaVersion = 1e8;
16549 } else if (options.ecmaVersion == null) {
16550 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
16551 warnedAboutEcmaVersion = true;
16552 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
16553 }
16554 options.ecmaVersion = 11;
16555 } else if (options.ecmaVersion >= 2015) {
16556 options.ecmaVersion -= 2009;
16557 }
16558
16559 if (options.allowReserved == null)
16560 { options.allowReserved = options.ecmaVersion < 5; }
16561
16562 if (isArray(options.onToken)) {
16563 var tokens = options.onToken;
16564 options.onToken = function (token) { return tokens.push(token); };
16565 }
16566 if (isArray(options.onComment))
16567 { options.onComment = pushComment(options, options.onComment); }
16568
16569 return options
16570}
16571
16572function pushComment(options, array) {
16573 return function(block, text, start, end, startLoc, endLoc) {
16574 var comment = {
16575 type: block ? "Block" : "Line",
16576 value: text,
16577 start: start,
16578 end: end
16579 };
16580 if (options.locations)
16581 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
16582 if (options.ranges)
16583 { comment.range = [start, end]; }
16584 array.push(comment);
16585 }
16586}
16587
16588// Each scope gets a bitset that may contain these flags
16589var
16590 SCOPE_TOP = 1,
16591 SCOPE_FUNCTION = 2,
16592 SCOPE_ASYNC = 4,
16593 SCOPE_GENERATOR = 8,
16594 SCOPE_ARROW = 16,
16595 SCOPE_SIMPLE_CATCH = 32,
16596 SCOPE_SUPER = 64,
16597 SCOPE_DIRECT_SUPER = 128,
16598 SCOPE_CLASS_STATIC_BLOCK = 256,
16599 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
16600
16601function functionFlags(async, generator) {
16602 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
16603}
16604
16605// Used in checkLVal* and declareName to determine the type of a binding
16606var
16607 BIND_NONE = 0, // Not a binding
16608 BIND_VAR = 1, // Var-style binding
16609 BIND_LEXICAL = 2, // Let- or const-style binding
16610 BIND_FUNCTION = 3, // Function declaration
16611 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
16612 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
16613
16614var Parser = function Parser(options, input, startPos) {
16615 this.options = options = getOptions(options);
16616 this.sourceFile = options.sourceFile;
16617 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
16618 var reserved = "";
16619 if (options.allowReserved !== true) {
16620 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
16621 if (options.sourceType === "module") { reserved += " await"; }
16622 }
16623 this.reservedWords = wordsRegexp(reserved);
16624 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
16625 this.reservedWordsStrict = wordsRegexp(reservedStrict);
16626 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
16627 this.input = String(input);
16628
16629 // Used to signal to callers of `readWord1` whether the word
16630 // contained any escape sequences. This is needed because words with
16631 // escape sequences must not be interpreted as keywords.
16632 this.containsEsc = false;
16633
16634 // Set up token state
16635
16636 // The current position of the tokenizer in the input.
16637 if (startPos) {
16638 this.pos = startPos;
16639 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
16640 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
16641 } else {
16642 this.pos = this.lineStart = 0;
16643 this.curLine = 1;
16644 }
16645
16646 // Properties of the current token:
16647 // Its type
16648 this.type = types$1.eof;
16649 // For tokens that include more information than their type, the value
16650 this.value = null;
16651 // Its start and end offset
16652 this.start = this.end = this.pos;
16653 // And, if locations are used, the {line, column} object
16654 // corresponding to those offsets
16655 this.startLoc = this.endLoc = this.curPosition();
16656
16657 // Position information for the previous token
16658 this.lastTokEndLoc = this.lastTokStartLoc = null;
16659 this.lastTokStart = this.lastTokEnd = this.pos;
16660
16661 // The context stack is used to superficially track syntactic
16662 // context to predict whether a regular expression is allowed in a
16663 // given position.
16664 this.context = this.initialContext();
16665 this.exprAllowed = true;
16666
16667 // Figure out if it's a module code.
16668 this.inModule = options.sourceType === "module";
16669 this.strict = this.inModule || this.strictDirective(this.pos);
16670
16671 // Used to signify the start of a potential arrow function
16672 this.potentialArrowAt = -1;
16673 this.potentialArrowInForAwait = false;
16674
16675 // Positions to delayed-check that yield/await does not exist in default parameters.
16676 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
16677 // Labels in scope.
16678 this.labels = [];
16679 // Thus-far undefined exports.
16680 this.undefinedExports = Object.create(null);
16681
16682 // If enabled, skip leading hashbang line.
16683 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
16684 { this.skipLineComment(2); }
16685
16686 // Scope tracking for duplicate variable names (see scope.js)
16687 this.scopeStack = [];
16688 this.enterScope(SCOPE_TOP);
16689
16690 // For RegExp validation
16691 this.regexpState = null;
16692
16693 // The stack of private names.
16694 // Each element has two properties: 'declared' and 'used'.
16695 // When it exited from the outermost class definition, all used private names must be declared.
16696 this.privateNameStack = [];
16697};
16698
16699var 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 } };
16700
16701Parser.prototype.parse = function parse () {
16702 var node = this.options.program || this.startNode();
16703 this.nextToken();
16704 return this.parseTopLevel(node)
16705};
16706
16707prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
16708
16709prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
16710
16711prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
16712
16713prototypeAccessors.canAwait.get = function () {
16714 for (var i = this.scopeStack.length - 1; i >= 0; i--) {
16715 var scope = this.scopeStack[i];
16716 if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
16717 if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
16718 }
16719 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
16720};
16721
16722prototypeAccessors.allowSuper.get = function () {
16723 var ref = this.currentThisScope();
16724 var flags = ref.flags;
16725 var inClassFieldInit = ref.inClassFieldInit;
16726 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
16727};
16728
16729prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
16730
16731prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
16732
16733prototypeAccessors.allowNewDotTarget.get = function () {
16734 var ref = this.currentThisScope();
16735 var flags = ref.flags;
16736 var inClassFieldInit = ref.inClassFieldInit;
16737 return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
16738};
16739
16740prototypeAccessors.inClassStaticBlock.get = function () {
16741 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
16742};
16743
16744Parser.extend = function extend () {
16745 var plugins = [], len = arguments.length;
16746 while ( len-- ) plugins[ len ] = arguments[ len ];
16747
16748 var cls = this;
16749 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
16750 return cls
16751};
16752
16753Parser.parse = function parse (input, options) {
16754 return new this(options, input).parse()
16755};
16756
16757Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
16758 var parser = new this(options, input, pos);
16759 parser.nextToken();
16760 return parser.parseExpression()
16761};
16762
16763Parser.tokenizer = function tokenizer (input, options) {
16764 return new this(options, input)
16765};
16766
16767Object.defineProperties( Parser.prototype, prototypeAccessors );
16768
16769var pp$9 = Parser.prototype;
16770
16771// ## Parser utilities
16772
16773var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
16774pp$9.strictDirective = function(start) {
16775 if (this.options.ecmaVersion < 5) { return false }
16776 for (;;) {
16777 // Try to find string literal.
16778 skipWhiteSpace.lastIndex = start;
16779 start += skipWhiteSpace.exec(this.input)[0].length;
16780 var match = literal.exec(this.input.slice(start));
16781 if (!match) { return false }
16782 if ((match[1] || match[2]) === "use strict") {
16783 skipWhiteSpace.lastIndex = start + match[0].length;
16784 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
16785 var next = this.input.charAt(end);
16786 return next === ";" || next === "}" ||
16787 (lineBreak.test(spaceAfter[0]) &&
16788 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
16789 }
16790 start += match[0].length;
16791
16792 // Skip semicolon, if any.
16793 skipWhiteSpace.lastIndex = start;
16794 start += skipWhiteSpace.exec(this.input)[0].length;
16795 if (this.input[start] === ";")
16796 { start++; }
16797 }
16798};
16799
16800// Predicate that tests whether the next token is of the given
16801// type, and if yes, consumes it as a side effect.
16802
16803pp$9.eat = function(type) {
16804 if (this.type === type) {
16805 this.next();
16806 return true
16807 } else {
16808 return false
16809 }
16810};
16811
16812// Tests whether parsed token is a contextual keyword.
16813
16814pp$9.isContextual = function(name) {
16815 return this.type === types$1.name && this.value === name && !this.containsEsc
16816};
16817
16818// Consumes contextual keyword if possible.
16819
16820pp$9.eatContextual = function(name) {
16821 if (!this.isContextual(name)) { return false }
16822 this.next();
16823 return true
16824};
16825
16826// Asserts that following token is given contextual keyword.
16827
16828pp$9.expectContextual = function(name) {
16829 if (!this.eatContextual(name)) { this.unexpected(); }
16830};
16831
16832// Test whether a semicolon can be inserted at the current position.
16833
16834pp$9.canInsertSemicolon = function() {
16835 return this.type === types$1.eof ||
16836 this.type === types$1.braceR ||
16837 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
16838};
16839
16840pp$9.insertSemicolon = function() {
16841 if (this.canInsertSemicolon()) {
16842 if (this.options.onInsertedSemicolon)
16843 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
16844 return true
16845 }
16846};
16847
16848// Consume a semicolon, or, failing that, see if we are allowed to
16849// pretend that there is a semicolon at this position.
16850
16851pp$9.semicolon = function() {
16852 if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
16853};
16854
16855pp$9.afterTrailingComma = function(tokType, notNext) {
16856 if (this.type === tokType) {
16857 if (this.options.onTrailingComma)
16858 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
16859 if (!notNext)
16860 { this.next(); }
16861 return true
16862 }
16863};
16864
16865// Expect a token of a given type. If found, consume it, otherwise,
16866// raise an unexpected token error.
16867
16868pp$9.expect = function(type) {
16869 this.eat(type) || this.unexpected();
16870};
16871
16872// Raise an unexpected token error.
16873
16874pp$9.unexpected = function(pos) {
16875 this.raise(pos != null ? pos : this.start, "Unexpected token");
16876};
16877
16878var DestructuringErrors = function DestructuringErrors() {
16879 this.shorthandAssign =
16880 this.trailingComma =
16881 this.parenthesizedAssign =
16882 this.parenthesizedBind =
16883 this.doubleProto =
16884 -1;
16885};
16886
16887pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
16888 if (!refDestructuringErrors) { return }
16889 if (refDestructuringErrors.trailingComma > -1)
16890 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
16891 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
16892 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
16893};
16894
16895pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
16896 if (!refDestructuringErrors) { return false }
16897 var shorthandAssign = refDestructuringErrors.shorthandAssign;
16898 var doubleProto = refDestructuringErrors.doubleProto;
16899 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
16900 if (shorthandAssign >= 0)
16901 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
16902 if (doubleProto >= 0)
16903 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
16904};
16905
16906pp$9.checkYieldAwaitInDefaultParams = function() {
16907 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
16908 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
16909 if (this.awaitPos)
16910 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
16911};
16912
16913pp$9.isSimpleAssignTarget = function(expr) {
16914 if (expr.type === "ParenthesizedExpression")
16915 { return this.isSimpleAssignTarget(expr.expression) }
16916 return expr.type === "Identifier" || expr.type === "MemberExpression"
16917};
16918
16919var pp$8 = Parser.prototype;
16920
16921// ### Statement parsing
16922
16923// Parse a program. Initializes the parser, reads any number of
16924// statements, and wraps them in a Program node. Optionally takes a
16925// `program` argument. If present, the statements will be appended
16926// to its body instead of creating a new node.
16927
16928pp$8.parseTopLevel = function(node) {
16929 var exports = Object.create(null);
16930 if (!node.body) { node.body = []; }
16931 while (this.type !== types$1.eof) {
16932 var stmt = this.parseStatement(null, true, exports);
16933 node.body.push(stmt);
16934 }
16935 if (this.inModule)
16936 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
16937 {
16938 var name = list[i];
16939
16940 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
16941 } }
16942 this.adaptDirectivePrologue(node.body);
16943 this.next();
16944 node.sourceType = this.options.sourceType;
16945 return this.finishNode(node, "Program")
16946};
16947
16948var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
16949
16950pp$8.isLet = function(context) {
16951 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
16952 skipWhiteSpace.lastIndex = this.pos;
16953 var skip = skipWhiteSpace.exec(this.input);
16954 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
16955 // For ambiguous cases, determine if a LexicalDeclaration (or only a
16956 // Statement) is allowed here. If context is not empty then only a Statement
16957 // is allowed. However, `let [` is an explicit negative lookahead for
16958 // ExpressionStatement, so special-case it first.
16959 if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
16960 if (context) { return false }
16961
16962 if (nextCh === 123) { return true } // '{'
16963 if (isIdentifierStart(nextCh, true)) {
16964 var pos = next + 1;
16965 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
16966 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
16967 var ident = this.input.slice(next, pos);
16968 if (!keywordRelationalOperator.test(ident)) { return true }
16969 }
16970 return false
16971};
16972
16973// check 'async [no LineTerminator here] function'
16974// - 'async /*foo*/ function' is OK.
16975// - 'async /*\n*/ function' is invalid.
16976pp$8.isAsyncFunction = function() {
16977 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
16978 { return false }
16979
16980 skipWhiteSpace.lastIndex = this.pos;
16981 var skip = skipWhiteSpace.exec(this.input);
16982 var next = this.pos + skip[0].length, after;
16983 return !lineBreak.test(this.input.slice(this.pos, next)) &&
16984 this.input.slice(next, next + 8) === "function" &&
16985 (next + 8 === this.input.length ||
16986 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
16987};
16988
16989// Parse a single statement.
16990//
16991// If expecting a statement and finding a slash operator, parse a
16992// regular expression literal. This is to handle cases like
16993// `if (foo) /blah/.exec(foo)`, where looking at the previous token
16994// does not help.
16995
16996pp$8.parseStatement = function(context, topLevel, exports) {
16997 var starttype = this.type, node = this.startNode(), kind;
16998
16999 if (this.isLet(context)) {
17000 starttype = types$1._var;
17001 kind = "let";
17002 }
17003
17004 // Most types of statements are recognized by the keyword they
17005 // start with. Many are trivial to parse, some require a bit of
17006 // complexity.
17007
17008 switch (starttype) {
17009 case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
17010 case types$1._debugger: return this.parseDebuggerStatement(node)
17011 case types$1._do: return this.parseDoStatement(node)
17012 case types$1._for: return this.parseForStatement(node)
17013 case types$1._function:
17014 // Function as sole body of either an if statement or a labeled statement
17015 // works, but not when it is part of a labeled statement that is the sole
17016 // body of an if statement.
17017 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
17018 return this.parseFunctionStatement(node, false, !context)
17019 case types$1._class:
17020 if (context) { this.unexpected(); }
17021 return this.parseClass(node, true)
17022 case types$1._if: return this.parseIfStatement(node)
17023 case types$1._return: return this.parseReturnStatement(node)
17024 case types$1._switch: return this.parseSwitchStatement(node)
17025 case types$1._throw: return this.parseThrowStatement(node)
17026 case types$1._try: return this.parseTryStatement(node)
17027 case types$1._const: case types$1._var:
17028 kind = kind || this.value;
17029 if (context && kind !== "var") { this.unexpected(); }
17030 return this.parseVarStatement(node, kind)
17031 case types$1._while: return this.parseWhileStatement(node)
17032 case types$1._with: return this.parseWithStatement(node)
17033 case types$1.braceL: return this.parseBlock(true, node)
17034 case types$1.semi: return this.parseEmptyStatement(node)
17035 case types$1._export:
17036 case types$1._import:
17037 if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
17038 skipWhiteSpace.lastIndex = this.pos;
17039 var skip = skipWhiteSpace.exec(this.input);
17040 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
17041 if (nextCh === 40 || nextCh === 46) // '(' or '.'
17042 { return this.parseExpressionStatement(node, this.parseExpression()) }
17043 }
17044
17045 if (!this.options.allowImportExportEverywhere) {
17046 if (!topLevel)
17047 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
17048 if (!this.inModule)
17049 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
17050 }
17051 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
17052
17053 // If the statement does not start with a statement keyword or a
17054 // brace, it's an ExpressionStatement or LabeledStatement. We
17055 // simply start parsing an expression, and afterwards, if the
17056 // next token is a colon and the expression was a simple
17057 // Identifier node, we switch to interpreting it as a label.
17058 default:
17059 if (this.isAsyncFunction()) {
17060 if (context) { this.unexpected(); }
17061 this.next();
17062 return this.parseFunctionStatement(node, true, !context)
17063 }
17064
17065 var maybeName = this.value, expr = this.parseExpression();
17066 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
17067 { return this.parseLabeledStatement(node, maybeName, expr, context) }
17068 else { return this.parseExpressionStatement(node, expr) }
17069 }
17070};
17071
17072pp$8.parseBreakContinueStatement = function(node, keyword) {
17073 var isBreak = keyword === "break";
17074 this.next();
17075 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
17076 else if (this.type !== types$1.name) { this.unexpected(); }
17077 else {
17078 node.label = this.parseIdent();
17079 this.semicolon();
17080 }
17081
17082 // Verify that there is an actual destination to break or
17083 // continue to.
17084 var i = 0;
17085 for (; i < this.labels.length; ++i) {
17086 var lab = this.labels[i];
17087 if (node.label == null || lab.name === node.label.name) {
17088 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
17089 if (node.label && isBreak) { break }
17090 }
17091 }
17092 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
17093 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
17094};
17095
17096pp$8.parseDebuggerStatement = function(node) {
17097 this.next();
17098 this.semicolon();
17099 return this.finishNode(node, "DebuggerStatement")
17100};
17101
17102pp$8.parseDoStatement = function(node) {
17103 this.next();
17104 this.labels.push(loopLabel);
17105 node.body = this.parseStatement("do");
17106 this.labels.pop();
17107 this.expect(types$1._while);
17108 node.test = this.parseParenExpression();
17109 if (this.options.ecmaVersion >= 6)
17110 { this.eat(types$1.semi); }
17111 else
17112 { this.semicolon(); }
17113 return this.finishNode(node, "DoWhileStatement")
17114};
17115
17116// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
17117// loop is non-trivial. Basically, we have to parse the init `var`
17118// statement or expression, disallowing the `in` operator (see
17119// the second parameter to `parseExpression`), and then check
17120// whether the next token is `in` or `of`. When there is no init
17121// part (semicolon immediately after the opening parenthesis), it
17122// is a regular `for` loop.
17123
17124pp$8.parseForStatement = function(node) {
17125 this.next();
17126 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
17127 this.labels.push(loopLabel);
17128 this.enterScope(0);
17129 this.expect(types$1.parenL);
17130 if (this.type === types$1.semi) {
17131 if (awaitAt > -1) { this.unexpected(awaitAt); }
17132 return this.parseFor(node, null)
17133 }
17134 var isLet = this.isLet();
17135 if (this.type === types$1._var || this.type === types$1._const || isLet) {
17136 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
17137 this.next();
17138 this.parseVar(init$1, true, kind);
17139 this.finishNode(init$1, "VariableDeclaration");
17140 if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
17141 if (this.options.ecmaVersion >= 9) {
17142 if (this.type === types$1._in) {
17143 if (awaitAt > -1) { this.unexpected(awaitAt); }
17144 } else { node.await = awaitAt > -1; }
17145 }
17146 return this.parseForIn(node, init$1)
17147 }
17148 if (awaitAt > -1) { this.unexpected(awaitAt); }
17149 return this.parseFor(node, init$1)
17150 }
17151 var startsWithLet = this.isContextual("let"), isForOf = false;
17152 var refDestructuringErrors = new DestructuringErrors;
17153 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
17154 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
17155 if (this.options.ecmaVersion >= 9) {
17156 if (this.type === types$1._in) {
17157 if (awaitAt > -1) { this.unexpected(awaitAt); }
17158 } else { node.await = awaitAt > -1; }
17159 }
17160 if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
17161 this.toAssignable(init, false, refDestructuringErrors);
17162 this.checkLValPattern(init);
17163 return this.parseForIn(node, init)
17164 } else {
17165 this.checkExpressionErrors(refDestructuringErrors, true);
17166 }
17167 if (awaitAt > -1) { this.unexpected(awaitAt); }
17168 return this.parseFor(node, init)
17169};
17170
17171pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
17172 this.next();
17173 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
17174};
17175
17176pp$8.parseIfStatement = function(node) {
17177 this.next();
17178 node.test = this.parseParenExpression();
17179 // allow function declarations in branches, but only in non-strict mode
17180 node.consequent = this.parseStatement("if");
17181 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
17182 return this.finishNode(node, "IfStatement")
17183};
17184
17185pp$8.parseReturnStatement = function(node) {
17186 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
17187 { this.raise(this.start, "'return' outside of function"); }
17188 this.next();
17189
17190 // In `return` (and `break`/`continue`), the keywords with
17191 // optional arguments, we eagerly look for a semicolon or the
17192 // possibility to insert one.
17193
17194 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
17195 else { node.argument = this.parseExpression(); this.semicolon(); }
17196 return this.finishNode(node, "ReturnStatement")
17197};
17198
17199pp$8.parseSwitchStatement = function(node) {
17200 this.next();
17201 node.discriminant = this.parseParenExpression();
17202 node.cases = [];
17203 this.expect(types$1.braceL);
17204 this.labels.push(switchLabel);
17205 this.enterScope(0);
17206
17207 // Statements under must be grouped (by label) in SwitchCase
17208 // nodes. `cur` is used to keep the node that we are currently
17209 // adding statements to.
17210
17211 var cur;
17212 for (var sawDefault = false; this.type !== types$1.braceR;) {
17213 if (this.type === types$1._case || this.type === types$1._default) {
17214 var isCase = this.type === types$1._case;
17215 if (cur) { this.finishNode(cur, "SwitchCase"); }
17216 node.cases.push(cur = this.startNode());
17217 cur.consequent = [];
17218 this.next();
17219 if (isCase) {
17220 cur.test = this.parseExpression();
17221 } else {
17222 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
17223 sawDefault = true;
17224 cur.test = null;
17225 }
17226 this.expect(types$1.colon);
17227 } else {
17228 if (!cur) { this.unexpected(); }
17229 cur.consequent.push(this.parseStatement(null));
17230 }
17231 }
17232 this.exitScope();
17233 if (cur) { this.finishNode(cur, "SwitchCase"); }
17234 this.next(); // Closing brace
17235 this.labels.pop();
17236 return this.finishNode(node, "SwitchStatement")
17237};
17238
17239pp$8.parseThrowStatement = function(node) {
17240 this.next();
17241 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
17242 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
17243 node.argument = this.parseExpression();
17244 this.semicolon();
17245 return this.finishNode(node, "ThrowStatement")
17246};
17247
17248// Reused empty array added for node fields that are always empty.
17249
17250var empty$1 = [];
17251
17252pp$8.parseTryStatement = function(node) {
17253 this.next();
17254 node.block = this.parseBlock();
17255 node.handler = null;
17256 if (this.type === types$1._catch) {
17257 var clause = this.startNode();
17258 this.next();
17259 if (this.eat(types$1.parenL)) {
17260 clause.param = this.parseBindingAtom();
17261 var simple = clause.param.type === "Identifier";
17262 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
17263 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
17264 this.expect(types$1.parenR);
17265 } else {
17266 if (this.options.ecmaVersion < 10) { this.unexpected(); }
17267 clause.param = null;
17268 this.enterScope(0);
17269 }
17270 clause.body = this.parseBlock(false);
17271 this.exitScope();
17272 node.handler = this.finishNode(clause, "CatchClause");
17273 }
17274 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
17275 if (!node.handler && !node.finalizer)
17276 { this.raise(node.start, "Missing catch or finally clause"); }
17277 return this.finishNode(node, "TryStatement")
17278};
17279
17280pp$8.parseVarStatement = function(node, kind) {
17281 this.next();
17282 this.parseVar(node, false, kind);
17283 this.semicolon();
17284 return this.finishNode(node, "VariableDeclaration")
17285};
17286
17287pp$8.parseWhileStatement = function(node) {
17288 this.next();
17289 node.test = this.parseParenExpression();
17290 this.labels.push(loopLabel);
17291 node.body = this.parseStatement("while");
17292 this.labels.pop();
17293 return this.finishNode(node, "WhileStatement")
17294};
17295
17296pp$8.parseWithStatement = function(node) {
17297 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
17298 this.next();
17299 node.object = this.parseParenExpression();
17300 node.body = this.parseStatement("with");
17301 return this.finishNode(node, "WithStatement")
17302};
17303
17304pp$8.parseEmptyStatement = function(node) {
17305 this.next();
17306 return this.finishNode(node, "EmptyStatement")
17307};
17308
17309pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
17310 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
17311 {
17312 var label = list[i$1];
17313
17314 if (label.name === maybeName)
17315 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
17316 } }
17317 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
17318 for (var i = this.labels.length - 1; i >= 0; i--) {
17319 var label$1 = this.labels[i];
17320 if (label$1.statementStart === node.start) {
17321 // Update information about previous labels on this node
17322 label$1.statementStart = this.start;
17323 label$1.kind = kind;
17324 } else { break }
17325 }
17326 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
17327 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
17328 this.labels.pop();
17329 node.label = expr;
17330 return this.finishNode(node, "LabeledStatement")
17331};
17332
17333pp$8.parseExpressionStatement = function(node, expr) {
17334 node.expression = expr;
17335 this.semicolon();
17336 return this.finishNode(node, "ExpressionStatement")
17337};
17338
17339// Parse a semicolon-enclosed block of statements, handling `"use
17340// strict"` declarations when `allowStrict` is true (used for
17341// function bodies).
17342
17343pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
17344 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
17345 if ( node === void 0 ) node = this.startNode();
17346
17347 node.body = [];
17348 this.expect(types$1.braceL);
17349 if (createNewLexicalScope) { this.enterScope(0); }
17350 while (this.type !== types$1.braceR) {
17351 var stmt = this.parseStatement(null);
17352 node.body.push(stmt);
17353 }
17354 if (exitStrict) { this.strict = false; }
17355 this.next();
17356 if (createNewLexicalScope) { this.exitScope(); }
17357 return this.finishNode(node, "BlockStatement")
17358};
17359
17360// Parse a regular `for` loop. The disambiguation code in
17361// `parseStatement` will already have parsed the init statement or
17362// expression.
17363
17364pp$8.parseFor = function(node, init) {
17365 node.init = init;
17366 this.expect(types$1.semi);
17367 node.test = this.type === types$1.semi ? null : this.parseExpression();
17368 this.expect(types$1.semi);
17369 node.update = this.type === types$1.parenR ? null : this.parseExpression();
17370 this.expect(types$1.parenR);
17371 node.body = this.parseStatement("for");
17372 this.exitScope();
17373 this.labels.pop();
17374 return this.finishNode(node, "ForStatement")
17375};
17376
17377// Parse a `for`/`in` and `for`/`of` loop, which are almost
17378// same from parser's perspective.
17379
17380pp$8.parseForIn = function(node, init) {
17381 var isForIn = this.type === types$1._in;
17382 this.next();
17383
17384 if (
17385 init.type === "VariableDeclaration" &&
17386 init.declarations[0].init != null &&
17387 (
17388 !isForIn ||
17389 this.options.ecmaVersion < 8 ||
17390 this.strict ||
17391 init.kind !== "var" ||
17392 init.declarations[0].id.type !== "Identifier"
17393 )
17394 ) {
17395 this.raise(
17396 init.start,
17397 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
17398 );
17399 }
17400 node.left = init;
17401 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
17402 this.expect(types$1.parenR);
17403 node.body = this.parseStatement("for");
17404 this.exitScope();
17405 this.labels.pop();
17406 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
17407};
17408
17409// Parse a list of variable declarations.
17410
17411pp$8.parseVar = function(node, isFor, kind) {
17412 node.declarations = [];
17413 node.kind = kind;
17414 for (;;) {
17415 var decl = this.startNode();
17416 this.parseVarId(decl, kind);
17417 if (this.eat(types$1.eq)) {
17418 decl.init = this.parseMaybeAssign(isFor);
17419 } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
17420 this.unexpected();
17421 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
17422 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
17423 } else {
17424 decl.init = null;
17425 }
17426 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
17427 if (!this.eat(types$1.comma)) { break }
17428 }
17429 return node
17430};
17431
17432pp$8.parseVarId = function(decl, kind) {
17433 decl.id = this.parseBindingAtom();
17434 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
17435};
17436
17437var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
17438
17439// Parse a function declaration or literal (depending on the
17440// `statement & FUNC_STATEMENT`).
17441
17442// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
17443pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
17444 this.initFunction(node);
17445 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
17446 if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
17447 { this.unexpected(); }
17448 node.generator = this.eat(types$1.star);
17449 }
17450 if (this.options.ecmaVersion >= 8)
17451 { node.async = !!isAsync; }
17452
17453 if (statement & FUNC_STATEMENT) {
17454 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
17455 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
17456 // If it is a regular function declaration in sloppy mode, then it is
17457 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
17458 // mode depends on properties of the current scope (see
17459 // treatFunctionsAsVar).
17460 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
17461 }
17462
17463 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
17464 this.yieldPos = 0;
17465 this.awaitPos = 0;
17466 this.awaitIdentPos = 0;
17467 this.enterScope(functionFlags(node.async, node.generator));
17468
17469 if (!(statement & FUNC_STATEMENT))
17470 { node.id = this.type === types$1.name ? this.parseIdent() : null; }
17471
17472 this.parseFunctionParams(node);
17473 this.parseFunctionBody(node, allowExpressionBody, false, forInit);
17474
17475 this.yieldPos = oldYieldPos;
17476 this.awaitPos = oldAwaitPos;
17477 this.awaitIdentPos = oldAwaitIdentPos;
17478 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
17479};
17480
17481pp$8.parseFunctionParams = function(node) {
17482 this.expect(types$1.parenL);
17483 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
17484 this.checkYieldAwaitInDefaultParams();
17485};
17486
17487// Parse a class declaration or literal (depending on the
17488// `isStatement` parameter).
17489
17490pp$8.parseClass = function(node, isStatement) {
17491 this.next();
17492
17493 // ecma-262 14.6 Class Definitions
17494 // A class definition is always strict mode code.
17495 var oldStrict = this.strict;
17496 this.strict = true;
17497
17498 this.parseClassId(node, isStatement);
17499 this.parseClassSuper(node);
17500 var privateNameMap = this.enterClassBody();
17501 var classBody = this.startNode();
17502 var hadConstructor = false;
17503 classBody.body = [];
17504 this.expect(types$1.braceL);
17505 while (this.type !== types$1.braceR) {
17506 var element = this.parseClassElement(node.superClass !== null);
17507 if (element) {
17508 classBody.body.push(element);
17509 if (element.type === "MethodDefinition" && element.kind === "constructor") {
17510 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
17511 hadConstructor = true;
17512 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
17513 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
17514 }
17515 }
17516 }
17517 this.strict = oldStrict;
17518 this.next();
17519 node.body = this.finishNode(classBody, "ClassBody");
17520 this.exitClassBody();
17521 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
17522};
17523
17524pp$8.parseClassElement = function(constructorAllowsSuper) {
17525 if (this.eat(types$1.semi)) { return null }
17526
17527 var ecmaVersion = this.options.ecmaVersion;
17528 var node = this.startNode();
17529 var keyName = "";
17530 var isGenerator = false;
17531 var isAsync = false;
17532 var kind = "method";
17533 var isStatic = false;
17534
17535 if (this.eatContextual("static")) {
17536 // Parse static init block
17537 if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
17538 this.parseClassStaticBlock(node);
17539 return node
17540 }
17541 if (this.isClassElementNameStart() || this.type === types$1.star) {
17542 isStatic = true;
17543 } else {
17544 keyName = "static";
17545 }
17546 }
17547 node.static = isStatic;
17548 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
17549 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
17550 isAsync = true;
17551 } else {
17552 keyName = "async";
17553 }
17554 }
17555 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
17556 isGenerator = true;
17557 }
17558 if (!keyName && !isAsync && !isGenerator) {
17559 var lastValue = this.value;
17560 if (this.eatContextual("get") || this.eatContextual("set")) {
17561 if (this.isClassElementNameStart()) {
17562 kind = lastValue;
17563 } else {
17564 keyName = lastValue;
17565 }
17566 }
17567 }
17568
17569 // Parse element name
17570 if (keyName) {
17571 // 'async', 'get', 'set', or 'static' were not a keyword contextually.
17572 // The last token is any of those. Make it the element name.
17573 node.computed = false;
17574 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
17575 node.key.name = keyName;
17576 this.finishNode(node.key, "Identifier");
17577 } else {
17578 this.parseClassElementName(node);
17579 }
17580
17581 // Parse element value
17582 if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
17583 var isConstructor = !node.static && checkKeyName(node, "constructor");
17584 var allowsDirectSuper = isConstructor && constructorAllowsSuper;
17585 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
17586 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
17587 node.kind = isConstructor ? "constructor" : kind;
17588 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
17589 } else {
17590 this.parseClassField(node);
17591 }
17592
17593 return node
17594};
17595
17596pp$8.isClassElementNameStart = function() {
17597 return (
17598 this.type === types$1.name ||
17599 this.type === types$1.privateId ||
17600 this.type === types$1.num ||
17601 this.type === types$1.string ||
17602 this.type === types$1.bracketL ||
17603 this.type.keyword
17604 )
17605};
17606
17607pp$8.parseClassElementName = function(element) {
17608 if (this.type === types$1.privateId) {
17609 if (this.value === "constructor") {
17610 this.raise(this.start, "Classes can't have an element named '#constructor'");
17611 }
17612 element.computed = false;
17613 element.key = this.parsePrivateIdent();
17614 } else {
17615 this.parsePropertyName(element);
17616 }
17617};
17618
17619pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
17620 // Check key and flags
17621 var key = method.key;
17622 if (method.kind === "constructor") {
17623 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
17624 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
17625 } else if (method.static && checkKeyName(method, "prototype")) {
17626 this.raise(key.start, "Classes may not have a static property named prototype");
17627 }
17628
17629 // Parse value
17630 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
17631
17632 // Check value
17633 if (method.kind === "get" && value.params.length !== 0)
17634 { this.raiseRecoverable(value.start, "getter should have no params"); }
17635 if (method.kind === "set" && value.params.length !== 1)
17636 { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
17637 if (method.kind === "set" && value.params[0].type === "RestElement")
17638 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
17639
17640 return this.finishNode(method, "MethodDefinition")
17641};
17642
17643pp$8.parseClassField = function(field) {
17644 if (checkKeyName(field, "constructor")) {
17645 this.raise(field.key.start, "Classes can't have a field named 'constructor'");
17646 } else if (field.static && checkKeyName(field, "prototype")) {
17647 this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
17648 }
17649
17650 if (this.eat(types$1.eq)) {
17651 // To raise SyntaxError if 'arguments' exists in the initializer.
17652 var scope = this.currentThisScope();
17653 var inClassFieldInit = scope.inClassFieldInit;
17654 scope.inClassFieldInit = true;
17655 field.value = this.parseMaybeAssign();
17656 scope.inClassFieldInit = inClassFieldInit;
17657 } else {
17658 field.value = null;
17659 }
17660 this.semicolon();
17661
17662 return this.finishNode(field, "PropertyDefinition")
17663};
17664
17665pp$8.parseClassStaticBlock = function(node) {
17666 node.body = [];
17667
17668 var oldLabels = this.labels;
17669 this.labels = [];
17670 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
17671 while (this.type !== types$1.braceR) {
17672 var stmt = this.parseStatement(null);
17673 node.body.push(stmt);
17674 }
17675 this.next();
17676 this.exitScope();
17677 this.labels = oldLabels;
17678
17679 return this.finishNode(node, "StaticBlock")
17680};
17681
17682pp$8.parseClassId = function(node, isStatement) {
17683 if (this.type === types$1.name) {
17684 node.id = this.parseIdent();
17685 if (isStatement)
17686 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
17687 } else {
17688 if (isStatement === true)
17689 { this.unexpected(); }
17690 node.id = null;
17691 }
17692};
17693
17694pp$8.parseClassSuper = function(node) {
17695 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
17696};
17697
17698pp$8.enterClassBody = function() {
17699 var element = {declared: Object.create(null), used: []};
17700 this.privateNameStack.push(element);
17701 return element.declared
17702};
17703
17704pp$8.exitClassBody = function() {
17705 var ref = this.privateNameStack.pop();
17706 var declared = ref.declared;
17707 var used = ref.used;
17708 var len = this.privateNameStack.length;
17709 var parent = len === 0 ? null : this.privateNameStack[len - 1];
17710 for (var i = 0; i < used.length; ++i) {
17711 var id = used[i];
17712 if (!hasOwn(declared, id.name)) {
17713 if (parent) {
17714 parent.used.push(id);
17715 } else {
17716 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
17717 }
17718 }
17719 }
17720};
17721
17722function isPrivateNameConflicted(privateNameMap, element) {
17723 var name = element.key.name;
17724 var curr = privateNameMap[name];
17725
17726 var next = "true";
17727 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
17728 next = (element.static ? "s" : "i") + element.kind;
17729 }
17730
17731 // `class { get #a(){}; static set #a(_){} }` is also conflict.
17732 if (
17733 curr === "iget" && next === "iset" ||
17734 curr === "iset" && next === "iget" ||
17735 curr === "sget" && next === "sset" ||
17736 curr === "sset" && next === "sget"
17737 ) {
17738 privateNameMap[name] = "true";
17739 return false
17740 } else if (!curr) {
17741 privateNameMap[name] = next;
17742 return false
17743 } else {
17744 return true
17745 }
17746}
17747
17748function checkKeyName(node, name) {
17749 var computed = node.computed;
17750 var key = node.key;
17751 return !computed && (
17752 key.type === "Identifier" && key.name === name ||
17753 key.type === "Literal" && key.value === name
17754 )
17755}
17756
17757// Parses module export declaration.
17758
17759pp$8.parseExport = function(node, exports) {
17760 this.next();
17761 // export * from '...'
17762 if (this.eat(types$1.star)) {
17763 if (this.options.ecmaVersion >= 11) {
17764 if (this.eatContextual("as")) {
17765 node.exported = this.parseModuleExportName();
17766 this.checkExport(exports, node.exported, this.lastTokStart);
17767 } else {
17768 node.exported = null;
17769 }
17770 }
17771 this.expectContextual("from");
17772 if (this.type !== types$1.string) { this.unexpected(); }
17773 node.source = this.parseExprAtom();
17774 this.semicolon();
17775 return this.finishNode(node, "ExportAllDeclaration")
17776 }
17777 if (this.eat(types$1._default)) { // export default ...
17778 this.checkExport(exports, "default", this.lastTokStart);
17779 var isAsync;
17780 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
17781 var fNode = this.startNode();
17782 this.next();
17783 if (isAsync) { this.next(); }
17784 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
17785 } else if (this.type === types$1._class) {
17786 var cNode = this.startNode();
17787 node.declaration = this.parseClass(cNode, "nullableID");
17788 } else {
17789 node.declaration = this.parseMaybeAssign();
17790 this.semicolon();
17791 }
17792 return this.finishNode(node, "ExportDefaultDeclaration")
17793 }
17794 // export var|const|let|function|class ...
17795 if (this.shouldParseExportStatement()) {
17796 node.declaration = this.parseStatement(null);
17797 if (node.declaration.type === "VariableDeclaration")
17798 { this.checkVariableExport(exports, node.declaration.declarations); }
17799 else
17800 { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
17801 node.specifiers = [];
17802 node.source = null;
17803 } else { // export { x, y as z } [from '...']
17804 node.declaration = null;
17805 node.specifiers = this.parseExportSpecifiers(exports);
17806 if (this.eatContextual("from")) {
17807 if (this.type !== types$1.string) { this.unexpected(); }
17808 node.source = this.parseExprAtom();
17809 } else {
17810 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
17811 // check for keywords used as local names
17812 var spec = list[i];
17813
17814 this.checkUnreserved(spec.local);
17815 // check if export is defined
17816 this.checkLocalExport(spec.local);
17817
17818 if (spec.local.type === "Literal") {
17819 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
17820 }
17821 }
17822
17823 node.source = null;
17824 }
17825 this.semicolon();
17826 }
17827 return this.finishNode(node, "ExportNamedDeclaration")
17828};
17829
17830pp$8.checkExport = function(exports, name, pos) {
17831 if (!exports) { return }
17832 if (typeof name !== "string")
17833 { name = name.type === "Identifier" ? name.name : name.value; }
17834 if (hasOwn(exports, name))
17835 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
17836 exports[name] = true;
17837};
17838
17839pp$8.checkPatternExport = function(exports, pat) {
17840 var type = pat.type;
17841 if (type === "Identifier")
17842 { this.checkExport(exports, pat, pat.start); }
17843 else if (type === "ObjectPattern")
17844 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
17845 {
17846 var prop = list[i];
17847
17848 this.checkPatternExport(exports, prop);
17849 } }
17850 else if (type === "ArrayPattern")
17851 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
17852 var elt = list$1[i$1];
17853
17854 if (elt) { this.checkPatternExport(exports, elt); }
17855 } }
17856 else if (type === "Property")
17857 { this.checkPatternExport(exports, pat.value); }
17858 else if (type === "AssignmentPattern")
17859 { this.checkPatternExport(exports, pat.left); }
17860 else if (type === "RestElement")
17861 { this.checkPatternExport(exports, pat.argument); }
17862 else if (type === "ParenthesizedExpression")
17863 { this.checkPatternExport(exports, pat.expression); }
17864};
17865
17866pp$8.checkVariableExport = function(exports, decls) {
17867 if (!exports) { return }
17868 for (var i = 0, list = decls; i < list.length; i += 1)
17869 {
17870 var decl = list[i];
17871
17872 this.checkPatternExport(exports, decl.id);
17873 }
17874};
17875
17876pp$8.shouldParseExportStatement = function() {
17877 return this.type.keyword === "var" ||
17878 this.type.keyword === "const" ||
17879 this.type.keyword === "class" ||
17880 this.type.keyword === "function" ||
17881 this.isLet() ||
17882 this.isAsyncFunction()
17883};
17884
17885// Parses a comma-separated list of module exports.
17886
17887pp$8.parseExportSpecifiers = function(exports) {
17888 var nodes = [], first = true;
17889 // export { x, y as z } [from '...']
17890 this.expect(types$1.braceL);
17891 while (!this.eat(types$1.braceR)) {
17892 if (!first) {
17893 this.expect(types$1.comma);
17894 if (this.afterTrailingComma(types$1.braceR)) { break }
17895 } else { first = false; }
17896
17897 var node = this.startNode();
17898 node.local = this.parseModuleExportName();
17899 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
17900 this.checkExport(
17901 exports,
17902 node.exported,
17903 node.exported.start
17904 );
17905 nodes.push(this.finishNode(node, "ExportSpecifier"));
17906 }
17907 return nodes
17908};
17909
17910// Parses import declaration.
17911
17912pp$8.parseImport = function(node) {
17913 this.next();
17914 // import '...'
17915 if (this.type === types$1.string) {
17916 node.specifiers = empty$1;
17917 node.source = this.parseExprAtom();
17918 } else {
17919 node.specifiers = this.parseImportSpecifiers();
17920 this.expectContextual("from");
17921 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
17922 }
17923 this.semicolon();
17924 return this.finishNode(node, "ImportDeclaration")
17925};
17926
17927// Parses a comma-separated list of module imports.
17928
17929pp$8.parseImportSpecifiers = function() {
17930 var nodes = [], first = true;
17931 if (this.type === types$1.name) {
17932 // import defaultObj, { x, y as z } from '...'
17933 var node = this.startNode();
17934 node.local = this.parseIdent();
17935 this.checkLValSimple(node.local, BIND_LEXICAL);
17936 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
17937 if (!this.eat(types$1.comma)) { return nodes }
17938 }
17939 if (this.type === types$1.star) {
17940 var node$1 = this.startNode();
17941 this.next();
17942 this.expectContextual("as");
17943 node$1.local = this.parseIdent();
17944 this.checkLValSimple(node$1.local, BIND_LEXICAL);
17945 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
17946 return nodes
17947 }
17948 this.expect(types$1.braceL);
17949 while (!this.eat(types$1.braceR)) {
17950 if (!first) {
17951 this.expect(types$1.comma);
17952 if (this.afterTrailingComma(types$1.braceR)) { break }
17953 } else { first = false; }
17954
17955 var node$2 = this.startNode();
17956 node$2.imported = this.parseModuleExportName();
17957 if (this.eatContextual("as")) {
17958 node$2.local = this.parseIdent();
17959 } else {
17960 this.checkUnreserved(node$2.imported);
17961 node$2.local = node$2.imported;
17962 }
17963 this.checkLValSimple(node$2.local, BIND_LEXICAL);
17964 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
17965 }
17966 return nodes
17967};
17968
17969pp$8.parseModuleExportName = function() {
17970 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
17971 var stringLiteral = this.parseLiteral(this.value);
17972 if (loneSurrogate.test(stringLiteral.value)) {
17973 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
17974 }
17975 return stringLiteral
17976 }
17977 return this.parseIdent(true)
17978};
17979
17980// Set `ExpressionStatement#directive` property for directive prologues.
17981pp$8.adaptDirectivePrologue = function(statements) {
17982 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
17983 statements[i].directive = statements[i].expression.raw.slice(1, -1);
17984 }
17985};
17986pp$8.isDirectiveCandidate = function(statement) {
17987 return (
17988 statement.type === "ExpressionStatement" &&
17989 statement.expression.type === "Literal" &&
17990 typeof statement.expression.value === "string" &&
17991 // Reject parenthesized strings.
17992 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
17993 )
17994};
17995
17996var pp$7 = Parser.prototype;
17997
17998// Convert existing expression atom to assignable pattern
17999// if possible.
18000
18001pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
18002 if (this.options.ecmaVersion >= 6 && node) {
18003 switch (node.type) {
18004 case "Identifier":
18005 if (this.inAsync && node.name === "await")
18006 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
18007 break
18008
18009 case "ObjectPattern":
18010 case "ArrayPattern":
18011 case "AssignmentPattern":
18012 case "RestElement":
18013 break
18014
18015 case "ObjectExpression":
18016 node.type = "ObjectPattern";
18017 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18018 for (var i = 0, list = node.properties; i < list.length; i += 1) {
18019 var prop = list[i];
18020
18021 this.toAssignable(prop, isBinding);
18022 // Early error:
18023 // AssignmentRestProperty[Yield, Await] :
18024 // `...` DestructuringAssignmentTarget[Yield, Await]
18025 //
18026 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
18027 if (
18028 prop.type === "RestElement" &&
18029 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
18030 ) {
18031 this.raise(prop.argument.start, "Unexpected token");
18032 }
18033 }
18034 break
18035
18036 case "Property":
18037 // AssignmentProperty has type === "Property"
18038 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
18039 this.toAssignable(node.value, isBinding);
18040 break
18041
18042 case "ArrayExpression":
18043 node.type = "ArrayPattern";
18044 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18045 this.toAssignableList(node.elements, isBinding);
18046 break
18047
18048 case "SpreadElement":
18049 node.type = "RestElement";
18050 this.toAssignable(node.argument, isBinding);
18051 if (node.argument.type === "AssignmentPattern")
18052 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
18053 break
18054
18055 case "AssignmentExpression":
18056 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
18057 node.type = "AssignmentPattern";
18058 delete node.operator;
18059 this.toAssignable(node.left, isBinding);
18060 break
18061
18062 case "ParenthesizedExpression":
18063 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
18064 break
18065
18066 case "ChainExpression":
18067 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
18068 break
18069
18070 case "MemberExpression":
18071 if (!isBinding) { break }
18072
18073 default:
18074 this.raise(node.start, "Assigning to rvalue");
18075 }
18076 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
18077 return node
18078};
18079
18080// Convert list of expression atoms to binding list.
18081
18082pp$7.toAssignableList = function(exprList, isBinding) {
18083 var end = exprList.length;
18084 for (var i = 0; i < end; i++) {
18085 var elt = exprList[i];
18086 if (elt) { this.toAssignable(elt, isBinding); }
18087 }
18088 if (end) {
18089 var last = exprList[end - 1];
18090 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
18091 { this.unexpected(last.argument.start); }
18092 }
18093 return exprList
18094};
18095
18096// Parses spread element.
18097
18098pp$7.parseSpread = function(refDestructuringErrors) {
18099 var node = this.startNode();
18100 this.next();
18101 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
18102 return this.finishNode(node, "SpreadElement")
18103};
18104
18105pp$7.parseRestBinding = function() {
18106 var node = this.startNode();
18107 this.next();
18108
18109 // RestElement inside of a function parameter must be an identifier
18110 if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
18111 { this.unexpected(); }
18112
18113 node.argument = this.parseBindingAtom();
18114
18115 return this.finishNode(node, "RestElement")
18116};
18117
18118// Parses lvalue (assignable) atom.
18119
18120pp$7.parseBindingAtom = function() {
18121 if (this.options.ecmaVersion >= 6) {
18122 switch (this.type) {
18123 case types$1.bracketL:
18124 var node = this.startNode();
18125 this.next();
18126 node.elements = this.parseBindingList(types$1.bracketR, true, true);
18127 return this.finishNode(node, "ArrayPattern")
18128
18129 case types$1.braceL:
18130 return this.parseObj(true)
18131 }
18132 }
18133 return this.parseIdent()
18134};
18135
18136pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
18137 var elts = [], first = true;
18138 while (!this.eat(close)) {
18139 if (first) { first = false; }
18140 else { this.expect(types$1.comma); }
18141 if (allowEmpty && this.type === types$1.comma) {
18142 elts.push(null);
18143 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
18144 break
18145 } else if (this.type === types$1.ellipsis) {
18146 var rest = this.parseRestBinding();
18147 this.parseBindingListItem(rest);
18148 elts.push(rest);
18149 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
18150 this.expect(close);
18151 break
18152 } else {
18153 var elem = this.parseMaybeDefault(this.start, this.startLoc);
18154 this.parseBindingListItem(elem);
18155 elts.push(elem);
18156 }
18157 }
18158 return elts
18159};
18160
18161pp$7.parseBindingListItem = function(param) {
18162 return param
18163};
18164
18165// Parses assignment pattern around given atom if possible.
18166
18167pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
18168 left = left || this.parseBindingAtom();
18169 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
18170 var node = this.startNodeAt(startPos, startLoc);
18171 node.left = left;
18172 node.right = this.parseMaybeAssign();
18173 return this.finishNode(node, "AssignmentPattern")
18174};
18175
18176// The following three functions all verify that a node is an lvalue —
18177// something that can be bound, or assigned to. In order to do so, they perform
18178// a variety of checks:
18179//
18180// - Check that none of the bound/assigned-to identifiers are reserved words.
18181// - Record name declarations for bindings in the appropriate scope.
18182// - Check duplicate argument names, if checkClashes is set.
18183//
18184// If a complex binding pattern is encountered (e.g., object and array
18185// destructuring), the entire pattern is recursively checked.
18186//
18187// There are three versions of checkLVal*() appropriate for different
18188// circumstances:
18189//
18190// - checkLValSimple() shall be used if the syntactic construct supports
18191// nothing other than identifiers and member expressions. Parenthesized
18192// expressions are also correctly handled. This is generally appropriate for
18193// constructs for which the spec says
18194//
18195// > It is a Syntax Error if AssignmentTargetType of [the production] is not
18196// > simple.
18197//
18198// It is also appropriate for checking if an identifier is valid and not
18199// defined elsewhere, like import declarations or function/class identifiers.
18200//
18201// Examples where this is used include:
18202// a += …;
18203// import a from '…';
18204// where a is the node to be checked.
18205//
18206// - checkLValPattern() shall be used if the syntactic construct supports
18207// anything checkLValSimple() supports, as well as object and array
18208// destructuring patterns. This is generally appropriate for constructs for
18209// which the spec says
18210//
18211// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
18212// > an ArrayLiteral and AssignmentTargetType of [the production] is not
18213// > simple.
18214//
18215// Examples where this is used include:
18216// (a = …);
18217// const a = …;
18218// try { … } catch (a) { … }
18219// where a is the node to be checked.
18220//
18221// - checkLValInnerPattern() shall be used if the syntactic construct supports
18222// anything checkLValPattern() supports, as well as default assignment
18223// patterns, rest elements, and other constructs that may appear within an
18224// object or array destructuring pattern.
18225//
18226// As a special case, function parameters also use checkLValInnerPattern(),
18227// as they also support defaults and rest constructs.
18228//
18229// These functions deliberately support both assignment and binding constructs,
18230// as the logic for both is exceedingly similar. If the node is the target of
18231// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
18232// should be set to the appropriate BIND_* constant, like BIND_VAR or
18233// BIND_LEXICAL.
18234//
18235// If the function is called with a non-BIND_NONE bindingType, then
18236// additionally a checkClashes object may be specified to allow checking for
18237// duplicate argument names. checkClashes is ignored if the provided construct
18238// is an assignment (i.e., bindingType is BIND_NONE).
18239
18240pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
18241 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18242
18243 var isBind = bindingType !== BIND_NONE;
18244
18245 switch (expr.type) {
18246 case "Identifier":
18247 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
18248 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
18249 if (isBind) {
18250 if (bindingType === BIND_LEXICAL && expr.name === "let")
18251 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
18252 if (checkClashes) {
18253 if (hasOwn(checkClashes, expr.name))
18254 { this.raiseRecoverable(expr.start, "Argument name clash"); }
18255 checkClashes[expr.name] = true;
18256 }
18257 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
18258 }
18259 break
18260
18261 case "ChainExpression":
18262 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
18263 break
18264
18265 case "MemberExpression":
18266 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
18267 break
18268
18269 case "ParenthesizedExpression":
18270 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
18271 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
18272
18273 default:
18274 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
18275 }
18276};
18277
18278pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
18279 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18280
18281 switch (expr.type) {
18282 case "ObjectPattern":
18283 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
18284 var prop = list[i];
18285
18286 this.checkLValInnerPattern(prop, bindingType, checkClashes);
18287 }
18288 break
18289
18290 case "ArrayPattern":
18291 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
18292 var elem = list$1[i$1];
18293
18294 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
18295 }
18296 break
18297
18298 default:
18299 this.checkLValSimple(expr, bindingType, checkClashes);
18300 }
18301};
18302
18303pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
18304 if ( bindingType === void 0 ) bindingType = BIND_NONE;
18305
18306 switch (expr.type) {
18307 case "Property":
18308 // AssignmentProperty has type === "Property"
18309 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
18310 break
18311
18312 case "AssignmentPattern":
18313 this.checkLValPattern(expr.left, bindingType, checkClashes);
18314 break
18315
18316 case "RestElement":
18317 this.checkLValPattern(expr.argument, bindingType, checkClashes);
18318 break
18319
18320 default:
18321 this.checkLValPattern(expr, bindingType, checkClashes);
18322 }
18323};
18324
18325// The algorithm used to determine whether a regexp can appear at a
18326
18327var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
18328 this.token = token;
18329 this.isExpr = !!isExpr;
18330 this.preserveSpace = !!preserveSpace;
18331 this.override = override;
18332 this.generator = !!generator;
18333};
18334
18335var types = {
18336 b_stat: new TokContext("{", false),
18337 b_expr: new TokContext("{", true),
18338 b_tmpl: new TokContext("${", false),
18339 p_stat: new TokContext("(", false),
18340 p_expr: new TokContext("(", true),
18341 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
18342 f_stat: new TokContext("function", false),
18343 f_expr: new TokContext("function", true),
18344 f_expr_gen: new TokContext("function", true, false, null, true),
18345 f_gen: new TokContext("function", false, false, null, true)
18346};
18347
18348var pp$6 = Parser.prototype;
18349
18350pp$6.initialContext = function() {
18351 return [types.b_stat]
18352};
18353
18354pp$6.curContext = function() {
18355 return this.context[this.context.length - 1]
18356};
18357
18358pp$6.braceIsBlock = function(prevType) {
18359 var parent = this.curContext();
18360 if (parent === types.f_expr || parent === types.f_stat)
18361 { return true }
18362 if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
18363 { return !parent.isExpr }
18364
18365 // The check for `tt.name && exprAllowed` detects whether we are
18366 // after a `yield` or `of` construct. See the `updateContext` for
18367 // `tt.name`.
18368 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
18369 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
18370 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
18371 { return true }
18372 if (prevType === types$1.braceL)
18373 { return parent === types.b_stat }
18374 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
18375 { return false }
18376 return !this.exprAllowed
18377};
18378
18379pp$6.inGeneratorContext = function() {
18380 for (var i = this.context.length - 1; i >= 1; i--) {
18381 var context = this.context[i];
18382 if (context.token === "function")
18383 { return context.generator }
18384 }
18385 return false
18386};
18387
18388pp$6.updateContext = function(prevType) {
18389 var update, type = this.type;
18390 if (type.keyword && prevType === types$1.dot)
18391 { this.exprAllowed = false; }
18392 else if (update = type.updateContext)
18393 { update.call(this, prevType); }
18394 else
18395 { this.exprAllowed = type.beforeExpr; }
18396};
18397
18398// Used to handle egde case when token context could not be inferred correctly in tokenize phase
18399pp$6.overrideContext = function(tokenCtx) {
18400 if (this.curContext() !== tokenCtx) {
18401 this.context[this.context.length - 1] = tokenCtx;
18402 }
18403};
18404
18405// Token-specific context update code
18406
18407types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
18408 if (this.context.length === 1) {
18409 this.exprAllowed = true;
18410 return
18411 }
18412 var out = this.context.pop();
18413 if (out === types.b_stat && this.curContext().token === "function") {
18414 out = this.context.pop();
18415 }
18416 this.exprAllowed = !out.isExpr;
18417};
18418
18419types$1.braceL.updateContext = function(prevType) {
18420 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
18421 this.exprAllowed = true;
18422};
18423
18424types$1.dollarBraceL.updateContext = function() {
18425 this.context.push(types.b_tmpl);
18426 this.exprAllowed = true;
18427};
18428
18429types$1.parenL.updateContext = function(prevType) {
18430 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
18431 this.context.push(statementParens ? types.p_stat : types.p_expr);
18432 this.exprAllowed = true;
18433};
18434
18435types$1.incDec.updateContext = function() {
18436 // tokExprAllowed stays unchanged
18437};
18438
18439types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
18440 if (prevType.beforeExpr && prevType !== types$1._else &&
18441 !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
18442 !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
18443 !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
18444 { this.context.push(types.f_expr); }
18445 else
18446 { this.context.push(types.f_stat); }
18447 this.exprAllowed = false;
18448};
18449
18450types$1.backQuote.updateContext = function() {
18451 if (this.curContext() === types.q_tmpl)
18452 { this.context.pop(); }
18453 else
18454 { this.context.push(types.q_tmpl); }
18455 this.exprAllowed = false;
18456};
18457
18458types$1.star.updateContext = function(prevType) {
18459 if (prevType === types$1._function) {
18460 var index = this.context.length - 1;
18461 if (this.context[index] === types.f_expr)
18462 { this.context[index] = types.f_expr_gen; }
18463 else
18464 { this.context[index] = types.f_gen; }
18465 }
18466 this.exprAllowed = true;
18467};
18468
18469types$1.name.updateContext = function(prevType) {
18470 var allowed = false;
18471 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
18472 if (this.value === "of" && !this.exprAllowed ||
18473 this.value === "yield" && this.inGeneratorContext())
18474 { allowed = true; }
18475 }
18476 this.exprAllowed = allowed;
18477};
18478
18479// A recursive descent parser operates by defining functions for all
18480
18481var pp$5 = Parser.prototype;
18482
18483// Check if property name clashes with already added.
18484// Object/class getters and setters are not allowed to clash —
18485// either with each other or with an init property — and in
18486// strict mode, init properties are also not allowed to be repeated.
18487
18488pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
18489 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
18490 { return }
18491 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
18492 { return }
18493 var key = prop.key;
18494 var name;
18495 switch (key.type) {
18496 case "Identifier": name = key.name; break
18497 case "Literal": name = String(key.value); break
18498 default: return
18499 }
18500 var kind = prop.kind;
18501 if (this.options.ecmaVersion >= 6) {
18502 if (name === "__proto__" && kind === "init") {
18503 if (propHash.proto) {
18504 if (refDestructuringErrors) {
18505 if (refDestructuringErrors.doubleProto < 0) {
18506 refDestructuringErrors.doubleProto = key.start;
18507 }
18508 } else {
18509 this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
18510 }
18511 }
18512 propHash.proto = true;
18513 }
18514 return
18515 }
18516 name = "$" + name;
18517 var other = propHash[name];
18518 if (other) {
18519 var redefinition;
18520 if (kind === "init") {
18521 redefinition = this.strict && other.init || other.get || other.set;
18522 } else {
18523 redefinition = other.init || other[kind];
18524 }
18525 if (redefinition)
18526 { this.raiseRecoverable(key.start, "Redefinition of property"); }
18527 } else {
18528 other = propHash[name] = {
18529 init: false,
18530 get: false,
18531 set: false
18532 };
18533 }
18534 other[kind] = true;
18535};
18536
18537// ### Expression parsing
18538
18539// These nest, from the most general expression type at the top to
18540// 'atomic', nondivisible expression types at the bottom. Most of
18541// the functions will simply let the function(s) below them parse,
18542// and, *if* the syntactic construct they handle is present, wrap
18543// the AST node that the inner parser gave them in another node.
18544
18545// Parse a full expression. The optional arguments are used to
18546// forbid the `in` operator (in for loops initalization expressions)
18547// and provide reference for storing '=' operator inside shorthand
18548// property assignment in contexts where both object expression
18549// and object pattern might appear (so it's possible to raise
18550// delayed syntax error at correct position).
18551
18552pp$5.parseExpression = function(forInit, refDestructuringErrors) {
18553 var startPos = this.start, startLoc = this.startLoc;
18554 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
18555 if (this.type === types$1.comma) {
18556 var node = this.startNodeAt(startPos, startLoc);
18557 node.expressions = [expr];
18558 while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
18559 return this.finishNode(node, "SequenceExpression")
18560 }
18561 return expr
18562};
18563
18564// Parse an assignment expression. This includes applications of
18565// operators like `+=`.
18566
18567pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
18568 if (this.isContextual("yield")) {
18569 if (this.inGenerator) { return this.parseYield(forInit) }
18570 // The tokenizer will assume an expression is allowed after
18571 // `yield`, but this isn't that kind of yield
18572 else { this.exprAllowed = false; }
18573 }
18574
18575 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
18576 if (refDestructuringErrors) {
18577 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
18578 oldTrailingComma = refDestructuringErrors.trailingComma;
18579 oldDoubleProto = refDestructuringErrors.doubleProto;
18580 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
18581 } else {
18582 refDestructuringErrors = new DestructuringErrors;
18583 ownDestructuringErrors = true;
18584 }
18585
18586 var startPos = this.start, startLoc = this.startLoc;
18587 if (this.type === types$1.parenL || this.type === types$1.name) {
18588 this.potentialArrowAt = this.start;
18589 this.potentialArrowInForAwait = forInit === "await";
18590 }
18591 var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
18592 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
18593 if (this.type.isAssign) {
18594 var node = this.startNodeAt(startPos, startLoc);
18595 node.operator = this.value;
18596 if (this.type === types$1.eq)
18597 { left = this.toAssignable(left, false, refDestructuringErrors); }
18598 if (!ownDestructuringErrors) {
18599 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
18600 }
18601 if (refDestructuringErrors.shorthandAssign >= left.start)
18602 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
18603 if (this.type === types$1.eq)
18604 { this.checkLValPattern(left); }
18605 else
18606 { this.checkLValSimple(left); }
18607 node.left = left;
18608 this.next();
18609 node.right = this.parseMaybeAssign(forInit);
18610 if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
18611 return this.finishNode(node, "AssignmentExpression")
18612 } else {
18613 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
18614 }
18615 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
18616 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
18617 return left
18618};
18619
18620// Parse a ternary conditional (`?:`) operator.
18621
18622pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
18623 var startPos = this.start, startLoc = this.startLoc;
18624 var expr = this.parseExprOps(forInit, refDestructuringErrors);
18625 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18626 if (this.eat(types$1.question)) {
18627 var node = this.startNodeAt(startPos, startLoc);
18628 node.test = expr;
18629 node.consequent = this.parseMaybeAssign();
18630 this.expect(types$1.colon);
18631 node.alternate = this.parseMaybeAssign(forInit);
18632 return this.finishNode(node, "ConditionalExpression")
18633 }
18634 return expr
18635};
18636
18637// Start the precedence parser.
18638
18639pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
18640 var startPos = this.start, startLoc = this.startLoc;
18641 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
18642 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18643 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
18644};
18645
18646// Parse binary operators with the operator precedence parsing
18647// algorithm. `left` is the left-hand side of the operator.
18648// `minPrec` provides context that allows the function to stop and
18649// defer further parser to one of its callers when it encounters an
18650// operator that has a lower precedence than the set it is parsing.
18651
18652pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
18653 var prec = this.type.binop;
18654 if (prec != null && (!forInit || this.type !== types$1._in)) {
18655 if (prec > minPrec) {
18656 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
18657 var coalesce = this.type === types$1.coalesce;
18658 if (coalesce) {
18659 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
18660 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
18661 prec = types$1.logicalAND.binop;
18662 }
18663 var op = this.value;
18664 this.next();
18665 var startPos = this.start, startLoc = this.startLoc;
18666 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
18667 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
18668 if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
18669 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
18670 }
18671 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
18672 }
18673 }
18674 return left
18675};
18676
18677pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
18678 if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
18679 var node = this.startNodeAt(startPos, startLoc);
18680 node.left = left;
18681 node.operator = op;
18682 node.right = right;
18683 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
18684};
18685
18686// Parse unary operators, both prefix and postfix.
18687
18688pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
18689 var startPos = this.start, startLoc = this.startLoc, expr;
18690 if (this.isContextual("await") && this.canAwait) {
18691 expr = this.parseAwait(forInit);
18692 sawUnary = true;
18693 } else if (this.type.prefix) {
18694 var node = this.startNode(), update = this.type === types$1.incDec;
18695 node.operator = this.value;
18696 node.prefix = true;
18697 this.next();
18698 node.argument = this.parseMaybeUnary(null, true, update, forInit);
18699 this.checkExpressionErrors(refDestructuringErrors, true);
18700 if (update) { this.checkLValSimple(node.argument); }
18701 else if (this.strict && node.operator === "delete" &&
18702 node.argument.type === "Identifier")
18703 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
18704 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
18705 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
18706 else { sawUnary = true; }
18707 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
18708 } else if (!sawUnary && this.type === types$1.privateId) {
18709 if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
18710 expr = this.parsePrivateIdent();
18711 // only could be private fields in 'in', such as #x in obj
18712 if (this.type !== types$1._in) { this.unexpected(); }
18713 } else {
18714 expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
18715 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
18716 while (this.type.postfix && !this.canInsertSemicolon()) {
18717 var node$1 = this.startNodeAt(startPos, startLoc);
18718 node$1.operator = this.value;
18719 node$1.prefix = false;
18720 node$1.argument = expr;
18721 this.checkLValSimple(expr);
18722 this.next();
18723 expr = this.finishNode(node$1, "UpdateExpression");
18724 }
18725 }
18726
18727 if (!incDec && this.eat(types$1.starstar)) {
18728 if (sawUnary)
18729 { this.unexpected(this.lastTokStart); }
18730 else
18731 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
18732 } else {
18733 return expr
18734 }
18735};
18736
18737function isPrivateFieldAccess(node) {
18738 return (
18739 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
18740 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
18741 )
18742}
18743
18744// Parse call, dot, and `[]`-subscript expressions.
18745
18746pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
18747 var startPos = this.start, startLoc = this.startLoc;
18748 var expr = this.parseExprAtom(refDestructuringErrors, forInit);
18749 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
18750 { return expr }
18751 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
18752 if (refDestructuringErrors && result.type === "MemberExpression") {
18753 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
18754 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
18755 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
18756 }
18757 return result
18758};
18759
18760pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
18761 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
18762 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
18763 this.potentialArrowAt === base.start;
18764 var optionalChained = false;
18765
18766 while (true) {
18767 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
18768
18769 if (element.optional) { optionalChained = true; }
18770 if (element === base || element.type === "ArrowFunctionExpression") {
18771 if (optionalChained) {
18772 var chainNode = this.startNodeAt(startPos, startLoc);
18773 chainNode.expression = element;
18774 element = this.finishNode(chainNode, "ChainExpression");
18775 }
18776 return element
18777 }
18778
18779 base = element;
18780 }
18781};
18782
18783pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
18784 var optionalSupported = this.options.ecmaVersion >= 11;
18785 var optional = optionalSupported && this.eat(types$1.questionDot);
18786 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
18787
18788 var computed = this.eat(types$1.bracketL);
18789 if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
18790 var node = this.startNodeAt(startPos, startLoc);
18791 node.object = base;
18792 if (computed) {
18793 node.property = this.parseExpression();
18794 this.expect(types$1.bracketR);
18795 } else if (this.type === types$1.privateId && base.type !== "Super") {
18796 node.property = this.parsePrivateIdent();
18797 } else {
18798 node.property = this.parseIdent(this.options.allowReserved !== "never");
18799 }
18800 node.computed = !!computed;
18801 if (optionalSupported) {
18802 node.optional = optional;
18803 }
18804 base = this.finishNode(node, "MemberExpression");
18805 } else if (!noCalls && this.eat(types$1.parenL)) {
18806 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
18807 this.yieldPos = 0;
18808 this.awaitPos = 0;
18809 this.awaitIdentPos = 0;
18810 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
18811 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
18812 this.checkPatternErrors(refDestructuringErrors, false);
18813 this.checkYieldAwaitInDefaultParams();
18814 if (this.awaitIdentPos > 0)
18815 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
18816 this.yieldPos = oldYieldPos;
18817 this.awaitPos = oldAwaitPos;
18818 this.awaitIdentPos = oldAwaitIdentPos;
18819 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
18820 }
18821 this.checkExpressionErrors(refDestructuringErrors, true);
18822 this.yieldPos = oldYieldPos || this.yieldPos;
18823 this.awaitPos = oldAwaitPos || this.awaitPos;
18824 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
18825 var node$1 = this.startNodeAt(startPos, startLoc);
18826 node$1.callee = base;
18827 node$1.arguments = exprList;
18828 if (optionalSupported) {
18829 node$1.optional = optional;
18830 }
18831 base = this.finishNode(node$1, "CallExpression");
18832 } else if (this.type === types$1.backQuote) {
18833 if (optional || optionalChained) {
18834 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
18835 }
18836 var node$2 = this.startNodeAt(startPos, startLoc);
18837 node$2.tag = base;
18838 node$2.quasi = this.parseTemplate({isTagged: true});
18839 base = this.finishNode(node$2, "TaggedTemplateExpression");
18840 }
18841 return base
18842};
18843
18844// Parse an atomic expression — either a single token that is an
18845// expression, an expression started by a keyword like `function` or
18846// `new`, or an expression wrapped in punctuation like `()`, `[]`,
18847// or `{}`.
18848
18849pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
18850 // If a division operator appears in an expression position, the
18851 // tokenizer got confused, and we force it to read a regexp instead.
18852 if (this.type === types$1.slash) { this.readRegexp(); }
18853
18854 var node, canBeArrow = this.potentialArrowAt === this.start;
18855 switch (this.type) {
18856 case types$1._super:
18857 if (!this.allowSuper)
18858 { this.raise(this.start, "'super' keyword outside a method"); }
18859 node = this.startNode();
18860 this.next();
18861 if (this.type === types$1.parenL && !this.allowDirectSuper)
18862 { this.raise(node.start, "super() call outside constructor of a subclass"); }
18863 // The `super` keyword can appear at below:
18864 // SuperProperty:
18865 // super [ Expression ]
18866 // super . IdentifierName
18867 // SuperCall:
18868 // super ( Arguments )
18869 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
18870 { this.unexpected(); }
18871 return this.finishNode(node, "Super")
18872
18873 case types$1._this:
18874 node = this.startNode();
18875 this.next();
18876 return this.finishNode(node, "ThisExpression")
18877
18878 case types$1.name:
18879 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
18880 var id = this.parseIdent(false);
18881 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
18882 this.overrideContext(types.f_expr);
18883 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
18884 }
18885 if (canBeArrow && !this.canInsertSemicolon()) {
18886 if (this.eat(types$1.arrow))
18887 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
18888 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
18889 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
18890 id = this.parseIdent(false);
18891 if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
18892 { this.unexpected(); }
18893 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
18894 }
18895 }
18896 return id
18897
18898 case types$1.regexp:
18899 var value = this.value;
18900 node = this.parseLiteral(value.value);
18901 node.regex = {pattern: value.pattern, flags: value.flags};
18902 return node
18903
18904 case types$1.num: case types$1.string:
18905 return this.parseLiteral(this.value)
18906
18907 case types$1._null: case types$1._true: case types$1._false:
18908 node = this.startNode();
18909 node.value = this.type === types$1._null ? null : this.type === types$1._true;
18910 node.raw = this.type.keyword;
18911 this.next();
18912 return this.finishNode(node, "Literal")
18913
18914 case types$1.parenL:
18915 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
18916 if (refDestructuringErrors) {
18917 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
18918 { refDestructuringErrors.parenthesizedAssign = start; }
18919 if (refDestructuringErrors.parenthesizedBind < 0)
18920 { refDestructuringErrors.parenthesizedBind = start; }
18921 }
18922 return expr
18923
18924 case types$1.bracketL:
18925 node = this.startNode();
18926 this.next();
18927 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
18928 return this.finishNode(node, "ArrayExpression")
18929
18930 case types$1.braceL:
18931 this.overrideContext(types.b_expr);
18932 return this.parseObj(false, refDestructuringErrors)
18933
18934 case types$1._function:
18935 node = this.startNode();
18936 this.next();
18937 return this.parseFunction(node, 0)
18938
18939 case types$1._class:
18940 return this.parseClass(this.startNode(), false)
18941
18942 case types$1._new:
18943 return this.parseNew()
18944
18945 case types$1.backQuote:
18946 return this.parseTemplate()
18947
18948 case types$1._import:
18949 if (this.options.ecmaVersion >= 11) {
18950 return this.parseExprImport()
18951 } else {
18952 return this.unexpected()
18953 }
18954
18955 default:
18956 this.unexpected();
18957 }
18958};
18959
18960pp$5.parseExprImport = function() {
18961 var node = this.startNode();
18962
18963 // Consume `import` as an identifier for `import.meta`.
18964 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
18965 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
18966 var meta = this.parseIdent(true);
18967
18968 switch (this.type) {
18969 case types$1.parenL:
18970 return this.parseDynamicImport(node)
18971 case types$1.dot:
18972 node.meta = meta;
18973 return this.parseImportMeta(node)
18974 default:
18975 this.unexpected();
18976 }
18977};
18978
18979pp$5.parseDynamicImport = function(node) {
18980 this.next(); // skip `(`
18981
18982 // Parse node.source.
18983 node.source = this.parseMaybeAssign();
18984
18985 // Verify ending.
18986 if (!this.eat(types$1.parenR)) {
18987 var errorPos = this.start;
18988 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
18989 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
18990 } else {
18991 this.unexpected(errorPos);
18992 }
18993 }
18994
18995 return this.finishNode(node, "ImportExpression")
18996};
18997
18998pp$5.parseImportMeta = function(node) {
18999 this.next(); // skip `.`
19000
19001 var containsEsc = this.containsEsc;
19002 node.property = this.parseIdent(true);
19003
19004 if (node.property.name !== "meta")
19005 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
19006 if (containsEsc)
19007 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
19008 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
19009 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
19010
19011 return this.finishNode(node, "MetaProperty")
19012};
19013
19014pp$5.parseLiteral = function(value) {
19015 var node = this.startNode();
19016 node.value = value;
19017 node.raw = this.input.slice(this.start, this.end);
19018 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
19019 this.next();
19020 return this.finishNode(node, "Literal")
19021};
19022
19023pp$5.parseParenExpression = function() {
19024 this.expect(types$1.parenL);
19025 var val = this.parseExpression();
19026 this.expect(types$1.parenR);
19027 return val
19028};
19029
19030pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
19031 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
19032 if (this.options.ecmaVersion >= 6) {
19033 this.next();
19034
19035 var innerStartPos = this.start, innerStartLoc = this.startLoc;
19036 var exprList = [], first = true, lastIsComma = false;
19037 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
19038 this.yieldPos = 0;
19039 this.awaitPos = 0;
19040 // Do not save awaitIdentPos to allow checking awaits nested in parameters
19041 while (this.type !== types$1.parenR) {
19042 first ? first = false : this.expect(types$1.comma);
19043 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
19044 lastIsComma = true;
19045 break
19046 } else if (this.type === types$1.ellipsis) {
19047 spreadStart = this.start;
19048 exprList.push(this.parseParenItem(this.parseRestBinding()));
19049 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
19050 break
19051 } else {
19052 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
19053 }
19054 }
19055 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
19056 this.expect(types$1.parenR);
19057
19058 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
19059 this.checkPatternErrors(refDestructuringErrors, false);
19060 this.checkYieldAwaitInDefaultParams();
19061 this.yieldPos = oldYieldPos;
19062 this.awaitPos = oldAwaitPos;
19063 return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
19064 }
19065
19066 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
19067 if (spreadStart) { this.unexpected(spreadStart); }
19068 this.checkExpressionErrors(refDestructuringErrors, true);
19069 this.yieldPos = oldYieldPos || this.yieldPos;
19070 this.awaitPos = oldAwaitPos || this.awaitPos;
19071
19072 if (exprList.length > 1) {
19073 val = this.startNodeAt(innerStartPos, innerStartLoc);
19074 val.expressions = exprList;
19075 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
19076 } else {
19077 val = exprList[0];
19078 }
19079 } else {
19080 val = this.parseParenExpression();
19081 }
19082
19083 if (this.options.preserveParens) {
19084 var par = this.startNodeAt(startPos, startLoc);
19085 par.expression = val;
19086 return this.finishNode(par, "ParenthesizedExpression")
19087 } else {
19088 return val
19089 }
19090};
19091
19092pp$5.parseParenItem = function(item) {
19093 return item
19094};
19095
19096pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
19097 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
19098};
19099
19100// New's precedence is slightly tricky. It must allow its argument to
19101// be a `[]` or dot subscript expression, but not a call — at least,
19102// not without wrapping it in parentheses. Thus, it uses the noCalls
19103// argument to parseSubscripts to prevent it from consuming the
19104// argument list.
19105
19106var empty = [];
19107
19108pp$5.parseNew = function() {
19109 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
19110 var node = this.startNode();
19111 var meta = this.parseIdent(true);
19112 if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
19113 node.meta = meta;
19114 var containsEsc = this.containsEsc;
19115 node.property = this.parseIdent(true);
19116 if (node.property.name !== "target")
19117 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
19118 if (containsEsc)
19119 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
19120 if (!this.allowNewDotTarget)
19121 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
19122 return this.finishNode(node, "MetaProperty")
19123 }
19124 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
19125 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
19126 if (isImport && node.callee.type === "ImportExpression") {
19127 this.raise(startPos, "Cannot use new with import()");
19128 }
19129 if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
19130 else { node.arguments = empty; }
19131 return this.finishNode(node, "NewExpression")
19132};
19133
19134// Parse template expression.
19135
19136pp$5.parseTemplateElement = function(ref) {
19137 var isTagged = ref.isTagged;
19138
19139 var elem = this.startNode();
19140 if (this.type === types$1.invalidTemplate) {
19141 if (!isTagged) {
19142 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
19143 }
19144 elem.value = {
19145 raw: this.value,
19146 cooked: null
19147 };
19148 } else {
19149 elem.value = {
19150 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
19151 cooked: this.value
19152 };
19153 }
19154 this.next();
19155 elem.tail = this.type === types$1.backQuote;
19156 return this.finishNode(elem, "TemplateElement")
19157};
19158
19159pp$5.parseTemplate = function(ref) {
19160 if ( ref === void 0 ) ref = {};
19161 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
19162
19163 var node = this.startNode();
19164 this.next();
19165 node.expressions = [];
19166 var curElt = this.parseTemplateElement({isTagged: isTagged});
19167 node.quasis = [curElt];
19168 while (!curElt.tail) {
19169 if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
19170 this.expect(types$1.dollarBraceL);
19171 node.expressions.push(this.parseExpression());
19172 this.expect(types$1.braceR);
19173 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
19174 }
19175 this.next();
19176 return this.finishNode(node, "TemplateLiteral")
19177};
19178
19179pp$5.isAsyncProp = function(prop) {
19180 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
19181 (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)) &&
19182 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
19183};
19184
19185// Parse an object literal or binding pattern.
19186
19187pp$5.parseObj = function(isPattern, refDestructuringErrors) {
19188 var node = this.startNode(), first = true, propHash = {};
19189 node.properties = [];
19190 this.next();
19191 while (!this.eat(types$1.braceR)) {
19192 if (!first) {
19193 this.expect(types$1.comma);
19194 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
19195 } else { first = false; }
19196
19197 var prop = this.parseProperty(isPattern, refDestructuringErrors);
19198 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
19199 node.properties.push(prop);
19200 }
19201 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
19202};
19203
19204pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
19205 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
19206 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
19207 if (isPattern) {
19208 prop.argument = this.parseIdent(false);
19209 if (this.type === types$1.comma) {
19210 this.raise(this.start, "Comma is not permitted after the rest element");
19211 }
19212 return this.finishNode(prop, "RestElement")
19213 }
19214 // To disallow parenthesized identifier via `this.toAssignable()`.
19215 if (this.type === types$1.parenL && refDestructuringErrors) {
19216 if (refDestructuringErrors.parenthesizedAssign < 0) {
19217 refDestructuringErrors.parenthesizedAssign = this.start;
19218 }
19219 if (refDestructuringErrors.parenthesizedBind < 0) {
19220 refDestructuringErrors.parenthesizedBind = this.start;
19221 }
19222 }
19223 // Parse argument.
19224 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
19225 // To disallow trailing comma via `this.toAssignable()`.
19226 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
19227 refDestructuringErrors.trailingComma = this.start;
19228 }
19229 // Finish
19230 return this.finishNode(prop, "SpreadElement")
19231 }
19232 if (this.options.ecmaVersion >= 6) {
19233 prop.method = false;
19234 prop.shorthand = false;
19235 if (isPattern || refDestructuringErrors) {
19236 startPos = this.start;
19237 startLoc = this.startLoc;
19238 }
19239 if (!isPattern)
19240 { isGenerator = this.eat(types$1.star); }
19241 }
19242 var containsEsc = this.containsEsc;
19243 this.parsePropertyName(prop);
19244 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
19245 isAsync = true;
19246 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
19247 this.parsePropertyName(prop, refDestructuringErrors);
19248 } else {
19249 isAsync = false;
19250 }
19251 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
19252 return this.finishNode(prop, "Property")
19253};
19254
19255pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
19256 if ((isGenerator || isAsync) && this.type === types$1.colon)
19257 { this.unexpected(); }
19258
19259 if (this.eat(types$1.colon)) {
19260 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
19261 prop.kind = "init";
19262 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
19263 if (isPattern) { this.unexpected(); }
19264 prop.kind = "init";
19265 prop.method = true;
19266 prop.value = this.parseMethod(isGenerator, isAsync);
19267 } else if (!isPattern && !containsEsc &&
19268 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
19269 (prop.key.name === "get" || prop.key.name === "set") &&
19270 (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
19271 if (isGenerator || isAsync) { this.unexpected(); }
19272 prop.kind = prop.key.name;
19273 this.parsePropertyName(prop);
19274 prop.value = this.parseMethod(false);
19275 var paramCount = prop.kind === "get" ? 0 : 1;
19276 if (prop.value.params.length !== paramCount) {
19277 var start = prop.value.start;
19278 if (prop.kind === "get")
19279 { this.raiseRecoverable(start, "getter should have no params"); }
19280 else
19281 { this.raiseRecoverable(start, "setter should have exactly one param"); }
19282 } else {
19283 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
19284 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
19285 }
19286 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
19287 if (isGenerator || isAsync) { this.unexpected(); }
19288 this.checkUnreserved(prop.key);
19289 if (prop.key.name === "await" && !this.awaitIdentPos)
19290 { this.awaitIdentPos = startPos; }
19291 prop.kind = "init";
19292 if (isPattern) {
19293 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19294 } else if (this.type === types$1.eq && refDestructuringErrors) {
19295 if (refDestructuringErrors.shorthandAssign < 0)
19296 { refDestructuringErrors.shorthandAssign = this.start; }
19297 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
19298 } else {
19299 prop.value = this.copyNode(prop.key);
19300 }
19301 prop.shorthand = true;
19302 } else { this.unexpected(); }
19303};
19304
19305pp$5.parsePropertyName = function(prop) {
19306 if (this.options.ecmaVersion >= 6) {
19307 if (this.eat(types$1.bracketL)) {
19308 prop.computed = true;
19309 prop.key = this.parseMaybeAssign();
19310 this.expect(types$1.bracketR);
19311 return prop.key
19312 } else {
19313 prop.computed = false;
19314 }
19315 }
19316 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
19317};
19318
19319// Initialize empty function node.
19320
19321pp$5.initFunction = function(node) {
19322 node.id = null;
19323 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
19324 if (this.options.ecmaVersion >= 8) { node.async = false; }
19325};
19326
19327// Parse object or class method.
19328
19329pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
19330 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19331
19332 this.initFunction(node);
19333 if (this.options.ecmaVersion >= 6)
19334 { node.generator = isGenerator; }
19335 if (this.options.ecmaVersion >= 8)
19336 { node.async = !!isAsync; }
19337
19338 this.yieldPos = 0;
19339 this.awaitPos = 0;
19340 this.awaitIdentPos = 0;
19341 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
19342
19343 this.expect(types$1.parenL);
19344 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
19345 this.checkYieldAwaitInDefaultParams();
19346 this.parseFunctionBody(node, false, true, false);
19347
19348 this.yieldPos = oldYieldPos;
19349 this.awaitPos = oldAwaitPos;
19350 this.awaitIdentPos = oldAwaitIdentPos;
19351 return this.finishNode(node, "FunctionExpression")
19352};
19353
19354// Parse arrow function expression with given parameters.
19355
19356pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
19357 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
19358
19359 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
19360 this.initFunction(node);
19361 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
19362
19363 this.yieldPos = 0;
19364 this.awaitPos = 0;
19365 this.awaitIdentPos = 0;
19366
19367 node.params = this.toAssignableList(params, true);
19368 this.parseFunctionBody(node, true, false, forInit);
19369
19370 this.yieldPos = oldYieldPos;
19371 this.awaitPos = oldAwaitPos;
19372 this.awaitIdentPos = oldAwaitIdentPos;
19373 return this.finishNode(node, "ArrowFunctionExpression")
19374};
19375
19376// Parse function body and check parameters.
19377
19378pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
19379 var isExpression = isArrowFunction && this.type !== types$1.braceL;
19380 var oldStrict = this.strict, useStrict = false;
19381
19382 if (isExpression) {
19383 node.body = this.parseMaybeAssign(forInit);
19384 node.expression = true;
19385 this.checkParams(node, false);
19386 } else {
19387 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
19388 if (!oldStrict || nonSimple) {
19389 useStrict = this.strictDirective(this.end);
19390 // If this is a strict mode function, verify that argument names
19391 // are not repeated, and it does not try to bind the words `eval`
19392 // or `arguments`.
19393 if (useStrict && nonSimple)
19394 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
19395 }
19396 // Start a new scope with regard to labels and the `inFunction`
19397 // flag (restore them to their old value afterwards).
19398 var oldLabels = this.labels;
19399 this.labels = [];
19400 if (useStrict) { this.strict = true; }
19401
19402 // Add the params to varDeclaredNames to ensure that an error is thrown
19403 // if a let/const declaration in the function clashes with one of the params.
19404 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
19405 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
19406 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
19407 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
19408 node.expression = false;
19409 this.adaptDirectivePrologue(node.body.body);
19410 this.labels = oldLabels;
19411 }
19412 this.exitScope();
19413};
19414
19415pp$5.isSimpleParamList = function(params) {
19416 for (var i = 0, list = params; i < list.length; i += 1)
19417 {
19418 var param = list[i];
19419
19420 if (param.type !== "Identifier") { return false
19421 } }
19422 return true
19423};
19424
19425// Checks function params for various disallowed patterns such as using "eval"
19426// or "arguments" and duplicate parameters.
19427
19428pp$5.checkParams = function(node, allowDuplicates) {
19429 var nameHash = Object.create(null);
19430 for (var i = 0, list = node.params; i < list.length; i += 1)
19431 {
19432 var param = list[i];
19433
19434 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
19435 }
19436};
19437
19438// Parses a comma-separated list of expressions, and returns them as
19439// an array. `close` is the token type that ends the list, and
19440// `allowEmpty` can be turned on to allow subsequent commas with
19441// nothing in between them to be parsed as `null` (which is needed
19442// for array literals).
19443
19444pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
19445 var elts = [], first = true;
19446 while (!this.eat(close)) {
19447 if (!first) {
19448 this.expect(types$1.comma);
19449 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
19450 } else { first = false; }
19451
19452 var elt = (void 0);
19453 if (allowEmpty && this.type === types$1.comma)
19454 { elt = null; }
19455 else if (this.type === types$1.ellipsis) {
19456 elt = this.parseSpread(refDestructuringErrors);
19457 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
19458 { refDestructuringErrors.trailingComma = this.start; }
19459 } else {
19460 elt = this.parseMaybeAssign(false, refDestructuringErrors);
19461 }
19462 elts.push(elt);
19463 }
19464 return elts
19465};
19466
19467pp$5.checkUnreserved = function(ref) {
19468 var start = ref.start;
19469 var end = ref.end;
19470 var name = ref.name;
19471
19472 if (this.inGenerator && name === "yield")
19473 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
19474 if (this.inAsync && name === "await")
19475 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
19476 if (this.currentThisScope().inClassFieldInit && name === "arguments")
19477 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
19478 if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
19479 { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
19480 if (this.keywords.test(name))
19481 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
19482 if (this.options.ecmaVersion < 6 &&
19483 this.input.slice(start, end).indexOf("\\") !== -1) { return }
19484 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
19485 if (re.test(name)) {
19486 if (!this.inAsync && name === "await")
19487 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
19488 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
19489 }
19490};
19491
19492// Parse the next token as an identifier. If `liberal` is true (used
19493// when parsing properties), it will also convert keywords into
19494// identifiers.
19495
19496pp$5.parseIdent = function(liberal, isBinding) {
19497 var node = this.startNode();
19498 if (this.type === types$1.name) {
19499 node.name = this.value;
19500 } else if (this.type.keyword) {
19501 node.name = this.type.keyword;
19502
19503 // To fix https://github.com/acornjs/acorn/issues/575
19504 // `class` and `function` keywords push new context into this.context.
19505 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
19506 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
19507 if ((node.name === "class" || node.name === "function") &&
19508 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
19509 this.context.pop();
19510 }
19511 } else {
19512 this.unexpected();
19513 }
19514 this.next(!!liberal);
19515 this.finishNode(node, "Identifier");
19516 if (!liberal) {
19517 this.checkUnreserved(node);
19518 if (node.name === "await" && !this.awaitIdentPos)
19519 { this.awaitIdentPos = node.start; }
19520 }
19521 return node
19522};
19523
19524pp$5.parsePrivateIdent = function() {
19525 var node = this.startNode();
19526 if (this.type === types$1.privateId) {
19527 node.name = this.value;
19528 } else {
19529 this.unexpected();
19530 }
19531 this.next();
19532 this.finishNode(node, "PrivateIdentifier");
19533
19534 // For validating existence
19535 if (this.privateNameStack.length === 0) {
19536 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
19537 } else {
19538 this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
19539 }
19540
19541 return node
19542};
19543
19544// Parses yield expression inside generator.
19545
19546pp$5.parseYield = function(forInit) {
19547 if (!this.yieldPos) { this.yieldPos = this.start; }
19548
19549 var node = this.startNode();
19550 this.next();
19551 if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
19552 node.delegate = false;
19553 node.argument = null;
19554 } else {
19555 node.delegate = this.eat(types$1.star);
19556 node.argument = this.parseMaybeAssign(forInit);
19557 }
19558 return this.finishNode(node, "YieldExpression")
19559};
19560
19561pp$5.parseAwait = function(forInit) {
19562 if (!this.awaitPos) { this.awaitPos = this.start; }
19563
19564 var node = this.startNode();
19565 this.next();
19566 node.argument = this.parseMaybeUnary(null, true, false, forInit);
19567 return this.finishNode(node, "AwaitExpression")
19568};
19569
19570var pp$4 = Parser.prototype;
19571
19572// This function is used to raise exceptions on parse errors. It
19573// takes an offset integer (into the current `input`) to indicate
19574// the location of the error, attaches the position to the end
19575// of the error message, and then raises a `SyntaxError` with that
19576// message.
19577
19578pp$4.raise = function(pos, message) {
19579 var loc = getLineInfo(this.input, pos);
19580 message += " (" + loc.line + ":" + loc.column + ")";
19581 var err = new SyntaxError(message);
19582 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
19583 throw err
19584};
19585
19586pp$4.raiseRecoverable = pp$4.raise;
19587
19588pp$4.curPosition = function() {
19589 if (this.options.locations) {
19590 return new Position(this.curLine, this.pos - this.lineStart)
19591 }
19592};
19593
19594var pp$3 = Parser.prototype;
19595
19596var Scope = function Scope(flags) {
19597 this.flags = flags;
19598 // A list of var-declared names in the current lexical scope
19599 this.var = [];
19600 // A list of lexically-declared names in the current lexical scope
19601 this.lexical = [];
19602 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
19603 this.functions = [];
19604 // A switch to disallow the identifier reference 'arguments'
19605 this.inClassFieldInit = false;
19606};
19607
19608// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
19609
19610pp$3.enterScope = function(flags) {
19611 this.scopeStack.push(new Scope(flags));
19612};
19613
19614pp$3.exitScope = function() {
19615 this.scopeStack.pop();
19616};
19617
19618// The spec says:
19619// > At the top level of a function, or script, function declarations are
19620// > treated like var declarations rather than like lexical declarations.
19621pp$3.treatFunctionsAsVarInScope = function(scope) {
19622 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
19623};
19624
19625pp$3.declareName = function(name, bindingType, pos) {
19626 var redeclared = false;
19627 if (bindingType === BIND_LEXICAL) {
19628 var scope = this.currentScope();
19629 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
19630 scope.lexical.push(name);
19631 if (this.inModule && (scope.flags & SCOPE_TOP))
19632 { delete this.undefinedExports[name]; }
19633 } else if (bindingType === BIND_SIMPLE_CATCH) {
19634 var scope$1 = this.currentScope();
19635 scope$1.lexical.push(name);
19636 } else if (bindingType === BIND_FUNCTION) {
19637 var scope$2 = this.currentScope();
19638 if (this.treatFunctionsAsVar)
19639 { redeclared = scope$2.lexical.indexOf(name) > -1; }
19640 else
19641 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
19642 scope$2.functions.push(name);
19643 } else {
19644 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
19645 var scope$3 = this.scopeStack[i];
19646 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
19647 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
19648 redeclared = true;
19649 break
19650 }
19651 scope$3.var.push(name);
19652 if (this.inModule && (scope$3.flags & SCOPE_TOP))
19653 { delete this.undefinedExports[name]; }
19654 if (scope$3.flags & SCOPE_VAR) { break }
19655 }
19656 }
19657 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
19658};
19659
19660pp$3.checkLocalExport = function(id) {
19661 // scope.functions must be empty as Module code is always strict.
19662 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
19663 this.scopeStack[0].var.indexOf(id.name) === -1) {
19664 this.undefinedExports[id.name] = id;
19665 }
19666};
19667
19668pp$3.currentScope = function() {
19669 return this.scopeStack[this.scopeStack.length - 1]
19670};
19671
19672pp$3.currentVarScope = function() {
19673 for (var i = this.scopeStack.length - 1;; i--) {
19674 var scope = this.scopeStack[i];
19675 if (scope.flags & SCOPE_VAR) { return scope }
19676 }
19677};
19678
19679// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
19680pp$3.currentThisScope = function() {
19681 for (var i = this.scopeStack.length - 1;; i--) {
19682 var scope = this.scopeStack[i];
19683 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
19684 }
19685};
19686
19687var Node = function Node(parser, pos, loc) {
19688 this.type = "";
19689 this.start = pos;
19690 this.end = 0;
19691 if (parser.options.locations)
19692 { this.loc = new SourceLocation(parser, loc); }
19693 if (parser.options.directSourceFile)
19694 { this.sourceFile = parser.options.directSourceFile; }
19695 if (parser.options.ranges)
19696 { this.range = [pos, 0]; }
19697};
19698
19699// Start an AST node, attaching a start offset.
19700
19701var pp$2 = Parser.prototype;
19702
19703pp$2.startNode = function() {
19704 return new Node(this, this.start, this.startLoc)
19705};
19706
19707pp$2.startNodeAt = function(pos, loc) {
19708 return new Node(this, pos, loc)
19709};
19710
19711// Finish an AST node, adding `type` and `end` properties.
19712
19713function finishNodeAt(node, type, pos, loc) {
19714 node.type = type;
19715 node.end = pos;
19716 if (this.options.locations)
19717 { node.loc.end = loc; }
19718 if (this.options.ranges)
19719 { node.range[1] = pos; }
19720 return node
19721}
19722
19723pp$2.finishNode = function(node, type) {
19724 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
19725};
19726
19727// Finish node at given position
19728
19729pp$2.finishNodeAt = function(node, type, pos, loc) {
19730 return finishNodeAt.call(this, node, type, pos, loc)
19731};
19732
19733pp$2.copyNode = function(node) {
19734 var newNode = new Node(this, node.start, this.startLoc);
19735 for (var prop in node) { newNode[prop] = node[prop]; }
19736 return newNode
19737};
19738
19739// This file contains Unicode properties extracted from the ECMAScript
19740// specification. The lists are extracted like so:
19741// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
19742
19743// #table-binary-unicode-properties
19744var 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";
19745var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
19746var ecma11BinaryProperties = ecma10BinaryProperties;
19747var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
19748var ecma13BinaryProperties = ecma12BinaryProperties;
19749var unicodeBinaryProperties = {
19750 9: ecma9BinaryProperties,
19751 10: ecma10BinaryProperties,
19752 11: ecma11BinaryProperties,
19753 12: ecma12BinaryProperties,
19754 13: ecma13BinaryProperties
19755};
19756
19757// #table-unicode-general-category-values
19758var 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";
19759
19760// #table-unicode-script-values
19761var 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";
19762var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
19763var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
19764var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
19765var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
19766var unicodeScriptValues = {
19767 9: ecma9ScriptValues,
19768 10: ecma10ScriptValues,
19769 11: ecma11ScriptValues,
19770 12: ecma12ScriptValues,
19771 13: ecma13ScriptValues
19772};
19773
19774var data = {};
19775function buildUnicodeData(ecmaVersion) {
19776 var d = data[ecmaVersion] = {
19777 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
19778 nonBinary: {
19779 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
19780 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
19781 }
19782 };
19783 d.nonBinary.Script_Extensions = d.nonBinary.Script;
19784
19785 d.nonBinary.gc = d.nonBinary.General_Category;
19786 d.nonBinary.sc = d.nonBinary.Script;
19787 d.nonBinary.scx = d.nonBinary.Script_Extensions;
19788}
19789
19790for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
19791 var ecmaVersion = list[i];
19792
19793 buildUnicodeData(ecmaVersion);
19794}
19795
19796var pp$1 = Parser.prototype;
19797
19798var RegExpValidationState = function RegExpValidationState(parser) {
19799 this.parser = parser;
19800 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
19801 this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
19802 this.source = "";
19803 this.flags = "";
19804 this.start = 0;
19805 this.switchU = false;
19806 this.switchN = false;
19807 this.pos = 0;
19808 this.lastIntValue = 0;
19809 this.lastStringValue = "";
19810 this.lastAssertionIsQuantifiable = false;
19811 this.numCapturingParens = 0;
19812 this.maxBackReference = 0;
19813 this.groupNames = [];
19814 this.backReferenceNames = [];
19815};
19816
19817RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
19818 var unicode = flags.indexOf("u") !== -1;
19819 this.start = start | 0;
19820 this.source = pattern + "";
19821 this.flags = flags;
19822 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
19823 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
19824};
19825
19826RegExpValidationState.prototype.raise = function raise (message) {
19827 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
19828};
19829
19830// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
19831// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
19832RegExpValidationState.prototype.at = function at (i, forceU) {
19833 if ( forceU === void 0 ) forceU = false;
19834
19835 var s = this.source;
19836 var l = s.length;
19837 if (i >= l) {
19838 return -1
19839 }
19840 var c = s.charCodeAt(i);
19841 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
19842 return c
19843 }
19844 var next = s.charCodeAt(i + 1);
19845 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
19846};
19847
19848RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
19849 if ( forceU === void 0 ) forceU = false;
19850
19851 var s = this.source;
19852 var l = s.length;
19853 if (i >= l) {
19854 return l
19855 }
19856 var c = s.charCodeAt(i), next;
19857 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
19858 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
19859 return i + 1
19860 }
19861 return i + 2
19862};
19863
19864RegExpValidationState.prototype.current = function current (forceU) {
19865 if ( forceU === void 0 ) forceU = false;
19866
19867 return this.at(this.pos, forceU)
19868};
19869
19870RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
19871 if ( forceU === void 0 ) forceU = false;
19872
19873 return this.at(this.nextIndex(this.pos, forceU), forceU)
19874};
19875
19876RegExpValidationState.prototype.advance = function advance (forceU) {
19877 if ( forceU === void 0 ) forceU = false;
19878
19879 this.pos = this.nextIndex(this.pos, forceU);
19880};
19881
19882RegExpValidationState.prototype.eat = function eat (ch, forceU) {
19883 if ( forceU === void 0 ) forceU = false;
19884
19885 if (this.current(forceU) === ch) {
19886 this.advance(forceU);
19887 return true
19888 }
19889 return false
19890};
19891
19892/**
19893 * Validate the flags part of a given RegExpLiteral.
19894 *
19895 * @param {RegExpValidationState} state The state to validate RegExp.
19896 * @returns {void}
19897 */
19898pp$1.validateRegExpFlags = function(state) {
19899 var validFlags = state.validFlags;
19900 var flags = state.flags;
19901
19902 for (var i = 0; i < flags.length; i++) {
19903 var flag = flags.charAt(i);
19904 if (validFlags.indexOf(flag) === -1) {
19905 this.raise(state.start, "Invalid regular expression flag");
19906 }
19907 if (flags.indexOf(flag, i + 1) > -1) {
19908 this.raise(state.start, "Duplicate regular expression flag");
19909 }
19910 }
19911};
19912
19913/**
19914 * Validate the pattern part of a given RegExpLiteral.
19915 *
19916 * @param {RegExpValidationState} state The state to validate RegExp.
19917 * @returns {void}
19918 */
19919pp$1.validateRegExpPattern = function(state) {
19920 this.regexp_pattern(state);
19921
19922 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
19923 // parsing contains a |GroupName|, reparse with the goal symbol
19924 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
19925 // exception if _P_ did not conform to the grammar, if any elements of _P_
19926 // were not matched by the parse, or if any Early Error conditions exist.
19927 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
19928 state.switchN = true;
19929 this.regexp_pattern(state);
19930 }
19931};
19932
19933// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
19934pp$1.regexp_pattern = function(state) {
19935 state.pos = 0;
19936 state.lastIntValue = 0;
19937 state.lastStringValue = "";
19938 state.lastAssertionIsQuantifiable = false;
19939 state.numCapturingParens = 0;
19940 state.maxBackReference = 0;
19941 state.groupNames.length = 0;
19942 state.backReferenceNames.length = 0;
19943
19944 this.regexp_disjunction(state);
19945
19946 if (state.pos !== state.source.length) {
19947 // Make the same messages as V8.
19948 if (state.eat(0x29 /* ) */)) {
19949 state.raise("Unmatched ')'");
19950 }
19951 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
19952 state.raise("Lone quantifier brackets");
19953 }
19954 }
19955 if (state.maxBackReference > state.numCapturingParens) {
19956 state.raise("Invalid escape");
19957 }
19958 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
19959 var name = list[i];
19960
19961 if (state.groupNames.indexOf(name) === -1) {
19962 state.raise("Invalid named capture referenced");
19963 }
19964 }
19965};
19966
19967// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
19968pp$1.regexp_disjunction = function(state) {
19969 this.regexp_alternative(state);
19970 while (state.eat(0x7C /* | */)) {
19971 this.regexp_alternative(state);
19972 }
19973
19974 // Make the same message as V8.
19975 if (this.regexp_eatQuantifier(state, true)) {
19976 state.raise("Nothing to repeat");
19977 }
19978 if (state.eat(0x7B /* { */)) {
19979 state.raise("Lone quantifier brackets");
19980 }
19981};
19982
19983// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
19984pp$1.regexp_alternative = function(state) {
19985 while (state.pos < state.source.length && this.regexp_eatTerm(state))
19986 { }
19987};
19988
19989// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
19990pp$1.regexp_eatTerm = function(state) {
19991 if (this.regexp_eatAssertion(state)) {
19992 // Handle `QuantifiableAssertion Quantifier` alternative.
19993 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
19994 // is a QuantifiableAssertion.
19995 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
19996 // Make the same message as V8.
19997 if (state.switchU) {
19998 state.raise("Invalid quantifier");
19999 }
20000 }
20001 return true
20002 }
20003
20004 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
20005 this.regexp_eatQuantifier(state);
20006 return true
20007 }
20008
20009 return false
20010};
20011
20012// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
20013pp$1.regexp_eatAssertion = function(state) {
20014 var start = state.pos;
20015 state.lastAssertionIsQuantifiable = false;
20016
20017 // ^, $
20018 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
20019 return true
20020 }
20021
20022 // \b \B
20023 if (state.eat(0x5C /* \ */)) {
20024 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
20025 return true
20026 }
20027 state.pos = start;
20028 }
20029
20030 // Lookahead / Lookbehind
20031 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
20032 var lookbehind = false;
20033 if (this.options.ecmaVersion >= 9) {
20034 lookbehind = state.eat(0x3C /* < */);
20035 }
20036 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
20037 this.regexp_disjunction(state);
20038 if (!state.eat(0x29 /* ) */)) {
20039 state.raise("Unterminated group");
20040 }
20041 state.lastAssertionIsQuantifiable = !lookbehind;
20042 return true
20043 }
20044 }
20045
20046 state.pos = start;
20047 return false
20048};
20049
20050// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
20051pp$1.regexp_eatQuantifier = function(state, noError) {
20052 if ( noError === void 0 ) noError = false;
20053
20054 if (this.regexp_eatQuantifierPrefix(state, noError)) {
20055 state.eat(0x3F /* ? */);
20056 return true
20057 }
20058 return false
20059};
20060
20061// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
20062pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
20063 return (
20064 state.eat(0x2A /* * */) ||
20065 state.eat(0x2B /* + */) ||
20066 state.eat(0x3F /* ? */) ||
20067 this.regexp_eatBracedQuantifier(state, noError)
20068 )
20069};
20070pp$1.regexp_eatBracedQuantifier = function(state, noError) {
20071 var start = state.pos;
20072 if (state.eat(0x7B /* { */)) {
20073 var min = 0, max = -1;
20074 if (this.regexp_eatDecimalDigits(state)) {
20075 min = state.lastIntValue;
20076 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
20077 max = state.lastIntValue;
20078 }
20079 if (state.eat(0x7D /* } */)) {
20080 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
20081 if (max !== -1 && max < min && !noError) {
20082 state.raise("numbers out of order in {} quantifier");
20083 }
20084 return true
20085 }
20086 }
20087 if (state.switchU && !noError) {
20088 state.raise("Incomplete quantifier");
20089 }
20090 state.pos = start;
20091 }
20092 return false
20093};
20094
20095// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
20096pp$1.regexp_eatAtom = function(state) {
20097 return (
20098 this.regexp_eatPatternCharacters(state) ||
20099 state.eat(0x2E /* . */) ||
20100 this.regexp_eatReverseSolidusAtomEscape(state) ||
20101 this.regexp_eatCharacterClass(state) ||
20102 this.regexp_eatUncapturingGroup(state) ||
20103 this.regexp_eatCapturingGroup(state)
20104 )
20105};
20106pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
20107 var start = state.pos;
20108 if (state.eat(0x5C /* \ */)) {
20109 if (this.regexp_eatAtomEscape(state)) {
20110 return true
20111 }
20112 state.pos = start;
20113 }
20114 return false
20115};
20116pp$1.regexp_eatUncapturingGroup = function(state) {
20117 var start = state.pos;
20118 if (state.eat(0x28 /* ( */)) {
20119 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
20120 this.regexp_disjunction(state);
20121 if (state.eat(0x29 /* ) */)) {
20122 return true
20123 }
20124 state.raise("Unterminated group");
20125 }
20126 state.pos = start;
20127 }
20128 return false
20129};
20130pp$1.regexp_eatCapturingGroup = function(state) {
20131 if (state.eat(0x28 /* ( */)) {
20132 if (this.options.ecmaVersion >= 9) {
20133 this.regexp_groupSpecifier(state);
20134 } else if (state.current() === 0x3F /* ? */) {
20135 state.raise("Invalid group");
20136 }
20137 this.regexp_disjunction(state);
20138 if (state.eat(0x29 /* ) */)) {
20139 state.numCapturingParens += 1;
20140 return true
20141 }
20142 state.raise("Unterminated group");
20143 }
20144 return false
20145};
20146
20147// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
20148pp$1.regexp_eatExtendedAtom = function(state) {
20149 return (
20150 state.eat(0x2E /* . */) ||
20151 this.regexp_eatReverseSolidusAtomEscape(state) ||
20152 this.regexp_eatCharacterClass(state) ||
20153 this.regexp_eatUncapturingGroup(state) ||
20154 this.regexp_eatCapturingGroup(state) ||
20155 this.regexp_eatInvalidBracedQuantifier(state) ||
20156 this.regexp_eatExtendedPatternCharacter(state)
20157 )
20158};
20159
20160// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
20161pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
20162 if (this.regexp_eatBracedQuantifier(state, true)) {
20163 state.raise("Nothing to repeat");
20164 }
20165 return false
20166};
20167
20168// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
20169pp$1.regexp_eatSyntaxCharacter = function(state) {
20170 var ch = state.current();
20171 if (isSyntaxCharacter(ch)) {
20172 state.lastIntValue = ch;
20173 state.advance();
20174 return true
20175 }
20176 return false
20177};
20178function isSyntaxCharacter(ch) {
20179 return (
20180 ch === 0x24 /* $ */ ||
20181 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
20182 ch === 0x2E /* . */ ||
20183 ch === 0x3F /* ? */ ||
20184 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
20185 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
20186 )
20187}
20188
20189// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
20190// But eat eager.
20191pp$1.regexp_eatPatternCharacters = function(state) {
20192 var start = state.pos;
20193 var ch = 0;
20194 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
20195 state.advance();
20196 }
20197 return state.pos !== start
20198};
20199
20200// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
20201pp$1.regexp_eatExtendedPatternCharacter = function(state) {
20202 var ch = state.current();
20203 if (
20204 ch !== -1 &&
20205 ch !== 0x24 /* $ */ &&
20206 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
20207 ch !== 0x2E /* . */ &&
20208 ch !== 0x3F /* ? */ &&
20209 ch !== 0x5B /* [ */ &&
20210 ch !== 0x5E /* ^ */ &&
20211 ch !== 0x7C /* | */
20212 ) {
20213 state.advance();
20214 return true
20215 }
20216 return false
20217};
20218
20219// GroupSpecifier ::
20220// [empty]
20221// `?` GroupName
20222pp$1.regexp_groupSpecifier = function(state) {
20223 if (state.eat(0x3F /* ? */)) {
20224 if (this.regexp_eatGroupName(state)) {
20225 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
20226 state.raise("Duplicate capture group name");
20227 }
20228 state.groupNames.push(state.lastStringValue);
20229 return
20230 }
20231 state.raise("Invalid group");
20232 }
20233};
20234
20235// GroupName ::
20236// `<` RegExpIdentifierName `>`
20237// Note: this updates `state.lastStringValue` property with the eaten name.
20238pp$1.regexp_eatGroupName = function(state) {
20239 state.lastStringValue = "";
20240 if (state.eat(0x3C /* < */)) {
20241 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
20242 return true
20243 }
20244 state.raise("Invalid capture group name");
20245 }
20246 return false
20247};
20248
20249// RegExpIdentifierName ::
20250// RegExpIdentifierStart
20251// RegExpIdentifierName RegExpIdentifierPart
20252// Note: this updates `state.lastStringValue` property with the eaten name.
20253pp$1.regexp_eatRegExpIdentifierName = function(state) {
20254 state.lastStringValue = "";
20255 if (this.regexp_eatRegExpIdentifierStart(state)) {
20256 state.lastStringValue += codePointToString(state.lastIntValue);
20257 while (this.regexp_eatRegExpIdentifierPart(state)) {
20258 state.lastStringValue += codePointToString(state.lastIntValue);
20259 }
20260 return true
20261 }
20262 return false
20263};
20264
20265// RegExpIdentifierStart ::
20266// UnicodeIDStart
20267// `$`
20268// `_`
20269// `\` RegExpUnicodeEscapeSequence[+U]
20270pp$1.regexp_eatRegExpIdentifierStart = function(state) {
20271 var start = state.pos;
20272 var forceU = this.options.ecmaVersion >= 11;
20273 var ch = state.current(forceU);
20274 state.advance(forceU);
20275
20276 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20277 ch = state.lastIntValue;
20278 }
20279 if (isRegExpIdentifierStart(ch)) {
20280 state.lastIntValue = ch;
20281 return true
20282 }
20283
20284 state.pos = start;
20285 return false
20286};
20287function isRegExpIdentifierStart(ch) {
20288 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
20289}
20290
20291// RegExpIdentifierPart ::
20292// UnicodeIDContinue
20293// `$`
20294// `_`
20295// `\` RegExpUnicodeEscapeSequence[+U]
20296// <ZWNJ>
20297// <ZWJ>
20298pp$1.regexp_eatRegExpIdentifierPart = function(state) {
20299 var start = state.pos;
20300 var forceU = this.options.ecmaVersion >= 11;
20301 var ch = state.current(forceU);
20302 state.advance(forceU);
20303
20304 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
20305 ch = state.lastIntValue;
20306 }
20307 if (isRegExpIdentifierPart(ch)) {
20308 state.lastIntValue = ch;
20309 return true
20310 }
20311
20312 state.pos = start;
20313 return false
20314};
20315function isRegExpIdentifierPart(ch) {
20316 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
20317}
20318
20319// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
20320pp$1.regexp_eatAtomEscape = function(state) {
20321 if (
20322 this.regexp_eatBackReference(state) ||
20323 this.regexp_eatCharacterClassEscape(state) ||
20324 this.regexp_eatCharacterEscape(state) ||
20325 (state.switchN && this.regexp_eatKGroupName(state))
20326 ) {
20327 return true
20328 }
20329 if (state.switchU) {
20330 // Make the same message as V8.
20331 if (state.current() === 0x63 /* c */) {
20332 state.raise("Invalid unicode escape");
20333 }
20334 state.raise("Invalid escape");
20335 }
20336 return false
20337};
20338pp$1.regexp_eatBackReference = function(state) {
20339 var start = state.pos;
20340 if (this.regexp_eatDecimalEscape(state)) {
20341 var n = state.lastIntValue;
20342 if (state.switchU) {
20343 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
20344 if (n > state.maxBackReference) {
20345 state.maxBackReference = n;
20346 }
20347 return true
20348 }
20349 if (n <= state.numCapturingParens) {
20350 return true
20351 }
20352 state.pos = start;
20353 }
20354 return false
20355};
20356pp$1.regexp_eatKGroupName = function(state) {
20357 if (state.eat(0x6B /* k */)) {
20358 if (this.regexp_eatGroupName(state)) {
20359 state.backReferenceNames.push(state.lastStringValue);
20360 return true
20361 }
20362 state.raise("Invalid named reference");
20363 }
20364 return false
20365};
20366
20367// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
20368pp$1.regexp_eatCharacterEscape = function(state) {
20369 return (
20370 this.regexp_eatControlEscape(state) ||
20371 this.regexp_eatCControlLetter(state) ||
20372 this.regexp_eatZero(state) ||
20373 this.regexp_eatHexEscapeSequence(state) ||
20374 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
20375 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
20376 this.regexp_eatIdentityEscape(state)
20377 )
20378};
20379pp$1.regexp_eatCControlLetter = function(state) {
20380 var start = state.pos;
20381 if (state.eat(0x63 /* c */)) {
20382 if (this.regexp_eatControlLetter(state)) {
20383 return true
20384 }
20385 state.pos = start;
20386 }
20387 return false
20388};
20389pp$1.regexp_eatZero = function(state) {
20390 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
20391 state.lastIntValue = 0;
20392 state.advance();
20393 return true
20394 }
20395 return false
20396};
20397
20398// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
20399pp$1.regexp_eatControlEscape = function(state) {
20400 var ch = state.current();
20401 if (ch === 0x74 /* t */) {
20402 state.lastIntValue = 0x09; /* \t */
20403 state.advance();
20404 return true
20405 }
20406 if (ch === 0x6E /* n */) {
20407 state.lastIntValue = 0x0A; /* \n */
20408 state.advance();
20409 return true
20410 }
20411 if (ch === 0x76 /* v */) {
20412 state.lastIntValue = 0x0B; /* \v */
20413 state.advance();
20414 return true
20415 }
20416 if (ch === 0x66 /* f */) {
20417 state.lastIntValue = 0x0C; /* \f */
20418 state.advance();
20419 return true
20420 }
20421 if (ch === 0x72 /* r */) {
20422 state.lastIntValue = 0x0D; /* \r */
20423 state.advance();
20424 return true
20425 }
20426 return false
20427};
20428
20429// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
20430pp$1.regexp_eatControlLetter = function(state) {
20431 var ch = state.current();
20432 if (isControlLetter(ch)) {
20433 state.lastIntValue = ch % 0x20;
20434 state.advance();
20435 return true
20436 }
20437 return false
20438};
20439function isControlLetter(ch) {
20440 return (
20441 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
20442 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
20443 )
20444}
20445
20446// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
20447pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
20448 if ( forceU === void 0 ) forceU = false;
20449
20450 var start = state.pos;
20451 var switchU = forceU || state.switchU;
20452
20453 if (state.eat(0x75 /* u */)) {
20454 if (this.regexp_eatFixedHexDigits(state, 4)) {
20455 var lead = state.lastIntValue;
20456 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
20457 var leadSurrogateEnd = state.pos;
20458 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
20459 var trail = state.lastIntValue;
20460 if (trail >= 0xDC00 && trail <= 0xDFFF) {
20461 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
20462 return true
20463 }
20464 }
20465 state.pos = leadSurrogateEnd;
20466 state.lastIntValue = lead;
20467 }
20468 return true
20469 }
20470 if (
20471 switchU &&
20472 state.eat(0x7B /* { */) &&
20473 this.regexp_eatHexDigits(state) &&
20474 state.eat(0x7D /* } */) &&
20475 isValidUnicode(state.lastIntValue)
20476 ) {
20477 return true
20478 }
20479 if (switchU) {
20480 state.raise("Invalid unicode escape");
20481 }
20482 state.pos = start;
20483 }
20484
20485 return false
20486};
20487function isValidUnicode(ch) {
20488 return ch >= 0 && ch <= 0x10FFFF
20489}
20490
20491// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
20492pp$1.regexp_eatIdentityEscape = function(state) {
20493 if (state.switchU) {
20494 if (this.regexp_eatSyntaxCharacter(state)) {
20495 return true
20496 }
20497 if (state.eat(0x2F /* / */)) {
20498 state.lastIntValue = 0x2F; /* / */
20499 return true
20500 }
20501 return false
20502 }
20503
20504 var ch = state.current();
20505 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
20506 state.lastIntValue = ch;
20507 state.advance();
20508 return true
20509 }
20510
20511 return false
20512};
20513
20514// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
20515pp$1.regexp_eatDecimalEscape = function(state) {
20516 state.lastIntValue = 0;
20517 var ch = state.current();
20518 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
20519 do {
20520 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20521 state.advance();
20522 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
20523 return true
20524 }
20525 return false
20526};
20527
20528// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
20529pp$1.regexp_eatCharacterClassEscape = function(state) {
20530 var ch = state.current();
20531
20532 if (isCharacterClassEscape(ch)) {
20533 state.lastIntValue = -1;
20534 state.advance();
20535 return true
20536 }
20537
20538 if (
20539 state.switchU &&
20540 this.options.ecmaVersion >= 9 &&
20541 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
20542 ) {
20543 state.lastIntValue = -1;
20544 state.advance();
20545 if (
20546 state.eat(0x7B /* { */) &&
20547 this.regexp_eatUnicodePropertyValueExpression(state) &&
20548 state.eat(0x7D /* } */)
20549 ) {
20550 return true
20551 }
20552 state.raise("Invalid property name");
20553 }
20554
20555 return false
20556};
20557function isCharacterClassEscape(ch) {
20558 return (
20559 ch === 0x64 /* d */ ||
20560 ch === 0x44 /* D */ ||
20561 ch === 0x73 /* s */ ||
20562 ch === 0x53 /* S */ ||
20563 ch === 0x77 /* w */ ||
20564 ch === 0x57 /* W */
20565 )
20566}
20567
20568// UnicodePropertyValueExpression ::
20569// UnicodePropertyName `=` UnicodePropertyValue
20570// LoneUnicodePropertyNameOrValue
20571pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
20572 var start = state.pos;
20573
20574 // UnicodePropertyName `=` UnicodePropertyValue
20575 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
20576 var name = state.lastStringValue;
20577 if (this.regexp_eatUnicodePropertyValue(state)) {
20578 var value = state.lastStringValue;
20579 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
20580 return true
20581 }
20582 }
20583 state.pos = start;
20584
20585 // LoneUnicodePropertyNameOrValue
20586 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
20587 var nameOrValue = state.lastStringValue;
20588 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
20589 return true
20590 }
20591 return false
20592};
20593pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
20594 if (!hasOwn(state.unicodeProperties.nonBinary, name))
20595 { state.raise("Invalid property name"); }
20596 if (!state.unicodeProperties.nonBinary[name].test(value))
20597 { state.raise("Invalid property value"); }
20598};
20599pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
20600 if (!state.unicodeProperties.binary.test(nameOrValue))
20601 { state.raise("Invalid property name"); }
20602};
20603
20604// UnicodePropertyName ::
20605// UnicodePropertyNameCharacters
20606pp$1.regexp_eatUnicodePropertyName = function(state) {
20607 var ch = 0;
20608 state.lastStringValue = "";
20609 while (isUnicodePropertyNameCharacter(ch = state.current())) {
20610 state.lastStringValue += codePointToString(ch);
20611 state.advance();
20612 }
20613 return state.lastStringValue !== ""
20614};
20615function isUnicodePropertyNameCharacter(ch) {
20616 return isControlLetter(ch) || ch === 0x5F /* _ */
20617}
20618
20619// UnicodePropertyValue ::
20620// UnicodePropertyValueCharacters
20621pp$1.regexp_eatUnicodePropertyValue = function(state) {
20622 var ch = 0;
20623 state.lastStringValue = "";
20624 while (isUnicodePropertyValueCharacter(ch = state.current())) {
20625 state.lastStringValue += codePointToString(ch);
20626 state.advance();
20627 }
20628 return state.lastStringValue !== ""
20629};
20630function isUnicodePropertyValueCharacter(ch) {
20631 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
20632}
20633
20634// LoneUnicodePropertyNameOrValue ::
20635// UnicodePropertyValueCharacters
20636pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
20637 return this.regexp_eatUnicodePropertyValue(state)
20638};
20639
20640// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
20641pp$1.regexp_eatCharacterClass = function(state) {
20642 if (state.eat(0x5B /* [ */)) {
20643 state.eat(0x5E /* ^ */);
20644 this.regexp_classRanges(state);
20645 if (state.eat(0x5D /* ] */)) {
20646 return true
20647 }
20648 // Unreachable since it threw "unterminated regular expression" error before.
20649 state.raise("Unterminated character class");
20650 }
20651 return false
20652};
20653
20654// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
20655// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
20656// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
20657pp$1.regexp_classRanges = function(state) {
20658 while (this.regexp_eatClassAtom(state)) {
20659 var left = state.lastIntValue;
20660 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
20661 var right = state.lastIntValue;
20662 if (state.switchU && (left === -1 || right === -1)) {
20663 state.raise("Invalid character class");
20664 }
20665 if (left !== -1 && right !== -1 && left > right) {
20666 state.raise("Range out of order in character class");
20667 }
20668 }
20669 }
20670};
20671
20672// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
20673// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
20674pp$1.regexp_eatClassAtom = function(state) {
20675 var start = state.pos;
20676
20677 if (state.eat(0x5C /* \ */)) {
20678 if (this.regexp_eatClassEscape(state)) {
20679 return true
20680 }
20681 if (state.switchU) {
20682 // Make the same message as V8.
20683 var ch$1 = state.current();
20684 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
20685 state.raise("Invalid class escape");
20686 }
20687 state.raise("Invalid escape");
20688 }
20689 state.pos = start;
20690 }
20691
20692 var ch = state.current();
20693 if (ch !== 0x5D /* ] */) {
20694 state.lastIntValue = ch;
20695 state.advance();
20696 return true
20697 }
20698
20699 return false
20700};
20701
20702// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
20703pp$1.regexp_eatClassEscape = function(state) {
20704 var start = state.pos;
20705
20706 if (state.eat(0x62 /* b */)) {
20707 state.lastIntValue = 0x08; /* <BS> */
20708 return true
20709 }
20710
20711 if (state.switchU && state.eat(0x2D /* - */)) {
20712 state.lastIntValue = 0x2D; /* - */
20713 return true
20714 }
20715
20716 if (!state.switchU && state.eat(0x63 /* c */)) {
20717 if (this.regexp_eatClassControlLetter(state)) {
20718 return true
20719 }
20720 state.pos = start;
20721 }
20722
20723 return (
20724 this.regexp_eatCharacterClassEscape(state) ||
20725 this.regexp_eatCharacterEscape(state)
20726 )
20727};
20728
20729// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
20730pp$1.regexp_eatClassControlLetter = function(state) {
20731 var ch = state.current();
20732 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
20733 state.lastIntValue = ch % 0x20;
20734 state.advance();
20735 return true
20736 }
20737 return false
20738};
20739
20740// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20741pp$1.regexp_eatHexEscapeSequence = function(state) {
20742 var start = state.pos;
20743 if (state.eat(0x78 /* x */)) {
20744 if (this.regexp_eatFixedHexDigits(state, 2)) {
20745 return true
20746 }
20747 if (state.switchU) {
20748 state.raise("Invalid escape");
20749 }
20750 state.pos = start;
20751 }
20752 return false
20753};
20754
20755// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
20756pp$1.regexp_eatDecimalDigits = function(state) {
20757 var start = state.pos;
20758 var ch = 0;
20759 state.lastIntValue = 0;
20760 while (isDecimalDigit(ch = state.current())) {
20761 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
20762 state.advance();
20763 }
20764 return state.pos !== start
20765};
20766function isDecimalDigit(ch) {
20767 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
20768}
20769
20770// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
20771pp$1.regexp_eatHexDigits = function(state) {
20772 var start = state.pos;
20773 var ch = 0;
20774 state.lastIntValue = 0;
20775 while (isHexDigit(ch = state.current())) {
20776 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
20777 state.advance();
20778 }
20779 return state.pos !== start
20780};
20781function isHexDigit(ch) {
20782 return (
20783 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
20784 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
20785 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
20786 )
20787}
20788function hexToInt(ch) {
20789 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
20790 return 10 + (ch - 0x41 /* A */)
20791 }
20792 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
20793 return 10 + (ch - 0x61 /* a */)
20794 }
20795 return ch - 0x30 /* 0 */
20796}
20797
20798// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
20799// Allows only 0-377(octal) i.e. 0-255(decimal).
20800pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
20801 if (this.regexp_eatOctalDigit(state)) {
20802 var n1 = state.lastIntValue;
20803 if (this.regexp_eatOctalDigit(state)) {
20804 var n2 = state.lastIntValue;
20805 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
20806 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
20807 } else {
20808 state.lastIntValue = n1 * 8 + n2;
20809 }
20810 } else {
20811 state.lastIntValue = n1;
20812 }
20813 return true
20814 }
20815 return false
20816};
20817
20818// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
20819pp$1.regexp_eatOctalDigit = function(state) {
20820 var ch = state.current();
20821 if (isOctalDigit(ch)) {
20822 state.lastIntValue = ch - 0x30; /* 0 */
20823 state.advance();
20824 return true
20825 }
20826 state.lastIntValue = 0;
20827 return false
20828};
20829function isOctalDigit(ch) {
20830 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
20831}
20832
20833// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
20834// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
20835// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
20836pp$1.regexp_eatFixedHexDigits = function(state, length) {
20837 var start = state.pos;
20838 state.lastIntValue = 0;
20839 for (var i = 0; i < length; ++i) {
20840 var ch = state.current();
20841 if (!isHexDigit(ch)) {
20842 state.pos = start;
20843 return false
20844 }
20845 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
20846 state.advance();
20847 }
20848 return true
20849};
20850
20851// Object type used to represent tokens. Note that normally, tokens
20852// simply exist as properties on the parser object. This is only
20853// used for the onToken callback and the external tokenizer.
20854
20855var Token = function Token(p) {
20856 this.type = p.type;
20857 this.value = p.value;
20858 this.start = p.start;
20859 this.end = p.end;
20860 if (p.options.locations)
20861 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
20862 if (p.options.ranges)
20863 { this.range = [p.start, p.end]; }
20864};
20865
20866// ## Tokenizer
20867
20868var pp = Parser.prototype;
20869
20870// Move to the next token
20871
20872pp.next = function(ignoreEscapeSequenceInKeyword) {
20873 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
20874 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
20875 if (this.options.onToken)
20876 { this.options.onToken(new Token(this)); }
20877
20878 this.lastTokEnd = this.end;
20879 this.lastTokStart = this.start;
20880 this.lastTokEndLoc = this.endLoc;
20881 this.lastTokStartLoc = this.startLoc;
20882 this.nextToken();
20883};
20884
20885pp.getToken = function() {
20886 this.next();
20887 return new Token(this)
20888};
20889
20890// If we're in an ES6 environment, make parsers iterable
20891if (typeof Symbol !== "undefined")
20892 { pp[Symbol.iterator] = function() {
20893 var this$1$1 = this;
20894
20895 return {
20896 next: function () {
20897 var token = this$1$1.getToken();
20898 return {
20899 done: token.type === types$1.eof,
20900 value: token
20901 }
20902 }
20903 }
20904 }; }
20905
20906// Toggle strict mode. Re-reads the next number or string to please
20907// pedantic tests (`"use strict"; 010;` should fail).
20908
20909// Read a single token, updating the parser object's token-related
20910// properties.
20911
20912pp.nextToken = function() {
20913 var curContext = this.curContext();
20914 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
20915
20916 this.start = this.pos;
20917 if (this.options.locations) { this.startLoc = this.curPosition(); }
20918 if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
20919
20920 if (curContext.override) { return curContext.override(this) }
20921 else { this.readToken(this.fullCharCodeAtPos()); }
20922};
20923
20924pp.readToken = function(code) {
20925 // Identifier or keyword. '\uXXXX' sequences are allowed in
20926 // identifiers, so '\' also dispatches to that.
20927 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
20928 { return this.readWord() }
20929
20930 return this.getTokenFromCode(code)
20931};
20932
20933pp.fullCharCodeAtPos = function() {
20934 var code = this.input.charCodeAt(this.pos);
20935 if (code <= 0xd7ff || code >= 0xdc00) { return code }
20936 var next = this.input.charCodeAt(this.pos + 1);
20937 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
20938};
20939
20940pp.skipBlockComment = function() {
20941 var startLoc = this.options.onComment && this.curPosition();
20942 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
20943 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
20944 this.pos = end + 2;
20945 if (this.options.locations) {
20946 for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
20947 ++this.curLine;
20948 pos = this.lineStart = nextBreak;
20949 }
20950 }
20951 if (this.options.onComment)
20952 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
20953 startLoc, this.curPosition()); }
20954};
20955
20956pp.skipLineComment = function(startSkip) {
20957 var start = this.pos;
20958 var startLoc = this.options.onComment && this.curPosition();
20959 var ch = this.input.charCodeAt(this.pos += startSkip);
20960 while (this.pos < this.input.length && !isNewLine(ch)) {
20961 ch = this.input.charCodeAt(++this.pos);
20962 }
20963 if (this.options.onComment)
20964 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
20965 startLoc, this.curPosition()); }
20966};
20967
20968// Called at the start of the parse and after every token. Skips
20969// whitespace and comments, and.
20970
20971pp.skipSpace = function() {
20972 loop: while (this.pos < this.input.length) {
20973 var ch = this.input.charCodeAt(this.pos);
20974 switch (ch) {
20975 case 32: case 160: // ' '
20976 ++this.pos;
20977 break
20978 case 13:
20979 if (this.input.charCodeAt(this.pos + 1) === 10) {
20980 ++this.pos;
20981 }
20982 case 10: case 8232: case 8233:
20983 ++this.pos;
20984 if (this.options.locations) {
20985 ++this.curLine;
20986 this.lineStart = this.pos;
20987 }
20988 break
20989 case 47: // '/'
20990 switch (this.input.charCodeAt(this.pos + 1)) {
20991 case 42: // '*'
20992 this.skipBlockComment();
20993 break
20994 case 47:
20995 this.skipLineComment(2);
20996 break
20997 default:
20998 break loop
20999 }
21000 break
21001 default:
21002 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
21003 ++this.pos;
21004 } else {
21005 break loop
21006 }
21007 }
21008 }
21009};
21010
21011// Called at the end of every token. Sets `end`, `val`, and
21012// maintains `context` and `exprAllowed`, and skips the space after
21013// the token, so that the next one's `start` will point at the
21014// right position.
21015
21016pp.finishToken = function(type, val) {
21017 this.end = this.pos;
21018 if (this.options.locations) { this.endLoc = this.curPosition(); }
21019 var prevType = this.type;
21020 this.type = type;
21021 this.value = val;
21022
21023 this.updateContext(prevType);
21024};
21025
21026// ### Token reading
21027
21028// This is the function that is called to fetch the next token. It
21029// is somewhat obscure, because it works in character codes rather
21030// than characters, and because operator parsing has been inlined
21031// into it.
21032//
21033// All in the name of speed.
21034//
21035pp.readToken_dot = function() {
21036 var next = this.input.charCodeAt(this.pos + 1);
21037 if (next >= 48 && next <= 57) { return this.readNumber(true) }
21038 var next2 = this.input.charCodeAt(this.pos + 2);
21039 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
21040 this.pos += 3;
21041 return this.finishToken(types$1.ellipsis)
21042 } else {
21043 ++this.pos;
21044 return this.finishToken(types$1.dot)
21045 }
21046};
21047
21048pp.readToken_slash = function() { // '/'
21049 var next = this.input.charCodeAt(this.pos + 1);
21050 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
21051 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21052 return this.finishOp(types$1.slash, 1)
21053};
21054
21055pp.readToken_mult_modulo_exp = function(code) { // '%*'
21056 var next = this.input.charCodeAt(this.pos + 1);
21057 var size = 1;
21058 var tokentype = code === 42 ? types$1.star : types$1.modulo;
21059
21060 // exponentiation operator ** and **=
21061 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
21062 ++size;
21063 tokentype = types$1.starstar;
21064 next = this.input.charCodeAt(this.pos + 2);
21065 }
21066
21067 if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
21068 return this.finishOp(tokentype, size)
21069};
21070
21071pp.readToken_pipe_amp = function(code) { // '|&'
21072 var next = this.input.charCodeAt(this.pos + 1);
21073 if (next === code) {
21074 if (this.options.ecmaVersion >= 12) {
21075 var next2 = this.input.charCodeAt(this.pos + 2);
21076 if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
21077 }
21078 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
21079 }
21080 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21081 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
21082};
21083
21084pp.readToken_caret = function() { // '^'
21085 var next = this.input.charCodeAt(this.pos + 1);
21086 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21087 return this.finishOp(types$1.bitwiseXOR, 1)
21088};
21089
21090pp.readToken_plus_min = function(code) { // '+-'
21091 var next = this.input.charCodeAt(this.pos + 1);
21092 if (next === code) {
21093 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
21094 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
21095 // A `-->` line comment
21096 this.skipLineComment(3);
21097 this.skipSpace();
21098 return this.nextToken()
21099 }
21100 return this.finishOp(types$1.incDec, 2)
21101 }
21102 if (next === 61) { return this.finishOp(types$1.assign, 2) }
21103 return this.finishOp(types$1.plusMin, 1)
21104};
21105
21106pp.readToken_lt_gt = function(code) { // '<>'
21107 var next = this.input.charCodeAt(this.pos + 1);
21108 var size = 1;
21109 if (next === code) {
21110 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
21111 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
21112 return this.finishOp(types$1.bitShift, size)
21113 }
21114 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
21115 this.input.charCodeAt(this.pos + 3) === 45) {
21116 // `<!--`, an XML-style comment that should be interpreted as a line comment
21117 this.skipLineComment(4);
21118 this.skipSpace();
21119 return this.nextToken()
21120 }
21121 if (next === 61) { size = 2; }
21122 return this.finishOp(types$1.relational, size)
21123};
21124
21125pp.readToken_eq_excl = function(code) { // '=!'
21126 var next = this.input.charCodeAt(this.pos + 1);
21127 if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
21128 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
21129 this.pos += 2;
21130 return this.finishToken(types$1.arrow)
21131 }
21132 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
21133};
21134
21135pp.readToken_question = function() { // '?'
21136 var ecmaVersion = this.options.ecmaVersion;
21137 if (ecmaVersion >= 11) {
21138 var next = this.input.charCodeAt(this.pos + 1);
21139 if (next === 46) {
21140 var next2 = this.input.charCodeAt(this.pos + 2);
21141 if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
21142 }
21143 if (next === 63) {
21144 if (ecmaVersion >= 12) {
21145 var next2$1 = this.input.charCodeAt(this.pos + 2);
21146 if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
21147 }
21148 return this.finishOp(types$1.coalesce, 2)
21149 }
21150 }
21151 return this.finishOp(types$1.question, 1)
21152};
21153
21154pp.readToken_numberSign = function() { // '#'
21155 var ecmaVersion = this.options.ecmaVersion;
21156 var code = 35; // '#'
21157 if (ecmaVersion >= 13) {
21158 ++this.pos;
21159 code = this.fullCharCodeAtPos();
21160 if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
21161 return this.finishToken(types$1.privateId, this.readWord1())
21162 }
21163 }
21164
21165 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21166};
21167
21168pp.getTokenFromCode = function(code) {
21169 switch (code) {
21170 // The interpretation of a dot depends on whether it is followed
21171 // by a digit or another two dots.
21172 case 46: // '.'
21173 return this.readToken_dot()
21174
21175 // Punctuation tokens.
21176 case 40: ++this.pos; return this.finishToken(types$1.parenL)
21177 case 41: ++this.pos; return this.finishToken(types$1.parenR)
21178 case 59: ++this.pos; return this.finishToken(types$1.semi)
21179 case 44: ++this.pos; return this.finishToken(types$1.comma)
21180 case 91: ++this.pos; return this.finishToken(types$1.bracketL)
21181 case 93: ++this.pos; return this.finishToken(types$1.bracketR)
21182 case 123: ++this.pos; return this.finishToken(types$1.braceL)
21183 case 125: ++this.pos; return this.finishToken(types$1.braceR)
21184 case 58: ++this.pos; return this.finishToken(types$1.colon)
21185
21186 case 96: // '`'
21187 if (this.options.ecmaVersion < 6) { break }
21188 ++this.pos;
21189 return this.finishToken(types$1.backQuote)
21190
21191 case 48: // '0'
21192 var next = this.input.charCodeAt(this.pos + 1);
21193 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
21194 if (this.options.ecmaVersion >= 6) {
21195 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
21196 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
21197 }
21198
21199 // Anything else beginning with a digit is an integer, octal
21200 // number, or float.
21201 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
21202 return this.readNumber(false)
21203
21204 // Quotes produce strings.
21205 case 34: case 39: // '"', "'"
21206 return this.readString(code)
21207
21208 // Operators are parsed inline in tiny state machines. '=' (61) is
21209 // often referred to. `finishOp` simply skips the amount of
21210 // characters it is given as second argument, and returns a token
21211 // of the type given by its first argument.
21212 case 47: // '/'
21213 return this.readToken_slash()
21214
21215 case 37: case 42: // '%*'
21216 return this.readToken_mult_modulo_exp(code)
21217
21218 case 124: case 38: // '|&'
21219 return this.readToken_pipe_amp(code)
21220
21221 case 94: // '^'
21222 return this.readToken_caret()
21223
21224 case 43: case 45: // '+-'
21225 return this.readToken_plus_min(code)
21226
21227 case 60: case 62: // '<>'
21228 return this.readToken_lt_gt(code)
21229
21230 case 61: case 33: // '=!'
21231 return this.readToken_eq_excl(code)
21232
21233 case 63: // '?'
21234 return this.readToken_question()
21235
21236 case 126: // '~'
21237 return this.finishOp(types$1.prefix, 1)
21238
21239 case 35: // '#'
21240 return this.readToken_numberSign()
21241 }
21242
21243 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
21244};
21245
21246pp.finishOp = function(type, size) {
21247 var str = this.input.slice(this.pos, this.pos + size);
21248 this.pos += size;
21249 return this.finishToken(type, str)
21250};
21251
21252pp.readRegexp = function() {
21253 var escaped, inClass, start = this.pos;
21254 for (;;) {
21255 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
21256 var ch = this.input.charAt(this.pos);
21257 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
21258 if (!escaped) {
21259 if (ch === "[") { inClass = true; }
21260 else if (ch === "]" && inClass) { inClass = false; }
21261 else if (ch === "/" && !inClass) { break }
21262 escaped = ch === "\\";
21263 } else { escaped = false; }
21264 ++this.pos;
21265 }
21266 var pattern = this.input.slice(start, this.pos);
21267 ++this.pos;
21268 var flagsStart = this.pos;
21269 var flags = this.readWord1();
21270 if (this.containsEsc) { this.unexpected(flagsStart); }
21271
21272 // Validate pattern
21273 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
21274 state.reset(start, pattern, flags);
21275 this.validateRegExpFlags(state);
21276 this.validateRegExpPattern(state);
21277
21278 // Create Literal#value property value.
21279 var value = null;
21280 try {
21281 value = new RegExp(pattern, flags);
21282 } catch (e) {
21283 // ESTree requires null if it failed to instantiate RegExp object.
21284 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
21285 }
21286
21287 return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
21288};
21289
21290// Read an integer in the given radix. Return null if zero digits
21291// were read, the integer value otherwise. When `len` is given, this
21292// will return `null` unless the integer has exactly `len` digits.
21293
21294pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
21295 // `len` is used for character escape sequences. In that case, disallow separators.
21296 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
21297
21298 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
21299 // and isn't fraction part nor exponent part. In that case, if the first digit
21300 // is zero then disallow separators.
21301 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
21302
21303 var start = this.pos, total = 0, lastCode = 0;
21304 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
21305 var code = this.input.charCodeAt(this.pos), val = (void 0);
21306
21307 if (allowSeparators && code === 95) {
21308 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
21309 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
21310 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
21311 lastCode = code;
21312 continue
21313 }
21314
21315 if (code >= 97) { val = code - 97 + 10; } // a
21316 else if (code >= 65) { val = code - 65 + 10; } // A
21317 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
21318 else { val = Infinity; }
21319 if (val >= radix) { break }
21320 lastCode = code;
21321 total = total * radix + val;
21322 }
21323
21324 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
21325 if (this.pos === start || len != null && this.pos - start !== len) { return null }
21326
21327 return total
21328};
21329
21330function stringToNumber(str, isLegacyOctalNumericLiteral) {
21331 if (isLegacyOctalNumericLiteral) {
21332 return parseInt(str, 8)
21333 }
21334
21335 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
21336 return parseFloat(str.replace(/_/g, ""))
21337}
21338
21339function stringToBigInt(str) {
21340 if (typeof BigInt !== "function") {
21341 return null
21342 }
21343
21344 // `BigInt(value)` throws syntax error if the string contains numeric separators.
21345 return BigInt(str.replace(/_/g, ""))
21346}
21347
21348pp.readRadixNumber = function(radix) {
21349 var start = this.pos;
21350 this.pos += 2; // 0x
21351 var val = this.readInt(radix);
21352 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
21353 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
21354 val = stringToBigInt(this.input.slice(start, this.pos));
21355 ++this.pos;
21356 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21357 return this.finishToken(types$1.num, val)
21358};
21359
21360// Read an integer, octal integer, or floating-point number.
21361
21362pp.readNumber = function(startsWithDot) {
21363 var start = this.pos;
21364 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
21365 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
21366 if (octal && this.strict) { this.raise(start, "Invalid number"); }
21367 var next = this.input.charCodeAt(this.pos);
21368 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
21369 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
21370 ++this.pos;
21371 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21372 return this.finishToken(types$1.num, val$1)
21373 }
21374 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
21375 if (next === 46 && !octal) { // '.'
21376 ++this.pos;
21377 this.readInt(10);
21378 next = this.input.charCodeAt(this.pos);
21379 }
21380 if ((next === 69 || next === 101) && !octal) { // 'eE'
21381 next = this.input.charCodeAt(++this.pos);
21382 if (next === 43 || next === 45) { ++this.pos; } // '+-'
21383 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
21384 }
21385 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
21386
21387 var val = stringToNumber(this.input.slice(start, this.pos), octal);
21388 return this.finishToken(types$1.num, val)
21389};
21390
21391// Read a string value, interpreting backslash-escapes.
21392
21393pp.readCodePoint = function() {
21394 var ch = this.input.charCodeAt(this.pos), code;
21395
21396 if (ch === 123) { // '{'
21397 if (this.options.ecmaVersion < 6) { this.unexpected(); }
21398 var codePos = ++this.pos;
21399 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
21400 ++this.pos;
21401 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
21402 } else {
21403 code = this.readHexChar(4);
21404 }
21405 return code
21406};
21407
21408pp.readString = function(quote) {
21409 var out = "", chunkStart = ++this.pos;
21410 for (;;) {
21411 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
21412 var ch = this.input.charCodeAt(this.pos);
21413 if (ch === quote) { break }
21414 if (ch === 92) { // '\'
21415 out += this.input.slice(chunkStart, this.pos);
21416 out += this.readEscapedChar(false);
21417 chunkStart = this.pos;
21418 } else if (ch === 0x2028 || ch === 0x2029) {
21419 if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
21420 ++this.pos;
21421 if (this.options.locations) {
21422 this.curLine++;
21423 this.lineStart = this.pos;
21424 }
21425 } else {
21426 if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
21427 ++this.pos;
21428 }
21429 }
21430 out += this.input.slice(chunkStart, this.pos++);
21431 return this.finishToken(types$1.string, out)
21432};
21433
21434// Reads template string tokens.
21435
21436var INVALID_TEMPLATE_ESCAPE_ERROR = {};
21437
21438pp.tryReadTemplateToken = function() {
21439 this.inTemplateElement = true;
21440 try {
21441 this.readTmplToken();
21442 } catch (err) {
21443 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
21444 this.readInvalidTemplateToken();
21445 } else {
21446 throw err
21447 }
21448 }
21449
21450 this.inTemplateElement = false;
21451};
21452
21453pp.invalidStringToken = function(position, message) {
21454 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
21455 throw INVALID_TEMPLATE_ESCAPE_ERROR
21456 } else {
21457 this.raise(position, message);
21458 }
21459};
21460
21461pp.readTmplToken = function() {
21462 var out = "", chunkStart = this.pos;
21463 for (;;) {
21464 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
21465 var ch = this.input.charCodeAt(this.pos);
21466 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
21467 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
21468 if (ch === 36) {
21469 this.pos += 2;
21470 return this.finishToken(types$1.dollarBraceL)
21471 } else {
21472 ++this.pos;
21473 return this.finishToken(types$1.backQuote)
21474 }
21475 }
21476 out += this.input.slice(chunkStart, this.pos);
21477 return this.finishToken(types$1.template, out)
21478 }
21479 if (ch === 92) { // '\'
21480 out += this.input.slice(chunkStart, this.pos);
21481 out += this.readEscapedChar(true);
21482 chunkStart = this.pos;
21483 } else if (isNewLine(ch)) {
21484 out += this.input.slice(chunkStart, this.pos);
21485 ++this.pos;
21486 switch (ch) {
21487 case 13:
21488 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
21489 case 10:
21490 out += "\n";
21491 break
21492 default:
21493 out += String.fromCharCode(ch);
21494 break
21495 }
21496 if (this.options.locations) {
21497 ++this.curLine;
21498 this.lineStart = this.pos;
21499 }
21500 chunkStart = this.pos;
21501 } else {
21502 ++this.pos;
21503 }
21504 }
21505};
21506
21507// Reads a template token to search for the end, without validating any escape sequences
21508pp.readInvalidTemplateToken = function() {
21509 for (; this.pos < this.input.length; this.pos++) {
21510 switch (this.input[this.pos]) {
21511 case "\\":
21512 ++this.pos;
21513 break
21514
21515 case "$":
21516 if (this.input[this.pos + 1] !== "{") {
21517 break
21518 }
21519
21520 // falls through
21521 case "`":
21522 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
21523
21524 // no default
21525 }
21526 }
21527 this.raise(this.start, "Unterminated template");
21528};
21529
21530// Used to read escaped characters
21531
21532pp.readEscapedChar = function(inTemplate) {
21533 var ch = this.input.charCodeAt(++this.pos);
21534 ++this.pos;
21535 switch (ch) {
21536 case 110: return "\n" // 'n' -> '\n'
21537 case 114: return "\r" // 'r' -> '\r'
21538 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
21539 case 117: return codePointToString(this.readCodePoint()) // 'u'
21540 case 116: return "\t" // 't' -> '\t'
21541 case 98: return "\b" // 'b' -> '\b'
21542 case 118: return "\u000b" // 'v' -> '\u000b'
21543 case 102: return "\f" // 'f' -> '\f'
21544 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
21545 case 10: // ' \n'
21546 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
21547 return ""
21548 case 56:
21549 case 57:
21550 if (this.strict) {
21551 this.invalidStringToken(
21552 this.pos - 1,
21553 "Invalid escape sequence"
21554 );
21555 }
21556 if (inTemplate) {
21557 var codePos = this.pos - 1;
21558
21559 this.invalidStringToken(
21560 codePos,
21561 "Invalid escape sequence in template string"
21562 );
21563
21564 return null
21565 }
21566 default:
21567 if (ch >= 48 && ch <= 55) {
21568 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
21569 var octal = parseInt(octalStr, 8);
21570 if (octal > 255) {
21571 octalStr = octalStr.slice(0, -1);
21572 octal = parseInt(octalStr, 8);
21573 }
21574 this.pos += octalStr.length - 1;
21575 ch = this.input.charCodeAt(this.pos);
21576 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
21577 this.invalidStringToken(
21578 this.pos - 1 - octalStr.length,
21579 inTemplate
21580 ? "Octal literal in template string"
21581 : "Octal literal in strict mode"
21582 );
21583 }
21584 return String.fromCharCode(octal)
21585 }
21586 if (isNewLine(ch)) {
21587 // Unicode new line characters after \ get removed from output in both
21588 // template literals and strings
21589 return ""
21590 }
21591 return String.fromCharCode(ch)
21592 }
21593};
21594
21595// Used to read character escape sequences ('\x', '\u', '\U').
21596
21597pp.readHexChar = function(len) {
21598 var codePos = this.pos;
21599 var n = this.readInt(16, len);
21600 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
21601 return n
21602};
21603
21604// Read an identifier, and return it as a string. Sets `this.containsEsc`
21605// to whether the word contained a '\u' escape.
21606//
21607// Incrementally adds only escaped chars, adding other chunks as-is
21608// as a micro-optimization.
21609
21610pp.readWord1 = function() {
21611 this.containsEsc = false;
21612 var word = "", first = true, chunkStart = this.pos;
21613 var astral = this.options.ecmaVersion >= 6;
21614 while (this.pos < this.input.length) {
21615 var ch = this.fullCharCodeAtPos();
21616 if (isIdentifierChar(ch, astral)) {
21617 this.pos += ch <= 0xffff ? 1 : 2;
21618 } else if (ch === 92) { // "\"
21619 this.containsEsc = true;
21620 word += this.input.slice(chunkStart, this.pos);
21621 var escStart = this.pos;
21622 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
21623 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
21624 ++this.pos;
21625 var esc = this.readCodePoint();
21626 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
21627 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
21628 word += codePointToString(esc);
21629 chunkStart = this.pos;
21630 } else {
21631 break
21632 }
21633 first = false;
21634 }
21635 return word + this.input.slice(chunkStart, this.pos)
21636};
21637
21638// Read an identifier or keyword token. Will check for reserved
21639// words when necessary.
21640
21641pp.readWord = function() {
21642 var word = this.readWord1();
21643 var type = types$1.name;
21644 if (this.keywords.test(word)) {
21645 type = keywords[word];
21646 }
21647 return this.finishToken(type, word)
21648};
21649
21650// Acorn is a tiny, fast JavaScript parser written in JavaScript.
21651
21652var version = "8.7.1";
21653
21654Parser.acorn = {
21655 Parser: Parser,
21656 version: version,
21657 defaultOptions: defaultOptions,
21658 Position: Position,
21659 SourceLocation: SourceLocation,
21660 getLineInfo: getLineInfo,
21661 Node: Node,
21662 TokenType: TokenType,
21663 tokTypes: types$1,
21664 keywordTypes: keywords,
21665 TokContext: TokContext,
21666 tokContexts: types,
21667 isIdentifierChar: isIdentifierChar,
21668 isIdentifierStart: isIdentifierStart,
21669 Token: Token,
21670 isNewLine: isNewLine,
21671 lineBreak: lineBreak,
21672 lineBreakG: lineBreakG,
21673 nonASCIIwhitespace: nonASCIIwhitespace
21674};
21675
21676function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21677 let skipped = null;
21678 let replaceContext = null;
21679 if (skip) {
21680 skipped = new Set();
21681 for (const skippedCall of skip) {
21682 if (source === skippedCall.source && importer === skippedCall.importer) {
21683 skipped.add(skippedCall.plugin);
21684 }
21685 }
21686 replaceContext = (pluginContext, plugin) => ({
21687 ...pluginContext,
21688 resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
21689 return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
21690 }
21691 });
21692 }
21693 return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
21694}
21695
21696async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
21697 const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
21698 if (pluginResult != null)
21699 return pluginResult;
21700 // external modules (non-entry modules that start with neither '.' or '/')
21701 // are skipped at this stage.
21702 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
21703 return null;
21704 // `resolve` processes paths from right to left, prepending them until an
21705 // absolute path is created. Absolute importees therefore shortcircuit the
21706 // resolve call and require no special handing on our part.
21707 // See https://nodejs.org/api/path.html#path_path_resolve_paths
21708 return addJsExtensionIfNecessary(importer ? require$$0.resolve(require$$0.dirname(importer), source) : require$$0.resolve(source), preserveSymlinks);
21709}
21710async function addJsExtensionIfNecessary(file, preserveSymlinks) {
21711 var _a, _b;
21712 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)));
21713}
21714async function findFile(file, preserveSymlinks) {
21715 try {
21716 const stats = await require$$0$1.promises.lstat(file);
21717 if (!preserveSymlinks && stats.isSymbolicLink())
21718 return await findFile(await require$$0$1.promises.realpath(file), preserveSymlinks);
21719 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
21720 // check case
21721 const name = require$$0.basename(file);
21722 const files = await require$$0$1.promises.readdir(require$$0.dirname(file));
21723 if (files.includes(name))
21724 return file;
21725 }
21726 }
21727 catch (_a) {
21728 // suppress
21729 }
21730}
21731
21732const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
21733const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
21734function throwPluginError(err, plugin, { hook, id } = {}) {
21735 if (typeof err === 'string')
21736 err = { message: err };
21737 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
21738 err.pluginCode = err.code;
21739 }
21740 err.code = Errors.PLUGIN_ERROR;
21741 err.plugin = plugin;
21742 if (hook) {
21743 err.hook = hook;
21744 }
21745 if (id) {
21746 err.id = id;
21747 }
21748 return error(err);
21749}
21750const deprecatedHooks = [
21751 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
21752];
21753function warnDeprecatedHooks(plugins, options) {
21754 for (const { active, deprecated, replacement } of deprecatedHooks) {
21755 for (const plugin of plugins) {
21756 if (deprecated in plugin) {
21757 warnDeprecation({
21758 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
21759 plugin: plugin.name
21760 }, active, options);
21761 }
21762 }
21763 }
21764}
21765
21766function createPluginCache(cache) {
21767 return {
21768 delete(id) {
21769 return delete cache[id];
21770 },
21771 get(id) {
21772 const item = cache[id];
21773 if (!item)
21774 return undefined;
21775 item[0] = 0;
21776 return item[1];
21777 },
21778 has(id) {
21779 const item = cache[id];
21780 if (!item)
21781 return false;
21782 item[0] = 0;
21783 return true;
21784 },
21785 set(id, value) {
21786 cache[id] = [0, value];
21787 }
21788 };
21789}
21790function getTrackedPluginCache(pluginCache, onUse) {
21791 return {
21792 delete(id) {
21793 onUse();
21794 return pluginCache.delete(id);
21795 },
21796 get(id) {
21797 onUse();
21798 return pluginCache.get(id);
21799 },
21800 has(id) {
21801 onUse();
21802 return pluginCache.has(id);
21803 },
21804 set(id, value) {
21805 onUse();
21806 return pluginCache.set(id, value);
21807 }
21808 };
21809}
21810const NO_CACHE = {
21811 delete() {
21812 return false;
21813 },
21814 get() {
21815 return undefined;
21816 },
21817 has() {
21818 return false;
21819 },
21820 set() { }
21821};
21822function uncacheablePluginError(pluginName) {
21823 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
21824 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
21825 return error({
21826 code: 'ANONYMOUS_PLUGIN_CACHE',
21827 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
21828 });
21829 }
21830 return error({
21831 code: 'DUPLICATE_PLUGIN_NAME',
21832 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).`
21833 });
21834}
21835function getCacheForUncacheablePlugin(pluginName) {
21836 return {
21837 delete() {
21838 return uncacheablePluginError(pluginName);
21839 },
21840 get() {
21841 return uncacheablePluginError(pluginName);
21842 },
21843 has() {
21844 return uncacheablePluginError(pluginName);
21845 },
21846 set() {
21847 return uncacheablePluginError(pluginName);
21848 }
21849 };
21850}
21851
21852async function transform(source, module, pluginDriver, warn) {
21853 const id = module.id;
21854 const sourcemapChain = [];
21855 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
21856 const originalCode = source.code;
21857 let ast = source.ast;
21858 const transformDependencies = [];
21859 const emittedFiles = [];
21860 let customTransformCache = false;
21861 const useCustomTransformCache = () => (customTransformCache = true);
21862 let pluginName = '';
21863 const curSource = source.code;
21864 function transformReducer(previousCode, result, plugin) {
21865 let code;
21866 let map;
21867 if (typeof result === 'string') {
21868 code = result;
21869 }
21870 else if (result && typeof result === 'object') {
21871 module.updateOptions(result);
21872 if (result.code == null) {
21873 if (result.map || result.ast) {
21874 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
21875 }
21876 return previousCode;
21877 }
21878 ({ code, map, ast } = result);
21879 }
21880 else {
21881 return previousCode;
21882 }
21883 // strict null check allows 'null' maps to not be pushed to the chain,
21884 // while 'undefined' gets the missing map warning
21885 if (map !== null) {
21886 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
21887 missing: true,
21888 plugin: plugin.name
21889 });
21890 }
21891 return code;
21892 }
21893 let code;
21894 try {
21895 code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
21896 pluginName = plugin.name;
21897 return {
21898 ...pluginContext,
21899 addWatchFile(id) {
21900 transformDependencies.push(id);
21901 pluginContext.addWatchFile(id);
21902 },
21903 cache: customTransformCache
21904 ? pluginContext.cache
21905 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
21906 emitAsset(name, source) {
21907 emittedFiles.push({ name, source, type: 'asset' });
21908 return pluginContext.emitAsset(name, source);
21909 },
21910 emitChunk(id, options) {
21911 emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
21912 return pluginContext.emitChunk(id, options);
21913 },
21914 emitFile(emittedFile) {
21915 emittedFiles.push(emittedFile);
21916 return pluginDriver.emitFile(emittedFile);
21917 },
21918 error(err, pos) {
21919 if (typeof err === 'string')
21920 err = { message: err };
21921 if (pos)
21922 augmentCodeLocation(err, pos, curSource, id);
21923 err.id = id;
21924 err.hook = 'transform';
21925 return pluginContext.error(err);
21926 },
21927 getCombinedSourcemap() {
21928 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
21929 if (!combinedMap) {
21930 const magicString = new MagicString(originalCode);
21931 return magicString.generateMap({ hires: true, includeContent: true, source: id });
21932 }
21933 if (originalSourcemap !== combinedMap) {
21934 originalSourcemap = combinedMap;
21935 sourcemapChain.length = 0;
21936 }
21937 return new SourceMap({
21938 ...combinedMap,
21939 file: null,
21940 sourcesContent: combinedMap.sourcesContent
21941 });
21942 },
21943 setAssetSource() {
21944 return this.error({
21945 code: 'INVALID_SETASSETSOURCE',
21946 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
21947 });
21948 },
21949 warn(warning, pos) {
21950 if (typeof warning === 'string')
21951 warning = { message: warning };
21952 if (pos)
21953 augmentCodeLocation(warning, pos, curSource, id);
21954 warning.id = id;
21955 warning.hook = 'transform';
21956 pluginContext.warn(warning);
21957 }
21958 };
21959 });
21960 }
21961 catch (err) {
21962 throwPluginError(err, pluginName, { hook: 'transform', id });
21963 }
21964 if (!customTransformCache) {
21965 // files emitted by a transform hook need to be emitted again if the hook is skipped
21966 if (emittedFiles.length)
21967 module.transformFiles = emittedFiles;
21968 }
21969 return {
21970 ast,
21971 code,
21972 customTransformCache,
21973 originalCode,
21974 originalSourcemap,
21975 sourcemapChain,
21976 transformDependencies
21977 };
21978}
21979
21980const RESOLVE_DEPENDENCIES = 'resolveDependencies';
21981class ModuleLoader {
21982 constructor(graph, modulesById, options, pluginDriver) {
21983 this.graph = graph;
21984 this.modulesById = modulesById;
21985 this.options = options;
21986 this.pluginDriver = pluginDriver;
21987 this.implicitEntryModules = new Set();
21988 this.indexedEntryModules = [];
21989 this.latestLoadModulesPromise = Promise.resolve();
21990 this.moduleLoadPromises = new Map();
21991 this.modulesWithLoadedDependencies = new Set();
21992 this.nextChunkNamePriority = 0;
21993 this.nextEntryModuleIndex = 0;
21994 this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
21995 return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
21996 ? false
21997 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
21998 };
21999 this.hasModuleSideEffects = options.treeshake
22000 ? options.treeshake.moduleSideEffects
22001 : () => true;
22002 }
22003 async addAdditionalModules(unresolvedModules) {
22004 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
22005 await this.awaitLoadModulesPromise();
22006 return result;
22007 }
22008 async addEntryModules(unresolvedEntryModules, isUserDefined) {
22009 const firstEntryModuleIndex = this.nextEntryModuleIndex;
22010 this.nextEntryModuleIndex += unresolvedEntryModules.length;
22011 const firstChunkNamePriority = this.nextChunkNamePriority;
22012 this.nextChunkNamePriority += unresolvedEntryModules.length;
22013 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
22014 for (let index = 0; index < entryModules.length; index++) {
22015 const entryModule = entryModules[index];
22016 entryModule.isUserDefinedEntryPoint =
22017 entryModule.isUserDefinedEntryPoint || isUserDefined;
22018 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
22019 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
22020 if (!existingIndexedModule) {
22021 this.indexedEntryModules.push({
22022 index: firstEntryModuleIndex + index,
22023 module: entryModule
22024 });
22025 }
22026 else {
22027 existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
22028 }
22029 }
22030 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
22031 return entryModules;
22032 }));
22033 await this.awaitLoadModulesPromise();
22034 return {
22035 entryModules: this.indexedEntryModules.map(({ module }) => module),
22036 implicitEntryModules: [...this.implicitEntryModules],
22037 newEntryModules
22038 };
22039 }
22040 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
22041 const unresolvedModule = {
22042 fileName: fileName || null,
22043 id,
22044 importer,
22045 name: name || null
22046 };
22047 const module = implicitlyLoadedAfterOneOf
22048 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
22049 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
22050 if (preserveSignature != null) {
22051 module.preserveSignature = preserveSignature;
22052 }
22053 return module;
22054 }
22055 async preloadModule(resolvedId) {
22056 const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
22057 return module.info;
22058 }
22059 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
22060 const chunkNamePriority = this.nextChunkNamePriority++;
22061 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
22062 addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
22063 if (!entryModule.info.isEntry) {
22064 this.implicitEntryModules.add(entryModule);
22065 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
22066 for (const module of implicitlyLoadedAfterModules) {
22067 entryModule.implicitlyLoadedAfter.add(module);
22068 }
22069 for (const dependant of entryModule.implicitlyLoadedAfter) {
22070 dependant.implicitlyLoadedBefore.add(entryModule);
22071 }
22072 }
22073 return entryModule;
22074 }));
22075 }
22076 async addModuleSource(id, importer, module) {
22077 timeStart('load modules', 3);
22078 let source;
22079 try {
22080 source = await this.graph.fileOperationQueue.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')); });
22081 }
22082 catch (err) {
22083 timeEnd('load modules', 3);
22084 let msg = `Could not load ${id}`;
22085 if (importer)
22086 msg += ` (imported by ${relativeId(importer)})`;
22087 msg += `: ${err.message}`;
22088 err.message = msg;
22089 throw err;
22090 }
22091 timeEnd('load modules', 3);
22092 const sourceDescription = typeof source === 'string'
22093 ? { code: source }
22094 : source != null && typeof source === 'object' && typeof source.code === 'string'
22095 ? source
22096 : error(errBadLoader(id));
22097 const cachedModule = this.graph.cachedModules.get(id);
22098 if (cachedModule &&
22099 !cachedModule.customTransformCache &&
22100 cachedModule.originalCode === sourceDescription.code &&
22101 !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
22102 {
22103 ast: cachedModule.ast,
22104 code: cachedModule.code,
22105 id: cachedModule.id,
22106 meta: cachedModule.meta,
22107 moduleSideEffects: cachedModule.moduleSideEffects,
22108 resolvedSources: cachedModule.resolvedIds,
22109 syntheticNamedExports: cachedModule.syntheticNamedExports
22110 }
22111 ]))) {
22112 if (cachedModule.transformFiles) {
22113 for (const emittedFile of cachedModule.transformFiles)
22114 this.pluginDriver.emitFile(emittedFile);
22115 }
22116 module.setSource(cachedModule);
22117 }
22118 else {
22119 module.updateOptions(sourceDescription);
22120 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
22121 }
22122 }
22123 async awaitLoadModulesPromise() {
22124 let startingPromise;
22125 do {
22126 startingPromise = this.latestLoadModulesPromise;
22127 await startingPromise;
22128 } while (startingPromise !== this.latestLoadModulesPromise);
22129 }
22130 extendLoadModulesPromise(loadNewModulesPromise) {
22131 this.latestLoadModulesPromise = Promise.all([
22132 loadNewModulesPromise,
22133 this.latestLoadModulesPromise
22134 ]);
22135 this.latestLoadModulesPromise.catch(() => {
22136 /* Avoid unhandled Promise rejections */
22137 });
22138 return loadNewModulesPromise;
22139 }
22140 async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
22141 const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
22142 if (resolvedId === null)
22143 return null;
22144 if (typeof resolvedId === 'string') {
22145 dynamicImport.resolution = resolvedId;
22146 return null;
22147 }
22148 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
22149 })));
22150 for (const dependency of dependencies) {
22151 if (dependency) {
22152 module.dynamicDependencies.add(dependency);
22153 dependency.dynamicImporters.push(module.id);
22154 }
22155 }
22156 }
22157 // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
22158 // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
22159 // Otherwise it returns immediately.
22160 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
22161 const existingModule = this.modulesById.get(id);
22162 if (existingModule instanceof Module) {
22163 await this.handleExistingModule(existingModule, isEntry, isPreload);
22164 return existingModule;
22165 }
22166 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
22167 this.modulesById.set(id, module);
22168 this.graph.watchFiles[id] = true;
22169 const loadPromise = this.addModuleSource(id, importer, module).then(() => [
22170 this.getResolveStaticDependencyPromises(module),
22171 this.getResolveDynamicImportPromises(module),
22172 loadAndResolveDependenciesPromise
22173 ]);
22174 const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
22175 loadAndResolveDependenciesPromise.catch(() => {
22176 /* avoid unhandled promise rejections */
22177 });
22178 this.moduleLoadPromises.set(module, loadPromise);
22179 const resolveDependencyPromises = await loadPromise;
22180 if (!isPreload) {
22181 await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
22182 }
22183 else if (isPreload === RESOLVE_DEPENDENCIES) {
22184 await loadAndResolveDependenciesPromise;
22185 }
22186 return module;
22187 }
22188 async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
22189 if (this.modulesWithLoadedDependencies.has(module)) {
22190 return;
22191 }
22192 this.modulesWithLoadedDependencies.add(module);
22193 await Promise.all([
22194 this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
22195 this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
22196 ]);
22197 module.linkImports();
22198 // To handle errors when resolving dependencies or in moduleParsed
22199 await loadAndResolveDependenciesPromise;
22200 }
22201 fetchResolvedDependency(source, importer, resolvedId) {
22202 if (resolvedId.external) {
22203 const { external, id, moduleSideEffects, meta } = resolvedId;
22204 if (!this.modulesById.has(id)) {
22205 this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
22206 }
22207 const externalModule = this.modulesById.get(id);
22208 if (!(externalModule instanceof ExternalModule)) {
22209 return error(errInternalIdCannotBeExternal(source, importer));
22210 }
22211 return Promise.resolve(externalModule);
22212 }
22213 return this.fetchModule(resolvedId, importer, false, false);
22214 }
22215 async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
22216 for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
22217 module.dependencies.add(dependency);
22218 dependency.importers.push(module.id);
22219 }
22220 if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
22221 for (const dependency of module.dependencies) {
22222 if (dependency instanceof Module) {
22223 dependency.importedFromNotTreeshaken = true;
22224 }
22225 }
22226 }
22227 }
22228 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
22229 const { makeAbsoluteExternalsRelative } = this.options;
22230 if (resolveIdResult) {
22231 if (typeof resolveIdResult === 'object') {
22232 const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
22233 return {
22234 ...resolveIdResult,
22235 external: external &&
22236 (external === 'relative' ||
22237 !isAbsolute(resolveIdResult.id) ||
22238 (external === true &&
22239 isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
22240 'absolute')
22241 };
22242 }
22243 const external = this.options.external(resolveIdResult, importer, true);
22244 return {
22245 external: external &&
22246 (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
22247 'absolute'),
22248 id: external && makeAbsoluteExternalsRelative
22249 ? normalizeRelativeExternalId(resolveIdResult, importer)
22250 : resolveIdResult
22251 };
22252 }
22253 const id = makeAbsoluteExternalsRelative
22254 ? normalizeRelativeExternalId(source, importer)
22255 : source;
22256 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
22257 return null;
22258 }
22259 return {
22260 external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
22261 id
22262 };
22263 }
22264 getResolveDynamicImportPromises(module) {
22265 return module.dynamicImports.map(async (dynamicImport) => {
22266 const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
22267 ? dynamicImport.argument
22268 : dynamicImport.argument.esTreeNode, module.id);
22269 if (resolvedId && typeof resolvedId === 'object') {
22270 dynamicImport.id = resolvedId.id;
22271 }
22272 return [dynamicImport, resolvedId];
22273 });
22274 }
22275 getResolveStaticDependencyPromises(module) {
22276 return Array.from(module.sources, async (source) => [
22277 source,
22278 (module.resolvedIds[source] =
22279 module.resolvedIds[source] ||
22280 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
22281 ]);
22282 }
22283 getResolvedIdWithDefaults(resolvedId) {
22284 var _a, _b;
22285 if (!resolvedId) {
22286 return null;
22287 }
22288 const external = resolvedId.external || false;
22289 return {
22290 external,
22291 id: resolvedId.id,
22292 meta: resolvedId.meta || {},
22293 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
22294 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
22295 };
22296 }
22297 async handleExistingModule(module, isEntry, isPreload) {
22298 const loadPromise = this.moduleLoadPromises.get(module);
22299 if (isPreload) {
22300 return isPreload === RESOLVE_DEPENDENCIES
22301 ? waitForDependencyResolution(loadPromise)
22302 : loadPromise;
22303 }
22304 if (isEntry) {
22305 module.info.isEntry = true;
22306 this.implicitEntryModules.delete(module);
22307 for (const dependant of module.implicitlyLoadedAfter) {
22308 dependant.implicitlyLoadedBefore.delete(module);
22309 }
22310 module.implicitlyLoadedAfter.clear();
22311 }
22312 return this.fetchModuleDependencies(module, ...(await loadPromise));
22313 }
22314 handleResolveId(resolvedId, source, importer) {
22315 if (resolvedId === null) {
22316 if (isRelative(source)) {
22317 return error(errUnresolvedImport(source, importer));
22318 }
22319 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
22320 return {
22321 external: true,
22322 id: source,
22323 meta: {},
22324 moduleSideEffects: this.hasModuleSideEffects(source, true),
22325 syntheticNamedExports: false
22326 };
22327 }
22328 else if (resolvedId.external && resolvedId.syntheticNamedExports) {
22329 this.options.onwarn(errExternalSyntheticExports(source, importer));
22330 }
22331 return resolvedId;
22332 }
22333 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
22334 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
22335 if (resolveIdResult == null) {
22336 return error(implicitlyLoadedBefore === null
22337 ? errUnresolvedEntry(unresolvedId)
22338 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
22339 }
22340 if (resolveIdResult === false ||
22341 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
22342 return error(implicitlyLoadedBefore === null
22343 ? errEntryCannotBeExternal(unresolvedId)
22344 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
22345 }
22346 return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
22347 ? resolveIdResult
22348 : { id: resolveIdResult }), undefined, isEntry, false);
22349 }
22350 async resolveDynamicImport(module, specifier, importer) {
22351 var _a;
22352 var _b;
22353 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
22354 specifier,
22355 importer
22356 ]);
22357 if (typeof specifier !== 'string') {
22358 if (typeof resolution === 'string') {
22359 return resolution;
22360 }
22361 if (!resolution) {
22362 return null;
22363 }
22364 return {
22365 external: false,
22366 moduleSideEffects: true,
22367 ...resolution
22368 };
22369 }
22370 if (resolution == null) {
22371 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)));
22372 }
22373 return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
22374 }
22375}
22376function normalizeRelativeExternalId(source, importer) {
22377 return isRelative(source)
22378 ? importer
22379 ? require$$0.resolve(importer, '..', source)
22380 : require$$0.resolve(source)
22381 : source;
22382}
22383function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
22384 var _a;
22385 if (fileName !== null) {
22386 module.chunkFileNames.add(fileName);
22387 }
22388 else if (name !== null) {
22389 // Always keep chunkNames sorted by priority
22390 let namePosition = 0;
22391 while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
22392 namePosition++;
22393 module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
22394 }
22395}
22396function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
22397 return (makeAbsoluteExternalsRelative === true ||
22398 (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
22399 !isAbsolute(id));
22400}
22401async function waitForDependencyResolution(loadPromise) {
22402 const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
22403 return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
22404}
22405
22406class GlobalScope extends Scope$1 {
22407 constructor() {
22408 super();
22409 this.parent = null;
22410 this.variables.set('undefined', new UndefinedVariable());
22411 }
22412 findVariable(name) {
22413 let variable = this.variables.get(name);
22414 if (!variable) {
22415 variable = new GlobalVariable(name);
22416 this.variables.set(name, variable);
22417 }
22418 return variable;
22419 }
22420}
22421
22422function generateAssetFileName(name, source, outputOptions, bundle) {
22423 const emittedName = outputOptions.sanitizeFileName(name || 'asset');
22424 return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
22425 ? outputOptions.assetFileNames({ name, source, type: 'asset' })
22426 : outputOptions.assetFileNames, 'output.assetFileNames', {
22427 ext: () => require$$0.extname(emittedName).substring(1),
22428 extname: () => require$$0.extname(emittedName),
22429 hash() {
22430 return createHash()
22431 .update(emittedName)
22432 .update(':')
22433 .update(source)
22434 .digest('hex')
22435 .substring(0, 8);
22436 },
22437 name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
22438 }), bundle);
22439}
22440function reserveFileNameInBundle(fileName, bundle, warn) {
22441 const lowercaseFileName = fileName.toLowerCase();
22442 if (bundle[lowercaseBundleKeys].has(lowercaseFileName)) {
22443 warn(errFileNameConflict(fileName));
22444 }
22445 else {
22446 bundle[fileName] = FILE_PLACEHOLDER;
22447 }
22448}
22449function hasValidType(emittedFile) {
22450 return Boolean(emittedFile &&
22451 (emittedFile.type === 'asset' ||
22452 emittedFile.type === 'chunk'));
22453}
22454function hasValidName(emittedFile) {
22455 const validatedName = emittedFile.fileName || emittedFile.name;
22456 return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
22457}
22458function getValidSource(source, emittedFile, fileReferenceId) {
22459 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
22460 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
22461 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.`));
22462 }
22463 return source;
22464}
22465function getAssetFileName(file, referenceId) {
22466 if (typeof file.fileName !== 'string') {
22467 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
22468 }
22469 return file.fileName;
22470}
22471function getChunkFileName(file, facadeChunkByModule) {
22472 var _a;
22473 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));
22474 if (!fileName)
22475 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
22476 return fileName;
22477}
22478class FileEmitter {
22479 constructor(graph, options, baseFileEmitter) {
22480 this.graph = graph;
22481 this.options = options;
22482 this.bundle = null;
22483 this.facadeChunkByModule = null;
22484 this.outputOptions = null;
22485 this.assertAssetsFinalized = () => {
22486 for (const [referenceId, emittedFile] of this.filesByReferenceId) {
22487 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
22488 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
22489 }
22490 };
22491 this.emitFile = (emittedFile) => {
22492 if (!hasValidType(emittedFile)) {
22493 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
22494 }
22495 if (!hasValidName(emittedFile)) {
22496 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}".`));
22497 }
22498 if (emittedFile.type === 'chunk') {
22499 return this.emitChunk(emittedFile);
22500 }
22501 return this.emitAsset(emittedFile);
22502 };
22503 this.getFileName = (fileReferenceId) => {
22504 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
22505 if (!emittedFile)
22506 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
22507 if (emittedFile.type === 'chunk') {
22508 return getChunkFileName(emittedFile, this.facadeChunkByModule);
22509 }
22510 return getAssetFileName(emittedFile, fileReferenceId);
22511 };
22512 this.setAssetSource = (referenceId, requestedSource) => {
22513 const consumedFile = this.filesByReferenceId.get(referenceId);
22514 if (!consumedFile)
22515 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
22516 if (consumedFile.type !== 'asset') {
22517 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
22518 }
22519 if (consumedFile.source !== undefined) {
22520 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
22521 }
22522 const source = getValidSource(requestedSource, consumedFile, referenceId);
22523 if (this.bundle) {
22524 this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
22525 }
22526 else {
22527 consumedFile.source = source;
22528 }
22529 };
22530 this.setOutputBundle = (bundle, outputOptions, facadeChunkByModule) => {
22531 this.outputOptions = outputOptions;
22532 this.bundle = bundle;
22533 this.facadeChunkByModule = facadeChunkByModule;
22534 for (const { fileName } of this.filesByReferenceId.values()) {
22535 if (fileName) {
22536 reserveFileNameInBundle(fileName, bundle, this.options.onwarn);
22537 }
22538 }
22539 for (const [referenceId, consumedFile] of this.filesByReferenceId) {
22540 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
22541 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, bundle);
22542 }
22543 }
22544 };
22545 this.filesByReferenceId = baseFileEmitter
22546 ? new Map(baseFileEmitter.filesByReferenceId)
22547 : new Map();
22548 }
22549 assignReferenceId(file, idBase) {
22550 let referenceId;
22551 do {
22552 referenceId = createHash()
22553 .update(referenceId || idBase)
22554 .digest('hex')
22555 .substring(0, 8);
22556 } while (this.filesByReferenceId.has(referenceId));
22557 this.filesByReferenceId.set(referenceId, file);
22558 return referenceId;
22559 }
22560 emitAsset(emittedAsset) {
22561 const source = typeof emittedAsset.source !== 'undefined'
22562 ? getValidSource(emittedAsset.source, emittedAsset, null)
22563 : undefined;
22564 const consumedAsset = {
22565 fileName: emittedAsset.fileName,
22566 name: emittedAsset.name,
22567 source,
22568 type: 'asset'
22569 };
22570 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
22571 if (this.bundle) {
22572 if (emittedAsset.fileName) {
22573 reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
22574 }
22575 if (source !== undefined) {
22576 this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
22577 }
22578 }
22579 return referenceId;
22580 }
22581 emitChunk(emittedChunk) {
22582 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
22583 return error(errInvalidRollupPhaseForChunkEmission());
22584 }
22585 if (typeof emittedChunk.id !== 'string') {
22586 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
22587 }
22588 const consumedChunk = {
22589 fileName: emittedChunk.fileName,
22590 module: null,
22591 name: emittedChunk.name || emittedChunk.id,
22592 type: 'chunk'
22593 };
22594 this.graph.moduleLoader
22595 .emitChunk(emittedChunk)
22596 .then(module => (consumedChunk.module = module))
22597 .catch(() => {
22598 // Avoid unhandled Promise rejection as the error will be thrown later
22599 // once module loading has finished
22600 });
22601 return this.assignReferenceId(consumedChunk, emittedChunk.id);
22602 }
22603 finalizeAsset(consumedFile, source, referenceId, bundle) {
22604 const fileName = consumedFile.fileName ||
22605 findExistingAssetFileNameWithSource(bundle, source) ||
22606 generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
22607 // We must not modify the original assets to avoid interaction between outputs
22608 const assetWithFileName = { ...consumedFile, fileName, source };
22609 this.filesByReferenceId.set(referenceId, assetWithFileName);
22610 const { options } = this;
22611 bundle[fileName] = {
22612 fileName,
22613 get isAsset() {
22614 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
22615 return true;
22616 },
22617 name: consumedFile.name,
22618 source,
22619 type: 'asset'
22620 };
22621 }
22622}
22623// TODO This can lead to a performance problem when many assets are emitted.
22624// Instead, we should only deduplicate string assets and use their sources as
22625// object keys for better performance.
22626function findExistingAssetFileNameWithSource(bundle, source) {
22627 for (const [fileName, outputFile] of Object.entries(bundle)) {
22628 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
22629 return fileName;
22630 }
22631 return null;
22632}
22633function areSourcesEqual(sourceA, sourceB) {
22634 if (typeof sourceA === 'string') {
22635 return sourceA === sourceB;
22636 }
22637 if (typeof sourceB === 'string') {
22638 return false;
22639 }
22640 if ('equals' in sourceA) {
22641 return sourceA.equals(sourceB);
22642 }
22643 if (sourceA.length !== sourceB.length) {
22644 return false;
22645 }
22646 for (let index = 0; index < sourceA.length; index++) {
22647 if (sourceA[index] !== sourceB[index]) {
22648 return false;
22649 }
22650 }
22651 return true;
22652}
22653
22654function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
22655 let deprecationWarningShown = false;
22656 return ((...args) => {
22657 if (!deprecationWarningShown) {
22658 deprecationWarningShown = true;
22659 warnDeprecation({
22660 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
22661 plugin: pluginName
22662 }, activeDeprecation, options);
22663 }
22664 return handler(...args);
22665 });
22666}
22667function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
22668 let cacheable = true;
22669 if (typeof plugin.cacheKey !== 'string') {
22670 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
22671 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
22672 existingPluginNames.has(plugin.name)) {
22673 cacheable = false;
22674 }
22675 else {
22676 existingPluginNames.add(plugin.name);
22677 }
22678 }
22679 let cacheInstance;
22680 if (!pluginCache) {
22681 cacheInstance = NO_CACHE;
22682 }
22683 else if (cacheable) {
22684 const cacheKey = plugin.cacheKey || plugin.name;
22685 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
22686 }
22687 else {
22688 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
22689 }
22690 return {
22691 addWatchFile(id) {
22692 if (graph.phase >= BuildPhase.GENERATE) {
22693 return this.error(errInvalidRollupPhaseForAddWatchFile());
22694 }
22695 graph.watchFiles[id] = true;
22696 },
22697 cache: cacheInstance,
22698 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
22699 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
22700 emitFile: fileEmitter.emitFile.bind(fileEmitter),
22701 error(err) {
22702 return throwPluginError(err, plugin.name);
22703 },
22704 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
22705 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
22706 getFileName: fileEmitter.getFileName,
22707 getModuleIds: () => graph.modulesById.keys(),
22708 getModuleInfo: graph.getModuleInfo,
22709 getWatchFiles: () => Object.keys(graph.watchFiles),
22710 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
22711 load(resolvedId) {
22712 return graph.moduleLoader.preloadModule(resolvedId);
22713 },
22714 meta: {
22715 rollupVersion: version$1,
22716 watchMode: graph.watchMode
22717 },
22718 get moduleIds() {
22719 function* wrappedModuleIds() {
22720 // We are wrapping this in a generator to only show the message once we are actually iterating
22721 warnDeprecation({
22722 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
22723 plugin: plugin.name
22724 }, false, options);
22725 yield* moduleIds;
22726 }
22727 const moduleIds = graph.modulesById.keys();
22728 return wrappedModuleIds();
22729 },
22730 parse: graph.contextParse.bind(graph),
22731 resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
22732 return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
22733 },
22734 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
22735 .resolveId(source, importer, BLANK, undefined)
22736 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
22737 setAssetSource: fileEmitter.setAssetSource,
22738 warn(warning) {
22739 if (typeof warning === 'string')
22740 warning = { message: warning };
22741 if (warning.code)
22742 warning.pluginCode = warning.code;
22743 warning.code = 'PLUGIN_WARNING';
22744 warning.plugin = plugin.name;
22745 options.onwarn(warning);
22746 }
22747 };
22748}
22749
22750// This will make sure no input hook is omitted
22751const inputHookNames = {
22752 buildEnd: 1,
22753 buildStart: 1,
22754 closeBundle: 1,
22755 closeWatcher: 1,
22756 load: 1,
22757 moduleParsed: 1,
22758 options: 1,
22759 resolveDynamicImport: 1,
22760 resolveId: 1,
22761 shouldTransformCachedModule: 1,
22762 transform: 1,
22763 watchChange: 1
22764};
22765const inputHooks = Object.keys(inputHookNames);
22766class PluginDriver {
22767 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
22768 this.graph = graph;
22769 this.options = options;
22770 this.pluginCache = pluginCache;
22771 this.sortedPlugins = new Map();
22772 this.unfulfilledActions = new Set();
22773 warnDeprecatedHooks(userPlugins, options);
22774 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
22775 this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
22776 this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
22777 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
22778 this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22779 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
22780 const existingPluginNames = new Set();
22781 this.pluginContexts = new Map(this.plugins.map(plugin => [
22782 plugin,
22783 getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
22784 ]));
22785 if (basePluginDriver) {
22786 for (const plugin of userPlugins) {
22787 for (const hook of inputHooks) {
22788 if (hook in plugin) {
22789 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
22790 }
22791 }
22792 }
22793 }
22794 }
22795 createOutputPluginDriver(plugins) {
22796 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
22797 }
22798 getUnfulfilledHookActions() {
22799 return this.unfulfilledActions;
22800 }
22801 // chains, first non-null result stops and returns
22802 hookFirst(hookName, args, replaceContext, skipped) {
22803 let promise = Promise.resolve(null);
22804 for (const plugin of this.getSortedPlugins(hookName)) {
22805 if (skipped && skipped.has(plugin))
22806 continue;
22807 promise = promise.then(result => {
22808 if (result != null)
22809 return result;
22810 return this.runHook(hookName, args, plugin, replaceContext);
22811 });
22812 }
22813 return promise;
22814 }
22815 // chains synchronously, first non-null result stops and returns
22816 hookFirstSync(hookName, args, replaceContext) {
22817 for (const plugin of this.getSortedPlugins(hookName)) {
22818 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22819 if (result != null)
22820 return result;
22821 }
22822 return null;
22823 }
22824 // parallel, ignores returns
22825 async hookParallel(hookName, args, replaceContext) {
22826 const parallelPromises = [];
22827 for (const plugin of this.getSortedPlugins(hookName)) {
22828 if (plugin[hookName].sequential) {
22829 await Promise.all(parallelPromises);
22830 parallelPromises.length = 0;
22831 await this.runHook(hookName, args, plugin, replaceContext);
22832 }
22833 else {
22834 parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
22835 }
22836 }
22837 await Promise.all(parallelPromises);
22838 }
22839 // chains, reduces returned value, handling the reduced value as the first hook argument
22840 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
22841 let promise = Promise.resolve(arg0);
22842 for (const plugin of this.getSortedPlugins(hookName)) {
22843 promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
22844 }
22845 return promise;
22846 }
22847 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
22848 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
22849 for (const plugin of this.getSortedPlugins(hookName)) {
22850 const args = [arg0, ...rest];
22851 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22852 arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
22853 }
22854 return arg0;
22855 }
22856 // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
22857 async hookReduceValue(hookName, initialValue, args, reducer) {
22858 const results = [];
22859 const parallelResults = [];
22860 for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
22861 if (plugin[hookName].sequential) {
22862 results.push(...(await Promise.all(parallelResults)));
22863 parallelResults.length = 0;
22864 results.push(await this.runHook(hookName, args, plugin));
22865 }
22866 else {
22867 parallelResults.push(this.runHook(hookName, args, plugin));
22868 }
22869 }
22870 results.push(...(await Promise.all(parallelResults)));
22871 return results.reduce(reducer, await initialValue);
22872 }
22873 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
22874 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
22875 let acc = initialValue;
22876 for (const plugin of this.getSortedPlugins(hookName)) {
22877 const result = this.runHookSync(hookName, args, plugin, replaceContext);
22878 acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
22879 }
22880 return acc;
22881 }
22882 // chains, ignores returns
22883 hookSeq(hookName, args, replaceContext) {
22884 let promise = Promise.resolve();
22885 for (const plugin of this.getSortedPlugins(hookName)) {
22886 promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
22887 }
22888 return promise.then(noReturn);
22889 }
22890 getSortedPlugins(hookName, validateHandler) {
22891 return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
22892 }
22893 // Implementation signature
22894 runHook(hookName, args, plugin, replaceContext) {
22895 // We always filter for plugins that support the hook before running it
22896 const hook = plugin[hookName];
22897 const handler = typeof hook === 'object' ? hook.handler : hook;
22898 let context = this.pluginContexts.get(plugin);
22899 if (replaceContext) {
22900 context = replaceContext(context, plugin);
22901 }
22902 let action = null;
22903 return Promise.resolve()
22904 .then(() => {
22905 if (typeof handler !== 'function') {
22906 return handler;
22907 }
22908 // eslint-disable-next-line @typescript-eslint/ban-types
22909 const hookResult = handler.apply(context, args);
22910 if (!(hookResult === null || hookResult === void 0 ? void 0 : hookResult.then)) {
22911 // short circuit for non-thenables and non-Promises
22912 return hookResult;
22913 }
22914 // Track pending hook actions to properly error out when
22915 // unfulfilled promises cause rollup to abruptly and confusingly
22916 // exit with a successful 0 return code but without producing any
22917 // output, errors or warnings.
22918 action = [plugin.name, hookName, args];
22919 this.unfulfilledActions.add(action);
22920 // Although it would be more elegant to just return hookResult here
22921 // and put the .then() handler just above the .catch() handler below,
22922 // doing so would subtly change the defacto async event dispatch order
22923 // which at least one test and some plugins in the wild may depend on.
22924 return Promise.resolve(hookResult).then(result => {
22925 // action was fulfilled
22926 this.unfulfilledActions.delete(action);
22927 return result;
22928 });
22929 })
22930 .catch(err => {
22931 if (action !== null) {
22932 // action considered to be fulfilled since error being handled
22933 this.unfulfilledActions.delete(action);
22934 }
22935 return throwPluginError(err, plugin.name, { hook: hookName });
22936 });
22937 }
22938 /**
22939 * Run a sync plugin hook and return the result.
22940 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
22941 * @param args Arguments passed to the plugin hook.
22942 * @param plugin The acutal plugin
22943 * @param replaceContext When passed, the plugin context can be overridden.
22944 */
22945 runHookSync(hookName, args, plugin, replaceContext) {
22946 const hook = plugin[hookName];
22947 const handler = typeof hook === 'object' ? hook.handler : hook;
22948 let context = this.pluginContexts.get(plugin);
22949 if (replaceContext) {
22950 context = replaceContext(context, plugin);
22951 }
22952 try {
22953 // eslint-disable-next-line @typescript-eslint/ban-types
22954 return handler.apply(context, args);
22955 }
22956 catch (err) {
22957 return throwPluginError(err, plugin.name, { hook: hookName });
22958 }
22959 }
22960}
22961function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
22962 const pre = [];
22963 const normal = [];
22964 const post = [];
22965 for (const plugin of plugins) {
22966 const hook = plugin[hookName];
22967 if (hook) {
22968 if (typeof hook === 'object') {
22969 validateHandler(hook.handler, hookName, plugin);
22970 if (hook.order === 'pre') {
22971 pre.push(plugin);
22972 continue;
22973 }
22974 if (hook.order === 'post') {
22975 post.push(plugin);
22976 continue;
22977 }
22978 }
22979 else {
22980 validateHandler(hook, hookName, plugin);
22981 }
22982 normal.push(plugin);
22983 }
22984 }
22985 return [...pre, ...normal, ...post];
22986}
22987function validateFunctionPluginHandler(handler, hookName, plugin) {
22988 if (typeof handler !== 'function') {
22989 error(errInvalidFunctionPluginHook(hookName, plugin.name));
22990 }
22991}
22992function validateAddonPluginHandler(handler, hookName, plugin) {
22993 if (typeof handler !== 'string' && typeof handler !== 'function') {
22994 return error(errInvalidAddonPluginHook(hookName, plugin.name));
22995 }
22996}
22997function noReturn() { }
22998
22999class Queue {
23000 constructor(maxParallel) {
23001 this.maxParallel = maxParallel;
23002 this.queue = [];
23003 this.workerCount = 0;
23004 }
23005 run(task) {
23006 return new Promise((resolve, reject) => {
23007 this.queue.push({ reject, resolve, task });
23008 this.work();
23009 });
23010 }
23011 async work() {
23012 if (this.workerCount >= this.maxParallel)
23013 return;
23014 this.workerCount++;
23015 let entry;
23016 while ((entry = this.queue.shift())) {
23017 const { reject, resolve, task } = entry;
23018 try {
23019 const result = await task();
23020 resolve(result);
23021 }
23022 catch (err) {
23023 reject(err);
23024 }
23025 }
23026 this.workerCount--;
23027 }
23028}
23029
23030function normalizeEntryModules(entryModules) {
23031 if (Array.isArray(entryModules)) {
23032 return entryModules.map(id => ({
23033 fileName: null,
23034 id,
23035 implicitlyLoadedAfter: [],
23036 importer: undefined,
23037 name: null
23038 }));
23039 }
23040 return Object.entries(entryModules).map(([name, id]) => ({
23041 fileName: null,
23042 id,
23043 implicitlyLoadedAfter: [],
23044 importer: undefined,
23045 name
23046 }));
23047}
23048class Graph {
23049 constructor(options, watcher) {
23050 var _a, _b;
23051 this.options = options;
23052 this.cachedModules = new Map();
23053 this.deoptimizationTracker = new PathTracker();
23054 this.entryModules = [];
23055 this.modulesById = new Map();
23056 this.needsTreeshakingPass = false;
23057 this.phase = BuildPhase.LOAD_AND_PARSE;
23058 this.scope = new GlobalScope();
23059 this.watchFiles = Object.create(null);
23060 this.watchMode = false;
23061 this.externalModules = [];
23062 this.implicitEntryModules = [];
23063 this.modules = [];
23064 this.getModuleInfo = (moduleId) => {
23065 const foundModule = this.modulesById.get(moduleId);
23066 if (!foundModule)
23067 return null;
23068 return foundModule.info;
23069 };
23070 if (options.cache !== false) {
23071 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
23072 for (const module of options.cache.modules)
23073 this.cachedModules.set(module.id, module);
23074 }
23075 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
23076 // increment access counter
23077 for (const name in this.pluginCache) {
23078 const cache = this.pluginCache[name];
23079 for (const value of Object.values(cache))
23080 value[0]++;
23081 }
23082 }
23083 if (watcher) {
23084 this.watchMode = true;
23085 const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
23086 const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
23087 watcher.onCurrentAwaited('change', handleChange);
23088 watcher.onCurrentAwaited('close', handleClose);
23089 }
23090 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
23091 this.acornParser = Parser.extend(...options.acornInjectPlugins);
23092 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
23093 this.fileOperationQueue = new Queue(options.maxParallelFileOps);
23094 }
23095 async build() {
23096 timeStart('generate module graph', 2);
23097 await this.generateModuleGraph();
23098 timeEnd('generate module graph', 2);
23099 timeStart('sort modules', 2);
23100 this.phase = BuildPhase.ANALYSE;
23101 this.sortModules();
23102 timeEnd('sort modules', 2);
23103 timeStart('mark included statements', 2);
23104 this.includeStatements();
23105 timeEnd('mark included statements', 2);
23106 this.phase = BuildPhase.GENERATE;
23107 }
23108 contextParse(code, options = {}) {
23109 const onCommentOrig = options.onComment;
23110 const comments = [];
23111 if (onCommentOrig && typeof onCommentOrig == 'function') {
23112 options.onComment = (block, text, start, end, ...args) => {
23113 comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
23114 return onCommentOrig.call(options, block, text, start, end, ...args);
23115 };
23116 }
23117 else {
23118 options.onComment = comments;
23119 }
23120 const ast = this.acornParser.parse(code, {
23121 ...this.options.acorn,
23122 ...options
23123 });
23124 if (typeof onCommentOrig == 'object') {
23125 onCommentOrig.push(...comments);
23126 }
23127 options.onComment = onCommentOrig;
23128 addAnnotations(comments, ast, code);
23129 return ast;
23130 }
23131 getCache() {
23132 // handle plugin cache eviction
23133 for (const name in this.pluginCache) {
23134 const cache = this.pluginCache[name];
23135 let allDeleted = true;
23136 for (const [key, value] of Object.entries(cache)) {
23137 if (value[0] >= this.options.experimentalCacheExpiry)
23138 delete cache[key];
23139 else
23140 allDeleted = false;
23141 }
23142 if (allDeleted)
23143 delete this.pluginCache[name];
23144 }
23145 return {
23146 modules: this.modules.map(module => module.toJSON()),
23147 plugins: this.pluginCache
23148 };
23149 }
23150 async generateModuleGraph() {
23151 ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
23152 await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
23153 if (this.entryModules.length === 0) {
23154 throw new Error('You must supply options.input to rollup');
23155 }
23156 for (const module of this.modulesById.values()) {
23157 if (module instanceof Module) {
23158 this.modules.push(module);
23159 }
23160 else {
23161 this.externalModules.push(module);
23162 }
23163 }
23164 }
23165 includeStatements() {
23166 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23167 markModuleAndImpureDependenciesAsExecuted(module);
23168 }
23169 if (this.options.treeshake) {
23170 let treeshakingPass = 1;
23171 do {
23172 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
23173 this.needsTreeshakingPass = false;
23174 for (const module of this.modules) {
23175 if (module.isExecuted) {
23176 if (module.info.moduleSideEffects === 'no-treeshake') {
23177 module.includeAllInBundle();
23178 }
23179 else {
23180 module.include();
23181 }
23182 }
23183 }
23184 if (treeshakingPass === 1) {
23185 // We only include exports after the first pass to avoid issues with
23186 // the TDZ detection logic
23187 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
23188 if (module.preserveSignature !== false) {
23189 module.includeAllExports(false);
23190 this.needsTreeshakingPass = true;
23191 }
23192 }
23193 }
23194 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
23195 } while (this.needsTreeshakingPass);
23196 }
23197 else {
23198 for (const module of this.modules)
23199 module.includeAllInBundle();
23200 }
23201 for (const externalModule of this.externalModules)
23202 externalModule.warnUnusedImports();
23203 for (const module of this.implicitEntryModules) {
23204 for (const dependant of module.implicitlyLoadedAfter) {
23205 if (!(dependant.info.isEntry || dependant.isIncluded())) {
23206 error(errImplicitDependantIsNotIncluded(dependant));
23207 }
23208 }
23209 }
23210 }
23211 sortModules() {
23212 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
23213 for (const cyclePath of cyclePaths) {
23214 this.options.onwarn({
23215 code: 'CIRCULAR_DEPENDENCY',
23216 cycle: cyclePath,
23217 importer: cyclePath[0],
23218 message: `Circular dependency: ${cyclePath.join(' -> ')}`
23219 });
23220 }
23221 this.modules = orderedModules;
23222 for (const module of this.modules) {
23223 module.bindReferences();
23224 }
23225 this.warnForMissingExports();
23226 }
23227 warnForMissingExports() {
23228 for (const module of this.modules) {
23229 for (const importDescription of module.importDescriptions.values()) {
23230 if (importDescription.name !== '*' &&
23231 !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
23232 module.warn({
23233 code: 'NON_EXISTENT_EXPORT',
23234 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
23235 name: importDescription.name,
23236 source: importDescription.module.id
23237 }, importDescription.start);
23238 }
23239 }
23240 }
23241 }
23242}
23243
23244function formatAction([pluginName, hookName, args]) {
23245 const action = `(${pluginName}) ${hookName}`;
23246 const s = JSON.stringify;
23247 switch (hookName) {
23248 case 'resolveId':
23249 return `${action} ${s(args[0])} ${s(args[1])}`;
23250 case 'load':
23251 return `${action} ${s(args[0])}`;
23252 case 'transform':
23253 return `${action} ${s(args[1])}`;
23254 case 'shouldTransformCachedModule':
23255 return `${action} ${s(args[0].id)}`;
23256 case 'moduleParsed':
23257 return `${action} ${s(args[0].id)}`;
23258 }
23259 return action;
23260}
23261// We do not directly listen on process to avoid max listeners warnings for
23262// complicated build processes
23263const beforeExitEvent = 'beforeExit';
23264const beforeExitEmitter = new require$$0$2.EventEmitter();
23265beforeExitEmitter.setMaxListeners(0);
23266process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
23267async function catchUnfinishedHookActions(pluginDriver, callback) {
23268 let handleEmptyEventLoop;
23269 const emptyEventLoopPromise = new Promise((_, reject) => {
23270 handleEmptyEventLoop = () => {
23271 const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
23272 reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
23273 [...unfulfilledActions].map(formatAction).join('\n')));
23274 };
23275 beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
23276 });
23277 const result = await Promise.race([callback(), emptyEventLoopPromise]);
23278 beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
23279 return result;
23280}
23281
23282function normalizeInputOptions(config) {
23283 var _a, _b, _c;
23284 // These are options that may trigger special warnings or behaviour later
23285 // if the user did not select an explicit value
23286 const unsetOptions = new Set();
23287 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
23288 const onwarn = getOnwarn(config);
23289 const strictDeprecations = config.strictDeprecations || false;
23290 const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
23291 const options = {
23292 acorn: getAcorn(config),
23293 acornInjectPlugins: getAcornInjectPlugins(config),
23294 cache: getCache(config),
23295 context,
23296 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
23297 external: getIdMatcher(config.external),
23298 inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
23299 input: getInput(config),
23300 makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
23301 manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
23302 maxParallelFileOps,
23303 maxParallelFileReads: maxParallelFileOps,
23304 moduleContext: getModuleContext(config, context),
23305 onwarn,
23306 perf: config.perf || false,
23307 plugins: ensureArray$1(config.plugins),
23308 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
23309 preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
23310 preserveSymlinks: config.preserveSymlinks || false,
23311 shimMissingExports: config.shimMissingExports || false,
23312 strictDeprecations,
23313 treeshake: getTreeshake(config, onwarn, strictDeprecations)
23314 };
23315 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
23316 return { options, unsetOptions };
23317}
23318const getOnwarn = (config) => {
23319 const { onwarn } = config;
23320 return onwarn
23321 ? warning => {
23322 warning.toString = () => {
23323 let str = '';
23324 if (warning.plugin)
23325 str += `(${warning.plugin} plugin) `;
23326 if (warning.loc)
23327 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
23328 str += warning.message;
23329 return str;
23330 };
23331 onwarn(warning, defaultOnWarn);
23332 }
23333 : defaultOnWarn;
23334};
23335const getAcorn = (config) => ({
23336 allowAwaitOutsideFunction: true,
23337 ecmaVersion: 'latest',
23338 preserveParens: false,
23339 sourceType: 'module',
23340 ...config.acorn
23341});
23342const getAcornInjectPlugins = (config) => ensureArray$1(config.acornInjectPlugins);
23343const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
23344const getIdMatcher = (option) => {
23345 if (option === true) {
23346 return () => true;
23347 }
23348 if (typeof option === 'function') {
23349 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
23350 }
23351 if (option) {
23352 const ids = new Set();
23353 const matchers = [];
23354 for (const value of ensureArray$1(option)) {
23355 if (value instanceof RegExp) {
23356 matchers.push(value);
23357 }
23358 else {
23359 ids.add(value);
23360 }
23361 }
23362 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
23363 }
23364 return () => false;
23365};
23366const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
23367 const configInlineDynamicImports = config.inlineDynamicImports;
23368 if (configInlineDynamicImports) {
23369 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
23370 }
23371 return configInlineDynamicImports;
23372};
23373const getInput = (config) => {
23374 const configInput = config.input;
23375 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
23376};
23377const getManualChunks$1 = (config, warn, strictDeprecations) => {
23378 const configManualChunks = config.manualChunks;
23379 if (configManualChunks) {
23380 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
23381 }
23382 return configManualChunks;
23383};
23384const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
23385 var _a;
23386 const maxParallelFileReads = config.maxParallelFileReads;
23387 if (typeof maxParallelFileReads === 'number') {
23388 warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
23389 }
23390 const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
23391 if (typeof maxParallelFileOps === 'number') {
23392 if (maxParallelFileOps <= 0)
23393 return Infinity;
23394 return maxParallelFileOps;
23395 }
23396 return 20;
23397};
23398const getModuleContext = (config, context) => {
23399 const configModuleContext = config.moduleContext;
23400 if (typeof configModuleContext === 'function') {
23401 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
23402 }
23403 if (configModuleContext) {
23404 const contextByModuleId = Object.create(null);
23405 for (const [key, moduleContext] of Object.entries(configModuleContext)) {
23406 contextByModuleId[require$$0.resolve(key)] = moduleContext;
23407 }
23408 return id => contextByModuleId[id] || context;
23409 }
23410 return () => context;
23411};
23412const getPreserveEntrySignatures = (config, unsetOptions) => {
23413 const configPreserveEntrySignatures = config.preserveEntrySignatures;
23414 if (configPreserveEntrySignatures == null) {
23415 unsetOptions.add('preserveEntrySignatures');
23416 }
23417 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
23418};
23419const getPreserveModules$1 = (config, warn, strictDeprecations) => {
23420 const configPreserveModules = config.preserveModules;
23421 if (configPreserveModules) {
23422 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
23423 }
23424 return configPreserveModules;
23425};
23426const getTreeshake = (config, warn, strictDeprecations) => {
23427 const configTreeshake = config.treeshake;
23428 if (configTreeshake === false) {
23429 return false;
23430 }
23431 const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
23432 if (typeof configWithPreset.pureExternalModules !== 'undefined') {
23433 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);
23434 }
23435 return {
23436 annotations: configWithPreset.annotations !== false,
23437 correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
23438 moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
23439 ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
23440 : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
23441 propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
23442 ? 'always'
23443 : configWithPreset.propertyReadSideEffects !== false,
23444 tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
23445 unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
23446 };
23447};
23448const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
23449 if (typeof moduleSideEffectsOption === 'boolean') {
23450 return () => moduleSideEffectsOption;
23451 }
23452 if (moduleSideEffectsOption === 'no-external') {
23453 return (_id, external) => !external;
23454 }
23455 if (typeof moduleSideEffectsOption === 'function') {
23456 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
23457 }
23458 if (Array.isArray(moduleSideEffectsOption)) {
23459 const ids = new Set(moduleSideEffectsOption);
23460 return id => ids.has(id);
23461 }
23462 if (moduleSideEffectsOption) {
23463 error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23464 }
23465 const isPureExternalModule = getIdMatcher(pureExternalModules);
23466 return (id, external) => !(external && isPureExternalModule(id));
23467};
23468
23469// https://datatracker.ietf.org/doc/html/rfc2396
23470// eslint-disable-next-line no-control-regex
23471const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
23472const DRIVE_LETTER_REGEX = /^[a-z]:/i;
23473function sanitizeFileName(name) {
23474 const match = DRIVE_LETTER_REGEX.exec(name);
23475 const driveLetter = match ? match[0] : '';
23476 // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
23477 // Otherwise, avoid them because they can refer to NTFS alternate data streams.
23478 return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
23479}
23480
23481function isValidUrl(url) {
23482 try {
23483 new URL(url);
23484 }
23485 catch (_) {
23486 return false;
23487 }
23488 return true;
23489}
23490
23491function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23492 var _a, _b, _c, _d, _e, _f, _g;
23493 // These are options that may trigger special warnings or behaviour later
23494 // if the user did not select an explicit value
23495 const unsetOptions = new Set(unsetInputOptions);
23496 const compact = config.compact || false;
23497 const format = getFormat(config);
23498 const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
23499 const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
23500 const file = getFile(config, preserveModules, inputOptions);
23501 const preferConst = getPreferConst(config, inputOptions);
23502 const generatedCode = getGeneratedCode(config, preferConst);
23503 const outputOptions = {
23504 amd: getAmd(config),
23505 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
23506 banner: getAddon(config, 'banner'),
23507 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
23508 compact,
23509 dir: getDir(config, file),
23510 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
23511 entryFileNames: getEntryFileNames(config, unsetOptions),
23512 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
23513 exports: getExports(config, unsetOptions),
23514 extend: config.extend || false,
23515 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
23516 file,
23517 footer: getAddon(config, 'footer'),
23518 format,
23519 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
23520 generatedCode,
23521 globals: config.globals || {},
23522 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
23523 indent: getIndent(config, compact),
23524 inlineDynamicImports,
23525 interop: getInterop(config, inputOptions),
23526 intro: getAddon(config, 'intro'),
23527 manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
23528 minifyInternalExports: getMinifyInternalExports(config, format, compact),
23529 name: config.name,
23530 namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
23531 noConflict: config.noConflict || false,
23532 outro: getAddon(config, 'outro'),
23533 paths: config.paths || {},
23534 plugins: ensureArray$1(config.plugins),
23535 preferConst,
23536 preserveModules,
23537 preserveModulesRoot: getPreserveModulesRoot(config),
23538 sanitizeFileName: typeof config.sanitizeFileName === 'function'
23539 ? config.sanitizeFileName
23540 : config.sanitizeFileName === false
23541 ? id => id
23542 : sanitizeFileName,
23543 sourcemap: config.sourcemap || false,
23544 sourcemapBaseUrl: getSourcemapBaseUrl(config),
23545 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
23546 sourcemapFile: config.sourcemapFile,
23547 sourcemapPathTransform: config.sourcemapPathTransform,
23548 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
23549 systemNullSetters: config.systemNullSetters || false,
23550 validate: config.validate || false
23551 };
23552 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
23553 return { options: outputOptions, unsetOptions };
23554}
23555const getFile = (config, preserveModules, inputOptions) => {
23556 const { file } = config;
23557 if (typeof file === 'string') {
23558 if (preserveModules) {
23559 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
23560 }
23561 if (!Array.isArray(inputOptions.input))
23562 return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
23563 }
23564 return file;
23565};
23566const getFormat = (config) => {
23567 const configFormat = config.format;
23568 switch (configFormat) {
23569 case undefined:
23570 case 'es':
23571 case 'esm':
23572 case 'module':
23573 return 'es';
23574 case 'cjs':
23575 case 'commonjs':
23576 return 'cjs';
23577 case 'system':
23578 case 'systemjs':
23579 return 'system';
23580 case 'amd':
23581 case 'iife':
23582 case 'umd':
23583 return configFormat;
23584 default:
23585 return error({
23586 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
23587 url: `https://rollupjs.org/guide/en/#outputformat`
23588 });
23589 }
23590};
23591const getInlineDynamicImports = (config, inputOptions) => {
23592 var _a;
23593 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
23594 const { input } = inputOptions;
23595 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
23596 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
23597 }
23598 return inlineDynamicImports;
23599};
23600const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
23601 var _a;
23602 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
23603 if (preserveModules) {
23604 if (inlineDynamicImports) {
23605 return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
23606 }
23607 if (inputOptions.preserveEntrySignatures === false) {
23608 return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
23609 }
23610 }
23611 return preserveModules;
23612};
23613const getPreferConst = (config, inputOptions) => {
23614 const configPreferConst = config.preferConst;
23615 if (configPreferConst != null) {
23616 warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
23617 }
23618 return !!configPreferConst;
23619};
23620const getPreserveModulesRoot = (config) => {
23621 const { preserveModulesRoot } = config;
23622 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
23623 return undefined;
23624 }
23625 return require$$0.resolve(preserveModulesRoot);
23626};
23627const getAmd = (config) => {
23628 const mergedOption = {
23629 autoId: false,
23630 basePath: '',
23631 define: 'define',
23632 forceJsExtensionForImports: false,
23633 ...config.amd
23634 };
23635 if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
23636 return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
23637 }
23638 if (mergedOption.basePath && !mergedOption.autoId) {
23639 return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
23640 }
23641 let normalized;
23642 if (mergedOption.autoId) {
23643 normalized = {
23644 autoId: true,
23645 basePath: mergedOption.basePath,
23646 define: mergedOption.define,
23647 forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
23648 };
23649 }
23650 else {
23651 normalized = {
23652 autoId: false,
23653 define: mergedOption.define,
23654 forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
23655 id: mergedOption.id
23656 };
23657 }
23658 return normalized;
23659};
23660const getAddon = (config, name) => {
23661 const configAddon = config[name];
23662 if (typeof configAddon === 'function') {
23663 return configAddon;
23664 }
23665 return () => configAddon || '';
23666};
23667const getDir = (config, file) => {
23668 const { dir } = config;
23669 if (typeof dir === 'string' && typeof file === 'string') {
23670 return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
23671 }
23672 return dir;
23673};
23674const getDynamicImportFunction = (config, inputOptions) => {
23675 const configDynamicImportFunction = config.dynamicImportFunction;
23676 if (configDynamicImportFunction) {
23677 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
23678 }
23679 return configDynamicImportFunction;
23680};
23681const getEntryFileNames = (config, unsetOptions) => {
23682 const configEntryFileNames = config.entryFileNames;
23683 if (configEntryFileNames == null) {
23684 unsetOptions.add('entryFileNames');
23685 }
23686 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
23687};
23688function getExports(config, unsetOptions) {
23689 const configExports = config.exports;
23690 if (configExports == null) {
23691 unsetOptions.add('exports');
23692 }
23693 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
23694 return error(errInvalidExportOptionValue(configExports));
23695 }
23696 return configExports || 'auto';
23697}
23698const getGeneratedCode = (config, preferConst) => {
23699 const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
23700 return {
23701 arrowFunctions: configWithPreset.arrowFunctions === true,
23702 constBindings: configWithPreset.constBindings === true || preferConst,
23703 objectShorthand: configWithPreset.objectShorthand === true,
23704 reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
23705 symbols: configWithPreset.symbols === true
23706 };
23707};
23708const getIndent = (config, compact) => {
23709 if (compact) {
23710 return '';
23711 }
23712 const configIndent = config.indent;
23713 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
23714};
23715const ALLOWED_INTEROP_TYPES = new Set([
23716 'auto',
23717 'esModule',
23718 'default',
23719 'defaultOnly',
23720 true,
23721 false
23722]);
23723const getInterop = (config, inputOptions) => {
23724 const configInterop = config.interop;
23725 const validatedInteropTypes = new Set();
23726 const validateInterop = (interop) => {
23727 if (!validatedInteropTypes.has(interop)) {
23728 validatedInteropTypes.add(interop);
23729 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
23730 return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
23731 }
23732 if (typeof interop === 'boolean') {
23733 warnDeprecation({
23734 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
23735 url: 'https://rollupjs.org/guide/en/#outputinterop'
23736 }, false, inputOptions);
23737 }
23738 }
23739 return interop;
23740 };
23741 if (typeof configInterop === 'function') {
23742 const interopPerId = Object.create(null);
23743 let defaultInterop = null;
23744 return id => id === null
23745 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
23746 : id in interopPerId
23747 ? interopPerId[id]
23748 : validateInterop((interopPerId[id] = configInterop(id)));
23749 }
23750 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
23751};
23752const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
23753 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
23754 if (configManualChunks) {
23755 if (inlineDynamicImports) {
23756 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
23757 }
23758 if (preserveModules) {
23759 return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
23760 }
23761 }
23762 return configManualChunks || {};
23763};
23764const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
23765const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
23766 const configNamespaceToStringTag = config.namespaceToStringTag;
23767 if (configNamespaceToStringTag != null) {
23768 warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
23769 return configNamespaceToStringTag;
23770 }
23771 return generatedCode.symbols || false;
23772};
23773const getSourcemapBaseUrl = (config) => {
23774 const { sourcemapBaseUrl } = config;
23775 if (sourcemapBaseUrl) {
23776 if (isValidUrl(sourcemapBaseUrl)) {
23777 return sourcemapBaseUrl;
23778 }
23779 return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
23780 }
23781};
23782
23783function rollup(rawInputOptions) {
23784 return rollupInternal(rawInputOptions, null);
23785}
23786async function rollupInternal(rawInputOptions, watcher) {
23787 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
23788 initialiseTimers(inputOptions);
23789 const graph = new Graph(inputOptions, watcher);
23790 // remove the cache option from the memory after graph creation (cache is not used anymore)
23791 const useCache = rawInputOptions.cache !== false;
23792 delete inputOptions.cache;
23793 delete rawInputOptions.cache;
23794 timeStart('BUILD', 1);
23795 await catchUnfinishedHookActions(graph.pluginDriver, async () => {
23796 try {
23797 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
23798 await graph.build();
23799 }
23800 catch (err) {
23801 const watchFiles = Object.keys(graph.watchFiles);
23802 if (watchFiles.length > 0) {
23803 err.watchFiles = watchFiles;
23804 }
23805 await graph.pluginDriver.hookParallel('buildEnd', [err]);
23806 await graph.pluginDriver.hookParallel('closeBundle', []);
23807 throw err;
23808 }
23809 await graph.pluginDriver.hookParallel('buildEnd', []);
23810 });
23811 timeEnd('BUILD', 1);
23812 const result = {
23813 cache: useCache ? graph.getCache() : undefined,
23814 async close() {
23815 if (result.closed)
23816 return;
23817 result.closed = true;
23818 await graph.pluginDriver.hookParallel('closeBundle', []);
23819 },
23820 closed: false,
23821 async generate(rawOutputOptions) {
23822 if (result.closed)
23823 return error(errAlreadyClosed());
23824 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23825 },
23826 watchFiles: Object.keys(graph.watchFiles),
23827 async write(rawOutputOptions) {
23828 if (result.closed)
23829 return error(errAlreadyClosed());
23830 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
23831 }
23832 };
23833 if (inputOptions.perf)
23834 result.getTimings = getTimings;
23835 return result;
23836}
23837async function getInputOptions(rawInputOptions, watchMode) {
23838 if (!rawInputOptions) {
23839 throw new Error('You must supply an options object to rollup');
23840 }
23841 const rawPlugins = getSortedValidatedPlugins('options', ensureArray$1(rawInputOptions.plugins));
23842 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
23843 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
23844 return { options, unsetOptions };
23845}
23846function applyOptionHook(watchMode) {
23847 return async (inputOptions, plugin) => {
23848 const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
23849 return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
23850 };
23851}
23852function normalizePlugins(plugins, anonymousPrefix) {
23853 plugins.forEach((plugin, index) => {
23854 if (!plugin.name) {
23855 plugin.name = `${anonymousPrefix}${index + 1}`;
23856 }
23857 });
23858}
23859function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
23860 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
23861 return catchUnfinishedHookActions(outputPluginDriver, async () => {
23862 const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
23863 const generated = await bundle.generate(isWrite);
23864 if (isWrite) {
23865 if (!outputOptions.dir && !outputOptions.file) {
23866 return error({
23867 code: 'MISSING_OPTION',
23868 message: 'You must specify "output.file" or "output.dir" for the build.'
23869 });
23870 }
23871 await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
23872 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
23873 }
23874 return createOutput(generated);
23875 });
23876}
23877function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
23878 if (!rawOutputOptions) {
23879 throw new Error('You must supply an options object');
23880 }
23881 const rawPlugins = ensureArray$1(rawOutputOptions.plugins);
23882 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
23883 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
23884 return {
23885 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
23886 outputPluginDriver
23887 };
23888}
23889function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
23890 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
23891 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
23892 return {
23893 ...pluginContext,
23894 emitFile: emitError,
23895 setAssetSource: emitError
23896 };
23897 }), inputOptions, unsetInputOptions);
23898}
23899function createOutput(outputBundle) {
23900 return {
23901 output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
23902 };
23903}
23904var SortingFileType;
23905(function (SortingFileType) {
23906 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
23907 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
23908 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
23909})(SortingFileType || (SortingFileType = {}));
23910function getSortingFileType(file) {
23911 if (file.type === 'asset') {
23912 return SortingFileType.ASSET;
23913 }
23914 if (file.isEntry) {
23915 return SortingFileType.ENTRY_CHUNK;
23916 }
23917 return SortingFileType.SECONDARY_CHUNK;
23918}
23919async function writeOutputFile(outputFile, outputOptions) {
23920 const fileName = require$$0.resolve(outputOptions.dir || require$$0.dirname(outputOptions.file), outputFile.fileName);
23921 // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
23922 await require$$0$1.promises.mkdir(require$$0.dirname(fileName), { recursive: true });
23923 let writeSourceMapPromise;
23924 let source;
23925 if (outputFile.type === 'asset') {
23926 source = outputFile.source;
23927 }
23928 else {
23929 source = outputFile.code;
23930 if (outputOptions.sourcemap && outputFile.map) {
23931 let url;
23932 if (outputOptions.sourcemap === 'inline') {
23933 url = outputFile.map.toUrl();
23934 }
23935 else {
23936 const { sourcemapBaseUrl } = outputOptions;
23937 const sourcemapFileName = `${require$$0.basename(outputFile.fileName)}.map`;
23938 url = sourcemapBaseUrl
23939 ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
23940 : sourcemapFileName;
23941 writeSourceMapPromise = require$$0$1.promises.writeFile(`${fileName}.map`, outputFile.map.toString());
23942 }
23943 if (outputOptions.sourcemap !== 'hidden') {
23944 source += `//# ${exports.SOURCEMAPPING_URL}=${url}\n`;
23945 }
23946 }
23947 }
23948 return Promise.all([require$$0$1.promises.writeFile(fileName, source), writeSourceMapPromise]);
23949}
23950/**
23951 * Auxiliary function for defining rollup configuration
23952 * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
23953 * @param options
23954 */
23955function defineConfig(options) {
23956 return options;
23957}
23958
23959class WatchEmitter extends require$$0$2.EventEmitter {
23960 constructor() {
23961 super();
23962 this.awaitedHandlers = Object.create(null);
23963 // Allows more than 10 bundles to be watched without
23964 // showing the `MaxListenersExceededWarning` to the user.
23965 this.setMaxListeners(Infinity);
23966 }
23967 // Will be overwritten by Rollup
23968 async close() { }
23969 emitAndAwait(event, ...args) {
23970 this.emit(event, ...args);
23971 return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
23972 }
23973 onCurrentAwaited(event, listener) {
23974 this.getHandlers(event).push(listener);
23975 return this;
23976 }
23977 removeAwaited() {
23978 this.awaitedHandlers = {};
23979 return this;
23980 }
23981 getHandlers(event) {
23982 return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
23983 }
23984}
23985
23986function watch(configs) {
23987 const emitter = new WatchEmitter();
23988 const configArray = ensureArray$1(configs);
23989 const watchConfigs = configArray.filter(config => config.watch !== false);
23990 if (watchConfigs.length === 0) {
23991 return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
23992 }
23993 loadFsEvents()
23994 .then(() => Promise.resolve().then(() => require('./watch.js')))
23995 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
23996 return emitter;
23997}
23998
23999exports.commonjsGlobal = commonjsGlobal;
24000exports.createFilter = createFilter;
24001exports.defaultOnWarn = defaultOnWarn;
24002exports.defineConfig = defineConfig;
24003exports.ensureArray = ensureArray$1;
24004exports.error = error;
24005exports.fseventsImporter = fseventsImporter;
24006exports.generatedCodePresets = generatedCodePresets;
24007exports.getAliasName = getAliasName;
24008exports.getAugmentedNamespace = getAugmentedNamespace;
24009exports.getOrCreate = getOrCreate;
24010exports.loadFsEvents = loadFsEvents;
24011exports.objectifyOption = objectifyOption;
24012exports.objectifyOptionWithPresets = objectifyOptionWithPresets;
24013exports.picomatch = picomatch$1;
24014exports.printQuotedStringList = printQuotedStringList;
24015exports.relativeId = relativeId;
24016exports.rollup = rollup;
24017exports.rollupInternal = rollupInternal;
24018exports.treeshakePresets = treeshakePresets;
24019exports.version = version$1;
24020exports.warnUnknownOptions = warnUnknownOptions;
24021exports.watch = watch;
24022//# sourceMappingURL=rollup.js.map
Note: See TracBrowser for help on using the repository browser.