@andrew_l/ioc 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2024 Andrew L. <andrew.io.dev@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # Description
2
+
3
+ Before running the application code, set up the service container. This example auto-imports all `*.service.js` files from the service directories.
4
+
5
+ [Documentation](https://men232.github.io/toolkit/reference/@andrew_l/ioc/)
6
+
7
+ # Setup
8
+
9
+ ```js
10
+ import { ServiceContainer } from '@andrew_l/ioc';
11
+
12
+ await ServiceContainer.setup({
13
+ pathRoot: process.cwd(),
14
+ autoImportPatterns: ['./services/*/**/*.service.{js,mjs}'],
15
+ typeOutput: './ioc.d.ts',
16
+ generateTypes: true,
17
+ });
18
+
19
+ // your code
20
+ ```
21
+
22
+ # Usage
23
+
24
+ ```js
25
+ // user.service.js
26
+ import { ServiceContainer } from '@andrew_l/ioc';
27
+
28
+ export class UserService {
29
+ async create() {
30
+ // TODO
31
+ }
32
+ }
33
+
34
+ ServiceContainer.set('UserService', UserService);
35
+ ```
36
+
37
+ ```js
38
+ // user.controller.js
39
+ import { ioc } from '@andrew_l/ioc';
40
+
41
+ export function createUser() {
42
+ const UserService = ioc('UserService');
43
+
44
+ ctx.body = await UserService.create(ctx.request.body);
45
+ }
46
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+
3
+ const glob = require('glob');
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs/promises');
6
+ const path = require('node:path');
7
+ const toolkit = require('@andrew_l/toolkit');
8
+
9
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
11
+
12
+ const glob__default = /*#__PURE__*/_interopDefaultCompat(glob);
13
+ const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto);
14
+ const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
15
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path);
16
+
17
+ const storage = /* @__PURE__ */ new Map();
18
+ const log = toolkit.logger(({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }), "IOC");
19
+ const ServiceContainer = {
20
+ get(id) {
21
+ const service = storage.get(id);
22
+ if (!service) {
23
+ throw new Error(`No service is registered for [${id}]`);
24
+ }
25
+ if (!service.instance) {
26
+ service.instance = service.factory?.();
27
+ service.factory = void 0;
28
+ }
29
+ return service.instance;
30
+ },
31
+ set(id, factoryOrClassReference, buildInstantly = false) {
32
+ if (this.isSet(id)) {
33
+ throw new Error(`Service [${id}] is already registered`);
34
+ }
35
+ let constructorPath;
36
+ try {
37
+ constructorPath = new URL(
38
+ toolkit.captureStackTrace(this.set).split("\n")[0].slice(7)
39
+ ).pathname.split(":")[0];
40
+ } catch (_) {
41
+ }
42
+ this.override(id, factoryOrClassReference, buildInstantly, constructorPath);
43
+ },
44
+ override(id, factoryOrClassReference, buildInstantly = false, constructorPath) {
45
+ const factory = getFactory(factoryOrClassReference);
46
+ storage.set(id, {
47
+ factory: buildInstantly ? void 0 : factory,
48
+ instance: buildInstantly ? factory() : void 0,
49
+ constructorName: getConstructorName(factoryOrClassReference),
50
+ constructorPath
51
+ });
52
+ },
53
+ isSet(id) {
54
+ return storage.has(id);
55
+ },
56
+ clear() {
57
+ storage.clear();
58
+ },
59
+ async setup({
60
+ pathRoot = process.cwd(),
61
+ generateTypes = false,
62
+ autoImportPatterns = ["./services/*/**/*.service.{js,mjs,ts,mts,cts}"],
63
+ typeOutput = "./ioc.d.ts"
64
+ } = {}) {
65
+ typeOutput = path__default.isAbsolute(typeOutput) ? typeOutput : path__default.join(pathRoot, typeOutput);
66
+ if (!typeOutput.endsWith(".d.ts")) {
67
+ typeOutput = path__default.join(typeOutput, "ioc.d.ts");
68
+ }
69
+ autoImportPatterns = autoImportPatterns.map((servicePath) => {
70
+ return path__default.isAbsolute(servicePath) ? servicePath : path__default.join(pathRoot, servicePath);
71
+ });
72
+ log.debug("Setup", {
73
+ pathRoot,
74
+ generateTypes,
75
+ autoImportPatterns,
76
+ typeOutput
77
+ });
78
+ await this.importServices(autoImportPatterns);
79
+ if (generateTypes) {
80
+ await this.writeTypes(typeOutput);
81
+ }
82
+ },
83
+ async importServices(autoImportPatterns) {
84
+ for (const pattern of autoImportPatterns) {
85
+ for (const filePath of glob__default.sync(pattern)) {
86
+ await import(filePath);
87
+ }
88
+ }
89
+ },
90
+ async writeTypes(outputFilePath) {
91
+ const typesDefinitions = [];
92
+ const outputFolderPath = path__default.dirname(outputFilePath);
93
+ for (const [
94
+ key,
95
+ { constructorName, constructorPath }
96
+ ] of storage.entries()) {
97
+ if (!constructorName) continue;
98
+ if (!constructorPath) continue;
99
+ typesDefinitions.push(
100
+ `"${key}": import('./${path__default.relative(
101
+ outputFolderPath,
102
+ constructorPath
103
+ )}').${constructorName};`
104
+ );
105
+ }
106
+ const typesContent = `/* eslint-disable */
107
+ /* prettier-ignore */
108
+ // @ts-nocheck
109
+ // Generated by @andrew_l/ioc
110
+
111
+ export {};
112
+
113
+ declare module '@andrew_l/ioc' {
114
+ interface IocMap {
115
+ ${typesDefinitions.sort().join("\n ")}
116
+ }
117
+
118
+ function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
119
+ }`;
120
+ const newHash = crypto__default.createHmac("sha256", "").update(typesContent).digest("hex");
121
+ const oldHash = await getHashFromTypeFile(outputFilePath);
122
+ if (newHash !== oldHash) {
123
+ log.warn("Types file has been updated.");
124
+ await fs__default.writeFile(
125
+ outputFilePath,
126
+ `// hash:${newHash}
127
+ ${typesContent}
128
+ `
129
+ );
130
+ }
131
+ }
132
+ };
133
+ function isConstructable(obj) {
134
+ return !!obj.prototype && !!obj.prototype.constructor.name;
135
+ }
136
+ function getFactory(factoryOrClassReference) {
137
+ return isConstructable(factoryOrClassReference) ? () => new factoryOrClassReference() : factoryOrClassReference;
138
+ }
139
+ function getConstructorName(factoryOrClassReference) {
140
+ return isConstructable(factoryOrClassReference) ? factoryOrClassReference.prototype.constructor.name : String(factoryOrClassReference).match(/new\s(\w+)\(/)?.[1] || "";
141
+ }
142
+ async function getHashFromTypeFile(filePath) {
143
+ try {
144
+ const content = await fs__default.readFile(filePath, { encoding: "utf8" });
145
+ const lastLine = content.split("\n").at(0);
146
+ return lastLine?.split("hash:")[1] || null;
147
+ } catch (_) {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ function ioc(id) {
153
+ return ServiceContainer.get(id);
154
+ }
155
+
156
+ exports.ServiceContainer = ServiceContainer;
157
+ exports.ioc = ioc;
158
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/ServiceContainer.ts","../src/ioc.ts"],"sourcesContent":["import glob from 'glob';\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { type AnyFunction, captureStackTrace, logger } from '@andrew_l/toolkit';\n\nexport type Factory = any;\n\nexport type Service = {\n factory?: Factory;\n constructorName?: string;\n constructorPath?: string;\n instance: any;\n};\n\nexport interface SetupOptions {\n pathRoot?: string;\n\n /**\n * Absolute or relative path where generated type file will be saved\n */\n typeOutput?: string;\n\n /**\n * Absolute or relative glob patterns to auto-import service files\n */\n autoImportPatterns?: string[];\n\n /**\n * Should generate type file\n */\n generateTypes?: boolean;\n}\n\nconst storage = new Map<string, Service>();\n\nconst log = logger(import.meta, 'IOC');\n\nexport default {\n get<T>(id: string): T {\n const service = storage.get(id);\n\n if (!service) {\n throw new Error(`No service is registered for [${id}]`);\n }\n\n if (!service.instance) {\n service.instance = service.factory?.();\n service.factory = undefined;\n }\n\n return service.instance;\n },\n\n set(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n ) {\n if (this.isSet(id)) {\n throw new Error(`Service [${id}] is already registered`);\n }\n\n let constructorPath: string | undefined;\n\n try {\n constructorPath = new URL(\n captureStackTrace(this.set).split('\\n')[0].slice(7),\n ).pathname.split(':')[0];\n } catch (_) {}\n\n this.override(id, factoryOrClassReference, buildInstantly, constructorPath);\n },\n\n override(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n constructorPath?: string,\n ) {\n const factory: Factory = getFactory(factoryOrClassReference);\n\n storage.set(id, {\n factory: buildInstantly ? undefined : factory,\n instance: buildInstantly ? factory() : undefined,\n constructorName: getConstructorName(factoryOrClassReference),\n constructorPath,\n });\n },\n\n isSet(id: string): boolean {\n return storage.has(id);\n },\n\n clear() {\n storage.clear();\n },\n\n async setup({\n pathRoot = process.cwd(),\n generateTypes = false,\n autoImportPatterns = ['./services/*/**/*.service.{js,mjs,ts,mts,cts}'],\n typeOutput = './ioc.d.ts',\n }: SetupOptions | undefined = {}) {\n typeOutput = path.isAbsolute(typeOutput)\n ? typeOutput\n : path.join(pathRoot, typeOutput);\n\n if (!typeOutput.endsWith('.d.ts')) {\n typeOutput = path.join(typeOutput, 'ioc.d.ts');\n }\n\n autoImportPatterns = autoImportPatterns.map(servicePath => {\n return path.isAbsolute(servicePath)\n ? servicePath\n : path.join(pathRoot, servicePath);\n });\n\n log.debug('Setup', {\n pathRoot,\n generateTypes,\n autoImportPatterns,\n typeOutput,\n });\n\n await this.importServices(autoImportPatterns);\n\n if (generateTypes) {\n await this.writeTypes(typeOutput);\n }\n },\n\n async importServices(autoImportPatterns: string[]) {\n for (const pattern of autoImportPatterns) {\n for (const filePath of glob.sync(pattern)) {\n await import(filePath);\n }\n }\n },\n\n async writeTypes(outputFilePath: string) {\n const typesDefinitions: string[] = [];\n const outputFolderPath = path.dirname(outputFilePath);\n\n for (const [\n key,\n { constructorName, constructorPath },\n ] of storage.entries()) {\n if (!constructorName) continue;\n if (!constructorPath) continue;\n\n typesDefinitions.push(\n `\"${key}\": import('./${path.relative(\n outputFolderPath,\n constructorPath,\n )}').${constructorName};`,\n );\n }\n\n const typesContent = `/* eslint-disable */\n/* prettier-ignore */\n// @ts-nocheck\n// Generated by @andrew_l/ioc\n\nexport {};\n\ndeclare module '@andrew_l/ioc' {\n\tinterface IocMap {\n\t\t${typesDefinitions.sort().join('\\n\\t\\t')}\n\t}\n\n\tfunction ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];\n}`;\n\n const newHash = crypto\n .createHmac('sha256', '')\n .update(typesContent)\n .digest('hex');\n\n const oldHash = await getHashFromTypeFile(outputFilePath);\n\n if (newHash !== oldHash) {\n log.warn('Types file has been updated.');\n\n await fs.writeFile(\n outputFilePath,\n `// hash:${newHash}\\n${typesContent}\\n`,\n );\n }\n },\n};\n\nfunction isConstructable(obj: any): obj is Function {\n // https://stackoverflow.com/a/46320004\n return !!obj.prototype && !!obj.prototype.constructor.name;\n}\n\nfunction getFactory(factoryOrClassReference: Factory | AnyFunction): Factory {\n return isConstructable(factoryOrClassReference)\n ? () => new factoryOrClassReference()\n : factoryOrClassReference;\n}\n\nfunction getConstructorName(\n factoryOrClassReference: Factory | AnyFunction,\n): string {\n return isConstructable(factoryOrClassReference)\n ? factoryOrClassReference.prototype.constructor.name\n : String(factoryOrClassReference).match(/new\\s(\\w+)\\(/)?.[1] || '';\n}\n\nasync function getHashFromTypeFile(filePath: string): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, { encoding: 'utf8' });\n const lastLine = content.split('\\n').at(0);\n\n return lastLine?.split('hash:')[1] || null;\n } catch (_) {\n return null;\n }\n}\n","import ServiceContainer from './ServiceContainer';\n\n/**\n * This interface can be augmented by users to add types to ioc\n */\ninterface IocMap {}\n\n/**\n * Get instance of service\n * @example\n * const userService ioc('UserService');\n *\n * @group Main\n */\nexport function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key] {\n return ServiceContainer.get(id as any) as any;\n}\nexport type { IocMap };\n"],"names":["logger","captureStackTrace","path","glob","crypto","fs"],"mappings":";;;;;;;;;;;;;;;;AAoCA,MAAM,OAAA,uBAAc,GAAqB,EAAA,CAAA;AAEzC,MAAM,GAAA,GAAMA,cAAO,CAAA,sQAAA,EAAa,KAAK,CAAA,CAAA;AAErC,yBAAe;AAAA,EACb,IAAO,EAAe,EAAA;AACpB,IAAM,MAAA,OAAA,GAAU,OAAQ,CAAA,GAAA,CAAI,EAAE,CAAA,CAAA;AAE9B,IAAA,IAAI,CAAC,OAAS,EAAA;AACZ,MAAA,MAAM,IAAI,KAAA,CAAM,CAAiC,8BAAA,EAAA,EAAE,CAAG,CAAA,CAAA,CAAA,CAAA;AAAA,KACxD;AAEA,IAAI,IAAA,CAAC,QAAQ,QAAU,EAAA;AACrB,MAAQ,OAAA,CAAA,QAAA,GAAW,QAAQ,OAAU,IAAA,CA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_l/toolkit';
2
+
3
+ type Factory = any;
4
+ interface SetupOptions {
5
+ pathRoot?: string;
6
+ /**
7
+ * Absolute or relative path where generated type file will be saved
8
+ */
9
+ typeOutput?: string;
10
+ /**
11
+ * Absolute or relative glob patterns to auto-import service files
12
+ */
13
+ autoImportPatterns?: string[];
14
+ /**
15
+ * Should generate type file
16
+ */
17
+ generateTypes?: boolean;
18
+ }
19
+ declare const _default: {
20
+ get<T>(id: string): T;
21
+ set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
22
+ override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
23
+ isSet(id: string): boolean;
24
+ clear(): void;
25
+ setup({ pathRoot, generateTypes, autoImportPatterns, typeOutput, }?: SetupOptions | undefined): Promise<void>;
26
+ importServices(autoImportPatterns: string[]): Promise<void>;
27
+ writeTypes(outputFilePath: string): Promise<void>;
28
+ };
29
+
30
+ /**
31
+ * This interface can be augmented by users to add types to ioc
32
+ */
33
+ interface IocMap {
34
+ }
35
+ /**
36
+ * Get instance of service
37
+ * @example
38
+ * const userService ioc('UserService');
39
+ *
40
+ * @group Main
41
+ */
42
+ declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
43
+
44
+ export { type IocMap, _default as ServiceContainer, ioc };
@@ -0,0 +1,44 @@
1
+ import { AnyFunction } from '@andrew_l/toolkit';
2
+
3
+ type Factory = any;
4
+ interface SetupOptions {
5
+ pathRoot?: string;
6
+ /**
7
+ * Absolute or relative path where generated type file will be saved
8
+ */
9
+ typeOutput?: string;
10
+ /**
11
+ * Absolute or relative glob patterns to auto-import service files
12
+ */
13
+ autoImportPatterns?: string[];
14
+ /**
15
+ * Should generate type file
16
+ */
17
+ generateTypes?: boolean;
18
+ }
19
+ declare const _default: {
20
+ get<T>(id: string): T;
21
+ set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
22
+ override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
23
+ isSet(id: string): boolean;
24
+ clear(): void;
25
+ setup({ pathRoot, generateTypes, autoImportPatterns, typeOutput, }?: SetupOptions | undefined): Promise<void>;
26
+ importServices(autoImportPatterns: string[]): Promise<void>;
27
+ writeTypes(outputFilePath: string): Promise<void>;
28
+ };
29
+
30
+ /**
31
+ * This interface can be augmented by users to add types to ioc
32
+ */
33
+ interface IocMap {
34
+ }
35
+ /**
36
+ * Get instance of service
37
+ * @example
38
+ * const userService ioc('UserService');
39
+ *
40
+ * @group Main
41
+ */
42
+ declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
43
+
44
+ export { type IocMap, _default as ServiceContainer, ioc };
@@ -0,0 +1,44 @@
1
+ import { AnyFunction } from '@andrew_l/toolkit';
2
+
3
+ type Factory = any;
4
+ interface SetupOptions {
5
+ pathRoot?: string;
6
+ /**
7
+ * Absolute or relative path where generated type file will be saved
8
+ */
9
+ typeOutput?: string;
10
+ /**
11
+ * Absolute or relative glob patterns to auto-import service files
12
+ */
13
+ autoImportPatterns?: string[];
14
+ /**
15
+ * Should generate type file
16
+ */
17
+ generateTypes?: boolean;
18
+ }
19
+ declare const _default: {
20
+ get<T>(id: string): T;
21
+ set(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean): void;
22
+ override(id: string, factoryOrClassReference: Factory | AnyFunction, buildInstantly?: boolean, constructorPath?: string): void;
23
+ isSet(id: string): boolean;
24
+ clear(): void;
25
+ setup({ pathRoot, generateTypes, autoImportPatterns, typeOutput, }?: SetupOptions | undefined): Promise<void>;
26
+ importServices(autoImportPatterns: string[]): Promise<void>;
27
+ writeTypes(outputFilePath: string): Promise<void>;
28
+ };
29
+
30
+ /**
31
+ * This interface can be augmented by users to add types to ioc
32
+ */
33
+ interface IocMap {
34
+ }
35
+ /**
36
+ * Get instance of service
37
+ * @example
38
+ * const userService ioc('UserService');
39
+ *
40
+ * @group Main
41
+ */
42
+ declare function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
43
+
44
+ export { type IocMap, _default as ServiceContainer, ioc };
package/dist/index.mjs ADDED
@@ -0,0 +1,147 @@
1
+ import glob from 'glob';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { logger, captureStackTrace } from '@andrew_l/toolkit';
6
+
7
+ const storage = /* @__PURE__ */ new Map();
8
+ const log = logger(import.meta, "IOC");
9
+ const ServiceContainer = {
10
+ get(id) {
11
+ const service = storage.get(id);
12
+ if (!service) {
13
+ throw new Error(`No service is registered for [${id}]`);
14
+ }
15
+ if (!service.instance) {
16
+ service.instance = service.factory?.();
17
+ service.factory = void 0;
18
+ }
19
+ return service.instance;
20
+ },
21
+ set(id, factoryOrClassReference, buildInstantly = false) {
22
+ if (this.isSet(id)) {
23
+ throw new Error(`Service [${id}] is already registered`);
24
+ }
25
+ let constructorPath;
26
+ try {
27
+ constructorPath = new URL(
28
+ captureStackTrace(this.set).split("\n")[0].slice(7)
29
+ ).pathname.split(":")[0];
30
+ } catch (_) {
31
+ }
32
+ this.override(id, factoryOrClassReference, buildInstantly, constructorPath);
33
+ },
34
+ override(id, factoryOrClassReference, buildInstantly = false, constructorPath) {
35
+ const factory = getFactory(factoryOrClassReference);
36
+ storage.set(id, {
37
+ factory: buildInstantly ? void 0 : factory,
38
+ instance: buildInstantly ? factory() : void 0,
39
+ constructorName: getConstructorName(factoryOrClassReference),
40
+ constructorPath
41
+ });
42
+ },
43
+ isSet(id) {
44
+ return storage.has(id);
45
+ },
46
+ clear() {
47
+ storage.clear();
48
+ },
49
+ async setup({
50
+ pathRoot = process.cwd(),
51
+ generateTypes = false,
52
+ autoImportPatterns = ["./services/*/**/*.service.{js,mjs,ts,mts,cts}"],
53
+ typeOutput = "./ioc.d.ts"
54
+ } = {}) {
55
+ typeOutput = path.isAbsolute(typeOutput) ? typeOutput : path.join(pathRoot, typeOutput);
56
+ if (!typeOutput.endsWith(".d.ts")) {
57
+ typeOutput = path.join(typeOutput, "ioc.d.ts");
58
+ }
59
+ autoImportPatterns = autoImportPatterns.map((servicePath) => {
60
+ return path.isAbsolute(servicePath) ? servicePath : path.join(pathRoot, servicePath);
61
+ });
62
+ log.debug("Setup", {
63
+ pathRoot,
64
+ generateTypes,
65
+ autoImportPatterns,
66
+ typeOutput
67
+ });
68
+ await this.importServices(autoImportPatterns);
69
+ if (generateTypes) {
70
+ await this.writeTypes(typeOutput);
71
+ }
72
+ },
73
+ async importServices(autoImportPatterns) {
74
+ for (const pattern of autoImportPatterns) {
75
+ for (const filePath of glob.sync(pattern)) {
76
+ await import(filePath);
77
+ }
78
+ }
79
+ },
80
+ async writeTypes(outputFilePath) {
81
+ const typesDefinitions = [];
82
+ const outputFolderPath = path.dirname(outputFilePath);
83
+ for (const [
84
+ key,
85
+ { constructorName, constructorPath }
86
+ ] of storage.entries()) {
87
+ if (!constructorName) continue;
88
+ if (!constructorPath) continue;
89
+ typesDefinitions.push(
90
+ `"${key}": import('./${path.relative(
91
+ outputFolderPath,
92
+ constructorPath
93
+ )}').${constructorName};`
94
+ );
95
+ }
96
+ const typesContent = `/* eslint-disable */
97
+ /* prettier-ignore */
98
+ // @ts-nocheck
99
+ // Generated by @andrew_l/ioc
100
+
101
+ export {};
102
+
103
+ declare module '@andrew_l/ioc' {
104
+ interface IocMap {
105
+ ${typesDefinitions.sort().join("\n ")}
106
+ }
107
+
108
+ function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];
109
+ }`;
110
+ const newHash = crypto.createHmac("sha256", "").update(typesContent).digest("hex");
111
+ const oldHash = await getHashFromTypeFile(outputFilePath);
112
+ if (newHash !== oldHash) {
113
+ log.warn("Types file has been updated.");
114
+ await fs.writeFile(
115
+ outputFilePath,
116
+ `// hash:${newHash}
117
+ ${typesContent}
118
+ `
119
+ );
120
+ }
121
+ }
122
+ };
123
+ function isConstructable(obj) {
124
+ return !!obj.prototype && !!obj.prototype.constructor.name;
125
+ }
126
+ function getFactory(factoryOrClassReference) {
127
+ return isConstructable(factoryOrClassReference) ? () => new factoryOrClassReference() : factoryOrClassReference;
128
+ }
129
+ function getConstructorName(factoryOrClassReference) {
130
+ return isConstructable(factoryOrClassReference) ? factoryOrClassReference.prototype.constructor.name : String(factoryOrClassReference).match(/new\s(\w+)\(/)?.[1] || "";
131
+ }
132
+ async function getHashFromTypeFile(filePath) {
133
+ try {
134
+ const content = await fs.readFile(filePath, { encoding: "utf8" });
135
+ const lastLine = content.split("\n").at(0);
136
+ return lastLine?.split("hash:")[1] || null;
137
+ } catch (_) {
138
+ return null;
139
+ }
140
+ }
141
+
142
+ function ioc(id) {
143
+ return ServiceContainer.get(id);
144
+ }
145
+
146
+ export { ServiceContainer, ioc };
147
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/ServiceContainer.ts","../src/ioc.ts"],"sourcesContent":["import glob from 'glob';\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { type AnyFunction, captureStackTrace, logger } from '@andrew_l/toolkit';\n\nexport type Factory = any;\n\nexport type Service = {\n factory?: Factory;\n constructorName?: string;\n constructorPath?: string;\n instance: any;\n};\n\nexport interface SetupOptions {\n pathRoot?: string;\n\n /**\n * Absolute or relative path where generated type file will be saved\n */\n typeOutput?: string;\n\n /**\n * Absolute or relative glob patterns to auto-import service files\n */\n autoImportPatterns?: string[];\n\n /**\n * Should generate type file\n */\n generateTypes?: boolean;\n}\n\nconst storage = new Map<string, Service>();\n\nconst log = logger(import.meta, 'IOC');\n\nexport default {\n get<T>(id: string): T {\n const service = storage.get(id);\n\n if (!service) {\n throw new Error(`No service is registered for [${id}]`);\n }\n\n if (!service.instance) {\n service.instance = service.factory?.();\n service.factory = undefined;\n }\n\n return service.instance;\n },\n\n set(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n ) {\n if (this.isSet(id)) {\n throw new Error(`Service [${id}] is already registered`);\n }\n\n let constructorPath: string | undefined;\n\n try {\n constructorPath = new URL(\n captureStackTrace(this.set).split('\\n')[0].slice(7),\n ).pathname.split(':')[0];\n } catch (_) {}\n\n this.override(id, factoryOrClassReference, buildInstantly, constructorPath);\n },\n\n override(\n id: string,\n factoryOrClassReference: Factory | AnyFunction,\n buildInstantly: boolean = false,\n constructorPath?: string,\n ) {\n const factory: Factory = getFactory(factoryOrClassReference);\n\n storage.set(id, {\n factory: buildInstantly ? undefined : factory,\n instance: buildInstantly ? factory() : undefined,\n constructorName: getConstructorName(factoryOrClassReference),\n constructorPath,\n });\n },\n\n isSet(id: string): boolean {\n return storage.has(id);\n },\n\n clear() {\n storage.clear();\n },\n\n async setup({\n pathRoot = process.cwd(),\n generateTypes = false,\n autoImportPatterns = ['./services/*/**/*.service.{js,mjs,ts,mts,cts}'],\n typeOutput = './ioc.d.ts',\n }: SetupOptions | undefined = {}) {\n typeOutput = path.isAbsolute(typeOutput)\n ? typeOutput\n : path.join(pathRoot, typeOutput);\n\n if (!typeOutput.endsWith('.d.ts')) {\n typeOutput = path.join(typeOutput, 'ioc.d.ts');\n }\n\n autoImportPatterns = autoImportPatterns.map(servicePath => {\n return path.isAbsolute(servicePath)\n ? servicePath\n : path.join(pathRoot, servicePath);\n });\n\n log.debug('Setup', {\n pathRoot,\n generateTypes,\n autoImportPatterns,\n typeOutput,\n });\n\n await this.importServices(autoImportPatterns);\n\n if (generateTypes) {\n await this.writeTypes(typeOutput);\n }\n },\n\n async importServices(autoImportPatterns: string[]) {\n for (const pattern of autoImportPatterns) {\n for (const filePath of glob.sync(pattern)) {\n await import(filePath);\n }\n }\n },\n\n async writeTypes(outputFilePath: string) {\n const typesDefinitions: string[] = [];\n const outputFolderPath = path.dirname(outputFilePath);\n\n for (const [\n key,\n { constructorName, constructorPath },\n ] of storage.entries()) {\n if (!constructorName) continue;\n if (!constructorPath) continue;\n\n typesDefinitions.push(\n `\"${key}\": import('./${path.relative(\n outputFolderPath,\n constructorPath,\n )}').${constructorName};`,\n );\n }\n\n const typesContent = `/* eslint-disable */\n/* prettier-ignore */\n// @ts-nocheck\n// Generated by @andrew_l/ioc\n\nexport {};\n\ndeclare module '@andrew_l/ioc' {\n\tinterface IocMap {\n\t\t${typesDefinitions.sort().join('\\n\\t\\t')}\n\t}\n\n\tfunction ioc<Key extends keyof IocMap>(id: Key): IocMap[Key];\n}`;\n\n const newHash = crypto\n .createHmac('sha256', '')\n .update(typesContent)\n .digest('hex');\n\n const oldHash = await getHashFromTypeFile(outputFilePath);\n\n if (newHash !== oldHash) {\n log.warn('Types file has been updated.');\n\n await fs.writeFile(\n outputFilePath,\n `// hash:${newHash}\\n${typesContent}\\n`,\n );\n }\n },\n};\n\nfunction isConstructable(obj: any): obj is Function {\n // https://stackoverflow.com/a/46320004\n return !!obj.prototype && !!obj.prototype.constructor.name;\n}\n\nfunction getFactory(factoryOrClassReference: Factory | AnyFunction): Factory {\n return isConstructable(factoryOrClassReference)\n ? () => new factoryOrClassReference()\n : factoryOrClassReference;\n}\n\nfunction getConstructorName(\n factoryOrClassReference: Factory | AnyFunction,\n): string {\n return isConstructable(factoryOrClassReference)\n ? factoryOrClassReference.prototype.constructor.name\n : String(factoryOrClassReference).match(/new\\s(\\w+)\\(/)?.[1] || '';\n}\n\nasync function getHashFromTypeFile(filePath: string): Promise<string | null> {\n try {\n const content = await fs.readFile(filePath, { encoding: 'utf8' });\n const lastLine = content.split('\\n').at(0);\n\n return lastLine?.split('hash:')[1] || null;\n } catch (_) {\n return null;\n }\n}\n","import ServiceContainer from './ServiceContainer';\n\n/**\n * This interface can be augmented by users to add types to ioc\n */\ninterface IocMap {}\n\n/**\n * Get instance of service\n * @example\n * const userService ioc('UserService');\n *\n * @group Main\n */\nexport function ioc<Key extends keyof IocMap>(id: Key): IocMap[Key] {\n return ServiceContainer.get(id as any) as any;\n}\nexport type { IocMap };\n"],"names":[],"mappings":";;;;;;AAoCA,MAAM,OAAA,uBAAc,GAAqB,EAAA,CAAA;A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AAU,QAAQ,CAAA,CAAA;AAChE,IAAA,MAAM,WAAW,OAAQ,CAAA,KAAA,CAAM,IAAI,CAAA,CAAE,GAAG,CAAC,CAAA,CAAA;AAEzC,IAAA,OAAO,QAAU,EAAA,KAAA,CAAM,OAAO,CAAA,CAAE,CAAC,CAAK,IAAA,IAAA,CAAA;AAAA,WAC/B,CAAG,EAAA;AACV,IAAO,OAAA,IAAA,CAAA;AAAA,GACT;AACF;;AChNO,SAAS,IAA8B,EAAsB,EAAA;AAClE,EAAO,OAAA,gBAAA,CAAiB,IAAI,EAAS,CAAA,CAAA;AACvC;;;;"}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@andrew_l/ioc",
3
+ "version": "0.0.1",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "keywords": [
7
+ "service",
8
+ "container",
9
+ "dependencies",
10
+ "injection",
11
+ "ioc"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/men232/toolkit.git",
16
+ "directory": "packages/ioc"
17
+ },
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.mjs",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "main": "./dist/index.cjs",
25
+ "types": "./dist/index.d.ts",
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "devDependencies": {
30
+ "unbuild": "3.0.0-rc.11",
31
+ "@types/node": "^20.16.10",
32
+ "typescript": "~5.6.2",
33
+ "vitest": "^2.1.3",
34
+ "@types/glob": "^8.1.0"
35
+ },
36
+ "dependencies": {
37
+ "glob": "^11.0.0",
38
+ "@andrew_l/toolkit": "0.0.1"
39
+ },
40
+ "scripts": {
41
+ "build": "unbuild",
42
+ "test": "vitest run --typecheck",
43
+ "test:watch": "vitest watch --typecheck"
44
+ }
45
+ }