index.cjs 56 KB

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