index.cjs 55 KB

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