@modern-js/utils 2.26.0 → 2.27.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (86) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cjs/universal/formatWebpack.js +0 -4
  3. package/dist/esm/cli/alias.js +26 -22
  4. package/dist/esm/cli/applyOptionsChain.js +8 -6
  5. package/dist/esm/cli/babel.js +50 -35
  6. package/dist/esm/cli/commands.js +7 -7
  7. package/dist/esm/cli/common.js +10 -5
  8. package/dist/esm/cli/constants/chainId.js +1 -1
  9. package/dist/esm/cli/constants/index.js +33 -37
  10. package/dist/esm/cli/ensure.js +4 -2
  11. package/dist/esm/cli/fs.js +56 -9
  12. package/dist/esm/cli/get/config.js +7 -7
  13. package/dist/esm/cli/get/data.js +93 -55
  14. package/dist/esm/cli/get/index.js +21 -6
  15. package/dist/esm/cli/is/config.js +33 -14
  16. package/dist/esm/cli/is/env.js +18 -6
  17. package/dist/esm/cli/is/platform.js +6 -2
  18. package/dist/esm/cli/is/project.js +73 -36
  19. package/dist/esm/cli/is/type.js +3 -1
  20. package/dist/esm/cli/logger.js +49 -38
  21. package/dist/esm/cli/monorepo.js +49 -36
  22. package/dist/esm/cli/package.js +156 -38
  23. package/dist/esm/cli/path.js +44 -20
  24. package/dist/esm/cli/pathSerializer.js +29 -15
  25. package/dist/esm/cli/port.js +89 -40
  26. package/dist/esm/cli/prettyInstructions.js +42 -31
  27. package/dist/esm/cli/require.js +21 -16
  28. package/dist/esm/cli/runtimeExports.js +21 -15
  29. package/dist/esm/cli/watch.js +94 -27
  30. package/dist/esm/compiled.js +3 -3
  31. package/dist/esm/import.js +4 -4
  32. package/dist/esm/runtime/nestedRoutes.js +42 -29
  33. package/dist/esm/runtime-browser/parsed.js +5 -5
  34. package/dist/esm/runtime-node/index.js +1 -1
  35. package/dist/esm/runtime-node/nestedRoutes.js +6 -4
  36. package/dist/esm/runtime-node/serialize.js +1 -1
  37. package/dist/esm/runtime-node/storage.js +12 -14
  38. package/dist/esm/universal/constants.js +3 -3
  39. package/dist/esm/universal/formatWebpack.js +20 -26
  40. package/dist/esm/universal/pluginDagSort.js +49 -26
  41. package/dist/esm-node/cli/alias.js +51 -0
  42. package/dist/esm-node/cli/applyOptionsChain.js +24 -0
  43. package/dist/esm-node/cli/babel.js +103 -0
  44. package/dist/esm-node/cli/commands.js +16 -0
  45. package/dist/esm-node/cli/common.js +10 -0
  46. package/dist/esm-node/cli/constants/chainId.js +180 -0
  47. package/dist/esm-node/cli/constants/index.js +103 -0
  48. package/dist/esm-node/cli/ensure.js +10 -0
  49. package/dist/esm-node/cli/fs.js +14 -0
  50. package/dist/esm-node/cli/get/config.js +16 -0
  51. package/dist/esm-node/cli/get/data.js +86 -0
  52. package/dist/esm-node/cli/get/index.js +13 -0
  53. package/dist/esm-node/cli/index.js +20 -0
  54. package/dist/esm-node/cli/is/config.js +40 -0
  55. package/dist/esm-node/cli/is/env.js +6 -0
  56. package/dist/esm-node/cli/is/index.js +5 -0
  57. package/dist/esm-node/cli/is/platform.js +2 -0
  58. package/dist/esm-node/cli/is/project.js +73 -0
  59. package/dist/esm-node/cli/is/type.js +25 -0
  60. package/dist/esm-node/cli/logger.js +103 -0
  61. package/dist/esm-node/cli/monorepo.js +70 -0
  62. package/dist/esm-node/cli/package.js +43 -0
  63. package/dist/esm-node/cli/path.js +49 -0
  64. package/dist/esm-node/cli/pathSerializer.js +46 -0
  65. package/dist/esm-node/cli/port.js +44 -0
  66. package/dist/esm-node/cli/prettyInstructions.js +77 -0
  67. package/dist/esm-node/cli/require.js +52 -0
  68. package/dist/esm-node/cli/runtimeExports.js +35 -0
  69. package/dist/esm-node/cli/watch.js +41 -0
  70. package/dist/esm-node/compiled.js +33 -0
  71. package/dist/esm-node/import.js +8 -0
  72. package/dist/esm-node/index.js +3 -0
  73. package/dist/esm-node/runtime/nestedRoutes.js +112 -0
  74. package/dist/esm-node/runtime/remixRouter.js +1 -0
  75. package/dist/esm-node/runtime/router.js +1 -0
  76. package/dist/esm-node/runtime-browser/index.js +1 -0
  77. package/dist/esm-node/runtime-browser/parsed.js +17 -0
  78. package/dist/esm-node/runtime-node/index.js +5 -0
  79. package/dist/esm-node/runtime-node/nestedRoutes.js +18 -0
  80. package/dist/esm-node/runtime-node/router.js +1 -0
  81. package/dist/esm-node/runtime-node/serialize.js +6 -0
  82. package/dist/esm-node/runtime-node/storage.js +38 -0
  83. package/dist/esm-node/universal/constants.js +3 -0
  84. package/dist/esm-node/universal/formatWebpack.js +61 -0
  85. package/dist/esm-node/universal/pluginDagSort.js +50 -0
  86. package/package.json +4 -4
@@ -0,0 +1,77 @@
1
+ import os from "os";
2
+ import { chalk } from "../compiled";
3
+ import { isDev, isSingleEntry } from "./is";
4
+ import { DEFAULT_DEV_HOST } from "./constants";
5
+ const normalizeUrl = (url) => url.replace(/([^:]\/)\/+/g, "$1");
6
+ const getIpv4Interfaces = () => {
7
+ const interfaces = os.networkInterfaces();
8
+ const ipv4Interfaces = [];
9
+ Object.keys(interfaces).forEach((key) => {
10
+ interfaces[key].forEach((detail) => {
11
+ const familyV4Value = typeof detail.family === "string" ? "IPv4" : 4;
12
+ if (detail.family === familyV4Value) {
13
+ ipv4Interfaces.push(detail);
14
+ }
15
+ });
16
+ });
17
+ return ipv4Interfaces;
18
+ };
19
+ export const getAddressUrls = (protocol = "http", port, host) => {
20
+ const LOCAL_LABEL = "Local: ";
21
+ const NETWORK_LABEL = "Network: ";
22
+ const isLocalhost = (url) => {
23
+ return url === null || url === void 0 ? void 0 : url.includes("localhost");
24
+ };
25
+ if (host && host !== DEFAULT_DEV_HOST) {
26
+ return [
27
+ {
28
+ label: isLocalhost(host) ? LOCAL_LABEL : NETWORK_LABEL,
29
+ url: `${protocol}://${host}:${port}`
30
+ }
31
+ ];
32
+ }
33
+ const ipv4Interfaces = getIpv4Interfaces();
34
+ return ipv4Interfaces.reduce((memo, detail) => {
35
+ if (isLocalhost(detail.address) || detail.internal) {
36
+ memo.push({
37
+ label: LOCAL_LABEL,
38
+ url: `${protocol}://localhost:${port}`
39
+ });
40
+ } else {
41
+ memo.push({
42
+ label: NETWORK_LABEL,
43
+ url: `${protocol}://${detail.address}:${port}`
44
+ });
45
+ }
46
+ return memo;
47
+ }, []);
48
+ };
49
+ export const prettyInstructions = (appContext, config) => {
50
+ var _appContext_builder_context_devServer, _appContext_builder, _config_dev;
51
+ const { entrypoints, serverRoutes, port, apiOnly, checkedEntries } = appContext;
52
+ const isHttps = isDev() && ((_appContext_builder_context_devServer = (_appContext_builder = appContext.builder) === null || _appContext_builder === void 0 ? void 0 : _appContext_builder.context.devServer) === null || _appContext_builder_context_devServer === void 0 ? void 0 : _appContext_builder_context_devServer.https);
53
+ const urls = getAddressUrls(isHttps ? "https" : "http", port, (_config_dev = config.dev) === null || _config_dev === void 0 ? void 0 : _config_dev.host);
54
+ const routes = !apiOnly ? serverRoutes.filter((route) => route.entryName) : serverRoutes;
55
+ let message = "App running at:\n\n";
56
+ if (isSingleEntry(entrypoints) || apiOnly) {
57
+ message += urls.map(({ label, url }) => ` ${chalk.bold(`> ${label.padEnd(10)}`)}${chalk.cyanBright(normalizeUrl(`${url}/${routes[0].urlPath}`))}
58
+ `).join("");
59
+ } else {
60
+ const maxNameLength = Math.max(...routes.map((r) => r.entryName.length));
61
+ urls.forEach(({ label, url }) => {
62
+ message += ` ${chalk.bold(`> ${label}`)}
63
+ `;
64
+ routes.forEach(({ entryName, urlPath, isSSR }) => {
65
+ if (!checkedEntries.includes(entryName)) {
66
+ return;
67
+ }
68
+ message += ` ${chalk.yellowBright(isSSR ? "λ" : "○")} ${chalk.yellowBright(entryName.padEnd(maxNameLength + 8))}${chalk.cyanBright(normalizeUrl(`${url}/${urlPath}`))}
69
+ `;
70
+ });
71
+ });
72
+ message += "\n";
73
+ message += chalk.cyanBright(" λ (Server) server-side renders at runtime\n");
74
+ message += chalk.cyanBright(" ○ (Static) client-side renders as static HTML\n");
75
+ }
76
+ return message;
77
+ };
@@ -0,0 +1,52 @@
1
+ import { findExists } from "./fs";
2
+ export const compatRequire = (filePath, interop = true) => {
3
+ const mod = require(filePath);
4
+ const rtnESMDefault = interop && (mod === null || mod === void 0 ? void 0 : mod.__esModule);
5
+ return rtnESMDefault ? mod.default : mod;
6
+ };
7
+ export const dynamicImport = new Function("modulePath", "return import(modulePath)");
8
+ export const requireExistModule = (filename, opt) => {
9
+ const final = {
10
+ extensions: [
11
+ ".ts",
12
+ ".js"
13
+ ],
14
+ interop: true,
15
+ ...opt
16
+ };
17
+ const exist = findExists(final.extensions.map((ext) => `${filename}${ext}`));
18
+ if (!exist) {
19
+ return null;
20
+ }
21
+ return compatRequire(exist, final.interop);
22
+ };
23
+ export const cleanRequireCache = (filelist) => {
24
+ filelist.forEach((filepath) => {
25
+ delete require.cache[filepath];
26
+ });
27
+ };
28
+ export function deleteRequireCache(path) {
29
+ if (require.cache[path]) {
30
+ delete require.cache[path];
31
+ }
32
+ if (module.children) {
33
+ module.children = module.children.filter((item) => item.filename !== path);
34
+ }
35
+ }
36
+ export const tryResolve = (name, resolvePath) => {
37
+ let filePath = "";
38
+ try {
39
+ filePath = require.resolve(name, {
40
+ paths: [
41
+ resolvePath
42
+ ]
43
+ });
44
+ delete require.cache[filePath];
45
+ } catch (err) {
46
+ if (err.code === "MODULE_NOT_FOUND") {
47
+ throw new Error(`Can not find module ${name}.`);
48
+ }
49
+ throw err;
50
+ }
51
+ return filePath;
52
+ };
@@ -0,0 +1,35 @@
1
+ import path from "path";
2
+ import { fs } from "../compiled";
3
+ import { normalizeOutputPath } from "./path";
4
+ const memo = (fn) => {
5
+ const cache = /* @__PURE__ */ new Map();
6
+ return (...params) => {
7
+ const stringifiedParams = JSON.stringify(params);
8
+ const cachedResult = cache.get(stringifiedParams);
9
+ if (cachedResult) {
10
+ return cachedResult;
11
+ }
12
+ const res = fn(...params);
13
+ cache.set(stringifiedParams, res);
14
+ return res;
15
+ };
16
+ };
17
+ export const createRuntimeExportsUtils = memo((pwd = "", namespace = "index") => {
18
+ const entryExportFile = path.join(pwd, `.runtime-exports/${namespace}.js`);
19
+ const addExport = (statement) => {
20
+ statement = normalizeOutputPath(statement);
21
+ try {
22
+ fs.ensureFileSync(entryExportFile);
23
+ if (!fs.readFileSync(entryExportFile, "utf8").includes(statement)) {
24
+ fs.appendFileSync(entryExportFile, `${statement}
25
+ `);
26
+ }
27
+ } catch {
28
+ }
29
+ };
30
+ const getPath = () => entryExportFile;
31
+ return {
32
+ addExport,
33
+ getPath
34
+ };
35
+ });
@@ -0,0 +1,41 @@
1
+ import path from "path";
2
+ import { chokidar } from "../compiled";
3
+ export const WatchChangeType = {
4
+ ADD: "add",
5
+ UNLINK: "unlink",
6
+ CHANGE: "change"
7
+ };
8
+ export const watch = (watchDir, runTask, ignored = []) => {
9
+ let ready = false;
10
+ const watcher = chokidar.watch(watchDir, {
11
+ ignored
12
+ });
13
+ watcher.on("ready", () => ready = true);
14
+ watcher.on("change", async (filePath) => {
15
+ const changedFilePath = path.resolve(filePath);
16
+ await runTask({
17
+ changedFilePath,
18
+ changeType: WatchChangeType.CHANGE
19
+ });
20
+ });
21
+ watcher.on("add", async (filePath) => {
22
+ const changedFilePath = path.resolve(filePath);
23
+ if (ready) {
24
+ await runTask({
25
+ changedFilePath,
26
+ changeType: WatchChangeType.ADD
27
+ });
28
+ }
29
+ });
30
+ watcher.on("unlink", async (filePath) => {
31
+ const changedFilePath = path.resolve(filePath);
32
+ await runTask({
33
+ changedFilePath,
34
+ changeType: WatchChangeType.UNLINK
35
+ });
36
+ });
37
+ watcher.on("error", (err) => {
38
+ throw err;
39
+ });
40
+ return watcher;
41
+ };
@@ -0,0 +1,33 @@
1
+ import { Import } from "./import";
2
+ export { default as fs } from "../compiled/fs-extra";
3
+ export { default as ora } from "../compiled/ora";
4
+ export { default as glob } from "../compiled/glob";
5
+ export { default as yaml } from "../compiled/js-yaml";
6
+ export { default as chalk } from "../compiled/chalk";
7
+ export { default as debug } from "../compiled/debug";
8
+ export { default as slash } from "../compiled/slash";
9
+ export { default as execa } from "../compiled/execa";
10
+ export { default as json5 } from "../compiled/json5";
11
+ export { default as upath } from "../compiled/upath";
12
+ export { default as pkgUp } from "../compiled/pkg-up";
13
+ export { nanoid } from "../compiled/nanoid";
14
+ export { default as semver } from "../compiled/semver";
15
+ export { default as dotenv } from "../compiled/dotenv";
16
+ export { default as lodash } from "../compiled/lodash";
17
+ export { default as globby } from "../compiled/globby";
18
+ export { default as address } from "../compiled/address";
19
+ export { default as signale } from "../compiled/signale";
20
+ export { default as urlJoin } from "../compiled/url-join";
21
+ export { default as minimist } from "../compiled/minimist";
22
+ export { default as fastGlob } from "../compiled/fast-glob";
23
+ export { default as filesize } from "../compiled/filesize";
24
+ export { default as gzipSize } from "../compiled/gzip-size";
25
+ export { default as stripAnsi } from "../compiled/strip-ansi";
26
+ export { default as dotenvExpand } from "../compiled/dotenv-expand";
27
+ export { default as browserslist } from "../compiled/browserslist";
28
+ export { default as recursiveReaddir } from "../compiled/recursive-readdir";
29
+ export { program, Command } from "../compiled/commander";
30
+ export { Signale } from "../compiled/signale";
31
+ export const mime = Import.lazy("../compiled/mime-types", require);
32
+ export const chokidar = Import.lazy("../compiled/chokidar", require);
33
+ export const inquirer = Import.lazy("../compiled/inquirer", require);
@@ -0,0 +1,8 @@
1
+ const lazy = (moduleName, requireFn) => {
2
+ const importLazyLocal = require("../compiled/import-lazy")(requireFn);
3
+ return importLazyLocal(moduleName);
4
+ };
5
+ export { lazy as lazyImport };
6
+ export const Import = {
7
+ lazy
8
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./compiled";
2
+ export * from "./cli";
3
+ export * from "./import";
@@ -0,0 +1,112 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Suspense } from "react";
3
+ import { createRoutesFromElements, Route } from "react-router-dom";
4
+ export const transformNestedRoutes = (routes) => {
5
+ const routeElements = [];
6
+ for (const route of routes) {
7
+ const routeElement = renderNestedRoute(route);
8
+ routeElements.push(routeElement);
9
+ }
10
+ return createRoutesFromElements(routeElements);
11
+ };
12
+ export const renderNestedRoute = (nestedRoute, options = {}) => {
13
+ const { children, index, id, component, isRoot, lazyImport, config, handle } = nestedRoute;
14
+ const Component = component;
15
+ const { parent, DeferredDataComponent, props = {} } = options;
16
+ const routeProps = {
17
+ caseSensitive: nestedRoute.caseSensitive,
18
+ path: nestedRoute.path,
19
+ id: nestedRoute.id,
20
+ loader: createLoader(nestedRoute),
21
+ action: nestedRoute.action,
22
+ hasErrorBoundary: nestedRoute.hasErrorBoundary,
23
+ shouldRevalidate: nestedRoute.shouldRevalidate,
24
+ handle: {
25
+ ...handle,
26
+ ...typeof config === "object" ? config === null || config === void 0 ? void 0 : config.handle : {}
27
+ },
28
+ index: nestedRoute.index,
29
+ element: nestedRoute.element,
30
+ errorElement: nestedRoute.errorElement
31
+ };
32
+ if (nestedRoute.error) {
33
+ const errorElement = /* @__PURE__ */ _jsx(nestedRoute.error, {});
34
+ routeProps.errorElement = errorElement;
35
+ }
36
+ let element;
37
+ if (Component) {
38
+ if ((parent === null || parent === void 0 ? void 0 : parent.loading) && lazyImport) {
39
+ const Loading = parent.loading;
40
+ if (isLoadableComponent(Component)) {
41
+ element = /* @__PURE__ */ _jsx(Component, {
42
+ fallback: /* @__PURE__ */ _jsx(Loading, {})
43
+ });
44
+ } else {
45
+ element = /* @__PURE__ */ _jsx(Suspense, {
46
+ fallback: /* @__PURE__ */ _jsx(Loading, {}),
47
+ children: /* @__PURE__ */ _jsx(Component, {})
48
+ });
49
+ }
50
+ } else if (isLoadableComponent(Component) && lazyImport) {
51
+ element = /* @__PURE__ */ _jsx(Component, {});
52
+ } else if (isRoot) {
53
+ element = /* @__PURE__ */ _jsxs(_Fragment, {
54
+ children: [
55
+ /* @__PURE__ */ _jsx(Component, {
56
+ ...props
57
+ }),
58
+ typeof document === "undefined" && DeferredDataComponent && /* @__PURE__ */ _jsx(DeferredDataComponent, {
59
+ nonce: props === null || props === void 0 ? void 0 : props.nonce
60
+ })
61
+ ]
62
+ });
63
+ } else if (lazyImport) {
64
+ element = /* @__PURE__ */ _jsx(Suspense, {
65
+ fallback: null,
66
+ children: /* @__PURE__ */ _jsx(Component, {})
67
+ });
68
+ } else {
69
+ element = /* @__PURE__ */ _jsx(Component, {});
70
+ }
71
+ } else {
72
+ nestedRoute.loading = parent === null || parent === void 0 ? void 0 : parent.loading;
73
+ }
74
+ if (element) {
75
+ routeProps.element = element;
76
+ }
77
+ const childElements = children === null || children === void 0 ? void 0 : children.map((childRoute) => {
78
+ return renderNestedRoute(childRoute, {
79
+ parent: nestedRoute
80
+ });
81
+ });
82
+ const routeElement = index ? /* @__PURE__ */ _jsx(Route, {
83
+ ...routeProps,
84
+ index: true
85
+ }, id) : /* @__PURE__ */ _jsx(Route, {
86
+ ...routeProps,
87
+ index: false,
88
+ children: childElements
89
+ }, id);
90
+ return routeElement;
91
+ };
92
+ function createLoader(route) {
93
+ const { loader } = route;
94
+ if (loader) {
95
+ return (args) => {
96
+ if (typeof route.lazyImport === "function") {
97
+ route.lazyImport();
98
+ }
99
+ return loader(args);
100
+ };
101
+ } else {
102
+ return () => {
103
+ if (typeof route.lazyImport === "function") {
104
+ route.lazyImport();
105
+ }
106
+ return null;
107
+ };
108
+ }
109
+ }
110
+ function isLoadableComponent(component) {
111
+ return component && component.displayName === "Loadable" && component.preload && typeof component.preload === "function";
112
+ }
@@ -0,0 +1 @@
1
+ export * from "@remix-run/router";
@@ -0,0 +1 @@
1
+ export * from "react-router-dom";
@@ -0,0 +1 @@
1
+ export * from "./parsed";
@@ -0,0 +1,17 @@
1
+ export const parsedJSONFromElement = (id) => {
2
+ const elements = document.querySelectorAll(`#${id}`);
3
+ if (elements.length === 0) {
4
+ return void 0;
5
+ }
6
+ const element = elements[elements.length - 1];
7
+ if (element) {
8
+ try {
9
+ const parsed = JSON.parse((element === null || element === void 0 ? void 0 : element.textContent) || "");
10
+ return parsed;
11
+ } catch (e) {
12
+ console.error(`parse ${id} error`, e);
13
+ return void 0;
14
+ }
15
+ }
16
+ return void 0;
17
+ };
@@ -0,0 +1,5 @@
1
+ import { createStorage } from "./storage";
2
+ const { run, useContext: useHeaders } = createStorage();
3
+ export { run, useHeaders };
4
+ export { serializeJson } from "./serialize";
5
+ export * from "./nestedRoutes";
@@ -0,0 +1,18 @@
1
+ function sortByUrlPath(entries) {
2
+ entries.sort(function(a, b) {
3
+ const length1 = a.urlPath.length;
4
+ const length2 = b.urlPath.length;
5
+ if (length1 < length2) {
6
+ return 1;
7
+ }
8
+ if (length1 > length2) {
9
+ return -1;
10
+ }
11
+ return 0;
12
+ });
13
+ return entries;
14
+ }
15
+ export const matchEntry = (pathname, entries) => {
16
+ sortByUrlPath(entries);
17
+ return entries.find((entry) => pathname.startsWith(entry.urlPath));
18
+ };
@@ -0,0 +1 @@
1
+ export * from "react-router-dom/server";
@@ -0,0 +1,6 @@
1
+ import serialize from "serialize-javascript";
2
+ export const serializeJson = (data) => {
3
+ return serialize(data, {
4
+ isJSON: true
5
+ });
6
+ };
@@ -0,0 +1,38 @@
1
+ import * as ah from "async_hooks";
2
+ const createStorage = () => {
3
+ let storage;
4
+ if (typeof ah.AsyncLocalStorage !== "undefined") {
5
+ storage = new ah.AsyncLocalStorage();
6
+ }
7
+ const run = (context, cb) => {
8
+ if (!storage) {
9
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
10
+ `);
11
+ }
12
+ return new Promise((resolve, reject) => {
13
+ storage.run(context, () => {
14
+ try {
15
+ return resolve(cb());
16
+ } catch (error) {
17
+ return reject(error);
18
+ }
19
+ });
20
+ });
21
+ };
22
+ const useContext = () => {
23
+ if (!storage) {
24
+ throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
25
+ `);
26
+ }
27
+ const context = storage.getStore();
28
+ if (!context) {
29
+ throw new Error(`Can't call useContext out of scope, make sure @modern-js/utils is a single version in node_modules`);
30
+ }
31
+ return context;
32
+ };
33
+ return {
34
+ run,
35
+ useContext
36
+ };
37
+ };
38
+ export { createStorage };
@@ -0,0 +1,3 @@
1
+ export const ROUTE_MANIFEST = `_MODERNJS_ROUTE_MANIFEST`;
2
+ export const HMR_SOCK_PATH = "/webpack-hmr";
3
+ export const HTML_CHUNKSMAP_SEPARATOR = "<!--<?- chunksMap.js ?>-->";
@@ -0,0 +1,61 @@
1
+ const friendlySyntaxErrorLabel = "SyntaxError:";
2
+ function isLikelyASyntaxError(message) {
3
+ return message.includes(friendlySyntaxErrorLabel);
4
+ }
5
+ function formatMessage(stats) {
6
+ let lines = [];
7
+ let message;
8
+ if (typeof stats === "object") {
9
+ const fileName = stats.moduleName ? `File: ${stats.moduleName}
10
+ ` : "";
11
+ const mainMessage = typeof stats.formatted === "string" ? stats.formatted : stats.message;
12
+ const details = stats.details ? `
13
+ Details: ${stats.details}
14
+ ` : "";
15
+ const stack = stats.stack ? `
16
+ ${stats.stack}` : "";
17
+ message = `${fileName}${mainMessage}${details}${stack}`;
18
+ } else {
19
+ message = stats;
20
+ }
21
+ lines = message.split("\n");
22
+ lines = lines.map((line) => {
23
+ const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line);
24
+ if (!parsingError) {
25
+ return line;
26
+ }
27
+ const [, errorLine, errorColumn, errorMessage] = parsingError;
28
+ return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
29
+ });
30
+ message = lines.join("\n");
31
+ message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)
32
+ `);
33
+ lines = message.split("\n");
34
+ if (lines.length > 2 && lines[1].trim() === "") {
35
+ lines.splice(1, 1);
36
+ }
37
+ lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, "$1");
38
+ if (lines[1] && lines[1].indexOf("Module not found:") !== -1) {
39
+ lines[1] = lines[1].replace("Error: ", "");
40
+ }
41
+ lines = lines.filter((line, index, arr) => index === 0 || line.trim() !== "" || line.trim() !== arr[index - 1].trim());
42
+ message = lines.join("\n");
43
+ return message.trim();
44
+ }
45
+ function formatWebpackMessages(json) {
46
+ var _json_errors, _json_warnings, _result_errors;
47
+ const formattedErrors = json === null || json === void 0 ? void 0 : (_json_errors = json.errors) === null || _json_errors === void 0 ? void 0 : _json_errors.map(formatMessage);
48
+ const formattedWarnings = json === null || json === void 0 ? void 0 : (_json_warnings = json.warnings) === null || _json_warnings === void 0 ? void 0 : _json_warnings.map(formatMessage);
49
+ const result = {
50
+ errors: formattedErrors || [],
51
+ warnings: formattedWarnings || []
52
+ };
53
+ if ((_result_errors = result.errors) === null || _result_errors === void 0 ? void 0 : _result_errors.some(isLikelyASyntaxError)) {
54
+ result.errors = result.errors.filter(isLikelyASyntaxError);
55
+ }
56
+ if (result.errors.length > 1) {
57
+ result.errors.length = 1;
58
+ }
59
+ return result;
60
+ }
61
+ export { formatWebpackMessages };
@@ -0,0 +1,50 @@
1
+ export const pluginDagSort = (plugins, key = "name", preKey = "pre", postKey = "post") => {
2
+ let allLines = [];
3
+ function getPluginByAny(q) {
4
+ const target = plugins.find((item) => typeof q === "string" ? item[key] === q : item[key] === q[key]);
5
+ if (!target) {
6
+ throw new Error(`plugin ${q} not existed`);
7
+ }
8
+ return target;
9
+ }
10
+ plugins.forEach((item) => {
11
+ var _item_preKey, _item_postKey;
12
+ (_item_preKey = item[preKey]) === null || _item_preKey === void 0 ? void 0 : _item_preKey.forEach((p) => {
13
+ if (plugins.find((ap) => ap.name === p)) {
14
+ allLines.push([
15
+ getPluginByAny(p)[key],
16
+ getPluginByAny(item)[key]
17
+ ]);
18
+ }
19
+ });
20
+ (_item_postKey = item[postKey]) === null || _item_postKey === void 0 ? void 0 : _item_postKey.forEach((pt) => {
21
+ if (plugins.find((ap) => ap.name === pt)) {
22
+ allLines.push([
23
+ getPluginByAny(item)[key],
24
+ getPluginByAny(pt)[key]
25
+ ]);
26
+ }
27
+ });
28
+ });
29
+ let zeroEndPoints = plugins.filter((item) => !allLines.find((l) => l[1] === item[key]));
30
+ const sortedPoint = [];
31
+ while (zeroEndPoints.length) {
32
+ const zep = zeroEndPoints.shift();
33
+ sortedPoint.push(getPluginByAny(zep));
34
+ allLines = allLines.filter((l) => l[0] !== getPluginByAny(zep)[key]);
35
+ const restPoints = plugins.filter((item) => !sortedPoint.find((sp) => sp[key] === item[key]));
36
+ zeroEndPoints = restPoints.filter(
37
+ // eslint-disable-next-line @typescript-eslint/no-loop-func
38
+ (item) => !allLines.find((l) => l[1] === item[key])
39
+ );
40
+ }
41
+ if (allLines.length) {
42
+ const restInRingPoints = {};
43
+ allLines.forEach((l) => {
44
+ restInRingPoints[l[0]] = true;
45
+ restInRingPoints[l[1]] = true;
46
+ });
47
+ throw new Error(`plugins dependences has loop: ${Object.keys(restInRingPoints).join(",")}`);
48
+ }
49
+ return sortedPoint;
50
+ };
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "modern",
16
16
  "modern.js"
17
17
  ],
18
- "version": "2.26.0",
18
+ "version": "2.27.0",
19
19
  "jsnext:source": "./src/index.ts",
20
20
  "types": "./dist/types/index.d.ts",
21
21
  "main": "./dist/cjs/index.js",
@@ -235,9 +235,9 @@
235
235
  "typescript": "^5",
236
236
  "webpack": "^5.88.1",
237
237
  "@types/serialize-javascript": "^5.0.1",
238
- "@modern-js/types": "2.26.0",
239
- "@scripts/jest-config": "2.26.0",
240
- "@scripts/build": "2.26.0"
238
+ "@modern-js/types": "2.27.0",
239
+ "@scripts/jest-config": "2.27.0",
240
+ "@scripts/build": "2.27.0"
241
241
  },
242
242
  "sideEffects": false,
243
243
  "scripts": {