weboptimizer 3.0.29 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ejsLoader.js CHANGED
@@ -16,29 +16,23 @@
16
16
  endregion
17
17
  */
18
18
  // region imports
19
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
20
- Object.defineProperty(exports, "__esModule", {
21
- value: true
22
- });
23
- exports.log = exports.loader = exports["default"] = void 0;
24
- var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
25
- var _core = require("@babel/core");
26
- var _babelPresetMinify = _interopRequireDefault(require("babel-preset-minify"));
27
- var _clientnode = require("clientnode");
28
- var _ejs = _interopRequireDefault(require("ejs"));
29
- var _fs = require("fs");
30
- var _htmlMinifier = require("html-minifier");
31
- var _path = require("path");
32
- var _configurator = _interopRequireDefault(require("./configurator"));
33
- var _helper = require("./helper");
34
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
35
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
19
+ import { FileResult, transformSync as babelTransformSync } from '@babel/core';
20
+ import babelMinifyPreset from 'babel-preset-minify';
21
+ import { convertSubstringInPlainObject, copy, currentRequire, evaluate, EvaluationResult, Encoding, extend, Logger, Mapping, RecursivePartial, UTILITY_SCOPE } from 'clientnode';
22
+ import ejs, { Options, TemplateFunction as EJSTemplateFunction } from 'ejs';
23
+ import { readFileSync } from 'fs';
24
+ import { minify as minifyHTML } from 'html-minifier';
25
+ import { extname } from 'path';
26
+ import { LoaderContext } from 'webpack';
27
+ import getConfiguration from './configurator';
28
+ import { determineModuleFilePath } from './helper';
29
+ import { Extensions, Replacements, ResolvedConfiguration } from './type';
36
30
  // endregion
37
31
  // region types
38
32
 
39
33
  // endregion
40
- var configuration = (0, _configurator["default"])();
41
- var log = exports.log = new _clientnode.Logger({
34
+ const configuration = getConfiguration();
35
+ export const log = new Logger({
42
36
  name: 'weboptimizer.ejs-loader'
43
37
  });
44
38
  /**
@@ -46,11 +40,8 @@ var log = exports.log = new _clientnode.Logger({
46
40
  * @param source - Input string to transform.
47
41
  * @returns Transformed string.
48
42
  */
49
- var loader = exports.loader = function loader(source) {
50
- var _ref,
51
- _this = this,
52
- _givenOptions$compile;
53
- var givenOptions = (0, _clientnode.convertSubstringInPlainObject)((0, _clientnode.extend)(true, {
43
+ export const loader = function (source) {
44
+ const givenOptions = convertSubstringInPlainObject(extend(true, {
54
45
  compiler: {
55
46
  localsName: '_'
56
47
  },
@@ -71,159 +62,210 @@ var loader = exports.loader = function loader(source) {
71
62
  aliases: {},
72
63
  replacements: {}
73
64
  }
74
- }, this.getOptions ? this.getOptions() : (_ref = this.query) !== null && _ref !== void 0 ? _ref : {}), /#%%%#/g, '!');
75
- var _compile = function compile(template) {
76
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : givenOptions.compiler;
77
- var compileSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
78
- return function () {
79
- var locals = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
80
- options = _objectSpread({
81
- filename: template
82
- }, options);
83
- var givenLocals = [].concat(locals);
84
- var require = function require(request) {
85
- var _givenOptions$module, _givenOptions$module2, _givenOptions$extensi;
86
- var nestedLocals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
87
- var template = request.replace(/^(.+)\?[^?]+$/, '$1');
88
- var queryMatch = /^[^?]+\?(.+)$/.exec(request);
89
- if (queryMatch) {
90
- var evaluated = (0, _clientnode.evaluate)(queryMatch[1], {
91
- compile: _compile,
92
- locals: locals,
93
- request: request,
94
- source: source,
95
- template: template
96
- });
97
- if (evaluated.error) log.warn('Error occurred during processing given query:', evaluated.error);else if (evaluated.result) (0, _clientnode.extend)(true, nestedLocals, evaluated.result);
98
- }
99
- var nestedOptions = (0, _clientnode.copy)(options);
100
- delete nestedOptions.client;
101
- nestedOptions = (0, _clientnode.extend)(true, {
102
- encoding: configuration.encoding
103
- }, nestedOptions, nestedLocals.options || {}, options !== null && options !== void 0 ? options : {});
104
- if (nestedOptions.isString) return _compile(template, nestedOptions)(nestedLocals);
105
- var templateFilePath = (0, _helper.determineModuleFilePath)(template, (_givenOptions$module = givenOptions.module) === null || _givenOptions$module === void 0 ? void 0 : _givenOptions$module.aliases, (_givenOptions$module2 = givenOptions.module) === null || _givenOptions$module2 === void 0 ? void 0 : _givenOptions$module2.replacements, {
106
- file: ((_givenOptions$extensi = givenOptions.extensions) === null || _givenOptions$extensi === void 0 ? void 0 : _givenOptions$extensi.file.internal) || []
107
- }, givenOptions.context, configuration.path.source.asset.base, configuration.path.ignore, configuration.module.directoryNames, configuration["package"].main.fileNames, configuration["package"].main.propertyNames, configuration["package"].aliasPropertyNames, configuration.encoding);
108
- if (templateFilePath) {
109
- if (_this.addDependency) _this.addDependency(templateFilePath);
110
- /*
111
- NOTE: If there aren't any locals options or variables and
112
- file doesn't seem to be an ejs template we simply load
113
- included file content.
114
- */
115
- if (queryMatch || templateFilePath.endsWith('.ejs')) return _compile(templateFilePath, nestedOptions)(nestedLocals);
116
- return (0, _fs.readFileSync)(templateFilePath, {
117
- encoding: nestedOptions.encoding
118
- });
119
- }
120
- throw new Error("Given template file \"".concat(template, "\" couldn't be resolved."));
121
- };
122
- var compressHTML = function compressHTML(content) {
123
- var _givenOptions$compres;
124
- return (0, _htmlMinifier.minify)(content, (0, _clientnode.extend)(true, {
125
- caseSensitive: true,
126
- collapseInlineTagWhitespace: true,
127
- collapseWhitespace: true,
128
- conservativeCollapse: true,
129
- minifyCSS: true,
130
- minifyJS: true,
131
- processScripts: ['text/ng-template', 'text/x-handlebars-template'],
132
- removeAttributeQuotes: true,
133
- removeComments: true,
134
- removeRedundantAttributes: true,
135
- removeScriptTypeAttributes: true,
136
- removeStyleLinkTypeAttributes: true,
137
- sortAttributes: true,
138
- sortClassName: true,
139
- /*
140
- NOTE: Avoids whitespace around placeholder in
141
- tags.
142
- */
143
- trimCustomFragments: true,
144
- useShortDoctype: true
145
- }, ((_givenOptions$compres = givenOptions.compress) === null || _givenOptions$compres === void 0 ? void 0 : _givenOptions$compres.html) || {}));
146
- };
147
- var result = template;
148
- var isString = Boolean(options.isString);
149
- delete options.isString;
150
-
151
- // NOTE: Needed to have standalone useable js code afterwards.
152
- if (compileSteps % 2) options.client = true;
153
- var stepLocals;
154
- var scope = {};
155
- for (var step = 1; step <= compileSteps; step += 1) {
156
- // On every odd compile step we have to determine the environment.
157
- if (step % 2) {
158
- // region determine scope
159
- var localsIndex = Math.round(step / 2) - 1;
160
- stepLocals = localsIndex < givenLocals.length ? givenLocals[localsIndex] : {};
161
- scope = {};
162
- if (step < 3 && 1 < compileSteps) scope = _objectSpread(_objectSpread({}, _clientnode.UTILITY_SCOPE), {}, {
163
- configuration: configuration,
164
- include: require,
165
- require: require
166
- }, Array.isArray(stepLocals) ? {} : stepLocals);else if (!Array.isArray(stepLocals)) scope = stepLocals;
167
- // endregion
168
- }
169
- if (typeof result === 'string') {
170
- var filePath = isString ? options.filename : result;
171
- if (filePath && (0, _path.extname)(filePath) === '.js' && _clientnode.currentRequire) result = (0, _clientnode.currentRequire)(filePath);else {
172
- var _givenOptions$compres2;
173
- if (!isString) {
174
- var encoding = configuration.encoding;
175
- if (typeof options.encoding === 'string') encoding = options.encoding;
176
- result = (0, _fs.readFileSync)(result, {
177
- encoding: encoding
178
- });
179
- }
180
- if (step === compileSteps && (_givenOptions$compres2 = givenOptions.compress) !== null && _givenOptions$compres2 !== void 0 && _givenOptions$compres2.html) result = compressHTML(result);
181
- if (step === compileSteps && compileSteps % 2) {
182
- /*
183
- We have to use the templace class directly to get
184
- the generated source code.
185
- */
186
- var templateInstance = new _ejs["default"].Template(template, options);
187
- templateInstance.compile();
188
- var compiledSourceCode = templateInstance.source;
189
- result = "\n module.exports = function(\n ".concat(options.localsName, "\n ) {\n var escapeFn = function(value) {\n return String(value)\n .replace(\n /[&<>\"']/g,\n function(char) {\n return {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": \"&#39;\"\n }[char]\n }\n )\n };\n var include = function() {\n throw new Error('Include not implemented.')\n };\n var rethrow = function rethrow(\n err, str, flnm, lineno, esc\n ) {\n var lines = str.split('\\n');\n var start = Math.max(lineno - 3, 0);\n var end = Math.min(\n lines.length, lineno + 3\n );\n var filename = esc(flnm);\n // Error context\n var context = lines\n .slice(start, end)\n .map(function (line, i) {\n var curr = i + start + 1;\n return (\n curr == lineno ?\n ' >> ' :\n ' '\n ) +\n curr +\n '| ' +\n line;\n })\n .join('\\n');\n // Alter exception message\n err.path = filename;\n err.message =\n (filename || 'ejs') +\n ':' +\n lineno +\n '\\n' +\n context +\n '\\n\\n' +\n err.message;\n throw err;\n };\n ").concat(compiledSourceCode, "\n };\n ").trim();
190
- } else result = _ejs["default"].compile(result, options);
191
- }
192
- } else {
193
- var _givenOptions$compres3;
194
- result = result(scope);
195
- if ((_givenOptions$compres3 = givenOptions.compress) !== null && _givenOptions$compres3 !== void 0 && _givenOptions$compres3.html) result = compressHTML(result);
196
- }
65
+ }, this.getOptions ? this.getOptions() : this.query ?? {}), /#%%%#/g, '!');
66
+ const compile = (template, options = givenOptions.compiler, compileSteps = 2) => (locals = {}) => {
67
+ options = {
68
+ filename: template,
69
+ ...options
70
+ };
71
+ const givenLocals = [].concat(locals);
72
+ const require = (request, nestedLocals = {}) => {
73
+ const template = request.replace(/^(.+)\?[^?]+$/, '$1');
74
+ const queryMatch = /^[^?]+\?(.+)$/.exec(request);
75
+ if (queryMatch) {
76
+ const evaluated = evaluate(queryMatch[1], {
77
+ compile,
78
+ locals,
79
+ request,
80
+ source,
81
+ template
82
+ });
83
+ if (evaluated.error) log.warn('Error occurred during processing given query:', evaluated.error);else if (evaluated.result) extend(true, nestedLocals, evaluated.result);
197
84
  }
198
- if (compileSteps % 2) {
199
- var _givenOptions$compres4, _givenOptions$compres5, _givenOptions$compres6, _givenOptions$compres7;
200
- var processed = (0, _core.transformSync)(result, {
201
- ast: false,
202
- babelrc: false,
203
- comments: !((_givenOptions$compres4 = givenOptions.compress) !== null && _givenOptions$compres4 !== void 0 && _givenOptions$compres4.javaScript),
204
- compact: Boolean((_givenOptions$compres5 = givenOptions.compress) === null || _givenOptions$compres5 === void 0 ? void 0 : _givenOptions$compres5.javaScript),
205
- filename: options.filename || 'unknown',
206
- minified: Boolean((_givenOptions$compres6 = givenOptions.compress) === null || _givenOptions$compres6 === void 0 ? void 0 : _givenOptions$compres6.javaScript),
207
- presets: (_givenOptions$compres7 = givenOptions.compress) !== null && _givenOptions$compres7 !== void 0 && _givenOptions$compres7.javaScript ? [[_babelPresetMinify["default"], givenOptions.compress.javaScript]] : [],
208
- sourceMaps: false,
209
- sourceType: 'script'
85
+ let nestedOptions = copy(options);
86
+ delete nestedOptions.client;
87
+ nestedOptions = extend(true, {
88
+ encoding: configuration.encoding
89
+ }, nestedOptions, nestedLocals.options || {}, options ?? {});
90
+ if (nestedOptions.isString) return compile(template, nestedOptions)(nestedLocals);
91
+ const templateFilePath = determineModuleFilePath(template, givenOptions.module?.aliases, givenOptions.module?.replacements, {
92
+ file: givenOptions.extensions?.file.internal || []
93
+ }, givenOptions.context, configuration.path.source.asset.base, configuration.path.ignore, configuration.module.directoryNames, configuration.package.main.fileNames, configuration.package.main.propertyNames, configuration.package.aliasPropertyNames, configuration.encoding);
94
+ if (templateFilePath) {
95
+ if (this.addDependency) this.addDependency(templateFilePath);
96
+ /*
97
+ NOTE: If there aren't any locals options or variables and
98
+ file doesn't seem to be an ejs template we simply load
99
+ included file content.
100
+ */
101
+ if (queryMatch || templateFilePath.endsWith('.ejs')) return compile(templateFilePath, nestedOptions)(nestedLocals);
102
+ return readFileSync(templateFilePath, {
103
+ encoding: nestedOptions.encoding
210
104
  });
211
- if (typeof (processed === null || processed === void 0 ? void 0 : processed.code) === 'string') result = processed.code;
212
- return "".concat(options.strict ? "'use strict';\n" : '').concat(result);
105
+ }
106
+ throw new Error(`Given template file "${template}" couldn't be resolved.`);
107
+ };
108
+ const compressHTML = content => minifyHTML(content, extend(true, {
109
+ caseSensitive: true,
110
+ collapseInlineTagWhitespace: true,
111
+ collapseWhitespace: true,
112
+ conservativeCollapse: true,
113
+ minifyCSS: true,
114
+ minifyJS: true,
115
+ processScripts: ['text/ng-template', 'text/x-handlebars-template'],
116
+ removeAttributeQuotes: true,
117
+ removeComments: true,
118
+ removeRedundantAttributes: true,
119
+ removeScriptTypeAttributes: true,
120
+ removeStyleLinkTypeAttributes: true,
121
+ sortAttributes: true,
122
+ sortClassName: true,
123
+ /*
124
+ NOTE: Avoids whitespace around placeholder in
125
+ tags.
126
+ */
127
+ trimCustomFragments: true,
128
+ useShortDoctype: true
129
+ }, givenOptions.compress?.html || {}));
130
+ let result = template;
131
+ const isString = Boolean(options.isString);
132
+ delete options.isString;
133
+
134
+ // NOTE: Needed to have standalone useable js code afterwards.
135
+ if (compileSteps % 2) options.client = true;
136
+ let stepLocals;
137
+ let scope = {};
138
+ for (let step = 1; step <= compileSteps; step += 1) {
139
+ // On every odd compile step we have to determine the environment.
140
+ if (step % 2) {
141
+ // region determine scope
142
+ const localsIndex = Math.round(step / 2) - 1;
143
+ stepLocals = localsIndex < givenLocals.length ? givenLocals[localsIndex] : {};
144
+ scope = {};
145
+ if (step < 3 && 1 < compileSteps) scope = {
146
+ ...UTILITY_SCOPE,
147
+ configuration,
148
+ include: require,
149
+ require,
150
+ ...(Array.isArray(stepLocals) ? {} : stepLocals)
151
+ };else if (!Array.isArray(stepLocals)) scope = stepLocals;
152
+ // endregion
213
153
  }
214
154
  if (typeof result === 'string') {
215
- result = result.replace(new RegExp("<script +processing-workaround *" + "(?: = *(?: \" *\"|' *') *)?>([\\s\\S]*?)</ *script *>", 'ig'), '$1').replace(new RegExp("<script +processing(-+)-workaround *" + "(?: = *(?: \" *\"|' *') *)?>([\\s\\S]*?)</ *script *>", 'ig'), '<script processing$1workaround>$2</script>');
216
- return result;
155
+ const filePath = isString ? options.filename : result;
156
+ if (filePath && extname(filePath) === '.js' && currentRequire) result = currentRequire(filePath);else {
157
+ if (!isString) {
158
+ let encoding = configuration.encoding;
159
+ if (typeof options.encoding === 'string') encoding = options.encoding;
160
+ result = readFileSync(result, {
161
+ encoding
162
+ });
163
+ }
164
+ if (step === compileSteps && givenOptions.compress?.html) result = compressHTML(result);
165
+ if (step === compileSteps && compileSteps % 2) {
166
+ /*
167
+ We have to use the templace class directly to get
168
+ the generated source code.
169
+ */
170
+ const templateInstance = new ejs.Template(template, options);
171
+ templateInstance.compile();
172
+ const compiledSourceCode = templateInstance.source;
173
+ result = `
174
+ module.exports = function(
175
+ ${options.localsName}
176
+ ) {
177
+ var escapeFn = function(value) {
178
+ return String(value)
179
+ .replace(
180
+ /[&<>"']/g,
181
+ function(char) {
182
+ return {
183
+ '&': '&amp;',
184
+ '<': '&lt;',
185
+ '>': '&gt;',
186
+ '"': '&quot;',
187
+ "'": "&#39;"
188
+ }[char]
189
+ }
190
+ )
191
+ };
192
+ var include = function() {
193
+ throw new Error('Include not implemented.')
194
+ };
195
+ var rethrow = function rethrow(
196
+ err, str, flnm, lineno, esc
197
+ ) {
198
+ var lines = str.split('\\n');
199
+ var start = Math.max(lineno - 3, 0);
200
+ var end = Math.min(
201
+ lines.length, lineno + 3
202
+ );
203
+ var filename = esc(flnm);
204
+ // Error context
205
+ var context = lines
206
+ .slice(start, end)
207
+ .map(function (line, i) {
208
+ var curr = i + start + 1;
209
+ return (
210
+ curr == lineno ?
211
+ ' >> ' :
212
+ ' '
213
+ ) +
214
+ curr +
215
+ '| ' +
216
+ line;
217
+ })
218
+ .join('\\n');
219
+ // Alter exception message
220
+ err.path = filename;
221
+ err.message =
222
+ (filename || 'ejs') +
223
+ ':' +
224
+ lineno +
225
+ '\\n' +
226
+ context +
227
+ '\\n\\n' +
228
+ err.message;
229
+ throw err;
230
+ };
231
+ ${compiledSourceCode}
232
+ };
233
+ `.trim();
234
+ } else result = ejs.compile(result, options);
235
+ }
236
+ } else {
237
+ result = result(scope);
238
+ if (givenOptions.compress?.html) result = compressHTML(result);
217
239
  }
218
- return '';
219
- };
240
+ }
241
+ if (compileSteps % 2) {
242
+ const processed = babelTransformSync(result, {
243
+ ast: false,
244
+ babelrc: false,
245
+ comments: !givenOptions.compress?.javaScript,
246
+ compact: Boolean(givenOptions.compress?.javaScript),
247
+ filename: options.filename || 'unknown',
248
+ minified: Boolean(givenOptions.compress?.javaScript),
249
+ presets: givenOptions.compress?.javaScript ? [[babelMinifyPreset, givenOptions.compress.javaScript]] : [],
250
+ sourceMaps: false,
251
+ sourceType: 'script'
252
+ });
253
+ if (typeof processed?.code === 'string') result = processed.code;
254
+ return `${options.strict ? `'use strict';\n` : ''}${result}`;
255
+ }
256
+ if (typeof result === 'string') {
257
+ result = result.replace(new RegExp(`<script +processing-workaround *` + `(?: = *(?: " *"|' *') *)?>([\\s\\S]*?)</ *script *>`, 'ig'), '$1').replace(new RegExp(`<script +processing(-+)-workaround *` + `(?: = *(?: " *"|' *') *)?>([\\s\\S]*?)</ *script *>`, 'ig'), '<script processing$1workaround>$2</script>');
258
+ return result;
259
+ }
260
+ return '';
220
261
  };
221
- return _compile(source, _objectSpread(_objectSpread({}, givenOptions.compiler), {}, {
222
- client: Boolean(((_givenOptions$compile = givenOptions.compileSteps) !== null && _givenOptions$compile !== void 0 ? _givenOptions$compile : 2) % 2),
262
+ return compile(source, {
263
+ ...givenOptions.compiler,
264
+ client: Boolean((givenOptions.compileSteps ?? 2) % 2),
223
265
  compileDebug: givenOptions.debug,
224
266
  debug: givenOptions.debug,
225
267
  filename: this.resourcePath || 'unknown',
226
268
  isString: true
227
- }), givenOptions.compileSteps)(givenOptions.locals || {});
269
+ }, givenOptions.compileSteps)(givenOptions.locals || {});
228
270
  };
229
- var _default = exports["default"] = loader;
271
+ export default loader;
package/eslint.config.mjs CHANGED
@@ -1,3 +1,7 @@
1
+ import "core-js/modules/es.iterator.constructor.js";
2
+ import "core-js/modules/es.iterator.filter.js";
3
+ import "core-js/modules/es.iterator.reduce.js";
4
+ import "core-js/modules/es.json.parse.js";
1
5
  import { defineConfig } from 'eslint/config';
2
6
  import google from 'eslint-config-google';
3
7
  import jsdoc from 'eslint-plugin-jsdoc';