catalyst-core-internal 0.0.1-beta.0

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 (100) hide show
  1. package/README.md +145 -0
  2. package/babel.config.json +24 -0
  3. package/bin/catalyst.js +40 -0
  4. package/caching.js +16 -0
  5. package/config.json +7 -0
  6. package/index.js +16 -0
  7. package/logger.js +96 -0
  8. package/package.json +84 -0
  9. package/packages/create-framework-app/templates/redux-js/node_modules/@babel/core/lib/config/caching.js +261 -0
  10. package/packages/create-framework-app/templates/redux-js/node_modules/@remix-run/router/dist/router.js +4327 -0
  11. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/router.js +15 -0
  12. package/packages/create-framework-app/templates/redux-js/node_modules/catalyst/src/router.js +1 -0
  13. package/packages/create-framework-app/templates/redux-js/node_modules/http-proxy-middleware/dist/router.js +46 -0
  14. package/router/ClientRouter.js +19 -0
  15. package/router/ServerRouter.js +19 -0
  16. package/router/index.js +32 -0
  17. package/router.js +16 -0
  18. package/scripts/build.js +29 -0
  19. package/scripts/checkVersion.js +5 -0
  20. package/scripts/loadEnvironmentVariables.js +24 -0
  21. package/scripts/loadScriptsBeforeServerStarts.js +47 -0
  22. package/scripts/prepare.js +19 -0
  23. package/scripts/registerAliases.js +30 -0
  24. package/scripts/serve.js +30 -0
  25. package/scripts/start.js +26 -0
  26. package/scripts/validator.js +130 -0
  27. package/server/expressServer.js +50 -0
  28. package/server/mainIndex.js +65 -0
  29. package/server/mainServer.js +70 -0
  30. package/server/renderer/document/Body.js +36 -0
  31. package/server/renderer/document/Head.js +43 -0
  32. package/server/renderer/document/index.js +27 -0
  33. package/server/renderer/extract.js +87 -0
  34. package/server/renderer/handler.js +244 -0
  35. package/server/renderer/index.js +12 -0
  36. package/server/renderer/render.js +73 -0
  37. package/server/renderer/userAgentUtil.js +55 -0
  38. package/server/startServer.js +65 -0
  39. package/server/utils/userAgentUtil.js +55 -0
  40. package/server/utils/validator.js +130 -0
  41. package/tsconfig.json +110 -0
  42. package/types/caching.d.ts +1 -0
  43. package/types/config/config.d.ts +19 -0
  44. package/types/index.d.ts +1 -0
  45. package/types/logger/index.d.ts +14 -0
  46. package/types/reducer/index.d.ts +22 -0
  47. package/types/reducer/loadableConfigReducer.d.ts +9 -0
  48. package/types/router/ClientRouter.d.ts +5 -0
  49. package/types/router/ServerRouter.d.ts +7 -0
  50. package/types/router/index.d.ts +8 -0
  51. package/types/router.d.ts +1 -0
  52. package/types/scripts/build.d.ts +1 -0
  53. package/types/scripts/loadEnvironmentVariables.d.ts +5 -0
  54. package/types/scripts/loadScriptsBeforeServerStarts.d.ts +1 -0
  55. package/types/scripts/prepare.d.ts +1 -0
  56. package/types/scripts/registerAliases.d.ts +1 -0
  57. package/types/scripts/serve.d.ts +1 -0
  58. package/types/scripts/start.d.ts +1 -0
  59. package/types/scripts/validator.d.ts +9 -0
  60. package/types/scripts/verifyConfig.d.ts +1 -0
  61. package/types/server/mainIndex.d.ts +1 -0
  62. package/types/server/mainServer.d.ts +2 -0
  63. package/types/server/renderer/document/Body.d.ts +11 -0
  64. package/types/server/renderer/document/Head.d.ts +11 -0
  65. package/types/server/renderer/document/index.d.ts +2 -0
  66. package/types/server/renderer/extract.d.ts +18 -0
  67. package/types/server/renderer/handler.d.ts +6 -0
  68. package/types/server/renderer/index.d.ts +2 -0
  69. package/types/server/renderer/render.d.ts +38 -0
  70. package/types/server/renderer/userAgentUtil.d.ts +1 -0
  71. package/types/store/index.d.ts +11 -0
  72. package/types/store/index.dev.d.ts +8 -0
  73. package/types/store/index.prod.d.ts +8 -0
  74. package/types/webpack/babel-plugins/remove-client.plugin.d.ts +10 -0
  75. package/types/webpack/babel-plugins/remove-ssr.plugin.d.ts +10 -0
  76. package/types/webpack/babel.config.client.d.ts +21 -0
  77. package/types/webpack/babel.config.d.ts +16 -0
  78. package/types/webpack/babel.config.ssr.d.ts +21 -0
  79. package/types/webpack/base.babel.d.ts +184 -0
  80. package/types/webpack/development.client.babel.d.ts +1 -0
  81. package/types/webpack/plugins/mime-types.d.ts +78 -0
  82. package/types/webpack/plugins/route-manifest-plugin.d.ts +1 -0
  83. package/types/webpack/plugins/upload-assets-plugin.d.ts +1 -0
  84. package/types/webpack/production.client.babel.d.ts +174 -0
  85. package/types/webpack/production.ssr.babel.d.ts +2 -0
  86. package/types/webpack/scssParams.d.ts +2 -0
  87. package/webpack/babel-plugins/remove-client.plugin.js +31 -0
  88. package/webpack/babel-plugins/remove-ssr.plugin.js +21 -0
  89. package/webpack/babel.config.client.js +24 -0
  90. package/webpack/babel.config.js +20 -0
  91. package/webpack/babel.config.ssr.js +24 -0
  92. package/webpack/base.babel.js +165 -0
  93. package/webpack/development.client.babel.js +82 -0
  94. package/webpack/plugins/mime-types.js +82 -0
  95. package/webpack/plugins/route-manifest-copy.js +122 -0
  96. package/webpack/plugins/route-manifest-plugin.js +122 -0
  97. package/webpack/plugins/upload-assets-plugin.js +181 -0
  98. package/webpack/production.client.babel.js +78 -0
  99. package/webpack/production.ssr.babel.js +61 -0
  100. package/webpack/scssParams.js +35 -0
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.basePlugins = void 0;
7
+ var _path = _interopRequireDefault(require("path"));
8
+ var _webpack = _interopRequireDefault(require("webpack"));
9
+ var _miniCssExtractPlugin = _interopRequireDefault(require("mini-css-extract-plugin"));
10
+ var _webpackBundleAnalyzer = require("webpack-bundle-analyzer");
11
+ var _webpackPlugin = _interopRequireDefault(require("@loadable/webpack-plugin"));
12
+ var _scssParams = require("./scssParams");
13
+ var _babelConfig = _interopRequireDefault(require("./babel.config.client"));
14
+ var _babelConfig2 = _interopRequireDefault(require("./babel.config.ssr"));
15
+ var _loadEnvironmentVariables = _interopRequireDefault(require("../scripts/loadEnvironmentVariables"));
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ const catalystConfig = require(_path.default.resolve(__dirname, "..", "config.json"));
18
+ const {
19
+ CLIENT_ENV_VARIABLES: clientEnv,
20
+ ANALYZE_BUNDLE
21
+ } = require(`${process.env.src_path}/config/config.json`);
22
+ const {
23
+ _moduleAliases
24
+ } = require(`${process.env.src_path}/package.json`);
25
+ (0, _loadEnvironmentVariables.default)();
26
+ const isDev = process.env.NODE_ENV === "development";
27
+ const isSSR = !!process.env.SSR || false;
28
+ const basePlugins = exports.basePlugins = [new _webpackPlugin.default({
29
+ filename: "loadable-stats.json",
30
+ writeToDisk: {
31
+ filename: _path.default.join(__dirname, "..")
32
+ }
33
+ }),
34
+ // **This loads process.env variable during webpack build process
35
+ new _webpack.default.DefinePlugin({
36
+ "process.env": ([...clientEnv, ...Object.keys(process.env)] || []).reduce((clientEnvMap, env) => {
37
+ clientEnvMap[env] = JSON.stringify(process.env[env]);
38
+ return clientEnvMap;
39
+ }, {})
40
+ }),
41
+ // ** This is used to analyze bundle size.
42
+ ANALYZE_BUNDLE && new _webpackBundleAnalyzer.BundleAnalyzerPlugin({
43
+ generateStatsFile: ANALYZE_BUNDLE
44
+ }), new _webpack.default.IgnorePlugin({
45
+ resourceRegExp: /^\.\/locale$/,
46
+ contextRegExp: /moment$/
47
+ })];
48
+ const {
49
+ PUBLIC_STATIC_ASSET_URL,
50
+ PUBLIC_STATIC_ASSET_PATH
51
+ } = process.env;
52
+ let publicPath = `${PUBLIC_STATIC_ASSET_URL}${PUBLIC_STATIC_ASSET_PATH}`;
53
+ var _default = exports.default = {
54
+ context: _path.default.resolve(process.env.src_path),
55
+ mode: isDev ? "development" : "production",
56
+ entry: {
57
+ app: [_path.default.resolve(process.env.src_path, "./client/index.js")]
58
+ },
59
+ output: {
60
+ path: _path.default.join(process.env.src_path, `${process.env.BUILD_OUTPUT_PATH}/public`),
61
+ chunkFilename: process.env.NODE_ENV === "development" ? catalystConfig.chunkFileNameDev : catalystConfig.chunkFileNameProd,
62
+ publicPath: publicPath,
63
+ chunkFilename: process.env.NODE_ENV === "development" ? catalystConfig.chunkFileNameDev : catalystConfig.chunkFileNameProd
64
+ },
65
+ resolve: {
66
+ fallback: {
67
+ url: require.resolve("url")
68
+ },
69
+ extensions: [".js", ".jsx", ".scss"],
70
+ alias: Object.keys(_moduleAliases || {}).reduce((moduleEnvMap, alias) => {
71
+ moduleEnvMap[alias] = _path.default.join(process.env.src_path, ..._moduleAliases[alias].split("/"));
72
+ return moduleEnvMap;
73
+ }, {})
74
+ },
75
+ plugins: basePlugins,
76
+ module: {
77
+ rules: [{
78
+ test: /\.jsx$|\.js$/,
79
+ exclude: _path.default.resolve(process.env.src_path, "./node_modules"),
80
+ use: {
81
+ loader: "babel-loader",
82
+ options: isSSR ? _babelConfig2.default : _babelConfig.default
83
+ }
84
+ }, {
85
+ // This loader processes all the .scss files that should be modularized. This should exclude anything inside node_modules and everything inside src/css/base since they should be globally scoped.
86
+ test: /\.scss$/,
87
+ exclude: [_path.default.resolve(process.env.src_path, "./node_modules"), _path.default.resolve(process.env.src_path, "./src/static/css/base")],
88
+ use: [isDev && "css-hot-loader", !isSSR && _miniCssExtractPlugin.default.loader, {
89
+ loader: "css-loader",
90
+ options: {
91
+ modules: {
92
+ mode: "local",
93
+ exportOnlyLocals: !isDev && isSSR,
94
+ localIdentName: isDev ? catalystConfig.cssModulesIdentifierDev : catalystConfig.cssModulesIdentifierProd
95
+ }
96
+ }
97
+ }, {
98
+ loader: "postcss-loader"
99
+ }, {
100
+ loader: "sass-loader",
101
+ options: {
102
+ additionalData: "$font_url: " + (0, _scssParams.fontUrl)() + ";" + "$url_for: " + (0, _scssParams.imageUrl)() + ";"
103
+ }
104
+ }, {
105
+ loader: "sass-resources-loader",
106
+ options: {
107
+ resources: [_path.default.resolve(process.env.src_path, "./src/static/css/resources/*.scss")]
108
+ }
109
+ }]
110
+ }, {
111
+ // In development mode, client request app.css ,which has all the css in node_modules and src/static/css/base, This is served by webpack-dev-server. However in prod this css is injected in the doc sent from the server and needs to be global, so we don't pass the files through css-loader to be modularized.
112
+ test: /\.scss$/,
113
+ include: [_path.default.resolve(process.env.src_path, "./node_modules"), _path.default.resolve(process.env.src_path, "./src/static/css/base")],
114
+ use: [isDev && "css-hot-loader", !isSSR && _miniCssExtractPlugin.default.loader, {
115
+ loader: "css-loader"
116
+ }, {
117
+ loader: "postcss-loader"
118
+ }, {
119
+ loader: "sass-loader",
120
+ options: {
121
+ additionalData: "$font_url: " + (0, _scssParams.fontUrl)() + ";" + "$url_for: " + (0, _scssParams.imageUrl)() + ";"
122
+ }
123
+ }, {
124
+ loader: "sass-resources-loader",
125
+ options: {
126
+ resources: [_path.default.resolve(process.env.src_path, "./src/static/css/resources/*.scss")]
127
+ }
128
+ }]
129
+ }, {
130
+ test: /\.css$/,
131
+ use: [!isSSR && _miniCssExtractPlugin.default.loader, "css-loader", "postcss-loader"]
132
+ }, {
133
+ test: /\.(png|jpg|gif|jpeg|ico?)$/,
134
+ use: ["url-loader?limit=10240", "img-loader"]
135
+ }, {
136
+ test: /\.svg$/i,
137
+ issuer: /\.[jt]sx?$/,
138
+ use: ["@svgr/webpack", "url-loader?limit=10240", "img-loader"]
139
+ }, {
140
+ // This loader loads fonts in src/static/fonts using file-loader
141
+ test: /\.(ttf|eot|woff2|json?)$/,
142
+ use: [{
143
+ loader: "url-loader",
144
+ options: {
145
+ limit: 10240,
146
+ outputPath: [_path.default.resolve(process.env.src_path, "./src/static/fonts/")]
147
+ }
148
+ }, "file-loader"]
149
+ }, {
150
+ // This loader loads html files
151
+ test: /\.html$/,
152
+ use: [{
153
+ loader: "html-loader",
154
+ options: {
155
+ minimize: {
156
+ minifyJS: true,
157
+ minifyCSS: true,
158
+ removeComments: false,
159
+ collapseWhitespace: true
160
+ }
161
+ }
162
+ }]
163
+ }]
164
+ }
165
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ var _path = _interopRequireDefault(require("path"));
4
+ var _webpackDevServer = _interopRequireDefault(require("webpack-dev-server"));
5
+ var _webpack = _interopRequireDefault(require("webpack"));
6
+ var _webpackMerge = _interopRequireDefault(require("webpack-merge"));
7
+ var _baseBabel = _interopRequireDefault(require("./base.babel.js"));
8
+ var _reactRefreshWebpackPlugin = _interopRequireDefault(require("@pmmmwh/react-refresh-webpack-plugin"));
9
+ var _miniCssExtractPlugin = _interopRequireDefault(require("mini-css-extract-plugin"));
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ /* eslint-disable no-console */
12
+
13
+ const {
14
+ WEBPACK_DEV_SERVER_PORT,
15
+ WEBPACK_DEV_SERVER_HOSTNAME
16
+ } = process.env;
17
+ const catalystConfig = require(_path.default.resolve(__dirname, "..", "config.json"));
18
+ const plugins = require(_path.default.join(process.env.src_path, "webpackConfig.js"));
19
+ const webpackConfig = (0, _webpackMerge.default)(_baseBabel.default, {
20
+ devtool: "inline-source-map",
21
+ stats: "minimal",
22
+ plugins: [new _reactRefreshWebpackPlugin.default({
23
+ overlay: {
24
+ entry: false
25
+ }
26
+ }), new _miniCssExtractPlugin.default({
27
+ filename: catalystConfig.cssChunkFileName,
28
+ ignoreOrder: true
29
+ }), ...plugins.developmentPlugins].filter(Boolean),
30
+ optimization: {
31
+ runtimeChunk: "single",
32
+ moduleIds: "deterministic",
33
+ splitChunks: {
34
+ cacheGroups: {
35
+ commonVendor: {
36
+ test: /[\\/]node_modules[\\/](react|react-dom|react-redux|react-router|react-router-dom|redux|redux-thunk|axios|react-loadable-visibility|react-helmet-async|react-fast-compare|react-async-script|babel|@loadable\/component|catalyst)[\\/]/,
37
+ name: "commonVendor",
38
+ minSize: 30000
39
+ },
40
+ utilityVendor: {
41
+ maxInitialRequests: Infinity,
42
+ chunks: "all",
43
+ // minSize: 0, // Enable to replicate stand alone chunking for all packages
44
+ reuseExistingChunk: true,
45
+ // Disable to replicate stand alone chunking for all packages
46
+ minRemainingSize: 1000,
47
+ // Disable to replicate stand alone chunking for all packages
48
+ test: /[\\/]node_modules[\\/]/,
49
+ name(module) {
50
+ const moduleFileName = module.identifier().split("/").reduceRight(item => item);
51
+ return `npm.${moduleFileName}`;
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+ });
58
+ console.info("Firing up catalyst dev server...\n");
59
+ let devServer = new _webpackDevServer.default({
60
+ port: process.env.WEBPACK_DEV_SERVER_PORT,
61
+ host: process.env.WEBPACK_DEV_SERVER_HOSTNAME,
62
+ static: {
63
+ publicPath: webpackConfig.output.publicPath
64
+ },
65
+ hot: true,
66
+ historyApiFallback: true,
67
+ headers: {
68
+ "Access-Control-Allow-Origin": "*"
69
+ },
70
+ client: {
71
+ logging: "error",
72
+ overlay: {
73
+ errors: false,
74
+ warnings: false,
75
+ runtimeErrors: false
76
+ },
77
+ reconnect: true
78
+ }
79
+ }, (0, _webpack.default)(webpackConfig));
80
+ devServer.startCallback(() => {
81
+ console.info(`Webpack dev server mounted at http://${WEBPACK_DEV_SERVER_HOSTNAME}:${WEBPACK_DEV_SERVER_PORT}.`);
82
+ });
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ module.exports = {
4
+ m4a: "audio/mp4",
5
+ f4a: "audio/mp4",
6
+ f4b: "audio/mp4",
7
+ oga: "audio/ogg",
8
+ ogg: "audio/ogg",
9
+ mid: "audio/&",
10
+ midi: "audio/&",
11
+ mp3: "audio/&",
12
+ wav: "audio/&",
13
+ js: "application/javascript",
14
+ jsonp: "application/javascript",
15
+ json: "application/json",
16
+ doc: "application/msword",
17
+ dot: "application/msword",
18
+ bin: "application/octet-stream",
19
+ ai: "application/postscript",
20
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
21
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
23
+ xla: "application/vnd.ms-excel",
24
+ xls: "application/vnd.ms-excel",
25
+ xlt: "application/vnd.ms-excel",
26
+ eot: "application/vnd.ms-fontobject",
27
+ pot: "application/vnd.ms-powerpoint",
28
+ ppa: "application/vnd.ms-powerpoint",
29
+ pps: "application/vnd.ms-powerpoint",
30
+ ppt: "application/vnd.ms-powerpoint",
31
+ swf: "application/x-shockwave-flash",
32
+ atom: "application/xml",
33
+ rdf: "application/xml",
34
+ rss: "application/xml",
35
+ xml: "application/xml",
36
+ pdf: "application/&",
37
+ rtf: "application/&",
38
+ zip: "application/&",
39
+ otf: "font/opentype",
40
+ ttf: "font/&",
41
+ ttc: "font/&",
42
+ woff: "font/&",
43
+ jpe: "image/jpeg",
44
+ jpeg: "image/jpeg",
45
+ jpg: "image/jpeg",
46
+ svg: "image/svg+xml",
47
+ svgz: "image/svg+xml",
48
+ psd: "image/vnd.adobe.photoshop",
49
+ ico: "image/vnd.microsoft.icon",
50
+ bmp: "image/&",
51
+ ief: "image/&",
52
+ gif: "image/&",
53
+ png: "image/&",
54
+ tif: "image/&",
55
+ tiff: "image/&",
56
+ webp: "image/&",
57
+ appcache: "text/cache-manifest",
58
+ manifest: "text/cache-manifest",
59
+ txt: "text/plain",
60
+ htc: "text/x-component",
61
+ vcf: "text/x-vcard",
62
+ css: "text/&",
63
+ html: "text/&",
64
+ php: "text/&",
65
+ vtt: "text/&",
66
+ markdown: "text/x-&",
67
+ md: "text/x-&",
68
+ mp4: "video/mp4",
69
+ m4v: "video/mp4",
70
+ f4v: "video/mp4",
71
+ f4p: "video/mp4",
72
+ ogv: "video/ogg",
73
+ mov: "video/quicktime",
74
+ qt: "video/quicktime",
75
+ avi: "video/&",
76
+ mpg: "video/&",
77
+ vdo: "video/&",
78
+ viv: "video/&",
79
+ vivo: "video/&",
80
+ webm: "video/&",
81
+ flv: "video/x-&"
82
+ };
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ 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; }
4
+ 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) { _defineProperty(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; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
7
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8
+ const NAME = "route-manifest-plugin";
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const acornLoose = require("acorn-loose");
12
+ const zlib = require("zlib");
13
+ const generateMappingToOrigin = (pathToRoutesFile, routesVariableName) => {
14
+ const fileContent = fs.readFileSync(path.resolve(pathToRoutesFile), "utf-8");
15
+ const ast = acornLoose.parse(fileContent, {
16
+ ecmaVersion: 2020
17
+ });
18
+ const routes = [];
19
+ const componentMapping = {};
20
+ const getValue = valueObj => {
21
+ switch (valueObj.type) {
22
+ case "Literal":
23
+ return valueObj.value;
24
+ case "Identifier":
25
+ return valueObj.name;
26
+ default:
27
+ return "";
28
+ }
29
+ };
30
+ ast.body.forEach(declarationBlock => {
31
+ declarationBlock?.declarations?.forEach(variableDeclaration => {
32
+ if (variableDeclaration?.id?.name === routesVariableName) {
33
+ const objectExpression = variableDeclaration?.init?.elements;
34
+ objectExpression.forEach(obj => {
35
+ const route = {};
36
+ obj?.properties.forEach(property => {
37
+ if (property) route[property.key.name] = getValue(property.value);
38
+ });
39
+ routes.push(route);
40
+ });
41
+ }
42
+ if (variableDeclaration?.init?.type === "CallExpression" && variableDeclaration?.init?.callee?.name === "loadable") {
43
+ const componentName = variableDeclaration?.id?.name;
44
+ const importArgument = variableDeclaration?.init?.arguments?.[0]; // import is first argument in loadable;
45
+ componentMapping[componentName] = importArgument?.body?.source?.value;
46
+ }
47
+ });
48
+ });
49
+ const mappedRoutes = routes.map(route => _objectSpread(_objectSpread({}, route), {}, {
50
+ origin: componentMapping[route.component] || ""
51
+ }));
52
+ return mappedRoutes;
53
+ };
54
+ const RoutesManifestPlugin = function (options) {
55
+ this.options = options;
56
+ };
57
+ RoutesManifestPlugin.prototype.run = function (bundle, options) {
58
+ const {
59
+ pathToRoutesFile,
60
+ routesVariableName
61
+ } = options;
62
+ const mappedRoutes = generateMappingToOrigin(pathToRoutesFile, routesVariableName);
63
+ const {
64
+ publicPath,
65
+ chunks
66
+ } = bundle.getStats().toJson();
67
+ const originToChunksMapping = {};
68
+ const originToChildrenMapping = {};
69
+ chunks.forEach(chunk => {
70
+ chunk.origins.forEach(origin => {
71
+ originToChunksMapping[origin.request] = [...(originToChunksMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
72
+ chunk.children.forEach(childId => {
73
+ const chunk = chunks.find(chunk => chunk.id === childId);
74
+ originToChildrenMapping[origin.request] = [...(originToChildrenMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
75
+ });
76
+ });
77
+ });
78
+ mappedRoutes.forEach(mappedRoute => {
79
+ mappedRoute.chunks = [...new Set(originToChunksMapping[mappedRoute.origin])];
80
+ mappedRoute.children = [...new Set(originToChildrenMapping[mappedRoute.origin])];
81
+ });
82
+ return mappedRoutes;
83
+ };
84
+ RoutesManifestPlugin.prototype.apply = function (compiler) {
85
+ if (compiler.hooks !== void 0) {
86
+ compiler.hooks.emit.tap(NAME, compilation => {
87
+ const assetsMappingJson = this.run(compilation, this.options);
88
+ const stringifiedAssetsMappingJson = JSON.stringify(assetsMappingJson);
89
+ const compressedGzip = zlib.gzipSync(stringifiedAssetsMappingJson);
90
+ const compressedBrotli = zlib.brotliCompressSync(stringifiedAssetsMappingJson);
91
+ compilation.assets["route-manifest.json.gz"] = {
92
+ source: function () {
93
+ return compressedGzip;
94
+ },
95
+ size: function () {
96
+ return compressedGzip.length;
97
+ }
98
+ };
99
+ compilation.assets["route-manifest.json.br"] = {
100
+ source: function () {
101
+ return compressedBrotli;
102
+ },
103
+ size: function () {
104
+ return compressedBrotli.length;
105
+ }
106
+ };
107
+ compilation.assets["route-manifest.json"] = {
108
+ source: function () {
109
+ return stringifiedAssetsMappingJson;
110
+ },
111
+ size: function () {
112
+ return stringifiedAssetsMappingJson.length;
113
+ }
114
+ };
115
+ });
116
+ } else {
117
+ compiler.plugin("emit", bundle => {
118
+ this.run(bundle, this.options);
119
+ });
120
+ }
121
+ };
122
+ module.exports = RoutesManifestPlugin;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ 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; }
4
+ 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) { _defineProperty(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; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
7
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8
+ const NAME = "route-manifest-plugin";
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const acornLoose = require("acorn-loose");
12
+ const zlib = require("zlib");
13
+ const generateMappingToOrigin = (pathToRoutesFile, routesVariableName) => {
14
+ const fileContent = fs.readFileSync(path.resolve(pathToRoutesFile), "utf-8");
15
+ const ast = acornLoose.parse(fileContent, {
16
+ ecmaVersion: 2020
17
+ });
18
+ const routes = [];
19
+ const componentMapping = {};
20
+ const getValue = valueObj => {
21
+ switch (valueObj.type) {
22
+ case "Literal":
23
+ return valueObj.value;
24
+ case "Identifier":
25
+ return valueObj.name;
26
+ default:
27
+ return "";
28
+ }
29
+ };
30
+ ast.body.forEach(declarationBlock => {
31
+ declarationBlock?.declarations?.forEach(variableDeclaration => {
32
+ if (variableDeclaration?.id?.name === routesVariableName) {
33
+ const objectExpression = variableDeclaration?.init?.elements;
34
+ objectExpression.forEach(obj => {
35
+ const route = {};
36
+ obj?.properties.forEach(property => {
37
+ if (property) route[property.key.name] = getValue(property.value);
38
+ });
39
+ routes.push(route);
40
+ });
41
+ }
42
+ if (variableDeclaration?.init?.type === "CallExpression" && variableDeclaration?.init?.callee?.name === "loadable") {
43
+ const componentName = variableDeclaration?.id?.name;
44
+ const importArgument = variableDeclaration?.init?.arguments?.[0]; // import is first argument in loadable;
45
+ componentMapping[componentName] = importArgument?.body?.source?.value;
46
+ }
47
+ });
48
+ });
49
+ const mappedRoutes = routes.map(route => _objectSpread(_objectSpread({}, route), {}, {
50
+ origin: componentMapping[route.component] || ""
51
+ }));
52
+ return mappedRoutes;
53
+ };
54
+ const RoutesManifestPlugin = function (options) {
55
+ this.options = options;
56
+ };
57
+ RoutesManifestPlugin.prototype.run = function (bundle, options) {
58
+ const {
59
+ pathToRoutesFile,
60
+ routesVariableName
61
+ } = options;
62
+ const mappedRoutes = generateMappingToOrigin(pathToRoutesFile, routesVariableName);
63
+ const {
64
+ publicPath,
65
+ chunks
66
+ } = bundle.getStats().toJson();
67
+ const originToChunksMapping = {};
68
+ const originToChildrenMapping = {};
69
+ chunks.forEach(chunk => {
70
+ chunk.origins.forEach(origin => {
71
+ originToChunksMapping[origin.request] = [...(originToChunksMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
72
+ chunk.children.forEach(childId => {
73
+ const chunk = chunks.find(chunk => chunk.id === childId);
74
+ originToChildrenMapping[origin.request] = [...(originToChildrenMapping[origin.request] || []), ...chunk.files.map(file => `${publicPath}${file}`)];
75
+ });
76
+ });
77
+ });
78
+ mappedRoutes.forEach(mappedRoute => {
79
+ mappedRoute.chunks = [...new Set(originToChunksMapping[mappedRoute.origin])];
80
+ mappedRoute.children = [...new Set(originToChildrenMapping[mappedRoute.origin])];
81
+ });
82
+ return mappedRoutes;
83
+ };
84
+ RoutesManifestPlugin.prototype.apply = function (compiler) {
85
+ if (compiler.hooks !== void 0) {
86
+ compiler.hooks.emit.tap(NAME, compilation => {
87
+ const assetsMappingJson = this.run(compilation, this.options);
88
+ const stringifiedAssetsMappingJson = JSON.stringify(assetsMappingJson);
89
+ const compressedGzip = zlib.gzipSync(stringifiedAssetsMappingJson);
90
+ const compressedBrotli = zlib.brotliCompressSync(stringifiedAssetsMappingJson);
91
+ compilation.assets["route-manifest.json.gz"] = {
92
+ source: function () {
93
+ return compressedGzip;
94
+ },
95
+ size: function () {
96
+ return compressedGzip.length;
97
+ }
98
+ };
99
+ compilation.assets["route-manifest.json.br"] = {
100
+ source: function () {
101
+ return compressedBrotli;
102
+ },
103
+ size: function () {
104
+ return compressedBrotli.length;
105
+ }
106
+ };
107
+ compilation.assets["route-manifest.json"] = {
108
+ source: function () {
109
+ return stringifiedAssetsMappingJson;
110
+ },
111
+ size: function () {
112
+ return stringifiedAssetsMappingJson.length;
113
+ }
114
+ };
115
+ });
116
+ } else {
117
+ compiler.plugin("emit", bundle => {
118
+ this.run(bundle, this.options);
119
+ });
120
+ }
121
+ };
122
+ module.exports = RoutesManifestPlugin;