index.cjs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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/utils/model-name-to-collection-name.js
  973. function modelNameToCollectionName(modelName) {
  974. const ccName = toCamelCase2(modelName);
  975. const woModel = ccName.replace(/Model$/i, "");
  976. if (woModel.length <= 2) {
  977. return pluralize(ccName);
  978. }
  979. return pluralize(woModel);
  980. }
  981. __name(modelNameToCollectionName, "modelNameToCollectionName");
  982. // src/mongodb-adapter.js
  983. var MONGODB_OPTION_NAMES = [
  984. "ALPNProtocols",
  985. "allowPartialTrustChain",
  986. "appName",
  987. "auth",
  988. "authMechanism",
  989. "authMechanismProperties",
  990. "authSource",
  991. "autoEncryption",
  992. "autoSelectFamily",
  993. "autoSelectFamilyAttemptTimeout",
  994. "bsonRegExp",
  995. "ca",
  996. "cert",
  997. "checkKeys",
  998. "checkServerIdentity",
  999. "ciphers",
  1000. "compressors",
  1001. "connectTimeoutMS",
  1002. "crl",
  1003. "directConnection",
  1004. "driverInfo",
  1005. "ecdhCurve",
  1006. "enableUtf8Validation",
  1007. "family",
  1008. "fieldsAsRaw",
  1009. "forceServerObjectId",
  1010. "heartbeatFrequencyMS",
  1011. "hints",
  1012. "ignoreUndefined",
  1013. "journal",
  1014. "keepAliveInitialDelay",
  1015. "key",
  1016. "loadBalanced",
  1017. "localAddress",
  1018. "localPort",
  1019. "localThresholdMS",
  1020. "lookup",
  1021. "maxConnecting",
  1022. "maxIdleTimeMS",
  1023. "maxPoolSize",
  1024. "maxStalenessSeconds",
  1025. "minDHSize",
  1026. "minHeartbeatFrequencyMS",
  1027. "minPoolSize",
  1028. "mongodbLogComponentSeverities",
  1029. "mongodbLogMaxDocumentLength",
  1030. "mongodbLogPath",
  1031. "monitorCommands",
  1032. "noDelay",
  1033. "passphrase",
  1034. "pfx",
  1035. "pkFactory",
  1036. "promoteBuffers",
  1037. "promoteLongs",
  1038. "promoteValues",
  1039. "proxyHost",
  1040. "proxyPassword",
  1041. "proxyPort",
  1042. "proxyUsername",
  1043. "raw",
  1044. "readConcern",
  1045. "readConcernLevel",
  1046. "readPreference",
  1047. "readPreferenceTags",
  1048. "rejectUnauthorized",
  1049. "replicaSet",
  1050. "retryReads",
  1051. "retryWrites",
  1052. "secureContext",
  1053. "secureProtocol",
  1054. "serializeFunctions",
  1055. "serverApi",
  1056. "serverMonitoringMode",
  1057. "serverSelectionTimeoutMS",
  1058. "servername",
  1059. "session",
  1060. "socketTimeoutMS",
  1061. "srvMaxHosts",
  1062. "srvServiceName",
  1063. "ssl",
  1064. "timeoutMS",
  1065. "tls",
  1066. "tlsAllowInvalidCertificates",
  1067. "tlsAllowInvalidHostnames",
  1068. "tlsCAFile",
  1069. "tlsCRLFile",
  1070. "tlsCertificateKeyFile",
  1071. "tlsCertificateKeyFilePassword",
  1072. "tlsInsecure",
  1073. "useBigInt64",
  1074. "w",
  1075. "waitQueueTimeoutMS",
  1076. "writeConcern",
  1077. "wtimeoutMS",
  1078. "zlibCompressionLevel"
  1079. ];
  1080. var DEFAULT_SETTINGS = {
  1081. // connectTimeoutMS: 2500,
  1082. // serverSelectionTimeoutMS: 2500,
  1083. };
  1084. var _MongodbAdapter = class _MongodbAdapter extends import_js_repository3.Adapter {
  1085. /**
  1086. * Mongodb instance.
  1087. *
  1088. * @type {MongoClient}
  1089. * @private
  1090. */
  1091. _client;
  1092. /**
  1093. * Client.
  1094. *
  1095. * @returns {MongoClient}
  1096. */
  1097. get client() {
  1098. return this._client;
  1099. }
  1100. /**
  1101. * Collections.
  1102. *
  1103. * @type {Map<any, any>}
  1104. * @private
  1105. */
  1106. _collections = /* @__PURE__ */ new Map();
  1107. /**
  1108. * Constructor.
  1109. *
  1110. * @param {ServiceContainer} container
  1111. * @param settings
  1112. */
  1113. constructor(container, settings) {
  1114. settings = Object.assign({}, DEFAULT_SETTINGS, settings || {});
  1115. settings.protocol = settings.protocol || "mongodb";
  1116. settings.hostname = settings.hostname || settings.host || "127.0.0.1";
  1117. settings.port = settings.port || 27017;
  1118. settings.database = settings.database || settings.db || "database";
  1119. super(container, settings);
  1120. const options = (0, import_js_repository3.selectObjectKeys)(this.settings, MONGODB_OPTION_NAMES);
  1121. const url = createMongodbUrl(this.settings);
  1122. this._client = new import_mongodb3.MongoClient(url, options);
  1123. }
  1124. /**
  1125. * Get id prop name.
  1126. *
  1127. * @param modelName
  1128. * @private
  1129. */
  1130. _getIdPropName(modelName) {
  1131. return this.getService(import_js_repository3.ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  1132. modelName
  1133. );
  1134. }
  1135. /**
  1136. * Get id col name.
  1137. *
  1138. * @param modelName
  1139. * @private
  1140. */
  1141. _getIdColName(modelName) {
  1142. return this.getService(import_js_repository3.ModelDefinitionUtils).getPrimaryKeyAsColumnName(
  1143. modelName
  1144. );
  1145. }
  1146. /**
  1147. * Coerce id.
  1148. *
  1149. * @param value
  1150. * @returns {ObjectId|*}
  1151. * @private
  1152. */
  1153. _coerceId(value) {
  1154. if (value == null) return value;
  1155. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1156. return value;
  1157. }
  1158. /**
  1159. * Coerce date.
  1160. *
  1161. * @param value
  1162. * @returns {Date|*}
  1163. * @private
  1164. */
  1165. _coerceDate(value) {
  1166. if (value == null) return value;
  1167. if (value instanceof Date) return value;
  1168. if (isIsoDate(value)) return new Date(value);
  1169. return value;
  1170. }
  1171. /**
  1172. * To database.
  1173. *
  1174. * @param {string} modelName
  1175. * @param {object} modelData
  1176. * @returns {object}
  1177. * @private
  1178. */
  1179. _toDatabase(modelName, modelData) {
  1180. const tableData = this.getService(
  1181. import_js_repository3.ModelDefinitionUtils
  1182. ).convertPropertyNamesToColumnNames(modelName, modelData);
  1183. const idColName = this._getIdColName(modelName);
  1184. if (idColName !== "id" && idColName !== "_id")
  1185. throw new import_js_repository3.InvalidArgumentError(
  1186. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1187. idColName
  1188. );
  1189. if (idColName in tableData && idColName !== "_id") {
  1190. tableData._id = tableData[idColName];
  1191. delete tableData[idColName];
  1192. }
  1193. return transformValuesDeep(tableData, (value) => {
  1194. if (value instanceof import_mongodb2.ObjectId) return value;
  1195. if (value instanceof Date) return value;
  1196. if (isObjectId(value)) return new import_mongodb2.ObjectId(value);
  1197. if (isIsoDate(value)) return new Date(value);
  1198. return value;
  1199. });
  1200. }
  1201. /**
  1202. * From database.
  1203. *
  1204. * @param {string} modelName
  1205. * @param {object} tableData
  1206. * @returns {object}
  1207. * @private
  1208. */
  1209. _fromDatabase(modelName, tableData) {
  1210. if ("_id" in tableData) {
  1211. const idColName = this._getIdColName(modelName);
  1212. if (idColName !== "id" && idColName !== "_id")
  1213. throw new import_js_repository3.InvalidArgumentError(
  1214. 'MongoDB is not supporting custom names of the primary key. Do use "id" as a primary key instead of %v.',
  1215. idColName
  1216. );
  1217. if (idColName !== "_id") {
  1218. tableData[idColName] = tableData._id;
  1219. delete tableData._id;
  1220. }
  1221. }
  1222. const modelData = this.getService(
  1223. import_js_repository3.ModelDefinitionUtils
  1224. ).convertColumnNamesToPropertyNames(modelName, tableData);
  1225. return transformValuesDeep(modelData, (value) => {
  1226. if (value instanceof import_mongodb2.ObjectId) return String(value);
  1227. if (value instanceof Date) return value.toISOString();
  1228. return value;
  1229. });
  1230. }
  1231. /**
  1232. * Get collection name by model name.
  1233. *
  1234. * @param {string} modelName
  1235. */
  1236. _getCollectionNameByModelName(modelName) {
  1237. const modelDef = this.getService(import_js_repository3.DefinitionRegistry).getModel(modelName);
  1238. if (modelDef.tableName != null) return modelDef.tableName;
  1239. return modelNameToCollectionName(modelDef.name);
  1240. }
  1241. /**
  1242. * Get collection.
  1243. *
  1244. * @param {string} modelName
  1245. * @returns {*}
  1246. * @private
  1247. */
  1248. _getCollection(modelName) {
  1249. let collection = this._collections.get(modelName);
  1250. if (collection) return collection;
  1251. const collectionName = this._getCollectionNameByModelName(modelName);
  1252. collection = this.client.db(this.settings.database).collection(collectionName);
  1253. this._collections.set(modelName, collection);
  1254. return collection;
  1255. }
  1256. /**
  1257. * Get id type.
  1258. *
  1259. * @param modelName
  1260. * @returns {string|*}
  1261. * @private
  1262. */
  1263. _getIdType(modelName) {
  1264. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1265. const pkPropName = utils.getPrimaryKeyAsPropertyName(modelName);
  1266. return utils.getDataTypeByPropertyName(modelName, pkPropName);
  1267. }
  1268. /**
  1269. * Get col name.
  1270. *
  1271. * @param {string} modelName
  1272. * @param {string} propName
  1273. * @returns {string}
  1274. * @private
  1275. */
  1276. _getColName(modelName, propName) {
  1277. if (!propName || typeof propName !== "string")
  1278. throw new import_js_repository3.InvalidArgumentError(
  1279. "Property name must be a non-empty String, but %v given.",
  1280. propName
  1281. );
  1282. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1283. let colName = propName;
  1284. try {
  1285. colName = utils.getColumnNameByPropertyName(modelName, propName);
  1286. } catch (error) {
  1287. if (!(error instanceof import_js_repository3.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1288. throw error;
  1289. }
  1290. }
  1291. return colName;
  1292. }
  1293. /**
  1294. * Convert prop names chain to col names chain.
  1295. *
  1296. * @param {string} modelName
  1297. * @param {string} propsChain
  1298. * @returns {string}
  1299. * @private
  1300. */
  1301. _convertPropNamesChainToColNamesChain(modelName, propsChain) {
  1302. if (!modelName || typeof modelName !== "string")
  1303. throw new import_js_repository3.InvalidArgumentError(
  1304. "Model name must be a non-empty String, but %v given.",
  1305. modelName
  1306. );
  1307. if (!propsChain || typeof propsChain !== "string")
  1308. throw new import_js_repository3.InvalidArgumentError(
  1309. "Properties chain must be a non-empty String, but %v given.",
  1310. propsChain
  1311. );
  1312. propsChain = propsChain.replace(/\.{2,}/g, ".");
  1313. const propNames = propsChain.split(".");
  1314. const utils = this.getService(import_js_repository3.ModelDefinitionUtils);
  1315. let currModelName = modelName;
  1316. return propNames.map((currPropName) => {
  1317. if (!currModelName) return currPropName;
  1318. const colName = this._getColName(currModelName, currPropName);
  1319. currModelName = utils.getModelNameOfPropertyValueIfDefined(
  1320. currModelName,
  1321. currPropName
  1322. );
  1323. return colName;
  1324. }).join(".");
  1325. }
  1326. /**
  1327. * Build projection.
  1328. *
  1329. * @param {string} modelName
  1330. * @param {string|string[]} fields
  1331. * @returns {Record<string, number>|undefined}
  1332. * @private
  1333. */
  1334. _buildProjection(modelName, fields) {
  1335. if (fields == null) return;
  1336. if (Array.isArray(fields) === false) fields = [fields];
  1337. if (!fields.length) return;
  1338. if (fields.indexOf("_id") === -1) fields.push("_id");
  1339. return fields.reduce((acc, field) => {
  1340. if (!field || typeof field !== "string")
  1341. throw new import_js_repository3.InvalidArgumentError(
  1342. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v given.',
  1343. field
  1344. );
  1345. let colName = this._convertPropNamesChainToColNamesChain(
  1346. modelName,
  1347. field
  1348. );
  1349. acc[colName] = 1;
  1350. return acc;
  1351. }, {});
  1352. }
  1353. /**
  1354. * Build sort.
  1355. *
  1356. * @param {string} modelName
  1357. * @param {string|string[]} clause
  1358. * @returns {object|undefined}
  1359. * @private
  1360. */
  1361. _buildSort(modelName, clause) {
  1362. if (clause == null) return;
  1363. if (Array.isArray(clause) === false) clause = [clause];
  1364. if (!clause.length) return;
  1365. const idPropName = this._getIdPropName(modelName);
  1366. return clause.reduce((acc, order) => {
  1367. if (!order || typeof order !== "string")
  1368. throw new import_js_repository3.InvalidArgumentError(
  1369. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v given.',
  1370. order
  1371. );
  1372. const direction = order.match(/\s+(A|DE)SC$/);
  1373. let field = order.replace(/\s+(A|DE)SC$/, "").trim();
  1374. if (field === idPropName) {
  1375. field = "_id";
  1376. } else {
  1377. try {
  1378. field = this._convertPropNamesChainToColNamesChain(modelName, field);
  1379. } catch (error) {
  1380. if (!(error instanceof import_js_repository3.InvalidArgumentError) || error.message.indexOf("does not have the property") === -1) {
  1381. throw error;
  1382. }
  1383. }
  1384. }
  1385. acc[field] = direction && direction[1] === "DE" ? -1 : 1;
  1386. return acc;
  1387. }, {});
  1388. }
  1389. /**
  1390. * Build query.
  1391. *
  1392. * @param {string} modelName
  1393. * @param {object} clause
  1394. * @returns {object}
  1395. * @private
  1396. */
  1397. _buildQuery(modelName, clause) {
  1398. if (clause == null) return;
  1399. if (typeof clause !== "object" || Array.isArray(clause))
  1400. throw new import_js_repository3.InvalidArgumentError(
  1401. 'The provided option "where" should be an Object, but %v given.',
  1402. clause
  1403. );
  1404. const query = {};
  1405. const idPropName = this._getIdPropName(modelName);
  1406. Object.keys(clause).forEach((key) => {
  1407. var _a, _b;
  1408. if (String(key).indexOf("$") !== -1)
  1409. throw new import_js_repository3.InvalidArgumentError(
  1410. 'The symbol "$" is not supported, but %v given.',
  1411. key
  1412. );
  1413. let cond = clause[key];
  1414. if (key === "and" || key === "or" || key === "nor") {
  1415. if (cond == null) return;
  1416. if (!Array.isArray(cond))
  1417. throw new import_js_repository3.InvalidOperatorValueError(key, "an Array", cond);
  1418. if (cond.length === 0) return;
  1419. cond = cond.map((c) => this._buildQuery(modelName, c));
  1420. cond = cond.filter((c) => c != null);
  1421. const opKey = "$" + key;
  1422. query[opKey] = (_a = query[opKey]) != null ? _a : [];
  1423. query[opKey] = [...query[opKey], ...cond];
  1424. return;
  1425. }
  1426. if (key === idPropName) {
  1427. key = "_id";
  1428. } else {
  1429. key = this._convertPropNamesChainToColNamesChain(modelName, key);
  1430. }
  1431. if (typeof cond === "string") {
  1432. query[key] = this._coerceId(cond);
  1433. query[key] = this._coerceDate(query[key]);
  1434. return;
  1435. }
  1436. if (cond instanceof import_mongodb2.ObjectId) {
  1437. query[key] = cond;
  1438. return;
  1439. }
  1440. if (cond && cond.constructor && cond.constructor.name === "Object") {
  1441. const opConds = [];
  1442. if ("eq" in cond) {
  1443. let eq = this._coerceId(cond.eq);
  1444. eq = this._coerceDate(eq);
  1445. opConds.push({ $eq: eq });
  1446. }
  1447. if ("neq" in cond) {
  1448. let neq = this._coerceId(cond.neq);
  1449. neq = this._coerceDate(neq);
  1450. opConds.push({ $ne: neq });
  1451. }
  1452. if ("gt" in cond) {
  1453. const gt = this._coerceDate(cond.gt);
  1454. opConds.push({ $gt: gt });
  1455. }
  1456. if ("lt" in cond) {
  1457. const lt = this._coerceDate(cond.lt);
  1458. opConds.push({ $lt: lt });
  1459. }
  1460. if ("gte" in cond) {
  1461. const gte = this._coerceDate(cond.gte);
  1462. opConds.push({ $gte: gte });
  1463. }
  1464. if ("lte" in cond) {
  1465. const lte = this._coerceDate(cond.lte);
  1466. opConds.push({ $lte: lte });
  1467. }
  1468. if ("inq" in cond) {
  1469. if (!cond.inq || !Array.isArray(cond.inq))
  1470. throw new import_js_repository3.InvalidOperatorValueError(
  1471. "inq",
  1472. "an Array of possible values",
  1473. cond.inq
  1474. );
  1475. const inq = cond.inq.map((v) => {
  1476. v = this._coerceId(v);
  1477. v = this._coerceDate(v);
  1478. return v;
  1479. });
  1480. opConds.push({ $in: inq });
  1481. }
  1482. if ("nin" in cond) {
  1483. if (!cond.nin || !Array.isArray(cond.nin))
  1484. throw new import_js_repository3.InvalidOperatorValueError(
  1485. "nin",
  1486. "an Array of possible values",
  1487. cond
  1488. );
  1489. const nin = cond.nin.map((v) => {
  1490. v = this._coerceId(v);
  1491. v = this._coerceDate(v);
  1492. return v;
  1493. });
  1494. opConds.push({ $nin: nin });
  1495. }
  1496. if ("between" in cond) {
  1497. if (!Array.isArray(cond.between) || cond.between.length !== 2)
  1498. throw new import_js_repository3.InvalidOperatorValueError(
  1499. "between",
  1500. "an Array of 2 elements",
  1501. cond.between
  1502. );
  1503. const gte = this._coerceDate(cond.between[0]);
  1504. const lte = this._coerceDate(cond.between[1]);
  1505. opConds.push({ $gte: gte, $lte: lte });
  1506. }
  1507. if ("exists" in cond) {
  1508. if (typeof cond.exists !== "boolean")
  1509. throw new import_js_repository3.InvalidOperatorValueError(
  1510. "exists",
  1511. "a Boolean",
  1512. cond.exists
  1513. );
  1514. opConds.push({ $exists: cond.exists });
  1515. }
  1516. if ("like" in cond) {
  1517. if (typeof cond.like !== "string" && !(cond.like instanceof RegExp))
  1518. throw new import_js_repository3.InvalidOperatorValueError(
  1519. "like",
  1520. "a String or RegExp",
  1521. cond.like
  1522. );
  1523. opConds.push({ $regex: (0, import_js_repository3.likeToRegexp)(cond.like) });
  1524. }
  1525. if ("nlike" in cond) {
  1526. if (typeof cond.nlike !== "string" && !(cond.nlike instanceof RegExp))
  1527. throw new import_js_repository3.InvalidOperatorValueError(
  1528. "nlike",
  1529. "a String or RegExp",
  1530. cond.nlike
  1531. );
  1532. opConds.push({ $not: (0, import_js_repository3.likeToRegexp)(cond.nlike) });
  1533. }
  1534. if ("ilike" in cond) {
  1535. if (typeof cond.ilike !== "string" && !(cond.ilike instanceof RegExp))
  1536. throw new import_js_repository3.InvalidOperatorValueError(
  1537. "ilike",
  1538. "a String or RegExp",
  1539. cond.ilike
  1540. );
  1541. opConds.push({ $regex: (0, import_js_repository3.likeToRegexp)(cond.ilike, true) });
  1542. }
  1543. if ("nilike" in cond) {
  1544. if (typeof cond.nilike !== "string" && !(cond.nilike instanceof RegExp)) {
  1545. throw new import_js_repository3.InvalidOperatorValueError(
  1546. "nilike",
  1547. "a String or RegExp",
  1548. cond.nilike
  1549. );
  1550. }
  1551. opConds.push({ $not: (0, import_js_repository3.likeToRegexp)(cond.nilike, true) });
  1552. }
  1553. if ("regexp" in cond) {
  1554. if (typeof cond.regexp !== "string" && !(cond.regexp instanceof RegExp)) {
  1555. throw new import_js_repository3.InvalidOperatorValueError(
  1556. "regexp",
  1557. "a String or RegExp",
  1558. cond.regexp
  1559. );
  1560. }
  1561. const flags = cond.flags || void 0;
  1562. if (flags && typeof flags !== "string")
  1563. throw new import_js_repository3.InvalidArgumentError(
  1564. "RegExp flags must be a String, but %v given.",
  1565. cond.flags
  1566. );
  1567. opConds.push({ $regex: (0, import_js_repository3.stringToRegexp)(cond.regexp, flags) });
  1568. }
  1569. if (opConds.length === 1) {
  1570. query[key] = opConds[0];
  1571. } else if (opConds.length > 1) {
  1572. query["$and"] = (_b = query["$and"]) != null ? _b : [];
  1573. opConds.forEach((c) => query["$and"].push({ [key]: c }));
  1574. }
  1575. return;
  1576. }
  1577. query[key] = cond;
  1578. });
  1579. return Object.keys(query).length ? query : void 0;
  1580. }
  1581. /**
  1582. * Create.
  1583. *
  1584. * @param {string} modelName
  1585. * @param {object} modelData
  1586. * @param {object|undefined} filter
  1587. * @returns {Promise<object>}
  1588. */
  1589. async create(modelName, modelData, filter = void 0) {
  1590. const idPropName = this._getIdPropName(modelName);
  1591. const idValue = modelData[idPropName];
  1592. if (idValue == null || idValue === "" || idValue === 0) {
  1593. const pkType = this._getIdType(modelName);
  1594. if (pkType !== import_js_repository3.DataType.STRING && pkType !== import_js_repository3.DataType.ANY)
  1595. throw new import_js_repository3.InvalidArgumentError(
  1596. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1597. (0, import_js_repository3.capitalize)(pkType),
  1598. idPropName
  1599. );
  1600. delete modelData[idPropName];
  1601. }
  1602. const tableData = this._toDatabase(modelName, modelData);
  1603. const table = this._getCollection(modelName);
  1604. const { insertedId } = await table.insertOne(tableData);
  1605. const projection = this._buildProjection(
  1606. modelName,
  1607. filter && filter.fields
  1608. );
  1609. const insertedData = await table.findOne({ _id: insertedId }, { projection });
  1610. return this._fromDatabase(modelName, insertedData);
  1611. }
  1612. /**
  1613. * Replace by id.
  1614. *
  1615. * @param {string} modelName
  1616. * @param {string|number} id
  1617. * @param {object} modelData
  1618. * @param {object|undefined} filter
  1619. * @returns {Promise<object>}
  1620. */
  1621. async replaceById(modelName, id, modelData, filter = void 0) {
  1622. id = this._coerceId(id);
  1623. const idPropName = this._getIdPropName(modelName);
  1624. modelData[idPropName] = id;
  1625. const tableData = this._toDatabase(modelName, modelData);
  1626. const table = this._getCollection(modelName);
  1627. const { matchedCount } = await table.replaceOne({ _id: id }, tableData);
  1628. if (matchedCount < 1)
  1629. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1630. const projection = this._buildProjection(
  1631. modelName,
  1632. filter && filter.fields
  1633. );
  1634. const replacedData = await table.findOne({ _id: id }, { projection });
  1635. return this._fromDatabase(modelName, replacedData);
  1636. }
  1637. /**
  1638. * Replace or create.
  1639. *
  1640. * @param {string} modelName
  1641. * @param {object} modelData
  1642. * @param {object|undefined} filter
  1643. * @returns {Promise<object>}
  1644. */
  1645. async replaceOrCreate(modelName, modelData, filter = void 0) {
  1646. const idPropName = this._getIdPropName(modelName);
  1647. let idValue = modelData[idPropName];
  1648. idValue = this._coerceId(idValue);
  1649. if (idValue == null || idValue === "" || idValue === 0) {
  1650. const pkType = this._getIdType(modelName);
  1651. if (pkType !== import_js_repository3.DataType.STRING && pkType !== import_js_repository3.DataType.ANY)
  1652. throw new import_js_repository3.InvalidArgumentError(
  1653. "MongoDB unable to generate primary keys of %s. Do provide your own value for the %v property or set property type to String.",
  1654. (0, import_js_repository3.capitalize)(pkType),
  1655. idPropName
  1656. );
  1657. delete modelData[idPropName];
  1658. idValue = void 0;
  1659. }
  1660. const tableData = this._toDatabase(modelName, modelData);
  1661. const table = this._getCollection(modelName);
  1662. if (idValue == null) {
  1663. const { insertedId } = await table.insertOne(tableData);
  1664. idValue = insertedId;
  1665. } else {
  1666. const { upsertedId } = await table.replaceOne({ _id: idValue }, tableData, {
  1667. upsert: true
  1668. });
  1669. if (upsertedId) idValue = upsertedId;
  1670. }
  1671. const projection = this._buildProjection(
  1672. modelName,
  1673. filter && filter.fields
  1674. );
  1675. const upsertedData = await table.findOne({ _id: idValue }, { projection });
  1676. return this._fromDatabase(modelName, upsertedData);
  1677. }
  1678. /**
  1679. * Patch.
  1680. *
  1681. * @param {string} modelName
  1682. * @param {object} modelData
  1683. * @param {object|undefined} where
  1684. * @returns {Promise<number>}
  1685. */
  1686. async patch(modelName, modelData, where = void 0) {
  1687. const idPropName = this._getIdPropName(modelName);
  1688. delete modelData[idPropName];
  1689. const query = this._buildQuery(modelName, where) || {};
  1690. const tableData = this._toDatabase(modelName, modelData);
  1691. const table = this._getCollection(modelName);
  1692. const { matchedCount } = await table.updateMany(query, { $set: tableData });
  1693. return matchedCount;
  1694. }
  1695. /**
  1696. * Patch by id.
  1697. *
  1698. * @param {string} modelName
  1699. * @param {string|number} id
  1700. * @param {object} modelData
  1701. * @param {object|undefined} filter
  1702. * @returns {Promise<object>}
  1703. */
  1704. async patchById(modelName, id, modelData, filter = void 0) {
  1705. id = this._coerceId(id);
  1706. const idPropName = this._getIdPropName(modelName);
  1707. delete modelData[idPropName];
  1708. const tableData = this._toDatabase(modelName, modelData);
  1709. const table = this._getCollection(modelName);
  1710. const { matchedCount } = await table.updateOne({ _id: id }, { $set: tableData });
  1711. if (matchedCount < 1)
  1712. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1713. const projection = this._buildProjection(
  1714. modelName,
  1715. filter && filter.fields
  1716. );
  1717. const patchedData = await table.findOne({ _id: id }, { projection });
  1718. return this._fromDatabase(modelName, patchedData);
  1719. }
  1720. /**
  1721. * Find.
  1722. *
  1723. * @param {string} modelName
  1724. * @param {object|undefined} filter
  1725. * @returns {Promise<object[]>}
  1726. */
  1727. async find(modelName, filter = void 0) {
  1728. filter = filter || {};
  1729. const query = this._buildQuery(modelName, filter.where);
  1730. const sort = this._buildSort(modelName, filter.order);
  1731. const limit = filter.limit || void 0;
  1732. const skip = filter.skip || void 0;
  1733. const projection = this._buildProjection(modelName, filter.fields);
  1734. const collection = this._getCollection(modelName);
  1735. const options = { sort, limit, skip, projection };
  1736. const tableItems = await collection.find(query, options).toArray();
  1737. return tableItems.map((v) => this._fromDatabase(modelName, v));
  1738. }
  1739. /**
  1740. * Find by id.
  1741. *
  1742. * @param {string} modelName
  1743. * @param {string|number} id
  1744. * @param {object|undefined} filter
  1745. * @returns {Promise<object>}
  1746. */
  1747. async findById(modelName, id, filter = void 0) {
  1748. id = this._coerceId(id);
  1749. const table = this._getCollection(modelName);
  1750. const projection = this._buildProjection(
  1751. modelName,
  1752. filter && filter.fields
  1753. );
  1754. const patchedData = await table.findOne({ _id: id }, { projection });
  1755. if (!patchedData)
  1756. throw new import_js_repository3.InvalidArgumentError("Identifier %v is not found.", String(id));
  1757. return this._fromDatabase(modelName, patchedData);
  1758. }
  1759. /**
  1760. * Delete.
  1761. *
  1762. * @param {string} modelName
  1763. * @param {object|undefined} where
  1764. * @returns {Promise<number>}
  1765. */
  1766. async delete(modelName, where = void 0) {
  1767. const table = this._getCollection(modelName);
  1768. const query = this._buildQuery(modelName, where);
  1769. const { deletedCount } = await table.deleteMany(query);
  1770. return deletedCount;
  1771. }
  1772. /**
  1773. * Delete by id.
  1774. *
  1775. * @param {string} modelName
  1776. * @param {string|number} id
  1777. * @returns {Promise<boolean>}
  1778. */
  1779. async deleteById(modelName, id) {
  1780. id = this._coerceId(id);
  1781. const table = this._getCollection(modelName);
  1782. const { deletedCount } = await table.deleteOne({ _id: id });
  1783. return deletedCount > 0;
  1784. }
  1785. /**
  1786. * Exists.
  1787. *
  1788. * @param {string} modelName
  1789. * @param {string|number} id
  1790. * @returns {Promise<boolean>}
  1791. */
  1792. async exists(modelName, id) {
  1793. id = this._coerceId(id);
  1794. const table = this._getCollection(modelName);
  1795. const result = await table.findOne({ _id: id }, {});
  1796. return result != null;
  1797. }
  1798. /**
  1799. * Count.
  1800. *
  1801. * @param {string} modelName
  1802. * @param {object|undefined} where
  1803. * @returns {Promise<number>}
  1804. */
  1805. async count(modelName, where = void 0) {
  1806. const query = this._buildQuery(modelName, where);
  1807. const table = this._getCollection(modelName);
  1808. return await table.countDocuments(query);
  1809. }
  1810. };
  1811. __name(_MongodbAdapter, "MongodbAdapter");
  1812. var MongodbAdapter = _MongodbAdapter;
  1813. // Annotate the CommonJS export names for ESM import in node:
  1814. 0 && (module.exports = {
  1815. MongodbAdapter
  1816. });