index.cjs 56 KB

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