@resolid/di 0.1.0

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) 2022-present, Resolid Tech
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,119 @@
1
+ # Resolid: DI Container Package
2
+
3
+ ![GitHub License](https://img.shields.io/github/license/resolid/framework)
4
+
5
+ <b>[Documentation](https://www.resolid.tech/docs/di)</b> | [Framework Bundle](https://github.com/resolid/framework)
6
+
7
+ ## TypeScript Dependency Injection Container
8
+
9
+ A lightweight, fully-typed Dependency Injection (DI) container for TypeScript.
10
+ Supports singleton & transient scopes, lazy resolution, and disposable resources. Fully functional with async factories
11
+ and avoids circular dependency issues.
12
+
13
+ ### Features
14
+
15
+ - Fully typed with TypeScript, no any.
16
+ - Supports singleton and transient scopes.
17
+ - Lazy resolution for async dependencies.
18
+ - Detects circular dependencies.
19
+ - Handles disposable instances with dispose() support.
20
+ - Fully async-compatible.
21
+
22
+ ### Installation
23
+
24
+ ```shell
25
+ pnpm add @resolid/di
26
+ # or
27
+ npm install @resolid/di
28
+ # or
29
+ yarn add @resolid/di
30
+ # or
31
+ bun add @resolid/di
32
+ ```
33
+
34
+ ### Usage
35
+
36
+ #### Creating a container
37
+
38
+ ```js
39
+ import { createContainer } from "@resolid/di";
40
+
41
+ const container = createContainer();
42
+ ```
43
+
44
+ #### Binding dependencies
45
+
46
+ You can bind values, functions, or factories:
47
+
48
+ 1. Bind a value
49
+
50
+ ```js
51
+ const TOKEN = Symbol("token");
52
+
53
+ container.bind(TOKEN).toValue({ message: "Hello World" });
54
+
55
+ const result = await container.resolve(TOKEN); // result = "Hello World"
56
+ ```
57
+
58
+ 2. Bind a function
59
+
60
+ ```js
61
+ const FUNC_TOKEN = Symbol("func");
62
+
63
+ container.bind(FUNC_TOKEN).toFunction(() => console.log("Hello from function"));
64
+
65
+ const fn = await container.resolve(FUNC_TOKEN);
66
+ const result = fn(); // result = "Hello from function"
67
+ ```
68
+
69
+ 3. Bind a factory
70
+
71
+ Bind a factory, can with bellow options:
72
+
73
+ - scope
74
+ - singleton (default): One instance per container.
75
+ - transient: A new instance each time resolved.
76
+
77
+ - config is optional
78
+
79
+ ```js
80
+ const TOKEN = Symbol("token");
81
+
82
+ container.bind(TOKEN).toValue({ message: "Hello" });
83
+
84
+ const FACTORY_TOKEN = Symbol("factory");
85
+
86
+ container.bind(FACTORY_TOKEN).toFactory(
87
+ ({ resolver, config }) => {
88
+ const dep = resolver.resolve(TOKEN);
89
+ return `Factory resolved: ${dep.message} ${config.message}`;
90
+ },
91
+ { scope: "singleton", config: { message: "World." } },
92
+ );
93
+
94
+ const result = await container.resolve(FACTORY_TOKEN); // result = "Factory resolved: Hello world."
95
+ ```
96
+
97
+ 4. Circular dependencies
98
+
99
+ ```js
100
+ const LAZY_DEP = Symbol("lazyDep");
101
+ const CONSUMER = Symbol("consumer");
102
+
103
+ container.bind(LAZY_DEP).toValue({ data: "lazy data" });
104
+
105
+ container.bind(CONSUMER).toFactory(({ resolver }) => {
106
+ const lazy = resolver.lazyResolve(LAZY_DEP);
107
+
108
+ return {
109
+ getLazyData: () => lazy.value.data,
110
+ };
111
+ });
112
+
113
+ const consumer = await container.resolve(CONSUMER);
114
+ // consumer.getLazyData()).toBe("lazy data");
115
+ ```
116
+
117
+ ## License
118
+
119
+ MIT License (MIT). Please see [LICENSE](./LICENSE) for more information.
@@ -0,0 +1,42 @@
1
+ //#region src/types/index.d.ts
2
+ type Scope = "singleton" | "transient";
3
+ type BindingConfig = Record<string, unknown>;
4
+ //#endregion
5
+ //#region src/utils/index.d.ts
6
+ type Disposable = {
7
+ dispose: () => Promise<void> | void;
8
+ };
9
+ //#endregion
10
+ //#region src/container/index.d.ts
11
+ type Resolve = (name: symbol) => unknown;
12
+ type LazyResolve = <T = unknown>(name: symbol) => Readonly<{
13
+ value: T;
14
+ }>;
15
+ type Resolver = {
16
+ resolve: Resolve;
17
+ lazyResolve: LazyResolve;
18
+ };
19
+ type ToValue = (value: unknown) => void;
20
+ type ToFunction = (fn: (...args: unknown[]) => unknown) => void;
21
+ type ToFactory = (fn: ({
22
+ resolver,
23
+ config
24
+ }: {
25
+ resolver: Resolver;
26
+ config?: BindingConfig;
27
+ }) => unknown | Promise<unknown>, options?: {
28
+ scope?: Scope;
29
+ config?: BindingConfig;
30
+ }) => void;
31
+ type Container = {
32
+ bind: (name: symbol) => {
33
+ toValue: ToValue;
34
+ toFunction: ToFunction;
35
+ toFactory: ToFactory;
36
+ };
37
+ resolve: <T>(name: symbol) => Promise<T>;
38
+ lazyResolve: LazyResolve;
39
+ } & Disposable;
40
+ declare const createContainer: () => Container;
41
+ //#endregion
42
+ export { BindingConfig, Container, Scope, createContainer };
package/dist/index.js ADDED
@@ -0,0 +1,130 @@
1
+ //#region src/utils/index.ts
2
+ const isDisposable = (obj) => !!obj && typeof obj.dispose === "function";
3
+ const formatChain = (chain, current) => {
4
+ return (current ? [...chain, current] : chain).map(String).join(" -> ");
5
+ };
6
+
7
+ //#endregion
8
+ //#region src/container/index.ts
9
+ const createContainer = () => {
10
+ const result = _createContainer();
11
+ return {
12
+ bind: result.bind,
13
+ resolve: result.resolve,
14
+ lazyResolve: result.lazyResolve,
15
+ dispose: result.dispose
16
+ };
17
+ };
18
+ const _createContainer = (parent, item, constructing) => {
19
+ const bindings = parent?.bindings ?? /* @__PURE__ */ new Map();
20
+ const singletons = parent?.singletons ?? /* @__PURE__ */ new Map();
21
+ const currentConstructing = item ? [...constructing ?? parent?.constructing ?? [], item] : [];
22
+ const lazyResolveQueue = [];
23
+ const container = {};
24
+ const enqueueLazyResolve = (name) => {
25
+ return new Promise((resolve$1) => {
26
+ const lazy = (value) => {
27
+ resolve$1(value);
28
+ };
29
+ lazyResolveQueue.push({
30
+ name,
31
+ resolve: lazy
32
+ });
33
+ });
34
+ };
35
+ const dequeueLazyResolves = async () => {
36
+ for (const lazyResolve$1 of lazyResolveQueue) try {
37
+ lazyResolve$1.resolve(await resolveBinding(lazyResolve$1.name, []));
38
+ } catch (e) {
39
+ throw new Error(`Failed to resolve lazy resolver for name ${lazyResolve$1.name.toString()}: ${e instanceof Error ? e.message : String(e)}`);
40
+ }
41
+ };
42
+ const bind = (name) => {
43
+ const toValue = (value) => {
44
+ bindings.set(name, {
45
+ factory: () => value,
46
+ scope: "singleton"
47
+ });
48
+ };
49
+ const toFunction = (fn) => {
50
+ bindings.set(name, {
51
+ factory: () => fn,
52
+ scope: "singleton"
53
+ });
54
+ };
55
+ const toFactory = (fn, options) => {
56
+ bindings.set(name, {
57
+ factory: (resolve$1, lazyResolve$1) => {
58
+ return fn({
59
+ resolver: {
60
+ resolve: resolve$1,
61
+ lazyResolve: lazyResolve$1
62
+ },
63
+ config: options?.config
64
+ });
65
+ },
66
+ scope: options?.scope ?? "singleton",
67
+ config: options?.config
68
+ });
69
+ };
70
+ return {
71
+ toValue,
72
+ toFunction,
73
+ toFactory
74
+ };
75
+ };
76
+ const resolveBinding = async (name, constructing$1) => {
77
+ const binding = bindings.get(name);
78
+ if (!binding) throw new Error(`No binding found for name: ${name.toString()}`);
79
+ const isSingleton = binding.scope === "singleton";
80
+ if (isSingleton && singletons.has(name)) return singletons.get(name);
81
+ const child = _createContainer(container, name, constructing$1);
82
+ const result = await binding.factory(child.resolve, child.lazyResolve);
83
+ if (isSingleton) singletons.set(name, result);
84
+ await child.dequeueLazyResolves();
85
+ return result;
86
+ };
87
+ const resolve = async (name) => {
88
+ if (currentConstructing.includes(name)) throw new Error(`Circular dependency detected: ${formatChain(currentConstructing, name)}`);
89
+ return resolveBinding(name);
90
+ };
91
+ const lazyResolve = (name) => {
92
+ let value;
93
+ enqueueLazyResolve(name).then((resolved) => {
94
+ value = resolved;
95
+ });
96
+ return { get value() {
97
+ if (!value) throw new Error("Lazy binding is not yet resolved. Do not use lazy-resolved bindings before the binding construction ends.");
98
+ return value;
99
+ } };
100
+ };
101
+ const dispose = async () => {
102
+ const disposeErrors = [];
103
+ for (const [name, instance] of singletons) if (isDisposable(instance)) try {
104
+ await instance.dispose();
105
+ } catch (error) {
106
+ disposeErrors.push({
107
+ name,
108
+ error
109
+ });
110
+ }
111
+ if (disposeErrors.length > 0) {
112
+ const errorMessages = disposeErrors.map(({ name, error }) => `${name.toString()}: ${error instanceof Error ? error.message : String(error)}`).join("; ");
113
+ throw new Error(`Failed to dispose ${disposeErrors.length} binding(s): ${errorMessages}`);
114
+ }
115
+ };
116
+ Object.assign(container, {
117
+ bindings,
118
+ singletons,
119
+ constructing: currentConstructing,
120
+ dequeueLazyResolves,
121
+ bind,
122
+ resolve,
123
+ lazyResolve,
124
+ dispose
125
+ });
126
+ return container;
127
+ };
128
+
129
+ //#endregion
130
+ export { createContainer };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@resolid/di",
3
+ "type": "module",
4
+ "license": "MIT",
5
+ "private": false,
6
+ "sideEffects": false,
7
+ "version": "0.1.0",
8
+ "description": "The Resolid DI Container package.",
9
+ "publishConfig": {
10
+ "access": "public",
11
+ "provenance": true
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "dependencies": {},
23
+ "devDependencies": {},
24
+ "peerDependencies": {
25
+ "typescript": "^5.9.3"
26
+ },
27
+ "engines": {
28
+ "node": "^22.13.0 || >=24"
29
+ },
30
+ "homepage": "https://www.resolid.tech",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/resolid/framework.git",
34
+ "directory": "packages/di"
35
+ },
36
+ "scripts": {
37
+ "lint": "eslint .",
38
+ "build": "tsdown",
39
+ "test": "vitest run",
40
+ "bench": "vitest bench",
41
+ "typecheck": "tsc --noEmit"
42
+ }
43
+ }