index.cjs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815
  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. MongodbAdapter: () => MongodbAdapter
  25. });
  26. module.exports = __toCommonJS(index_exports);
  27. // src/mongodb-adapter.js
  28. var import_mongodb2 = require("mongodb");
  29. // node_modules/@e22m4u/js-service/src/errors/invalid-argument-error.js
  30. var import_js_format = require("@e22m4u/js-format");
  31. var _InvalidArgumentError = class _InvalidArgumentError extends import_js_format.Errorf {
  32. };
  33. __name(_InvalidArgumentError, "InvalidArgumentError");
  34. var InvalidArgumentError = _InvalidArgumentError;
  35. // node_modules/@e22m4u/js-service/src/service-container.js
  36. var SERVICE_CONTAINER_CLASS_NAME = "ServiceContainer";
  37. var _ServiceContainer = class _ServiceContainer {
  38. /**
  39. * Services map.
  40. *
  41. * @type {Map<any, any>}
  42. * @private
  43. */
  44. _services = /* @__PURE__ */ new Map();
  45. /**
  46. * Parent container.
  47. *
  48. * @type {ServiceContainer}
  49. * @private
  50. */
  51. _parent;
  52. /**
  53. * Constructor.
  54. *
  55. * @param {ServiceContainer|undefined} parent
  56. */
  57. constructor(parent = void 0) {
  58. if (parent != null) {
  59. if (!(parent instanceof _ServiceContainer))
  60. throw new InvalidArgumentError(
  61. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  62. parent
  63. );
  64. this._parent = parent;
  65. }
  66. }
  67. /**
  68. * Получить родительский сервис-контейнер или выбросить ошибку.
  69. *
  70. * @returns {ServiceContainer}
  71. */
  72. getParent() {
  73. if (!this._parent)
  74. throw new InvalidArgumentError("The service container has no parent.");
  75. return this._parent;
  76. }
  77. /**
  78. * Проверить наличие родительского сервис-контейнера.
  79. *
  80. * @returns {boolean}
  81. */
  82. hasParent() {
  83. return Boolean(this._parent);
  84. }
  85. /**
  86. * Получить существующий или новый экземпляр.
  87. *
  88. * @param {*} ctor
  89. * @param {*} args
  90. * @returns {*}
  91. */
  92. get(ctor, ...args) {
  93. if (!ctor || typeof ctor !== "function")
  94. throw new InvalidArgumentError(
  95. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  96. ctor
  97. );
  98. const isCtorRegistered = this._services.has(ctor);
  99. let service = this._services.get(ctor);
  100. let inheritedCtor = void 0;
  101. if (!service) {
  102. const ctors = Array.from(this._services.keys());
  103. inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  104. if (inheritedCtor) service = this._services.get(inheritedCtor);
  105. }
  106. if (!service && !isCtorRegistered && !inheritedCtor && this._parent && this._parent.has(ctor)) {
  107. return this._parent.get(ctor, ...args);
  108. }
  109. if (!isCtorRegistered && inheritedCtor) {
  110. ctor = inheritedCtor;
  111. }
  112. if (!service || args.length) {
  113. service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  114. this._services.set(ctor, service);
  115. } else if (typeof service === "function") {
  116. service = service();
  117. this._services.set(ctor, service);
  118. }
  119. return service;
  120. }
  121. /**
  122. * Получить существующий или новый экземпляр,
  123. * только если конструктор зарегистрирован.
  124. *
  125. * @param {*} ctor
  126. * @param {*} args
  127. * @returns {*}
  128. */
  129. getRegistered(ctor, ...args) {
  130. if (!this.has(ctor))
  131. throw new InvalidArgumentError(
  132. "The constructor %v is not registered.",
  133. ctor
  134. );
  135. return this.get(ctor, ...args);
  136. }
  137. /**
  138. * Проверить существование конструктора в контейнере.
  139. *
  140. * @param {*} ctor
  141. * @returns {boolean}
  142. */
  143. has(ctor) {
  144. if (this._services.has(ctor)) return true;
  145. const ctors = Array.from(this._services.keys());
  146. const inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  147. if (inheritedCtor) return true;
  148. if (this._parent) return this._parent.has(ctor);
  149. return false;
  150. }
  151. /**
  152. * Добавить конструктор в контейнер.
  153. *
  154. * @param {*} ctor
  155. * @param {*} args
  156. * @returns {this}
  157. */
  158. add(ctor, ...args) {
  159. if (!ctor || typeof ctor !== "function")
  160. throw new InvalidArgumentError(
  161. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  162. ctor
  163. );
  164. const factory = /* @__PURE__ */ __name(() => Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args), "factory");
  165. this._services.set(ctor, factory);
  166. return this;
  167. }
  168. /**
  169. * Добавить конструктор и создать экземпляр.
  170. *
  171. * @param {*} ctor
  172. * @param {*} args
  173. * @returns {this}
  174. */
  175. use(ctor, ...args) {
  176. if (!ctor || typeof ctor !== "function")
  177. throw new InvalidArgumentError(
  178. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  179. ctor
  180. );
  181. const service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  182. this._services.set(ctor, service);
  183. return this;
  184. }
  185. /**
  186. * Добавить конструктор и связанный экземпляр.
  187. *
  188. * @param {*} ctor
  189. * @param {*} service
  190. * @returns {this}
  191. */
  192. set(ctor, service) {
  193. if (!ctor || typeof ctor !== "function")
  194. throw new InvalidArgumentError(
  195. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  196. ctor
  197. );
  198. if (!service || typeof service !== "object" || Array.isArray(service))
  199. throw new InvalidArgumentError(
  200. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  201. service
  202. );
  203. this._services.set(ctor, service);
  204. return this;
  205. }
  206. /**
  207. * Найти сервис удовлетворяющий условию.
  208. *
  209. * @param {function(Function, ServiceContainer): boolean} predicate
  210. * @param {boolean} noParent
  211. * @returns {*}
  212. */
  213. find(predicate, noParent = false) {
  214. if (typeof predicate !== "function") {
  215. throw new InvalidArgumentError(
  216. "The first argument of ServiceContainer.find must be a function, but %v given.",
  217. predicate
  218. );
  219. }
  220. const isRecursive = !noParent;
  221. let currentContainer = this;
  222. do {
  223. for (const ctor of currentContainer._services.keys()) {
  224. if (predicate(ctor, currentContainer) === true) {
  225. return this.get(ctor);
  226. }
  227. }
  228. if (isRecursive && currentContainer.hasParent()) {
  229. currentContainer = currentContainer.getParent();
  230. } else {
  231. currentContainer = null;
  232. }
  233. } while (currentContainer);
  234. return void 0;
  235. }
  236. };
  237. __name(_ServiceContainer, "ServiceContainer");
  238. /**
  239. * Kinds.
  240. *
  241. * @type {string[]}
  242. */
  243. __publicField(_ServiceContainer, "kinds", [SERVICE_CONTAINER_CLASS_NAME]);
  244. var ServiceContainer = _ServiceContainer;
  245. // node_modules/@e22m4u/js-service/src/utils/is-service-container.js
  246. function isServiceContainer(container) {
  247. return Boolean(
  248. container && typeof container === "object" && typeof container.constructor === "function" && Array.isArray(container.constructor.kinds) && container.constructor.kinds.includes(SERVICE_CONTAINER_CLASS_NAME)
  249. );
  250. }
  251. __name(isServiceContainer, "isServiceContainer");
  252. // node_modules/@e22m4u/js-service/src/service.js
  253. var SERVICE_CLASS_NAME = "Service";
  254. var _Service = class _Service {
  255. /**
  256. * Container.
  257. *
  258. * @type {ServiceContainer}
  259. */
  260. container;
  261. /**
  262. * Constructor.
  263. *
  264. * @param {ServiceContainer|undefined} container
  265. */
  266. constructor(container = void 0) {
  267. this.container = isServiceContainer(container) ? container : new ServiceContainer();
  268. }
  269. /**
  270. * Получить существующий или новый экземпляр.
  271. *
  272. * @param {*} ctor
  273. * @param {*} args
  274. * @returns {*}
  275. */
  276. getService(ctor, ...args) {
  277. return this.container.get(ctor, ...args);
  278. }
  279. /**
  280. * Получить существующий или новый экземпляр,
  281. * только если конструктор зарегистрирован.
  282. *
  283. * @param {*} ctor
  284. * @param {*} args
  285. * @returns {*}
  286. */
  287. getRegisteredService(ctor, ...args) {
  288. return this.container.getRegistered(ctor, ...args);
  289. }
  290. /**
  291. * Проверка существования конструктора в контейнере.
  292. *
  293. * @param {*} ctor
  294. * @returns {boolean}
  295. */
  296. hasService(ctor) {
  297. return this.container.has(ctor);
  298. }
  299. /**
  300. * Добавить конструктор в контейнер.
  301. *
  302. * @param {*} ctor
  303. * @param {*} args
  304. * @returns {this}
  305. */
  306. addService(ctor, ...args) {
  307. this.container.add(ctor, ...args);
  308. return this;
  309. }
  310. /**
  311. * Добавить конструктор и создать экземпляр.
  312. *
  313. * @param {*} ctor
  314. * @param {*} args
  315. * @returns {this}
  316. */
  317. useService(ctor, ...args) {
  318. this.container.use(ctor, ...args);
  319. return this;
  320. }
  321. /**
  322. * Добавить конструктор и связанный экземпляр.
  323. *
  324. * @param {*} ctor
  325. * @param {*} service
  326. * @returns {this}
  327. */
  328. setService(ctor, service) {
  329. this.container.set(ctor, service);
  330. return this;
  331. }
  332. /**
  333. * Найти сервис удовлетворяющий условию.
  334. *
  335. * @param {function(Function, ServiceContainer): boolean} predicate
  336. * @param {boolean} noParent
  337. * @returns {*}
  338. */
  339. findService(predicate, noParent = false) {
  340. return this.container.find(predicate, noParent);
  341. }
  342. };
  343. __name(_Service, "Service");
  344. /**
  345. * Kinds.
  346. *
  347. * @type {string[]}
  348. */
  349. __publicField(_Service, "kinds", [SERVICE_CLASS_NAME]);
  350. var Service = _Service;
  351. // node_modules/@e22m4u/js-debug/src/utils/to-camel-case.js
  352. function toCamelCase(input) {
  353. return input.replace(/(^\w|[A-Z]|\b\w)/g, (c) => c.toUpperCase()).replace(/\W+/g, "").replace(/(^\w)/g, (c) => c.toLowerCase());
  354. }
  355. __name(toCamelCase, "toCamelCase");
  356. // node_modules/@e22m4u/js-debug/src/utils/is-non-array-object.js
  357. function isNonArrayObject(input) {
  358. return Boolean(input && typeof input === "object" && !Array.isArray(input));
  359. }
  360. __name(isNonArrayObject, "isNonArrayObject");
  361. // node_modules/@e22m4u/js-debug/src/utils/generate-random-hex.js
  362. function generateRandomHex(length = 4) {
  363. if (length <= 0) {
  364. return "";
  365. }
  366. const firstCharCandidates = "abcdef";
  367. const restCharCandidates = "0123456789abcdef";
  368. let result = "";
  369. const firstCharIndex = Math.floor(Math.random() * firstCharCandidates.length);
  370. result += firstCharCandidates[firstCharIndex];
  371. for (let i = 1; i < length; i++) {
  372. const randomIndex = Math.floor(Math.random() * restCharCandidates.length);
  373. result += restCharCandidates[randomIndex];
  374. }
  375. return result;
  376. }
  377. __name(generateRandomHex, "generateRandomHex");
  378. // node_modules/@e22m4u/js-debug/src/debuggable.js
  379. var _Debuggable = class _Debuggable {
  380. /**
  381. * Debug.
  382. *
  383. * @type {Function}
  384. */
  385. debug;
  386. /**
  387. * Ctor Debug.
  388. *
  389. * @type {Function}
  390. */
  391. ctorDebug;
  392. /**
  393. * Возвращает функцию-отладчик с сегментом пространства имен
  394. * указанного в параметре метода.
  395. *
  396. * @param {Function} method
  397. * @returns {Function}
  398. */
  399. getDebuggerFor(method) {
  400. const name = method.name || "anonymous";
  401. return this.debug.withHash().withNs(name);
  402. }
  403. /**
  404. * Constructor.
  405. *
  406. * @param {DebuggableOptions|undefined} options
  407. */
  408. constructor(options = void 0) {
  409. const className = toCamelCase(this.constructor.name);
  410. options = typeof options === "object" && options || {};
  411. const namespace = options.namespace && String(options.namespace) || void 0;
  412. if (namespace) {
  413. this.debug = createDebugger(namespace, className);
  414. } else {
  415. this.debug = createDebugger(className);
  416. }
  417. const noEnvironmentNamespace = Boolean(options.noEnvironmentNamespace);
  418. if (noEnvironmentNamespace) this.debug = this.debug.withoutEnvNs();
  419. this.ctorDebug = this.debug.withNs("constructor").withHash();
  420. const noInstantiationMessage = Boolean(options.noInstantiationMessage);
  421. if (!noInstantiationMessage)
  422. this.ctorDebug(_Debuggable.INSTANTIATION_MESSAGE);
  423. }
  424. };
  425. __name(_Debuggable, "Debuggable");
  426. /**
  427. * Instantiation message;
  428. *
  429. * @type {string}
  430. */
  431. __publicField(_Debuggable, "INSTANTIATION_MESSAGE", "Instantiated.");
  432. var Debuggable = _Debuggable;
  433. // node_modules/@e22m4u/js-debug/src/create-debugger.js
  434. var import_js_format2 = require("@e22m4u/js-format");
  435. var import_js_format3 = require("@e22m4u/js-format");
  436. // node_modules/@e22m4u/js-debug/src/create-colorized-dump.js
  437. var import_util = require("util");
  438. var INSPECT_OPTIONS = {
  439. showHidden: false,
  440. depth: null,
  441. colors: true,
  442. compact: false
  443. };
  444. function createColorizedDump(value) {
  445. return (0, import_util.inspect)(value, INSPECT_OPTIONS);
  446. }
  447. __name(createColorizedDump, "createColorizedDump");
  448. // node_modules/@e22m4u/js-debug/src/create-debugger.js
  449. var AVAILABLE_COLORS = [
  450. 20,
  451. 21,
  452. 26,
  453. 27,
  454. 32,
  455. 33,
  456. 38,
  457. 39,
  458. 40,
  459. 41,
  460. 42,
  461. 43,
  462. 44,
  463. 45,
  464. 56,
  465. 57,
  466. 62,
  467. 63,
  468. 68,
  469. 69,
  470. 74,
  471. 75,
  472. 76,
  473. 77,
  474. 78,
  475. 79,
  476. 80,
  477. 81,
  478. 92,
  479. 93,
  480. 98,
  481. 99,
  482. 112,
  483. 113,
  484. 128,
  485. 129,
  486. 134,
  487. 135,
  488. 148,
  489. 149,
  490. 160,
  491. 161,
  492. 162,
  493. 163,
  494. 164,
  495. 165,
  496. 166,
  497. 167,
  498. 168,
  499. 169,
  500. 170,
  501. 171,
  502. 172,
  503. 173,
  504. 178,
  505. 179,
  506. 184,
  507. 185,
  508. 196,
  509. 197,
  510. 198,
  511. 199,
  512. 200,
  513. 201,
  514. 202,
  515. 203,
  516. 204,
  517. 205,
  518. 206,
  519. 207,
  520. 208,
  521. 209,
  522. 214,
  523. 215,
  524. 220,
  525. 221
  526. ];
  527. var DEFAULT_OFFSET_STEP_SPACES = 2;
  528. function pickColorCode(input) {
  529. if (typeof input !== "string")
  530. throw new import_js_format2.Errorf(
  531. 'The parameter "input" of the function pickColorCode must be a String, but %v given.',
  532. input
  533. );
  534. let hash = 0;
  535. for (let i = 0; i < input.length; i++) {
  536. hash = (hash << 5) - hash + input.charCodeAt(i);
  537. hash |= 0;
  538. }
  539. return AVAILABLE_COLORS[Math.abs(hash) % AVAILABLE_COLORS.length];
  540. }
  541. __name(pickColorCode, "pickColorCode");
  542. function wrapStringByColorCode(input, color) {
  543. if (typeof input !== "string")
  544. throw new import_js_format2.Errorf(
  545. 'The parameter "input" of the function wrapStringByColorCode must be a String, but %v given.',
  546. input
  547. );
  548. if (typeof color !== "number")
  549. throw new import_js_format2.Errorf(
  550. 'The parameter "color" of the function wrapStringByColorCode must be a Number, but %v given.',
  551. color
  552. );
  553. const colorCode = "\x1B[3" + (Number(color) < 8 ? color : "8;5;" + color);
  554. return `${colorCode};1m${input}\x1B[0m`;
  555. }
  556. __name(wrapStringByColorCode, "wrapStringByColorCode");
  557. function matchPattern(pattern, input) {
  558. if (typeof pattern !== "string")
  559. throw new import_js_format2.Errorf(
  560. 'The parameter "pattern" of the function matchPattern must be a String, but %v given.',
  561. pattern
  562. );
  563. if (typeof input !== "string")
  564. throw new import_js_format2.Errorf(
  565. 'The parameter "input" of the function matchPattern must be a String, but %v given.',
  566. input
  567. );
  568. const regexpStr = pattern.replace(/\*/g, ".*?");
  569. const regexp = new RegExp("^" + regexpStr + "$");
  570. return regexp.test(input);
  571. }
  572. __name(matchPattern, "matchPattern");
  573. function createDebugger(namespaceOrOptions = void 0, ...namespaceSegments) {
  574. if (namespaceOrOptions && typeof namespaceOrOptions !== "string" && !isNonArrayObject(namespaceOrOptions)) {
  575. throw new import_js_format2.Errorf(
  576. 'The parameter "namespace" of the function createDebugger must be a String or an Object, but %v given.',
  577. namespaceOrOptions
  578. );
  579. }
  580. const withCustomState = isNonArrayObject(namespaceOrOptions);
  581. const state = withCustomState ? namespaceOrOptions : {};
  582. state.envNsSegments = Array.isArray(state.envNsSegments) ? state.envNsSegments : [];
  583. state.nsSegments = Array.isArray(state.nsSegments) ? state.nsSegments : [];
  584. state.pattern = typeof state.pattern === "string" ? state.pattern : "";
  585. state.hash = typeof state.hash === "string" ? state.hash : "";
  586. state.offsetSize = typeof state.offsetSize === "number" ? state.offsetSize : 0;
  587. state.offsetStep = typeof state.offsetStep !== "string" ? " ".repeat(DEFAULT_OFFSET_STEP_SPACES) : state.offsetStep;
  588. state.delimiter = state.delimiter && typeof state.delimiter === "string" ? state.delimiter : ":";
  589. if (!withCustomState) {
  590. if (typeof process !== "undefined" && process.env && process.env["DEBUGGER_NAMESPACE"]) {
  591. state.envNsSegments.push(process.env.DEBUGGER_NAMESPACE);
  592. }
  593. if (typeof namespaceOrOptions === "string")
  594. state.nsSegments.push(namespaceOrOptions);
  595. }
  596. namespaceSegments.forEach((segment) => {
  597. if (!segment || typeof segment !== "string")
  598. throw new import_js_format2.Errorf(
  599. "Namespace segment must be a non-empty String, but %v given.",
  600. segment
  601. );
  602. state.nsSegments.push(segment);
  603. });
  604. if (typeof process !== "undefined" && process.env && process.env["DEBUG"]) {
  605. state.pattern = process.env["DEBUG"];
  606. } else if (typeof localStorage !== "undefined" && typeof localStorage.getItem("debug") === "string") {
  607. state.pattern = localStorage.getItem("debug");
  608. }
  609. const isDebuggerEnabled = /* @__PURE__ */ __name(() => {
  610. const nsStr = [...state.envNsSegments, ...state.nsSegments].join(
  611. state.delimiter
  612. );
  613. const patterns = state.pattern.split(/[\s,]+/).filter((p) => p.length > 0);
  614. if (patterns.length === 0 && state.pattern !== "*") return false;
  615. for (const singlePattern of patterns) {
  616. if (matchPattern(singlePattern, nsStr)) return true;
  617. }
  618. return false;
  619. }, "isDebuggerEnabled");
  620. const getPrefix = /* @__PURE__ */ __name(() => {
  621. let tokens = [];
  622. [...state.envNsSegments, ...state.nsSegments, state.hash].filter(Boolean).forEach((token) => {
  623. const extractedTokens = token.split(state.delimiter).filter(Boolean);
  624. tokens = [...tokens, ...extractedTokens];
  625. });
  626. let res = tokens.reduce((acc, token, index) => {
  627. const isLast = tokens.length - 1 === index;
  628. const tokenColor = pickColorCode(token);
  629. acc += wrapStringByColorCode(token, tokenColor);
  630. if (!isLast) acc += state.delimiter;
  631. return acc;
  632. }, "");
  633. if (state.offsetSize > 0) res += state.offsetStep.repeat(state.offsetSize);
  634. return res;
  635. }, "getPrefix");
  636. function debugFn(messageOrData, ...args) {
  637. if (!isDebuggerEnabled()) return;
  638. const prefix = getPrefix();
  639. const multiString = (0, import_js_format3.format)(messageOrData, ...args);
  640. const rows = multiString.split("\n");
  641. rows.forEach((message) => {
  642. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  643. });
  644. }
  645. __name(debugFn, "debugFn");
  646. debugFn.withNs = function(namespace, ...args) {
  647. const stateCopy = JSON.parse(JSON.stringify(state));
  648. [namespace, ...args].forEach((ns) => {
  649. if (!ns || typeof ns !== "string")
  650. throw new import_js_format2.Errorf(
  651. "Debugger namespace must be a non-empty String, but %v given.",
  652. ns
  653. );
  654. stateCopy.nsSegments.push(ns);
  655. });
  656. return createDebugger(stateCopy);
  657. };
  658. debugFn.withHash = function(hashLength = 4) {
  659. const stateCopy = JSON.parse(JSON.stringify(state));
  660. if (!hashLength || typeof hashLength !== "number" || hashLength < 1) {
  661. throw new import_js_format2.Errorf(
  662. "Debugger hash must be a positive Number, but %v given.",
  663. hashLength
  664. );
  665. }
  666. stateCopy.hash = generateRandomHex(hashLength);
  667. return createDebugger(stateCopy);
  668. };
  669. debugFn.withOffset = function(offsetSize) {
  670. const stateCopy = JSON.parse(JSON.stringify(state));
  671. if (!offsetSize || typeof offsetSize !== "number" || offsetSize < 1) {
  672. throw new import_js_format2.Errorf(
  673. "Debugger offset must be a positive Number, but %v given.",
  674. offsetSize
  675. );
  676. }
  677. stateCopy.offsetSize = offsetSize;
  678. return createDebugger(stateCopy);
  679. };
  680. debugFn.withoutEnvNs = function() {
  681. const stateCopy = JSON.parse(JSON.stringify(state));
  682. stateCopy.envNsSegments = [];
  683. return createDebugger(stateCopy);
  684. };
  685. debugFn.inspect = function(valueOrDesc, ...args) {
  686. if (!isDebuggerEnabled()) return;
  687. const prefix = getPrefix();
  688. let multiString = "";
  689. if (typeof valueOrDesc === "string" && args.length) {
  690. multiString += `${valueOrDesc}
  691. `;
  692. const multilineDump = args.map((v) => createColorizedDump(v)).join("\n");
  693. const dumpRows = multilineDump.split("\n");
  694. multiString += dumpRows.map((v) => `${state.offsetStep}${v}`).join("\n");
  695. } else {
  696. multiString += [valueOrDesc, ...args].map((v) => createColorizedDump(v)).join("\n");
  697. }
  698. const rows = multiString.split("\n");
  699. rows.forEach((message) => {
  700. prefix ? console.log(`${prefix} ${message}`) : console.log(message);
  701. });
  702. };
  703. debugFn.state = state;
  704. return debugFn;
  705. }
  706. __name(createDebugger, "createDebugger");
  707. // node_modules/@e22m4u/js-service/src/debuggable-service.js
  708. var _DebuggableService = class _DebuggableService extends Debuggable {
  709. /**
  710. * Service.
  711. *
  712. * @type {Service}
  713. */
  714. _service;
  715. /**
  716. * Container.
  717. *
  718. * @type {ServiceContainer}
  719. */
  720. get container() {
  721. return this._service.container;
  722. }
  723. /**
  724. * Получить существующий или новый экземпляр.
  725. *
  726. * @type {Service['getService']}
  727. */
  728. get getService() {
  729. return this._service.getService;
  730. }
  731. /**
  732. * Получить существующий или новый экземпляр,
  733. * только если конструктор зарегистрирован.
  734. *
  735. * @type {Service['getRegisteredService']}
  736. */
  737. get getRegisteredService() {
  738. return this._service.getRegisteredService;
  739. }
  740. /**
  741. * Проверка существования конструктора в контейнере.
  742. *
  743. * @type {Service['hasService']}
  744. */
  745. get hasService() {
  746. return this._service.hasService;
  747. }
  748. /**
  749. * Добавить конструктор в контейнер.
  750. *
  751. * @type {Service['addService']}
  752. */
  753. get addService() {
  754. return this._service.addService;
  755. }
  756. /**
  757. * Добавить конструктор и создать экземпляр.
  758. *
  759. * @type {Service['useService']}
  760. */
  761. get useService() {
  762. return this._service.useService;
  763. }
  764. /**
  765. * Добавить конструктор и связанный экземпляр.
  766. *
  767. * @type {Service['setService']}
  768. */
  769. get setService() {
  770. return this._service.setService;
  771. }
  772. /**
  773. * Найти сервис удовлетворяющий условию.
  774. *
  775. * @type {Service['findService']}
  776. */
  777. get findService() {
  778. return this._service.findService;
  779. }
  780. /**
  781. * Constructor.
  782. *
  783. * @param {ServiceContainer|undefined} container
  784. * @param {import('@e22m4u/js-debug').DebuggableOptions|undefined} options
  785. */
  786. constructor(container = void 0, options = void 0) {
  787. super(options);
  788. this._service = new Service(container);
  789. }
  790. };
  791. __name(_DebuggableService, "DebuggableService");
  792. /**
  793. * Kinds.
  794. *
  795. * @type {string[]}
  796. */
  797. __publicField(_DebuggableService, "kinds", Service.kinds);
  798. var DebuggableService = _DebuggableService;
  799. // src/mongodb-adapter.js
  800. var import_js_repository3 = require("@e22m4u/js-repository");
  801. // src/utils/pluralize.js
  802. var singularExceptions = [
  803. /access$/i,
  804. /address$/i,
  805. /alias$/i,
  806. /bonus$/i,
  807. /boss$/i,
  808. /bus$/i,
  809. /business$/i,
  810. /canvas$/i,
  811. /class$/i,
  812. /cross$/i,
  813. /dress$/i,
  814. /focus$/i,
  815. /gas$/i,
  816. /glass$/i,
  817. /kiss$/i,
  818. /lens$/i,
  819. /loss$/i,
  820. /pass$/i,
  821. /plus$/i,
  822. /process$/i,
  823. /status$/i,
  824. /success$/i,
  825. /virus$/i
  826. ];
  827. function pluralize(input) {
  828. if (!input || typeof input !== "string") {
  829. return input;
  830. }
  831. if (/s$/i.test(input) && !singularExceptions.some((re) => re.test(input))) {
  832. return input;
  833. }
  834. const lastChar = input.slice(-1);
  835. const isLastCharUpper = lastChar === lastChar.toUpperCase() && lastChar !== lastChar.toLowerCase();
  836. if (/(s|x|z|ch|sh)$/i.test(input)) {
  837. return input + (isLastCharUpper ? "ES" : "es");
  838. }
  839. if (/[^aeiou]y$/i.test(input)) {
  840. return input.slice(0, -1) + (isLastCharUpper ? "IES" : "ies");
  841. }
  842. return input + (isLastCharUpper ? "S" : "s");
  843. }
  844. __name(pluralize, "pluralize");
  845. // src/utils/is-iso-date.js
  846. function isIsoDate(value) {
  847. if (!value) return false;
  848. if (value instanceof Date) return true;
  849. if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(value)) return false;
  850. const d = new Date(value);
  851. return d instanceof Date && !isNaN(d.getTime()) && d.toISOString() === value;
  852. }
  853. __name(isIsoDate, "isIsoDate");
  854. // src/utils/is-object-id.js
  855. var import_mongodb = require("mongodb");
  856. function isObjectId(value) {
  857. if (!value) return false;
  858. if (value instanceof import_mongodb.ObjectId) return true;
  859. if (typeof value !== "string") return false;
  860. return value.match(/^[a-fA-F0-9]{24}$/) != null;
  861. }
  862. __name(isObjectId, "isObjectId");
  863. // src/utils/to-camel-case.js
  864. function toCamelCase2(input) {
  865. if (!input) return "";
  866. const spacedString = String(input).replace(/([-_])/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2");
  867. const intermediateCased = spacedString.toLowerCase().replace(/\s(.)/g, ($1) => $1.toUpperCase()).replace(/\s/g, "");
  868. if (!intermediateCased) return "";
  869. return intermediateCased.charAt(0).toLowerCase() + intermediateCased.slice(1);
  870. }
  871. __name(toCamelCase2, "toCamelCase");
  872. // src/utils/create-mongodb-url.js
  873. var import_js_repository = require("@e22m4u/js-repository");
  874. function createMongodbUrl(options = {}) {
  875. if (!options || typeof options !== "object" || Array.isArray(options))
  876. throw new import_js_repository.InvalidArgumentError(
  877. 'The first argument of "createMongodbUrl" must be an Object, but %v given.',
  878. options
  879. );
  880. if (options.protocol && typeof options.protocol !== "string")
  881. throw new import_js_repository.InvalidArgumentError(
  882. 'MongoDB option "protocol" must be a String, but %v given.',
  883. options.protocol
  884. );
  885. if (options.hostname && typeof options.hostname !== "string")
  886. throw new import_js_repository.InvalidArgumentError(
  887. 'MongoDB option "hostname" must be a String, but %v given.',
  888. options.hostname
  889. );
  890. if (options.host && typeof options.host !== "string")
  891. throw new import_js_repository.InvalidArgumentError(
  892. 'MongoDB option "host" must be a String, but %v given.',
  893. options.host
  894. );
  895. if (options.port && typeof options.port !== "number" && typeof options.port !== "string") {
  896. throw new import_js_repository.InvalidArgumentError(
  897. 'MongoDB option "port" must be a Number or a String, but %v given.',
  898. options.port
  899. );
  900. }
  901. if (options.database && typeof options.database !== "string")
  902. throw new import_js_repository.InvalidArgumentError(
  903. 'MongoDB option "database" must be a String, but %v given.',
  904. options.database
  905. );
  906. if (options.db && typeof options.db !== "string")
  907. throw new import_js_repository.InvalidArgumentError(
  908. 'MongoDB option "db" must be a String, but %v given.',
  909. options.db
  910. );
  911. if (options.username && typeof options.username !== "string")
  912. throw new import_js_repository.InvalidArgumentError(
  913. 'MongoDB option "username" must be a String, but %v given.',
  914. options.username
  915. );
  916. if (options.password && typeof options.password !== "string" && typeof options.password !== "number") {
  917. throw new import_js_repository.InvalidArgumentError(
  918. 'MongoDB option "password" must be a String or a Number, but %v given.',
  919. options.password
  920. );
  921. }
  922. if (options.pass && typeof options.pass !== "string" && typeof options.pass !== "number") {
  923. throw new import_js_repository.InvalidArgumentError(
  924. 'MongoDB option "pass" must be a String or a Number, but %v given.',
  925. options.pass
  926. );
  927. }
  928. const protocol = options.protocol || "mongodb";
  929. const hostname = options.hostname || options.host || "127.0.0.1";
  930. const port = options.port || 27017;
  931. const database = options.database || options.db || "database";
  932. const username = options.username || options.user;
  933. const password = options.password || options.pass || void 0;
  934. let portUrl = "";
  935. if (protocol !== "mongodb+srv") {
  936. portUrl = ":" + port;
  937. }
  938. if (username && password) {
  939. return `${protocol}://${username}:${password}@${hostname}${portUrl}/${database}`;
  940. } else {
  941. return `${protocol}://${hostname}${portUrl}/${database}`;
  942. }
  943. }
  944. __name(createMongodbUrl, "createMongodbUrl");
  945. // src/utils/transform-values-deep.js
  946. var import_js_repository2 = require("@e22m4u/js-repository");
  947. function transformValuesDeep(value, transformer) {
  948. if (!transformer || typeof transformer !== "function")
  949. throw new import_js_repository2.InvalidArgumentError(
  950. 'The second argument of "transformValuesDeep" must be a Function, but %v given.',
  951. transformer
  952. );
  953. if (Array.isArray(value)) {
  954. value.forEach((v, i) => value[i] = transformValuesDeep(v, transformer));
  955. return value;
  956. } else if (value && typeof value === "object") {
  957. if (!value.constructor || value.constructor && value.constructor.name === "Object") {
  958. Object.keys(value).forEach((key) => {
  959. if (Object.prototype.hasOwnProperty.call(value, key))
  960. value[key] = transformValuesDeep(value[key], transformer);
  961. });
  962. return value;
  963. } else {
  964. return transformer(value);
  965. }
  966. } else {
  967. return transformer(value);
  968. }
  969. }
  970. __name(transformValuesDeep, "transformValuesDeep");
  971. // src/mongodb-adapter.js
  972. var MONGODB_OPTION_NAMES = [
  973. "ALPNProtocols",
  974. "allowPartialTrustChain",
  975. "appName",
  976. "auth",
  977. "authMechanism",
  978. "authMechanismProperties",
  979. "authSource",
  980. "autoEncryption",
  981. "autoSelectFamily",
  982. "autoSelectFamilyAttemptTimeout",
  983. "bsonRegExp",
  984. "ca",
  985. "cert",
  986. "checkKeys",
  987. "checkServerIdentity",
  988. "ciphers",
  989. "compressors",
  990. "connectTimeoutMS",
  991. "crl",
  992. "directConnection",
  993. "driverInfo",
  994. "ecdhCurve",
  995. "enableUtf8Validation",
  996. "family",
  997. "fieldsAsRaw",
  998. "forceServerObjectId",
  999. "heartbeatFrequencyMS",
  1000. "hints",
  1001. "ignoreUndefined",
  1002. "journal",
  1003. "keepAliveInitialDelay",
  1004. "key",
  1005. "loadBalanced",
  1006. "localAddress",
  1007. "localPort",
  1008. "localThresholdMS",
  1009. "lookup",
  1010. "maxConnecting",
  1011. "maxIdleTimeMS",
  1012. "maxPoolSize",
  1013. "maxStalenessSeconds",
  1014. "minDHSize",
  1015. "minHeartbeatFrequencyMS",
  1016. "minPoolSize",
  1017. "mongodbLogComponentSeverities",
  1018. "mongodbLogMaxDocumentLength",
  1019. "mongodbLogPath",
  1020. "monitorCommands",
  1021. "noDelay",
  1022. "passphrase",
  1023. "pfx",
  1024. "pkFactory",
  1025. "promoteBuffers",
  1026. "promoteLongs",
  1027. "promoteValues",
  1028. "proxyHost",
  1029. "proxyPassword",
  1030. "proxyPort",
  1031. "proxyUsername",
  1032. "raw",
  1033. "readConcern",
  1034. "readConcernLevel",
  1035. "readPreference",
  1036. "readPreferenceTags",
  1037. "rejectUnauthorized",
  1038. "replicaSet",
  1039. "retryReads",
  1040. "retryWrites",
  1041. "secureContext",
  1042. "secureProtocol",
  1043. "serializeFunctions",
  1044. "serverApi",
  1045. "serverMonitoringMode",
  1046. "serverSelectionTimeoutMS",
  1047. "servername",
  1048. "session",
  1049. "socketTimeoutMS",
  1050. "srvMaxHosts",
  1051. "srvServiceName",
  1052. "ssl",
  1053. "timeoutMS",
  1054. "tls",
  1055. "tlsAllowInvalidCertificates",
  1056. "tlsAllowInvalidHostnames",
  1057. "tlsCAFile",
  1058. "tlsCRLFile",
  1059. "tlsCertificateKeyFile",
  1060. "tlsCertificateKeyFilePassword",
  1061. "tlsInsecure",
  1062. "useBigInt64",
  1063. "w",
  1064. "waitQueueTimeoutMS",
  1065. "writeConcern",
  1066. "wtimeoutMS",
  1067. "zlibCompressionLevel"
  1068. ];
  1069. var DEFAULT_SETTINGS = {
  1070. // connectTimeoutMS: 2500,
  1071. // serverSelectionTimeoutMS: 2500,
  1072. };
  1073. var _MongodbAdapter = class _MongodbAdapter extends import_js_repository3.Adapter {
  1074. /**
  1075. * Mongodb instance.
  1076. *
  1077. * @type {MongoClient}
  1078. */
  1079. _client;
  1080. /**
  1081. * Client.
  1082. *
  1083. * @returns {MongoClient}
  1084. */
  1085. get client() {
  1086. return this._client;
  1087. }
  1088. /**
  1089. * Collections.
  1090. *
  1091. * @type {Map<any, any>}
  1092. */
  1093. _collections = /* @__PURE__ */ new Map();
  1094. /**
  1095. * Constructor.
  1096. *
  1097. * @param {ServiceContainer} container
  1098. * @param {object} settings
  1099. */
  1100. constructor(container, settings) {
  1101. settings = Object.assign({}, DEFAULT_SETTINGS, settings || {});
  1102. settings.protocol = settings.protocol || "mongodb";
  1103. settings.hostname = settings.hostname || settings.host || "127.0.0.1";
  1104. settings.port = settings.port || 27017;
  1105. settings.database = settings.database || settings.db || "database";
  1106. super(container, settings);
  1107. const options = (0, import_js_repository3.selectObjectKeys)(this.settings, MONGODB_OPTION_NAMES);
  1108. const url = createMongodbUrl(this.settings);
  1109. this._client = new import_mongodb2.MongoClient(url, options);
  1110. }
  1111. /**
  1112. * Get id prop name.
  1113. *
  1114. * @param {string} modelName
  1115. * @returns {string}
  1116. */
  1117. _getIdPropName(modelName) {
  1118. return this.getService(import_js_repository3.ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  1119. modelName
  1120. );
  1121. }
  1122. /**
  1123. * Get id col name.
  1124. *
  1125. * @param {string} modelName
  1126. * @returns {string}
  1127. */
  1128. _getIdColName(modelName) {
  1129. return this.getService(import_js_repository3.ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  1130. modelName
  1131. );
  1132. }
  1133. /**
  1134. * Coerce id.
  1135. *
  1136. * @param {*} value
  1137. * @returns {ObjectId|*}
  1138. */
  1139. _coerceId(value) {
  1140. if (value == null) return value;
  1141. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1142. return value;
  1143. }
  1144. /**
  1145. * Coerce date.
  1146. *
  1147. * @param {Date|string|*} value
  1148. * @returns {Date|*}
  1149. */
  1150. _coerceDate(value) {
  1151. if (value == null) return value;
  1152. if (value instanceof Date) return value;
  1153. if (isIsoDate(value)) return new Date(value);
  1154. return value;
  1155. }
  1156. /**
  1157. * To database.
  1158. *
  1159. * @param {string} modelName
  1160. * @param {object} modelData
  1161. * @returns {object}
  1162. */
  1163. _toDatabase(modelName, modelData) {
  1164. const tableData = this.getService(
  1165. import_js_repository3.ModelDefinitionUtils
  1166. ).convertPropertyNamesToColumnNames(modelName, modelData);
  1167. const idColName = this._getIdColName(modelName);
  1168. if (idColName !== "id" && idColName !== "_id")
  1169. throw new import_js_repository3.InvalidArgumentError(
  1170. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1171. idColName
  1172. );
  1173. if (idColName in tableData && idColName !== "_id") {
  1174. tableData._id = tableData[idColName];
  1175. delete tableData[idColName];
  1176. }
  1177. return transformValuesDeep(tableData, (value) => {
  1178. if (value instanceof import_mongodb2.ObjectId) return value;
  1179. if (value instanceof Date) return value;
  1180. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1181. if (isIsoDate(value)) return new Date(value);
  1182. return value;
  1183. });
  1184. }
  1185. /**
  1186. * From database.
  1187. *
  1188. * @param {string} modelName
  1189. * @param {object} tableData
  1190. * @returns {object}
  1191. */
  1192. _fromDatabase(modelName, tableData) {
  1193. if ("_id" in tableData) {
  1194. const idColName = this._getIdColName(modelName);
  1195. if (idColName !== "id" && idColName !== "_id")
  1196. throw new import_js_repository3.InvalidArgumentError(
  1197. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1198. idColName
  1199. );
  1200. if (idColName !== "_id") {
  1201. tableData[idColName] = tableData._id;
  1202. delete tableData._id;
  1203. }
  1204. }
  1205. const modelData = this.getService(
  1206. import_js_repository3.ModelDefinitionUtils
  1207. ).convertColumnNamesToPropertyNames(modelName, tableData);
  1208. return transformValuesDeep(modelData, (value) => {
  1209. if (value instanceof import_mongodb2.ObjectId) return String(value);
  1210. if (value instanceof Date) return value.toISOString();
  1211. return value;
  1212. });
  1213. }
  1214. /**
  1215. * Get collection name by model name.
  1216. *
  1217. * @param {string} modelName
  1218. * @returns {string}
  1219. */
  1220. _getCollectionNameByModelName(modelName) {
  1221. const modelDef = this.getService(import_js_repository3.DefinitionRegistry).getModel(modelName);
  1222. if (modelDef.tableName != null) return modelDef.tableName;
  1223. return pluralize(toCamelCase2(modelDef.name));
  1224. }
  1225. /**
  1226. * Get collection.
  1227. *
  1228. * @param {string} modelName
  1229. * @returns {*}
  1230. */
  1231. _getCollection(modelName) {
  1232. let collection = this._collections.get(modelName);
  1233. if (collection) return collection;
  1234. const collectionName = this._getCollectionNameByModelName(modelName);
  1235. collection = this.client.db(this.settings.database).collection(collectionName);
  1236. this._collections.set(modelName, collection);
  1237. return collection;
  1238. }
  1239. /**
  1240. * Get id type.
  1241. *
  1242. * @param {string} modelName
  1243. * @returns {string|*}
  1244. */
  1245. _getIdType(modelName) {
  1246. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1247. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  1248. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  1249. }
  1250. /**
  1251. * Get col name.
  1252. *
  1253. * @param {string} modelName
  1254. * @param {string} propName
  1255. * @returns {string}
  1256. */
  1257. _getColName(modelName, propName) {
  1258. if (!propName || typeof propName !== "string")
  1259. throw new import_js_repository3.InvalidArgumentError(
  1260. "Property name must be a non-empty String, but %v given.",
  1261. propName
  1262. );
  1263. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1264. let colName = propName;
  1265. try {
  1266. colName = utils.getColumnNameByPropertyName(modelName, propName);
  1267. } catch (error) {
  1268. if (!(error instanceof import_js_repository3.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1269. throw error;
  1270. }
  1271. }
  1272. return colName;
  1273. }
  1274. /**
  1275. * Convert prop names chain to col names chain.
  1276. *
  1277. * @param {string} modelName
  1278. * @param {string} propsChain
  1279. * @returns {string}
  1280. */
  1281. _convertPropNamesChainToColNamesChain(modelName, propsChain) {
  1282. if (!modelName || typeof modelName !== "string")
  1283. throw new import_js_repository3.InvalidArgumentError(
  1284. "Model name must be a non-empty String, but %v given.",
  1285. modelName
  1286. );
  1287. if (!propsChain || typeof propsChain !== "string")
  1288. throw new import_js_repository3.InvalidArgumentError(
  1289. "Properties chain must be a non-empty String, but %v given.",
  1290. propsChain
  1291. );
  1292. propsChain = propsChain.replace(/\.{2,}/g, ".");
  1293. const propNames = propsChain.split(".");
  1294. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1295. let currModelName = modelName;
  1296. return propNames.map((currPropName) => {
  1297. if (!currModelName) return currPropName;
  1298. const colName = this._getColName(currModelName, currPropName);
  1299. currModelName = utils.getModelNameOfPropertyValueIfDefined(
  1300. currModelName,
  1301. currPropName
  1302. );
  1303. return colName;
  1304. }).join(".");
  1305. }
  1306. /**
  1307. * Build projection.
  1308. *
  1309. * @param {string} modelName
  1310. * @param {string|string[]} fields
  1311. * @returns {Record<string, number>|undefined}
  1312. */
  1313. _buildProjection(modelName, fields) {
  1314. if (fields == null) return;
  1315. if (Array.isArray(fields) === false) fields = [fields];
  1316. if (!fields.length) return;
  1317. if (fields.indexOf("_id") === -1) fields.push("_id");
  1318. return fields.reduce((acc, field) => {
  1319. if (!field || typeof field !== "string")
  1320. throw new import_js_repository3.InvalidArgumentError(
  1321. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  1322. field
  1323. );
  1324. let colName = this._convertPropNamesChainToColNamesChain(
  1325. modelName,
  1326. field
  1327. );
  1328. acc[colName] = 1;
  1329. return acc;
  1330. }, {});
  1331. }
  1332. /**
  1333. * Build sort.
  1334. *
  1335. * @param {string} modelName
  1336. * @param {string|string[]} clause
  1337. * @returns {object|undefined}
  1338. */
  1339. _buildSort(modelName, clause) {
  1340. if (clause == null) return;
  1341. if (Array.isArray(clause) === false) clause = [clause];
  1342. if (!clause.length) return;
  1343. const idPropName = this._getIdPropName(modelName);
  1344. return clause.reduce((acc, order) => {
  1345. if (!order || typeof order !== "string")
  1346. throw new import_js_repository3.InvalidArgumentError(
  1347. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  1348. order
  1349. );
  1350. const direction = order.match(/\s+(A|DE)SC$/);
  1351. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  1352. if (field === idPropName) {
  1353. field = "_id";
  1354. } else {
  1355. try {
  1356. field = this._convertPropNamesChainToColNamesChain(modelName, field);
  1357. } catch (error) {
  1358. if (!(error instanceof import_js_repository3.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1359. throw error;
  1360. }
  1361. }
  1362. }
  1363. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  1364. return acc;
  1365. }, {});
  1366. }
  1367. /**
  1368. * Build query.
  1369. *
  1370. * @param {string} modelName
  1371. * @param {object} clause
  1372. * @returns {object|undefined}
  1373. */
  1374. _buildQuery(modelName, clause) {
  1375. if (clause == null) return;
  1376. if (typeof clause !== "object" || Array.isArray(clause))
  1377. throw new import_js_repository3.InvalidArgumentError(
  1378. 'The provided option "where" should be an Object, but %v given.',
  1379. clause
  1380. );
  1381. const query = {};
  1382. const idPropName = this._getIdPropName(modelName);
  1383. Object.keys(clause).forEach((key) => {
  1384. var _a, _b;
  1385. if (String(key).indexOf("$") !== -1)
  1386. throw new import_js_repository3.InvalidArgumentError(
  1387. 'The symbol "$" is not supported, but %v given.',
  1388. key
  1389. );
  1390. let cond = clause[key];
  1391. if (key === "and" || key === "or" || key === "nor") {
  1392. if (cond == null) return;
  1393. if (!Array.isArray(cond))
  1394. throw new import_js_repository3.InvalidOperatorValueError(key, "an Array", cond);
  1395. if (cond.length === 0) return;
  1396. cond = cond.map((c) => this._buildQuery(modelName, c));
  1397. cond = cond.filter((c) => c != null);
  1398. const opKey = "$" + key;
  1399. query[opKey] = (_a = query[opKey]) != null ? _a : [];
  1400. query[opKey] = [...query[opKey], ...cond];
  1401. return;
  1402. }
  1403. if (key === idPropName) {
  1404. key = "_id";
  1405. } else {
  1406. key = this._convertPropNamesChainToColNamesChain(modelName, key);
  1407. }
  1408. if (typeof cond === "string") {
  1409. query[key] = this._coerceId(cond);
  1410. query[key] = this._coerceDate(query[key]);
  1411. return;
  1412. }
  1413. if (cond instanceof import_mongodb2.ObjectId) {
  1414. query[key] = cond;
  1415. return;
  1416. }
  1417. if (cond && cond.constructor && cond.constructor.name === "Object") {
  1418. const opConds = [];
  1419. if ("eq" in cond) {
  1420. let eq = this._coerceId(cond.eq);
  1421. eq = this._coerceDate(eq);
  1422. opConds.push({ $eq: eq });
  1423. }
  1424. if ("neq" in cond) {
  1425. let neq = this._coerceId(cond.neq);
  1426. neq = this._coerceDate(neq);
  1427. opConds.push({ $ne: neq });
  1428. }
  1429. if ("gt" in cond) {
  1430. const gt = this._coerceDate(cond.gt);
  1431. opConds.push({ $gt: gt });
  1432. }
  1433. if ("lt" in cond) {
  1434. const lt = this._coerceDate(cond.lt);
  1435. opConds.push({ $lt: lt });
  1436. }
  1437. if ("gte" in cond) {
  1438. const gte = this._coerceDate(cond.gte);
  1439. opConds.push({ $gte: gte });
  1440. }
  1441. if ("lte" in cond) {
  1442. const lte = this._coerceDate(cond.lte);
  1443. opConds.push({ $lte: lte });
  1444. }
  1445. if ("inq" in cond) {
  1446. if (!cond.inq || !Array.isArray(cond.inq))
  1447. throw new import_js_repository3.InvalidOperatorValueError(
  1448. "inq",
  1449. "an Array of possible values",
  1450. cond.inq
  1451. );
  1452. const inq = cond.inq.map((v) => {
  1453. v = this._coerceId(v);
  1454. v = this._coerceDate(v);
  1455. return v;
  1456. });
  1457. opConds.push({ $in: inq });
  1458. }
  1459. if ("nin" in cond) {
  1460. if (!cond.nin || !Array.isArray(cond.nin))
  1461. throw new import_js_repository3.InvalidOperatorValueError(
  1462. "nin",
  1463. "an Array of possible values",
  1464. cond
  1465. );
  1466. const nin = cond.nin.map((v) => {
  1467. v = this._coerceId(v);
  1468. v = this._coerceDate(v);
  1469. return v;
  1470. });
  1471. opConds.push({ $nin: nin });
  1472. }
  1473. if ("between" in cond) {
  1474. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  1475. throw new import_js_repository3.InvalidOperatorValueError(
  1476. "between",
  1477. "an Array of 2 elements",
  1478. cond.between
  1479. );
  1480. const gte = this._coerceDate(cond.between[0]);
  1481. const lte = this._coerceDate(cond.between[1]);
  1482. opConds.push({ $gte: gte, $lte: lte });
  1483. }
  1484. if ("exists" in cond) {
  1485. if (typeof cond.exists !== "boolean")
  1486. throw new import_js_repository3.InvalidOperatorValueError(
  1487. "exists",
  1488. "a Boolean",
  1489. cond.exists
  1490. );
  1491. opConds.push({ $exists: cond.exists });
  1492. }
  1493. if ("like" in cond) {
  1494. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  1495. throw new import_js_repository3.InvalidOperatorValueError(
  1496. "like",
  1497. "a String or RegExp",
  1498. cond.like
  1499. );
  1500. opConds.push({ $regex: (0, import_js_repository3.likeToRegexp)(cond.like) });
  1501. }
  1502. if ("nlike" in cond) {
  1503. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  1504. throw new import_js_repository3.InvalidOperatorValueError(
  1505. "nlike",
  1506. "a String or RegExp",
  1507. cond.nlike
  1508. );
  1509. opConds.push({ $not: (0, import_js_repository3.likeToRegexp)(cond.nlike) });
  1510. }
  1511. if ("ilike" in cond) {
  1512. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  1513. throw new import_js_repository3.InvalidOperatorValueError(
  1514. "ilike",
  1515. "a String or RegExp",
  1516. cond.ilike
  1517. );
  1518. opConds.push({ $regex: (0, import_js_repository3.likeToRegexp)(cond.ilike, true) });
  1519. }
  1520. if ("nilike" in cond) {
  1521. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  1522. throw new import_js_repository3.InvalidOperatorValueError(
  1523. "nilike",
  1524. "a String or RegExp",
  1525. cond.nilike
  1526. );
  1527. }
  1528. opConds.push({ $not: (0, import_js_repository3.likeToRegexp)(cond.nilike, true) });
  1529. }
  1530. if ("regexp" in cond) {
  1531. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  1532. throw new import_js_repository3.InvalidOperatorValueError(
  1533. "regexp",
  1534. "a String or RegExp",
  1535. cond.regexp
  1536. );
  1537. }
  1538. const flags = cond.flags || void 0;
  1539. if (flags && typeof flags !== "string")
  1540. throw new import_js_repository3.InvalidArgumentError(
  1541. "RegExp flags must be a String, but %v given.",
  1542. cond.flags
  1543. );
  1544. opConds.push({ $regex: (0, import_js_repository3.stringToRegexp)(cond.regexp, flags) });
  1545. }
  1546. if (opConds.length === 1) {
  1547. query[key] = opConds[0];
  1548. } else if (opConds.length > 1) {
  1549. query["$and"] = (_b = query["$and"]) != null ? _b : [];
  1550. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  1551. }
  1552. return;
  1553. }
  1554. query[key] = cond;
  1555. });
  1556. return Object.keys(query).length ? query : void 0;
  1557. }
  1558. /**
  1559. * Create.
  1560. *
  1561. * @param {string} modelName
  1562. * @param {object} modelData
  1563. * @param {object|undefined} filter
  1564. * @returns {Promise<object>}
  1565. */
  1566. async create(modelName, modelData, filter = void 0) {
  1567. const idPropName = this._getIdPropName(modelName);
  1568. const idValue = modelData[idPropName];
  1569. if (idValue == null || idValue === "" || idValue === 0) {
  1570. const pkType = this._getIdType(modelName);
  1571. if (pkType !== import_js_repository3.DataType.STRING && pkType !== import_js_repository3.DataType.ANY)
  1572. throw new import_js_repository3.InvalidArgumentError(
  1573. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1574. (0, import_js_repository3.capitalize)(pkType),
  1575. idPropName
  1576. );
  1577. delete modelData[idPropName];
  1578. }
  1579. const tableData = this._toDatabase(modelName, modelData);
  1580. const table = this._getCollection(modelName);
  1581. const { insertedId } = await table.insertOne(tableData);
  1582. const projection = this._buildProjection(
  1583. modelName,
  1584. filter && filter.fields
  1585. );
  1586. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  1587. return this._fromDatabase(modelName, insertedData);
  1588. }
  1589. /**
  1590. * Replace by id.
  1591. *
  1592. * @param {string} modelName
  1593. * @param {string|number} id
  1594. * @param {object} modelData
  1595. * @param {object|undefined} filter
  1596. * @returns {Promise<object>}
  1597. */
  1598. async replaceById(modelName, id, modelData, filter = void 0) {
  1599. id = this._coerceId(id);
  1600. const idPropName = this._getIdPropName(modelName);
  1601. modelData[idPropName] = id;
  1602. const tableData = this._toDatabase(modelName, modelData);
  1603. const table = this._getCollection(modelName);
  1604. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  1605. if (matchedCount < 1)
  1606. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1607. const projection = this._buildProjection(
  1608. modelName,
  1609. filter && filter.fields
  1610. );
  1611. const replacedData = await table.findOne({ _id: id }, { projection });
  1612. return this._fromDatabase(modelName, replacedData);
  1613. }
  1614. /**
  1615. * Replace or create.
  1616. *
  1617. * @param {string} modelName
  1618. * @param {object} modelData
  1619. * @param {object|undefined} filter
  1620. * @returns {Promise<object>}
  1621. */
  1622. async replaceOrCreate(modelName, modelData, filter = void 0) {
  1623. const idPropName = this._getIdPropName(modelName);
  1624. let idValue = modelData[idPropName];
  1625. idValue = this._coerceId(idValue);
  1626. if (idValue == null || idValue === "" || idValue === 0) {
  1627. const pkType = this._getIdType(modelName);
  1628. if (pkType !== import_js_repository3.DataType.STRING && pkType !== import_js_repository3.DataType.ANY)
  1629. throw new import_js_repository3.InvalidArgumentError(
  1630. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1631. (0, import_js_repository3.capitalize)(pkType),
  1632. idPropName
  1633. );
  1634. delete modelData[idPropName];
  1635. idValue = void 0;
  1636. }
  1637. const tableData = this._toDatabase(modelName, modelData);
  1638. const table = this._getCollection(modelName);
  1639. if (idValue == null) {
  1640. const { insertedId } = await table.insertOne(tableData);
  1641. idValue = insertedId;
  1642. } else {
  1643. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  1644. upsert: true
  1645. });
  1646. if (upsertedId) idValue = upsertedId;
  1647. }
  1648. const projection = this._buildProjection(
  1649. modelName,
  1650. filter && filter.fields
  1651. );
  1652. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  1653. return this._fromDatabase(modelName, upsertedData);
  1654. }
  1655. /**
  1656. * Patch.
  1657. *
  1658. * @param {string} modelName
  1659. * @param {object} modelData
  1660. * @param {object|undefined} where
  1661. * @returns {Promise<number>}
  1662. */
  1663. async patch(modelName, modelData, where = void 0) {
  1664. const idPropName = this._getIdPropName(modelName);
  1665. delete modelData[idPropName];
  1666. const query = this._buildQuery(modelName, where) || {};
  1667. const tableData = this._toDatabase(modelName, modelData);
  1668. const table = this._getCollection(modelName);
  1669. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  1670. return matchedCount;
  1671. }
  1672. /**
  1673. * Patch by id.
  1674. *
  1675. * @param {string} modelName
  1676. * @param {string|number} id
  1677. * @param {object} modelData
  1678. * @param {object|undefined} filter
  1679. * @returns {Promise<object>}
  1680. */
  1681. async patchById(modelName, id, modelData, filter = void 0) {
  1682. id = this._coerceId(id);
  1683. const idPropName = this._getIdPropName(modelName);
  1684. delete modelData[idPropName];
  1685. const tableData = this._toDatabase(modelName, modelData);
  1686. const table = this._getCollection(modelName);
  1687. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  1688. if (matchedCount < 1)
  1689. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1690. const projection = this._buildProjection(
  1691. modelName,
  1692. filter && filter.fields
  1693. );
  1694. const patchedData = await table.findOne({ _id: id }, { projection });
  1695. return this._fromDatabase(modelName, patchedData);
  1696. }
  1697. /**
  1698. * Find.
  1699. *
  1700. * @param {string} modelName
  1701. * @param {object|undefined} filter
  1702. * @returns {Promise<object[]>}
  1703. */
  1704. async find(modelName, filter = void 0) {
  1705. filter = filter || {};
  1706. const query = this._buildQuery(modelName, filter.where);
  1707. const sort = this._buildSort(modelName, filter.order);
  1708. const limit = filter.limit || void 0;
  1709. const skip = filter.skip || void 0;
  1710. const projection = this._buildProjection(modelName, filter.fields);
  1711. const collection = this._getCollection(modelName);
  1712. const options = { sort, limit, skip, projection };
  1713. const tableItems = await collection.find(query, options).toArray();
  1714. return tableItems.map((v) => this._fromDatabase(modelName, v));
  1715. }
  1716. /**
  1717. * Find by id.
  1718. *
  1719. * @param {string} modelName
  1720. * @param {string|number} id
  1721. * @param {object|undefined} filter
  1722. * @returns {Promise<object>}
  1723. */
  1724. async findById(modelName, id, filter = void 0) {
  1725. id = this._coerceId(id);
  1726. const table = this._getCollection(modelName);
  1727. const projection = this._buildProjection(
  1728. modelName,
  1729. filter && filter.fields
  1730. );
  1731. const patchedData = await table.findOne({ _id: id }, { projection });
  1732. if (!patchedData)
  1733. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1734. return this._fromDatabase(modelName, patchedData);
  1735. }
  1736. /**
  1737. * Delete.
  1738. *
  1739. * @param {string} modelName
  1740. * @param {object|undefined} where
  1741. * @returns {Promise<number>}
  1742. */
  1743. async delete(modelName, where = void 0) {
  1744. const table = this._getCollection(modelName);
  1745. const query = this._buildQuery(modelName, where);
  1746. const { deletedCount } = await table.deleteMany(query);
  1747. return deletedCount;
  1748. }
  1749. /**
  1750. * Delete by id.
  1751. *
  1752. * @param {string} modelName
  1753. * @param {string|number} id
  1754. * @returns {Promise<boolean>}
  1755. */
  1756. async deleteById(modelName, id) {
  1757. id = this._coerceId(id);
  1758. const table = this._getCollection(modelName);
  1759. const { deletedCount } = await table.deleteOne({ _id: id });
  1760. return deletedCount > 0;
  1761. }
  1762. /**
  1763. * Exists.
  1764. *
  1765. * @param {string} modelName
  1766. * @param {string|number} id
  1767. * @returns {Promise<boolean>}
  1768. */
  1769. async exists(modelName, id) {
  1770. id = this._coerceId(id);
  1771. const table = this._getCollection(modelName);
  1772. const result = await table.findOne({ _id: id }, {});
  1773. return result != null;
  1774. }
  1775. /**
  1776. * Count.
  1777. *
  1778. * @param {string} modelName
  1779. * @param {object|undefined} where
  1780. * @returns {Promise<number>}
  1781. */
  1782. async count(modelName, where = void 0) {
  1783. const query = this._buildQuery(modelName, where);
  1784. const table = this._getCollection(modelName);
  1785. return await table.countDocuments(query);
  1786. }
  1787. };
  1788. __name(_MongodbAdapter, "MongodbAdapter");
  1789. var MongodbAdapter = _MongodbAdapter;
  1790. // Annotate the CommonJS export names for ESM import in node:
  1791. 0 && (module.exports = {
  1792. MongodbAdapter
  1793. });