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

@savafeed/module-manager

v2.0.3

Published

js modules solution

Downloads

569

Readme

Summary

IOC (Inversion of Control) - is a design principle in object-oriented programming where the control over the creation and relationships of objects is delegated to an external system or framework, rather than being handled by the object itself.

Key points:

  • Purpose of IOC : to reduce coupling between components in an application;
  • How it works : instead of creating dependencies internally, an object receives them from the outside;
  • Common implementation : through Dependency Injection (DI) — a technique where dependencies are provided to an object externally;

Base sample

An example of using all the features in one example is in the __tests__ folder (github link).

Start

NPM package:

npm i @savafeed/module-manager

or CDN:

https://unpkg.com/@savafeed/[email protected]/dist/index.cjs.js
https://unpkg.com/@savafeed/[email protected]/dist/index.esm.js
https://unpkg.com/@savafeed/[email protected]/dist/index.umd.js

Main dependency - reflect-metadata

Consists of

The library consists of:

  • Module:
    • @Module - class decorator;
  • Controller:
    • @Controller - class decorator;
  • Dependency:
    • @Injectable - class decorator;
    • @Inject - property decorator;
  • Container;

Controller and Dependency

The difference between a Controller and a Dependency is that a controller cannot be passed as a dependency and can be obtained from a Module and its methods can be used.

Also, a Controller belongs only to a Module at a time, while a Dependency belongs to the entire container.

Controller sample:

@Controller('app-co')
export class AppController {
  constructor(private appService: AppService) {}

  buildInfo() {
    const bInfo = this.appService.getBuildInfo();
    console.log('bInfo:', bInfo);
    return bInfo;
  }

  createPerson({ name }: { name: string }) {
    const personSchema = this.appService.personSchema();
    const person = personSchema.person;
    person.id = Math.floor(2 + Math.random() * (999 + 2 - 2));
    person.name = name;
    console.log('new person:', person);
    return person;
  }

  pricing() {
    const price = this.appService.getPrice();
    console.log('price:', price);
    return price;
  }
}

Dependency sample:

@Injectable()
export class AppRepository {
  constructor(@Inject(PRICE_SERVICE) private priceService: AbstractPriceService) {}

  mock() {
    return schema || {};
  }

  getPrice() {
    const currentCurrency = 'USD';
    const { price, currency } = this.priceService.getPrice(currentCurrency);
    return `${price} ${currency}`;
  }
}

Module

Module - is a logical block of an application that groups related components (classes, services, repositories, etc.) and defines how they interact with each other and with the outside world.

Modules are often used for:

  • Registering dependencies in the IoC container;
  • Configuring the application's behavior;
  • Structuring code into functional areas;

Module sample:

@Module({
  name: 'app-module',
  imports: [PricingModule],
  providers: [
    AppService,
    AppRepository,
    {
      token: 'CONFIG_TOKEN',
      useValue: { configVersion: 1 },
    },
  ],
  controllers: [AppController],
})
export class AppModule {}

Module isolation: imports and exports

Each module has its own provider scope: a provider (class or token) declared in one module is not visible to other modules by default. To share a provider across modules, the owning module must list it in exports, and the consuming module must list the owning module in imports:

export const PRICE_SERVICE = new InjectionToken<AbstractPriceService>('PRICE_SERVICE');

@Module({
  name: 'pricing-module',
  providers: [
    {
      token: PRICE_SERVICE,
      useClass: PriceService,
    },
  ],
  exports: [PRICE_SERVICE],
})
export class PricingModule {}
@Module({
  name: 'app-module',
  imports: [PricingModule], // makes PRICE_SERVICE resolvable here
  providers: [AppService, AppRepository],
  controllers: [AppController],
})
export class AppModule {}

A provider that exists in PricingModule.providers but is missing from PricingModule.exports stays private to PricingModule — importing it elsewhere and injecting that token throws a ProviderNotFoundError.

A token provider ({ token, ... }) is built with exactly one of:

  • useValue - a precomputed value, used as-is (including falsy values like 0/false/'');
  • useClass - a class, instantiated with new (no constructor arguments are resolved for it);
  • useFactory - a plain function, called with no arguments and used as-is (not called with new).

useClass and useFactory are deliberately separate - telling a class and a plain function apart reliably isn't possible without actually calling the value, so guessing isn't done. Put a class in useClass; put everything else in useFactory.

Typed tokens: InjectionToken and getProvider

A class used as a provider is already typed — @Inject isn't even needed for it, and moduleRef.getProvider(SomeClass) infers SomeClass automatically from its constructor.

A string token ('PRICE_SERVICE') carries no type at compile time, so @Inject('PRICE_SERVICE') and getProvider('PRICE_SERVICE') fall back to any. InjectionToken<T> is a typed drop-in replacement for string tokens — the type parameter exists only at compile time (purely for inference, nothing changes at runtime) and is compared by reference, so always import the same token value rather than re-creating it:

export const PRICE_SERVICE = new InjectionToken<AbstractPriceService>('PRICE_SERVICE');

@Injectable()
export class AppRepository {
  constructor(@Inject(PRICE_SERVICE) private priceService: AbstractPriceService) {}
}

const priceService = appModuleRef.getProvider(PRICE_SERVICE); // AbstractPriceService | undefined

Plain string tokens keep working everywhere (getProvider just returns any for them) — moving to InjectionToken<T> is opt-in, not a breaking change.

getProvider follows the same imports/exports visibility as regular injection: it returns a module's own providers plus anything exported by its imports, and undefined for anything that isn't visible to that module (it does not throw).

Errors

Misconfiguration fails fast instead of logging a warning and continuing with an undefined dependency. container.registerModule(...) (or the @Inject/class construction it triggers) throws one of the errors exported from the package:

  • ProviderNotFoundError - a class/token dependency isn't declared in the module, and isn't exported by any of its imports;
  • CircularDependencyError - two or more providers depend on each other transitively;
  • CircularImportError - two or more modules import each other transitively;
  • InvalidFactoryError - a useFactory threw while being called;
  • ModuleManagerError - base class for the above, plus other configuration errors (e.g. a class provider missing @Injectable()).
import { container, ProviderNotFoundError } from '@savafeed/module-manager';

try {
  container.registerModule(AppModule);
} catch (error) {
  if (error instanceof ProviderNotFoundError) {
    // a provider is missing from `providers`, or needs to be added to some module's `exports`
  }
}

Container

IoC Container - is a key component that implements the Inversion of Control principle in practice. It automates dependency management and the lifecycle of objects.

Example of registering a module in a container:

import { container } from '../src';
import { AppController } from './app-module/app.controller';
import { AppModule } from './app-module/app.module';
import { AppRepository } from './app-module/app.repository';

const appModuleRef = container.registerModule(AppModule);

const appController = container.getController<AppController>('app-co');

appController?.buildInfo();

appController?.createPerson({
  name: 'Yuu',
});

appController?.pricing();

console.log(container.getModuleByName('app-module'));

// registerModule returns the module's ModuleRef, with typed access to its providers
const appRepository = appModuleRef.getProvider(AppRepository); // AppRepository | undefined