DependenciesBlockVariable.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource, ReplaceSource } = require("webpack-sources");
  7. /** @typedef {import("./Dependency")} Dependency */
  8. /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */
  9. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  10. /** @typedef {import("./util/createHash").Hash} Hash */
  11. /** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */
  12. /** @typedef {Map<Function, DependencyTemplate>} DependencyTemplates */
  13. class DependenciesBlockVariable {
  14. /**
  15. * Creates an instance of DependenciesBlockVariable.
  16. * @param {string} name name of DependenciesBlockVariable
  17. * @param {string} expression expression string
  18. * @param {Dependency[]=} dependencies dependencies tied to this varaiable
  19. */
  20. constructor(name, expression, dependencies) {
  21. this.name = name;
  22. this.expression = expression;
  23. this.dependencies = dependencies || [];
  24. }
  25. /**
  26. * @param {Hash} hash hash for instance to update
  27. * @returns {void}
  28. */
  29. updateHash(hash) {
  30. hash.update(this.name);
  31. hash.update(this.expression);
  32. for (const d of this.dependencies) {
  33. d.updateHash(hash);
  34. }
  35. }
  36. /**
  37. * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map.
  38. * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce
  39. * @returns {ReplaceSource} returns constructed source for expression via templates
  40. */
  41. expressionSource(dependencyTemplates, runtimeTemplate) {
  42. const source = new ReplaceSource(new RawSource(this.expression));
  43. for (const dep of this.dependencies) {
  44. const template = dependencyTemplates.get(dep.constructor);
  45. if (!template) {
  46. throw new Error(`No template for dependency: ${dep.constructor.name}`);
  47. }
  48. template.apply(dep, source, runtimeTemplate, dependencyTemplates);
  49. }
  50. return source;
  51. }
  52. disconnect() {
  53. for (const d of this.dependencies) {
  54. d.disconnect();
  55. }
  56. }
  57. hasDependencies(filter) {
  58. if (filter) {
  59. return this.dependencies.some(filter);
  60. }
  61. return this.dependencies.length > 0;
  62. }
  63. }
  64. module.exports = DependenciesBlockVariable;