AssetParser.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Yuta Hiroto @hiroppy
  4. */
  5. "use strict";
  6. const Parser = require("../Parser");
  7. /** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */
  8. /** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
  9. /** @typedef {import("../Module")} Module */
  10. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  11. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  12. /** @typedef {import("../Parser").ParserState} ParserState */
  13. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  14. /** @typedef {((source: string | Buffer, context: { filename: string, module: Module }) => boolean)} AssetParserDataUrlFunction */
  15. class AssetParser extends Parser {
  16. /**
  17. * Creates an instance of AssetParser.
  18. * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl
  19. */
  20. constructor(dataUrlCondition) {
  21. super();
  22. /** @type {AssetParserOptions["dataUrlCondition"] | boolean} */
  23. this.dataUrlCondition = dataUrlCondition;
  24. }
  25. /**
  26. * Parses the provided source and updates the parser state.
  27. * @param {string | Buffer | PreparsedAst} source the source to parse
  28. * @param {ParserState} state the parser state
  29. * @returns {ParserState} the parser state
  30. */
  31. parse(source, state) {
  32. if (typeof source === "object" && !Buffer.isBuffer(source)) {
  33. throw new Error("AssetParser doesn't accept preparsed AST");
  34. }
  35. const buildInfo =
  36. /** @type {BuildInfo} */
  37. (state.module.buildInfo);
  38. buildInfo.strict = true;
  39. const buildMeta =
  40. /** @type {BuildMeta} */
  41. (state.module.buildMeta);
  42. buildMeta.exportsType = "default";
  43. buildMeta.defaultObject = false;
  44. if (typeof this.dataUrlCondition === "function") {
  45. buildInfo.dataUrl = this.dataUrlCondition(source, {
  46. filename: /** @type {string} */ (state.module.getResource()),
  47. module: state.module
  48. });
  49. } else if (typeof this.dataUrlCondition === "boolean") {
  50. buildInfo.dataUrl = this.dataUrlCondition;
  51. } else if (
  52. this.dataUrlCondition &&
  53. typeof this.dataUrlCondition === "object"
  54. ) {
  55. buildInfo.dataUrl =
  56. Buffer.byteLength(source) <=
  57. /** @type {NonNullable<AssetParserDataUrlOptions["maxSize"]>} */
  58. (this.dataUrlCondition.maxSize);
  59. } else {
  60. throw new Error("Unexpected dataUrlCondition type");
  61. }
  62. return state;
  63. }
  64. }
  65. module.exports = AssetParser;