index.cjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. DebuggableService: () => DebuggableService,
  25. SERVICE_CLASS_NAME: () => SERVICE_CLASS_NAME,
  26. SERVICE_CONTAINER_CLASS_NAME: () => SERVICE_CONTAINER_CLASS_NAME,
  27. Service: () => Service,
  28. ServiceContainer: () => ServiceContainer,
  29. isServiceContainer: () => isServiceContainer
  30. });
  31. module.exports = __toCommonJS(index_exports);
  32. // src/errors/invalid-argument-error.js
  33. var import_js_format = require("@e22m4u/js-format");
  34. var _InvalidArgumentError = class _InvalidArgumentError extends import_js_format.Errorf {
  35. };
  36. __name(_InvalidArgumentError, "InvalidArgumentError");
  37. var InvalidArgumentError = _InvalidArgumentError;
  38. // src/service-container.js
  39. var SERVICE_CONTAINER_CLASS_NAME = "ServiceContainer";
  40. var _ServiceContainer = class _ServiceContainer {
  41. /**
  42. * Services map.
  43. *
  44. * @type {Map<any, any>}
  45. * @private
  46. */
  47. _services = /* @__PURE__ */ new Map();
  48. /**
  49. * Parent container.
  50. *
  51. * @type {ServiceContainer}
  52. * @private
  53. */
  54. _parent;
  55. /**
  56. * Constructor.
  57. *
  58. * @param {ServiceContainer|undefined} parent
  59. */
  60. constructor(parent = void 0) {
  61. if (parent != null) {
  62. if (!(parent instanceof _ServiceContainer))
  63. throw new InvalidArgumentError(
  64. 'The provided parameter "parent" of ServicesContainer.constructor must be an instance ServiceContainer, but %v given.',
  65. parent
  66. );
  67. this._parent = parent;
  68. }
  69. }
  70. /**
  71. * Получить родительский сервис-контейнер или выбросить ошибку.
  72. *
  73. * @returns {ServiceContainer}
  74. */
  75. getParent() {
  76. if (!this._parent)
  77. throw new InvalidArgumentError("The service container has no parent.");
  78. return this._parent;
  79. }
  80. /**
  81. * Проверить наличие родительского сервис-контейнера.
  82. *
  83. * @returns {boolean}
  84. */
  85. hasParent() {
  86. return Boolean(this._parent);
  87. }
  88. /**
  89. * Получить существующий или новый экземпляр.
  90. *
  91. * @param {*} ctor
  92. * @param {*} args
  93. * @returns {*}
  94. */
  95. get(ctor, ...args) {
  96. if (!ctor || typeof ctor !== "function")
  97. throw new InvalidArgumentError(
  98. "The first argument of ServicesContainer.get must be a class constructor, but %v given.",
  99. ctor
  100. );
  101. const isCtorRegistered = this._services.has(ctor);
  102. let service = this._services.get(ctor);
  103. let inheritedCtor = void 0;
  104. if (!service) {
  105. const ctors = Array.from(this._services.keys());
  106. inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  107. if (inheritedCtor) service = this._services.get(inheritedCtor);
  108. }
  109. if (!service && !isCtorRegistered && !inheritedCtor && this._parent && this._parent.has(ctor)) {
  110. return this._parent.get(ctor, ...args);
  111. }
  112. if (!isCtorRegistered && inheritedCtor) {
  113. ctor = inheritedCtor;
  114. }
  115. if (!service || args.length) {
  116. service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  117. this._services.set(ctor, service);
  118. } else if (typeof service === "function") {
  119. service = service();
  120. this._services.set(ctor, service);
  121. }
  122. return service;
  123. }
  124. /**
  125. * Получить существующий или новый экземпляр,
  126. * только если конструктор зарегистрирован.
  127. *
  128. * @param {*} ctor
  129. * @param {*} args
  130. * @returns {*}
  131. */
  132. getRegistered(ctor, ...args) {
  133. if (!this.has(ctor))
  134. throw new InvalidArgumentError(
  135. "The constructor %v is not registered.",
  136. ctor
  137. );
  138. return this.get(ctor, ...args);
  139. }
  140. /**
  141. * Проверить существование конструктора в контейнере.
  142. *
  143. * @param {*} ctor
  144. * @returns {boolean}
  145. */
  146. has(ctor) {
  147. if (this._services.has(ctor)) return true;
  148. const ctors = Array.from(this._services.keys());
  149. const inheritedCtor = ctors.find((v) => v.prototype instanceof ctor);
  150. if (inheritedCtor) return true;
  151. if (this._parent) return this._parent.has(ctor);
  152. return false;
  153. }
  154. /**
  155. * Добавить конструктор в контейнер.
  156. *
  157. * @param {*} ctor
  158. * @param {*} args
  159. * @returns {this}
  160. */
  161. add(ctor, ...args) {
  162. if (!ctor || typeof ctor !== "function")
  163. throw new InvalidArgumentError(
  164. "The first argument of ServicesContainer.add must be a class constructor, but %v given.",
  165. ctor
  166. );
  167. const factory = /* @__PURE__ */ __name(() => Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args), "factory");
  168. this._services.set(ctor, factory);
  169. return this;
  170. }
  171. /**
  172. * Добавить конструктор и создать экземпляр.
  173. *
  174. * @param {*} ctor
  175. * @param {*} args
  176. * @returns {this}
  177. */
  178. use(ctor, ...args) {
  179. if (!ctor || typeof ctor !== "function")
  180. throw new InvalidArgumentError(
  181. "The first argument of ServicesContainer.use must be a class constructor, but %v given.",
  182. ctor
  183. );
  184. const service = Array.isArray(ctor.kinds) && ctor.kinds.includes(SERVICE_CLASS_NAME) ? new ctor(this, ...args) : new ctor(...args);
  185. this._services.set(ctor, service);
  186. return this;
  187. }
  188. /**
  189. * Добавить конструктор и связанный экземпляр.
  190. *
  191. * @param {*} ctor
  192. * @param {*} service
  193. * @returns {this}
  194. */
  195. set(ctor, service) {
  196. if (!ctor || typeof ctor !== "function")
  197. throw new InvalidArgumentError(
  198. "The first argument of ServicesContainer.set must be a class constructor, but %v given.",
  199. ctor
  200. );
  201. if (!service || typeof service !== "object" || Array.isArray(service))
  202. throw new InvalidArgumentError(
  203. "The second argument of ServicesContainer.set must be an Object, but %v given.",
  204. service
  205. );
  206. this._services.set(ctor, service);
  207. return this;
  208. }
  209. /**
  210. * Найти сервис удовлетворяющий условию.
  211. *
  212. * @param {function(Function, ServiceContainer): boolean} predicate
  213. * @param {boolean} noParent
  214. * @returns {*}
  215. */
  216. find(predicate, noParent = false) {
  217. if (typeof predicate !== "function") {
  218. throw new InvalidArgumentError(
  219. "The first argument of ServiceContainer.find must be a function, but %v given.",
  220. predicate
  221. );
  222. }
  223. const isRecursive = !noParent;
  224. let currentContainer = this;
  225. do {
  226. for (const ctor of currentContainer._services.keys()) {
  227. if (predicate(ctor, currentContainer) === true) {
  228. return this.get(ctor);
  229. }
  230. }
  231. if (isRecursive && currentContainer.hasParent()) {
  232. currentContainer = currentContainer.getParent();
  233. } else {
  234. currentContainer = null;
  235. }
  236. } while (currentContainer);
  237. return void 0;
  238. }
  239. };
  240. __name(_ServiceContainer, "ServiceContainer");
  241. /**
  242. * Kinds.
  243. *
  244. * @type {string[]}
  245. */
  246. __publicField(_ServiceContainer, "kinds", [SERVICE_CONTAINER_CLASS_NAME]);
  247. var ServiceContainer = _ServiceContainer;
  248. // src/utils/is-service-container.js
  249. function isServiceContainer(container) {
  250. return Boolean(
  251. container && typeof container === "object" && typeof container.constructor === "function" && Array.isArray(container.constructor.kinds) && container.constructor.kinds.includes(SERVICE_CONTAINER_CLASS_NAME)
  252. );
  253. }
  254. __name(isServiceContainer, "isServiceContainer");
  255. // src/service.js
  256. var SERVICE_CLASS_NAME = "Service";
  257. var _Service = class _Service {
  258. /**
  259. * Container.
  260. *
  261. * @type {ServiceContainer}
  262. */
  263. container;
  264. /**
  265. * Constructor.
  266. *
  267. * @param {ServiceContainer|undefined} container
  268. */
  269. constructor(container = void 0) {
  270. this.container = isServiceContainer(container) ? container : new ServiceContainer();
  271. }
  272. /**
  273. * Получить существующий или новый экземпляр.
  274. *
  275. * @param {*} ctor
  276. * @param {*} args
  277. * @returns {*}
  278. */
  279. getService(ctor, ...args) {
  280. return this.container.get(ctor, ...args);
  281. }
  282. /**
  283. * Получить существующий или новый экземпляр,
  284. * только если конструктор зарегистрирован.
  285. *
  286. * @param {*} ctor
  287. * @param {*} args
  288. * @returns {*}
  289. */
  290. getRegisteredService(ctor, ...args) {
  291. return this.container.getRegistered(ctor, ...args);
  292. }
  293. /**
  294. * Проверка существования конструктора в контейнере.
  295. *
  296. * @param {*} ctor
  297. * @returns {boolean}
  298. */
  299. hasService(ctor) {
  300. return this.container.has(ctor);
  301. }
  302. /**
  303. * Добавить конструктор в контейнер.
  304. *
  305. * @param {*} ctor
  306. * @param {*} args
  307. * @returns {this}
  308. */
  309. addService(ctor, ...args) {
  310. this.container.add(ctor, ...args);
  311. return this;
  312. }
  313. /**
  314. * Добавить конструктор и создать экземпляр.
  315. *
  316. * @param {*} ctor
  317. * @param {*} args
  318. * @returns {this}
  319. */
  320. useService(ctor, ...args) {
  321. this.container.use(ctor, ...args);
  322. return this;
  323. }
  324. /**
  325. * Добавить конструктор и связанный экземпляр.
  326. *
  327. * @param {*} ctor
  328. * @param {*} service
  329. * @returns {this}
  330. */
  331. setService(ctor, service) {
  332. this.container.set(ctor, service);
  333. return this;
  334. }
  335. /**
  336. * Найти сервис удовлетворяющий условию.
  337. *
  338. * @param {function(Function, ServiceContainer): boolean} predicate
  339. * @param {boolean} noParent
  340. * @returns {*}
  341. */
  342. findService(predicate, noParent = false) {
  343. return this.container.find(predicate, noParent);
  344. }
  345. };
  346. __name(_Service, "Service");
  347. /**
  348. * Kinds.
  349. *
  350. * @type {string[]}
  351. */
  352. __publicField(_Service, "kinds", [SERVICE_CLASS_NAME]);
  353. var Service = _Service;
  354. // src/debuggable-service.js
  355. var import_js_debug = require("@e22m4u/js-debug");
  356. var _DebuggableService = class _DebuggableService extends import_js_debug.Debuggable {
  357. /**
  358. * Service.
  359. *
  360. * @type {Service}
  361. */
  362. _service;
  363. /**
  364. * Container.
  365. *
  366. * @type {ServiceContainer}
  367. */
  368. get container() {
  369. return this._service.container;
  370. }
  371. /**
  372. * Получить существующий или новый экземпляр.
  373. *
  374. * @type {Service['getService']}
  375. */
  376. get getService() {
  377. return this._service.getService;
  378. }
  379. /**
  380. * Получить существующий или новый экземпляр,
  381. * только если конструктор зарегистрирован.
  382. *
  383. * @type {Service['getRegisteredService']}
  384. */
  385. get getRegisteredService() {
  386. return this._service.getRegisteredService;
  387. }
  388. /**
  389. * Проверка существования конструктора в контейнере.
  390. *
  391. * @type {Service['hasService']}
  392. */
  393. get hasService() {
  394. return this._service.hasService;
  395. }
  396. /**
  397. * Добавить конструктор в контейнер.
  398. *
  399. * @type {Service['addService']}
  400. */
  401. get addService() {
  402. return this._service.addService;
  403. }
  404. /**
  405. * Добавить конструктор и создать экземпляр.
  406. *
  407. * @type {Service['useService']}
  408. */
  409. get useService() {
  410. return this._service.useService;
  411. }
  412. /**
  413. * Добавить конструктор и связанный экземпляр.
  414. *
  415. * @type {Service['setService']}
  416. */
  417. get setService() {
  418. return this._service.setService;
  419. }
  420. /**
  421. * Найти сервис удовлетворяющий условию.
  422. *
  423. * @type {Service['findService']}
  424. */
  425. get findService() {
  426. return this._service.findService;
  427. }
  428. /**
  429. * Constructor.
  430. *
  431. * @param {ServiceContainer|undefined} container
  432. * @param {import('@e22m4u/js-debug').DebuggableOptions|undefined} options
  433. */
  434. constructor(container = void 0, options = void 0) {
  435. super(options);
  436. this._service = new Service(container);
  437. }
  438. };
  439. __name(_DebuggableService, "DebuggableService");
  440. /**
  441. * Kinds.
  442. *
  443. * @type {string[]}
  444. */
  445. __publicField(_DebuggableService, "kinds", Service.kinds);
  446. var DebuggableService = _DebuggableService;
  447. // Annotate the CommonJS export names for ESM import in node:
  448. 0 && (module.exports = {
  449. DebuggableService,
  450. SERVICE_CLASS_NAME,
  451. SERVICE_CONTAINER_CLASS_NAME,
  452. Service,
  453. ServiceContainer,
  454. isServiceContainer
  455. });