UNPKG

@omnia/tooling-vue

Version:

Used to bundle and serve manifests web component that build on Vue framework.

359 lines (358 loc) • 16.5 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PreventInlineEntryModule = exports.ChunkAssets = exports.BuildWebpackRequire = exports.ModifyContent = exports.NamedModulesPlugin = exports.StatsWriterPlugin = exports.DllReferencePlugin = void 0; const tslib_1 = require("tslib"); const $ = tslib_1.__importStar(require("../variables")); const webpack_1 = require("webpack"); const parseJson = require("json-parse-better-errors"); const DelegatedModuleFactoryPlugin = require("webpack/lib/DelegatedModuleFactoryPlugin"); const ExternalModuleFactoryPlugin = require("webpack/lib/ExternalModuleFactoryPlugin"); const DelegatedSourceDependency = require("webpack/lib/dependencies/DelegatedSourceDependency"); const createSchemaValidation = require("webpack/lib/util/create-schema-validation"); const makePathsRelative = require("webpack/lib/util/identifier").makePathsRelative; const INDENT = 2; const DEFAULT_TRANSFORM = (data) => JSON.stringify(data, null, INDENT); var ConcatSource = require('webpack-core/lib/ConcatSource'); function modifyAsset(assets, fileName, replacements) { var result = assets[fileName].source(); replacements.forEach(function (modifier) { modifier.replacement = modifier.replacement || ""; if (typeof modifier.replacement === 'function') { modifier.replacement(result); } else if (modifier.insertToEOF) { var insertData = ""; if (modifier.pattern) { var matchs = result.match(modifier.pattern); if (matchs !== null) { insertData = modifier.replacement(matchs[0]); } } else insertData = modifier.replacement; if (typeof insertData === "string") { result = result + '\r\n' + insertData; } } else if (modifier.pattern) { result = result.replace(modifier.pattern, modifier.replacement); } }); assets[fileName] = new ConcatSource(result); } function ModifyContent(replacements, allowAllFileExtensions) { if (!(replacements instanceof Array)) { throw new TypeError('Argument "args" must be an array.'); } this.replacements = replacements; this.allowAllFileExtensions = allowAllFileExtensions; } exports.ModifyContent = ModifyContent; ModifyContent.prototype.apply = function (compiler) { compiler.hooks.compilation.tap("ModifyContent", (compilation) => { compilation.hooks.processAssets.tap({ name: 'BuildWebpackRequire', stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, // see below for more stages }, (assets, done) => { if (assets) { Object.keys(assets).forEach((fileName) => { if (this.allowAllFileExtensions || $.path.extname(fileName) === ".js") { modifyAsset(assets, fileName, this.replacements); } }); } }); }); }; class PreventInlineEntryModule { apply(compiler) { compiler.hooks.compilation.tap("PreventInlineEntryModule", (compilation) => { const hooks = webpack_1.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation); hooks.inlineInRuntimeBailout.tap("PreventInlineEntryModule", () => "PreventInlineEntryModule is used."); }); } } exports.PreventInlineEntryModule = PreventInlineEntryModule; class ChunkAssets { constructor(callBack) { this.callBack = callBack; this.callBack = callBack || null; } apply(compiler) { if (typeof this.callBack === "function") { compiler.hooks.compilation.tap("ChunkAssets", (compilation) => { compilation.hooks.processAssets.tap({ name: 'BuildWebpackRequire', stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, }, (assets) => { if (assets) { Object.keys(assets).forEach(fileName => { if (typeof this.callBack === "function") this.callBack(compilation, fileName); }); } }); }); } } } exports.ChunkAssets = ChunkAssets; class BuildWebpackRequire { constructor(omniaServiceId, manifestId, autoGenerateCommonChunk) { this.omniaServiceId = omniaServiceId; this.manifestId = manifestId; this.autoGenerateCommonChunk = autoGenerateCommonChunk; this.omniaServiceId = omniaServiceId || ""; this.manifestId = manifestId || ""; this.autoGenerateCommonChunk = autoGenerateCommonChunk || false; } apply(compiler) { compiler.hooks.compilation.tap("BuildWebpackRequire", (compilation) => { compilation.hooks.additionalTreeRuntimeRequirements.tap("BuildWebpackRequire", (chunk, runtimeRequirements) => { runtimeRequirements.add(webpack_1.RuntimeGlobals.require); }); compilation.hooks.processAssets.tap({ name: 'BuildWebpackRequire', stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, // see below for more stages }, (assets, done) => { if (assets) { Object.keys(assets).forEach((fileName) => { if ($.path.extname(fileName) === ".js") { "".replace; var result = assets[fileName].source(); result = result .replace('var __webpack_module_cache__ = {};', `/******/ if (typeof omniaWebpackJsonp === 'undefined'){ /******/ globalThis['omniaWebpackJsonp'] = {}; /******/ } /******/ globalThis.omniaWebpackJsonp['${this.omniaServiceId}'] = globalThis.omniaWebpackJsonp['${this.omniaServiceId}'] || {}; /******/ if (globalThis.omniaWebpackJsonp['${this.omniaServiceId}']['${this.manifestId}']){ /******/ console.error("Error, already loaded manifest ${this.manifestId} with service id ${this.omniaServiceId}"); /******/ return; /******/ } /******/ globalThis.omniaWebpackJsonp['${this.omniaServiceId}']['${this.manifestId}'] = __webpack_require__; /******/ var __omnia_webpack_module_cache__ = {};`) .replace(/__webpack_module_cache__/g, '__omnia_webpack_module_cache__'); assets[fileName] = new ConcatSource(result); } }); } }); }); if (this.autoGenerateCommonChunk) { compiler.hooks.compilation.tap("BuildWebpackRequire", (compilation) => { compilation.hooks.processAssets.tap({ name: 'BuildWebpackRequire', stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, // see below for more stages }, (assets, done) => { Object.keys(assets).forEach((fileName) => { if ($.path.extname(fileName) === ".js") { modifyAsset(assets, fileName, [ { insertToEOF: true, replacement: "globalThis.omniaWebpackJsonp['" + this.omniaServiceId + "']['" + $.tooling.utils.getGuidValue(fileName.toLowerCase()) + "'] = omniaWebpackJsonp['" + this.omniaServiceId + "']['" + this.manifestId + "'];" } ]); } }); }); }); } } } exports.BuildWebpackRequire = BuildWebpackRequire; function NamedModulesPlugin(options) { this.options = options || {}; } exports.NamedModulesPlugin = NamedModulesPlugin; NamedModulesPlugin.prototype.apply = function (compiler) { compiler.hooks.compilation.tap("OmniaNamedModulesPlugin", function (compilation) { compilation.hooks.beforeModuleIds.tap("OmniaNamedModulesPlugin", function (modules) { Array.from(modules).forEach(function (module) { const chunkGraph = compilation.chunkGraph; const context = this.options.context || compiler.options.context; for (const module of Array.from(modules)) { let moduleId = chunkGraph.getModuleId(module); if (!moduleId && module.libIdent) { moduleId = module.libIdent({ context }); if (moduleId) { if (this.options.replacements !== undefined) { this.options.replacements.forEach(function (replacement) { moduleId = moduleId.replace(replacement.pattern, replacement.replace); }, this); } moduleId = moduleId.toLowerCase(); chunkGraph.setModuleId(module, moduleId); } } } }, this); }.bind(this)); }.bind(this)); }; class StatsWriterPlugin { constructor(opts) { this.opts = opts; this.opts = this.opts || {}; this.opts.fields = typeof this.opts.fields !== "undefined" ? this.opts.fields : ["assetsByChunkName"]; this.opts.transform = this.opts.transform || DEFAULT_TRANSFORM; } apply(compiler) { if (compiler.hooks) { compiler.hooks.emit.tapPromise("stats-writer-plugin", this.emitStats.bind(this)); } else { compiler.plugin("emit", this.emitStats.bind(this)); } } emitStats(curCompiler, callback) { // Get stats. // **Note**: In future, could pass something like `{ showAssets: true }` // to the `getStats()` function for more limited object returned. let stats = curCompiler.getStats().toJson(); // Filter to fields. if (this.opts.fields) { stats = this.opts.fields.reduce((memo, key) => { memo[key] = stats[key]; return memo; }, {}); } // Transform to string. let err; return Promise.resolve() // Transform. .then(() => this.opts.transform(stats, { compiler: curCompiler })) .catch((e) => { err = e; }); } } exports.StatsWriterPlugin = StatsWriterPlugin; const validate = createSchemaValidation(require("webpack/schemas/plugins/DllReferencePlugin.check.js"), () => require("webpack/schemas/plugins/DllReferencePlugin.json"), { name: "Dll Reference Plugin", baseDataPath: "options" }); class DllReferencePlugin { /** * @param {DllReferencePluginOptions} options options object */ constructor(options) { validate(options); this.options = options; /** @type {WeakMap<Object, {path: string, data: DllReferencePluginOptionsManifest?, error: Error?}>} */ this._compilationData = new WeakMap(); } getModuleId(name) { let module = DllReferencePlugin.modulesMap.find(m => m.name === name); if (module === undefined) { module = { name: name, id: ++DllReferencePlugin.trackingModuleRefId }; DllReferencePlugin.modulesMap.push(module); } return module.id; } apply(compiler) { compiler.hooks.compilation.tap("DllReferencePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set(DelegatedSourceDependency, normalModuleFactory); }); compiler.hooks.beforeCompile.tapAsync("DllReferencePlugin", (params, callback) => { if ("manifest" in this.options) { const manifest = this.options.manifest; if (typeof manifest === "string") { compiler.inputFileSystem.readFile(manifest, (err, result) => { if (err) return callback(err); const data = { path: manifest, data: undefined, error: undefined }; // Catch errors parsing the manifest so that blank // or malformed manifest files don't kill the process. try { data.data = parseJson(result.toString("utf-8")); } catch (e) { // Store the error in the params so that it can // be added as a compilation error later on. const manifestPath = makePathsRelative(compiler.options.context, manifest, compiler.root); data.error = new DllManifestError(manifestPath, e.message); } this._compilationData.set(params, data); return callback(); }); return; } } return callback(); }); compiler.hooks.compile.tap("DllReferencePlugin", params => { let name = this.options.name; let sourceType = this.options.sourceType; let content = "content" in this.options ? this.options.content : undefined; if ("manifest" in this.options) { let manifestParameter = this.options.manifest; let manifest; if (typeof manifestParameter === "string") { const data = this._compilationData.get(params); // If there was an error parsing the manifest // file, exit now because the error will be added // as a compilation error in the "compilation" hook. if (data.error) { return; } manifest = data.data; } else { manifest = manifestParameter; } if (manifest) { if (!name) name = manifest.name; if (!sourceType) sourceType = manifest.type; if (!content) content = manifest.content; } } /** @type {Externals} */ const externals = {}; //const source = "dll-reference " + name const source = `dll-reference md${this.getModuleId(name)}`; externals[source] = name; const normalModuleFactory = params.normalModuleFactory; new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply(normalModuleFactory); new DelegatedModuleFactoryPlugin({ source: source, type: this.options.type, scope: this.options.scope, context: this.options.context || compiler.options.context, content, extensions: this.options.extensions, associatedObjectForCache: compiler.root }).apply(normalModuleFactory); }); compiler.hooks.compilation.tap("DllReferencePlugin", (compilation, params) => { if ("manifest" in this.options) { let manifest = this.options.manifest; if (typeof manifest === "string") { const data = this._compilationData.get(params); // If there was an error parsing the manifest file, add the // error as a compilation error to make the compilation fail. if (data.error) { compilation.errors.push(data.error); } compilation.fileDependencies.add(manifest); } } }); } } exports.DllReferencePlugin = DllReferencePlugin; DllReferencePlugin.trackingModuleRefId = 1; DllReferencePlugin.modulesMap = []; class DllManifestError extends webpack_1.WebpackError { constructor(filename, message) { super(); this.name = "DllManifestError"; this.message = `Dll manifest ${filename}\n${message}`; } }