AssetParser.js 2.2 KB

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