npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@fozy-labs/simplest-di

v0.2.3

Published

Простейшая система внедрения зависимостей для React-приложений с поддержкой RxJS.

Readme

@fozy-labs/simplest-di

Простейшая система внедрения зависимостей (DI) для TypeScript с поддержкой React и RxJS.

npm version TypeScript RxJS

📦 Установка

npm install @fozy-labs/simplest-di

Peer-зависимости

| Зависимость | Версия | Обязательность | |---|---|---| | rxjs | ^7.0.0 | Обязательна | | react | ^19.0.0 | Опционально (только для React-интеграции) |

🚀 Быстрый старт

Базовый пример: Singleton-сервис

import { injectable, inject } from '@fozy-labs/simplest-di';

@injectable('SINGLETON')
class ApiClient {
    fetch(url: string) { /* ... */ }
}

// Первый вызов создаёт экземпляр
const client1 = inject(ApiClient);
// Второй вызов возвращает тот же экземпляр
const client2 = inject(ApiClient);
// client1 === client2 → true

Контракты через inject.define

import { inject, injectable } from '@fozy-labs/simplest-di';

interface ChatDataSource {
    fetchChatMessages(): Promise<string[]>;
}

@injectable('SINGLETON')
class CloudChatDataSource implements ChatDataSource {
    fetchChatMessages() {
        return Promise.resolve(['cloud']);
    }
}

const ChatDataSource = inject.define<ChatDataSource>('ChatDataSource');
ChatDataSource.bind(CloudChatDataSource);

const dataSource = inject(ChatDataSource);

Контрактом является сам объект, возвращённый inject.define(). Имя используется для диагностики, а bind() нужно вызвать до первого inject(contract). Если контракт не привязан, первый inject(contract) завершится ранней ошибкой.

React: DiScopeProvider

import { setupReactDi, DiScopeProvider, injectable, inject } from '@fozy-labs/simplest-di';

// Вызвать один раз при старте приложения
setupReactDi();

@injectable('SCOPED')
class AppStore {
    count = 0;
}

function Counter() {
    const store = inject(AppStore);
    return <div>{store.count}</div>;
}

function App() {
    return (
        <DiScopeProvider provide={[AppStore]}>
            <Counter />
        </DiScopeProvider>
    );
}

✨ Особенности

  • 🔄 Три режима жизненного циклаSINGLETON, TRANSIENT, SCOPED
  • 🧩 Контракты интерфейсовinject.define<T>(name) для выбора реализации без нового named export
  • 🌳 Иерархия скоупов — Родительские и дочерние скоупы с наследованием зависимостей
  • ⚛️ React-интеграцияDiScopeProvider для управления скоупами в React-дереве
  • 🎨 Stage 3 декораторы — TC39 декораторы, без experimentalDecorators
  • 🧪 Изоляция тестовresetRegistry() для очистки синглтон-состояния между тестами
  • 🔷 TypeScript-first — Полная типизация

📚 Документация

📖 API

Основные экспорты

| Экспорт | Тип | Описание | |---|---|---| | inject | Функция | Разрешение зависимости по токену (классу или контракту) | | inject.define | Метод | Создание контрактного токена с последующим bind() | | inject.provide | Метод | Явная регистрация зависимости в скоупе | | injectable | Декоратор | Помечает класс метаданными DI (lifetime, опции) | | Scope | Класс | Контейнер скоупа с иерархией и жизненным циклом | | resetRegistry | Функция | Очистка синглтон-реестра (для тестов) | | getInjectorName | Функция | Получение имени родительского инжектора (отладка) |

Классы ошибок

| Экспорт | Описание | |---|---| | CircularDependencyError | Обнаружена циклическая зависимость | | NonCompatibleParentError | SCOPED-зависимость в SINGLETON/TRANSIENT-контексте | | MustBeProvidedError | Зависимость с requireProvide: true не предоставлена |

React-интеграция

| Экспорт | Тип | Описание | |---|---|---| | setupReactDi | Функция | Инициализация DI для React (вызвать один раз) | | DiScopeProvider | React-компонент | Создаёт дочерний скоуп в React-дереве |

Типы

| Экспорт | Описание | |---|---| | InjectionLifetime | 'SINGLETON' \| 'TRANSIENT' \| 'SCOPED' | | InjectableOptions<T> | Опции для @injectable() (строка или объект) | | InjectableDetailedOptions<T> | Подробные опции: lifetime, onScopeInit, requireProvide | | InjectOptions<T> | Полный дескриптор для ручной регистрации | | InjectComputedOptions<T> | Нормализованная форма InjectOptions | | ProvideOptions<T> | Тип аргумента inject() / inject.provide() | | Injectable | Тип класса с метаданными @injectable() | | InjectableOptionsSymbol | Тип символа INJECTABLE_OPTIONS | | InjectingInstanceSymbol | Тип символа INJECTING_INSTANCE | | DiScopeProviderProps | Props для DiScopeProvider |

⚙️ Требования TypeScript

  • TypeScript ≥ 5.0
  • Не включать experimentalDecorators — библиотека использует TC39 Stage 3 декораторы
  • В tsconfig.json не нужны дополнительные настройки для декораторов