index.cjs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. // src/index.js
  20. var index_exports = {};
  21. __export(index_exports, {
  22. INSPECT_OPTIONS: () => INSPECT_OPTIONS,
  23. createColorizedDump: () => createColorizedDump,
  24. createDebugger: () => createDebugger
  25. });
  26. module.exports = __toCommonJS(index_exports);
  27. // src/create-debugger.js
  28. var import_js_format = require("@e22m4u/js-format");
  29. var import_js_format2 = require("@e22m4u/js-format");
  30. // src/utils/is-non-array-object.js
  31. function isNonArrayObject(input) {
  32. return Boolean(input && typeof input === "object" && !Array.isArray(input));
  33. }
  34. __name(isNonArrayObject, "isNonArrayObject");
  35. // src/utils/generate-random-hex.js
  36. function generateRandomHex(length = 4) {
  37. if (length <= 0) {
  38. return "";
  39. }
  40. const firstCharCandidates = "abcdef";
  41. const restCharCandidates = "0123456789abcdef";
  42. let result = "";
  43. const firstCharIndex = Math.floor(Math.random() * firstCharCandidates.length);
  44. result += firstCharCandidates[firstCharIndex];
  45. for (let i = 1; i < length; i++) {
  46. const randomIndex = Math.floor(Math.random() * restCharCandidates.length);
  47. result += restCharCandidates[randomIndex];
  48. }
  49. return result;
  50. }
  51. __name(generateRandomHex, "generateRandomHex");
  52. // src/create-colorized-dump.js
  53. var import_util = require("util");
  54. var INSPECT_OPTIONS = {
  55. showHidden: false,
  56. depth: null,
  57. colors: true,
  58. compact: false
  59. };
  60. function createColorizedDump(value) {
  61. return (0, import_util.inspect)(value, INSPECT_OPTIONS);
  62. }
  63. __name(createColorizedDump, "createColorizedDump");
  64. // src/create-debugger.js
  65. var AVAILABLE_COLORS = [
  66. 20,
  67. 21,
  68. 26,
  69. 27,
  70. 32,
  71. 33,
  72. 38,
  73. 39,
  74. 40,
  75. 41,
  76. 42,
  77. 43,
  78. 44,
  79. 45,
  80. 56,
  81. 57,
  82. 62,
  83. 63,
  84. 68,
  85. 69,
  86. 74,
  87. 75,
  88. 76,
  89. 77,
  90. 78,
  91. 79,
  92. 80,
  93. 81,
  94. 92,
  95. 93,
  96. 98,
  97. 99,
  98. 112,
  99. 113,
  100. 128,
  101. 129,
  102. 134,
  103. 135,
  104. 148,
  105. 149,
  106. 160,
  107. 161,
  108. 162,
  109. 163,
  110. 164,
  111. 165,
  112. 166,
  113. 167,
  114. 168,
  115. 169,
  116. 170,
  117. 171,
  118. 172,
  119. 173,
  120. 178,
  121. 179,
  122. 184,
  123. 185,
  124. 196,
  125. 197,
  126. 198,
  127. 199,
  128. 200,
  129. 201,
  130. 202,
  131. 203,
  132. 204,
  133. 205,
  134. 206,
  135. 207,
  136. 208,
  137. 209,
  138. 214,
  139. 215,
  140. 220,
  141. 221
  142. ];
  143. function pickColorCode(input) {
  144. if (typeof input !== "string")
  145. throw new import_js_format.Errorf(
  146. 'The parameter "input" of the function pickColorCode must be a String, but %v given.',
  147. input
  148. );
  149. let hash = 0;
  150. for (let i = 0; i < input.length; i++) {
  151. hash = (hash << 5) - hash + input.charCodeAt(i);
  152. hash |= 0;
  153. }
  154. return AVAILABLE_COLORS[Math.abs(hash) % AVAILABLE_COLORS.length];
  155. }
  156. __name(pickColorCode, "pickColorCode");
  157. function wrapStringByColorCode(input, color) {
  158. if (typeof input !== "string")
  159. throw new import_js_format.Errorf(
  160. 'The parameter "input" of the function wrapStringByColorCode must be a String, but %v given.',
  161. input
  162. );
  163. if (typeof color !== "number")
  164. throw new import_js_format.Errorf(
  165. 'The parameter "color" of the function wrapStringByColorCode must be a Number, but %v given.',
  166. color
  167. );
  168. const colorCode = "\x1B[3" + (Number(color) < 8 ? color : "8;5;" + color);
  169. return `${colorCode};1m${input}\x1B[0m`;
  170. }
  171. __name(wrapStringByColorCode, "wrapStringByColorCode");
  172. function matchPattern(pattern, input) {
  173. if (typeof pattern !== "string")
  174. throw new import_js_format.Errorf(
  175. 'The parameter "pattern" of the function matchPattern must be a String, but %v given.',
  176. pattern
  177. );
  178. if (typeof input !== "string")
  179. throw new import_js_format.Errorf(
  180. 'The parameter "input" of the function matchPattern must be a String, but %v given.',
  181. input
  182. );
  183. const regexpStr = pattern.replace(/\*/g, ".*?");
  184. const regexp = new RegExp("^" + regexpStr + "$");
  185. return regexp.test(input);
  186. }
  187. __name(matchPattern, "matchPattern");
  188. function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
  189. if (namespaceOrOptions && typeof namespaceOrOptions !== "string" && !isNonArrayObject(namespaceOrOptions)) {
  190. throw new import_js_format.Errorf(
  191. 'The parameter "namespace" of the function createDebugger must be a String or an Object, but %v given.',
  192. namespaceOrOptions
  193. );
  194. }
  195. const withCustomState = isNonArrayObject(namespaceOrOptions);
  196. const state = withCustomState ? namespaceOrOptions : {};
  197. state.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  198. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  199. state.hash = typeof state.hash === "string" ? state.hash : "";
  200. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  201. state.offsetStep = typeof state.offsetStep === "string" ? state.offsetStep : " ";
  202. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  203. if (!withCustomState) {
  204. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  205. state.nsSegments.push(process.env.DEBUGGER_NAMESPACE);
  206. }
  207. if (typeof namespaceOrOptions === "string")
  208. state.nsSegments.push(namespaceOrOptions);
  209. }
  210. namespaceSegments.forEach((segment) => {
  211. if (!segment || typeof segment !== "string")
  212. throw new import_js_format.Errorf(
  213. "Namespace segment must be a non-empty String, but %v given.",
  214. segment
  215. );
  216. state.nsSegments.push(segment);
  217. });
  218. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  219. state.pattern = process.env["DEBUG"];
  220. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  221. state.pattern = localStorage.getItem("debug");
  222. }
  223. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  224. const nsStr = state.nsSegments.join(state.delimiter);
  225. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  226. if (patterns.length === 0 && state.pattern !== "*") return false;
  227. for (const singlePattern of patterns) {
  228. if (matchPattern(singlePattern, nsStr)) return true;
  229. }
  230. return false;
  231. }, "isDebuggerEnabled");
  232. const getPrefix = /* @__PURE__ */ __name(() => {
  233. let tokens = [];
  234. [...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  235. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  236. tokens = [...tokens, ...extractedTokens];
  237. });
  238. let res = tokens.reduce((acc, token, index) => {
  239. const isLast = tokens.length - 1 === index;
  240. const tokenColor = pickColorCode(token);
  241. acc += wrapStringByColorCode(token, tokenColor);
  242. if (!isLast) acc += state.delimiter;
  243. return acc;
  244. }, "");
  245. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  246. return res;
  247. }, "getPrefix");
  248. function debugFn(messageOrData, ...args) {
  249. if (!isDebuggerEnabled()) return;
  250. const prefix = getPrefix();
  251. if (typeof messageOrData === "string") {
  252. const multiString2 = (0, import_js_format2.format)(messageOrData, ...args);
  253. const rows2 = multiString2.split("\n");
  254. rows2.forEach((message) => {
  255. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  256. });
  257. return;
  258. }
  259. const multiString = createColorizedDump(messageOrData);
  260. const rows = multiString.split("\n");
  261. [...args, ...rows].forEach((message) => {
  262. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  263. });
  264. }
  265. __name(debugFn, "debugFn");
  266. debugFn.withNs = function(namespace, ...args) {
  267. const stateCopy = JSON.parse(JSON.stringify(state));
  268. [namespace, ...args].forEach((ns) => {
  269. if (!ns || typeof ns !== "string")
  270. throw new import_js_format.Errorf(
  271. "Debugger namespace must be a non-empty String, but %v given.",
  272. ns
  273. );
  274. stateCopy.nsSegments.push(ns);
  275. });
  276. return createDebugger(stateCopy);
  277. };
  278. debugFn.withHash = function(hashLength = 4) {
  279. const stateCopy = JSON.parse(JSON.stringify(state));
  280. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  281. throw new import_js_format.Errorf(
  282. "Debugger hash must be a positive Number, but %v given.",
  283. hashLength
  284. );
  285. }
  286. stateCopy.hash = generateRandomHex(hashLength);
  287. return createDebugger(stateCopy);
  288. };
  289. debugFn.withOffset = function(offsetSize) {
  290. const stateCopy = JSON.parse(JSON.stringify(state));
  291. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  292. throw new import_js_format.Errorf(
  293. "Debugger offset must be a positive Number, but %v given.",
  294. offsetSize
  295. );
  296. }
  297. stateCopy.offsetSize = offsetSize;
  298. return createDebugger(stateCopy);
  299. };
  300. return debugFn;
  301. }
  302. __name(createDebugger, "createDebugger");
  303. // Annotate the CommonJS export names for ESM import in node:
  304. 0 && (module.exports = {
  305. INSPECT_OPTIONS,
  306. createColorizedDump,
  307. createDebugger
  308. });