UNPKG

vue-svg-inline-loader-corejs3

Version:

Webpack loader used for inline replacement of SVG images with actual content of SVG files in Vue projects.

2 lines (1 loc) 15.1 kB
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");require("core-js/modules/es.symbol");require("core-js/modules/es.symbol.description");require("core-js/modules/es.symbol.iterator");require("core-js/modules/es.array.concat");require("core-js/modules/es.array.for-each");require("core-js/modules/es.array.from");require("core-js/modules/es.array.includes");require("core-js/modules/es.array.is-array");require("core-js/modules/es.array.iterator");require("core-js/modules/es.array.join");require("core-js/modules/es.array.map");require("core-js/modules/es.array.slice");require("core-js/modules/es.date.to-string");require("core-js/modules/es.function.name");require("core-js/modules/es.map");require("core-js/modules/es.object.freeze");require("core-js/modules/es.object.get-own-property-names");require("core-js/modules/es.object.to-string");require("core-js/modules/es.promise");require("core-js/modules/es.regexp.constructor");require("core-js/modules/es.regexp.exec");require("core-js/modules/es.regexp.to-string");require("core-js/modules/es.set");require("core-js/modules/es.string.iterator");require("core-js/modules/es.string.match");require("core-js/modules/es.string.replace");require("core-js/modules/es.string.trim");require("core-js/modules/web.dom-collections.for-each");require("core-js/modules/web.dom-collections.iterator");var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));require("regenerator-runtime/runtime");var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));function _createForOfIteratorHelper(o){if(typeof Symbol==="undefined"||o[Symbol.iterator]==null){if(Array.isArray(o)||(o=_unsupportedIterableToArray(o))){var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var it,normalCompletion=true,didErr=false,err;return{s:function s(){it=o[Symbol.iterator]()},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(n);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i]}return arr2}var path=require("path");var crypto=require("crypto");var _require=require("fs"),readFileSync=_require.readFileSync;var _require2=require("loader-utils"),getOptions=_require2.getOptions;var validateOptions=require("schema-utils");var SVGO=require("svgo");var DEFAULT_OPTIONS=freeze({inline:{keyword:"svg-inline",strict:true},sprite:{keyword:"svg-sprite",strict:true},addTitle:false,addAttributes:{role:"presentation",focusable:false,tabindex:-1},dataAttributes:[],removeAttributes:["alt","src"],transformImageAttributesToVueDirectives:true,md5:true,xhtml:false,svgo:{plugins:[{removeViewBox:false}]},verbose:false});var DEFAULT_OPTIONS_SCHEMA=freeze({type:"object",properties:{inline:{type:"object",properties:{keyword:{type:"string"},strict:{type:"boolean"}},additionalProperties:false},sprite:{type:"object",properties:{keyword:{type:"string"},strict:{type:"boolean"}},additionalProperties:false},addTitle:{type:"boolean"},addAttributes:{type:"object"},dataAttributes:{type:"array"},removeAttributes:{type:"array"},transformImageAttributesToVueDirectives:{type:"boolean"},md5:{type:"boolean"},xhtml:{type:"boolean"},svgo:{oneOf:[{type:"object",properties:{plugins:{type:"array"}},additionalProperties:false},{type:"boolean"},{"enum":[null]}]},verbose:{type:"boolean"}},additionalProperties:false});var PATTERN_VUE_SFC_HTML=/^\s*<template(?:\s+[^>]*lang[\s="']+html["'][^>]*)?>\s*/i;var PATTERN_BEFORE_ROOT_CLOSE_TAG=/(<template[^>]*>[\s\S]+)(\s*<\/[^>]+>[\s\S]*<\/template>)/i;var PATTERN_IMAGE_SRC_SVG=/(["']|#|`{3})?<img\s+[^>]*src[\s="']+([^"']+\.svg)(?:[?#][^"']*)?["'][^>]*\/?>(["']|#|`{3})?/gi;var PATTERN_SVG_CONTENT=/<svg(\s+[^>]+)?>([\s\S]+)<\/svg>/i;var PATTERN_SVG_TITLE=/<svg[^>]*>[\s\S]*(<title>[\s\S]*<\/title>)[\s\S]*<\/svg>/i;var PATTERN_SVG_TAG=/^<svg[^>]*/i;var PATTERN_USE_TAG=/<use[^>]*/i;var PATTERN_ATTRIBUTES=/\s*([:@]?[^\s=]+)[\s=]+(?:"([^"]*)"|'([^']*)')?\s*/g;var PATTERN_ATTRIBUTE_NAME=/^[:@]?[a-z](?:[a-z0-9-:.]*[a-z0-9])?$/i;var PATTERN_ATTRIBUTE_NAME_VUE=/^([:@]|v-).+$/i;var PATTERN_TAG=/^<|>$/;var PATTERN_DEPRECATED_OPTION=/^(inline|sprite)(keyword|strict)$/i;module.exports=function(content){var _this=this;this.cacheable&&this.cacheable();var callback=this.async();var loaderOptions=getOptions(this)||{};var loaderOptionsPropNames=Object.getOwnPropertyNames(loaderOptions);var _iterator=_createForOfIteratorHelper(loaderOptionsPropNames),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var name=_step.value;if(PATTERN_DEPRECATED_OPTION.test(name)){var value=loaderOptions[name];var matches=name.toLowerCase().match(PATTERN_DEPRECATED_OPTION);merge(loaderOptions,{arrayConcat:false,arrayUnique:false,overwrite:false,skipUndefined:true},(0,_defineProperty2["default"])({},matches[1],(0,_defineProperty2["default"])({},matches[2],value)));delete loaderOptions[name]}}}catch(err){_iterator.e(err)}finally{_iterator.f()}var options=merge({},{arrayConcat:false,arrayUnique:false,overwrite:true,skipUndefined:true},DEFAULT_OPTIONS,loaderOptions);["dataAttributes","removeAttributes"].forEach(function(option){options[option]=options[option].map(function(attribute){return attribute.toLowerCase()});options[option].forEach(function(attribute){[":","@"].forEach(function(shorthand){options[option].push(shorthand+attribute)})})});validateOptions(DEFAULT_OPTIONS_SCHEMA,options,"vue-svg-inline-loader");options._svgo=!!options.svgo;options._sprites=!!(path.extname(this.resourcePath).toLowerCase()===".vue"&&PATTERN_VUE_SFC_HTML.test(content));for(var _i=0,_arr=[options.inline.keyword,options.sprite.keyword];_i<_arr.length;_i++){var keyword=_arr[_i];if(!PATTERN_ATTRIBUTE_NAME.test(keyword)){throw new Error("Keyword ".concat(keyword," is not valid."))}}var PATTERN_INLINE_KEYWORD=new RegExp("\\s+(?:data-)?(?:v-)?".concat(options.inline.keyword,"\\s+"),"i");var PATTERN_SPRITE_KEYWORD=new RegExp("\\s+(?:data-)?(?:v-)?".concat(options.sprite.keyword,"\\s+"),"i");var svgo=options._svgo&&new SVGO(options.svgo===true?DEFAULT_OPTIONS.svgo:options.svgo);var symbols=new Set;replace(content,PATTERN_IMAGE_SRC_SVG,function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(image,leftQuote,source,rightQuote){var quotesMatch,filePath,file,attributes,attribute,alternativeTitle,_attribute,_iterator2,_step2,_attribute2,_iterator3,_step3,_attribute3;return _regenerator["default"].wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:quotesMatch=leftQuote&&rightQuote&&leftQuote===rightQuote;if(!(quotesMatch&&["#","```"].includes(leftQuote))){_context.next=3;break}return _context.abrupt("return",image.replace(new RegExp("^".concat(leftQuote)),"").replace(new RegExp("".concat(rightQuote,"$")),""));case 3:if(!(options.inline.strict&&!PATTERN_INLINE_KEYWORD.test(image))){_context.next=5;break}return _context.abrupt("return",image);case 5:_context.next=7;return new Promise(function(resolve,reject){_this.resolve(_this.context,source,function(error,resolvedPath){if(error){reject(error)}resolve(resolvedPath)})});case 7:filePath=_context.sent;file={path:filePath};_this.addDependency(path.normalize(file.path));_context.prev=10;file.content=readFileSync(file.path,{encoding:"utf-8"}).trim();_context.next=17;break;case 14:_context.prev=14;_context.t0=_context["catch"](10);throw new Error("File ".concat(file.path," does not exist."));case 17:if(options.verbose){console.log("before replace:\t%s",image)}if(options.verbose){console.log("before replace:\t%s",file.content)}if(PATTERN_SVG_CONTENT.test(file.content)){_context.next=21;break}throw new Error("File ".concat(file.path," is empty."));case 21:_context.prev=21;_context.t2=options._svgo;if(!_context.t2){_context.next=27;break}_context.next=26;return svgo.optimize(file.content,{path:file.path});case 26:_context.t2=_context.sent.data;case 27:_context.t1=_context.t2;if(_context.t1){_context.next=30;break}_context.t1=file.content;case 30:file.content=_context.t1;_context.next=36;break;case 33:_context.prev=33;_context.t3=_context["catch"](21);throw new Error("SVGO for ".concat(file.path," failed."));case 36:attributes=new Map;PATTERN_ATTRIBUTES.lastIndex=0;while(attribute=PATTERN_ATTRIBUTES.exec(image)){if(attribute.index===PATTERN_ATTRIBUTES.lastIndex){PATTERN_ATTRIBUTES.lastIndex++}if(attribute[1]&&!PATTERN_TAG.test(attribute[1])&&PATTERN_ATTRIBUTE_NAME.test(attribute[1])){attributes.set(attribute[1].toLowerCase(),attribute[2]||attribute[3]||"")}}if(!options.sprite.strict||PATTERN_SPRITE_KEYWORD.test(image)){if(options._sprites&&!PATTERN_USE_TAG.test(file.content)){file.content=file.content.replace(PATTERN_SVG_CONTENT,function(svg,attributes,symbol){var developmentId=[_this.resourcePath,file.path].map(function(path){return path.replace(_this.rootContext,"")}).join(":");var id=[options.sprite.keyword,options.md5?crypto.createHash("md5").update(developmentId).digest("hex"):developmentId].join(options.md5?"-":":");symbols.add("<symbol id=\"".concat(id,"\"").concat(attributes,">").concat(symbol,"</symbol>"));return"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><use xlink:href=\"#".concat(id,"\" href=\"#").concat(id,"\"></use></svg>")})}}else if(options.addTitle&&attributes.has("alt")){alternativeTitle=attributes.get("alt");file.content=PATTERN_SVG_TITLE.test(file.content)?file.content.replace(PATTERN_SVG_TITLE,function(svg,title){return svg.replace(title,"<title>".concat(alternativeTitle,"</title>"))}):file.content.replace(PATTERN_SVG_CONTENT,function(svg,attributes,symbol){return svg.replace(symbol,"<title>".concat(alternativeTitle,"</title>").concat(symbol))})}for(_attribute in options.addAttributes){if(!attributes.has(_attribute)){attributes.set(_attribute,options.addAttributes[_attribute].toString())}}_iterator2=_createForOfIteratorHelper(options.dataAttributes);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){_attribute2=_step2.value;if(attributes.has(_attribute2)){attributes.set("data-".concat(_attribute2),attributes.get(_attribute2));attributes["delete"](_attribute2)}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}_iterator3=_createForOfIteratorHelper(options.removeAttributes);try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){_attribute3=_step3.value;attributes["delete"](_attribute3)}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}if(quotesMatch&&["\"","'"].includes(leftQuote)){leftQuote=rightQuote="`"}file.content=(leftQuote||"")+(attributes.size?file.content.replace(PATTERN_SVG_TAG,"$& "+(0,_toConsumableArray2["default"])(attributes.keys()).map(function(attribute){var name=attribute;var value=attributes.get(attribute);value=(value?value:options.xhtml?name:"").replace(/"/g,"'");if(options.transformImageAttributesToVueDirectives&&!PATTERN_ATTRIBUTE_NAME_VUE.test(name)){name="v-bind:".concat(name);value="'".concat(value,"'")}return"".concat(name,"=\"").concat(value,"\"")}).join(" ")):file.content)+(rightQuote||"");if(options.verbose){console.log("after replace:\t%s",file.content);console.log()}return _context.abrupt("return",file.content);case 49:case"end":return _context.stop();}}},_callee,null,[[10,14],[21,33]])}));return function(_x,_x2,_x3,_x4){return _ref.apply(this,arguments)}}()).then(function(content){return callback(null,options._sprites&&symbols.size?content.replace(PATTERN_BEFORE_ROOT_CLOSE_TAG,"$1<svg xmlns=\"http://www.w3.org/2000/svg\" style=\"display: none !important;\">".concat((0,_toConsumableArray2["default"])(symbols).join(""),"</svg>$2")):content)})["catch"](function(error){return callback(error)})};function replace(_x5,_x6,_x7){return _replace.apply(this,arguments)}function _replace(){_replace=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(string,regex,callback){var promises,data;return _regenerator["default"].wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:regex.lastIndex=0;promises=[];string.replace(regex,function(match){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2]}var promise=callback.apply(void 0,[match].concat(args));promises.push(promise)});_context2.next=5;return Promise.all(promises);case 5:data=_context2.sent;return _context2.abrupt("return",data.length?string.replace(regex,function(){return data.shift()}):string);case 7:case"end":return _context2.stop();}}},_callee2)}));return _replace.apply(this,arguments)}function freeze(object){var propNames=Object.getOwnPropertyNames(object);var _iterator4=_createForOfIteratorHelper(propNames),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var name=_step4.value;var value=object[name];object[name]=value&&(0,_typeof2["default"])(value)==="object"?freeze(value):value}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}return Object.freeze(object)}function merge(object,options){for(var _len=arguments.length,sources=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){sources[_key-2]=arguments[_key]}for(var _i2=0,_sources=sources;_i2<_sources.length;_i2++){var source=_sources[_i2];var propNames=Object.getOwnPropertyNames(source);var _iterator5=_createForOfIteratorHelper(propNames),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var name=_step5.value;var value=source[name];if(options&&options.skipUndefined&&value===undefined){continue}if(value===object[name]){continue}if(value&&(0,_typeof2["default"])(value)==="object"){if(options&&options.arrayConcat&&Array.isArray(object[name])&&Array.isArray(value)){object[name]=object[name].concat(value);if(options&&options.arrayUnique){object[name]=Array.from(new Set(object[name]))}}else if(Array.isArray(value)){object[name]=options&&options.overwrite||object[name]===undefined?value:object[name]}else{object[name]=merge(object[name]||{},options,value)}}else{object[name]=options&&options.overwrite||object[name]===undefined?value:object[name]}}}catch(err){_iterator5.e(err)}finally{_iterator5.f()}}return object}