@zohodesk/client_build_tool 0.0.6-exp.9 → 0.0.7-exp.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.
Files changed (87) hide show
  1. package/index.html +600 -0
  2. package/lib/schemas/defaultConfigValues.js +23 -2
  3. package/lib/schemas/readOptions.js +33 -0
  4. package/lib/shared/babel/babelWebConfig.js +4 -1
  5. package/lib/shared/babel/runBabelForTsFile.js +30 -0
  6. package/lib/shared/bundler/webpack/common/decidePublicPath.js +5 -0
  7. package/lib/shared/bundler/webpack/common/nameTemplates.js +13 -9
  8. package/lib/shared/bundler/webpack/custom_plugins/CdnChangePlugin/index.js +12 -4
  9. package/lib/shared/bundler/webpack/custom_plugins/CdnChangePlugin/webpackCustomJsUrlLoader.js +19 -238
  10. package/lib/shared/bundler/webpack/custom_plugins/CustomScriptLoadingPlugin.js +109 -0
  11. package/lib/shared/bundler/webpack/custom_plugins/I18nSplitPlugin/getI18nLoadingRuntimeModule.js +1 -1
  12. package/lib/shared/bundler/webpack/custom_plugins/InitialHtmlPlugin.js +4 -0
  13. package/lib/shared/bundler/webpack/custom_plugins/ManifestJsonPlugin/addFilesNamesToManifestJson.js +8 -2
  14. package/lib/shared/bundler/webpack/custom_plugins/ManifestJsonPlugin/createInitialEntries.js +7 -1
  15. package/lib/shared/bundler/webpack/custom_plugins/ManifestJsonPlugin/createManifestJson.js +1 -1
  16. package/lib/shared/bundler/webpack/custom_plugins/ResourceHintsPlugin.js +1 -0
  17. package/lib/shared/bundler/webpack/custom_plugins/ServiceWorkerPlugin.js +5 -1
  18. package/lib/shared/bundler/webpack/custom_plugins/ServiceWorkerPluginUtils.js +13 -0
  19. package/lib/shared/bundler/webpack/custom_plugins/SourceMapPlugin/index.js +20 -2
  20. package/lib/shared/bundler/webpack/custom_plugins/TPHashMappingPlugin/index.js +1 -1
  21. package/lib/shared/bundler/webpack/custom_plugins/getInitialAssetsFuncTemplate.js +4 -4
  22. package/lib/shared/bundler/webpack/custom_plugins/getInitialI18nAssetsArrayStr.js +1 -1
  23. package/lib/shared/bundler/webpack/devtoolConfig.js +4 -1
  24. package/lib/shared/bundler/webpack/loaderConfigs/configsAssetsLoaders.js +1 -1
  25. package/lib/shared/bundler/webpack/loaderConfigs/cssClassNameGenerate.js +6 -1
  26. package/lib/shared/bundler/webpack/optimizationConfig.js +15 -2
  27. package/lib/shared/bundler/webpack/pluginConfigs/configCSSMinifierPlugin.js +5 -1
  28. package/lib/shared/bundler/webpack/pluginConfigs/configCustomScriptLoadingStrategyPlugin.js +76 -0
  29. package/lib/shared/bundler/webpack/pluginConfigs/configI18nSplitPlugin.js +1 -1
  30. package/lib/shared/bundler/webpack/pluginConfigs/configManifestJsonPlugin.js +25 -13
  31. package/lib/shared/bundler/webpack/pluginConfigs/configMiniCSSExtractPlugin.js +2 -1
  32. package/lib/shared/bundler/webpack/plugins.js +3 -1
  33. package/lib/shared/bundler/webpack/resolvers.js +2 -1
  34. package/lib/shared/bundler/webpack/tsLoaders.js +17 -0
  35. package/lib/shared/bundler/webpack/utils/index.js +6 -1
  36. package/lib/shared/bundler/webpack/webpackConfig.js +3 -1
  37. package/lib/shared/fileUtils/watchRun.js +13 -1
  38. package/lib/shared/postcss/custom_postcss_plugins/ValueReplacer.js +1 -1
  39. package/lib/shared/postcss/custom_postcss_plugins/VariableModificationPlugin/index.js +4 -0
  40. package/lib/shared/server/getServerURL.js +9 -2
  41. package/npm-shrinkwrap.json +412 -7328
  42. package/package.json +5 -2
  43. package/coverage/addFilesNamesToManifestJson.js.html +0 -148
  44. package/coverage/base.css +0 -224
  45. package/coverage/block-navigation.js +0 -87
  46. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/addFilesNamesToManifestJson.js.html +0 -148
  47. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/createInitialEntries.js.html +0 -136
  48. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/createManifestJson.js.html +0 -181
  49. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/findInitialFileNames.js.html +0 -133
  50. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/index.html +0 -146
  51. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/index.js.html +0 -199
  52. package/coverage/bundler/webpack/custom_plugins/AddManifestJson/removeHashFromFileName.js.html +0 -127
  53. package/coverage/bundler/webpack/custom_plugins/VariableConversionCollector/ErrorHandler.js.html +0 -346
  54. package/coverage/bundler/webpack/custom_plugins/VariableConversionCollector/index.html +0 -116
  55. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/constants.js.html +0 -94
  56. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/handleIgnores.js.html +0 -259
  57. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/index.html +0 -236
  58. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/index.js.html +0 -442
  59. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/insertBefore.js.html +0 -154
  60. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/isPreviouslyProcessed.js.html +0 -142
  61. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/replaceUtils.js.html +0 -127
  62. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/separateHoveredSelectorAndNormalSelector.js.html +0 -139
  63. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/specialCases.js.html +0 -184
  64. package/coverage/bundler/webpack/custom_postcss_plugins/HoverActivePlugin/typeCheckUtils.js.html +0 -193
  65. package/coverage/bundler/webpack/custom_postcss_plugins/SelectorReplace.js.html +0 -292
  66. package/coverage/bundler/webpack/custom_postcss_plugins/ValueReplacer.js.html +0 -223
  67. package/coverage/bundler/webpack/custom_postcss_plugins/VariableModificationPlugin/index.html +0 -116
  68. package/coverage/bundler/webpack/custom_postcss_plugins/VariableModificationPlugin/index.js.html +0 -1126
  69. package/coverage/bundler/webpack/custom_postcss_plugins/index.html +0 -131
  70. package/coverage/bundler/webpack/loaderConfigs/getSpecificPostCssPlugin.js.html +0 -247
  71. package/coverage/bundler/webpack/loaderConfigs/index.html +0 -116
  72. package/coverage/coverage-final.json +0 -4
  73. package/coverage/coverage-summary.json +0 -5
  74. package/coverage/createInitialEntries.js.html +0 -136
  75. package/coverage/dummy.js.html +0 -238
  76. package/coverage/favicon.png +0 -0
  77. package/coverage/index.html +0 -146
  78. package/coverage/index.js.html +0 -169
  79. package/coverage/isObject.js.html +0 -94
  80. package/coverage/isValid.js.html +0 -106
  81. package/coverage/prettify.css +0 -1
  82. package/coverage/prettify.js +0 -2
  83. package/coverage/removeHashFromFileName.js.html +0 -127
  84. package/coverage/sort-arrow-sprite.png +0 -0
  85. package/coverage/sorter.js +0 -196
  86. package/result.json +0 -1
  87. package/unittest/index.html +0 -35
@@ -54,6 +54,10 @@ var _default = {
54
54
  cli: 'print_progress'
55
55
  },
56
56
  server: {
57
+ k8s: {
58
+ value: false,
59
+ cli: 'k8s'
60
+ },
57
61
  httpsCerts: {
58
62
  value: '',
59
63
  cli: 'https_certs'
@@ -277,7 +281,9 @@ var _default = {
277
281
  i18nTemplate: ''
278
282
  },
279
283
  manifestJson: {
280
- enable: false
284
+ enable: false,
285
+ i18nManifestJson: false,
286
+ licenseManifest: false
281
287
  },
282
288
  changeRuntimeChunkChar: '~',
283
289
  serviceWorker: {
@@ -291,6 +297,7 @@ var _default = {
291
297
  allowPrefetchingMultipleChunks: false
292
298
  },
293
299
  devModeContentHashAllowedTypes: null,
300
+ nameTemplateCustomization: null,
294
301
  devLikeHash: {
295
302
  value: false,
296
303
  cli: 'dev_like_hash'
@@ -323,6 +330,20 @@ var _default = {
323
330
  cssAttributes: null,
324
331
  i18nAttributes: null
325
332
  },
326
- externals: null
333
+ externals: null,
334
+ typeScript: {
335
+ enable: {
336
+ value: false,
337
+ cli: 'type_script_enable'
338
+ }
339
+ },
340
+ optimization: {
341
+ jsExcludePath: '',
342
+ cssExcludePath: ''
343
+ },
344
+ customScriptLoadingStrategey: {
345
+ enable: false,
346
+ options: null
347
+ }
327
348
  };
328
349
  exports.default = _default;
@@ -25,6 +25,39 @@ const args = process.argv.slice(2);
25
25
  exports.args = args;
26
26
  const processEnv = (0, _npmConfigToObject.npmConfigToObject)();
27
27
  const cliArgsObject = (0, _cliArgsToObject.cliArgsToObject)(args);
28
+
29
+ if (cliArgsObject.app_domain && cliArgsObject.app_domain == 'kubernetes') {
30
+ cliArgsObject.k8s = true;
31
+ }
32
+
33
+ if (cliArgsObject.app_domain) {
34
+ cliArgsObject.domain = cliArgsObject.app_domain;
35
+ }
36
+
37
+ if (cliArgsObject.app_port) {
38
+ cliArgsObject.port = cliArgsObject.app_port;
39
+ }
40
+
41
+ if (cliArgsObject.app_host) {
42
+ cliArgsObject.host = cliArgsObject.app_host;
43
+ }
44
+
45
+ if (processEnv.app_domain && processEnv.app_domain == 'kubernetes') {
46
+ cliArgsObject.k8s = true;
47
+ }
48
+
49
+ if (processEnv.app_domain) {
50
+ cliArgsObject.domain = processEnv.app_domain;
51
+ }
52
+
53
+ if (processEnv.app_port) {
54
+ cliArgsObject.port = processEnv.app_port;
55
+ }
56
+
57
+ if (processEnv.app_host) {
58
+ cliArgsObject.host = processEnv.app_host;
59
+ }
60
+
28
61
  Object.assign(processEnv, cliArgsObject);
29
62
  let reactCLIOptions = null;
30
63
 
@@ -25,8 +25,11 @@ function babelWebConfig(options, mode) {
25
25
  plugins: babelPlugins,
26
26
  browserList
27
27
  } = options.babelCustomizations;
28
+ const {
29
+ enable: typeScriptEnable
30
+ } = options.typeScript;
28
31
  return {
29
- presets: [getBabelPresetEnvConfig(browserList, mode), require.resolve('@babel/preset-react')],
32
+ presets: typeScriptEnable ? [getBabelPresetEnvConfig(browserList, mode), require.resolve('@babel/preset-react'), require.resolve('@babel/preset-typescript')] : [getBabelPresetEnvConfig(browserList, mode), require.resolve('@babel/preset-react')],
30
33
  plugins: customBabelPlugins(babelPlugins).concat((0, _getBabelPlugin.getBabelPlugin)(options)).filter(Boolean)
31
34
  };
32
35
  }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.runBabelForTSFile = runBabelForTSFile;
7
+
8
+ var _core = require("@babel/core");
9
+
10
+ var _babelWebConfig = require("./babelWebConfig");
11
+
12
+ var _copyFile = require("../fileUtils/copyFile");
13
+
14
+ function runBabelForTSFile({
15
+ filename,
16
+ outputFile,
17
+ options,
18
+ mode = 'es'
19
+ }) {
20
+ const {
21
+ enable
22
+ } = options.typeScript;
23
+
24
+ if (enable) {
25
+ // const jsSourceCode = readFileSync(filename).toString();
26
+ const babelConfig = (0, _babelWebConfig.babelWebConfig)(options, mode);
27
+ const result = (0, _core.transformFileSync)(filename, babelConfig);
28
+ (0, _copyFile.writeFile)(outputFile.replace('.tsx', '.js'), result.code);
29
+ }
30
+ }
@@ -24,17 +24,22 @@ function modifiedServerOptions(options) {
24
24
  const {
25
25
  disableContextURL
26
26
  } = server;
27
+ const {
28
+ k8s
29
+ } = server;
27
30
  const port = Number(server.port);
28
31
  const httpsOptions = (0, _httpsOptions.httpsOptionsWithUserFriendlyError)(options);
29
32
  const machineDomain = (0, _getServerURL.getServerDomain)(server);
30
33
  const httpPort = port + 1;
31
34
  const httpsUrl = (0, _getServerURL.getServerUrl)({
32
35
  domain: machineDomain,
36
+ k8s,
33
37
  port,
34
38
  protocol: 'https'
35
39
  });
36
40
  const httpUrl = (0, _getServerURL.getServerUrl)({
37
41
  domain: machineDomain,
42
+ k8s,
38
43
  port: httpPort,
39
44
  protocol: 'http'
40
45
  });
@@ -12,16 +12,16 @@ var _modeUtils = require("./modeUtils");
12
12
  // NOTE: these below code can be done in js,
13
13
  // we did copy paste in order to avoid unnecessary confusion
14
14
  // NOTE: array[0] is dev mode file templates and array[1] is prod mode file templates
15
- const templates = {
15
+ const defaultTemplates = {
16
16
  html: ['index.html', 'index.[contenthash].html'],
17
- js: ['js/[name].js', 'js/[name].[contenthash].js'],
18
- chunkjs: ['js-chunks/[name].js', 'js-chunks/[name].[contenthash].js'],
19
- i18njs: ['i18n-chunks/[locale]/[name].i18n.js', 'i18n-chunks/[locale]/[name].[chunkhash].i18n.js'],
20
- i18nchunkjs: ['i18n-chunks/[locale]/[name].i18n.js', // 'i18n-chunks/[locale]/[name].[chunkhash].i18n.js'
21
- 'i18n-chunks/[locale]/[name].[contenthash].i18n.js'],
17
+ js: ['js/[name].js', 'js/[name].[contenthash]_.js'],
18
+ chunkjs: ['js-chunk/[name].js', 'js-chunks/[name].[contenthash]_.js'],
19
+ i18njs: ['i18n-chunk/[locale]/[name].i18n.js', 'i18n-chunk/[locale]/[name].[chunkhash:20]_.i18n.js'],
20
+ i18nchunkjs: ['i18n-chunk/[locale]/[name].i18n.js', // 'i18n-chunk/[locale]/[name].[chunkhash].i18n.js'
21
+ 'i18n-chunk/[locale]/[name].[contenthash]_.i18n.js'],
22
22
  i18nmanifest: ['i18n-manifest.json', 'i18n-manifest.json'],
23
23
  workerjs: ['js/[name].js', 'js/[name].[contenthash].js'],
24
- css: ['css/[name].css', 'css/[name].[contenthash].css'],
24
+ css: ['css/[name].css', 'css/[name].[contenthash]_.css'],
25
25
 
26
26
  /**
27
27
  * NOTE: when you change (cssdir) this line it will have affect on Below files will be affected
@@ -29,7 +29,7 @@ const templates = {
29
29
  * pluginConfigs/configMiniCSSExtractPlugin.js
30
30
  * pluginConfigs/configRtlCssPlugin.js
31
31
  * */
32
- cssdir: ['css/[name].[dir].css', 'css/[name].[contenthash].[dir].css'],
32
+ cssdir: ['css/[name].[dir].css', 'css/[name].[contenthash]_.[dir].css'],
33
33
  image: ['images/[name][ext]', 'images/[name].[contenthash][ext]'],
34
34
  font: ['fonts/[name][ext]', 'fonts/[name].[contenthash][ext]'],
35
35
  svg: ['fonts/[name][ext]', 'fonts/[name].[contenthash][ext]'],
@@ -54,12 +54,16 @@ function nameTemplates(type, options) {
54
54
  const {
55
55
  enableFileNameHashing,
56
56
  mode,
57
- devLikeHash
57
+ devLikeHash,
58
+ nameTemplateCustomization
58
59
  } = options;
59
60
  let {
60
61
  devModeContentHashAllowedTypes
61
62
  } = options;
62
63
  devModeContentHashAllowedTypes = devModeContentHashAllowedTypes || defaultDevModeContentHashAllowedTypes;
64
+ const templates = { ...defaultTemplates,
65
+ ...nameTemplateCustomization
66
+ };
63
67
  const templateName = templates[type];
64
68
 
65
69
  if (!templateName) {
@@ -39,7 +39,7 @@ class CdnChangePlugin {
39
39
  constructor(options) {
40
40
  this.createSeparateSMap = options.createSeparateSMap;
41
41
  this.i18nTemplate = options.i18nTemplate || '{{__I18N_CDN__}}';
42
- this.variableName = options.variableName || '__CSS_CDN__';
42
+ this.variableName = options.variableName || 'window.__SMAP_PATH__';
43
43
  this.cssTemplate = options.cssTemplate || '{{__CSS_CDN__}}';
44
44
  this.jsTemplate = options.jsTemplate || '{{__JS_CDN__}}';
45
45
  this.mode = options.mode || 'prod';
@@ -77,8 +77,12 @@ class CdnChangePlugin {
77
77
  data.assets = { ...data.assets,
78
78
  css: data.assets.css.map(css => `${this.cssTemplate}${css}`),
79
79
  js: data.assets.js.map(js => {
80
- if (((0, _modeUtils.isProductionMode)(mode) || createSeparateSMap) && !(0, _nameTemplates.isI18nFile)(js)) {
81
- js = js.replace('js/', `{{--js-smap}}js/`); //eslint-disable-line
80
+ if ((0, _modeUtils.isProductionMode)(mode) && createSeparateSMap && !(0, _nameTemplates.isI18nFile)(js)) {
81
+ if (js.includes('smap')) {
82
+ js = js.replace('smap/js/', `{{--js-smap}}js/`); //eslint-disable-line
83
+ } else {
84
+ js = js.replace('js/', `{{--js-smap}}js/`); //eslint-disable-line
85
+ }
82
86
  }
83
87
 
84
88
  return `${(0, _nameTemplates.isI18nFile)(js) ? this.i18nTemplate : this.jsTemplate}${js}`;
@@ -88,8 +92,12 @@ class CdnChangePlugin {
88
92
  });
89
93
 
90
94
  compilation.hooks.runtimeRequirementInTree.for(_webpack.RuntimeGlobals.getChunkScriptFilename).tap(pluginName, (chunk, set) => {
95
+ if (typeof compilation.outputOptions.chunkFilename === 'string' && /\[(full)?hash(:\d+)?\]/.test(compilation.outputOptions.chunkFilename)) {
96
+ set.add(_webpack.RuntimeGlobals.getFullHash);
97
+ }
98
+
91
99
  compilation.addRuntimeModule(chunk, // eslint-disable-next-line new-cap
92
- new _webpackCustomJsUrlLoader.default('javascript', 'javascript', _webpack.RuntimeGlobals.getChunkScriptFilename, chunk => chunk.filenameTemplate || (chunk.canBeInitial() ? compilation.outputOptions.filename : compilation.outputOptions.chunkFilename), false));
100
+ new _webpackCustomJsUrlLoader.default('javascript', 'javascript', _webpack.RuntimeGlobals.getChunkScriptFilename, chunk => chunk.filenameTemplate || (chunk.canBeInitial() ? compilation.outputOptions.filename : compilation.outputOptions.chunkFilename), false, this.variableName));
93
101
  return true;
94
102
  });
95
103
  });
@@ -5,258 +5,39 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
 
8
- var _webpack = require("webpack");
9
-
10
- const first = set => {
11
- const entry = set.values().next();
12
- return entry.done ? undefined : entry.value;
13
- };
14
-
15
- class CustomizedGetChunkFilenameRuntimeModule extends _webpack.RuntimeModule {
8
+ var _GetChunkFilenameRuntimeModule = _interopRequireDefault(require("webpack/lib/runtime/GetChunkFilenameRuntimeModule"));
9
+
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
12
+ // import { RuntimeGlobals, RuntimeModule, Template } from 'webpack';
13
+ // const GetChunkFilenameRuntimeModule = require('webpack/lib/runtime/GetChunkFilenameRuntimeModule');
14
+ // import GetChunkFilenameRuntimeModule from 'webpack/lib/runtime/GetChunkFilenameRuntimeModule';
15
+ // const first = set => {
16
+ // const entry = set.values().next();
17
+ // return entry.done ? undefined : entry.value;
18
+ // };
19
+ class CustomizedGetChunkFilenameRuntimeModule extends _GetChunkFilenameRuntimeModule.default {
16
20
  /**
17
- * @param {string} contentType the contentType to use the content hash for
21
+ * @param {string} contentType the to use the content hash for
18
22
  * @param {string} name kind of filename
19
23
  * @param {string} global function name to be assigned
20
24
  * @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function
21
25
  * @param {boolean} allChunks when false, only async chunks are included
22
26
  */
23
- constructor(contentType, name, global, getFilenameForChunk, allChunks) {
24
- super(`get ${name} chunk filename`);
27
+ constructor(contentType, name, global, getFilenameForChunk, allChunks, variableName) {
28
+ super(contentType, name, global, getFilenameForChunk, allChunks);
25
29
  this.contentType = contentType;
26
30
  this.global = global;
27
31
  this.getFilenameForChunk = getFilenameForChunk;
28
32
  this.allChunks = allChunks;
29
33
  this.dependentHash = true;
34
+ this.variableName = variableName;
30
35
  }
31
36
 
32
37
  generate() {
33
- const {
34
- global,
35
- chunk,
36
- chunkGraph,
37
- contentType,
38
- getFilenameForChunk,
39
- allChunks,
40
- compilation
41
- } = this;
42
- const {
43
- runtimeTemplate
44
- } = compilation;
45
- /** @type {Map<string | FilenameFunction, Set<Chunk>>} */
46
-
47
- const chunkFilenames = new Map();
48
- let maxChunks = 0;
49
- /** @type {string} */
50
-
51
- let dynamicFilename;
52
- /**
53
- * @param {Chunk} c the chunk
54
- * @returns {void}
55
- */
56
-
57
- const addChunk = c => {
58
- const chunkFilename = getFilenameForChunk(c);
59
-
60
- if (chunkFilename) {
61
- let set = chunkFilenames.get(chunkFilename);
62
-
63
- if (set === undefined) {
64
- chunkFilenames.set(chunkFilename, set = new Set());
65
- }
66
-
67
- set.add(c);
68
-
69
- if (typeof chunkFilename === 'string') {
70
- if (set.size < maxChunks) return;
71
-
72
- if (set.size === maxChunks) {
73
- if (chunkFilename.length < dynamicFilename.length) return;
74
-
75
- if (chunkFilename.length === dynamicFilename.length) {
76
- if (chunkFilename < dynamicFilename) return;
77
- }
78
- }
79
-
80
- maxChunks = set.size;
81
- dynamicFilename = chunkFilename;
82
- }
83
- }
84
- };
85
- /** @type {string[]} */
86
-
87
-
88
- const includedChunksMessages = [];
89
-
90
- if (allChunks) {
91
- includedChunksMessages.push('all chunks');
92
-
93
- for (const c of chunk.getAllReferencedChunks()) {
94
- addChunk(c);
95
- }
96
- } else {
97
- includedChunksMessages.push('async chunks');
98
-
99
- for (const c of chunk.getAllAsyncChunks()) {
100
- addChunk(c);
101
- }
102
-
103
- const includeEntries = chunkGraph.getTreeRuntimeRequirements(chunk).has(_webpack.RuntimeGlobals.ensureChunkIncludeEntries);
104
-
105
- if (includeEntries) {
106
- includedChunksMessages.push('sibling chunks for the entrypoint');
107
-
108
- for (const c of chunkGraph.getChunkEntryDependentChunksIterable(chunk)) {
109
- addChunk(c);
110
- }
111
- }
112
- }
113
-
114
- for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) {
115
- addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]);
116
- }
117
- /** @type {Map<string, Set<string | number>>} */
118
-
119
-
120
- const staticUrls = new Map();
121
- /** @type {Set<Chunk>} */
122
-
123
- const dynamicUrlChunks = new Set();
124
- /**
125
- * @param {Chunk} c the chunk
126
- * @param {string | FilenameFunction} chunkFilename the filename template for the chunk
127
- * @returns {void}
128
- */
129
-
130
- const addStaticUrl = (c, chunkFilename) => {
131
- /**
132
- * @param {string | number} value a value
133
- * @returns {string} string to put in quotes
134
- */
135
- const unquotedStringify = value => {
136
- const str = `${value}`;
137
-
138
- if (str.length >= 5 && str === `${c.id}`) {
139
- // This is shorter and generates the same result
140
- return '" + chunkId + "';
141
- }
142
-
143
- const s = JSON.stringify(str);
144
- return s.slice(1, s.length - 1);
145
- };
146
-
147
- const unquotedStringifyWithLength = value => length => unquotedStringify(`${value}`.slice(0, length));
148
-
149
- const chunkFilenameValue = typeof chunkFilename === 'function' ? JSON.stringify(chunkFilename({
150
- chunk: c,
151
- contentHashType: contentType
152
- })) : JSON.stringify(chunkFilename);
153
- const staticChunkFilename = compilation.getPath(chunkFilenameValue, {
154
- hash: `" + ${_webpack.RuntimeGlobals.getFullHash}() + "`,
155
- hashWithLength: length => `" + ${_webpack.RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`,
156
- chunk: {
157
- id: unquotedStringify(c.id),
158
- hash: unquotedStringify(c.renderedHash),
159
- hashWithLength: unquotedStringifyWithLength(c.renderedHash),
160
- name: unquotedStringify(c.name || c.id),
161
- contentHash: {
162
- [contentType]: unquotedStringify(c.contentHash[contentType])
163
- },
164
- contentHashWithLength: {
165
- [contentType]: unquotedStringifyWithLength(c.contentHash[contentType])
166
- }
167
- },
168
- contentHashType: contentType
169
- });
170
- let set = staticUrls.get(staticChunkFilename);
171
-
172
- if (set === undefined) {
173
- staticUrls.set(staticChunkFilename, set = new Set());
174
- }
175
-
176
- set.add(c.id);
177
- };
178
-
179
- for (const [filename, chunks] of chunkFilenames) {
180
- if (filename !== dynamicFilename) {
181
- for (const c of chunks) addStaticUrl(c, filename);
182
- } else {
183
- for (const c of chunks) dynamicUrlChunks.add(c);
184
- }
185
- }
186
- /**
187
- * @param {function(Chunk): string | number} fn function from chunk to value
188
- * @returns {string} code with static mapping of results of fn
189
- */
190
-
191
-
192
- const createMap = fn => {
193
- const obj = {};
194
- let useId = false;
195
- let lastKey;
196
- let entries = 0; // eslint-disable-next-line no-restricted-syntax
197
-
198
- for (const c of dynamicUrlChunks) {
199
- const value = fn(c);
200
-
201
- if (value === c.id) {
202
- useId = true;
203
- } else {
204
- obj[c.id] = value;
205
- lastKey = c.id;
206
- entries++;
207
- }
208
- }
209
-
210
- if (entries === 0) return 'chunkId';
211
-
212
- if (entries === 1) {
213
- return useId ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify(obj[lastKey])} : chunkId)` : JSON.stringify(obj[lastKey]);
214
- }
215
-
216
- return useId ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` : `${JSON.stringify(obj)}[chunkId]`;
217
- };
218
- /**
219
- * @param {function(Chunk): string | number} fn function from chunk to value
220
- * @returns {string} code with static mapping of results of fn for including in quoted string
221
- */
222
-
223
-
224
- const mapExpr = fn => {
225
- return `" + ${createMap(fn)} + "`;
226
- };
227
- /**
228
- * @param {function(Chunk): string | number} fn function from chunk to value
229
- * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length
230
- */
231
-
232
-
233
- const mapExprWithLength = fn => length => {
234
- return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`;
235
- };
236
-
237
- const url = dynamicFilename && compilation.getPath(JSON.stringify(dynamicFilename), {
238
- hash: `" + ${_webpack.RuntimeGlobals.getFullHash}() + "`,
239
- hashWithLength: length => `" + ${_webpack.RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`,
240
- chunk: {
241
- id: `" + chunkId + "`,
242
- hash: mapExpr(c => c.renderedHash),
243
- hashWithLength: mapExprWithLength(c => c.renderedHash),
244
- name: mapExpr(c => c.name || c.id),
245
- contentHash: {
246
- [contentType]: mapExpr(c => c.contentHash[contentType])
247
- },
248
- contentHashWithLength: {
249
- [contentType]: mapExprWithLength(c => c.contentHash[contentType])
250
- }
251
- },
252
- contentHashType: contentType
253
- });
254
- const cdn = `__CSS_CDN__`;
255
- return _webpack.Template.asString([`// This function allow to reference ${includedChunksMessages.join(' and ')}`, `${global} = ${runtimeTemplate.basicFunction('chunkId', staticUrls.size > 0 ? ['// return url for filenames not based on template', // it minimizes to `x===1?"...":x===2?"...":"..."`
256
- _webpack.Template.asString(Array.from(staticUrls, ([url, ids]) => {
257
- const condition = ids.size === 1 ? `chunkId === ${JSON.stringify(first(ids))}` : `{${Array.from(ids, id => `${JSON.stringify(id)}:1`).join(',')}}[chunkId]`;
258
- return `if (${condition}) return window.${cdn}+${url};`;
259
- })), '// return url for filenames based on template', `return window.${cdn}+${url};`] : ['// return url for filenames based on template', `return window.${cdn}+${url};`])};`]);
38
+ const sourceCode = super.generate().toString();
39
+ const replaceCode = sourceCode.replaceAll('"js-chunks/', `${this.variableName} + "js-chunks/`);
40
+ return replaceCode;
260
41
  }
261
42
 
262
43
  }
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CustomScriptLoadingStrategyPlugin = void 0;
7
+
8
+ var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));
9
+
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
12
+ const pluginName = 'CustomScriptLoadingStrategyPlugin';
13
+
14
+ class CustomScriptLoadingStrategyPlugin {
15
+ constructor({
16
+ scriptLoadingStategey
17
+ } = {}) {
18
+ this.scriptLoadingStrategy = scriptLoadingStategey;
19
+ this.tagNamesToMatch = ['script'];
20
+ }
21
+
22
+ getFileNameFromTagSrc(src) {
23
+ const fileNameArr = src.split('/');
24
+ return fileNameArr[fileNameArr.length - 1];
25
+ }
26
+
27
+ addAttributestToTag(tag, attributes) {
28
+ tag.attributes = Object.assign({}, tag.attributes, attributes);
29
+ }
30
+
31
+ matchFileName(tag, fileName) {
32
+ return fileName.test(this.getFileNameFromTagSrc(tag.attributes.src));
33
+ }
34
+
35
+ blockingStrategy(tag) {
36
+ delete tag.attributes.defer;
37
+ delete tag.attributes.async;
38
+ }
39
+
40
+ deferStrategy(tag) {
41
+ delete tag.attributes.async;
42
+ }
43
+
44
+ asyncStrategy(tag) {
45
+ delete tag.attributes.defer;
46
+ }
47
+
48
+ moduleStrategy(tag) {
49
+ this.deferStrategy(tag);
50
+ }
51
+
52
+ matchStrategy(scriptLoadingStrategy, tag) {
53
+ if (scriptLoadingStrategy === 'blocking') {
54
+ this.blockingStrategy(tag);
55
+ }
56
+
57
+ if (scriptLoadingStrategy === 'defer') {
58
+ this.deferStrategy(tag);
59
+ }
60
+
61
+ if (scriptLoadingStrategy === 'async') {
62
+ this.asyncStrategy(tag);
63
+ }
64
+
65
+ if (scriptLoadingStrategy === 'module') {
66
+ this.moduleStrategy(tag);
67
+ }
68
+ }
69
+
70
+ matchAndApplyCustomLoadingStrategyToScripts(tags) {
71
+ Object.keys(this.scriptLoadingStrategy).forEach(scriptLoadingStrategy => {
72
+ const filesToMatch = this.scriptLoadingStrategy[scriptLoadingStrategy];
73
+ tags.forEach(tag => {
74
+ if (this.tagNamesToMatch.includes(tag.tagName) && tag.attributes.src) {
75
+ const isFileMatch = filesToMatch.some(fileName => this.matchFileName(tag, fileName));
76
+
77
+ if (isFileMatch) {
78
+ this.matchStrategy(scriptLoadingStrategy, tag);
79
+ this.addAttributestToTag(tag, {
80
+ [scriptLoadingStrategy]: true
81
+ });
82
+ }
83
+ } // filesToMatch.forEach(fileName => {
84
+ // if (!this.matchFileName(tag, fileName)) {
85
+ // return;
86
+ // }
87
+ // this.matchStrategy(scriptLoadingStrategy, tag);
88
+ // this.addAttributestToTag(tag, fileName, {
89
+ // [scriptLoadingStrategy]: true
90
+ // });
91
+ // });
92
+
93
+ });
94
+ });
95
+ }
96
+
97
+ apply(compiler) {
98
+ compiler.hooks.compilation.tap(pluginName, compilation => {
99
+ _htmlWebpackPlugin.default.getHooks(compilation).alterAssetTagGroups.tapAsync(pluginName, (data, callback) => {
100
+ const tags = [...data.bodyTags, ...data.headTags];
101
+ this.matchAndApplyCustomLoadingStrategyToScripts(tags);
102
+ callback(null, data);
103
+ });
104
+ });
105
+ }
106
+
107
+ }
108
+
109
+ exports.CustomScriptLoadingStrategyPlugin = CustomScriptLoadingStrategyPlugin;
@@ -65,7 +65,7 @@ function getI18nLoadingRuntimeModule({
65
65
  return _webpack.Template.asString([`${prefixFunc(i18nChunks)}`, `var createI18nScriptTag = ${runtimeTemplate.basicFunction('chunkId, fullsrc, resolve, reject', ['var scriptTag = document.createElement("script");', attributes ? _webpack.Template.asString(Object.entries(attributes).map(entry => {
66
66
  const [key, value] = entry;
67
67
  return `scriptTag.setAttribute(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
68
- })) : '', scriptType ? `scriptTag.type = ${JSON.stringify(scriptType)};` : '', `var onScriptComplete = ${runtimeTemplate.basicFunction('event', ['// avoid mem leaks.', 'scriptTag.onerror = scriptTag.onload = null;', 'if (event.type === \'load\') {', _webpack.Template.indent(['resolve();']), '} else {', _webpack.Template.indent(['var errorType = event && (event.type === \'load\' ? \'missing\' : event.type);', 'var realSrc = event && event.target && event.target.src || fullsrc;', 'var err = new Error("Loading I18N chunk " + chunkId + " failed.\\n(" + realSrc + ")");', 'err.code = "I18N_CHUNK_LOAD_FAILED";', 'err.type = errorType;', 'err.request = realSrc;', 'scriptTag.parentNode.removeChild(scriptTag)', 'reject(err);']), '}'])}`, 'scriptTag.onerror = scriptTag.onload = onScriptComplete;', 'scriptTag.src = fullsrc;', crossOriginLoading ? _webpack.Template.asString(['if (scriptTag.src.indexOf(window.location.origin + \'/\') !== 0) {', _webpack.Template.indent(`scriptTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', insertRoot && insertPlace || _webpack.Template.asString(['document.head.appendChild(scriptTag);']), 'return scriptTag;'])};`, `var findI18nScriptTag = ${runtimeTemplate.basicFunction('src, fullsrc', ['var existingScriptTags = document.getElementsByTagName("script");', 'for(var i = 0; i < existingScriptTags.length; i++) {', _webpack.Template.indent(['var tag = existingScriptTags[i];', 'var dataSrc = tag.getAttribute("data-src") || tag.getAttribute("src");', 'if((dataSrc === src || dataSrc === fullsrc)) return tag;']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', _webpack.Template.indent(['var tag = existingStyleTags[i];', 'var dataSrc = tag.getAttribute("data-src");', 'if(dataSrc === src || dataSrc === fullsrc) return tag;']), '}'])};`, `var loadI18nScriptTag = ${runtimeTemplate.basicFunction('chunkId', `return new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var src = ${_webpack.RuntimeGlobals.require}.miniI18nF(chunkId);`, `var fullsrc = ${_webpack.RuntimeGlobals.publicPath} + src;`, 'if(findI18nScriptTag(src, fullsrc)) return resolve();', 'createI18nScriptTag(chunkId, fullsrc, resolve, reject);'])});`)}`, '// object to store loaded I18N chunks', 'var installedI18nChunks = {', _webpack.Template.indent(
68
+ })) : '', '__webpack_require__.nc && scriptTag.setAttribute("nonce", __webpack_require__.nc)', scriptType ? `scriptTag.type = ${JSON.stringify(scriptType)};` : '', `var onScriptComplete = ${runtimeTemplate.basicFunction('event', ['// avoid mem leaks.', 'scriptTag.onerror = scriptTag.onload = null;', 'if (event.type === \'load\') {', _webpack.Template.indent(['resolve();']), '} else {', _webpack.Template.indent(['var errorType = event && (event.type === \'load\' ? \'missing\' : event.type);', 'var realSrc = event && event.target && event.target.src || fullsrc;', 'var err = new Error("Loading I18N chunk " + chunkId + " failed.\\n(" + realSrc + ")");', 'err.code = "I18N_CHUNK_LOAD_FAILED";', 'err.type = errorType;', 'err.request = realSrc;', 'scriptTag.parentNode.removeChild(scriptTag)', 'reject(err);']), '}'])}`, 'scriptTag.onerror = scriptTag.onload = onScriptComplete;', 'scriptTag.src = fullsrc;', crossOriginLoading ? _webpack.Template.asString(['if (scriptTag.src.indexOf(window.location.origin + \'/\') !== 0) {', _webpack.Template.indent(`scriptTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', insertRoot && insertPlace || _webpack.Template.asString(['document.head.appendChild(scriptTag);']), 'return scriptTag;'])};`, `var findI18nScriptTag = ${runtimeTemplate.basicFunction('src, fullsrc', ['var existingScriptTags = document.getElementsByTagName("script");', 'for(var i = 0; i < existingScriptTags.length; i++) {', _webpack.Template.indent(['var tag = existingScriptTags[i];', 'var dataSrc = tag.getAttribute("data-src") || tag.getAttribute("src");', 'if((dataSrc === src || dataSrc === fullsrc)) return tag;']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', _webpack.Template.indent(['var tag = existingStyleTags[i];', 'var dataSrc = tag.getAttribute("data-src");', 'if(dataSrc === src || dataSrc === fullsrc) return tag;']), '}'])};`, `var loadI18nScriptTag = ${runtimeTemplate.basicFunction('chunkId', `return new Promise(${runtimeTemplate.basicFunction('resolve, reject', [`var src = ${_webpack.RuntimeGlobals.require}.miniI18nF(chunkId);`, `var fullsrc = ${_webpack.RuntimeGlobals.publicPath} + src;`, 'if(findI18nScriptTag(src, fullsrc)) return resolve();', 'createI18nScriptTag(chunkId, fullsrc, resolve, reject);'])});`)}`, '// object to store loaded I18N chunks', 'var installedI18nChunks = {', _webpack.Template.indent(
69
69
  /** @type {string[]} */
70
70
  chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(',\n')), '};', '', `${_webpack.RuntimeGlobals.ensureChunkHandlers}.miniI18n = ${runtimeTemplate.basicFunction('chunkId, promises', [`var i18nChunks = ${JSON.stringify(chunkMap)};`, 'if(installedI18nChunks[chunkId]) promises.push(installedI18nChunks[chunkId]);', 'else if(installedI18nChunks[chunkId] !== 0 && i18nChunks[chunkId]) {', _webpack.Template.indent([`promises.push(installedI18nChunks[chunkId] = loadI18nScriptTag(chunkId).then(${runtimeTemplate.basicFunction('', 'installedI18nChunks[chunkId] = 0;')}, ${runtimeTemplate.basicFunction('e', ['delete installedI18nChunks[chunkId];', 'throw e;'])}));`]), '}'])};`, '']);
71
71
  }
@@ -37,6 +37,10 @@ class InitialHtmlPlugin {
37
37
  const headTags = [];
38
38
  const bodyTags = [];
39
39
  data.headTags.forEach(tag => {
40
+ Object.assign(tag.attributes, {
41
+ nonce: '{{--CSP-nonce}}'
42
+ });
43
+
40
44
  if (tag.tagName === 'link') {
41
45
  headTags.push(tag);
42
46
  } else {