index.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  6. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  7. var __export = (target, all) => {
  8. for (var name in all)
  9. __defProp(target, name, { get: all[name], enumerable: true });
  10. };
  11. var __copyProps = (to, from, except, desc) => {
  12. if (from && typeof from === "object" || typeof from === "function") {
  13. for (let key of __getOwnPropNames(from))
  14. if (!__hasOwnProp.call(to, key) && key !== except)
  15. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  16. }
  17. return to;
  18. };
  19. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  20. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  21. // src/index.js
  22. var index_exports = {};
  23. __export(index_exports, {
  24. DEFAULT_OFFSET_STEP_SPACES: () => DEFAULT_OFFSET_STEP_SPACES,
  25. Debuggable: () => Debuggable,
  26. INSPECT_OPTIONS: () => INSPECT_OPTIONS,
  27. createColorizedDump: () => createColorizedDump,
  28. createDebugger: () => createDebugger
  29. });
  30. module.exports = __toCommonJS(index_exports);
  31. // src/utils/to-camel-case.js
  32. function toCamelCase(input) {
  33. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  34. }
  35. __name(toCamelCase, "toCamelCase");
  36. // src/utils/is-non-array-object.js
  37. function isNonArrayObject(input) {
  38. return Boolean(input && typeof input === "object" && !Array.isArray(input));
  39. }
  40. __name(isNonArrayObject, "isNonArrayObject");
  41. // src/utils/generate-random-hex.js
  42. function generateRandomHex(length = 4) {
  43. if (length <= 0) {
  44. return "";
  45. }
  46. const firstCharCandidates = "abcdef";
  47. const restCharCandidates = "0123456789abcdef";
  48. let result = "";
  49. const firstCharIndex = Math.floor(Math.random() * firstCharCandidates.length);
  50. result += firstCharCandidates[firstCharIndex];
  51. for (let i = 1; i < length; i++) {
  52. const randomIndex = Math.floor(Math.random() * restCharCandidates.length);
  53. result += restCharCandidates[randomIndex];
  54. }
  55. return result;
  56. }
  57. __name(generateRandomHex, "generateRandomHex");
  58. // src/debuggable.js
  59. var _Debuggable = class _Debuggable {
  60. /**
  61. * Debug.
  62. *
  63. * @type {Function}
  64. */
  65. debug;
  66. /**
  67. * Ctor Debug.
  68. *
  69. * @type {Function}
  70. */
  71. ctorDebug;
  72. /**
  73. * Возвращает функцию-отладчик с сегментом пространства имен
  74. * указанного в параметре метода.
  75. *
  76. * @param {Function} method
  77. * @returns {Function}
  78. */
  79. getDebuggerFor(method) {
  80. return this.debug.withHash().withNs(method.name);
  81. }
  82. /**
  83. * Constructor.
  84. *
  85. * @param {object|undefined} container
  86. * @param {DebuggableOptions|undefined} options
  87. */
  88. constructor(options = void 0) {
  89. const className = toCamelCase(this.constructor.name);
  90. options = typeof options === "object" && options || {};
  91. const namespace = options.namespace && String(options.namespace) || void 0;
  92. if (namespace) {
  93. this.debug = createDebugger(namespace, className);
  94. } else {
  95. this.debug = createDebugger(className);
  96. }
  97. const noEnvNs = Boolean(options.noEnvNs);
  98. if (noEnvNs) this.debug = this.debug.withoutEnvNs();
  99. this.ctorDebug = this.debug.withNs("constructor").withHash();
  100. const noInstMsg = Boolean(options.noInstMsg);
  101. if (!noInstMsg) this.ctorDebug(_Debuggable.INSTANTIATION_MESSAGE);
  102. }
  103. };
  104. __name(_Debuggable, "Debuggable");
  105. /**
  106. * Instantiation message;
  107. *
  108. * @type {string}
  109. */
  110. __publicField(_Debuggable, "INSTANTIATION_MESSAGE", "Instantiated.");
  111. var Debuggable = _Debuggable;
  112. // src/create-debugger.js
  113. var import_js_format = require("@e22m4u/js-format");
  114. var import_js_format2 = require("@e22m4u/js-format");
  115. // src/create-colorized-dump.js
  116. var import_util = require("util");
  117. var INSPECT_OPTIONS = {
  118. showHidden: false,
  119. depth: null,
  120. colors: true,
  121. compact: false
  122. };
  123. function createColorizedDump(value) {
  124. return (0, import_util.inspect)(value, INSPECT_OPTIONS);
  125. }
  126. __name(createColorizedDump, "createColorizedDump");
  127. // src/create-debugger.js
  128. var AVAILABLE_COLORS = [
  129. 20,
  130. 21,
  131. 26,
  132. 27,
  133. 32,
  134. 33,
  135. 38,
  136. 39,
  137. 40,
  138. 41,
  139. 42,
  140. 43,
  141. 44,
  142. 45,
  143. 56,
  144. 57,
  145. 62,
  146. 63,
  147. 68,
  148. 69,
  149. 74,
  150. 75,
  151. 76,
  152. 77,
  153. 78,
  154. 79,
  155. 80,
  156. 81,
  157. 92,
  158. 93,
  159. 98,
  160. 99,
  161. 112,
  162. 113,
  163. 128,
  164. 129,
  165. 134,
  166. 135,
  167. 148,
  168. 149,
  169. 160,
  170. 161,
  171. 162,
  172. 163,
  173. 164,
  174. 165,
  175. 166,
  176. 167,
  177. 168,
  178. 169,
  179. 170,
  180. 171,
  181. 172,
  182. 173,
  183. 178,
  184. 179,
  185. 184,
  186. 185,
  187. 196,
  188. 197,
  189. 198,
  190. 199,
  191. 200,
  192. 201,
  193. 202,
  194. 203,
  195. 204,
  196. 205,
  197. 206,
  198. 207,
  199. 208,
  200. 209,
  201. 214,
  202. 215,
  203. 220,
  204. 221
  205. ];
  206. var DEFAULT_OFFSET_STEP_SPACES = 2;
  207. function pickColorCode(input) {
  208. if (typeof input !== "string")
  209. throw new import_js_format.Errorf(
  210. 'The parameter "input" of the function pickColorCode must be a String, but %v given.',
  211. input
  212. );
  213. let hash = 0;
  214. for (let i = 0; i < input.length; i++) {
  215. hash = (hash << 5) - hash + input.charCodeAt(i);
  216. hash |= 0;
  217. }
  218. return AVAILABLE_COLORS[Math.abs(hash) % AVAILABLE_COLORS.length];
  219. }
  220. __name(pickColorCode, "pickColorCode");
  221. function wrapStringByColorCode(input, color) {
  222. if (typeof input !== "string")
  223. throw new import_js_format.Errorf(
  224. 'The parameter "input" of the function wrapStringByColorCode must be a String, but %v given.',
  225. input
  226. );
  227. if (typeof color !== "number")
  228. throw new import_js_format.Errorf(
  229. 'The parameter "color" of the function wrapStringByColorCode must be a Number, but %v given.',
  230. color
  231. );
  232. const colorCode = "\x1B[3" + (Number(color) < 8 ? color : "8;5;" + color);
  233. return `${colorCode};1m${input}\x1B[0m`;
  234. }
  235. __name(wrapStringByColorCode, "wrapStringByColorCode");
  236. function matchPattern(pattern, input) {
  237. if (typeof pattern !== "string")
  238. throw new import_js_format.Errorf(
  239. 'The parameter "pattern" of the function matchPattern must be a String, but %v given.',
  240. pattern
  241. );
  242. if (typeof input !== "string")
  243. throw new import_js_format.Errorf(
  244. 'The parameter "input" of the function matchPattern must be a String, but %v given.',
  245. input
  246. );
  247. const regexpStr = pattern.replace(/\*/g, ".*?");
  248. const regexp = new RegExp("^" + regexpStr + "$");
  249. return regexp.test(input);
  250. }
  251. __name(matchPattern, "matchPattern");
  252. function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
  253. if (namespaceOrOptions && typeof namespaceOrOptions !== "string" && !isNonArrayObject(namespaceOrOptions)) {
  254. throw new import_js_format.Errorf(
  255. 'The parameter "namespace" of the function createDebugger must be a String or an Object, but %v given.',
  256. namespaceOrOptions
  257. );
  258. }
  259. const withCustomState = isNonArrayObject(namespaceOrOptions);
  260. const state = withCustomState ? namespaceOrOptions : {};
  261. state.envNsSegments = Array.isArray(state.envNsSegments) ? state.envNsSegments : [];
  262. state.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  263. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  264. state.hash = typeof state.hash === "string" ? state.hash : "";
  265. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  266. state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
  267. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  268. if (!withCustomState) {
  269. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  270. state.envNsSegments.push(process.env.DEBUGGER_NAMESPACE);
  271. }
  272. if (typeof namespaceOrOptions === "string")
  273. state.nsSegments.push(namespaceOrOptions);
  274. }
  275. namespaceSegments.forEach((segment) => {
  276. if (!segment || typeof segment !== "string")
  277. throw new import_js_format.Errorf(
  278. "Namespace segment must be a non-empty String, but %v given.",
  279. segment
  280. );
  281. state.nsSegments.push(segment);
  282. });
  283. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  284. state.pattern = process.env["DEBUG"];
  285. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  286. state.pattern = localStorage.getItem("debug");
  287. }
  288. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  289. const nsStr = [...state.envNsSegments, ...state.nsSegments].join(
  290. state.delimiter
  291. );
  292. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  293. if (patterns.length === 0 && state.pattern !== "*") return false;
  294. for (const singlePattern of patterns) {
  295. if (matchPattern(singlePattern, nsStr)) return true;
  296. }
  297. return false;
  298. }, "isDebuggerEnabled");
  299. const getPrefix = /* @__PURE__ */ __name(() => {
  300. let tokens = [];
  301. [...state.envNsSegments, ...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  302. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  303. tokens = [...tokens, ...extractedTokens];
  304. });
  305. let res = tokens.reduce((acc, token, index) => {
  306. const isLast = tokens.length - 1 === index;
  307. const tokenColor = pickColorCode(token);
  308. acc += wrapStringByColorCode(token, tokenColor);
  309. if (!isLast) acc += state.delimiter;
  310. return acc;
  311. }, "");
  312. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  313. return res;
  314. }, "getPrefix");
  315. function debugFn(messageOrData, ...args) {
  316. if (!isDebuggerEnabled()) return;
  317. const prefix = getPrefix();
  318. const multiString = (0, import_js_format2.format)(messageOrData, ...args);
  319. const rows = multiString.split("\n");
  320. rows.forEach((message) => {
  321. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  322. });
  323. }
  324. __name(debugFn, "debugFn");
  325. debugFn.withNs = function(namespace, ...args) {
  326. const stateCopy = JSON.parse(JSON.stringify(state));
  327. [namespace, ...args].forEach((ns) => {
  328. if (!ns || typeof ns !== "string")
  329. throw new import_js_format.Errorf(
  330. "Debugger namespace must be a non-empty String, but %v given.",
  331. ns
  332. );
  333. stateCopy.nsSegments.push(ns);
  334. });
  335. return createDebugger(stateCopy);
  336. };
  337. debugFn.withHash = function(hashLength = 4) {
  338. const stateCopy = JSON.parse(JSON.stringify(state));
  339. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  340. throw new import_js_format.Errorf(
  341. "Debugger hash must be a positive Number, but %v given.",
  342. hashLength
  343. );
  344. }
  345. stateCopy.hash = generateRandomHex(hashLength);
  346. return createDebugger(stateCopy);
  347. };
  348. debugFn.withOffset = function(offsetSize) {
  349. const stateCopy = JSON.parse(JSON.stringify(state));
  350. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  351. throw new import_js_format.Errorf(
  352. "Debugger offset must be a positive Number, but %v given.",
  353. offsetSize
  354. );
  355. }
  356. stateCopy.offsetSize = offsetSize;
  357. return createDebugger(stateCopy);
  358. };
  359. debugFn.withoutEnvNs = function() {
  360. const stateCopy = JSON.parse(JSON.stringify(state));
  361. stateCopy.envNsSegments = [];
  362. return createDebugger(stateCopy);
  363. };
  364. debugFn.inspect = function(valueOrDesc, ...args) {
  365. if (!isDebuggerEnabled()) return;
  366. const prefix = getPrefix();
  367. let multiString = "";
  368. if (typeof valueOrDesc === "string" && args.length) {
  369. multiString += `${valueOrDesc}
  370. `;
  371. const multilineDump = args.map((v) => createColorizedDump(v)).join("\n");
  372. const dumpRows = multilineDump.split("\n");
  373. multiString += dumpRows.map((v) => `${state.offsetStep}${v}`).join("\n");
  374. } else {
  375. multiString += [valueOrDesc, ...args].map((v) => createColorizedDump(v)).join("\n");
  376. }
  377. const rows = multiString.split("\n");
  378. rows.forEach((message) => {
  379. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  380. });
  381. };
  382. debugFn.state = state;
  383. return debugFn;
  384. }
  385. __name(createDebugger, "createDebugger");
  386. // Annotate the CommonJS export names for ESM import in node:
  387. 0 && (module.exports = {
  388. DEFAULT_OFFSET_STEP_SPACES,
  389. Debuggable,
  390. INSPECT_OPTIONS,
  391. createColorizedDump,
  392. createDebugger
  393. });