@rsdoctor/utils 1.1.9 → 1.2.0-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 (151) hide show
  1. package/dist/cjs/build/envinfo.js +107 -95
  2. package/dist/cjs/build/file/cache.js +65 -56
  3. package/dist/cjs/build/file/index.js +78 -41
  4. package/dist/cjs/build/file/sharding.js +90 -78
  5. package/dist/cjs/build/index.js +49 -47
  6. package/dist/cjs/build/json.js +91 -98
  7. package/dist/cjs/build/process.js +47 -42
  8. package/dist/cjs/build/server.js +110 -87
  9. package/dist/cjs/common/alerts.js +46 -44
  10. package/dist/cjs/common/algorithm.js +63 -54
  11. package/dist/cjs/common/bundle.js +52 -46
  12. package/dist/cjs/common/crypto.js +47 -46
  13. package/dist/cjs/common/data/index.js +381 -455
  14. package/dist/cjs/common/file.js +44 -0
  15. package/dist/cjs/common/global-config.js +72 -64
  16. package/dist/cjs/common/graph/assets.js +274 -308
  17. package/dist/cjs/common/graph/chunk.js +66 -63
  18. package/dist/cjs/common/graph/dependency.js +42 -32
  19. package/dist/cjs/common/graph/entrypoints.js +33 -25
  20. package/dist/cjs/common/graph/index.js +93 -27
  21. package/dist/cjs/common/graph/modules.js +113 -98
  22. package/dist/cjs/common/index.js +101 -83
  23. package/dist/cjs/common/loader.js +277 -273
  24. package/dist/cjs/common/lodash.js +73 -62
  25. package/dist/cjs/common/manifest.js +57 -59
  26. package/dist/cjs/common/package.js +79 -80
  27. package/dist/cjs/common/plugin.js +78 -73
  28. package/dist/cjs/common/resolver.js +79 -69
  29. package/dist/cjs/common/rspack.js +43 -34
  30. package/dist/cjs/common/summary.js +39 -31
  31. package/dist/cjs/common/time.js +73 -78
  32. package/dist/cjs/common/url.js +44 -36
  33. package/dist/cjs/error/error.js +183 -220
  34. package/dist/cjs/error/index.js +70 -28
  35. package/dist/cjs/error/transform.js +150 -143
  36. package/dist/cjs/error/utils.js +54 -58
  37. package/dist/cjs/index.js +37 -38
  38. package/dist/cjs/logger.js +99 -73
  39. package/dist/cjs/rule-utils/document/document.js +83 -82
  40. package/dist/cjs/rule-utils/document/index.js +75 -23
  41. package/dist/cjs/rule-utils/document/server.js +42 -35
  42. package/dist/cjs/rule-utils/document/types.js +17 -15
  43. package/dist/cjs/rule-utils/index.js +66 -21
  44. package/dist/cjs/rule-utils/parser/asserts.js +129 -147
  45. package/dist/cjs/rule-utils/parser/index.js +84 -25
  46. package/dist/cjs/rule-utils/parser/parser.js +50 -85
  47. package/dist/cjs/rule-utils/parser/types.js +38 -30
  48. package/dist/cjs/rule-utils/parser/utils.js +141 -168
  49. package/dist/esm/build/envinfo.mjs +57 -0
  50. package/dist/esm/build/file/cache.mjs +23 -0
  51. package/dist/esm/build/file/index.mjs +4 -0
  52. package/dist/esm/build/file/sharding.mjs +50 -0
  53. package/dist/esm/build/index.mjs +6 -0
  54. package/dist/esm/build/json.mjs +66 -0
  55. package/dist/esm/build/process.mjs +17 -0
  56. package/dist/esm/build/server.mjs +96 -0
  57. package/dist/esm/common/alerts.mjs +17 -0
  58. package/dist/esm/common/algorithm.mjs +32 -0
  59. package/dist/esm/common/bundle.mjs +22 -0
  60. package/dist/esm/common/crypto.mjs +17 -0
  61. package/dist/esm/common/data/index.mjs +354 -0
  62. package/dist/esm/common/file.mjs +7 -0
  63. package/dist/esm/common/global-config.mjs +32 -0
  64. package/dist/esm/common/graph/assets.mjs +238 -0
  65. package/dist/esm/common/graph/chunk.mjs +32 -0
  66. package/dist/esm/common/graph/dependency.mjs +10 -0
  67. package/dist/esm/common/graph/entrypoints.mjs +4 -0
  68. package/dist/esm/common/graph/index.mjs +5 -0
  69. package/dist/esm/common/graph/modules.mjs +78 -0
  70. package/dist/esm/common/index.mjs +19 -0
  71. package/dist/esm/common/loader.mjs +247 -0
  72. package/dist/esm/common/lodash.mjs +32 -0
  73. package/dist/esm/common/manifest.mjs +30 -0
  74. package/dist/esm/common/package.mjs +56 -0
  75. package/dist/esm/common/plugin.mjs +48 -0
  76. package/dist/esm/common/resolver.mjs +46 -0
  77. package/dist/esm/common/rspack.mjs +9 -0
  78. package/dist/esm/common/summary.mjs +8 -0
  79. package/dist/esm/common/time.mjs +43 -0
  80. package/dist/esm/common/url.mjs +14 -0
  81. package/dist/esm/error/error.mjs +154 -0
  82. package/dist/esm/error/index.mjs +3 -0
  83. package/dist/esm/error/transform.mjs +138 -0
  84. package/dist/esm/error/utils.mjs +22 -0
  85. package/dist/esm/index.mjs +3 -0
  86. package/dist/esm/logger.mjs +49 -0
  87. package/dist/esm/rule-utils/document/document.mjs +58 -0
  88. package/dist/esm/rule-utils/document/index.mjs +3 -0
  89. package/dist/esm/rule-utils/document/server.mjs +12 -0
  90. package/dist/esm/rule-utils/index.mjs +2 -0
  91. package/dist/esm/rule-utils/parser/asserts.mjs +104 -0
  92. package/dist/esm/rule-utils/parser/index.mjs +4 -0
  93. package/dist/esm/rule-utils/parser/parser.mjs +23 -0
  94. package/dist/esm/rule-utils/parser/types.mjs +7 -0
  95. package/dist/esm/rule-utils/parser/utils.mjs +109 -0
  96. package/dist/type/common/file.d.ts +3 -0
  97. package/dist/type/common/file.d.ts.map +1 -0
  98. package/dist/type/common/graph/modules.d.ts +1 -1
  99. package/dist/type/common/graph/modules.d.ts.map +1 -1
  100. package/dist/type/common/index.d.ts +1 -0
  101. package/dist/type/common/index.d.ts.map +1 -1
  102. package/dist/type/logger.d.ts +3 -0
  103. package/dist/type/logger.d.ts.map +1 -1
  104. package/package.json +13 -12
  105. package/dist/esm/build/envinfo.js +0 -75
  106. package/dist/esm/build/file/cache.js +0 -30
  107. package/dist/esm/build/file/index.js +0 -7
  108. package/dist/esm/build/file/sharding.js +0 -50
  109. package/dist/esm/build/index.js +0 -12
  110. package/dist/esm/build/json.js +0 -85
  111. package/dist/esm/build/process.js +0 -24
  112. package/dist/esm/build/server.js +0 -96
  113. package/dist/esm/common/alerts.js +0 -25
  114. package/dist/esm/common/algorithm.js +0 -39
  115. package/dist/esm/common/bundle.js +0 -30
  116. package/dist/esm/common/crypto.js +0 -28
  117. package/dist/esm/common/data/index.js +0 -428
  118. package/dist/esm/common/global-config.js +0 -38
  119. package/dist/esm/common/graph/assets.js +0 -310
  120. package/dist/esm/common/graph/chunk.js +0 -49
  121. package/dist/esm/common/graph/dependency.js +0 -14
  122. package/dist/esm/common/graph/entrypoints.js +0 -6
  123. package/dist/esm/common/graph/index.js +0 -5
  124. package/dist/esm/common/graph/modules.js +0 -90
  125. package/dist/esm/common/index.js +0 -36
  126. package/dist/esm/common/loader.js +0 -279
  127. package/dist/esm/common/lodash.js +0 -49
  128. package/dist/esm/common/manifest.js +0 -46
  129. package/dist/esm/common/package.js +0 -71
  130. package/dist/esm/common/plugin.js +0 -59
  131. package/dist/esm/common/resolver.js +0 -54
  132. package/dist/esm/common/rspack.js +0 -12
  133. package/dist/esm/common/summary.js +0 -10
  134. package/dist/esm/common/time.js +0 -64
  135. package/dist/esm/common/url.js +0 -20
  136. package/dist/esm/error/error.js +0 -202
  137. package/dist/esm/error/index.js +0 -5
  138. package/dist/esm/error/transform.js +0 -141
  139. package/dist/esm/error/utils.js +0 -40
  140. package/dist/esm/index.js +0 -6
  141. package/dist/esm/logger.js +0 -43
  142. package/dist/esm/rule-utils/document/document.js +0 -67
  143. package/dist/esm/rule-utils/document/index.js +0 -3
  144. package/dist/esm/rule-utils/document/server.js +0 -17
  145. package/dist/esm/rule-utils/index.js +0 -2
  146. package/dist/esm/rule-utils/parser/asserts.js +0 -132
  147. package/dist/esm/rule-utils/parser/index.js +0 -4
  148. package/dist/esm/rule-utils/parser/parser.js +0 -58
  149. package/dist/esm/rule-utils/parser/types.js +0 -9
  150. package/dist/esm/rule-utils/parser/utils.js +0 -164
  151. /package/dist/esm/rule-utils/document/{types.js → types.mjs} +0 -0
@@ -0,0 +1,30 @@
1
+ import { decompressText } from "./algorithm.mjs";
2
+ import { isRemoteUrl } from "./url.mjs";
3
+ function isShardingData(data) {
4
+ if (Array.isArray(data) && data.length > 0) {
5
+ if (data.every((e)=>isRemoteUrl(e))) return true;
6
+ }
7
+ return false;
8
+ }
9
+ async function fetchShardingData(shardingFiles, fetchImplement) {
10
+ const res = await Promise.all(shardingFiles.map((url)=>fetchImplement(url)));
11
+ const strings = 0 === res.length ? [] : res.reduce((t, e)=>t + e);
12
+ return 'object' == typeof strings ? strings : JSON.parse(decompressText(strings));
13
+ }
14
+ async function fetchShardingFiles(data, fetchImplement, filterKeys) {
15
+ const datas = await Promise.all(Object.keys(data).map(async (_key)=>{
16
+ const key = _key;
17
+ const val = data[key];
18
+ if ((null == filterKeys ? void 0 : filterKeys.length) && filterKeys.indexOf(key) < 0) return {
19
+ [key]: []
20
+ };
21
+ if (isShardingData(val)) return {
22
+ [key]: await fetchShardingData(val, fetchImplement)
23
+ };
24
+ return {
25
+ [key]: val
26
+ };
27
+ }));
28
+ return datas.reduce((t, c)=>Object.assign(t, c));
29
+ }
30
+ export { fetchShardingData, fetchShardingFiles, isShardingData };
@@ -0,0 +1,56 @@
1
+ import { compact, isEmpty, last } from "./lodash.mjs";
2
+ const PACKAGE_PREFIX = /(?:node_modules|~)(?:\/\.pnpm)?/;
3
+ const PACKAGE_SLUG = /[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*/;
4
+ const VERSION = /@[\w|\-|_|.]+/;
5
+ const VERSION_NUMBER = '@([\\d.]+)';
6
+ const MODULE_PATH_PACKAGES = new RegExp([
7
+ `(?:${PACKAGE_PREFIX.source}/)`,
8
+ '(?:',
9
+ `(?:@${PACKAGE_SLUG.source}[/|+])?`,
10
+ `(?:${PACKAGE_SLUG.source}\\+)*`,
11
+ `(?:${PACKAGE_SLUG.source})`,
12
+ `(?:${VERSION.source})?`,
13
+ ')',
14
+ '(?:_',
15
+ `(?:@${PACKAGE_SLUG.source}[/|+])?`,
16
+ `(?:${PACKAGE_SLUG.source})`,
17
+ `(?:@${PACKAGE_SLUG.source})?`,
18
+ ')*',
19
+ '/'
20
+ ].join(''), 'g');
21
+ const PACKAGE_PATH_NAME = /(?:(?:node_modules|~)(?:\/\.pnpm)?\/)(?:((?:@[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*[/|+])?(?:(?:[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*\+)*)(?:[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*))(?:@[\w|\-|_|.]+)?)(?:_((?:@[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*[/|+])?(?:[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*))(?:@[a-zA-Z0-9]+(?:[-|_|.]+[a-zA-Z0-9]+)*))*\//gm;
22
+ const uniqLast = (data)=>{
23
+ const res = [];
24
+ data.forEach((item, index)=>{
25
+ if (!data.slice(index + 1).includes(item)) res.push(item);
26
+ });
27
+ return res;
28
+ };
29
+ const getPackageMetaFromModulePath = (modulePath)=>{
30
+ var _path_match_flat_slice, _path_match;
31
+ const paths = modulePath.match(MODULE_PATH_PACKAGES);
32
+ if (!paths) return {
33
+ name: '',
34
+ version: ''
35
+ };
36
+ const names = uniqLast(paths.flatMap((packagePath)=>{
37
+ const found = packagePath.matchAll(PACKAGE_PATH_NAME);
38
+ if (!found) return [];
39
+ const paksArray = compact([
40
+ ...found
41
+ ].flat());
42
+ return paksArray.slice(1).filter(Boolean).map((name)=>name.replace(/\+/g, '/'));
43
+ }));
44
+ if (isEmpty(names)) return {
45
+ name: '',
46
+ version: ''
47
+ };
48
+ const name = last(names);
49
+ const pattern = new RegExp(`(.*)(${last(paths)}).*`);
50
+ const path = modulePath.replace(pattern, '$1$2').replace(/\/$/, '');
51
+ return {
52
+ name,
53
+ version: path && name ? (null == (_path_match = path.match(new RegExp(`${name}${VERSION_NUMBER}`))) ? void 0 : null == (_path_match_flat_slice = _path_match.flat().slice(1)) ? void 0 : _path_match_flat_slice[0]) || '' : ''
54
+ };
55
+ };
56
+ export { MODULE_PATH_PACKAGES, PACKAGE_PATH_NAME, getPackageMetaFromModulePath };
@@ -0,0 +1,48 @@
1
+ function getPluginHooks(plugin) {
2
+ return Object.keys(plugin);
3
+ }
4
+ function getPluginTapNames(plugin) {
5
+ const hooks = getPluginHooks(plugin);
6
+ const tapNames = new Set();
7
+ hooks.forEach((hook)=>{
8
+ plugin[hook].forEach((data)=>{
9
+ tapNames.add(data.tapName);
10
+ });
11
+ });
12
+ return [
13
+ ...tapNames
14
+ ];
15
+ }
16
+ function getPluginSummary(plugin) {
17
+ return {
18
+ hooks: getPluginHooks(plugin),
19
+ tapNames: getPluginTapNames(plugin)
20
+ };
21
+ }
22
+ function getPluginData(plugin, selectedHooks = [], selectedTapNames = []) {
23
+ const hooks = getPluginHooks(plugin).filter((hook)=>{
24
+ if (selectedHooks.length && -1 === selectedHooks.indexOf(hook)) return false;
25
+ return true;
26
+ });
27
+ if (!hooks.length) return [];
28
+ const tapNames = getPluginTapNames(plugin);
29
+ return tapNames.reduce((total, tapName)=>{
30
+ if (selectedTapNames.length && -1 === selectedTapNames.indexOf(tapName)) return total;
31
+ hooks.forEach((hook)=>{
32
+ const hookData = plugin[hook].filter((e)=>e.tapName === tapName);
33
+ if (0 === hookData.length) return;
34
+ total.push({
35
+ tapName,
36
+ hook,
37
+ data: hookData.map((e)=>({
38
+ startAt: e.startAt,
39
+ endAt: e.endAt,
40
+ costs: e.costs,
41
+ type: e.type
42
+ }))
43
+ });
44
+ });
45
+ return total;
46
+ }, []);
47
+ }
48
+ export { getPluginData, getPluginHooks, getPluginSummary, getPluginTapNames };
@@ -0,0 +1,46 @@
1
+ import { mergeIntervals } from "./algorithm.mjs";
2
+ function isResolveSuccessData(data) {
3
+ return Boolean(data.result);
4
+ }
5
+ function isResolveFailData(data) {
6
+ return Boolean(data.error);
7
+ }
8
+ function getResolverCosts(resolver, resolvers) {
9
+ const blocked = resolvers.filter((e)=>e !== resolver && e.pid === resolver.pid && e.startAt >= resolver.startAt && e.endAt <= resolver.endAt);
10
+ let costs = resolver.endAt - resolver.startAt;
11
+ if (blocked.length) {
12
+ const intervals = blocked.map((e)=>[
13
+ Math.max(e.startAt, resolver.startAt),
14
+ Math.min(e.endAt, resolver.endAt)
15
+ ]);
16
+ mergeIntervals(intervals).forEach((e)=>{
17
+ const sub = e[1] - e[0];
18
+ costs -= sub;
19
+ });
20
+ }
21
+ return costs;
22
+ }
23
+ function getResolverFileTree(resolver) {
24
+ return resolver.map((e)=>({
25
+ issuerPath: e.issuerPath
26
+ }));
27
+ }
28
+ function getResolverFileDetails(filepath, resolvers, modules, moduleCodeMap) {
29
+ const module = modules.find((item)=>item.path === filepath);
30
+ const matchResolvers = resolvers.filter((e)=>e.issuerPath === filepath);
31
+ const before = module && moduleCodeMap && moduleCodeMap[module.id] ? moduleCodeMap[module.id].source : '';
32
+ const after = matchResolvers.reduce((t, c)=>{
33
+ if (c.request && isResolveSuccessData(c)) return t.replace(new RegExp(`["']${c.request}["']`), `"${c.result}"`);
34
+ return t;
35
+ }, before);
36
+ return {
37
+ filepath,
38
+ before,
39
+ after,
40
+ resolvers: matchResolvers.map((e)=>({
41
+ ...e,
42
+ costs: getResolverCosts(e, resolvers)
43
+ }))
44
+ };
45
+ }
46
+ export { getResolverCosts, getResolverFileDetails, getResolverFileTree, isResolveFailData, isResolveSuccessData };
@@ -0,0 +1,9 @@
1
+ const RspackLoaderInternalPropertyName = '__l__';
2
+ var rspack_RspackSummaryCostsDataName = /*#__PURE__*/ function(RspackSummaryCostsDataName) {
3
+ RspackSummaryCostsDataName["Bootstrap"] = "bootstrap->rspack:beforeCompile";
4
+ RspackSummaryCostsDataName["Compile"] = "rspack:beforeCompile->afterCompile";
5
+ RspackSummaryCostsDataName["Done"] = "rspack:afterCompile->done";
6
+ RspackSummaryCostsDataName["Minify"] = "rspack:minify(rspack:optimizeChunkAssets)";
7
+ return RspackSummaryCostsDataName;
8
+ }({});
9
+ export { RspackLoaderInternalPropertyName, rspack_RspackSummaryCostsDataName as RspackSummaryCostsDataName };
@@ -0,0 +1,8 @@
1
+ var summary_SummaryCostsDataName = /*#__PURE__*/ function(SummaryCostsDataName) {
2
+ SummaryCostsDataName["Bootstrap"] = "bootstrap->beforeCompile";
3
+ SummaryCostsDataName["Compile"] = "beforeCompile->afterCompile";
4
+ SummaryCostsDataName["Done"] = "afterCompile->done";
5
+ SummaryCostsDataName["Minify"] = "minify(processAssets)";
6
+ return SummaryCostsDataName;
7
+ }({});
8
+ export { summary_SummaryCostsDataName as SummaryCostsDataName };
@@ -0,0 +1,43 @@
1
+ import { hrtime } from "process";
2
+ function toFixedDigits(num, digits = 2) {
3
+ if (0 === digits) return Math.floor(num);
4
+ return +num.toFixed(digits);
5
+ }
6
+ function getUnit(num, type) {
7
+ let unit;
8
+ unit = 'm' === type ? num > 1 ? 'mins' : 'min' : num > 1 ? 'hours' : 'hour';
9
+ return unit;
10
+ }
11
+ function formatCosts(costs) {
12
+ costs = Number(costs);
13
+ if (costs >= 1000) {
14
+ const sec = costs / 1000;
15
+ if (sec >= 60) {
16
+ let mins = sec / 60;
17
+ if (mins >= 60) {
18
+ const hours = toFixedDigits(mins / 60, 0);
19
+ const restMins = toFixedDigits(mins % 60, 1);
20
+ const hUnit = getUnit(hours, 'h');
21
+ if (restMins > 0) return `${hours}${hUnit} ${restMins}${getUnit(restMins, 'm')}`;
22
+ return `${hours}${hUnit}`;
23
+ }
24
+ mins = toFixedDigits(mins, 0);
25
+ const mUnit = getUnit(mins, 'm');
26
+ const restSec = toFixedDigits(sec % 60, 0);
27
+ if (restSec > 0) return `${mins}${mUnit} ${restSec}s`;
28
+ return `${mins}${mUnit}`;
29
+ }
30
+ return `${toFixedDigits(sec, 1)}s`;
31
+ }
32
+ if (costs >= 10) return `${+toFixedDigits(costs, 0)}ms`;
33
+ if (costs >= 1) return `${+toFixedDigits(costs, 1)}ms`;
34
+ let r = +toFixedDigits(costs, 2);
35
+ if (0 === r) r = +toFixedDigits(costs, 3);
36
+ return `${r}ms`;
37
+ }
38
+ function getCurrentTimestamp(start, startHRTime) {
39
+ const endHRTime = hrtime(startHRTime);
40
+ const end = start + 1000 * endHRTime[0] + (process.env.RSTEST ? Math.round(endHRTime[1] / 1000000) : endHRTime[1] / 1000000);
41
+ return end;
42
+ }
43
+ export { formatCosts, getCurrentTimestamp, getUnit, toFixedDigits };
@@ -0,0 +1,14 @@
1
+ import { isAbsolute } from "path";
2
+ function isUrl(uri) {
3
+ return /^https?:\/\//.test(uri);
4
+ }
5
+ function isFilePath(uri) {
6
+ return isAbsolute(uri);
7
+ }
8
+ function isRemoteUrl(uri) {
9
+ if ('string' == typeof uri) {
10
+ if (isUrl(uri) || isFilePath(uri)) return true;
11
+ }
12
+ return false;
13
+ }
14
+ export { isFilePath, isRemoteUrl, isUrl };
@@ -0,0 +1,154 @@
1
+ import { codeFrameColumns } from "@babel/code-frame";
2
+ import { Err } from "@rsdoctor/types";
3
+ import { createColors } from "picocolors";
4
+ import deep_eql from "deep-eql";
5
+ import strip_ansi from "strip-ansi";
6
+ import { transform } from "./transform.mjs";
7
+ import { insertSpace, toLevel } from "./utils.mjs";
8
+ import { isNil } from "../common/lodash.mjs";
9
+ function _define_property(obj, key, value) {
10
+ if (key in obj) Object.defineProperty(obj, key, {
11
+ value: value,
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true
15
+ });
16
+ else obj[key] = value;
17
+ return obj;
18
+ }
19
+ let id = 1;
20
+ class DevToolError extends Error {
21
+ static from(err, opt) {
22
+ if (err instanceof DevToolError) return err;
23
+ return transform(err, opt);
24
+ }
25
+ get level() {
26
+ return Err.ErrorLevel[this._level];
27
+ }
28
+ get path() {
29
+ var _this__codeFrame;
30
+ return null == (_this__codeFrame = this._codeFrame) ? void 0 : _this__codeFrame.filePath;
31
+ }
32
+ set path(file) {
33
+ if (!file) return;
34
+ if (this._codeFrame) {
35
+ this._codeFrame.filePath = file;
36
+ return;
37
+ }
38
+ this._codeFrame = {
39
+ filePath: file
40
+ };
41
+ }
42
+ get codeFrame() {
43
+ return this._codeFrame;
44
+ }
45
+ printCodeFrame(print) {
46
+ const msgs = [];
47
+ const { _codeFrame: codeFrameOpt, _controller: controller } = this;
48
+ if (!codeFrameOpt) return msgs;
49
+ if ('start' in codeFrameOpt && codeFrameOpt.start) {
50
+ const { filePath, start } = codeFrameOpt;
51
+ msgs.push(`\n ${print.red(print.bold('File: '))}${print.bold(filePath)}:${start.line}${start.column ? `:${start.column}` : ''}`);
52
+ if ('fileContent' in codeFrameOpt) {
53
+ const { end, fileContent } = codeFrameOpt;
54
+ msgs.push(codeFrameColumns(fileContent, {
55
+ start,
56
+ end
57
+ }, {
58
+ highlightCode: !controller.noColor
59
+ }));
60
+ } else if ('lineText' in codeFrameOpt) {
61
+ const { length, lineText } = codeFrameOpt;
62
+ let lineCodeFrame = codeFrameColumns(lineText, {
63
+ start: {
64
+ line: 1,
65
+ column: start.column
66
+ },
67
+ end: {
68
+ line: 1,
69
+ column: isNil(start.column) || isNil(length) ? void 0 : start.column + length
70
+ }
71
+ }, {
72
+ highlightCode: !controller.noColor
73
+ });
74
+ if (start.line > 1) {
75
+ lineCodeFrame = lineCodeFrame.replace(' 1 |', ` ${start.line} |`);
76
+ if (start.line >= 10) lineCodeFrame = insertSpace(lineCodeFrame, 2, String(start.line).length - 1);
77
+ }
78
+ msgs.push(lineCodeFrame);
79
+ }
80
+ } else msgs.push(`\n ${print.red(print.bold('File: '))}${print.bold(codeFrameOpt.filePath)}\n`);
81
+ return msgs;
82
+ }
83
+ toString() {
84
+ const msgs = [];
85
+ const { code, title, message, hint, referenceUrl, _controller: controller } = this;
86
+ const print = createColors(!controller.noColor);
87
+ const mainColorPrint = this._level === Err.ErrorLevel.Error ? print.red : print.yellow;
88
+ const codeText = code ? `${mainColorPrint(print.blue(code))}:` : '';
89
+ msgs.push(mainColorPrint(print.bold(`[${codeText}${this.level}:${title.toUpperCase()}] `) + message));
90
+ msgs.push(...this.printCodeFrame(print));
91
+ if (hint || referenceUrl) msgs.push('');
92
+ if (hint) msgs.push(` ${print.blue(`HINT: ${hint}`)}`);
93
+ if (referenceUrl) msgs.push(print.magenta(print.bold(` See: ${referenceUrl}`)));
94
+ if (!controller.noStack && this.stack) msgs.push(print.red(print.bold(` Error Stack:\n${this.stack}\n`)));
95
+ return msgs.join('\n');
96
+ }
97
+ toData() {
98
+ var _this_detail;
99
+ return {
100
+ ...this.detail,
101
+ id: this.id,
102
+ category: this.category,
103
+ description: strip_ansi((null == (_this_detail = this.detail) ? void 0 : _this_detail.description) ?? this.message),
104
+ title: this.title.toUpperCase(),
105
+ code: this.code,
106
+ level: this.level.toLowerCase()
107
+ };
108
+ }
109
+ toError() {
110
+ const error = new Error();
111
+ error.message = this.toString();
112
+ error.name = this.name;
113
+ error.stack = this.stack;
114
+ return error;
115
+ }
116
+ toJSON() {
117
+ return {
118
+ message: this.toString(),
119
+ name: this.name,
120
+ stack: this.stack
121
+ };
122
+ }
123
+ setControllerOption(opt) {
124
+ this._controller = {
125
+ noStack: opt.noStack ?? this._controller.noStack ?? true,
126
+ noColor: opt.noColor ?? this._controller.noColor ?? false
127
+ };
128
+ }
129
+ setCodeFrame(opt) {
130
+ this._codeFrame = opt;
131
+ }
132
+ isSame(error) {
133
+ return this.code === error.code && this.message === error.message && this.hint === error.hint && this.level === error.level && this.title === error.title && this.referenceUrl === error.referenceUrl && this.code === error.code && deep_eql(this.codeFrame, error.codeFrame);
134
+ }
135
+ constructor(title, message, opts){
136
+ super(message), _define_property(this, "id", void 0), _define_property(this, "code", void 0), _define_property(this, "category", void 0), _define_property(this, "title", void 0), _define_property(this, "detail", void 0), _define_property(this, "fixData", void 0), _define_property(this, "hint", void 0), _define_property(this, "referenceUrl", void 0), _define_property(this, "_codeFrame", void 0), _define_property(this, "_controller", {
137
+ noStack: true,
138
+ noColor: false
139
+ }), _define_property(this, "_level", void 0);
140
+ this.id = id++;
141
+ this.title = title;
142
+ this.code = null == opts ? void 0 : opts.code;
143
+ this.hint = null == opts ? void 0 : opts.hint;
144
+ this.stack = null == opts ? void 0 : opts.stack;
145
+ this.detail = null == opts ? void 0 : opts.detail;
146
+ this.fixData = null == opts ? void 0 : opts.fixData;
147
+ this.category = null == opts ? void 0 : opts.category;
148
+ this.referenceUrl = null == opts ? void 0 : opts.referenceUrl;
149
+ this._level = (null == opts ? void 0 : opts.level) ? toLevel(opts.level) : Err.ErrorLevel.Error;
150
+ this._codeFrame = null == opts ? void 0 : opts.codeFrame;
151
+ this.setControllerOption((null == opts ? void 0 : opts.controller) ?? {});
152
+ }
153
+ }
154
+ export { DevToolError };
@@ -0,0 +1,3 @@
1
+ import { printErrors } from "./utils.mjs";
2
+ export * from "./error.mjs";
3
+ export { printErrors };
@@ -0,0 +1,138 @@
1
+ import strip_ansi from "strip-ansi";
2
+ import { Linter } from "@rsdoctor/types";
3
+ import { DevToolError } from "./error.mjs";
4
+ function isEsbuildError(err) {
5
+ return 'pluginName' in err && 'text' in err && 'location' in err;
6
+ }
7
+ function isBabelError(err) {
8
+ return 'code' in err && 'reasonCode' in err;
9
+ }
10
+ function isDiagnosticError(err) {
11
+ return 'severity' in err && 'title' in err;
12
+ }
13
+ function parseBabelErrorMessage(input) {
14
+ var _lines_find;
15
+ const lines = strip_ansi(input).split('\n');
16
+ const filePath = lines[0].replace(/^([^:]+):.*/, '$1');
17
+ const message = lines[0].replace(/.*: (.*) \(\d+:\d+\)*/, '$1');
18
+ const lineText = (null == (_lines_find = lines.find((line)=>line.startsWith('> '))) ? void 0 : _lines_find.replace(/> \d+ \| /, '')) ?? '';
19
+ return {
20
+ message,
21
+ filePath,
22
+ lineText
23
+ };
24
+ }
25
+ function clearMessage(str) {
26
+ return strip_ansi(str).replace(/.*: (.*)\n\n[\s\S]*/g, '$1');
27
+ }
28
+ function clearStack(str) {
29
+ return str.slice(str.indexOf(' at')).replace(/\s*at(.*) \((.*)\)/g, '$1\n$2\n');
30
+ }
31
+ function transformEsbuildError(err, opt) {
32
+ if (isEsbuildError(err)) {
33
+ var _err_location;
34
+ const errorCode = (null == opt ? void 0 : opt.code) ?? 'ESBUILD_ERROR';
35
+ const speedyError = 'object' == typeof err.detail ? DevToolError.from(err.detail) : new DevToolError(errorCode, clearMessage(err.text), {
36
+ ...opt,
37
+ hint: null == (_err_location = err.location) ? void 0 : _err_location.suggestion,
38
+ codeFrame: {
39
+ filePath: err.text.split(':')[0]
40
+ }
41
+ });
42
+ if (err.location) speedyError.setCodeFrame({
43
+ filePath: err.location.file,
44
+ lineText: err.location.lineText,
45
+ length: err.location.length,
46
+ start: {
47
+ line: err.location.line,
48
+ column: err.location.column + 1
49
+ }
50
+ });
51
+ return speedyError;
52
+ }
53
+ }
54
+ function transformBabelError(err, opt) {
55
+ if (isBabelError(err)) {
56
+ const errorCode = (null == opt ? void 0 : opt.code) ?? err.code ?? 'BABEL';
57
+ const title = err.reasonCode;
58
+ const errorParsed = parseBabelErrorMessage(err.message);
59
+ const speedyError = new DevToolError(title, errorParsed.message, {
60
+ ...opt,
61
+ code: errorCode,
62
+ stack: err.stack && clearStack(err.stack)
63
+ });
64
+ if (err.loc) speedyError.setCodeFrame({
65
+ ...errorParsed,
66
+ start: {
67
+ line: err.loc.line,
68
+ column: err.loc.column + 1
69
+ }
70
+ });
71
+ return speedyError;
72
+ }
73
+ }
74
+ function transformNormalError(err, opt) {
75
+ if (err instanceof Error) {
76
+ var _stacks__getFileName, _stacks_;
77
+ const stacks = [];
78
+ const filePath = null == stacks ? void 0 : null == (_stacks_ = stacks[0]) ? void 0 : null == (_stacks__getFileName = _stacks_.getFileName) ? void 0 : _stacks__getFileName.call(_stacks_);
79
+ return new DevToolError(err.name, clearMessage(err.message), {
80
+ ...opt,
81
+ codeFrame: filePath ? {
82
+ filePath
83
+ } : void 0,
84
+ stack: err.stack && clearStack(err.stack)
85
+ });
86
+ }
87
+ }
88
+ function transformErrorLike(err, opt) {
89
+ const isErrorLike = err && 'object' == typeof err && err.message;
90
+ if (isErrorLike) {
91
+ var _stacks__getFileName, _stacks_;
92
+ const stacks = [];
93
+ const filePath = null == stacks ? void 0 : null == (_stacks_ = stacks[0]) ? void 0 : null == (_stacks__getFileName = _stacks_.getFileName) ? void 0 : _stacks__getFileName.call(_stacks_);
94
+ return new DevToolError(err.name || 'UNKNOWN_ERROR', clearMessage(err.message), {
95
+ ...opt,
96
+ codeFrame: filePath ? {
97
+ filePath
98
+ } : void 0,
99
+ stack: err.stack && clearStack(err.stack)
100
+ });
101
+ }
102
+ }
103
+ function transformDiagnostic(err, opt) {
104
+ if (isDiagnosticError(err)) {
105
+ var _err_suggestions, _err_suggestions1;
106
+ return new DevToolError(err.title, err.message, {
107
+ ...err,
108
+ ...opt,
109
+ hint: null == (_err_suggestions = err.suggestions) ? void 0 : _err_suggestions.description,
110
+ fixData: null == (_err_suggestions1 = err.suggestions) ? void 0 : _err_suggestions1.fixData,
111
+ codeFrame: err.document ? {
112
+ filePath: err.document.path,
113
+ fileContent: err.document.content,
114
+ start: err.document.range.start,
115
+ end: err.document.range.end
116
+ } : void 0,
117
+ level: Linter.Severity[err.severity]
118
+ });
119
+ }
120
+ }
121
+ function defaultError(err, opt) {
122
+ return new DevToolError('UNKNOWN_ERROR', JSON.stringify(err), opt);
123
+ }
124
+ function transform(err, opt) {
125
+ const transformers = [
126
+ transformEsbuildError,
127
+ transformBabelError,
128
+ transformDiagnostic,
129
+ transformNormalError,
130
+ transformErrorLike
131
+ ];
132
+ for (const fn of transformers){
133
+ const result = fn(err, opt);
134
+ if (result) return result;
135
+ }
136
+ return defaultError(err, opt);
137
+ }
138
+ export { transform };
@@ -0,0 +1,22 @@
1
+ import { Err } from "@rsdoctor/types";
2
+ function toLevel(level) {
3
+ return Err.ErrorLevel[level];
4
+ }
5
+ function insertSpace(rawLines, line, width) {
6
+ const lines = rawLines.split('\n');
7
+ lines[line - 1] = Array(width).fill(' ').join('') + lines[line - 1];
8
+ return lines.join('\n');
9
+ }
10
+ function printErrors({ errors, warnings }, logLevel = 'Error') {
11
+ const onlyError = 'Error' === logLevel;
12
+ if ('Silent' === logLevel) return '';
13
+ if (onlyError && 0 === errors.length || !onlyError && 0 === errors.length && 0 === warnings.length) return '';
14
+ const msgs = [];
15
+ if (onlyError) msgs.push(`Build failed with ${errors.length} error:`, ...errors.map((item)=>item.toString()), '');
16
+ else {
17
+ const title = 0 === errors.length ? `Build succuss with ${warnings.length} warning:` : `Build failed with ${errors.length} error, ${warnings.length} warning:`;
18
+ msgs.push(title, ...errors.map((item)=>item.toString()), ...warnings.map((item)=>item.toString()), '');
19
+ }
20
+ return msgs.join('\n\n');
21
+ }
22
+ export { insertSpace, printErrors, toLevel };
@@ -0,0 +1,3 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__rule_utils_index_mjs_79331901__ from "./rule-utils/index.mjs";
2
+ import * as __WEBPACK_EXTERNAL_MODULE__logger_mjs_dfc7ebda__ from "./logger.mjs";
3
+ export { __WEBPACK_EXTERNAL_MODULE__logger_mjs_dfc7ebda__ as Logger, __WEBPACK_EXTERNAL_MODULE__rule_utils_index_mjs_79331901__ as RuleUtils };
@@ -0,0 +1,49 @@
1
+ import picocolors from "picocolors";
2
+ import { logger } from "rslog";
3
+ import { Constants } from "@rsdoctor/types";
4
+ function debug(getMsg, prefix = '') {
5
+ if (!process.env.DEBUG) return;
6
+ logger.level = 'verbose';
7
+ logger.debug(`${prefix} ${getMsg()}`);
8
+ }
9
+ logger.override({
10
+ log: (message)=>{
11
+ console.log(`${picocolors.green('[RSDOCTOR LOG]')} ${message}`);
12
+ },
13
+ info: (message)=>{
14
+ console.log(`${picocolors.yellow('[RSDOCTOR INFO]')} ${message}`);
15
+ },
16
+ warn: (message)=>{
17
+ console.warn(`${picocolors.yellow('[RSDOCTOR WARN]')} ${message}`);
18
+ },
19
+ start: (message)=>{
20
+ console.log(`${picocolors.green('[RSDOCTOR START]')} ${message}`);
21
+ },
22
+ ready: (message)=>{
23
+ console.log(`${picocolors.green('[RSDOCTOR READY]')} ${message}`);
24
+ },
25
+ error: (message)=>{
26
+ console.error(`${picocolors.red('[RSDOCTOR ERROR]')} ${message}`);
27
+ },
28
+ success: (message)=>{
29
+ console.error(`${picocolors.green('[RSDOCTOR SUCCESS]')} ${message}`);
30
+ },
31
+ debug: (message)=>{
32
+ if (process.env.DEBUG) console.log(`${picocolors.blue('[RSDOCTOR DEBUG]')} ${message}`);
33
+ }
34
+ });
35
+ const _timers = new Map();
36
+ function time(label) {
37
+ if (process.env.DEBUG !== Constants.RsdoctorProcessEnvDebugKey) return;
38
+ if (_timers.has(label)) return;
39
+ _timers.set(label, Date.now());
40
+ }
41
+ function timeEnd(label) {
42
+ if (process.env.DEBUG !== Constants.RsdoctorProcessEnvDebugKey) return;
43
+ const start = _timers.get(label);
44
+ if (null == start) return void logger.debug(`Timer '${label}' does not exist.`);
45
+ const duration = Date.now() - start;
46
+ logger.debug(`Timer '${label}' ended: ${duration}ms`);
47
+ _timers.delete(label);
48
+ }
49
+ export { picocolors as chalk, debug, logger, time, timeEnd };