| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266 |
- /*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Ivan Kopeykin @vankop
- */
- "use strict";
- const { ASSET_URL_TYPE } = require("../ModuleSourceTypeConstants");
- const RawDataUrlModule = require("../asset/RawDataUrlModule");
- const makeSerializable = require("../util/makeSerializable");
- const memoize = require("../util/memoize");
- const ModuleDependency = require("./ModuleDependency");
- /** @import { ReplaceSource } from "webpack-sources" */
- /** @import CodeGenerationResults from "../CodeGenerationResults" */
- /** @import Dependency, { UpdateHashContext } from "../Dependency" */
- /**
- * @import {
- * CssDependencyTemplateContext as DependencyTemplateContext
- * } from "../DependencyTemplate"
- */
- /** @import Module from "../Module" */
- /** @import { Range } from "../javascript/JavascriptParser" */
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<["string" | "url" | "src", true | undefined, true | undefined, ("high" | "low" | "auto" | undefined), string | undefined, string | undefined, string | undefined]>} ObjectDeserializerContext */
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<["string" | "url" | "src", true | undefined, true | undefined, ("high" | "low" | "auto" | undefined), string | undefined, string | undefined, string | undefined]>} ObjectSerializerContext */
- /** @import Hash from "../util/Hash" */
- /** @import { RuntimeSpec } from "../util/runtime" */
- /** @import { NormalModuleBuildInfo } from "../NormalModule" */
- const getIgnoredRawDataUrlModule = memoize(
- () => new RawDataUrlModule("data:,", "ignored-asset", "(ignored asset)")
- );
- class CssUrlDependency extends ModuleDependency {
- /**
- * Creates an instance of CssUrlDependency.
- * @param {string} request request
- * @param {Range} range range of the argument
- * @param {"string" | "url" | "src"} urlType dependency type e.g. url() or string
- */
- constructor(request, range, urlType) {
- super(request);
- this.range = range;
- this.urlType = urlType;
- /** @type {true | undefined} */
- this.prefetch = undefined;
- /** @type {true | undefined} */
- this.preload = undefined;
- /** @type {"low" | "high" | "auto" | undefined} */
- this.fetchPriority = undefined;
- /** @type {string | undefined} */
- this.asAttribute = undefined;
- /** @type {string | undefined} */
- this.typeAttribute = undefined;
- /** @type {string | undefined} */
- this.mediaAttribute = undefined;
- }
- get type() {
- return "css url()";
- }
- get category() {
- return "url";
- }
- get referencedSourceType() {
- return ASSET_URL_TYPE;
- }
- /**
- * Creates an ignored module.
- * @param {string} context context directory
- * @returns {Module} ignored module
- */
- createIgnoredModule(context) {
- return getIgnoredRawDataUrlModule();
- }
- /**
- * Updates the hash with the data contributed by this instance.
- * @param {Hash} hash hash to be updated
- * @param {UpdateHashContext} context context
- * @returns {void}
- */
- updateHash(hash, context) {
- // The dependency template substitutes the referenced asset's hashed
- // filename into the rendered CSS at code-generation time. Folding the
- // asset module's content hash into the dependency hash ensures the
- // CSS module's hash invalidates — and the CSS chunk's contenthash
- // updates — whenever the referenced asset's content changes.
- const { chunkGraph } = context;
- const module = chunkGraph.moduleGraph.getModule(this);
- if (!module) return;
- const buildInfo = /** @type {NormalModuleBuildInfo | undefined} */ (
- module.buildInfo
- );
- if (buildInfo && buildInfo.hash) {
- hash.update(/** @type {string} */ (buildInfo.hash));
- }
- }
- /**
- * Serializes this instance into the provided serializer context.
- * @param {ObjectSerializerContext} context context
- */
- serialize(context) {
- context
- .write(this.urlType)
- .write(this.prefetch)
- .write(this.preload)
- .write(this.fetchPriority)
- .write(this.asAttribute)
- .write(this.typeAttribute)
- .write(this.mediaAttribute);
- super.serialize(context);
- }
- /**
- * Restores this instance from the provided deserializer context.
- * @param {ObjectDeserializerContext} context context
- */
- deserialize(context) {
- this.urlType = context.read();
- const c1 = context.rest;
- this.prefetch = c1.read();
- const c2 = c1.rest;
- this.preload = c2.read();
- const c3 = c2.rest;
- this.fetchPriority = c3.read();
- const c4 = c3.rest;
- this.asAttribute = c4.read();
- const c5 = c4.rest;
- this.typeAttribute = c5.read();
- const c6 = c5.rest;
- this.mediaAttribute = c6.read();
- super.deserialize(c6.rest);
- }
- }
- // Hoisted out of `cssEscapeString` so the patterns + replacer aren't
- // recompiled/reallocated per `url()` / `src()` reference at code-gen.
- const CSS_ESCAPE_UNQUOTED_REGEXP = /[\n\t ()'"\\]/g;
- const CSS_ESCAPE_DOUBLE_REGEXP = /[\n"\\]/g;
- const CSS_ESCAPE_SINGLE_REGEXP = /[\n'\\]/g;
- /**
- * @param {string} m matched character
- * @returns {string} the character backslash-escaped
- */
- const cssEscapeReplacer = (m) => `\\${m}`;
- /**
- * Returns string in quotes if needed.
- * @param {string} str string
- * @returns {string} string in quotes if needed
- */
- const cssEscapeString = (str) => {
- let countWhiteOrBracket = 0;
- let countQuotation = 0;
- let countApostrophe = 0;
- for (let i = 0; i < str.length; i++) {
- const cc = str.charCodeAt(i);
- switch (cc) {
- case 9: // tab
- case 10: // nl
- case 32: // space
- case 40: // (
- case 41: // )
- countWhiteOrBracket++;
- break;
- case 34:
- countQuotation++;
- break;
- case 39:
- countApostrophe++;
- break;
- }
- }
- if (countWhiteOrBracket < 2) {
- return str.replace(CSS_ESCAPE_UNQUOTED_REGEXP, cssEscapeReplacer);
- } else if (countQuotation <= countApostrophe) {
- return `"${str.replace(CSS_ESCAPE_DOUBLE_REGEXP, cssEscapeReplacer)}"`;
- }
- return `'${str.replace(CSS_ESCAPE_SINGLE_REGEXP, cssEscapeReplacer)}'`;
- };
- CssUrlDependency.Template = class CssUrlDependencyTemplate extends (
- ModuleDependency.Template
- ) {
- /**
- * Applies the plugin by registering its hooks on the compiler.
- * @param {Dependency} dependency the dependency for which the template should be applied
- * @param {ReplaceSource} source the current replace source which can be modified
- * @param {DependencyTemplateContext} templateContext the context object
- * @returns {void}
- */
- apply(
- dependency,
- source,
- { type, moduleGraph, runtimeTemplate, codeGenerationResults }
- ) {
- if (type === "javascript") return;
- const dep = /** @type {CssUrlDependency} */ (dependency);
- const module = /** @type {Module} */ (moduleGraph.getModule(dep));
- /** @type {string | undefined} */
- let newValue;
- switch (dep.urlType) {
- case "string":
- newValue = cssEscapeString(
- this.assetUrl({
- module,
- codeGenerationResults
- })
- );
- break;
- case "url":
- newValue = `url(${cssEscapeString(
- this.assetUrl({
- module,
- codeGenerationResults
- })
- )})`;
- break;
- case "src":
- newValue = `src(${cssEscapeString(
- this.assetUrl({
- module,
- codeGenerationResults
- })
- )})`;
- break;
- }
- source.replace(
- dep.range[0],
- dep.range[1] - 1,
- /** @type {string} */ (newValue)
- );
- }
- /**
- * Returns the url of the asset.
- * @param {object} options options object
- * @param {Module} options.module the module
- * @param {RuntimeSpec=} options.runtime runtime
- * @param {CodeGenerationResults} options.codeGenerationResults the code generation results
- * @returns {string} the url of the asset
- */
- assetUrl({ runtime, module, codeGenerationResults }) {
- if (!module) {
- return "data:,";
- }
- const codeGen = codeGenerationResults.get(module, runtime);
- const data = codeGen.data;
- if (!data) return "data:,";
- const url = data.get("url");
- if (!url || !url[ASSET_URL_TYPE]) return "data:,";
- return url[ASSET_URL_TYPE];
- }
- };
- makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency");
- module.exports = CssUrlDependency;
|