index.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 (!service && !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. __name(_ServiceContainer, "ServiceContainer");
  211. /**
  212. * Kinds.
  213. *
  214. * @type {string[]}
  215. */
  216. __publicField(_ServiceContainer, "kinds", [SERVICE_CONTAINER_CLASS_NAME]);
  217. var ServiceContainer = _ServiceContainer;
  218. // src/utils/is-service-container.js
  219. function isServiceContainer(container) {
  220. return Boolean(
  221. container && typeof container === "object" && typeof container.constructor === "function" && Array.isArray(container.constructor.kinds) && container.constructor.kinds.includes(SERVICE_CONTAINER_CLASS_NAME)
  222. );
  223. }
  224. __name(isServiceContainer, "isServiceContainer");
  225. // src/service.js
  226. var SERVICE_CLASS_NAME = "Service";
  227. var _Service = class _Service {
  228. /**
  229. * Container.
  230. *
  231. * @type {ServiceContainer}
  232. */
  233. container;
  234. /**
  235. * Constructor.
  236. *
  237. * @param {ServiceContainer|undefined} container
  238. */
  239. constructor(container = void 0) {
  240. this.container = isServiceContainer(container) ? container : new ServiceContainer();
  241. }
  242. /**
  243. * Получить существующий или новый экземпляр.
  244. *
  245. * @param {*} ctor
  246. * @param {*} args
  247. * @returns {*}
  248. */
  249. getService(ctor, ...args) {
  250. return this.container.get(ctor, ...args);
  251. }
  252. /**
  253. * Получить существующий или новый экземпляр,
  254. * только если конструктор зарегистрирован.
  255. *
  256. * @param {*} ctor
  257. * @param {*} args
  258. * @returns {*}
  259. */
  260. getRegisteredService(ctor, ...args) {
  261. return this.container.getRegistered(ctor, ...args);
  262. }
  263. /**
  264. * Проверка существования конструктора в контейнере.
  265. *
  266. * @param {*} ctor
  267. * @returns {boolean}
  268. */
  269. hasService(ctor) {
  270. return this.container.has(ctor);
  271. }
  272. /**
  273. * Добавить конструктор в контейнер.
  274. *
  275. * @param {*} ctor
  276. * @param {*} args
  277. * @returns {this}
  278. */
  279. addService(ctor, ...args) {
  280. this.container.add(ctor, ...args);
  281. return this;
  282. }
  283. /**
  284. * Добавить конструктор и создать экземпляр.
  285. *
  286. * @param {*} ctor
  287. * @param {*} args
  288. * @returns {this}
  289. */
  290. useService(ctor, ...args) {
  291. this.container.use(ctor, ...args);
  292. return this;
  293. }
  294. /**
  295. * Добавить конструктор и связанный экземпляр.
  296. *
  297. * @param {*} ctor
  298. * @param {*} service
  299. * @returns {this}
  300. */
  301. setService(ctor, service) {
  302. this.container.set(ctor, service);
  303. return this;
  304. }
  305. };
  306. __name(_Service, "Service");
  307. /**
  308. * Kinds.
  309. *
  310. * @type {string[]}
  311. */
  312. __publicField(_Service, "kinds", [SERVICE_CLASS_NAME]);
  313. var Service = _Service;
  314. // src/debuggable-service.js
  315. var import_js_debug = require("@e22m4u/js-debug");
  316. var _DebuggableService = class _DebuggableService extends import_js_debug.Debuggable {
  317. /**
  318. * Service.
  319. *
  320. * @type {Service}
  321. */
  322. _service;
  323. /**
  324. * Container.
  325. *
  326. * @type {ServiceContainer}
  327. */
  328. get container() {
  329. return this._service.container;
  330. }
  331. /**
  332. * Получить существующий или новый экземпляр.
  333. *
  334. * @type {Service['getService']}
  335. */
  336. get getService() {
  337. return this._service.getService;
  338. }
  339. /**
  340. * Получить существующий или новый экземпляр,
  341. * только если конструктор зарегистрирован.
  342. *
  343. * @type {Service['getRegisteredService']}
  344. */
  345. get getRegisteredService() {
  346. return this._service.getRegisteredService;
  347. }
  348. /**
  349. * Проверка существования конструктора в контейнере.
  350. *
  351. * @type {Service['hasService']}
  352. */
  353. get hasService() {
  354. return this._service.hasService;
  355. }
  356. /**
  357. * Добавить конструктор в контейнер.
  358. *
  359. * @type {Service['addService']}
  360. */
  361. get addService() {
  362. return this._service.addService;
  363. }
  364. /**
  365. * Добавить конструктор и создать экземпляр.
  366. *
  367. * @type {Service['useService']}
  368. */
  369. get useService() {
  370. return this._service.useService;
  371. }
  372. /**
  373. * Добавить конструктор и связанный экземпляр.
  374. *
  375. * @type {Service['setService']}
  376. */
  377. get setService() {
  378. return this._service.setService;
  379. }
  380. /**
  381. * Constructor.
  382. *
  383. * @param {ServiceContainer|undefined} container
  384. * @param {import('@e22m4u/js-debug').DebuggableOptions|undefined} options
  385. */
  386. constructor(container = void 0, options = void 0) {
  387. super(options);
  388. this._service = new Service(container);
  389. }
  390. };
  391. __name(_DebuggableService, "DebuggableService");
  392. /**
  393. * Kinds.
  394. *
  395. * @type {string[]}
  396. */
  397. __publicField(_DebuggableService, "kinds", Service.kinds);
  398. var DebuggableService = _DebuggableService;
  399. // Annotate the CommonJS export names for ESM import in node:
  400. 0 && (module.exports = {
  401. DebuggableService,
  402. SERVICE_CLASS_NAME,
  403. SERVICE_CONTAINER_CLASS_NAME,
  404. Service,
  405. ServiceContainer,
  406. isServiceContainer
  407. });