lib/condenser/processors/node_modules/rollup/dist/rollup.es.js in condenser-0.0.5 vs lib/condenser/processors/node_modules/rollup/dist/rollup.es.js in condenser-0.0.7

- old
+ new

@@ -1,25 +1,58 @@ /* @license - Rollup.js v1.17.0 - Mon, 15 Jul 2019 04:31:04 GMT - commit 5d1541a577b06d9004a3533bde672761e5798482 + Rollup.js v1.20.2 + Sun, 25 Aug 2019 05:31:46 GMT - commit b1747e49d9659799a8c128d3052e5e5703362c37 https://github.com/rollup/rollup Released under the MIT License. */ import util from 'util'; import path, { relative as relative$1, extname, basename, dirname, resolve, sep } from 'path'; import { writeFile as writeFile$1, readdirSync, mkdirSync, readFile as readFile$1, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs'; import * as acorn__default from 'acorn'; -import { tokTypes, Parser } from 'acorn'; +import { Parser } from 'acorn'; import { EventEmitter } from 'events'; -import module$1 from 'module'; +import module from 'module'; -var version = "1.17.0"; +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { + step(generator.next(value)); + } + catch (e) { + reject(e); + } } + function rejected(value) { try { + step(generator["throw"](value)); + } + catch (e) { + reject(e); + } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +var version = "1.20.2"; + var minimalisticAssert = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } @@ -1883,57 +1916,49 @@ } } } const NO_SEMICOLON = { isNoStatement: true }; +// This assumes there are only white-space and comments between start and the string we are looking for function findFirstOccurrenceOutsideComment(code, searchString, start = 0) { let searchPos, charCodeAfterSlash; searchPos = code.indexOf(searchString, start); while (true) { start = code.indexOf('/', start); if (start === -1 || start > searchPos) return searchPos; charCodeAfterSlash = code.charCodeAt(++start); ++start; - if (charCodeAfterSlash === 47 /*"/"*/) { - start = code.indexOf('\n', start) + 1; - if (start === 0) - return -1; - if (start > searchPos) { - searchPos = code.indexOf(searchString, start); - } + // With our assumption, '/' always starts a comment. Determine comment type: + start = + charCodeAfterSlash === 47 /*"/"*/ + ? code.indexOf('\n', start) + 1 + : code.indexOf('*/', start) + 2; + if (start > searchPos) { + searchPos = code.indexOf(searchString, start); } - else if (charCodeAfterSlash === 42 /*"*"*/) { - start = code.indexOf('*/', start) + 2; - if (start > searchPos) { - searchPos = code.indexOf(searchString, start); - } - } } } -function findFirstLineBreakOutsideComment(code, start = 0) { - let lineBreakPos, charCodeAfterSlash; +// This assumes "code" only contains white-space and comments +function findFirstLineBreakOutsideComment(code) { + let lineBreakPos, charCodeAfterSlash, start = 0; lineBreakPos = code.indexOf('\n', start); while (true) { start = code.indexOf('/', start); if (start === -1 || start > lineBreakPos) return lineBreakPos; + // With our assumption, '/' always starts a comment. Determine comment type: charCodeAfterSlash = code.charCodeAt(++start); if (charCodeAfterSlash === 47 /*"/"*/) return lineBreakPos; - ++start; - if (charCodeAfterSlash === 42 /*"*"*/) { - start = code.indexOf('*/', start) + 2; - if (start > lineBreakPos) { - lineBreakPos = code.indexOf('\n', start); - } + start = code.indexOf('*/', start + 2) + 2; + if (start > lineBreakPos) { + lineBreakPos = code.indexOf('\n', start); } } } function renderStatementList(statements, code, start, end, options) { - if (statements.length === 0) - return; let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart; let nextNode = statements[0]; let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries; if (nextNodeNeedsBoundaries) { nextNodeStart = @@ -2006,10 +2031,21 @@ separator: null, start }); return splitUpNodes; } +// This assumes there are only white-space and comments between start and end +function removeLineBreaks(code, start, end) { + while (true) { + const lineBreakPos = findFirstLineBreakOutsideComment(code.original.slice(start, end)); + if (lineBreakPos === -1) { + break; + } + start = start + lineBreakPos + 1; + code.remove(start - 1, start); + } +} const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'; const base = 64; function toBase64(num) { let outStr = ''; @@ -2606,11 +2642,11 @@ } function makeLegal(str) { str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_'); if (startsWithDigit(str) || blacklisted[str]) str = `_${str}`; - return str; + return str || '_'; } const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/; const relativePath = /^\.?\.\//; function isAbsolute(path) { @@ -8663,10 +8699,19 @@ } } getAssignedVariableName() { return (this.originalId && this.originalId.name) || null; } + getBaseVariableName() { + const original = this.getOriginalVariable(); + if (original === this) { + return super.getBaseVariableName(); + } + else { + return original.getBaseVariableName(); + } + } getName() { const original = this.getOriginalVariable(); if (original === this) { return super.getName(); } @@ -8706,11 +8751,10 @@ else { original.setSafeName(name); } } } -ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName; const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim'; const INTEROP_DEFAULT_VARIABLE = '_interopDefault'; const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace'; @@ -8868,15 +8912,10 @@ this.containsExternalNamespace = false; this.referencedEarly = false; this.references = []; this.context = context; this.module = context.module; - for (const name of this.context.getExports().concat(this.context.getReexports())) { - if (name[0] === '*' && name.length > 1) - this.containsExternalNamespace = true; - this.memberVariables[name] = this.context.traceExport(name); - } } addReference(identifier) { this.references.push(identifier); this.name = identifier.name; } @@ -8913,10 +8952,17 @@ for (const memberName of Object.keys(this.memberVariables)) this.context.includeVariable(this.memberVariables[memberName]); } } } + initialise() { + for (const name of this.context.getExports().concat(this.context.getReexports())) { + if (name[0] === '*' && name.length > 1) + this.containsExternalNamespace = true; + this.memberVariables[name] = this.context.traceExport(name); + } + } renderBlock(options) { const _ = options.compact ? '' : ' '; const n = options.compact ? '' : '\n'; const t = options.indent; const members = Object.keys(this.memberVariables).map(name => { @@ -8970,11 +9016,11 @@ dependencies.some(dep => { if (!dep.reexports) return false; return dep.reexports.some(expt => { if (expt.reexported === 'default') { - local = dep.namedExportsMode ? `${dep.name}.${expt.imported}` : dep.name; + local = dep.namedExportsMode && expt.imported !== '*' ? `${dep.name}.${expt.imported}` : dep.name; return true; } return false; }); }); @@ -8987,17 +9033,24 @@ if (reexports && namedExportsMode) { reexports.forEach(specifier => { if (specifier.reexported === '*') { if (!compact && exportBlock) exportBlock += '\n'; - exportBlock += - `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` + - `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` + - `${t}${t}enumerable:${_}true,${n}` + - `${t}${t}get:${_}function${_}()${_}{${n}` + - `${t}${t}${t}return ${name}[k];${n}` + - `${t}${t}}${n}${t}});${n}});`; + if (specifier.needsLiveBinding) { + exportBlock += + `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` + + `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` + + `${t}${t}enumerable:${_}true,${n}` + + `${t}${t}get:${_}function${_}()${_}{${n}` + + `${t}${t}${t}return ${name}[k];${n}` + + `${t}${t}}${n}${t}});${n}});`; + } + else { + exportBlock += + `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` + + `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`; + } } }); } }); dependencies.forEach(({ name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode }) => { @@ -9068,29 +9121,35 @@ }) .filter(Boolean) .join(options.compact ? '' : '\n'); } -function getInteropNamespace(_, n, t) { - return `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` + +function copyPropertyLiveBinding(_, n, t, i) { + return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` + + `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` + + `${i}${t}enumerable:${_}true,${n}` + + `${i}${t}get:${_}function${_}()${_}{${n}` + + `${i}${t}${t}return e[k];${n}` + + `${i}${t}}${n}` + + `${i}});${n}`); +} +function copyPropertyStatic(_, n, _t, i) { + return `${i}n[k]${_}=e${_}[k];${n}`; +} +function getInteropNamespace(_, n, t, liveBindings) { + return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` + `${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` + `${t}${t}var n${_}=${_}{};${n}` + `${t}${t}if${_}(e)${_}{${n}` + `${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` + - `${t}${t}${t}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` + - `${t}${t}${t}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` + - `${t}${t}${t}${t}${t}enumerable:${_}true,${n}` + - `${t}${t}${t}${t}${t}get:${_}function${_}()${_}{${n}` + - `${t}${t}${t}${t}${t}${t}return e[k];${n}` + - `${t}${t}${t}${t}${t}}${n}` + - `${t}${t}${t}${t}});${n}` + + (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) + `${t}${t}${t}});${n}` + `${t}${t}}${n}` + `${t}${t}n['default']${_}=${_}e;${n}` + `${t}${t}return n;${n}` + `${t}}${n}` + - `}${n}${n}`; + `}${n}${n}`); } const builtins$1 = { assert: true, buffer: true, @@ -9169,11 +9228,11 @@ const interopBlock = getInteropBlock(dependencies, options, varOrConst); if (interopBlock) { magicString.prepend(interopBlock + n + n); } if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) { - magicString.prepend(getInteropNamespace(_, n, t)); + magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false)); } if (intro) magicString.prepend(intro); const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t); if (exportBlock) @@ -9233,11 +9292,11 @@ `function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` + `(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` + `?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`; } if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) { - intro += getInteropNamespace(_, n, t); + intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false); } if (importBlock) intro += importBlock + n + n; const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`); magicString.prepend(intro); @@ -9379,27 +9438,32 @@ return `${lineNum}: ${tabsToSpaces(str)}`; }) .join('\n'); } +function sanitizeFileName(name) { + return name.replace(/[\0?*]/g, '_'); +} + function getAliasName(id) { const base = basename(id); return base.substr(0, base.length - extname(id).length); } function relativeId(id) { if (typeof process === 'undefined' || !isAbsolute(id)) return id; return relative$1(process.cwd(), id); } -function isPlainName(name) { - // not starting with "./", "/". "../" - return !(name[0] === '/' || - (name[1] === '.' && (name[2] === '/' || (name[2] === '.' && name[3] === '/')))); +function isPlainPathFragment(name) { + // not starting with "/", "./", "../" + return (name[0] !== '/' && + !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) && + sanitizeFileName(name) === name); } function error(base, props) { - if (base instanceof Error === false) + if (!(base instanceof Error)) base = Object.assign(new Error(base.message), base); if (props) Object.assign(base, props); throw base; } @@ -9423,86 +9487,83 @@ Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED"; Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND"; Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET"; Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING"; Errors["BAD_LOADER"] = "BAD_LOADER"; - Errors["CHUNK_NOT_FOUND"] = "CHUNK_NOT_FOUND"; + Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK"; Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED"; Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE"; - Errors["INVALID_ASSET_NAME"] = "INVALID_ASSET_NAME"; + Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND"; + Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT"; Errors["INVALID_CHUNK"] = "INVALID_CHUNK"; Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID"; Errors["INVALID_OPTION"] = "INVALID_OPTION"; Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK"; Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE"; Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT"; + Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR"; Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY"; Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT"; + Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR"; })(Errors || (Errors = {})); -function errAssetNotFinalisedForFileName(asset) { +function errAssetNotFinalisedForFileName(name) { return { code: Errors.ASSET_NOT_FINALISED, - message: `Plugin error - Unable to get file name for asset "${asset.name}". Ensure that the source is set and that generate is called first.` + message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.` }; } -function errChunkNotGeneratedForFileName(entry) { +function errCannotEmitFromOptionsHook() { return { - code: Errors.CHUNK_NOT_GENERATED, - message: `Plugin error - Unable to get file name for chunk "${entry.name}". Ensure that generate is called first.` + code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK, + message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.` }; } -function errAssetReferenceIdNotFoundForFilename(assetReferenceId) { +function errChunkNotGeneratedForFileName(name) { return { - code: Errors.ASSET_NOT_FOUND, - message: `Plugin error - Unable to get file name for unknown asset "${assetReferenceId}".` + code: Errors.CHUNK_NOT_GENERATED, + message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.` }; } function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) { return { code: Errors.ASSET_NOT_FOUND, message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".` }; } -function errAssetSourceAlreadySet(asset) { +function errAssetSourceAlreadySet(name) { return { code: Errors.ASSET_SOURCE_ALREADY_SET, - message: `Plugin error - Unable to set the source for asset "${asset.name}", source already set.` + message: `Unable to set the source for asset "${name}", source already set.` }; } -function errAssetSourceMissingForSetSource(asset) { +function errNoAssetSourceSet(assetName) { return { code: Errors.ASSET_SOURCE_MISSING, - message: `Plugin error creating asset "${asset.name}", setAssetSource call without a source.` + message: `Plugin error creating asset "${assetName}" - no asset source set.` }; } -function errNoAssetSourceSet(asset) { - return { - code: Errors.ASSET_SOURCE_MISSING, - message: `Plugin error creating asset "${asset.name}" - no asset source set.` - }; -} function errBadLoader(id) { return { code: Errors.BAD_LOADER, message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null` }; } -function errChunkReferenceIdNotFoundForFilename(chunkReferenceId) { - return { - code: Errors.CHUNK_NOT_FOUND, - message: `Plugin error - Unable to get file name for unknown chunk "${chunkReferenceId}".` - }; -} function errDeprecation(deprecation) { return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation)); } -function errInvalidAssetName(name) { +function errFileReferenceIdNotFoundForFilename(assetReferenceId) { return { - code: Errors.INVALID_ASSET_NAME, - message: `Plugin error creating asset, name "${name}" is not a plain (non relative or absolute URL) string name.` + code: Errors.FILE_NOT_FOUND, + message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".` }; } +function errFileNameConflict(fileName) { + return { + code: Errors.FILE_NAME_CONFLICT, + message: `Could not emit file "${fileName}" as it conflicts with an already emitted file.` + }; +} function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) { return { code: Errors.INVALID_CHUNK, message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.` }; @@ -9523,14 +9584,14 @@ return { code: Errors.INVALID_ROLLUP_PHASE, message: `Cannot call addWatchFile after the build has finished.` }; } -function errInvalidRollupPhaseForEmitChunk() { +function errInvalidRollupPhaseForChunkEmission() { return { code: Errors.INVALID_ROLLUP_PHASE, - message: `Cannot call emitChunk after module loading has finished.` + message: `Cannot emit chunks after module loading has finished.` }; } function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) { return { code: Errors.NAMESPACE_CONFLICT, @@ -9565,10 +9626,16 @@ message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`, source, url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency' }; } +function errFailedValidation(message) { + return { + code: Errors.VALIDATION_ERROR, + message + }; +} // Generate strings which dereference dotted properties, but use array notation `['prop-deref']` // if the property name isn't trivial const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/; function property(prop) { @@ -10675,21 +10742,23 @@ } else { this.usedBranch.include(includeChildrenRecursively); } } - render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) { + render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { if (!this.test.included) { const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end); + const inclusionStart = (this.consequent.included + ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end) + : colonPos) + 1; + if (preventASI) { + removeLineBreaks(code, inclusionStart, this.usedBranch.start); + } + code.remove(this.start, inclusionStart); if (this.consequent.included) { - const questionmarkPos = findFirstOccurrenceOutsideComment(code.original, '?', this.test.end); - code.remove(this.start, questionmarkPos + 1); code.remove(colonPos, this.end); } - else { - code.remove(this.start, colonPos + 1); - } removeAnnotations(this, code); this.usedBranch.render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent : this.parent.callee === this, @@ -10937,43 +11006,62 @@ } } } } +class ImportDeclaration extends NodeBase { + bind() { } + hasEffects() { + return false; + } + initialise() { + this.context.addImport(this); + } + render(code, _options, { start, end } = BLANK) { + code.remove(start, end); + } +} +ImportDeclaration.prototype.needsBoundaries = true; + class Import extends NodeBase { constructor() { super(...arguments); this.exportMode = 'auto'; } - include() { + hasEffects() { + return true; + } + include(includeChildrenRecursively) { if (!this.included) { this.included = true; this.context.includeDynamicImport(this); } + this.source.include(includeChildrenRecursively); } initialise() { this.context.addDynamicImport(this); } render(code, options) { if (this.inlineNamespace) { const _ = options.compact ? '' : ' '; const s = options.compact ? '' : ';'; - code.overwrite(this.parent.start, this.parent.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`); + code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`); return; } const importMechanism = this.getDynamicImportMechanism(options); if (importMechanism) { - code.overwrite(this.parent.start, findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1, importMechanism.left); - code.overwrite(this.parent.end - 1, this.parent.end, importMechanism.right); + code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, importMechanism.left); + code.overwrite(this.end - 1, this.end, importMechanism.right); } + this.source.render(code, options); } renderFinalResolution(code, resolution, format) { if (this.included) { if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) { resolution = resolution.slice(0, -4) + "'"; } - code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution); + code.overwrite(this.source.start, this.source.end, resolution); } } setResolution(exportMode, inlineNamespace) { this.exportMode = exportMode; if (inlineNamespace) { @@ -11045,24 +11133,10 @@ } return null; } } -class ImportDeclaration extends NodeBase { - bind() { } - hasEffects() { - return false; - } - initialise() { - this.context.addImport(this); - } - render(code, _options, { start, end } = BLANK) { - code.remove(start, end); - } -} -ImportDeclaration.prototype.needsBoundaries = true; - class LabeledStatement extends NodeBase { hasEffects(options) { return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements()); } } @@ -11207,15 +11281,18 @@ } else { this.usedBranch.include(includeChildrenRecursively); } } - render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) { + render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { if (!this.left.included || !this.right.included) { const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end); if (this.right.included) { code.remove(this.start, operatorPos + 2); + if (preventASI) { + removeLineBreaks(code, operatorPos + 2, this.right.start); + } } else { code.remove(operatorPos, this.end); } removeAnnotations(this, code); @@ -11456,11 +11533,11 @@ code: 'MISSING_EXPORT', exporter: relativeId(fileName), importer: relativeId(this.context.fileName), message: `'${exportName}' is not exported by '${relativeId(fileName)}'`, missing: exportName, - url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-` + url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` }, path[0].pos); return 'undefined'; } return this.resolveNamespaceVariables(variable, path.slice(1)); } @@ -11576,11 +11653,15 @@ system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`), umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`) }; const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`); const relativeUrlMechanisms = { - amd: relativePath => getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`), + amd: relativePath => { + if (relativePath[0] !== '.') + relativePath = './' + relativePath; + return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`); + }, cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`, es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`), iife: relativePath => getRelativeUrlFromDocument(relativePath), system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`), umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})` @@ -11600,11 +11681,15 @@ umd: ['document', 'require', 'URL'] }; const ASSET_PREFIX = 'ROLLUP_ASSET_URL_'; const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_'; +const FILE_PREFIX = 'ROLLUP_FILE_URL_'; class MetaProperty extends NodeBase { + hasEffects() { + return false; + } hasEffectsWhenAccessedAtPath(path) { return path.length > 1; } include() { if (!this.included) { @@ -11616,11 +11701,13 @@ : null); if (metaProperty) { if (metaProperty === 'url') { this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals); } - else if (metaProperty.startsWith(ASSET_PREFIX) || metaProperty.startsWith(CHUNK_PREFIX)) { + else if (metaProperty.startsWith(FILE_PREFIX) || + metaProperty.startsWith(ASSET_PREFIX) || + metaProperty.startsWith(CHUNK_PREFIX)) { this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals); } } } } @@ -11631,23 +11718,32 @@ } renderFinalMechanism(code, chunkId, format, pluginDriver) { if (!this.included) return; const parent = this.parent; - const importMetaProperty = this.metaProperty; - if (importMetaProperty && - (importMetaProperty.startsWith(ASSET_PREFIX) || importMetaProperty.startsWith(CHUNK_PREFIX))) { + const metaProperty = this.metaProperty; + if (metaProperty && + (metaProperty.startsWith(FILE_PREFIX) || + metaProperty.startsWith(ASSET_PREFIX) || + metaProperty.startsWith(CHUNK_PREFIX))) { + let referenceId = null; let assetReferenceId = null; let chunkReferenceId = null; let fileName; - if (importMetaProperty.startsWith(ASSET_PREFIX)) { - assetReferenceId = importMetaProperty.substr(ASSET_PREFIX.length); - fileName = this.context.getAssetFileName(assetReferenceId); + if (metaProperty.startsWith(FILE_PREFIX)) { + referenceId = metaProperty.substr(FILE_PREFIX.length); + fileName = this.context.getFileName(referenceId); } + else if (metaProperty.startsWith(ASSET_PREFIX)) { + this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false); + assetReferenceId = metaProperty.substr(ASSET_PREFIX.length); + fileName = this.context.getFileName(assetReferenceId); + } else { - chunkReferenceId = importMetaProperty.substr(CHUNK_PREFIX.length); - fileName = this.context.getChunkFileName(chunkReferenceId); + this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false); + chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length); + fileName = this.context.getFileName(chunkReferenceId); } const relativePath = normalize(relative$1(dirname(chunkId), fileName)); let replacement; if (assetReferenceId !== null) { replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [ @@ -11667,19 +11763,20 @@ chunkId, chunkReferenceId, fileName, format, moduleId: this.context.module.id, + referenceId: referenceId || assetReferenceId || chunkReferenceId, relativePath } ]); } code.overwrite(parent.start, parent.end, replacement, { contentOnly: true }); return; } const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [ - importMetaProperty, + metaProperty, { chunkId, format, moduleId: this.context.module.id } @@ -12175,11 +12272,11 @@ initialise() { this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION); } render(code, options) { if (this.argument) { - this.argument.render(code, options); + this.argument.render(code, options, { preventASI: true }); if (this.argument.start === this.start + 6 /* 'return'.length */) { code.prependLeft(this.start + 6, ' '); } } } @@ -12218,18 +12315,21 @@ if (includeChildrenRecursively || node.shouldBeIncluded()) node.include(includeChildrenRecursively); } this.expressions[this.expressions.length - 1].include(includeChildrenRecursively); } - render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) { + render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) { let includedNodes = 0; for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) { if (!node.included) { treeshakeNode(node, code, start, end); continue; } includedNodes++; + if (includedNodes === 1 && preventASI) { + removeLineBreaks(code, start, node.start); + } if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) { node.render(code, options, { isCalleeOfRenderedParent: renderedParentType ? isCalleeOfRenderedParent : this.parent.callee === this, @@ -12399,10 +12499,13 @@ class ThrowStatement extends NodeBase { hasEffects(_options) { return true; } + render(code, options) { + this.argument.render(code, options, { preventASI: true }); + } } class TryStatement extends NodeBase { constructor() { super(...arguments); @@ -12757,12 +12860,12 @@ ForStatement, FunctionDeclaration, FunctionExpression: FunctionExpression$1, Identifier: Identifier$1, IfStatement, - Import, ImportDeclaration, + ImportExpression: Import, LabeledStatement, Literal, LogicalExpression, MemberExpression, MetaProperty, @@ -13056,11 +13159,14 @@ c(spec, st); } c(node.source, st, "Expression"); }; -base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = base$1.Import = ignore; +base$1.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); +}; +base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore; base$1.TaggedTemplateExpression = function (node, st, c) { c(node.tag, st, "Expression"); c(node.quasi, st, "Expression"); }; @@ -13234,11 +13340,11 @@ timeEnd = NOOP; } } const defaultAcornOptions = { - ecmaVersion: 2019, + ecmaVersion: 2020, preserveParens: false, sourceType: 'module' }; function tryParse(module, Parser, acornOptions) { try { @@ -13260,20 +13366,21 @@ } function handleMissingExport(exportName, importingModule, importedModule, importerStart) { importingModule.error({ code: 'MISSING_EXPORT', message: `'${exportName}' is not exported by ${relativeId(importedModule)}`, - url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-` + url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` }, importerStart); } const MISSING_EXPORT_SHIM_DESCRIPTION = { identifier: null, localName: MISSING_EXPORT_SHIM_VARIABLE }; class Module { constructor(graph, id, moduleSideEffects, isEntry) { - this.chunkAlias = null; + this.chunkFileNames = new Set(); + this.chunkName = null; this.comments = []; this.dependencies = []; this.dynamicallyImportedBy = []; this.dynamicDependencies = []; this.dynamicImports = []; @@ -13291,10 +13398,11 @@ this.isExecuted = false; this.isUserDefinedEntryPoint = false; this.manualChunkAlias = null; this.reexports = Object.create(null); this.sources = []; + this.userChunkNames = new Set(); this.usesTopLevelAwait = false; this.namespaceVariable = undefined; this.transformDependencies = null; this.id = id; this.graph = graph; @@ -13362,11 +13470,11 @@ } return allExportNames; } getDynamicImportExpressions() { return this.dynamicImports.map(({ node }) => { - const importArgument = node.parent.arguments[0]; + const importArgument = node.source; if (importArgument instanceof TemplateLiteral && importArgument.quasis.length === 1 && importArgument.quasis[0].value.cooked) { return importArgument.quasis[0].value.cooked; } @@ -13396,11 +13504,15 @@ } getExports() { return Object.keys(this.exports); } getOrCreateNamespace() { - return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext))); + if (!this.namespaceVariable) { + this.namespaceVariable = new NamespaceVariable(this.astContext); + this.namespaceVariable.initialise(); + } + return this.namespaceVariable; } getReexports() { if (this.transitiveReexports) { return this.transitiveReexports; } @@ -13544,21 +13656,18 @@ const magicString = this.magicString.clone(); this.ast.render(magicString, options); this.usesTopLevelAwait = this.astContext.usesTopLevelAwait; return magicString; } - setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformAssets, transformChunks, transformDependencies }) { + setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) { this.code = code; this.originalCode = originalCode; this.originalSourcemap = originalSourcemap; this.sourcemapChain = sourcemapChain; - if (transformAssets) { - this.transformAssets = transformAssets; + if (transformFiles) { + this.transformFiles = transformFiles; } - if (transformChunks) { - this.transformChunks = transformChunks; - } this.transformDependencies = transformDependencies; this.customTransformCache = customTransformCache; if (typeof moduleSideEffects === 'boolean') { this.moduleSideEffects = moduleSideEffects; } @@ -13585,13 +13694,12 @@ this.graph.treeshakingOptions.annotations), code, deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), fileName, - getAssetFileName: this.graph.pluginDriver.getAssetFileName, - getChunkFileName: this.graph.moduleLoader.getChunkFileName.bind(this.graph.moduleLoader), getExports: this.getExports.bind(this), + getFileName: this.graph.pluginDriver.getFileName, getModuleExecIndex: () => this.execIndex, getModuleName: this.basename.bind(this), getReexports: this.getReexports.bind(this), importDescriptions: this.importDescriptions, includeDynamicImport: this.includeDynamicImport.bind(this), @@ -13608,11 +13716,12 @@ traceVariable: this.traceVariable.bind(this), treeshake: !!this.graph.treeshakingOptions, tryCatchDeoptimization: (!this.graph.treeshakingOptions || this.graph.treeshakingOptions.tryCatchDeoptimization), usesTopLevelAwait: false, - warn: this.warn.bind(this) + warn: this.warn.bind(this), + warnDeprecation: this.graph.warnDeprecation.bind(this.graph) }; this.scope = new ModuleScope(this.graph.scope, this.astContext); this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope); timeEnd('analyse ast', 3); } @@ -13626,13 +13735,12 @@ moduleSideEffects: this.moduleSideEffects, originalCode: this.originalCode, originalSourcemap: this.originalSourcemap, resolvedIds: this.resolvedIds, sourcemapChain: this.sourcemapChain, - transformAssets: this.transformAssets, - transformChunks: this.transformChunks, - transformDependencies: this.transformDependencies + transformDependencies: this.transformDependencies, + transformFiles: this.transformFiles }; } traceVariable(name) { const localVariable = this.scope.variables.get(name); if (localVariable) { @@ -14225,28 +14333,20 @@ plugin: err.plugin }); }); } -function renderNamePattern(pattern, patternName, getReplacement) { - if (!isPlainName(pattern)) - error({ - code: 'INVALID_PATTERN', - message: `Invalid output pattern "${pattern}" for ${patternName}, cannot be an absolute or relative URL or path.` - }); +function renderNamePattern(pattern, patternName, replacements) { + if (!isPlainPathFragment(pattern)) + return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`)); return pattern.replace(/\[(\w+)\]/g, (_match, type) => { - const replacement = getReplacement(type); - if (replacement === undefined) - error({ - code: 'INVALID_PATTERN_REPLACEMENT', - message: `"${type}" is not a valid substitution name in output option ${patternName} pattern.` - }); - if (!isPlainName(replacement)) - error({ - code: 'INVALID_PATTERN_REPLACEMENT', - message: `Invalid replacement "${replacement}" for "${type}" in ${patternName} pattern, must be a plain path name.` - }); + if (!replacements.hasOwnProperty(type)) { + return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`)); + } + const replacement = replacements[type](); + if (!isPlainPathFragment(replacement)) + return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`)); return replacement; }); } function makeUnique(name, existingNames) { if (name in existingNames === false) @@ -14257,14 +14357,10 @@ while (existingNames[(uniqueName = name + ++uniqueIndex + ext)]) ; return uniqueName; } -function sanitizeFileName(name) { - return name.replace(/[\0?*]/g, '_'); -} - function getGlobalName(module, globals, graph, hasExports) { let globalName; if (typeof globals === 'function') { globalName = globals(module.id); } @@ -14290,19 +14386,22 @@ class Chunk$1 { constructor(graph, orderedModules) { this.entryModules = []; this.exportMode = 'named'; this.facadeModule = null; - this.id = undefined; + this.id = null; this.indentString = undefined; this.manualChunkAlias = null; this.usedModules = undefined; + this.variableName = 'chunk'; this.dependencies = undefined; this.dynamicDependencies = undefined; this.exportNames = Object.create(null); this.exports = new Set(); + this.fileName = null; this.imports = new Set(); + this.name = null; this.needsExportsShim = false; this.renderedDeclarations = undefined; this.renderedHash = undefined; this.renderedModuleSources = new Map(); this.renderedSource = null; @@ -14323,78 +14422,86 @@ if (module.isEntryPoint || module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) { this.entryModules.push(module); } } - const entryModule = this.entryModules[0]; - if (entryModule) { - this.variableName = makeLegal(basename(entryModule.chunkAlias || entryModule.manualChunkAlias || getAliasName(entryModule.id))); + const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1]; + if (moduleForNaming) { + this.variableName = makeLegal(basename(moduleForNaming.chunkName || + moduleForNaming.manualChunkAlias || + getAliasName(moduleForNaming.id))); } - else { - this.variableName = '__chunk_' + ++graph.curChunkIndex; - } } - static generateFacade(graph, facadedModule) { + static generateFacade(graph, facadedModule, facadeName) { const chunk = new Chunk$1(graph, []); + chunk.assignFacadeName(facadeName, facadedModule); + if (!facadedModule.facadeChunk) { + facadedModule.facadeChunk = chunk; + } chunk.dependencies = [facadedModule.chunk]; chunk.dynamicDependencies = []; chunk.facadeModule = facadedModule; - facadedModule.facadeChunk = chunk; for (const exportName of facadedModule.getAllExportNames()) { const tracedVariable = facadedModule.getVariableForExportName(exportName); chunk.exports.add(tracedVariable); chunk.exportNames[exportName] = tracedVariable; } return chunk; } - canModuleBeFacade(moduleExportNamesByVariable, moduleChunkAlias) { - if (this.manualChunkAlias && moduleChunkAlias && this.manualChunkAlias !== moduleChunkAlias) { - return false; - } + canModuleBeFacade(moduleExportNamesByVariable) { for (const exposedVariable of this.exports) { if (!moduleExportNamesByVariable.has(exposedVariable)) { return false; } } return true; } generateFacades() { const facades = []; for (const module of this.entryModules) { + const requiredFacades = Array.from(module.userChunkNames).map(name => ({ + name + })); + if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) { + requiredFacades.push({}); + } + requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName }))); + if (requiredFacades.length === 0) { + requiredFacades.push({}); + } if (!this.facadeModule) { const exportNamesByVariable = module.getExportNamesByVariable(); - if (this.graph.preserveModules || - this.canModuleBeFacade(exportNamesByVariable, module.chunkAlias)) { + if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) { this.facadeModule = module; + module.facadeChunk = this; for (const [variable, exportNames] of exportNamesByVariable) { for (const exportName of exportNames) { this.exportNames[exportName] = variable; } } - continue; + this.assignFacadeName(requiredFacades.shift(), module); } } - facades.push(Chunk$1.generateFacade(this.graph, module)); + for (const facadeName of requiredFacades) { + facades.push(Chunk$1.generateFacade(this.graph, module, facadeName)); + } } return facades; } generateId(pattern, patternName, addons, options, existingNames) { - this.id = makeUnique(renderNamePattern(pattern, patternName, type => { - switch (type) { - case 'format': - return options.format === 'es' ? 'esm' : options.format; - case 'hash': - return this.computeContentHashWithDependencies(addons, options); - case 'name': - return this.getChunkName(); - } - return undefined; + if (this.fileName !== null) { + return this.fileName; + } + return makeUnique(renderNamePattern(pattern, patternName, { + format: () => (options.format === 'es' ? 'esm' : options.format), + hash: () => this.computeContentHashWithDependencies(addons, options), + name: () => this.getChunkName() }), existingNames); } generateIdPreserveModules(preserveModulesRelativeDir, existingNames) { const sanitizedId = sanitizeFileName(this.orderedModules[0].id); - this.id = makeUnique(normalize(isAbsolute(this.orderedModules[0].id) + return makeUnique(normalize(isAbsolute(this.orderedModules[0].id) ? relative(preserveModulesRelativeDir, sanitizedId) : '_virtual/' + basename(sanitizedId)), existingNames); } generateInternalExports(options) { if (this.facadeModule !== null) @@ -14432,27 +14539,29 @@ this.exportNames[safeExportName] = variable; } } } getChunkName() { - return this.chunkName || (this.chunkName = this.computeChunkName()); + return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName())); } getDynamicImportIds() { return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean); } getExportNames() { return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort())); } getImportIds() { - return this.dependencies.map(chunk => chunk.id); + return this.dependencies.map(chunk => chunk.id).filter(Boolean); } getRenderedHash() { if (this.renderedHash) return this.renderedHash; if (!this.renderedSource) return ''; const hash = _256(); + const hashAugmentation = this.calculateHashAugmentation(); + hash.update(hashAugmentation); hash.update(this.renderedSource.toString()); hash.update(this.getExportNames() .map(exportName => { const variable = this.exportNames[exportName]; return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`; @@ -14700,16 +14809,13 @@ const dep = this.dependencies[i]; if (dep instanceof ExternalModule && !dep.renormalizeRenderPath) continue; const renderedDependency = this.renderedDeclarations.dependencies[i]; const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id; - let relPath = this.id ? normalize(relative(dirname(this.id), depId)) : depId; - if (!relPath.startsWith('../')) - relPath = './' + relPath; if (dep instanceof Chunk$1) renderedDependency.namedExportsMode = dep.exportMode !== 'default'; - renderedDependency.id = relPath; + renderedDependency.id = this.getRelativePath(depId); } this.finaliseDynamicImports(format); this.finaliseImportMetas(format); const hasExports = this.renderedDeclarations.exports.length !== 0 || this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0)); @@ -14770,17 +14876,12 @@ file = resolve(options.sourcemapFile || options.file); else if (options.dir) file = resolve(options.dir, this.id); else file = resolve(this.id); - if (this.graph.pluginDriver.hasLoadersOrTransforms) { - const decodedMap = magicString.generateDecodedMap({}); - map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources); - } - else { - map = magicString.generateMap({ file, includeContent: !options.sourcemapExcludeSources }); - } + const decodedMap = magicString.generateDecodedMap({}); + map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources); map.sources = map.sources.map(sourcePath => normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath)); timeEnd('sourcemap', 3); } if (options.compact !== true && code[code.length - 1] !== '\n') code += '\n'; @@ -14834,23 +14935,41 @@ dependency = depModule; } chunkDependencies.add(dependency); } } - computeChunkName() { - if (this.manualChunkAlias) { - return sanitizeFileName(this.manualChunkAlias); + assignFacadeName({ fileName, name }, facadedModule) { + if (fileName) { + this.fileName = fileName; } - if (this.facadeModule !== null) { - return sanitizeFileName(this.facadeModule.chunkAlias || getAliasName(this.facadeModule.id)); + else { + this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id)); } - for (const module of this.orderedModules) { - if (module.chunkAlias) - return sanitizeFileName(module.chunkAlias); - } - return 'chunk'; } + calculateHashAugmentation() { + const facadeModule = this.facadeModule; + const getChunkName = this.getChunkName.bind(this); + const preRenderedChunk = { + dynamicImports: this.getDynamicImportIds(), + exports: this.getExportNames(), + facadeModuleId: facadeModule && facadeModule.id, + imports: this.getImportIds(), + isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0, + isEntry: facadeModule !== null && facadeModule.isEntryPoint, + modules: this.renderedModules, + get name() { + return getChunkName(); + } + }; + const hashAugmentation = this.graph.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => { + if (pluginHash) { + hashAugmentation += pluginHash; + } + return hashAugmentation; + }); + return hashAugmentation; + } computeContentHashWithDependencies(addons, options) { const hash = _256(); hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':')); hash.update(options.format); this.visitDependencies(dep => { @@ -14867,27 +14986,19 @@ if (!resolution) continue; if (resolution instanceof Module) { if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) { const resolutionChunk = resolution.facadeChunk || resolution.chunk; - let relPath = normalize(relative(dirname(this.id), resolutionChunk.id)); - if (!relPath.startsWith('../')) - relPath = './' + relPath; - node.renderFinalResolution(code, `'${relPath}'`, format); + node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format); } } - else if (resolution instanceof ExternalModule) { - let resolutionId = resolution.id; - if (resolution.renormalizeRenderPath) { - resolutionId = normalize(relative(dirname(this.id), resolution.renderPath)); - if (!resolutionId.startsWith('../')) - resolutionId = './' + resolutionId; - } - node.renderFinalResolution(code, `'${resolutionId}'`, format); - } else { - node.renderFinalResolution(code, resolution, format); + node.renderFinalResolution(code, resolution instanceof ExternalModule + ? `'${resolution.renormalizeRenderPath + ? this.getRelativePath(resolution.renderPath) + : resolution.id}'` + : resolution, format); } } } } finaliseImportMetas(format) { @@ -14902,10 +15013,11 @@ for (let exportName of this.getExportNames()) { let exportChunk; let importName; let needsLiveBinding = false; if (exportName[0] === '*') { + needsLiveBinding = options.externalLiveBindings !== false; exportChunk = this.graph.moduleById.get(exportName.substr(1)); importName = exportName = '*'; } else { const variable = this.exportNames[exportName]; @@ -14919,11 +15031,11 @@ needsLiveBinding = variable.isReassigned; } else { exportChunk = module; importName = variable.name; - needsLiveBinding = true; + needsLiveBinding = options.externalLiveBindings !== false; } } let reexportDeclaration = reexportDeclarations.get(exportChunk); if (!reexportDeclaration) reexportDeclarations.set(exportChunk, (reexportDeclaration = [])); @@ -15018,10 +15130,23 @@ uninitialized }); } return exports; } + getFallbackChunkName() { + if (this.manualChunkAlias) { + return this.manualChunkAlias; + } + if (this.fileName) { + return getAliasName(this.fileName); + } + return getAliasName(this.orderedModules[this.orderedModules.length - 1].id); + } + getRelativePath(targetPath) { + const relativePath = normalize(relative(dirname(this.id), targetPath)); + return relativePath.startsWith('../') ? relativePath : './' + relativePath; + } inlineChunkDependencies(chunk, deep) { for (const dep of chunk.dependencies) { if (dep instanceof ExternalModule) { if (this.dependencies.indexOf(dep) === -1) this.dependencies.push(dep); @@ -15247,126 +15372,39 @@ } return chunks; } const tt = acorn__default.tokTypes; -const isIdentifierStart = acorn__default.isIdentifierStart; -var acornBigint = function (Parser) { - return class extends Parser { - parseLiteral(value) { - const node = super.parseLiteral(value); - if (node.raw.charCodeAt(node.raw.length - 1) == 110) - node.bigint = this.getNumberInput(node.start, node.end); - return node; - } - readRadixNumber(radix) { - let start = this.pos; - this.pos += 2; // 0x - let val = this.readInt(radix); - if (val === null) - this.raise(this.start + 2, `Expected number in radix ${radix}`); - if (this.input.charCodeAt(this.pos) == 110) { - let str = this.getNumberInput(start, this.pos); - val = typeof BigInt !== "undefined" ? BigInt(str) : null; - ++this.pos; - } - else if (isIdentifierStart(this.fullCharCodeAtPos())) - this.raise(this.pos, "Identifier directly after number"); - return this.finishToken(tt.num, val); - } - readNumber(startsWithDot) { - let start = this.pos; - // Not an int - if (startsWithDot) - return super.readNumber(startsWithDot); - // Legacy octal - if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) { - return super.readNumber(startsWithDot); - } - if (this.readInt(10) === null) - this.raise(start, "Invalid number"); - // Not a BigInt, reset and parse again - if (this.input.charCodeAt(this.pos) != 110) { - this.pos = start; - return super.readNumber(startsWithDot); - } - let str = this.getNumberInput(start, this.pos); - let val = typeof BigInt !== "undefined" ? BigInt(str) : null; - ++this.pos; - return this.finishToken(tt.num, val); - } - // This is basically a hook for acorn-numeric-separator - getNumberInput(start, end) { - if (super.getNumberInput) - return super.getNumberInput(start, end); - return this.input.slice(start, end); - } - }; -}; - -/* eslint-disable no-underscore-dangle */ -const DynamicImportKey = 'Import'; -// NOTE: This allows `yield import()` to parse correctly. -tokTypes._import.startsExpr = true; -function parseDynamicImport() { - const node = this.startNode(); - this.next(); - if (this.type !== tokTypes.parenL) { - this.unexpected(); - } - return this.finishNode(node, DynamicImportKey); -} -function parenAfter() { - return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos)); -} -function dynamicImport(Parser) { - return class extends Parser { - parseStatement(context, topLevel, exports) { - if (this.type === tokTypes._import && parenAfter.call(this)) { - return this.parseExpressionStatement(this.startNode(), this.parseExpression()); - } - return super.parseStatement(context, topLevel, exports); - } - parseExprAtom(refDestructuringErrors) { - if (this.type === tokTypes._import) { - return parseDynamicImport.call(this); - } - return super.parseExprAtom(refDestructuringErrors); - } - }; -} - -const tt$1 = acorn__default.tokTypes; const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; const nextTokenIsDot = parser => { skipWhiteSpace.lastIndex = parser.pos; let skip = skipWhiteSpace.exec(parser.input); let next = parser.pos + skip[0].length; return parser.input.slice(next, next + 1) === "."; }; var acornImportMeta = function (Parser) { return class extends Parser { parseExprAtom(refDestructuringErrors) { - if (this.type !== tt$1._import || !nextTokenIsDot(this)) + if (this.type !== tt._import || !nextTokenIsDot(this)) return super.parseExprAtom(refDestructuringErrors); if (!this.options.allowImportExportEverywhere && !this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } let node = this.startNode(); node.meta = this.parseIdent(true); - this.expect(tt$1.dot); + this.expect(tt.dot); node.property = this.parseIdent(true); if (node.property.name !== "meta") { this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta"); } if (this.containsEsc) { this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences"); } return this.finishNode(node, "MetaProperty"); } parseStatement(context, topLevel, exports) { - if (this.type !== tt$1._import || !nextTokenIsDot(this)) { + if (this.type !== tt._import || !nextTokenIsDot(this)) { return super.parseStatement(context, topLevel, exports); } let node = this.startNode(); let expr = this.parseExpression(); return this.parseExpressionStatement(node, expr); @@ -15437,147 +15475,233 @@ trackedPaths.tracked = true; return found; } } -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 +var BuildPhase; +(function (BuildPhase) { + BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE"; + BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE"; + BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE"; +})(BuildPhase || (BuildPhase = {})); -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { - step(generator.next(value)); +function generateAssetFileName(name, source, output) { + const emittedName = name || 'asset'; + return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', { + hash() { + const hash = _256(); + hash.update(emittedName); + hash.update(':'); + hash.update(source); + return hash.digest('hex').substr(0, 8); + }, + ext: () => extname(emittedName).substr(1), + extname: () => extname(emittedName), + name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length) + }), output.bundle); +} +function reserveFileNameInBundle(fileName, bundle) { + if (fileName in bundle) { + return error(errFileNameConflict(fileName)); + } + bundle[fileName] = FILE_PLACEHOLDER; +} +const FILE_PLACEHOLDER = { + isPlaceholder: true +}; +function hasValidType(emittedFile) { + return (emittedFile && + (emittedFile.type === 'asset' || + emittedFile.type === 'chunk')); +} +function hasValidName(emittedFile) { + const validatedName = emittedFile.fileName || emittedFile.name; + return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName))); +} +function getValidSource(source, emittedFile, fileReferenceId) { + if (typeof source !== 'string' && !Buffer.isBuffer(source)) { + const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId; + return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`)); + } + return source; +} +function getAssetFileName(file, referenceId) { + if (typeof file.fileName !== 'string') { + return error(errAssetNotFinalisedForFileName(file.name || referenceId)); + } + return file.fileName; +} +function getChunkFileName(file) { + const fileName = file.fileName || (file.module && file.module.facadeChunk.id); + if (!fileName) + return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); + return fileName; +} +class FileEmitter { + constructor(graph) { + this.filesByReferenceId = new Map(); + // tslint:disable member-ordering + this.buildFilesByReferenceId = this.filesByReferenceId; + this.output = null; + this.emitFile = (emittedFile) => { + if (!hasValidType(emittedFile)) { + return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && + emittedFile.type}".`)); + } + if (!hasValidName(emittedFile)) { + return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || + emittedFile.name}".`)); + } + if (emittedFile.type === 'chunk') { + return this.emitChunk(emittedFile); + } + else { + return this.emitAsset(emittedFile); + } + }; + this.getFileName = (fileReferenceId) => { + const emittedFile = this.filesByReferenceId.get(fileReferenceId); + if (!emittedFile) + return error(errFileReferenceIdNotFoundForFilename(fileReferenceId)); + if (emittedFile.type === 'chunk') { + return getChunkFileName(emittedFile); + } + else { + return getAssetFileName(emittedFile, fileReferenceId); + } + }; + this.setAssetSource = (referenceId, requestedSource) => { + const consumedFile = this.filesByReferenceId.get(referenceId); + if (!consumedFile) + return error(errAssetReferenceIdNotFoundForSetSource(referenceId)); + if (consumedFile.type !== 'asset') { + return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`)); + } + if (consumedFile.source !== undefined) { + return error(errAssetSourceAlreadySet(consumedFile.name || referenceId)); + } + const source = getValidSource(requestedSource, consumedFile, referenceId); + if (this.output) { + this.finalizeAsset(consumedFile, source, referenceId, this.output); + } + else { + consumedFile.source = source; + } + }; + this.graph = graph; + } + startOutput(outputBundle, assetFileNames) { + this.filesByReferenceId = new Map(this.buildFilesByReferenceId); + this.output = { + assetFileNames, + bundle: outputBundle + }; + for (const emittedFile of this.filesByReferenceId.values()) { + if (emittedFile.fileName) { + reserveFileNameInBundle(emittedFile.fileName, this.output.bundle); + } } - catch (e) { - reject(e); - } } - function rejected(value) { try { - step(generator["throw"](value)); + for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) { + if (consumedFile.type === 'asset' && consumedFile.source !== undefined) { + this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output); + } } - catch (e) { - reject(e); - } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function addWithNewReferenceId(item, idMap, hashBase) { - let referenceId; - do { - const hash = _256(); - if (referenceId) { - hash.update(referenceId); + } + assertAssetsFinalized() { + for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) { + if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string') + error(errNoAssetSourceSet(emittedFile.name || referenceId)); } - else { - hash.update(hashBase); + } + emitAsset(emittedAsset) { + const source = typeof emittedAsset.source !== 'undefined' + ? getValidSource(emittedAsset.source, emittedAsset, null) + : undefined; + const consumedAsset = { + fileName: emittedAsset.fileName, + name: emittedAsset.name, + source, + type: 'asset' + }; + const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type); + if (this.output) { + if (emittedAsset.fileName) { + reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle); + } + if (source !== undefined) { + this.finalizeAsset(consumedAsset, source, referenceId, this.output); + } } - referenceId = hash.digest('hex').substr(0, 8); - } while (idMap.has(referenceId)); - idMap.set(referenceId, item); - return referenceId; -} - -function getAssetFileName(asset, existingNames, assetFileNames) { - if (asset.source === undefined) - error(errNoAssetSourceSet(asset)); - if (asset.fileName) - return asset.fileName; - return makeUnique(renderNamePattern(assetFileNames, 'assetFileNames', name => { - switch (name) { - case 'hash': - const hash = _256(); - hash.update(name); - hash.update(':'); - hash.update(asset.source); - return hash.digest('hex').substr(0, 8); - case 'name': - return asset.name.substr(0, asset.name.length - extname(asset.name).length); - case 'extname': - return extname(asset.name); - case 'ext': - return extname(asset.name).substr(1); + return referenceId; + } + emitChunk(emittedChunk) { + if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) { + error(errInvalidRollupPhaseForChunkEmission()); } - return undefined; - }), existingNames); -} -function createAssetPluginHooks(assetsByReferenceId, outputBundle, assetFileNames) { - return { - emitAsset(name, source) { - if (typeof name !== 'string' || !isPlainName(name)) - error(errInvalidAssetName(name)); - const asset = { name, source: source, fileName: undefined }; - if (outputBundle && source !== undefined) - finaliseAsset(asset, outputBundle, assetFileNames); - return addWithNewReferenceId(asset, assetsByReferenceId, name); - }, - setAssetSource(assetReferenceId, source) { - const asset = assetsByReferenceId.get(assetReferenceId); - if (!asset) - return error(errAssetReferenceIdNotFoundForSetSource(assetReferenceId)); - if (asset.source !== undefined) - return error(errAssetSourceAlreadySet(asset)); - if (typeof source !== 'string' && !source) - return error(errAssetSourceMissingForSetSource(asset)); - asset.source = source; - if (outputBundle) - finaliseAsset(asset, outputBundle, assetFileNames); - }, - getAssetFileName(assetReferenceId) { - const asset = assetsByReferenceId.get(assetReferenceId); - if (!asset) - return error(errAssetReferenceIdNotFoundForFilename(assetReferenceId)); - if ((asset).fileName === undefined) - return error(errAssetNotFinalisedForFileName(asset)); - return (asset).fileName; + if (typeof emittedChunk.id !== 'string') { + return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`)); } - }; -} -function finaliseAsset(asset, outputBundle, assetFileNames) { - const fileName = getAssetFileName(asset, outputBundle, assetFileNames); - asset.fileName = fileName; - outputBundle[fileName] = { - fileName, - isAsset: true, - source: asset.source - }; -} -function createTransformEmitAsset(assetsByReferenceId, emitAsset) { - const assets = []; - return { - assets, - emitAsset: (name, source) => { - const assetReferenceId = emitAsset(name, source); - const asset = assetsByReferenceId.get(assetReferenceId); - assets.push({ - fileName: undefined, - name: asset.name, - source: asset.source - }); - return assetReferenceId; + const consumedChunk = { + fileName: emittedChunk.fileName, + module: null, + name: emittedChunk.name || emittedChunk.id, + type: 'chunk' + }; + this.graph.moduleLoader + .addEntryModules([ + { + fileName: emittedChunk.fileName || null, + id: emittedChunk.id, + name: emittedChunk.name || null + } + ], false) + .then(({ newEntryModules: [module] }) => { + consumedChunk.module = module; + }) + .catch(() => { + // Avoid unhandled Promise rejection as the error will be thrown later + // once module loading has finished + }); + return this.assignReferenceId(consumedChunk, emittedChunk.id); + } + assignReferenceId(file, idBase) { + let referenceId; + do { + const hash = _256(); + if (referenceId) { + hash.update(referenceId); + } + else { + hash.update(idBase); + } + referenceId = hash.digest('hex').substr(0, 8); + } while (this.filesByReferenceId.has(referenceId)); + this.filesByReferenceId.set(referenceId, file); + return referenceId; + } + finalizeAsset(consumedFile, source, referenceId, output) { + const fileName = consumedFile.fileName || + this.findExistingAssetFileNameWithSource(output.bundle, source) || + generateAssetFileName(consumedFile.name, source, output); + // We must not modify the original assets to avoid interaction between outputs + const assetWithFileName = Object.assign({}, consumedFile, { source, fileName }); + this.filesByReferenceId.set(referenceId, assetWithFileName); + output.bundle[fileName] = { fileName, isAsset: true, source }; + } + findExistingAssetFileNameWithSource(bundle, source) { + for (const fileName of Object.keys(bundle)) { + const outputFile = bundle[fileName]; + if (outputFile.isAsset && + (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source) + ? source.equals(outputFile.source) + : source === outputFile.source)) + return fileName; } - }; + return null; + } } -var BuildPhase; -(function (BuildPhase) { - BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE"; - BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE"; - BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE"; -})(BuildPhase || (BuildPhase = {})); - const ANONYMOUS_PLUGIN_PREFIX = 'at position '; const deprecatedHooks = [ { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' }, { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' }, { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' }, @@ -15594,32 +15718,57 @@ }, active); } } } } +function throwPluginError(err, plugin, { hook, id } = {}) { + if (typeof err === 'string') + err = { message: err }; + if (err.code && err.code !== Errors.PLUGIN_ERROR) { + err.pluginCode = err.code; + } + err.code = Errors.PLUGIN_ERROR; + err.plugin = plugin; + if (hook) { + err.hook = hook; + } + if (id) { + err.id = id; + } + return error(err); +} function createPluginDriver(graph, options, pluginCache, watcher) { warnDeprecatedHooks(options.plugins, graph); + function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) { + let deprecationWarningShown = false; + return ((...args) => { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + graph.warnDeprecation({ + message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`, + plugin: pluginName + }, acitveDeprecation); + } + return handler(...args); + }); + } const plugins = [ ...options.plugins, getRollupDefaultPlugin(options.preserveSymlinks) ]; - const { emitAsset, getAssetFileName, setAssetSource } = createAssetPluginHooks(graph.assetsById); + const fileEmitter = new FileEmitter(graph); const existingPluginKeys = new Set(); - let hasLoadersOrTransforms = false; const pluginContexts = plugins.map((plugin, pidx) => { let cacheable = true; if (typeof plugin.cacheKey !== 'string') { if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) { cacheable = false; } else { existingPluginKeys.add(plugin.name); } } - if (!hasLoadersOrTransforms && - (plugin.load || plugin.transform || plugin.transformBundle || plugin.transformChunk)) - hasLoadersOrTransforms = true; let cacheInstance; if (!pluginCache) { cacheInstance = noCache; } else if (cacheable) { @@ -15634,29 +15783,19 @@ if (graph.phase >= BuildPhase.GENERATE) this.error(errInvalidRollupPhaseForAddWatchFile()); graph.watchFiles[id] = true; }, cache: cacheInstance, - emitAsset, - emitChunk(id, options) { - if (graph.phase > BuildPhase.LOAD_AND_PARSE) - this.error(errInvalidRollupPhaseForEmitChunk()); - return pluginDriver.emitChunk(id, options); - }, + emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false), + emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false), + emitFile: fileEmitter.emitFile, error(err) { - if (typeof err === 'string') - err = { message: err }; - if (err.code) - err.pluginCode = err.code; - err.code = 'PLUGIN_ERROR'; - err.plugin = plugin.name; - return error(err); + return throwPluginError(err, plugin.name); }, - getAssetFileName: getAssetFileName, - getChunkFileName(chunkReferenceId) { - return graph.moduleLoader.getChunkFileName(chunkReferenceId); - }, + getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false), + getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false), + getFileName: fileEmitter.getFileName, getModuleInfo(moduleId) { const foundModule = graph.moduleById.get(moduleId); if (foundModule == null) { throw new Error(`Unable to find module ${moduleId}`); } @@ -15668,49 +15807,25 @@ : foundModule.sources.map(id => foundModule.resolvedIds[id].id), isEntry: foundModule instanceof Module && foundModule.isEntryPoint, isExternal: foundModule instanceof ExternalModule }; }, - isExternal: (() => { - let deprecationWarningShown = false; - return (id, parentId, isResolved = false) => { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - graph.warnDeprecation({ - message: `The "this.isExternal" plugin context function used by plugin ${plugin.name} is deprecated. The "this.resolve" plugin context function should be used instead.`, - plugin: plugin.name - }, false); - } - return graph.moduleLoader.isExternal(id, parentId, isResolved); - }; - })(), + isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false), meta: { rollupVersion: version }, get moduleIds() { return graph.moduleById.keys(); }, parse: graph.contextParse, resolve(source, importer, options) { return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null); }, - resolveId: (() => { - let deprecationWarningShown = false; - return (source, importer) => { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - graph.warnDeprecation({ - message: `The "this.resolveId" plugin context function used by plugin ${plugin.name} is deprecated. The "this.resolve" plugin context function should be used instead.`, - plugin: plugin.name - }, false); - } - return graph.moduleLoader - .resolveId(source, importer) - .then(resolveId => resolveId && resolveId.id); - }; - })(), - setAssetSource, + resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader + .resolveId(source, importer) + .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false), + setAssetSource: fileEmitter.setAssetSource, warn(warning) { if (typeof warning === 'string') warning = { message: warning }; if (warning.code) warning.pluginCode = warning.code; @@ -15759,22 +15874,12 @@ }); } return hook.apply(context, args); } catch (err) { - if (typeof err === 'string') - err = { message: err }; - if (err.code !== 'PLUGIN_ERROR') { - if (err.code) - err.pluginCode = err.code; - err.code = 'PLUGIN_ERROR'; - } - err.plugin = plugin.name; - err.hook = hookName; - error(err); + return throwPluginError(err, plugin.name, { hook: hookName }); } - return undefined; } function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) { const plugin = plugins[pluginIndex]; let context = pluginContexts[pluginIndex]; const hook = plugin[hookName]; @@ -15796,33 +15901,18 @@ message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.` }); } return hook.apply(context, args); }) - .catch(err => { - if (typeof err === 'string') - err = { message: err }; - if (err.code !== 'PLUGIN_ERROR') { - if (err.code) - err.pluginCode = err.code; - err.code = 'PLUGIN_ERROR'; - } - err.plugin = plugin.name; - err.hook = hookName; - error(err); - }); + .catch(err => throwPluginError(err, plugin.name, { hook: hookName })); } const pluginDriver = { - emitAsset, - emitChunk(id, options) { - return graph.moduleLoader.addEntryModuleAndGetReferenceId({ - alias: (options && options.name) || null, - unresolvedId: id - }); + emitFile: fileEmitter.emitFile, + finaliseAssets() { + fileEmitter.assertAssetsFinalized(); }, - getAssetFileName: getAssetFileName, - hasLoadersOrTransforms, + getFileName: fileEmitter.getFileName, // chains, ignores returns hookSeq(name, args, hookContext) { let promise = Promise.resolve(); for (let i = 0; i < plugins.length; i++) promise = promise.then(() => runHook(name, args, i, false, hookContext)); @@ -15898,10 +15988,22 @@ return value; return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i])); }); } return promise; + }, + // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values. + hookReduceValueSync(name, initial, args, reduce, hookContext) { + let acc = initial; + for (let i = 0; i < plugins.length; i++) { + const result = runHookSync(name, args, i, true, hookContext); + acc = reduce.call(pluginContexts[i], acc, result, plugins[i]); + } + return acc; + }, + startOutput(outputBundle, assetFileNames) { + fileEmitter.startOutput(outputBundle, assetFileNames); } }; return pluginDriver; } function createPluginCache(cache) { @@ -15994,16 +16096,14 @@ function transform(graph, source, module) { const id = module.id; const sourcemapChain = []; let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map); - const baseEmitAsset = graph.pluginDriver.emitAsset; const originalCode = source.code; let ast = source.ast; - let transformDependencies; - let emittedAssets; - const emittedChunks = []; + const transformDependencies = []; + const emittedFiles = []; let customTransformCache = false; let moduleSideEffects = null; let trackedPluginCache; let curPlugin; const curSource = source.code; @@ -16012,29 +16112,23 @@ if (!customTransformCache && trackedPluginCache.used) customTransformCache = true; if (customTransformCache) { if (result && typeof result === 'object' && Array.isArray(result.dependencies)) { for (const dep of result.dependencies) { - const depId = resolve(dirname(id), dep); - if (!graph.watchFiles[depId]) - graph.watchFiles[depId] = true; + graph.watchFiles[resolve(dirname(id), dep)] = true; } } } else { - // assets/chunks emitted by a transform hook need to be emitted again if the hook is skipped - if (emittedAssets.length) - module.transformAssets = emittedAssets; - if (emittedChunks.length) - module.transformChunks = emittedChunks; + // files emitted by a transform hook need to be emitted again if the hook is skipped + if (emittedFiles.length) + module.transformFiles = emittedFiles; if (result && typeof result === 'object' && Array.isArray(result.dependencies)) { // not great, but a useful way to track this without assuming WeakMap if (!curPlugin.warnedTransformDependencies) graph.warnDeprecation(`Returning "dependencies" from the "transform" hook as done by plugin ${plugin.name} is deprecated. The "this.addWatchFile" plugin context function should be used instead.`, true); curPlugin.warnedTransformDependencies = true; - if (!transformDependencies) - transformDependencies = []; for (const dep of result.dependencies) transformDependencies.push(resolve(dirname(id), dep)); } } if (typeof result === 'string') { @@ -16069,12 +16163,10 @@ curPlugin = plugin; if (curPlugin.cacheKey) customTransformCache = true; else trackedPluginCache = trackPluginCache(pluginContext.cache); - let emitAsset; - ({ assets: emittedAssets, emitAsset } = createTransformEmitAsset(graph.assetsById, baseEmitAsset)); return Object.assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) { if (typeof warning === 'string') warning = { message: warning }; if (pos) augmentCodeLocation(warning, pos, curSource, id); @@ -16089,28 +16181,35 @@ augmentCodeLocation(err, pos, curSource, id); err.id = id; err.hook = 'transform'; return pluginContext.error(err); }, - emitAsset, + emitAsset(name, source) { + const emittedFile = { type: 'asset', name, source }; + emittedFiles.push(Object.assign({}, emittedFile)); + return graph.pluginDriver.emitFile(emittedFile); + }, emitChunk(id, options) { - emittedChunks.push({ id, options }); - return graph.pluginDriver.emitChunk(id, options); + const emittedFile = { type: 'chunk', id, name: options && options.name }; + emittedFiles.push(Object.assign({}, emittedFile)); + return graph.pluginDriver.emitFile(emittedFile); }, + emitFile(emittedFile) { + emittedFiles.push(emittedFile); + return graph.pluginDriver.emitFile(emittedFile); + }, addWatchFile(id) { - if (!transformDependencies) - transformDependencies = []; transformDependencies.push(id); pluginContext.addWatchFile(id); }, setAssetSource(assetReferenceId, source) { pluginContext.setAssetSource(assetReferenceId, source); if (!customTransformCache && !setAssetSourceErr) { try { this.error({ code: 'INVALID_SETASSETSOURCE', - message: `setAssetSource cannot be called in transform for caching reasons. Use emitAsset with a source, or call setAssetSource in another hook.` + message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.` }); } catch (err) { setAssetSourceErr = err; } @@ -16127,21 +16226,11 @@ sourcemapChain.length = 0; } return new SourceMap(Object.assign({}, combinedMap, { file: null, sourcesContent: combinedMap.sourcesContent })); } }); }) - .catch(err => { - if (typeof err === 'string') - err = { message: err }; - if (err.code !== 'PLUGIN_ERROR') { - if (err.code) - err.pluginCode = err.code; - err.code = 'PLUGIN_ERROR'; - } - err.id = id; - error(err); - }) + .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id })) .then(code => { if (!customTransformCache && setAssetSourceErr) throw setAssetSourceErr; return { ast: ast, @@ -16192,110 +16281,95 @@ const isPureExternalModule = getIdMatcher(pureExternalModules); return (id, external) => !(external && isPureExternalModule(id)); } class ModuleLoader { constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) { - this.entriesByReferenceId = new Map(); - this.entryModules = []; + this.indexedEntryModules = []; this.latestLoadModulesPromise = Promise.resolve(); this.manualChunkModules = {}; - this.loadEntryModule = ({ alias, unresolvedId }, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => { + this.nextEntryModuleIndex = 0; + this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => { if (resolveIdResult === false || (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) { return error(errEntryCannotBeExternal(unresolvedId)); } const id = resolveIdResult && typeof resolveIdResult === 'object' ? resolveIdResult.id : resolveIdResult; if (typeof id === 'string') { - return this.fetchModule(id, undefined, true, isEntry).then(module => { - if (alias !== null) { - if (module.chunkAlias !== null && module.chunkAlias !== alias) { - return error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias)); - } - module.chunkAlias = alias; - } - return module; - }); + return this.fetchModule(id, undefined, true, isEntry); } return error(errUnresolvedEntry(unresolvedId)); }); this.graph = graph; this.modulesById = modulesById; this.pluginDriver = pluginDriver; this.isExternal = getIdMatcher(external); this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph); this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null; } - addEntryModuleAndGetReferenceId(unresolvedEntryModule) { - const entryRecord = { - module: null, - name: unresolvedEntryModule.unresolvedId - }; - const referenceId = addWithNewReferenceId(entryRecord, this.entriesByReferenceId, unresolvedEntryModule.unresolvedId); - this.addEntryModules([unresolvedEntryModule], false) - .then(({ newEntryModules: [module] }) => { - entryRecord.module = module; - }) - .catch(() => { - // Avoid unhandled Promise rejection as the error will be thrown later - // once module loading has finished - }); - return referenceId; - } addEntryModules(unresolvedEntryModules, isUserDefined) { - const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(unresolvedEntryModule => this.loadEntryModule(unresolvedEntryModule, true))).then(entryModules => { + const firstEntryModuleIndex = this.nextEntryModuleIndex; + this.nextEntryModuleIndex += unresolvedEntryModules.length; + const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => { + if (fileName !== null) { + module.chunkFileNames.add(fileName); + } + else if (name !== null) { + if (module.chunkName === null) { + module.chunkName = name; + } + if (isUserDefined) { + module.userChunkNames.add(name); + } + } + return module; + }))).then(entryModules => { + let moduleIndex = firstEntryModuleIndex; for (const entryModule of entryModules) { entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined; - const existingEntryModule = this.entryModules.find(module => module.id === entryModule.id); - if (!existingEntryModule) { - this.entryModules.push(entryModule); + const existingIndexModule = this.indexedEntryModules.find(indexedModule => indexedModule.module.id === entryModule.id); + if (!existingIndexModule) { + this.indexedEntryModules.push({ module: entryModule, index: moduleIndex }); } + else { + existingIndexModule.index = Math.min(existingIndexModule.index, moduleIndex); + } + moduleIndex++; } + this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1); return entryModules; }); return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({ - entryModules: this.entryModules, + entryModules: this.indexedEntryModules.map(({ module }) => module), manualChunkModulesByAlias: this.manualChunkModules, newEntryModules })); } addManualChunks(manualChunks) { const unresolvedManualChunks = []; for (const alias of Object.keys(manualChunks)) { const manualChunkIds = manualChunks[alias]; - for (const unresolvedId of manualChunkIds) { - unresolvedManualChunks.push({ alias: null, unresolvedId, manualChunkAlias: alias }); + for (const id of manualChunkIds) { + unresolvedManualChunks.push({ id, alias }); } } - const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(unresolvedManualChunk => this.loadEntryModule(unresolvedManualChunk, false))).then(manualChunkModules => { + const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => { for (let index = 0; index < manualChunkModules.length; index++) { - this.addToManualChunk(unresolvedManualChunks[index].manualChunkAlias, manualChunkModules[index]); + this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]); } }); return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise); } - getChunkFileName(referenceId) { - const entryRecord = this.entriesByReferenceId.get(referenceId); - if (!entryRecord) - return error(errChunkReferenceIdNotFoundForFilename(referenceId)); - const fileName = entryRecord.module && - (entryRecord.module.facadeChunk - ? entryRecord.module.facadeChunk.id - : entryRecord.module.chunk.id); - if (!fileName) - return error(errChunkNotGeneratedForFileName(entryRecord)); - return fileName; - } resolveId(source, importer, skip) { return __awaiter(this, void 0, void 0, function* () { return this.normalizeResolveIdResult(this.isExternal(source, importer, false) ? false : yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source); }); } - addToManualChunk(alias, module) { + addModuleToManualChunk(alias, module) { if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) { error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias)); } module.manualChunkAlias = alias; if (!this.manualChunkModules[alias]) { @@ -16344,11 +16418,11 @@ } const module = new Module(this.graph, id, moduleSideEffects, isEntry); this.modulesById.set(id, module); const manualChunkAlias = this.getManualChunk(id); if (typeof manualChunkAlias === 'string') { - this.addToManualChunk(manualChunkAlias, module); + this.addModuleToManualChunk(manualChunkAlias, module); } timeStart('load modules', 3); return Promise.resolve(this.pluginDriver.hookFirst('load', [id])) .catch((err) => { timeEnd('load modules', 3); @@ -16370,18 +16444,14 @@ .then(sourceDescription => { const cachedModule = this.graph.cachedModules.get(id); if (cachedModule && !cachedModule.customTransformCache && cachedModule.originalCode === sourceDescription.code) { - if (cachedModule.transformAssets) { - for (const { name, source } of cachedModule.transformAssets) - this.pluginDriver.emitAsset(name, source); + if (cachedModule.transformFiles) { + for (const emittedFile of cachedModule.transformFiles) + this.pluginDriver.emitFile(emittedFile); } - if (cachedModule.transformChunks) { - for (const { id, options } of cachedModule.transformChunks) - this.pluginDriver.emitChunk(id, options); - } return cachedModule; } if (typeof sourceDescription.moduleSideEffects === 'boolean') { module.moduleSideEffects = sourceDescription.moduleSideEffects; } @@ -16612,32 +16682,30 @@ warned[str] = true; }; } function normalizeEntryModules(entryModules) { if (typeof entryModules === 'string') { - return [{ alias: null, unresolvedId: entryModules }]; + return [{ fileName: null, name: null, id: entryModules }]; } if (Array.isArray(entryModules)) { - return entryModules.map(unresolvedId => ({ alias: null, unresolvedId })); + return entryModules.map(id => ({ fileName: null, name: null, id })); } - return Object.keys(entryModules).map(alias => ({ - alias, - unresolvedId: entryModules[alias] + return Object.keys(entryModules).map(name => ({ + fileName: null, + id: entryModules[name], + name })); } class Graph { constructor(options, watcher) { - this.assetsById = new Map(); - this.curChunkIndex = 0; this.moduleById = new Map(); this.needsTreeshakingPass = false; this.phase = BuildPhase.LOAD_AND_PARSE; this.watchFiles = Object.create(null); this.externalModules = []; this.modules = []; this.onwarn = options.onwarn || makeOnwarn(); - this.curChunkIndex = 0; this.deoptimizationTracker = new EntityPathTracker(); this.cachedModules = new Map(); if (options.cache) { if (options.cache.modules) for (const module of options.cache.modules) @@ -16698,15 +16766,13 @@ this.getModuleContext = id => moduleContext.get(id) || this.context; } else { this.getModuleContext = () => this.context; } - this.acornOptions = options.acorn || {}; + this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {}; const acornPluginsToInject = []; - acornPluginsToInject.push(dynamicImport); acornPluginsToInject.push(acornImportMeta); - acornPluginsToInject.push(acornBigint); if (options.experimentalTopLevelAwait) { this.acornOptions.allowAwaitOutsideFunction = true; } const acornInjectPlugins = options.acornInjectPlugins; acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins) @@ -16809,27 +16875,17 @@ chunk.link(); } chunks = chunks.filter(isChunkRendered); const facades = []; for (const chunk of chunks) { - for (const facade of chunk.generateFacades()) { - facades.push(facade); - } + facades.push(...chunk.generateFacades()); } timeEnd('generate chunks', 2); this.phase = BuildPhase.GENERATE; return chunks.concat(facades); }); } - finaliseAssets(assetFileNames) { - const outputBundle = Object.create(null); - this.assetsById.forEach(asset => { - if (asset.source !== undefined) - finaliseAsset(asset, outputBundle, assetFileNames); - }); - return outputBundle; - } getCache() { // handle plugin cache eviction for (const name in this.pluginCache) { const cache = this.pluginCache[name]; let allDeleted = true; @@ -16961,41 +17017,41 @@ \tError Message: ${err.message}` }); }); } -function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons) { - const usedIds = {}; - const [entryChunks, otherChunks] = chunks.reduce(([entryChunks, otherChunks], chunk) => { +function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) { + const entryChunks = []; + const otherChunks = []; + for (const chunk of chunks) { (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint ? entryChunks : otherChunks).push(chunk); - return [entryChunks, otherChunks]; - }, [[], []]); + } // make sure entry chunk names take precedence with regard to deconflicting const chunksForNaming = entryChunks.concat(otherChunks); - for (let i = 0; i < chunksForNaming.length; i++) { - const chunk = chunksForNaming[i]; + for (const chunk of chunksForNaming) { + const facadeModule = chunk.facadeModule; if (outputOptions.file) { chunk.id = basename(outputOptions.file); } else if (inputOptions.preserveModules) { - chunk.generateIdPreserveModules(inputBase, usedIds); + chunk.id = chunk.generateIdPreserveModules(inputBase, bundle); } else { let pattern, patternName; - if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) { + if (facadeModule && facadeModule.isUserDefinedEntryPoint) { pattern = outputOptions.entryFileNames || '[name].js'; patternName = 'output.entryFileNames'; } else { pattern = outputOptions.chunkFileNames || '[name]-[hash].js'; patternName = 'output.chunkFileNames'; } - chunk.generateId(pattern, patternName, addons, outputOptions, usedIds); + chunk.id = chunk.generateId(pattern, patternName, addons, outputOptions, bundle); } - usedIds[chunk.id] = true; + bundle[chunk.id] = FILE_PLACEHOLDER; } } // ported from https://github.com/substack/node-commondir function commondir(files) { @@ -17217,10 +17273,11 @@ dynamicImportFunction: getOption('dynamicImportFunction'), entryFileNames: getOption('entryFileNames'), esModule: getOption('esModule', true), exports: getOption('exports'), extend: getOption('extend'), + externalLiveBindings: getOption('externalLiveBindings', true), file: getOption('file'), footer: getOption('footer'), format: format === 'esm' ? 'es' : format, freeze: getOption('freeze', true), globals: getOption('globals'), @@ -17341,44 +17398,70 @@ } let curWatcher; function setWatcher(watcher) { curWatcher = watcher; } +function assignChunksToBundle(chunks, outputBundle) { + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const facadeModule = chunk.facadeModule; + outputBundle[chunk.id] = { + code: undefined, + dynamicImports: chunk.getDynamicImportIds(), + exports: chunk.getExportNames(), + facadeModuleId: facadeModule && facadeModule.id, + fileName: chunk.id, + imports: chunk.getImportIds(), + isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0, + isEntry: facadeModule !== null && facadeModule.isEntryPoint, + map: undefined, + modules: chunk.renderedModules, + get name() { + return chunk.getChunkName(); + } + }; + } + return outputBundle; +} function rollup(rawInputOptions) { - try { + return __awaiter(this, void 0, void 0, function* () { const inputOptions = getInputOptions$1(rawInputOptions); initialiseTimers(inputOptions); const graph = new Graph(inputOptions, curWatcher); curWatcher = undefined; // remove the cache option from the memory after graph creation (cache is not used anymore) const useCache = rawInputOptions.cache !== false; delete inputOptions.cache; delete rawInputOptions.cache; timeStart('BUILD', 1); - return graph.pluginDriver - .hookParallel('buildStart', [inputOptions]) - .then(() => graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports)) - .then(chunks => graph.pluginDriver.hookParallel('buildEnd', []).then(() => chunks), err => graph.pluginDriver.hookParallel('buildEnd', [err]).then(() => { + let chunks; + try { + yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]); + chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports); + } + catch (err) { + yield graph.pluginDriver.hookParallel('buildEnd', [err]); throw err; - })) - .then(chunks => { - timeEnd('BUILD', 1); - // ensure we only do one optimization pass per build - let optimized = false; - function getOutputOptions(rawOutputOptions) { - return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver); - } - function generate(outputOptions, isWrite) { + } + yield graph.pluginDriver.hookParallel('buildEnd', []); + timeEnd('BUILD', 1); + // ensure we only do one optimization pass per build + let optimized = false; + function getOutputOptions(rawOutputOptions) { + return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver); + } + function generate(outputOptions, isWrite) { + return __awaiter(this, void 0, void 0, function* () { timeStart('GENERATE', 1); const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]'; - const outputBundle = graph.finaliseAssets(assetFileNames); + const outputBundleWithPlaceholders = Object.create(null); + let outputBundle; const inputBase = commondir(getAbsoluteEntryModulePaths(chunks)); - return graph.pluginDriver - .hookParallel('renderStart', []) - .then(() => createAddons(graph, outputOptions)) - .then(addons => { - // pre-render all chunks + graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames); + try { + yield graph.pluginDriver.hookParallel('renderStart', []); + const addons = yield createAddons(graph, outputOptions); for (const chunk of chunks) { if (!inputOptions.preserveModules) chunk.generateInternalExports(outputOptions); if (chunk.facadeModule && chunk.facadeModule.isEntryPoint) chunk.exportMode = getExportMode(chunk, outputOptions); @@ -17388,124 +17471,88 @@ } if (!optimized && inputOptions.experimentalOptimizeChunks) { optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase); optimized = true; } - assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons); - // assign to outputBundle - for (let i = 0; i < chunks.length; i++) { - const chunk = chunks[i]; - const facadeModule = chunk.facadeModule; - outputBundle[chunk.id] = { - code: undefined, - dynamicImports: chunk.getDynamicImportIds(), - exports: chunk.getExportNames(), - facadeModuleId: facadeModule && facadeModule.id, - fileName: chunk.id, - imports: chunk.getImportIds(), - isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0, - isEntry: facadeModule !== null && facadeModule.isEntryPoint, - map: undefined, - modules: chunk.renderedModules, - get name() { - return chunk.getChunkName(); - } - }; - } - return Promise.all(chunks.map(chunk => { - const outputChunk = outputBundle[chunk.id]; + assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders); + outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders); + yield Promise.all(chunks.map(chunk => { + const outputChunk = outputBundleWithPlaceholders[chunk.id]; return chunk.render(outputOptions, addons, outputChunk).then(rendered => { outputChunk.code = rendered.code; outputChunk.map = rendered.map; return graph.pluginDriver.hookParallel('ongenerate', [ Object.assign({ bundle: outputChunk }, outputOptions), outputChunk ]); }); - })).then(() => { }); - }) - .catch(error => graph.pluginDriver.hookParallel('renderError', [error]).then(() => { + })); + } + catch (error) { + yield graph.pluginDriver.hookParallel('renderError', [error]); throw error; - })) - .then(() => { - // run generateBundle hook - // assets emitted during generateBundle are unique to that specific generate call - const assets = new Map(graph.assetsById); - const generateAssetPluginHooks = createAssetPluginHooks(assets, outputBundle, assetFileNames); - return graph.pluginDriver - .hookSeq('generateBundle', [outputOptions, outputBundle, isWrite], context => (Object.assign({}, context, generateAssetPluginHooks))) - .then(() => { - // throw errors for assets not finalised with a source - assets.forEach(asset => { - if (asset.fileName === undefined) - finaliseAsset(asset, outputBundle, assetFileNames); - }); + } + yield graph.pluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]); + graph.pluginDriver.finaliseAssets(); + timeEnd('GENERATE', 1); + return outputBundle; + }); + } + const cache = useCache ? graph.getCache() : undefined; + const result = { + cache: cache, + generate: ((rawOutputOptions) => { + const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result)); + Object.defineProperty(promise, 'code', throwAsyncGenerateError); + Object.defineProperty(promise, 'map', throwAsyncGenerateError); + return promise; + }), + watchFiles: Object.keys(graph.watchFiles), + write: ((rawOutputOptions) => { + const outputOptions = getOutputOptions(rawOutputOptions); + if (!outputOptions.dir && !outputOptions.file) { + error({ + code: 'MISSING_OPTION', + message: 'You must specify "output.file" or "output.dir" for the build.' }); - }) - .then(() => { - timeEnd('GENERATE', 1); - return outputBundle; - }); - } - const cache = useCache ? graph.getCache() : undefined; - const result = { - cache: cache, - generate: ((rawOutputOptions) => { - const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result)); - Object.defineProperty(promise, 'code', throwAsyncGenerateError); - Object.defineProperty(promise, 'map', throwAsyncGenerateError); - return promise; - }), - watchFiles: Object.keys(graph.watchFiles), - write: ((rawOutputOptions) => { - const outputOptions = getOutputOptions(rawOutputOptions); - if (!outputOptions.dir && !outputOptions.file) { - error({ - code: 'MISSING_OPTION', - message: 'You must specify "output.file" or "output.dir" for the build.' - }); + } + return generate(outputOptions, true).then((bundle) => __awaiter(this, void 0, void 0, function* () { + let chunkCnt = 0; + for (const fileName of Object.keys(bundle)) { + const file = bundle[fileName]; + if (file.isAsset) + continue; + chunkCnt++; + if (chunkCnt > 1) + break; } - return generate(outputOptions, true).then(bundle => { - let chunkCnt = 0; - for (const fileName of Object.keys(bundle)) { - const file = bundle[fileName]; - if (file.isAsset) - continue; - chunkCnt++; - if (chunkCnt > 1) - break; - } - if (chunkCnt > 1) { - if (outputOptions.sourcemapFile) - error({ - code: 'INVALID_OPTION', - message: '"output.sourcemapFile" is only supported for single-file builds.' - }); - if (typeof outputOptions.file === 'string') - error({ - code: 'INVALID_OPTION', - message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' + - (typeof inputOptions.input !== 'string' || - inputOptions.inlineDynamicImports === true - ? '' - : ' To inline dynamic imports, set the "inlineDynamicImports" option.') - }); - } - return Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions))) - .then(() => graph.pluginDriver.hookParallel('writeBundle', [bundle])) - .then(() => createOutput(bundle)); - }); - }) - }; - if (inputOptions.perf === true) - result.getTimings = getTimings; - return result; - }); - } - catch (err) { - return Promise.reject(err); - } + if (chunkCnt > 1) { + if (outputOptions.sourcemapFile) + error({ + code: 'INVALID_OPTION', + message: '"output.sourcemapFile" is only supported for single-file builds.' + }); + if (typeof outputOptions.file === 'string') + error({ + code: 'INVALID_OPTION', + message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' + + (typeof inputOptions.input !== 'string' || + inputOptions.inlineDynamicImports === true + ? '' + : ' To inline dynamic imports, set the "inlineDynamicImports" option.') + }); + } + yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions))); + yield graph.pluginDriver.hookParallel('writeBundle', [bundle]); + return createOutput(bundle); + })); + }) + }; + if (inputOptions.perf === true) + result.getTimings = getTimings; + return result; + }); } var SortingFileType; (function (SortingFileType) { SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK"; SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK"; @@ -17522,11 +17569,11 @@ } function createOutput(outputBundle) { return { output: Object.keys(outputBundle) .map(fileName => outputBundle[fileName]) - .sort((outputFileA, outputFileB) => { + .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => { const fileTypeA = getSortingFileType(outputFileA); const fileTypeB = getSortingFileType(outputFileB); if (fileTypeA === fileTypeB) return 0; return fileTypeA < fileTypeB ? -1 : 1; @@ -17578,11 +17625,14 @@ if (mergedOptions.optionError) throw new Error(mergedOptions.optionError); // now outputOptions is an array, but rollup.rollup API doesn't support arrays const mergedOutputOptions = mergedOptions.outputOptions[0]; const outputOptionsReducer = (outputOptions, result) => result || outputOptions; - const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer); + const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => { + const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook()); + return Object.assign({}, pluginContext, { emitFile: emitError, setAssetSource: emitError }); + }); checkOutputOptions(outputOptions); if (typeof outputOptions.file === 'string') { if (typeof outputOptions.dir === 'string') error({ code: 'INVALID_OPTION', @@ -20647,23 +20697,23 @@ var getModule = function (dir) { var rootPath = dir ? path.resolve(dir) : process.cwd(); var rootName = path.join(rootPath, '@root'); var root = modules[rootName]; if (!root) { - root = new module$1(rootName); + root = new module(rootName); root.filename = rootName; - root.paths = module$1._nodeModulePaths(rootPath); + root.paths = module._nodeModulePaths(rootPath); modules[rootName] = root; } return root; }; var requireRelative = function (requested, relativeTo) { var root = getModule(relativeTo); return root.require(requested); }; requireRelative.resolve = function (requested, relativeTo) { var root = getModule(relativeTo); - return module$1._resolveFilename(requested, root); + return module._resolveFilename(requested, root); }; var requireRelative_1 = requireRelative; let chokidar; try {