Compare commits

..

47 Commits

Author SHA1 Message Date
Sergey Penkovsky
1997110d92 chore(release): publish packages
- cherrypick@3.0.2
 - cherrypick_flutter@3.0.2
 - talker_cherrypick_logger@3.0.2
2025-10-20 17:31:40 +03:00
Sergey Penkovsky
0e600ca3a2 Merge pull request #25 from pese-git/issues/24
Issues/24
2025-10-20 17:28:01 +03:00
Sergey Penkovsky
25ae208ea1 fix(test): fix warning 2025-10-20 16:20:20 +03:00
Sergey Penkovsky
685c0ae49c fix(scope): properly clear binding and module references on dispose
Add memory leak/finalizer test to ensure no strong references remain after closing and disposing a scope.
2025-10-13 17:32:10 +03:00
Sergey Penkovsky
98d81b13a8 freeze deps 2025-10-13 17:26:39 +03:00
Sergey Penkovsky
c483d8c9e2 chore(release): publish packages
- cherrypick@3.0.1
 - cherrypick_annotations@3.0.1
 - cherrypick_flutter@3.0.1
 - cherrypick_generator@3.0.1
 - talker_cherrypick_logger@3.0.1
2025-09-09 13:47:11 +03:00
Sergey Penkovsky
a74cec645e Merge pull request #23 from pese-git/develop
Modified Files Summary

Configuration Files
- `.fvmrc` - FVM configuration
- `melos.yaml` - Melos workspace configuration
- Multiple `pubspec.yaml` files across packages

Documentation
- `README.md` (root and all packages) - Added Netlify badges
- Standardized CI/CD badge formatting

Dependency Management
- `pubspec.lock` files in example projects
- Dependency version adjustments

Code Quality
- `cherrypick_generator/analysis_options.yaml` - Updated analysis rules

Change Categories

📚 Documentation Improvements
- Added Netlify deployment status badges
- Enhanced project visibility
- Standardized badge formatting

⚙️ Maintenance Updates
- Development dependency version adjustments
- Environment constraint updates
- Improved cross-version compatibility

🛠️ Configuration Changes
- FVM configuration updates
- Melos workspace adjustments
- Analysis rules refinement

Impact Assessment

  Non-Breaking Changes
All modifications are backward compatible and include:
- Documentation enhancements
- Development environment improvements
- Dependency version updates
- Configuration refinements

🚀 Ready for Merge
The `develop` branch contains maintenance improvements that are:
-  Tested and stable
-  Non-breaking
-  Documentation-focused
-  Environment compatibility improvements
2025-09-09 13:46:23 +03:00
Sergey Penkovsky
082b5a6fb6 docs: add Netlify deployment status badge to README files
- Added Netlify deployment status badge to all package README files
- Standardized CI/CD badge formatting across the project
- Improves visibility of deployment status for documentation and examples
- Maintains consistent badge styling with existing Melos + FVM CI badge
2025-09-09 13:22:39 +03:00
Sergey Penkovsky
6c1ba523c6 chore(deps): adjust dev dependencies versions for broad compatibility
- Downgraded lints and test dependencies in multiple packages to ensure consistent analyzer and test ecosystem for Dart 3.2+.
- cherrypick_generator: Bump analyzer to ^7.7.1 and mockito to ^5.4.5 for patch updates and compatibility.
- cherrypick_flutter: Lowered flutter_lints and test to versions compatible with current stable toolchain.
- talker_cherrypick_logger: Lowered lints and test for alignment with mono-repo versions.
- melos.yaml: Added clean_all script for removing generated files and build artifacts repo-wide.

No functional code changes, only dependency and tooling improvements.
2025-09-09 12:45:12 +03:00
Sergey Penkovsky
651b2a26d6 chore(env): update Flutter and SDK constraints for compatibility
- Downgraded Flutter version in .fvmrc from 3.29.3 to 3.27.0 for compatibility with current dependencies
- Raised Dart SDK constraint in benchmark_di/pubspec.yaml from >=3.0.0 <4.0.0 to >=3.2.0 <4.0.0 to align with required package minimums

This change ensures environment compatibility for dependency resolution and build tools. No functional code changes.
2025-09-09 08:53:50 +03:00
Sergey Penkovsky
ec6e9aefd3 add banner 2025-09-09 00:47:00 +03:00
Sergey Penkovsky
751cb08064 Update approach descriptions in release notes
- Enhanced description of development approaches in both Russian and English versions
- Clarified distinction between programmatic (imperative) and declarative approaches
- Improved terminology consistency across both language versions
2025-09-09 00:46:09 +03:00
Sergey Penkovsky
b2fbce74b3 Code formatting fixes and dependency updates
- Fixed code formatting in benchmark_di CLI and adapter files
- Updated pubspec.lock files for benchmark_di, client_app, and postly examples
- Minor formatting improvements in disposable example
2025-09-08 17:22:49 +03:00
Sergey Penkovsky
81f14f5231 chore(release): publish packages
- cherrypick@3.0.0
 - cherrypick_annotations@3.0.0
 - cherrypick_flutter@3.0.0
 - cherrypick_generator@3.0.0
 - talker_cherrypick_logger@3.0.0
2025-09-08 17:17:50 +03:00
Sergey Penkovsky
a9101513e1 Add CI/CD badges to package README files
- Added Melos + FVM CI badges to all package README.md files
- Standardized badge formatting across all packages
- Improved project visibility with build status indicators
2025-09-08 17:16:51 +03:00
Sergey Penkovsky
f1cf1d054f Merge pull request #22 from pese-git/develop
# Release - CherryPick 3.x

> **CherryPick** — a lightweight and modular DI framework for Dart and Flutter that solves dependency injection through strong typing, code generation, and dependency control.

Version **3.x** was recently released with significant improvements.

## Main Changes in 3.x

* **O(1) dependency resolution** — thanks to Map indexing of bindings, performance does not depend on the size of the scope in the DI graph. This provides noticeable speedup in large projects.
* **Protection against circular dependencies** — checking works both within a single scope and across the entire hierarchy. When a cycle is detected, an informative exception with the dependency chain is thrown.
* **Integration with Talker** — all DI events (registration, creation, deletion, errors) are logged and can be displayed in the console or UI.
* **Automatic resource cleanup** — objects implementing `Disposable` are properly released when the scope is closed.
* **Stabilized declarative approach support** — annotations and code generation now work more reliably and are more convenient for use in projects.

## Resource Cleanup Example

```dart
class MyServiceWithSocket implements Disposable {
  @override
  Future<void> dispose() async {
    await socket.close();
    print('Socket closed!');
  }
}

class AppModule extends Module {
  @override
  void builder(Scope currentScope) {
    // singleton Api
    bind<MyServiceWithSocket>()
      .toProvide(() => MyServiceWithSocket())
      .singleton();
  }
}

scope.installModules([AppModule()]);

await CherryPick.closeRootScope(); // will wait for async dispose to complete
```

## Circular Dependency Checking

One of the new features in CherryPick 3.x is built-in cycle protection.
This helps catch situations early where services start depending on each other recursively.

### How to Enable Checking

For checking within a single scope:

```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```

For global checking across the entire hierarchy:

```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```

### How a Cycle Can Occur

Suppose we have two services that depend on each other:

```dart
class UserService {
  final OrderService orderService;
  UserService(this.orderService);
}

class OrderService {
  final UserService userService;
  OrderService(this.userService);
}
```

If we register them in the same scope:

```dart
class AppModule extends Module {
  @override
  void builder(Scope currentScope) {
    bind<UserService>().toProvide(() => UserService(scope.resolve()));
    bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
  }
}

final scope = CherryPick.openRootScope()
  ..enableCycleDetection()
  ..installModules([AppModule()]);

scope.resolve<UserService>();
```

Then when trying to resolve the dependency, an exception will be thrown:

```bash
 Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```

This way, the error is detected immediately, not "somewhere in runtime".

## Integration with Talker

CherryPick 3.x allows logging all DI events through [Talker](https://pub.dev/packages/talker): registration, object creation, deletion, and errors. This is convenient for debugging and diagnosing the dependency graph.

Connection example:

```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```

After this, DI events will be displayed in the console or UI:

```bash
┌───────────────────────────────────────────────────────────────
│ [info]    9:41:33  | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
│ [verbose] 9:41:33  | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```

In the log, you can see when scopes are created, which objects are registered and deleted, and catch errors and cycles in real time.


## Declarative Approach with Annotations

In addition to fully programmatic module descriptions, CherryPick supports **declarative DI style through annotations**.  
This allows minimizing manual code and automatically generating modules and mixins for automatic dependency injection.

Example of a declarative module:

```dart
@module()
abstract class AppModule extends Module {
  @provide()
  @singleton()
  Api api() => Api();

  @provide()
  Repo repo(Api api) => Repo(api);
}
````

After code generation, you can automatically inject dependencies into widgets or services:

```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
  @inject()
  late final Repo repo;

  MyScreen() {
    _inject(this);
  }
}
```

This way you can choose a convenient style: either **purely programmatic** or **declarative with annotations**.


## Who Might Find CherryPick Useful?

* Projects where it's important to guarantee **no cycles in the dependency graph**;
* Teams that want to **minimize manual DI code** and use a declarative style with annotations;
* Applications that require **automatic resource cleanup** (sockets, controllers, streams).

## Useful Links

* 📦 Package: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Code: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Documentation: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)
2025-09-08 17:04:48 +03:00
Sergey Penkovsky
f1ad1c42b5 Add ignore comment for deprecated member warning in binding.dart
- Added // ignore: deprecated_member_use_from_same_package comment
- This suppresses the warning about deprecated toProvideAsync method
- The comment is needed to maintain code quality while keeping backward compatibility
2025-09-08 16:50:45 +03:00
Sergey Penkovsky
be7f3e0392 Add release notes for CherryPick 3.x in both Russian and English
- Added comprehensive release notes for CherryPick 3.x
- Includes new features: O(1) dependency resolution, circular dependency protection
- Added Talker integration and automatic resource cleanup examples
- Added declarative approach with annotations section
- Both Russian and English versions included
2025-09-08 16:48:12 +03:00
Sergey Penkovsky
1b0615810d add presentation 2025-09-08 15:48:58 +03:00
Sergey Penkovsky
ef04f464da Update README.md 2025-09-08 15:40:09 +03:00
Sergey Penkovsky
6826f0f62c chore: synchronize package versions to 3.0.0-dev.X across all packages
- Unified MAJOR.MINOR versioning across all cherrypick ecosystem packages
- Updated cherrypick_annotations from 1.1.2-dev.2 to 3.0.0-dev.0
- Updated cherrypick_generator from 2.0.0-dev.2 to 3.0.0-dev.0
- Updated cherrypick_flutter from 1.1.3-dev.12 to 3.0.0-dev.1
- Updated documentation URLs from .dev to .netlify.app domain
- Maintained semantic versioning consistency for mono-repository management

This change ensures:
- Clear compatibility signaling between interdependent packages
- Simplified dependency management for consumers
- Consistent release versioning across the ecosystem
2025-09-08 15:06:19 +03:00
Sergey Penkovsky
9e517d047f chore(release): publish packages
- cherrypick@3.0.0-dev.13
 - cherrypick_flutter@3.0.0-dev.1
 - talker_cherrypick_logger@3.0.0-dev.1
2025-09-08 14:58:37 +03:00
Sergey Penkovsky
68a16aaa0c chore(release): publish packages
- talker_cherrypick_logger@3.0.0-dev.0
2025-09-08 14:57:29 +03:00
Sergey Penkovsky
679b2b87b7 chore(release): publish packages
- cherrypick_flutter@3.0.0-dev.0
2025-09-08 14:56:44 +03:00
Sergey Penkovsky
dbdae94673 chore(release): publish packages
- cherrypick_generator@3.0.0-dev.0
2025-09-08 14:55:04 +03:00
Sergey Penkovsky
4220967447 chore(release): publish packages
- cherrypick_annotations@3.0.0-dev.0
2025-09-08 14:53:10 +03:00
Sergey Penkovsky
dfe16fb10f chore: add yarn.lock file to track exact dependency versions 2025-09-08 14:42:46 +03:00
Sergey Penkovsky
ce2e770cbe docs: add important warnings about toInstance limitations and singleton behavior with params
- Add detailed warning about toInstance usage restrictions in module builders
- Explain singleton behavior with parameterized providers
- Clarify singleton() usage with toInstance() calls
- Update both English and Russian documentation versions
2025-09-08 14:07:48 +03:00
Sergey Penkovsky
7f5f5c4064 Merge pull request #21 from pese-git/website
Implement Website
2025-09-08 13:09:46 +03:00
Sergey Penkovsky
04ecb6d3a6 docs: update contributors list with GitHub links and add new contributor 2025-09-08 10:50:42 +03:00
Sergey Penkovsky
484061148d docs(binding,docs): clarify .singleton() with .toInstance() behavior in docs and API
- Add an explicit note and warning about the effect (or lack thereof) of calling `.singleton()` after `.toInstance()`:
  - in singleton() API doc-comment in binding.dart,
  - in README.md (after all binding usage patterns),
  - in full_tutorial_en.md and full_tutorial_ru.md.
- Explain that `.singleton()` has no effect on objects registered with `.toInstance()` — they are always single instance.
- Recommend `.singleton()` only for providers (toProvide/toProvideAsync), not direct instances.
- Improves clarity and prevents misuse/confusion for end users and future maintainers.
2025-09-08 10:46:20 +03:00
Sergey Penkovsky
b5b672765e docs(binding,docs): explain .singleton() + parametric provider behavior
- Add an explicit warning and usage examples for .singleton() combined with toProvideWithParams/toProvideAsyncWithParams:
  - in API doc-comment for singleton() in binding.dart,
  - in README.md and both full tutorials (EN/RU).
- Show correct and incorrect usage/pitfalls for parameterized providers and singleton.
- Help users avoid unintended singleton caching when using providers with parameters.
- Motivation: Prevent common confusion, make advanced DI scenarios safer and more obvious.
2025-09-08 10:18:19 +03:00
Sergey Penkovsky
482b7b0f5f docs(binding): clarify registration limitation in API doc
- Add an explicit warning and usage pattern examples to the toInstance() method doc-comment.
- Explain why resolving dependencies registered with toInstance inside the same Module.builder does not work.
- Reference safe and unsafe code samples for users navigating via IDE and API documentation.
2025-09-08 09:51:40 +03:00
Sergey Penkovsky
722a4d7980 docs(di): clarify 'toInstance' binding limitations in builder
- Add explicit note for users about the impossibility to use scope.resolve<T>() for just-to-be-registered types inside Module.builder when registering chained dependencies via toInstance.
- Show correct and incorrect usage patterns, functional and anti-pattern Dart examples in RU and EN full tutorials.
- Add the warning to the main README after core concept bindings block, improving discoverability for users starting with the library.
- Motivation: Prevent common misuse and hard-to-debug runtime errors for users who construct chains using toInstance/resolve inside the builder.
2025-09-08 09:23:00 +03:00
Sergey Penkovsky
16cd7199aa fix: fix examples 2025-09-05 09:37:24 +03:00
Sergey Penkovsky
846d55b124 feat(i18n): localize main page and enable i18n for homepage texts
- Updated index.tsx to use <Translate> and translate() for all main texts (title, subtitle, CTA, description) — now fully i18n-ready.
- Added new translation files (code.json, navbar.json, footer.json, etc.) to support Russian language for homepage and UI.
- Enables seamless language switching and correct translations of homepage elements.
2025-08-15 15:09:55 +03:00
Sergey Penkovsky
4f91d442af feat(i18n): localize FeatureList on homepage with <Translate> component
- Updated HomepageFeatures/index.tsx to use Docusaurus <Translate> component and unique ids for each feature title and description.
- Enables full i18n support for FeatureList (English & Russian).
- All feature texts are now ready for integration with Docusaurus translation workflow.
2025-08-15 14:40:33 +03:00
Sergey Penkovsky
d0c3870af6 feat(i18n): add Russian translation for docs intro page
- Added the initial Russian localizable version for the documentation introduction section ().
- Makes the first step of the CherryPick documentation available to Russian-speaking users.
- Ensures the /ru/docs/intro route is available and translated.
2025-08-15 10:10:37 +03:00
Sergey Penkovsky
c8292035b6 chore(docs): update editUrl for docs to project repository
- Changed docs.editUrl in docusaurus.config.ts to point to the actual GitHub repository (https://github.com/pese-git/cherrypick/tree/website/website).
- Allows users to edit documentation directly in this project's repo via the 'Edit this page' links.
2025-08-15 09:28:37 +03:00
Sergey Penkovsky
63ee3a9966 chore(config): remove blog preset block from docusaurus.config.ts
- Deleted all blog-related configuration from docusaurus.config.ts
- Intended for disabling or cleaning up unused blog features
2025-08-15 09:24:46 +03:00
Sergey Penkovsky
1f7e1d120d fix: update logo icon 2025-08-15 08:58:08 +03:00
Sergey Penkovsky
bcc5278c83 Fix Netlify SPA routing 2025-08-14 17:34:18 +03:00
Sergey Penkovsky
8863b10cbe feat: update dns 2025-08-14 16:57:25 +03:00
Sergey Penkovsky
e0a5ae66f6 fix(docs): comment out all broken links to allow successful Docusaurus build
- Commented out references to non-existent files and examples in both English and Russian documentation:
  - circular-dependency-detection.md
  - logging.md
  - documentation-links.md
  - using-annotations.md
- This fix prevents build failures caused by unresolved links in Docusaurus for both locales.
- All offending links are now non-blocking comments, allowing the site to build and deploy successfully until the related pages are added.
2025-08-14 16:24:57 +03:00
Sergey Penkovsky
9fee26c524 feat(i18n): add initial Russian localization for documentation and site config
- Added full Russian translations for all main documentation sections () into .
- Sections translated include: key features, installation, getting started, all core concepts, advanced features, API reference, FAQ, links, additional modules, contributing, and license.
- Updated  to ensure language switching is available and Russian locale is active.
- Each Russian file preserves the structure and formatting of the original Markdown, with machine-aided draft translation for immediate use.
- Lays the groundwork for UI language switching (en/ru) and enables further manual translation refinement and review.
2025-08-14 15:46:53 +03:00
Sergey Penkovsky
248bf4c8c5 feat(website): update home page to showcase CherryPick DI documentation
- Replaced the main action button text with 'Explore CherryPick Documentation 🍒' instead of 'Docusaurus Tutorial'.
- Updated the button link to target /docs/intro (main docs entry point).
- Changed <Layout> props:
  - Page title now uses project title only (siteConfig.title)
  - Added a CherryPick-related site description for better SEO and context.
- The homepage is now tailored to reflect CherryPick's purpose as a Dart & Flutter DI library instead of Docusaurus boilerplate.
2025-08-14 13:41:54 +03:00
Sergey Penkovsky
f4c4fe49a0 init: docusaurus website project 2025-08-13 18:19:25 +03:00
111 changed files with 30855 additions and 612 deletions

2
.fvmrc
View File

@@ -1,3 +1,3 @@
{
"flutter": "3.29.3"
"flutter": "3.27.0"
}

View File

@@ -3,6 +3,236 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2025-10-20
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.2`](#cherrypick---v302)
- [`cherrypick_flutter` - `v3.0.2`](#cherrypick_flutter---v302)
- [`talker_cherrypick_logger` - `v3.0.2`](#talker_cherrypick_logger---v302)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v3.0.2`
- `talker_cherrypick_logger` - `v3.0.2`
---
#### `cherrypick` - `v3.0.2`
- **FIX**(test): fix warning.
- **FIX**(scope): properly clear binding and module references on dispose.
## 2025-09-09
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.1`](#cherrypick---v301)
- [`cherrypick_annotations` - `v3.0.1`](#cherrypick_annotations---v301)
- [`cherrypick_flutter` - `v3.0.1`](#cherrypick_flutter---v301)
- [`cherrypick_generator` - `v3.0.1`](#cherrypick_generator---v301)
- [`talker_cherrypick_logger` - `v3.0.1`](#talker_cherrypick_logger---v301)
---
#### `cherrypick` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_annotations` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_flutter` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `cherrypick_generator` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
#### `talker_cherrypick_logger` - `v3.0.1`
- **DOCS**: add Netlify deployment status badge to README files.
## 2025-09-08
### Changes
---
Packages with breaking changes:
- [`cherrypick` - `v3.0.0`](#cherrypick---v300)
- [`cherrypick_annotations` - `v3.0.0`](#cherrypick_annotations---v300)
- [`cherrypick_flutter` - `v3.0.0`](#cherrypick_flutter---v300)
- [`cherrypick_generator` - `v3.0.0`](#cherrypick_generator---v300)
- [`talker_cherrypick_logger` - `v3.0.0`](#talker_cherrypick_logger---v300)
Packages with other changes:
- There are no other changes in this release.
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
- `cherrypick` - `v3.0.0`
- `cherrypick_annotations` - `v3.0.0`
- `cherrypick_flutter` - `v3.0.0`
- `cherrypick_generator` - `v3.0.0`
- `talker_cherrypick_logger` - `v3.0.0`
---
#### `cherrypick` - `v3.0.0`
#### `cherrypick_annotations` - `v3.0.0`
#### `cherrypick_flutter` - `v3.0.0`
#### `cherrypick_generator` - `v3.0.0`
#### `talker_cherrypick_logger` - `v3.0.0`
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick` - `v3.0.0-dev.13`](#cherrypick---v300-dev13)
- [`cherrypick_flutter` - `v3.0.0-dev.1`](#cherrypick_flutter---v300-dev1)
- [`talker_cherrypick_logger` - `v3.0.0-dev.1`](#talker_cherrypick_logger---v300-dev1)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `cherrypick_flutter` - `v3.0.0-dev.1`
- `talker_cherrypick_logger` - `v3.0.0-dev.1`
---
#### `cherrypick` - `v3.0.0-dev.13`
- **FIX**: fix examples.
- **DOCS**: update contributors list with GitHub links and add new contributor.
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
- **DOCS**(binding): clarify registration limitation in API doc.
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`talker_cherrypick_logger` - `v3.0.0-dev.0`](#talker_cherrypick_logger---v300-dev0)
---
#### `talker_cherrypick_logger` - `v3.0.0-dev.0`
- chore(talker_cherrypick_logger): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_flutter` - `v3.0.0-dev.0`](#cherrypick_flutter---v300-dev0)
---
#### `cherrypick_flutter` - `v3.0.0-dev.0`
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_generator` - `v3.0.0-dev.0`](#cherrypick_generator---v300-dev0)
---
#### `cherrypick_generator` - `v3.0.0-dev.0`
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
## 2025-09-08
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_annotations` - `v3.0.0-dev.0`](#cherrypick_annotations---v300-dev0)
---
#### `cherrypick_annotations` - `v3.0.0-dev.0`
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
## 2025-08-22
### Changes

View File

@@ -1,4 +1,5 @@
# Contributors
- Sergey Penkovsky <sergey.penkovsky@gmail.com>
- Klim Yaroshevich <yarashevich_kv@st.by>
- [Sergey Penkovsky](https://github.com/pese-git)
- [Klim Yaroshevich](https://github.com/KlimYarosh)
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick Workspace
CherryPick Workspace is a modular, open-source dependency injection ecosystem for Dart and Flutter, designed to offer lightweight, flexible, and scalable DI suitable for both backend and frontend (Flutter) development. This monorepo contains the main DI runtime library, annotation helpers, code generation for modular bindings, and seamless Flutter integration.
@@ -142,4 +147,4 @@ Please see:
---
**Happy Cherry Picking! 🍒**
**Happy Cherry Picking! 🍒**

View File

@@ -98,7 +98,7 @@ class BenchmarkCliRunner {
final di = RiverpodAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<
Map<String, rp.ProviderBase<Object?>>> (
Map<String, rp.ProviderBase<Object?>>>(
di,
chainCount: c,
nestingDepth: d,
@@ -111,7 +111,7 @@ class BenchmarkCliRunner {
);
} else {
final benchSync = UniversalChainBenchmark<
Map<String, rp.ProviderBase<Object?>>> (
Map<String, rp.ProviderBase<Object?>>>(
di,
chainCount: c,
nestingDepth: d,
@@ -127,7 +127,8 @@ class BenchmarkCliRunner {
} else if (config.di == 'yx_scope') {
final di = YxScopeAdapter();
if (scenario == UniversalScenario.asyncChain) {
final benchAsync = UniversalChainAsyncBenchmark<UniversalYxScopeContainer>(
final benchAsync =
UniversalChainAsyncBenchmark<UniversalYxScopeContainer>(
di,
chainCount: c,
nestingDepth: d,
@@ -139,7 +140,8 @@ class BenchmarkCliRunner {
repeats: config.repeats,
);
} else {
final benchSync = UniversalChainBenchmark<UniversalYxScopeContainer>(
final benchSync =
UniversalChainBenchmark<UniversalYxScopeContainer>(
di,
chainCount: c,
nestingDepth: d,

View File

@@ -20,77 +20,80 @@ class KiwiAdapter extends DIAdapter<KiwiContainer> {
registration(_container);
}
@override
Registration<KiwiContainer> universalRegistration<S extends Enum>({
required S scenario,
required int chainCount,
required int nestingDepth,
required UniversalBindingMode bindingMode,
}) {
if (scenario is UniversalScenario) {
if (scenario == UniversalScenario.asyncChain ||
bindingMode == UniversalBindingMode.asyncStrategy) {
throw UnsupportedError('Kiwi does not support async dependencies or async binding scenarios.');
}
return (container) {
switch (scenario) {
case UniversalScenario.asyncChain:
break;
case UniversalScenario.register:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(value: 'reg', dependency: null),
);
break;
case UniversalScenario.named:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl1'), name: 'impl1');
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl2'), name: 'impl2');
break;
case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
switch (bindingMode) {
case UniversalBindingMode.singletonStrategy:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.factoryStrategy:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.asyncStrategy:
// Не поддерживается
break;
@override
Registration<KiwiContainer> universalRegistration<S extends Enum>({
required S scenario,
required int chainCount,
required int nestingDepth,
required UniversalBindingMode bindingMode,
}) {
if (scenario is UniversalScenario) {
if (scenario == UniversalScenario.asyncChain ||
bindingMode == UniversalBindingMode.asyncStrategy) {
throw UnsupportedError(
'Kiwi does not support async dependencies or async binding scenarios.');
}
return (container) {
switch (scenario) {
case UniversalScenario.asyncChain:
break;
case UniversalScenario.register:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(value: 'reg', dependency: null),
);
break;
case UniversalScenario.named:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl1'),
name: 'impl1');
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(value: 'impl2'),
name: 'impl2');
break;
case UniversalScenario.chain:
for (int chain = 1; chain <= chainCount; chain++) {
for (int level = 1; level <= nestingDepth; level++) {
final prevDepName = '${chain}_${level - 1}';
final depName = '${chain}_$level';
switch (bindingMode) {
case UniversalBindingMode.singletonStrategy:
container.registerSingleton<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.factoryStrategy:
container.registerFactory<UniversalService>(
(c) => UniversalServiceImpl(
value: depName,
dependency: level > 1
? c.resolve<UniversalService>(prevDepName)
: null),
name: depName);
break;
case UniversalBindingMode.asyncStrategy:
// Не поддерживается
break;
}
}
}
}
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
case UniversalScenario.override:
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
}
};
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
case UniversalScenario.override:
final depName = '${chainCount}_$nestingDepth';
container.registerSingleton<UniversalService>(
(c) => c.resolve<UniversalService>(depName));
break;
}
};
}
throw UnsupportedError('Scenario $scenario not supported by KiwiAdapter');
}
throw UnsupportedError('Scenario $scenario not supported by KiwiAdapter');
}
@override
T resolve<T extends Object>({String? named}) {

View File

@@ -11,7 +11,8 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
late UniversalYxScopeContainer _scope;
@override
void setupDependencies(void Function(UniversalYxScopeContainer container) registration) {
void setupDependencies(
void Function(UniversalYxScopeContainer container) registration) {
_scope = UniversalYxScopeContainer();
registration(_scope);
}
@@ -45,7 +46,8 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
}
@override
Registration<UniversalYxScopeContainer> universalRegistration<S extends Enum>({
Registration<UniversalYxScopeContainer>
universalRegistration<S extends Enum>({
required S scenario,
required int chainCount,
required int nestingDepth,
@@ -112,7 +114,8 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
// handled at benchmark level
break;
}
if (scenario == UniversalScenario.chain || scenario == UniversalScenario.override) {
if (scenario == UniversalScenario.chain ||
scenario == UniversalScenario.override) {
final depName = '${chainCount}_$nestingDepth';
final lastDep = scope.dep<UniversalService>(
() => scope.depFor<UniversalService>(name: depName).get,
@@ -121,6 +124,7 @@ class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
}
};
}
throw UnsupportedError('Scenario $scenario not supported by YxScopeAdapter');
throw UnsupportedError(
'Scenario $scenario not supported by YxScopeAdapter');
}
}

View File

@@ -47,7 +47,7 @@ packages:
path: "../cherrypick"
relative: true
source: path
version: "3.0.0-dev.10"
version: "3.0.1"
collection:
dependency: transitive
description:

View File

@@ -4,7 +4,7 @@ publish_to: none
description: Universal benchmark for any DI library (cherrypick, get_it, and others)
environment:
sdk: '>=3.0.0 <4.0.0'
sdk: '>=3.2.0 <4.0.0'
dependencies:
cherrypick:

View File

@@ -1,3 +1,25 @@
## 3.0.2
- **FIX**(test): fix warning.
- **FIX**(scope): properly clear binding and module references on dispose.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.13
- **FIX**: fix examples.
- **DOCS**: update contributors list with GitHub links and add new contributor.
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
- **DOCS**(binding): clarify registration limitation in API doc.
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
## 3.0.0-dev.12
- **FIX**(scope): prevent concurrent modification in dispose().

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter.
@@ -102,31 +107,98 @@ A **Binding** acts as a configuration for how to create or provide a particular
#### Example
```dart
// Provide a direct instance
Binding<String>().toInstance("Hello world");
void builder(Scope scope) {
// Provide a direct instance
bind<String>().toInstance("Hello world");
// Provide an async direct instance
Binding<String>().toInstanceAsync(Future.value("Hello world"));
// Provide an async direct instance
bind<String>().toInstanceAsync(Future.value("Hello world"));
// Provide a lazy sync instance using a factory
Binding<String>().toProvide(() => "Hello world");
// Provide a lazy sync instance using a factory
bind<String>().toProvide(() => "Hello world");
// Provide a lazy async instance using a factory
Binding<String>().toProvideAsync(() async => "Hello async world");
// Provide a lazy async instance using a factory
bind<String>().toProvideAsync(() async => "Hello async world");
// Provide an instance with dynamic parameters (sync)
Binding<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (sync)
bind<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (async)
Binding<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Provide an instance with dynamic parameters (async)
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Named instance for retrieval by name
Binding<String>().toProvide(() => "Hello world").withName("my_string");
// Named instance for retrieval by name
bind<String>().toProvide(() => "Hello world").withName("my_string");
// Mark as singleton (only one instance within the scope)
Binding<String>().toProvide(() => "Hello world").singleton();
// Mark as singleton (only one instance within the scope)
bind<String>().toProvide(() => "Hello world").singleton();
}
```
> ⚠️ **Important note about using `toInstance` in Module `builder`:**
>
> If you register a chain of dependencies via `toInstance` inside a Module's `builder`, **do not** call `scope.resolve<T>()` for types that are also being registered in the same builder — at the moment they are registered.
>
> CherryPick initializes all bindings in the builder sequentially. Dependencies registered earlier are not yet available to `resolve` within the same builder execution. Trying to resolve just-registered types will result in an error (`Can't resolve dependency ...`).
>
> **How to do it right:**
> Manually construct the full dependency chain before calling `toInstance`:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies **only** to `toInstance`. With `toProvide`/`toProvideAsync` and similar providers, you can safely use `scope.resolve<T>()` inside the builder.
> ⚠️ **Special note regarding `.singleton()` with `toProvideWithParams()` / `toProvideAsyncWithParams()`:**
>
> If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters; every subsequent call (regardless of params) will return the same (cached) instance.
>
> **Example:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
> final a = scope.resolve<Service>(params: 1); // creates Service(1)
> final b = scope.resolve<Service>(params: 2); // returns Service(1)
> print(identical(a, b)); // true
> ```
>
> Use this pattern only when you want a “master” singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
> **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
### Module
A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope.
@@ -716,6 +788,14 @@ CherryPick provides a set of official add-on modules for advanced use cases and
---
## Contributors
- [Sergey Penkovsky](https://github.com/pese-git)
- [Klim Yaroshevich](https://github.com/KlimYarosh)
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)
---
## Contributing
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -141,6 +141,8 @@ void main() {
// Example 2: Without circular dependency detection (dangerous!)
print('2. Same code without circular dependency detection:');
try {
CherryPick.disableGlobalCrossScopeCycleDetection();
CherryPick.disableGlobalCycleDetection();
final scope = CherryPick.openRootScope();
// НЕ включаем обнаружение циклических зависимостей

View File

@@ -14,6 +14,14 @@ class MyService implements Disposable {
void doSomething() => print('Doing something...');
}
/// Пример модуля CherryPick
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}
void main() {
final scope = CherryPick.openRootScope();
@@ -30,11 +38,3 @@ void main() {
scope.dispose();
print('Service wasDisposed = ${service.wasDisposed}'); // true
}
/// Пример модуля CherryPick
class ModuleImpl extends Module {
@override
void builder(Scope scope) {
bind<MyService>().toProvide(() => MyService()).singleton();
}
}

View File

@@ -160,6 +160,39 @@ class Binding<T> {
/// ```dart
/// bind<Api>().toInstance(ApiMock());
/// ```
///
/// **Important limitation:**
/// If you register several dependencies via [toInstance] inside a [`Module.builder`],
/// do _not_ use `scope.resolve<T>()` to get objects that are also being registered during the _same_ builder execution.
/// All [toInstance] bindings are applied sequentially, and at the point of registration,
/// earlier objects are not yet available for resolve.
///
/// **Correct:**
/// ```dart
/// void builder(Scope scope) {
/// final a = A();
/// final b = B(a);
/// bind<A>().toInstance(a);
/// bind<B>().toInstance(b);
/// }
/// ```
/// **Wrong:**
/// ```dart
/// void builder(Scope scope) {
/// bind<A>().toInstance(A());
/// bind<B>().toInstance(B(scope.resolve<A>())); // Error! A is not available yet.
/// }
/// ```
/// **Wrong:**
/// ```dart
/// void builder(Scope scope) {
/// bind<A>().toProvide(() => A());
/// bind<B>().toInstance(B(scope.resolve<A>())); // Error! A is not available yet.
/// }
/// ```
/// This restriction only applies to [toInstance] bindings.
// ignore: deprecated_member_use_from_same_package
/// With [toProvide]/[toProvideAsync] you may freely use `scope.resolve<T>()` in the builder or provider function.
Binding<T> toInstance(Instance<T> value) {
_resolver = InstanceResolver<T>(value);
return this;
@@ -209,6 +242,30 @@ class Binding<T> {
/// ```dart
/// bind<Api>().toProvide(() => MyApi()).singleton();
/// ```
///
/// ---
///
/// ⚠️ **Special note: Behavior with parametric providers (`toProvideWithParams`/`toProvideAsyncWithParams`):**
///
/// If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters;
/// every subsequent call (regardless of params) will return the same (cached) instance.
///
/// Example:
/// ```dart
/// bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
/// final a = scope.resolve<Service>(params: 1); // creates Service(1)
/// final b = scope.resolve<Service>(params: 2); // returns Service(1)
/// print(identical(a, b)); // true
/// ```
///
/// Use this pattern only if you want a master singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
///
/// **Note about `.singleton()` and `.toInstance()`:**
///
/// Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior:
/// the object passed with `toInstance()` is already a single, constant instance that will always be returned for every resolve.
/// There is no need to use `.singleton()` with `toInstance()`. This call has no effect.
/// `.singleton()` is only meaningful with providers (`toProvide`, `toProvideAsync`, etc), to ensure only one instance is created by the factory.
Binding<T> singleton() {
_resolver?.toSingleton();
return this;

View File

@@ -498,5 +498,10 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
await d.dispose();
}
_disposables.clear();
// Clear modules
_modulesList.clear();
// Clear binding-index
_bindingResolvers.clear();
}
}

View File

@@ -1,8 +1,8 @@
name: cherrypick
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
version: 3.0.0-dev.12
homepage: https://cherrypick-di.dev/
documentation: https://cherrypick-di.dev/docs/intro
version: 3.0.2
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
@@ -13,14 +13,14 @@ topics:
- inversion-of-control
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: '>=3.2.0 <4.0.0'
dependencies:
meta: ^1.3.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.15
lints: ^4.0.0
test: ^1.25.6
mockito: ^5.0.6
mockito: ^5.4.4
melos: ^6.3.2

View File

@@ -0,0 +1,65 @@
import 'dart:async';
import 'package:cherrypick/cherrypick.dart';
import 'package:test/test.dart';
class HeavyService implements Disposable {
static int instanceCount = 0;
HeavyService() {
instanceCount++;
print('HeavyService created. Instance count: '
'\u001b[32m$instanceCount\u001b[0m');
}
@override
void dispose() {
instanceCount--;
print('HeavyService disposed. Instance count: '
'\u001b[31m$instanceCount\u001b[0m');
}
static final Finalizer<String> _finalizer = Finalizer((msg) {
print('GC FINALIZED HeavyService: $msg');
});
void registerFinalizer() => _finalizer.attach(this, toString(), detach: this);
}
class HeavyModule extends Module {
@override
void builder(Scope scope) {
bind<HeavyService>().toProvide(() => HeavyService());
}
}
void main() {
test('Binding memory is cleared after closing and reopening scope', () async {
final root = CherryPick.openRootScope();
for (int i = 0; i < 10; i++) {
print('\nIteration $i -------------------------------');
final subScope = root.openSubScope('leak-test-scope');
subScope.installModules([HeavyModule()]);
final service = subScope.resolve<HeavyService>();
expect(service, isNotNull);
await root.closeSubScope('leak-test-scope');
// Dart GC не сразу удаляет освобождённые объекты, добавляем паузу и вызываем GC.
await Future.delayed(const Duration(milliseconds: 200));
}
// Если dispose не вызвался, instanceCount > 0 => утечка.
expect(HeavyService.instanceCount, equals(0));
});
test('Service is finalized after scope is closed/cleaned', () async {
final root = CherryPick.openRootScope();
HeavyService? ref;
{
final sub = root.openSubScope('s');
sub.installModules([HeavyModule()]);
ref = sub.resolve<HeavyService>();
ref.registerFinalizer();
expect(HeavyService.instanceCount, 1);
await root.closeSubScope('s');
}
await Future.delayed(const Duration(seconds: 2));
expect(HeavyService.instanceCount, 0);
});
}

View File

@@ -1,3 +1,15 @@
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.0
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
## 1.1.2-dev.2
- **DOCS**(annotations): improve API documentation and usage example.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# cherrypick_annotations
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)

View File

@@ -1,9 +1,9 @@
name: cherrypick_annotations
description: |
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
version: 1.1.2-dev.2
homepage: https://cherrypick-di.dev/
documentation: https://cherrypick-di.dev/docs/intro
version: 3.0.1
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
@@ -14,7 +14,7 @@ topics:
- inversion-of-control
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: ">=3.6.0 <4.0.0"
# Add regular dependencies here.
dependencies:

View File

@@ -1,3 +1,23 @@
## 3.0.2
- Update a dependency to the latest release.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.1
- Update a dependency to the latest release.
## 3.0.0-dev.0
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
## 1.1.3-dev.12
- Update a dependency to the latest release.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# CherryPick Flutter
`cherrypick_flutter` offers a Flutter integration to access and manage dependency injection scopes using the `CherryPickProvider`. This setup facilitates accessing the root scope directly from the widget tree, providing a straightforward mechanism for dependences management within Flutter applications.

View File

@@ -1,8 +1,8 @@
name: cherrypick_flutter
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
version: 1.1.3-dev.12
homepage: https://cherrypick-di.dev/
documentation: https://cherrypick-di.dev/docs/intro
version: 3.0.2
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
@@ -13,19 +13,19 @@ topics:
- inversion-of-control
environment:
sdk: ">=3.5.2 <4.0.0"
flutter: ">=3.24.0"
sdk: '>=3.2.0 <4.0.0'
flutter: ">=3.16.0"
dependencies:
flutter:
sdk: flutter
cherrypick: ^3.0.0-dev.12
cherrypick: ^3.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
test: ^1.25.7
flutter_lints: ^4.0.0
test: ^1.25.6
melos: ^6.3.2
# For information on the generic Dart part of this file, see the

View File

@@ -1,3 +1,15 @@
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.0
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
## 2.0.0-dev.2
- Update a dependency to the latest release.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# Cherrypick Generator
**Cherrypick Generator** is a Dart code generation library for automating dependency injection (DI) boilerplate. It processes classes and fields annotated with [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations) and generates registration code for services, modules, and field injection for classes marked as `@injectable`. It supports advanced DI features such as scopes, named bindings, parameters, and asynchronous dependencies.

View File

@@ -31,4 +31,5 @@ include: package:lints/recommended.yaml
analyzer:
errors:
deprecated_member_use: ignore
deprecated_member_use: ignore
unintended_html_in_doc_comment: ignore

View File

@@ -2,9 +2,9 @@ name: cherrypick_generator
description: |
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
version: 2.0.0-dev.2
homepage: https://cherrypick-di.dev/
documentation: https://cherrypick-di.dev/docs/intro
version: 3.0.1
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
issue_tracker: https://github.com/pese-git/cherrypick/issues
topics:
@@ -15,20 +15,20 @@ topics:
- inversion-of-control
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: ">=3.6.0 <4.0.0"
# Add regular dependencies here.
dependencies:
cherrypick_annotations: ^1.1.2-dev.2
analyzer: ^7.0.0
cherrypick_annotations: ^3.0.1
analyzer: ^7.7.1
dart_style: ^3.0.0
build: ^2.4.1
source_gen: ^2.0.0
collection: ^1.18.0
dev_dependencies:
lints: ^4.0.0
mockito: ^5.4.4
lints: ^5.1.1
mockito: ^5.4.5
test: ^1.25.8
build_test: ^2.1.7
build_runner: ^2.4.13

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

View File

@@ -44,6 +44,46 @@ final setupFuture = loadEnvironment();
bind<Environment>().toInstanceAsync(setupFuture);
```
> ⚠️ **Important note about using toInstance in Module**
>
> If you register a chain of dependencies via `toInstance` inside the `builder` method of your `Module`, you must NOT call `scope.resolve<T>()` for a type that you have just bound—at this moment.
>
> CherryPick initializes all bindings inside `builder` sequentially: at the time of a new binding, not all other dependencies are registered yet in the DI container. If you try to use `scope.resolve<T>()` for an object you have just added in the same `builder`, it will result in an error (`Can't resolve dependency ...`).
>
> **Correct way:**
> Manually construct the entire object chain before registering:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Incorrect:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies only to `toInstance`. For providers (`toProvide`/`toProvideAsync`) and other strategies, you can freely use `scope.resolve<T>()` inside `builder`.
- **toProvide** — regular sync factory
- **toProvideAsync** — async factory (if you need to await a Future)
- **toProvideWithParams / toProvideAsyncWithParams** — factories with runtime parameters
@@ -67,6 +107,14 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — single instance per Scope lifetime
- By default, every resolve creates a new object
> **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
### Parameterized bindings
Allows you to create dependencies with runtime parameters, e.g., a service for a user with a given ID:
@@ -78,6 +126,26 @@ bind<UserService>().toProvideWithParams((userId) => UserService(userId));
final userService = scope.resolve<UserService>(params: '123');
```
> ⚠️ **Special note on using `.singleton()` after `toProvideWithParams` or `toProvideAsyncWithParams`:**
>
> If you declare a binding using `.toProvideWithParams((params) => ...)` (or its async variant) and then call `.singleton()`, the DI container will create and cache **only one instance** on the first `resolve` call—with the initial parameters. All subsequent calls to `resolve<T>(params: ...)` will return that same (cached) instance, **regardless of the new parameters**.
>
> **Example:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
>
> final a = scope.resolve<Service>(params: 1); // Creates Service(1)
> final b = scope.resolve<Service>(params: 2); // Returns Service(1)
> print(identical(a, b)); // true
> ```
>
> In other words:
> - The provider function receives parameters only on its first call,
> - After that, no matter what parameters are passed, the same instance is always returned.
>
> **Recommendation:**
> Use `.singleton()` with parameterized providers only if you are sure all parameters should always be identical, or you intentionally want a “master” instance. Otherwise, omit `.singleton()` to ensure a new object is constructed for every unique `params` value.
---
## Scope management: dependency hierarchy

View File

@@ -45,6 +45,48 @@ bind<Environment>().toInstanceAsync(setupFuture);
```
> ⚠️ **Важное примечание по использованию toInstance в Module**
>
> Если вы регистрируете цепочку зависимостей через `toInstance` внутри метода `builder` вашего `Module`, нельзя в это же время вызывать `scope.resolve<T>()` для только что объявленного типа.
>
> CherryPick инициализирует биндинги последовательно внутри builder: в этот момент ещё не все зависимости зарегистрированы в DI-контейнере. Попытка воспользоваться `scope.resolve<T>()` для только что добавленного объекта приведёт к ошибке (`Can't resolve dependency ...`).
>
> **Как правильно:**
> Складывайте всю цепочку вручную до регистрации:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Ошибка! В этот момент A ещё не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Ошибка! В этот момент A ещё не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Примечание:** Это ограничение касается только `toInstance`. Для провайдеров (`toProvide`/`toProvideAsync`) и других стратегий вы можете использовать `scope.resolve<T>()` внутри builder без ограничений.
- **toProvide** — обычная синхронная фабрика.
- **toProvideAsync** — асинхронная фабрика (например, если нужно дожидаться Future).
- **toProvideWithParams / toProvideAsyncWithParams** — фабрики с параметрами.
@@ -68,6 +110,15 @@ final api = scope.resolve<ApiClient>(named: 'mock');
- `.singleton()` — один инстанс на всё время жизни Scope.
- По умолчанию каждый resolve создаёт новый объект.
> **Примечание о `.singleton()` и `.toInstance()`:**
>
> Вызов `.singleton()` после `.toInstance()` не изменяет поведения биндинга: объект, переданный через `toInstance()`, и так всегда будет "единственным" (single instance), возвращаемым при каждом resolve.
>
> Применять `.singleton()` к уже существующему объекту нет необходимости — этот вызов ничего не меняет.
>
> `.singleton()` нужен только для провайдеров (например, `toProvide`/`toProvideAsync`), чтобы зафиксировать единственный экземпляр, создаваемый фабрикой.
### Параметрические биндинги
Позволяют создавать зависимости с runtime-параметрами — например, сервис для пользователя с ID:
@@ -79,6 +130,26 @@ bind<UserService>().toProvideWithParams((userId) => UserService(userId));
final userService = scope.resolve<UserService>(params: '123');
```
> ⚠️ **Особенности использования `.singleton()` после `toProvideWithParams` или `toProvideAsyncWithParams`:**
>
> Если вы объявляете биндинг через `.toProvideWithParams((params) => ...)` (или асинхронный вариант) и затем вызываете `.singleton()`, DI-контейнер создаст и закэширует **только один экземпляр** при первом вызове `resolve` — с первыми переданными параметрами. Все последующие вызовы `resolve<T>(params: ...)` вернут этот же (кэшированный) объект **независимо от новых параметров**.
>
> **Пример:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
>
> final a = scope.resolve<Service>(params: 1); // Создаётся Service(1)
> final b = scope.resolve<Service>(params: 2); // Возвращается уже Service(1)
> print(identical(a, b)); // true
> ```
>
> То есть:
> - параметры работают только для первого вызова,
> - дальше всегда возвращается экземпляр, созданный при первом обращении.
>
> **Рекомендация:**
> Используйте `.singleton()` совместно с провайдерами с параметрами только тогда, когда вы точно уверены, что все параметры всегда должны совпадать, или нужны именно “мастер”-экземпляры. В противном случае не используйте `.singleton()`, чтобы каждый вызов с новыми parameters создавал новый объект.
---
## Управление Scope'ами: иерархия зависимостей

View File

@@ -0,0 +1,178 @@
# Release - CherryPick 3.x
> **CherryPick** — a lightweight and modular DI framework for Dart and Flutter that solves dependency injection through strong typing, code generation, and dependency control.
Version **3.x** was recently released with significant improvements.
## Main Changes in 3.x
* **O(1) dependency resolution** — thanks to Map indexing of bindings, performance does not depend on the size of the scope in the DI graph. This provides noticeable speedup in large projects.
* **Protection against circular dependencies** — checking works both within a single scope and across the entire hierarchy. When a cycle is detected, an informative exception with the dependency chain is thrown.
* **Integration with Talker** — all DI events (registration, creation, deletion, errors) are logged and can be displayed in the console or UI.
* **Automatic resource cleanup** — objects implementing `Disposable` are properly released when the scope is closed.
* **Stabilized declarative approach support** — annotations and code generation now work more reliably and are more convenient for use in projects.
## Resource Cleanup Example
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket closed!');
}
}
class AppModule extends Module {
@override
void builder(Scope currentScope) {
// singleton Api
bind<MyServiceWithSocket>()
.toProvide(() => MyServiceWithSocket())
.singleton();
}
}
scope.installModules([AppModule()]);
await CherryPick.closeRootScope(); // will wait for async dispose to complete
```
## Circular Dependency Checking
One of the new features in CherryPick 3.x is built-in cycle protection.
This helps catch situations early where services start depending on each other recursively.
### How to Enable Checking
For checking within a single scope:
```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
For global checking across the entire hierarchy:
```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
### How a Cycle Can Occur
Suppose we have two services that depend on each other:
```dart
class UserService {
final OrderService orderService;
UserService(this.orderService);
}
class OrderService {
final UserService userService;
OrderService(this.userService);
}
```
If we register them in the same scope:
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(scope.resolve()));
bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
}
}
final scope = CherryPick.openRootScope()
..enableCycleDetection()
..installModules([AppModule()]);
scope.resolve<UserService>();
```
Then when trying to resolve the dependency, an exception will be thrown:
```bash
❌ Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
This way, the error is detected immediately, not "somewhere in runtime".
## Integration with Talker
CherryPick 3.x allows logging all DI events through [Talker](https://pub.dev/packages/talker): registration, object creation, deletion, and errors. This is convenient for debugging and diagnosing the dependency graph.
Connection example:
```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```
After this, DI events will be displayed in the console or UI:
```bash
┌───────────────────────────────────────────────────────────────
[info] 9:41:33 | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
[verbose] 9:41:33 | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```
In the log, you can see when scopes are created, which objects are registered and deleted, and catch errors and cycles in real time.
## Declarative Approach with Annotations
In addition to fully programmatic module descriptions, CherryPick supports **declarative DI style through annotations**.
This allows minimizing manual code and automatically generating modules and mixins for automatic dependency injection.
Example of a declarative module:
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
````
After code generation, you can automatically inject dependencies into widgets or services:
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
This way you can choose an approach in development: **programmatic (imperative) with explicit dependency registration** or **declarative through annotations**.
## Who Might Find CherryPick Useful?
* Projects where it's important to guarantee **no cycles in the dependency graph**;
* Teams that want to **minimize manual DI code** and use a declarative style with annotations;
* Applications that require **automatic resource cleanup** (sockets, controllers, streams).
## Useful Links
* 📦 Package: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Code: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Documentation: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)

View File

@@ -0,0 +1,180 @@
# Release - CherryPick 3.x
> **CherryPick** — лёгкий и модульный DI-фреймворк для Dart и Flutter, который решает задачу через строгую типизацию, кодогенерацию и контроль за зависимостями.
Недавно вышла версия **3.x**, где появились заметные улучшения.
## Основные изменения в 3.x
* **O(1) разрешение зависимостей** — благодаря Map-индексации биндингов производительность не зависит от размера скоупа в DI графе. На больших проектах это даёт ощутимое ускорение.
* **Защита от циклических зависимостей** — проверка работает как внутри одного scope, так и во всей иерархии. При обнаружении цикла выбрасывается информативное исключение с цепочкой зависимостей.
* **Интеграция с Talker** — все события DI (регистрация, создание, удаление, ошибки) логируются и могут выводиться в консоль или UI.
* **Автоматическая очистка ресурсов** — объекты, реализующие `Disposable`, корректно освобождаются при закрытии scope.
* **Стабилизирована поддержка декларативного подхода** — аннотации и генерация кода теперь работают надёжнее и удобнее для использования в проектах.
## Пример с очисткой ресурсов
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket закрыт!');
}
}
class AppModule extends Module {
@override
void builder(Scope currentScope) {
// singleton Api
bind<MyServiceWithSocket>()
.toProvide(() => MyServiceWithSocket())
.singleton();
}
}
scope.installModules([AppModule()]);
await CherryPick.closeRootScope(); // дождётся завершения async dispose
```
## Проверка циклических зависимостей
Одна из новинок CherryPick 3.x — встроенная защита от циклов.
Это помогает на раннем этапе отлавливать ситуации, когда сервисы начинают зависеть друг от друга рекурсивно.
### Как включить проверку
Для проверки внутри одного scope:
```dart
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
Для глобальной проверки во всей иерархии:
```dart
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
### Как может возникнуть цикл
Предположим, у нас есть два сервиса, которые зависят друг от друга:
```dart
class UserService {
final OrderService orderService;
UserService(this.orderService);
}
class OrderService {
final UserService userService;
OrderService(this.userService);
}
```
Если зарегистрировать их в одном scope:
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<UserService>().toProvide(() => UserService(scope.resolve());
bind<OrderService>().toProvide(() => OrderService(scope.resolve()));
}
}
final scope = CherryPick.openRootScope()
..enableCycleDetection()
..installModules([AppModule()]);
scope.resolve<UserService>();
```
То при попытке разрешить зависимость будет выброшено исключение:
```bash
❌ Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
Таким образом, ошибка выявляется сразу, а не «где-то в runtime».
## Интеграция с Talker
CherryPick 3.x позволяет логировать все события DI через [Talker](https://pub.dev/packages/talker): регистрацию, создание объектов, удаление и ошибки. Это удобно для отладки и диагностики графа зависимостей.
Пример подключения:
```dart
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(observer);
```
После этого в консоли или UI будут отображаться события DI:
```bash
┌───────────────────────────────────────────────────────────────
[info] 9:41:33 | [scope opened][CherryPick] scope_1757054493089_7072
└───────────────────────────────────────────────────────────────
┌───────────────────────────────────────────────────────────────
[verbose] 9:41:33 | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└───────────────────────────────────────────────────────────────
```
В логе можно увидеть, когда scope создаётся, какие объекты регистрируются и удаляются, а также отлавливать ошибки и циклы в реальном времени.
## Декларативный подход с аннотациями
Помимо полностью программного описания модулей, CherryPick поддерживает **декларативный стиль DI через аннотации**.
Это позволяет минимизировать ручной код и автоматически генерировать модули и mixin для автоподстановки зависимостей.
Пример декларативного модуля:
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
````
После генерации кода можно автоматически подтягивать зависимости в виджеты или сервисы:
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
Таким образом можно выбрать подход в разработке: **программный (императивный) с явной регистрацией зависимостей** или **декларативный через аннотации**.
## Кому может быть полезен CherryPick?
* проектам, где важно гарантировать **отсутствие циклов в графе зависимостей**;
* командам, которые хотят **минимизировать ручной DI-код** и использовать декларативный стиль с аннотациями;
* приложениям, где требуется **автоматическое освобождение ресурсов** (сокеты, контроллеры, потоки).
## Полезные ссылки
* 📦 Пакет: [pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
* 💻 Код: [github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
* 📖 Документация: [cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)

244
doc/presentation_ru.md Normal file
View File

@@ -0,0 +1,244 @@
---
marp: true
---
<!--
#backgroundImage: url('./doc/assets/image.png')
backgroundSize: cover
-->
# CherryPick 3.x
### Быстро. Безопасно. Просто.
Современный DI-framework для Dart и Flutter
Автор: Сергей Пеньковский
---
<!--
backgroundImage: none
-->
## Что такое CherryPick?
- Лёгкий и модульный framework для внедрения зависимостей (DI)
- Фокус: производительность, безопасность и лаконичный код
- Применяется во frontend, backend, CLI
---
## Эволюция: что нового в 3.x?
- Оптимизация скорости разрешения зависимостей
- Интеграция с Talker для наглядного логирования DI-событий
- Защита от циклических зависимостей на уровне ядра
- Полностью декларативное описание DI через аннотации и генерацию кода
- Автоматическая очистка ресурсов
---
## Быстро
* Мгновенное разрешение зависимостей
---
### Мгновенное разрешение зависимостей
- Операция resolve<T> теперь выполняется за O(1)
- Используется Map-индексация всех биндингов в каждом скоупе (в среднем ускорение в 10x+ на крупных графах)
- Производительность не зависит от размера приложения
---
## Безопасно
* Циклические зависимости больше не страшны
* Интеграция с Talker и расширенное логирование
---
### Циклические зависимости больше не страшны
- CherryPick 3.x автоматически выявляет циклы при разрешении зависимостей.
- Возможна проверка как внутри отдельного scope, так и во всём DI-графе (глобально).
---
#### Как включить проверку циклов
- Для защиты только внутри одного scope:
```dart
// 1. Для текущего scope (локальная проверка)
final scope = CherryPick.openRootScope();
scope.enableCycleDetection();
```
- Для защиты всей иерархии скоупов:
```dart
// 2. Для всей иерархии скоупов (глобальная проверка)
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openRootScope();
```
---
#### Пример обработки ошибки
При обнаружении цикла будет выброшено исключение с подробной трассировкой:
```dart
try {
scope.resolve<A>();
} on CircularDependencyException catch(e) {
print(e.dependencyChain);
}
```
```bash
=== Circular Dependency Detection Example ===
1. Attempt to create a scope with circular dependencies:
❌ Circular dependency detected: CircularDependencyException: Circular dependency detected for UserService
Dependency chain: UserService -> OrderService -> UserService
```
---
### Интеграция с Talker и расширенное логирование
- Всё, что происходит в DI: регистрация, создание, удаление, ошибки ― теперь логируется!
- Достаточно подключить observer:
```dart
final talker = Talker();
final talkerLogger = TalkerCherryPickObserver(talker);
CherryPick.setGlobalObserver(talkerLogger);
```
- Логи сразу видны в консоли, UI
```bash
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────
[info] | 9:41:33 89ms | [scope opened][CherryPick] scope_1757054493089_7072
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────
[verbose] | 9:41:33 90ms | [diagnostic][CherryPick] Scope created: scope_1757054493089_7072 {type: Scope, name: scope_1757054493089_7072, description: scope created}
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────
```
---
## Просто
* Декларативный DI
* Автоматическая очистка ресурсов
---
### Декларативный DI: аннотации и генерация кода
- Описывайте зависимости с помощью аннотаций
- Автоматически генерируется модуль DI и mixin для автоподстановки зависимостей
```dart
@module()
abstract class AppModule extends Module {
@provide()
@singleton()
Api api() => Api();
@provide()
Repo repo(Api api) => Repo(api);
}
```
Регистрация модуля
```dart
final scope = openRootScope()
..installModules([$AppModule()]);
```
---
### Field injection: минимум кода — максимум удобства
```dart
@injectable()
class MyScreen extends StatelessWidget with _$MyScreen {
@inject()
late final Repo repo;
MyScreen() {
_inject(this);
}
}
```
- После генерации mixin и вызова `screen._inject()` — зависимости готовы
- Сильная типизация, никаких ручных вызовов resolve
---
## Автоматическая очистка ресурсов
Автоматическая очистка ресурсов (контроллеры, потоки, сокеты, файлы и др.).
Если вы регистрируете объект, реализующий Disposable, через DI-контейнер, CherryPick вызовет его метод dispose() при закрытии скоупа.
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket закрыт!');
}
}
scope.installModules([
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
]);
await CherryPick.closeRootScope(); // дождётся завершения async очистки
```
---
## Почему это удобно?
### Сравнение с ручным DI
|| Аннотации | Ручной DI |
|:---|:-----------|:------------|
|Гибко|✅|✅|
|Кратко|✅|❌|
|Безопасно|✅|❌ (легко ошибиться)|
---
## CherryPick 3.x: ваш DI-фреймворк
- Быстрое разрешение зависимостей
- Гарантия безопасности и тестируемости
- Интеграция с логированием
- Максимально простой и декларативный код
---
<!--
#backgroundImage: url('./doc/assets/image.png')
backgroundSize: cover
-->
## Спасибо за внимание
---
## Вопросы?
- Try CherryPick - [https://pub.dev/packages/cherrypick](https://pub.dev/packages/cherrypick)
- Contributing — [https://github.com/pese-git/cherrypick](https://github.com/pese-git/cherrypick)
- Документация и примеры — [https://cherrypick-di.netlify.app](https://cherrypick-di.netlify.app/)
- Готов помочь — пишите, пробуйте, внедряйте!

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
url: "https://pub.dev"
source: hosted
version: "82.0.0"
version: "85.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0"
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
url: "https://pub.dev"
source: hosted
version: "7.4.5"
version: "7.7.1"
args:
dependency: transitive
description:
@@ -29,10 +29,10 @@ packages:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
url: "https://pub.dev"
source: hosted
version: "2.12.0"
version: "2.13.0"
boolean_selector:
dependency: transitive
description:
@@ -53,18 +53,18 @@ packages:
dependency: transitive
description:
name: build_config
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.2"
build_daemon:
dependency: transitive
description:
name: build_daemon
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9"
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.0.4"
build_resolvers:
dependency: transitive
description:
@@ -101,10 +101,10 @@ packages:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
url: "https://pub.dev"
source: hosted
version: "8.9.5"
version: "8.12.0"
characters:
dependency: transitive
description:
@@ -127,28 +127,28 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.9"
version: "3.0.1"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.2-dev.0"
version: "3.0.1"
cherrypick_flutter:
dependency: "direct main"
description:
path: "../../cherrypick_flutter"
relative: true
source: path
version: "1.1.3-dev.9"
version: "3.0.1"
cherrypick_generator:
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "2.0.0-dev.0"
version: "3.0.1"
clock:
dependency: transitive
description:
@@ -209,10 +209,10 @@ packages:
dependency: transitive
description:
name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.3"
file:
dependency: transitive
description:
@@ -275,10 +275,10 @@ packages:
dependency: transitive
description:
name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
http_multi_server:
dependency: transitive
description:
@@ -291,10 +291,10 @@ packages:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.1.2"
io:
dependency: transitive
description:
@@ -323,10 +323,10 @@ packages:
dependency: transitive
description:
name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
url: "https://pub.dev"
source: hosted
version: "10.0.8"
version: "10.0.9"
leak_tracker_flutter_testing:
dependency: transitive
description:
@@ -347,10 +347,10 @@ packages:
dependency: transitive
description:
name: lints
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "5.0.0"
version: "5.1.1"
logging:
dependency: transitive
description:
@@ -427,26 +427,26 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.4.2"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "3.0.0"
sky_engine:
dependency: transitive
description: flutter
@@ -544,18 +544,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
url: "https://pub.dev"
source: hosted
version: "14.3.1"
version: "15.0.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.3"
web:
dependency: transitive
description:

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: e55636ed79578b9abca5fecf9437947798f5ef7456308b5cb85720b793eac92f
sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f
url: "https://pub.dev"
source: hosted
version: "82.0.0"
version: "85.0.0"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "904ae5bb474d32c38fb9482e2d925d5454cda04ddd0e55d2e6826bc72f6ba8c0"
sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d"
url: "https://pub.dev"
source: hosted
version: "7.4.5"
version: "7.7.1"
ansi_styles:
dependency: transitive
description:
@@ -45,26 +45,26 @@ packages:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
url: "https://pub.dev"
source: hosted
version: "2.12.0"
version: "2.13.0"
auto_route:
dependency: "direct main"
description:
name: auto_route
sha256: "1d1bd908a1fec327719326d5d0791edd37f16caff6493c01003689fb03315ad7"
sha256: b8c036fa613a98a759cf0fdcba26e62f4985dcbff01a5e760ab411e8554bbaf0
url: "https://pub.dev"
source: hosted
version: "9.3.0+1"
version: "10.1.0+1"
auto_route_generator:
dependency: "direct main"
dependency: "direct dev"
description:
name: auto_route_generator
sha256: c2e359d8932986d4d1bcad7a428143f81384ce10fef8d4aa5bc29e1f83766a46
sha256: "8e622d26dc6be4bf496d47969e3e9ba555c3abcf2290da6abfa43cbd4f57fa52"
url: "https://pub.dev"
source: hosted
version: "9.3.1"
version: "10.0.1"
bloc:
dependency: transitive
description:
@@ -93,18 +93,18 @@ packages:
dependency: transitive
description:
name: build_config
sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1
sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.2"
build_daemon:
dependency: transitive
description:
name: build_daemon
sha256: "79b2aef6ac2ed00046867ed354c88778c9c0f029df8a20fe10b5436826721ef9"
sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.0.4"
build_resolvers:
dependency: transitive
description:
@@ -114,7 +114,7 @@ packages:
source: hosted
version: "2.4.4"
build_runner:
dependency: "direct main"
dependency: "direct dev"
description:
name: build_runner
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
@@ -141,10 +141,10 @@ packages:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d
url: "https://pub.dev"
source: hosted
version: "8.9.5"
version: "8.12.0"
characters:
dependency: transitive
description:
@@ -175,21 +175,21 @@ packages:
path: "../../cherrypick"
relative: true
source: path
version: "3.0.0-dev.9"
version: "3.0.1"
cherrypick_annotations:
dependency: "direct main"
description:
path: "../../cherrypick_annotations"
relative: true
source: path
version: "1.1.2-dev.0"
version: "3.0.1"
cherrypick_generator:
dependency: "direct main"
dependency: "direct dev"
description:
path: "../../cherrypick_generator"
relative: true
source: path
version: "2.0.0-dev.0"
version: "3.0.1"
cli_launcher:
dependency: transitive
description:
@@ -274,10 +274,10 @@ packages:
dependency: transitive
description:
name: dart_style
sha256: "5b236382b47ee411741447c1f1e111459c941ea1b3f2b540dde54c210a3662af"
sha256: "27eb0ae77836989a3bc541ce55595e8ceee0992807f14511552a898ddd0d88ac"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
version: "3.0.1"
dartz:
dependency: "direct main"
description:
@@ -290,10 +290,10 @@ packages:
dependency: "direct main"
description:
name: dio
sha256: "253a18bbd4851fecba42f7343a1df3a9a4c1d31a2c1b37e221086b4fa8c8dbc9"
sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9
url: "https://pub.dev"
source: hosted
version: "5.8.0+1"
version: "5.9.0"
dio_web_adapter:
dependency: transitive
description:
@@ -306,18 +306,18 @@ packages:
dependency: transitive
description:
name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
version: "1.3.3"
ffi:
dependency: transitive
description:
name: ffi
sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.1.3"
file:
dependency: transitive
description:
@@ -348,7 +348,7 @@ packages:
source: hosted
version: "9.1.1"
flutter_lints:
dependency: "direct main"
dependency: "direct dev"
description:
name: flutter_lints
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
@@ -356,7 +356,7 @@ packages:
source: hosted
version: "5.0.0"
flutter_test:
dependency: "direct main"
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
@@ -366,7 +366,7 @@ packages:
source: sdk
version: "0.0.0"
freezed:
dependency: "direct main"
dependency: "direct dev"
description:
name: freezed
sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c"
@@ -417,10 +417,10 @@ packages:
dependency: transitive
description:
name: http
sha256: "2c11f3f94c687ee9bad77c171151672986360b2b001d109814ee7140b2cf261b"
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
http_multi_server:
dependency: transitive
description:
@@ -433,10 +433,10 @@ packages:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
version: "4.1.2"
intl:
dependency: transitive
description:
@@ -470,7 +470,7 @@ packages:
source: hosted
version: "4.9.0"
json_serializable:
dependency: "direct main"
dependency: "direct dev"
description:
name: json_serializable
sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c
@@ -481,10 +481,10 @@ packages:
dependency: transitive
description:
name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
url: "https://pub.dev"
source: hosted
version: "10.0.8"
version: "10.0.9"
leak_tracker_flutter_testing:
dependency: transitive
description:
@@ -505,10 +505,10 @@ packages:
dependency: transitive
description:
name: lints
sha256: "3315600f3fb3b135be672bf4a178c55f274bebe368325ae18462c89ac1e3b413"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "5.0.0"
version: "5.1.1"
logging:
dependency: transitive
description:
@@ -697,10 +697,10 @@ packages:
dependency: transitive
description:
name: provider
sha256: "4abbd070a04e9ddc287673bf5a030c7ca8b685ff70218720abab8b092f53dd84"
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
url: "https://pub.dev"
source: hosted
version: "6.1.5"
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
@@ -721,58 +721,58 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "1.5.0"
retrofit:
dependency: "direct main"
description:
name: retrofit
sha256: c6cc9ad3374e6d07008343140a67afffaaa34cdf6bf08d4847d91417a99dcf45
sha256: "84d70114a5b6bae5f4c1302335f9cb610ebeb1b02023d5e7e87697aaff52926a"
url: "https://pub.dev"
source: hosted
version: "4.4.2"
version: "4.6.0"
retrofit_generator:
dependency: "direct main"
dependency: "direct dev"
description:
name: retrofit_generator
sha256: "65d28d3a7b4db485f1c73fee8ee32f552ef23ee4ecb68ba491f39d80b73bdcbf"
sha256: e48c5a7ac362621b74976c64c540500dc7a54b8b5b074616a96a4854a2e5bb5b
url: "https://pub.dev"
source: hosted
version: "9.2.0"
version: "9.6.0"
share_plus:
dependency: transitive
description:
name: share_plus
sha256: b2961506569e28948d75ec346c28775bb111986bb69dc6a20754a457e3d97fa0
sha256: d7dc0630a923883c6328ca31b89aa682bacbf2f8304162d29f7c6aaff03a27a1
url: "https://pub.dev"
source: hosted
version: "11.0.0"
version: "11.1.0"
share_plus_platform_interface:
dependency: transitive
description:
name: share_plus_platform_interface
sha256: "1032d392bc5d2095a77447a805aa3f804d2ae6a4d5eef5e6ebb3bd94c1bc19ef"
sha256: "88023e53a13429bd65d8e85e11a9b484f49d4c190abbd96c7932b74d6927cc9a"
url: "https://pub.dev"
source: hosted
version: "6.0.0"
version: "6.1.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.1"
version: "1.4.2"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "3.0.0"
sky_engine:
dependency: transitive
description: flutter
@@ -790,10 +790,10 @@ packages:
dependency: transitive
description:
name: source_helper
sha256: "86d247119aedce8e63f4751bd9626fc9613255935558447569ad42f9f5b48b3c"
sha256: a447acb083d3a5ef17f983dd36201aeea33fedadb3228fa831f2f0c92f0f3aca
url: "https://pub.dev"
source: hosted
version: "1.3.5"
version: "1.3.7"
source_span:
dependency: transitive
description:
@@ -846,49 +846,49 @@ packages:
dependency: transitive
description:
name: talker
sha256: "028a753874d98df39f210cb74f0ee09a0a95e28f8bc2dc975c3c328e24fde23d"
sha256: "2d742b54e5cda58b7d386cd2d95088c3429ef273b2a0869dec552fe02601367a"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_bloc_logger:
dependency: "direct main"
description:
name: talker_bloc_logger
sha256: cf1e3b1d70f9a47e061288f0d230ba0e04a0f6394629d5df1c7b0933b236e397
sha256: "7752ca8a0b2eba487c8c189ca2390ebfcdaa4f7b10eda27587e5067e4427e7cd"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_cherrypick_logger:
dependency: "direct main"
description:
path: "../../talker_cherrypick_logger"
relative: true
source: path
version: "1.1.0-dev.3"
version: "3.0.1"
talker_dio_logger:
dependency: "direct main"
description:
name: talker_dio_logger
sha256: dcf784f1841e248c270ef741f8a07ca9cf562c6424ee43fc6e598c4eb7f18238
sha256: "20cc3bc9820fa73040f23e27d5d86462e590ddf02c43d0a801c56bf5ecc68922"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_flutter:
dependency: "direct main"
description:
name: talker_flutter
sha256: "2cfee6661277d415a895b6258ecb0bf80d7b564e91ea7e769fc6d0f970a01c09"
sha256: d249fa16936a08fe5c4fb9e2b9b122fdcbaef6be9c4dcf61e448d0b76f3179f1
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
talker_logger:
dependency: transitive
description:
name: talker_logger
sha256: "778ec673f1b71a6516e5576ae8d90ea23bbbcf9f405a97cc30e8ccdc33e26d27"
sha256: "4f06d46db664c11cf4d629378da661f2c75aee629e3ef898dbc3cf44a0c41cd7"
url: "https://pub.dev"
source: hosted
version: "4.9.3"
version: "5.0.0"
term_glyph:
dependency: transitive
description:
@@ -973,18 +973,18 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
url: "https://pub.dev"
source: hosted
version: "14.3.1"
version: "15.0.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
version: "1.1.3"
web:
dependency: transitive
description:
@@ -1013,10 +1013,10 @@ packages:
dependency: transitive
description:
name: win32
sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba"
sha256: daf97c9d80197ed7b619040e86c8ab9a9dad285e7671ee7390f9180cc828a51e
url: "https://pub.dev"
source: hosted
version: "5.13.0"
version: "5.10.1"
xdg_directories:
dependency: transitive
description:
@@ -1050,5 +1050,5 @@ packages:
source: hosted
version: "2.2.2"
sdks:
dart: ">=3.7.0 <4.0.0"
dart: ">=3.7.0-0 <4.0.0"
flutter: ">=3.27.0"

View File

@@ -5,7 +5,7 @@ publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ^3.5.2
sdk: ">=3.6.0 <4.0.0"
dependencies:
@@ -22,32 +22,33 @@ dependencies:
freezed_annotation: ^2.4.4
dartz: ^0.10.1
flutter_bloc: ^9.1.1
auto_route: ^9.3.0+1
auto_route: ^10.1.0+1
cupertino_icons: ^1.0.8
talker_flutter: ^4.9.3
talker_flutter: ^5.0.0
talker_cherrypick_logger:
path: ../../talker_cherrypick_logger
talker_dio_logger: ^5.0.0
talker_bloc_logger: ^5.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^5.0.0
build_runner: 2.4.15
cherrypick_generator:
path: ../../cherrypick_generator
build_runner: 2.4.15
retrofit_generator: ^9.1.5
freezed: ^2.5.8
json_serializable: ^6.9.0
auto_route_generator: ^9.0.0
talker_dio_logger: ^4.9.3
talker_bloc_logger: ^4.9.3
retrofit_generator: ^9.1.5
auto_route_generator: ^10.0.1
freezed: ^2.5.8
melos: ^6.3.2
flutter:
uses-material-design: true
dev_dependencies:
melos: ^6.3.2

View File

@@ -13,6 +13,27 @@ packages:
- examples/postly
scripts:
clean_all:
run: |
melos clean
melos exec -- rm -rf lib/**.g.dart lib/generated/
description: |
Очищает build артефакты flutter и сгенерированный код во всех пакетах.
all:
steps:
- codegen
- analyze
- format
- test
description: Run all steps.
lint:all:
steps:
- analyze
- format
description: Run all static analysis checks.
analyze:
exec: dart analyze
@@ -20,11 +41,10 @@ scripts:
exec: dart format lib
test:
run: |
echo "Running Dart tests..."
melos exec --scope="cherrypick,cherrypick_annotations,cherrypick_generator" -- dart test --reporter=compact
echo "Running Flutter tests..."
melos exec --scope="cherrypick_flutter" -- flutter test --reporter=compact
steps:
- test:dart
- test:flutter
description: Run all tests.
test:dart:
description: "Run tests for Dart packages only"

View File

@@ -1,27 +1,6 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
_fe_analyzer_shared:
dependency: transitive
description:
name: _fe_analyzer_shared
sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab"
url: "https://pub.dev"
source: hosted
version: "76.0.0"
_macros:
dependency: transitive
description: dart
source: sdk
version: "0.3.3"
analyzer:
dependency: transitive
description:
name: analyzer
sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e"
url: "https://pub.dev"
source: hosted
version: "6.11.0"
ansi_styles:
dependency: transitive
description:
@@ -46,38 +25,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
build:
dependency: transitive
description:
name: build
sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
built_collection:
dependency: transitive
description:
name: built_collection
sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
built_value:
dependency: transitive
description:
name: built_value
sha256: ea90e81dc4a25a043d9bee692d20ed6d1c4a1662a28c03a96417446c093ed6b4
url: "https://pub.dev"
source: hosted
version: "8.9.5"
charcode:
dependency: transitive
description:
@@ -94,22 +41,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.3"
cli_config:
dependency: transitive
description:
name: cli_config
sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec
url: "https://pub.dev"
source: hosted
version: "0.2.0"
cli_launcher:
dependency: transitive
description:
name: cli_launcher
sha256: "5e7e0282b79e8642edd6510ee468ae2976d847a0a29b3916e85f5fa1bfe24005"
sha256: "67d89e0a1c07b103d1253f6b953a43d3f502ee36805c8cfc21196282c9ddf177"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
version: "0.3.2"
cli_util:
dependency: transitive
description:
@@ -126,14 +65,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_builder:
dependency: transitive
description:
name: code_builder
sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e"
url: "https://pub.dev"
source: hosted
version: "4.10.1"
collection:
dependency: transitive
description:
@@ -146,42 +77,10 @@ packages:
dependency: transitive
description:
name: conventional_commit
sha256: dec15ad1118f029c618651a4359eb9135d8b88f761aa24e4016d061cd45948f2
sha256: fad254feb6fb8eace2be18855176b0a4b97e0d50e416ff0fe590d5ba83735d34
url: "https://pub.dev"
source: hosted
version: "0.6.0+1"
convert:
dependency: transitive
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
url: "https://pub.dev"
source: hosted
version: "3.1.2"
coverage:
dependency: transitive
description:
name: coverage
sha256: "802bd084fb82e55df091ec8ad1553a7331b61c08251eef19a508b6f3f3a9858d"
url: "https://pub.dev"
source: hosted
version: "1.13.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
url: "https://pub.dev"
source: hosted
version: "3.0.6"
dart_style:
dependency: transitive
description:
name: dart_style
sha256: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab"
url: "https://pub.dev"
source: hosted
version: "2.3.7"
version: "0.6.1"
file:
dependency: transitive
description:
@@ -190,22 +89,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob:
dependency: transitive
description:
@@ -226,18 +109,10 @@ packages:
dependency: transitive
description:
name: http
sha256: fe7ab022b76f3034adc518fb6ea04a82387620e19977665ea18d30a1cf43442f
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
url: "https://pub.dev"
source: hosted
version: "1.3.0"
http_multi_server:
dependency: transitive
description:
name: http_multi_server
sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8
url: "https://pub.dev"
source: hosted
version: "3.2.2"
version: "1.5.0"
http_parser:
dependency: transitive
description:
@@ -262,14 +137,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.5"
js:
dependency: transitive
description:
name: js
sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf
url: "https://pub.dev"
source: hosted
version: "0.7.1"
json_annotation:
dependency: transitive
description:
@@ -282,34 +149,10 @@ packages:
dependency: "direct dev"
description:
name: lints
sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
url: "https://pub.dev"
source: hosted
version: "2.1.1"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
macros:
dependency: transitive
description:
name: macros
sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656"
url: "https://pub.dev"
source: hosted
version: "0.1.3-main.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
url: "https://pub.dev"
source: hosted
version: "0.12.17"
version: "5.1.1"
melos:
dependency: "direct dev"
description:
@@ -322,26 +165,10 @@ packages:
dependency: "direct main"
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
url: "https://pub.dev"
source: hosted
version: "1.16.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
mockito:
dependency: "direct dev"
description:
name: mockito
sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917"
url: "https://pub.dev"
source: hosted
version: "5.4.4"
version: "1.17.0"
mustache_template:
dependency: transitive
description:
@@ -350,22 +177,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
node_preamble:
dependency: transitive
description:
name: node_preamble
sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
package_config:
dependency: transitive
description:
name: package_config
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
url: "https://pub.dev"
source: hosted
version: "2.2.0"
path:
dependency: transitive
description:
@@ -394,10 +205,10 @@ packages:
dependency: transitive
description:
name: process
sha256: "107d8be718f120bbba9dcd1e95e3bd325b1b4a4f07db64154635ba03f2567a0d"
sha256: c6248e4526673988586e8c00bb22a49210c258dc91df5227d5da9748ecf79744
url: "https://pub.dev"
source: hosted
version: "5.0.3"
version: "5.0.5"
prompts:
dependency: transitive
description:
@@ -426,66 +237,10 @@ packages:
dependency: transitive
description:
name: pubspec_parse
sha256: "81876843eb50dc2e1e5b151792c9a985c5ed2536914115ed04e9c8528f6647b0"
url: "https://pub.dev"
source: hosted
version: "1.4.0"
shelf:
dependency: transitive
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
shelf_packages_handler:
dependency: transitive
description:
name: shelf_packages_handler
sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
shelf_static:
dependency: transitive
description:
name: shelf_static
sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3
url: "https://pub.dev"
source: hosted
version: "1.1.3"
shelf_web_socket:
dependency: transitive
description:
name: shelf_web_socket
sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925"
url: "https://pub.dev"
source: hosted
version: "3.0.0"
source_gen:
dependency: transitive
description:
name: source_gen
sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832"
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
source_map_stack_trace:
dependency: transitive
description:
name: source_map_stack_trace
sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b
url: "https://pub.dev"
source: hosted
version: "2.1.2"
source_maps:
dependency: transitive
description:
name: source_maps
sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812"
url: "https://pub.dev"
source: hosted
version: "0.10.13"
source_span:
dependency: transitive
description:
@@ -502,14 +257,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.12.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
@@ -526,30 +273,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test:
dependency: "direct dev"
description:
name: test
sha256: "301b213cd241ca982e9ba50266bd3f5bd1ea33f1455554c5abb85d1be0e2d87e"
url: "https://pub.dev"
source: hosted
version: "1.25.15"
test_api:
dependency: transitive
description:
name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
url: "https://pub.dev"
source: hosted
version: "0.7.4"
test_core:
dependency: transitive
description:
name: test_core
sha256: "84d17c3486c8dfdbe5e12a50c8ae176d15e2a771b96909a9442b40173649ccaa"
url: "https://pub.dev"
source: hosted
version: "0.6.8"
typed_data:
dependency: transitive
description:
@@ -558,22 +281,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
url: "https://pub.dev"
source: hosted
version: "15.0.0"
watcher:
dependency: transitive
description:
name: watcher
sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web:
dependency: transitive
description:
@@ -582,30 +289,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
web_socket:
dependency: transitive
description:
name: web_socket
sha256: bfe6f435f6ec49cb6c01da1e275ae4228719e59a6b067048c51e72d9d63bcc4b
url: "https://pub.dev"
source: hosted
version: "1.0.0"
web_socket_channel:
dependency: transitive
description:
name: web_socket_channel
sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webkit_inspection_protocol:
dependency: transitive
description:
name: webkit_inspection_protocol
sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572"
url: "https://pub.dev"
source: hosted
version: "1.2.1"
yaml:
dependency: transitive
description:
@@ -623,4 +306,4 @@ packages:
source: hosted
version: "2.2.2"
sdks:
dart: ">=3.5.2 <4.0.0"
dart: ">=3.6.0 <4.0.0"

View File

@@ -7,16 +7,11 @@ repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: ">=3.2.0 <4.0.0"
dependencies:
meta: ^1.3.0
dev_dependencies:
#pedantic: ^1.11.0
test: ^1.17.2
mockito: ^5.0.6
lints: ^2.1.0
lints: ^5.1.1
melos: ^6.3.2

View File

@@ -1,3 +1,23 @@
## 3.0.2
- Update a dependency to the latest release.
## 3.0.1
- **DOCS**: add Netlify deployment status badge to README files.
## 3.0.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 3.0.0-dev.1
- Update a dependency to the latest release.
## 3.0.0-dev.0
- chore(talker_cherrypick_logger): sync version with cherrypick 3.0.0-dev.12
## 1.1.0-dev.7
- Update a dependency to the latest release.

View File

@@ -1,3 +1,8 @@
[![Melos + FVM CI](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml/badge.svg)](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
[![Netlify Status](https://api.netlify.com/api/v1/badges/3c3e0f98-27a9-4dd4-9eab-4be0b96798b8/deploy-status)](https://app.netlify.com/projects/cherrypick-di/deploys)
---
# talker_cherrypick_logger
An integration package that allows you to log [CherryPick](https://github.com/pese-dot-work/cherrypick) Dependency Injection (DI) container events using the [Talker](https://pub.dev/packages/talker) logging system.

View File

@@ -1,8 +1,8 @@
name: talker_cherrypick_logger
description: A Talker logger integration for CherryPick DI to observe and log DI events and errors.
version: 1.1.0-dev.7
homepage: https://cherrypick-di.dev/
documentation: https://cherrypick-di.dev/docs/intro
version: 3.0.2
homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick
issue_tracker: https://github.com/pese-git/cherrypick/issues
@@ -13,14 +13,14 @@ topics:
- log
environment:
sdk: ">=3.5.2 <4.0.0"
sdk: '>=3.2.0 <4.0.0'
# Add regular dependencies here.
dependencies:
talker: ^4.9.3
cherrypick: ^3.0.0-dev.12
talker: ^5.0.0
cherrypick: ^3.0.2
dev_dependencies:
lints: ^5.0.0
test: ^1.24.0
lints: ^4.0.0
test: ^1.25.6

20
website/.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

41
website/README.md Normal file
View File

@@ -0,0 +1,41 @@
# Website
This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.
## Installation
```bash
yarn
```
## Local Development
```bash
yarn start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
## Build
```bash
yarn build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## Deployment
Using SSH:
```bash
USE_SSH=true yarn deploy
```
Not using SSH:
```bash
GIT_USER=<Your GitHub username> yarn deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

View File

@@ -0,0 +1,14 @@
---
sidebar_position: 9
---
# Additional Modules
CherryPick provides a set of official add-on modules for advanced use cases and specific platforms:
| Module name | Description |
|-------------|-------------|
| [**cherrypick_annotations**](https://pub.dev/packages/cherrypick_annotations) | Dart annotations for concise DI definitions and code generation. |
| [**cherrypick_generator**](https://pub.dev/packages/cherrypick_generator) | Code generator to produce DI bindings based on annotations. |
| [**cherrypick_flutter**](https://pub.dev/packages/cherrypick_flutter) | Flutter integration: DI provider widgets and helpers for Flutter. |
| [**talker_cherrypick_logger**](https://pub.dev/packages/talker_cherrypick_logger) | Advanced logger for CherryPick DI events and state. Provides seamless integration with [Talker](https://pub.dev/packages/talker) logger, enabling central and visual tracking of DI events, errors, and diagnostics in both UI and console. |

View File

@@ -0,0 +1,4 @@
{
"label": "Advanced Features",
"position": 6
}

View File

@@ -0,0 +1,71 @@
---
sidebar_position: 3
---
# Circular Dependency Detection
CherryPick can detect circular dependencies in your DI configuration, helping you avoid infinite loops and hard-to-debug errors.
## How to use:
### 1. Enable Cycle Detection for Development
**Local detection (within one scope):**
```dart
final scope = CherryPick.openSafeRootScope(); // Local detection enabled by default
// or, for an existing scope:
scope.enableCycleDetection();
```
**Global detection (across all scopes):**
```dart
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openGlobalSafeRootScope();
```
### 2. Error Example
If you declare mutually dependent services:
```dart
class A { A(B b); }
class B { B(A a); }
scope.installModules([
Module((bind) {
bind<A>().to((s) => A(s.resolve<B>()));
bind<B>().to((s) => B(s.resolve<A>()));
}),
]);
scope.resolve<A>(); // Throws CircularDependencyException
```
### 3. Typical Usage Pattern
- **Always enable detection** in debug and test environments for maximum safety.
- **Disable detection** in production for performance (after code is tested).
```dart
import 'package:flutter/foundation.dart';
void main() {
if (kDebugMode) {
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
}
runApp(MyApp());
}
```
### 4. Handling and Debugging Errors
On detection, `CircularDependencyException` is thrown with a readable dependency chain:
```dart
try {
scope.resolve<MyService>();
} on CircularDependencyException catch (e) {
print('Dependency chain: ${e.dependencyChain}');
}
```
<!-- **More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md) -->

View File

@@ -0,0 +1,45 @@
---
sidebar_position: 1
---
# Hierarchical Subscopes
CherryPick supports a hierarchical structure of scopes, allowing you to create complex and modular dependency graphs for advanced application architectures. Each subscope inherits from its parent, enabling context-specific overrides while still allowing access to global or shared services.
## Key Points
- **Subscopes** are child scopes that can be opened from any existing scope (including the root).
- Dependencies registered in a subscope override those from parent scopes when resolved.
- If a dependency is not found in the current subscope, the resolution process automatically searches parent scopes up the hierarchy.
- Subscopes can have their own modules, lifetime, and disposable objects.
- You can nest subscopes to any depth, modeling features, flows, or components independently.
## Example
```dart
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
// Open a hierarchical subscope for a feature or page
final userFeatureScope = rootScope.openSubScope('userFeature');
userFeatureScope.installModules([UserFeatureModule()]);
// Dependencies defined in UserFeatureModule will take precedence
final userService = userFeatureScope.resolve<UserService>();
// If not found in the subscope, lookup continues in the parent (rootScope)
final sharedService = userFeatureScope.resolve<SharedService>();
// You can nest subscopes
final dialogScope = userFeatureScope.openSubScope('dialog');
dialogScope.installModules([DialogModule()]);
final dialogManager = dialogScope.resolve<DialogManager>();
```
## Use Cases
- Isolate feature modules, flows, or screens with their own dependencies.
- Provide and override services for specific navigation stacks or platform-specific branches.
- Manage the lifetime and disposal of groups of dependencies independently (e.g., per-user, per-session, per-component).
**Tip:** Always close subscopes when they are no longer needed to release resources and trigger cleanup of Disposable dependencies.

View File

@@ -0,0 +1,63 @@
---
sidebar_position: 2
---
# Logging
CherryPick lets you log all dependency injection (DI) events and errors using a flexible observer mechanism.
## Custom Observers
You can pass any implementation of `CherryPickObserver` to your root scope or any sub-scope.
This allows centralized and extensible logging, which you can direct to print, files, visualization frameworks, external loggers, or systems like [Talker](https://pub.dev/packages/talker).
### Example: Printing All Events
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Use the built-in PrintCherryPickObserver for console logs
final observer = PrintCherryPickObserver();
final scope = CherryPick.openRootScope(observer: observer);
// All DI actions and errors will now be printed!
}
```
### Example: Advanced Logging with Talker
For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](https://pub.dev/packages/talker_cherrypick_logger):
<!-- For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](../talker_cherrypick_logger): -->
```dart
import 'package:cherrypick/cherrypick.dart';
import 'package:talker/talker.dart';
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
void main() {
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.openRootScope(observer: observer);
// All container events go to the Talker log system!
}
```
## Default Behavior
- By default, logging is silent (`SilentCherryPickObserver`) for production, with no output unless you supply an observer.
- You can configure observers **per scope** for isolated, test-specific, or feature-specific logging.
## Observer Capabilities
Events you can observe and log:
- Dependency registration
- Instance requests, creations, disposals
- Module installs/removals
- Scope opening/closing
- Cache hits/misses
- Cycle detection
- Diagnostics, warnings, errors
Just implement or extend `CherryPickObserver` and direct messages anywhere you want!
## When to Use
- Enable verbose logging and debugging in development or test builds.
- Route logs to your main log system or analytics.
- Hook into DI lifecycle for profiling or monitoring.

View File

@@ -0,0 +1,10 @@
---
sidebar_position: 4
---
# Performance Improvements
> **Performance Note:**
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()` and related methods are now O(1) operations, regardless of the number of modules or bindings in your scope. Previously, the library had to iterate over all modules and bindings to locate the requested dependency, which could impact performance as your project grew.
>
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.

View File

@@ -0,0 +1,7 @@
---
sidebar_position: 10
---
# Contributing
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -0,0 +1,4 @@
{
"label": "Core Concepts",
"position": 4
}

View File

@@ -0,0 +1,107 @@
---
sidebar_position: 1
---
# Binding
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
* Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
* Lazy providers (sync/async functions)
* Provider functions supporting dynamic parameters
* Named instances for resolving by string key
* Optional singleton lifecycle
#### Example
```dart
void builder(Scope scope) {
// Provide a direct instance
bind<String>().toInstance("Hello world");
// Provide an async direct instance
bind<String>().toInstanceAsync(Future.value("Hello world"));
// Provide a lazy sync instance using a factory
bind<String>().toProvide(() => "Hello world");
// Provide a lazy async instance using a factory
bind<String>().toProvideAsync(() async => "Hello async world");
// Provide an instance with dynamic parameters (sync)
bind<String>().toProvideWithParams((params) => "Hello $params");
// Provide an instance with dynamic parameters (async)
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Named instance for retrieval by name
bind<String>().toProvide(() => "Hello world").withName("my_string");
// Mark as singleton (only one instance within the scope)
bind<String>().toProvide(() => "Hello world").singleton();
}
```
> ⚠️ **Important note about using `toInstance` in Module `builder`:**
>
> If you register a chain of dependencies via `toInstance` inside a Module's `builder`, **do not** call `scope.resolve<T>()` for types that are also being registered in the same builder — at the moment they are registered.
>
> CherryPick initializes all bindings in the builder sequentially. Dependencies registered earlier are not yet available to `resolve` within the same builder execution. Trying to resolve just-registered types will result in an error (`Can't resolve dependency ...`).
>
> **How to do it right:**
> Manually construct the full dependency chain before calling `toInstance`:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Wrong:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Error! At this point, A is not registered yet.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Note:** This limitation applies **only** to `toInstance`. With `toProvide`/`toProvideAsync` and similar providers, you can safely use `scope.resolve<T>()` inside the builder.
> ⚠️ **Special note regarding `.singleton()` with `toProvideWithParams()` / `toProvideAsyncWithParams()`:**
>
> If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters; every subsequent call (regardless of params) will return the same (cached) instance.
>
> **Example:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
> final a = scope.resolve<Service>(params: 1); // creates Service(1)
> final b = scope.resolve<Service>(params: 2); // returns Service(1)
> print(identical(a, b)); // true
> ```
>
> Use this pattern only when you want a “master” singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
> **Note about `.singleton()` and `.toInstance()`:**
>
> Calling `.singleton()` after `.toInstance()` does **not** change the bindings behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
>
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
>
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.

View File

@@ -0,0 +1,52 @@
---
sidebar_position: 4
---
# Disposable
CherryPick can automatically clean up any dependency that implements the `Disposable` interface. This makes resource management (for controllers, streams, sockets, files, etc.) easy and reliable—especially when scopes or the app are shut down.
If you bind an object implementing `Disposable` as a singleton or provide it via the DI container, CherryPick will call its `dispose()` method when the scope is closed or cleaned up.
## Key Points
- Supports both synchronous and asynchronous cleanup (dispose may return `void` or `Future`).
- All `Disposable` instances from the current scope and subscopes will be disposed in the correct order.
- Prevents resource leaks and enforces robust cleanup.
- No manual wiring needed once your class implements `Disposable`.
## Minimal Sync Example
```dart
class CacheManager implements Disposable {
void dispose() {
cache.clear();
print('CacheManager disposed!');
}
}
final scope = CherryPick.openRootScope();
scope.installModules([
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
]);
// ...later
await CherryPick.closeRootScope(); // prints: CacheManager disposed!
```
## Async Example
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket closed!');
}
}
scope.installModules([
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
]);
await CherryPick.closeRootScope(); // awaits async disposal
```
**Tip:** Always call `await CherryPick.closeRootScope()` or `await scope.closeSubScope(key)` in your shutdown/teardown logic to ensure all resources are released automatically.

View File

@@ -0,0 +1,19 @@
---
sidebar_position: 2
---
# Module
A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope.
## Example
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello world!");
}
}
```

View File

@@ -0,0 +1,31 @@
---
sidebar_position: 3
---
# Scope
A **Scope** manages a tree of modules and dependency instances. Scopes can be nested into hierarchies (parent-child), supporting modular app composition and context-specific overrides.
You typically work with the root scope, but can also create named subscopes as needed.
## Example
```dart
// Open the main/root scope
final rootScope = CherryPick.openRootScope();
// Install a custom module
rootScope.installModules([AppModule()]);
// Resolve a dependency synchronously
final str = rootScope.resolve<String>();
// Resolve a dependency asynchronously
final result = await rootScope.resolveAsync<String>();
// Recommended: Close the root scope and release all resources
await CherryPick.closeRootScope();
// Alternatively, you may manually call dispose on any scope you manage individually
// await rootScope.dispose();
```

View File

@@ -0,0 +1,15 @@
---
sidebar_position: 4
---
# Dependency Resolution API
- `resolve<T>()` — Locates a dependency instance or throws if missing.
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
- `tryResolve<T>()` — Returns `null` if not found (sync).
- `tryResolveAsync<T>()` — Returns `null` async if not found.
Supports:
- Synchronous and asynchronous dependencies
- Named dependencies
- Provider functions with and without runtime parameters

View File

@@ -0,0 +1,7 @@
---
sidebar_position: 8
---
# Documentation Links
<!-- * Circular Dependency Detection [(En)](doc/cycle_detection.en.md)[(Ru)](doc/cycle_detection.ru.md) -->

View File

@@ -0,0 +1,124 @@
---
sidebar_position: 6
---
# Example Application
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
```dart
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:cherrypick/cherrypick.dart';
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
}
}
class FeatureModule extends Module {
final bool isMock;
FeatureModule({required this.isMock});
@override
void builder(Scope currentScope) {
// Async provider for DataRepository with named dependency selection
bind<DataRepository>()
.withName("networkRepo")
.toProvideAsync(() async {
final client = await Future.delayed(
Duration(milliseconds: 100),
() => currentScope.resolve<ApiClient>(
named: isMock ? "apiClientMock" : "apiClientImpl",
),
);
return NetworkDataRepository(client);
})
.singleton();
// Chained async provider for DataBloc
bind<DataBloc>().toProvideAsync(
() async {
final repo = await currentScope.resolveAsync<DataRepository>(
named: "networkRepo");
return DataBloc(repo);
},
);
}
}
void main() async {
final scope = CherryPick.openRootScope().installModules([AppModule()]);
final featureScope = scope.openSubScope("featureScope")
..installModules([FeatureModule(isMock: true)]);
final dataBloc = await featureScope.resolveAsync<DataBloc>();
dataBloc.data.listen(
(d) => print('Received data: $d'),
onError: (e) => print('Error: $e'),
onDone: () => print('DONE'),
);
await dataBloc.fetchData();
}
class DataBloc {
final DataRepository _dataRepository;
Stream<String> get data => _dataController.stream;
final StreamController<String> _dataController = StreamController.broadcast();
DataBloc(this._dataRepository);
Future<void> fetchData() async {
try {
_dataController.sink.add(await _dataRepository.getData());
} catch (e) {
_dataController.sink.addError(e);
}
}
void dispose() {
_dataController.close();
}
}
abstract class DataRepository {
Future<String> getData();
}
class NetworkDataRepository implements DataRepository {
final ApiClient _apiClient;
final _token = 'token';
NetworkDataRepository(this._apiClient);
@override
Future<String> getData() async =>
await _apiClient.sendRequest(
url: 'www.google.com',
token: _token,
requestBody: {'type': 'data'},
);
}
abstract class ApiClient {
Future sendRequest({@required String? url, String? token, Map? requestBody});
}
class ApiClientMock implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Local Data';
}
}
class ApiClientImpl implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Network data';
}
}
```

10
website/docs/faq.md Normal file
View File

@@ -0,0 +1,10 @@
---
sidebar_position: 7
---
# FAQ
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
**A:**
Yes! Even if none of your services currently implement `Disposable`, always use `await` when closing scopes. If you later add resource cleanup (by implementing `dispose()`), CherryPick will handle it automatically without you needing to change your scope cleanup code. This ensures resource management is future-proof, robust, and covers all application scenarios.

View File

@@ -0,0 +1,27 @@
---
sidebar_position: 3
---
# Getting Started
Here is a minimal example that registers and resolves a dependency:
```dart
import 'package:cherrypick/cherrypick.dart';
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello, CherryPick!");
}
}
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
final greeting = rootScope.resolve<String>();
print(greeting); // prints: Hello, CherryPick!
await CherryPick.closeRootScope();
```

View File

@@ -0,0 +1,18 @@
---
sidebar_position: 2
---
# Installation
Add to your `pubspec.yaml`:
```yaml
dependencies:
cherrypick: ^<latest_version>
```
Then run:
```shell
dart pub get
```

41
website/docs/intro.md Normal file
View File

@@ -0,0 +1,41 @@
---
sidebar_position: 1
---
# CherryPick — Dependency Injection for Dart & Flutter
Welcome to the documentation for **CherryPick**, a lightweight and flexible dependency injection library for Dart and Flutter.
---
## About CherryPick
CherryPick is a modular DI (Dependency Injection) toolkit designed for:
- Clean architecture
- Lightweight and intuitive API
- Powerful hierarchical scopes
- Fast synchronous & asynchronous injections
- Code generation and annotation-based configuration
Whether you build backend or Flutter apps, CherryPick will help you maintain clear and testable project structure with minimal boilerplate.
## Quick Links
- [Key Features](key-features.md)
- [Getting Started](getting-started.md)
- [Core Concepts](core-concepts/binding.md)
- [Advanced Features](advanced-features/hierarchical-subscopes.md)
- [Using Annotations](using-annotations.md)
- [FAQ](faq.md)
- [Example Application](example-application.md)
- [GitHub Repository](https://github.com/pese-git/cherrypick)
## Installation
See [Installation](installation.md) for instructions on adding CherryPick to your Dart/Flutter project.
---
CherryPick is open-source. Contributions and questions are welcome!
---

View File

@@ -0,0 +1,16 @@
---
sidebar_position: 1
---
# Key Features
- Main Scope and Named Subscopes
- Named Instance Binding and Resolution
- Asynchronous and Synchronous Providers
- Providers Supporting Runtime Parameters
- Singleton Lifecycle Management
- Modular and Hierarchical Composition
- Null-safe Resolution (tryResolve/tryResolveAsync)
- Circular Dependency Detection (Local and Global)
- Comprehensive logging of dependency injection state and actions
- Automatic resource cleanup for all registered Disposable dependencies

9
website/docs/license.md Normal file
View File

@@ -0,0 +1,9 @@
---
sidebar_position: 11
---
# License
Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
**Important:** Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for specific language governing permissions and limitations under the License.

View File

@@ -0,0 +1,133 @@
---
sidebar_position: 5
---
# Using Annotations & Code Generation
CherryPick provides best-in-class developer ergonomics and type safety through **Dart annotations** and code generation. This lets you dramatically reduce boilerplate: simply annotate your classes, fields, and modules, run the code generator, and enjoy auto-wired dependency injection!
## How It Works
1. **Annotate** your services, providers, and fields using `cherrypick_annotations`.
2. **Generate** code using `cherrypick_generator` with `build_runner`.
3. **Use** generated modules and mixins for fully automated DI (dependency injection).
---
## Supported Annotations
| Annotation | Target | Description |
|-------------------|---------------|--------------------------------------------------------------------------------|
| `@injectable()` | class | Enables automatic field injection for this class (mixin will be generated) |
| `@inject()` | field | Field will be injected using DI (works with @injectable classes) |
| `@module()` | class | Declares a DI module; its methods can provide services/providers |
| `@provide` | method | Registers as a DI provider method (may have dependencies as parameters) |
| `@instance` | method/class | Registers an instance (new object on each resolution, i.e. factory) |
| `@singleton` | method/class | Registers as a singleton (one instance per scope) |
| `@named` | field/param | Use named instance (bind/resolve by name or apply to field/param) |
| `@scope` | field/param | Inject or resolve from a specific named scope |
| `@params` | param | Marks method parameter as filled by user-supplied runtime params at resolution |
You can easily **combine** these annotations for advanced scenarios!
---
## Field Injection Example
```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@injectable()
class ProfilePage with _\$ProfilePage {
@inject()
late final AuthService auth;
@inject()
@scope('profile')
late final ProfileManager manager;
@inject()
@named('admin')
late final UserService adminUserService;
}
```
- After running build_runner, the mixin `_ProfilePage` will be generated for field injection.
- Call `myProfilePage.injectFields();` or use the mixin's auto-inject feature, and all dependencies will be set up for you.
## Module and Provider Example
```dart
@module()
abstract class AppModule {
@singleton
AuthService provideAuth(Api api) => AuthService(api);
@named('logging')
@provide
Future<Logger> provideLogger(@params Map<String, dynamic> args) async => ...;
}
```
- Mark class as `@module`, write provider methods.
- Use `@singleton`, `@named`, `@provide`, `@params` to control lifecycle, key names, and parameters.
- The generator will produce a class like `$AppModule` with the proper DI bindings.
## Usage Steps
1. **Add to your pubspec.yaml**:
```yaml
dependencies:
cherrypick: any
cherrypick_annotations: any
dev_dependencies:
cherrypick_generator: any
build_runner: any
```
2. **Annotate** your classes and modules as above.
3. **Run code generation:**
```shell
dart run build_runner build --delete-conflicting-outputs
# or in Flutter:
flutter pub run build_runner build --delete-conflicting-outputs
```
4. **Register modules and use auto-injection:**
```dart
final scope = CherryPick.openRootScope()
..installModules([\$AppModule()]);
final profile = ProfilePage();
profile.injectFields(); // injects all @inject fields
```
## Advanced: Parameters, Named Instances, and Scopes
- Use `@named` for key-based multi-implementation injection.
- Use `@scope` when dependencies live in a non-root scope.
- Use `@params` for runtime arguments passed during resolution.
---
## Troubleshooting & Tips
- After modifying DI-related code, always re-run `build_runner`.
- Do not manually edit `.g.dart` files—let the generator manage them.
- Errors in annotation usage (e.g., using `@singleton` on wrong target) are shown at build time.
---
## References
<!--
- [Full annotation reference (en)](doc/annotations_en.md)
- [cherrypick_annotations/README.md](../cherrypick_annotations/README.md)
- [cherrypick_generator/README.md](../cherrypick_generator/README.md)
- See the [`examples/postly`](../examples/postly) for a full working DI+annotations app.
-->

View File

@@ -0,0 +1,132 @@
import {themes as prismThemes} from 'prism-react-renderer';
import type {Config} from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
// This runs in Node.js - Don't use client-side code here (browser APIs, JSX...)
const config: Config = {
title: 'CherryPick',
tagline: 'CherryPick are cool',
favicon: 'img/favicon.ico',
// Future flags, see https://docusaurus.io/docs/api/docusaurus-config#future
future: {
v4: true, // Improve compatibility with the upcoming Docusaurus v4
},
// Set the production url of your site here
url: 'https://cherrypick-di.dev',
// Set the /<baseUrl>/ pathname under which your site is served
// For GitHub pages deployment, it is often '/<projectName>/'
baseUrl: '/',
// GitHub pages deployment config.
// If you aren't using GitHub pages, you don't need these.
organizationName: 'CherryPick', // Usually your GitHub org/user name.
projectName: 'CherryPick', // Usually your repo name.
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
// Even if you don't use internationalization, you can use this field to set
// useful metadata like html lang. For example, if your site is Chinese, you
// may want to replace "en" with "zh-Hans".
i18n: {
defaultLocale: 'en',
locales: ['en', 'ru'],
localeConfigs: {
en: { label: 'English' },
ru: { label: 'Русский' }
}
},
presets: [
[
'classic',
{
docs: {
sidebarPath: './sidebars.ts',
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl:
'https://github.com/pese-git/cherrypick/tree/website/website',
},
theme: {
customCss: './src/css/custom.css',
},
} satisfies Preset.Options,
],
],
themeConfig: {
// Replace with your project's social card
image: 'img/docusaurus-social-card.jpg',
navbar: {
title: 'CherryPick',
logo: {
alt: 'CherryPick Logo',
src: 'img/logo.svg',
},
items: [
{
type: 'docSidebar',
sidebarId: 'tutorialSidebar',
position: 'right',
label: 'Docs',
},
{
type: 'localeDropdown',
position: 'right',
},
{
href: 'https://github.com/pese-git/cherrypick',
label: 'GitHub',
position: 'right',
},
],
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{
label: 'Docs',
to: '/docs/intro',
},
],
},
{
title: 'Community',
items: [
{
label: 'Telegram',
href: 'https://t.me/+22IVT0vqXBg1NDdi',
},
],
},
{
title: 'More',
items: [
{
label: 'PubDev',
href: 'https://pub.dev/packages/cherrypick',
},
{
label: 'GitHub',
href: 'https://github.com/pese-git/cherrypick',
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} CherryPick, Inc. Built with Docusaurus.`,
},
prism: {
theme: prismThemes.github,
darkTheme: prismThemes.dracula,
},
} satisfies Preset.ThemeConfig,
};
export default config;

355
website/i18n/ru/code.json Normal file
View File

@@ -0,0 +1,355 @@
{
"feature.modular": {
"message": "Модульность и иерархия"
},
"feature.modular.desc": {
"message": "CherryPick поддерживает модульные DI-привязки и иерархию скоупов. Стройте масштабируемые приложения с чистой архитектурой."
},
"feature.syncAsync": {
"message": "Синхронный и асинхронный DI без рутины"
},
"feature.syncAsync.desc": {
"message": "Регистрируйте синхронные/асинхронные провайдеры, именованные и Singleton зависимости. Генерация кода по аннотациям полностью избавляет от ручной рутины."
},
"feature.dartFlutter": {
"message": "Для Dart и Flutter"
},
"feature.dartFlutter.desc": {
"message": "CherryPick одинаково хорош для backend, CLI и Flutter-приложений. Глубокая интеграция с Flutter, поддержка жизненонго цикла, удобное тестирование."
},
"homepage.title": {
"message": "CherryPick"
},
"homepage.subtitle": {
"message": "Модульный и быстрый DI для Dart & Flutter"
},
"homepage.cta": {
"message": "Читать документацию CherryPick 🍒"
},
"homepage.description": {
"message": "CherryPick: Модульный и быстрый dependency injection для Dart и Flutter. Легкий, мощный, интеграция за минуты."
},
"theme.ErrorPageContent.title": {
"message": "На странице произошёл сбой.",
"description": "The title of the fallback page when the page crashed"
},
"theme.BackToTopButton.buttonAriaLabel": {
"message": "Прокрутка к началу",
"description": "The ARIA label for the back to top button"
},
"theme.blog.archive.title": {
"message": "Архив",
"description": "The page & hero title of the blog archive page"
},
"theme.blog.archive.description": {
"message": "Архив",
"description": "The page & hero description of the blog archive page"
},
"theme.blog.paginator.navAriaLabel": {
"message": "Навигация по странице списка блогов",
"description": "The ARIA label for the blog pagination"
},
"theme.blog.paginator.newerEntries": {
"message": "Следующие записи",
"description": "The label used to navigate to the newer blog posts page (previous page)"
},
"theme.blog.paginator.olderEntries": {
"message": "Предыдущие записи",
"description": "The label used to navigate to the older blog posts page (next page)"
},
"theme.blog.post.paginator.navAriaLabel": {
"message": "Навигация по странице поста блога",
"description": "The ARIA label for the blog posts pagination"
},
"theme.blog.post.paginator.newerPost": {
"message": "Следующий пост",
"description": "The blog post button label to navigate to the newer/previous post"
},
"theme.blog.post.paginator.olderPost": {
"message": "Предыдущий пост",
"description": "The blog post button label to navigate to the older/next post"
},
"theme.tags.tagsPageLink": {
"message": "Посмотреть все теги",
"description": "The label of the link targeting the tag list page"
},
"theme.colorToggle.ariaLabel.mode.system": {
"message": "system mode",
"description": "The name for the system color mode"
},
"theme.colorToggle.ariaLabel.mode.light": {
"message": "Светлый режим",
"description": "The name for the light color mode"
},
"theme.colorToggle.ariaLabel.mode.dark": {
"message": "Тёмный режим",
"description": "The name for the dark color mode"
},
"theme.colorToggle.ariaLabel": {
"message": "Переключение между темным и светлым режимом (сейчас используется {mode})",
"description": "The ARIA label for the color mode toggle"
},
"theme.docs.breadcrumbs.navAriaLabel": {
"message": "Навигационная цепочка текущей страницы",
"description": "The ARIA label for the breadcrumbs"
},
"theme.docs.DocCard.categoryDescription.plurals": {
"message": "{count} элемент|{count} элемента|{count} элементов",
"description": "The default description for a category card in the generated index about how many items this category includes"
},
"theme.docs.paginator.navAriaLabel": {
"message": "Страница документа",
"description": "The ARIA label for the docs pagination"
},
"theme.docs.paginator.previous": {
"message": "Предыдущая страница",
"description": "The label used to navigate to the previous doc"
},
"theme.docs.paginator.next": {
"message": "Следующая страница",
"description": "The label used to navigate to the next doc"
},
"theme.docs.tagDocListPageTitle.nDocsTagged": {
"message": "Одна страница|{count} страницы|{count} страниц",
"description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
},
"theme.docs.tagDocListPageTitle": {
"message": "{nDocsTagged} с тегом \"{tagName}\"",
"description": "The title of the page for a docs tag"
},
"theme.docs.versionBadge.label": {
"message": "Версия: {versionLabel}"
},
"theme.docs.versions.unreleasedVersionLabel": {
"message": "Это документация для будущей версии {siteTitle} {versionLabel}.",
"description": "The label used to tell the user that he's browsing an unreleased doc version"
},
"theme.docs.versions.unmaintainedVersionLabel": {
"message": "Это документация {siteTitle} для версии {versionLabel}, которая уже не поддерживается.",
"description": "The label used to tell the user that he's browsing an unmaintained doc version"
},
"theme.docs.versions.latestVersionSuggestionLabel": {
"message": "Актуальная документация находится на странице {latestVersionLink} ({versionLabel}).",
"description": "The label used to tell the user to check the latest version"
},
"theme.docs.versions.latestVersionLinkLabel": {
"message": "последней версии",
"description": "The label used for the latest version suggestion link label"
},
"theme.common.editThisPage": {
"message": "Отредактировать эту страницу",
"description": "The link label to edit the current page"
},
"theme.common.headingLinkTitle": {
"message": "Прямая ссылка на {heading}",
"description": "Title for link to heading"
},
"theme.lastUpdated.atDate": {
"message": " {date}",
"description": "The words used to describe on which date a page has been last updated"
},
"theme.lastUpdated.byUser": {
"message": " от {user}",
"description": "The words used to describe by who the page has been last updated"
},
"theme.lastUpdated.lastUpdatedAtBy": {
"message": "Последнее обновление{atDate}{byUser}",
"description": "The sentence used to display when a page has been last updated, and by who"
},
"theme.navbar.mobileVersionsDropdown.label": {
"message": "Версии",
"description": "The label for the navbar versions dropdown on mobile view"
},
"theme.NotFound.title": {
"message": "Страница не найдена",
"description": "The title of the 404 page"
},
"theme.tags.tagsListLabel": {
"message": "Теги:",
"description": "The label alongside a tag list"
},
"theme.AnnouncementBar.closeButtonAriaLabel": {
"message": "Закрыть",
"description": "The ARIA label for close button of announcement bar"
},
"theme.admonition.caution": {
"message": "предупреждение",
"description": "The default label used for the Caution admonition (:::caution)"
},
"theme.admonition.danger": {
"message": "осторожно",
"description": "The default label used for the Danger admonition (:::danger)"
},
"theme.admonition.info": {
"message": "к сведению",
"description": "The default label used for the Info admonition (:::info)"
},
"theme.admonition.note": {
"message": "примечание",
"description": "The default label used for the Note admonition (:::note)"
},
"theme.admonition.tip": {
"message": "подсказка",
"description": "The default label used for the Tip admonition (:::tip)"
},
"theme.admonition.warning": {
"message": "warning",
"description": "The default label used for the Warning admonition (:::warning)"
},
"theme.blog.sidebar.navAriaLabel": {
"message": "Навигация по последним постам в блоге",
"description": "The ARIA label for recent posts in the blog sidebar"
},
"theme.DocSidebarItem.expandCategoryAriaLabel": {
"message": "Expand sidebar category '{label}'",
"description": "The ARIA label to expand the sidebar category"
},
"theme.DocSidebarItem.collapseCategoryAriaLabel": {
"message": "Collapse sidebar category '{label}'",
"description": "The ARIA label to collapse the sidebar category"
},
"theme.NavBar.navAriaLabel": {
"message": "Main",
"description": "The ARIA label for the main navigation"
},
"theme.NotFound.p1": {
"message": "К сожалению, мы не смогли найти запрашиваемую вами страницу.",
"description": "The first paragraph of the 404 page"
},
"theme.NotFound.p2": {
"message": "Пожалуйста, обратитесь к владельцу сайта, с которого вы перешли на эту ссылку, чтобы сообщить ему, что ссылка не работает.",
"description": "The 2nd paragraph of the 404 page"
},
"theme.navbar.mobileLanguageDropdown.label": {
"message": "Языки",
"description": "The label for the mobile language switcher dropdown"
},
"theme.TOCCollapsible.toggleButtonLabel": {
"message": "Содержание этой страницы",
"description": "The label used by the button on the collapsible TOC component"
},
"theme.blog.post.readMore": {
"message": "Читать дальше",
"description": "The label used in blog post item excerpts to link to full blog posts"
},
"theme.blog.post.readMoreLabel": {
"message": "Подробнее о {title}",
"description": "The ARIA label for the link to full blog posts from excerpts"
},
"theme.blog.post.readingTime.plurals": {
"message": "{readingTime} мин. чтения|{readingTime} мин. чтения|{readingTime} мин. чтения",
"description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
},
"theme.CodeBlock.copy": {
"message": "Скопировать",
"description": "The copy button label on code blocks"
},
"theme.CodeBlock.copied": {
"message": "Скопировано",
"description": "The copied button label on code blocks"
},
"theme.CodeBlock.copyButtonAriaLabel": {
"message": "Скопировать в буфер обмена",
"description": "The ARIA label for copy code blocks button"
},
"theme.CodeBlock.wordWrapToggle": {
"message": "Переключить перенос по строкам",
"description": "The title attribute for toggle word wrapping button of code block lines"
},
"theme.docs.breadcrumbs.home": {
"message": "Главная страница",
"description": "The ARIA label for the home page in the breadcrumbs"
},
"theme.docs.sidebar.collapseButtonTitle": {
"message": "Свернуть сайдбар",
"description": "The title attribute for collapse button of doc sidebar"
},
"theme.docs.sidebar.collapseButtonAriaLabel": {
"message": "Свернуть сайдбар",
"description": "The title attribute for collapse button of doc sidebar"
},
"theme.docs.sidebar.navAriaLabel": {
"message": "Docs sidebar",
"description": "The ARIA label for the sidebar navigation"
},
"theme.docs.sidebar.closeSidebarButtonAriaLabel": {
"message": "Закрыть панель навигации",
"description": "The ARIA label for close button of mobile sidebar"
},
"theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": {
"message": "← Перейти к главному меню",
"description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)"
},
"theme.docs.sidebar.toggleSidebarButtonAriaLabel": {
"message": "Переключить навигационную панель",
"description": "The ARIA label for hamburger menu button of mobile navigation"
},
"theme.navbar.mobileDropdown.collapseButton.expandAriaLabel": {
"message": "Expand the dropdown",
"description": "The ARIA label of the button to expand the mobile dropdown navbar item"
},
"theme.navbar.mobileDropdown.collapseButton.collapseAriaLabel": {
"message": "Collapse the dropdown",
"description": "The ARIA label of the button to collapse the mobile dropdown navbar item"
},
"theme.docs.sidebar.expandButtonTitle": {
"message": "Развернуть сайдбар",
"description": "The ARIA label and title attribute for expand button of doc sidebar"
},
"theme.docs.sidebar.expandButtonAriaLabel": {
"message": "Развернуть сайдбар",
"description": "The ARIA label and title attribute for expand button of doc sidebar"
},
"theme.blog.post.plurals": {
"message": "{count} запись|{count} записи|{count} записей",
"description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
},
"theme.blog.tagTitle": {
"message": "{nPosts} с тегом \"{tagName}\"",
"description": "The title of the page for a blog tag"
},
"theme.blog.author.pageTitle": {
"message": "{authorName} - {nPosts}",
"description": "The title of the page for a blog author"
},
"theme.blog.authorsList.pageTitle": {
"message": "Authors",
"description": "The title of the authors page"
},
"theme.blog.authorsList.viewAll": {
"message": "View All Authors",
"description": "The label of the link targeting the blog authors page"
},
"theme.blog.author.noPosts": {
"message": "This author has not written any posts yet.",
"description": "The text for authors with 0 blog post"
},
"theme.contentVisibility.unlistedBanner.title": {
"message": "Unlisted page",
"description": "The unlisted content banner title"
},
"theme.contentVisibility.unlistedBanner.message": {
"message": "This page is unlisted. Search engines will not index it, and only users having a direct link can access it.",
"description": "The unlisted content banner message"
},
"theme.contentVisibility.draftBanner.title": {
"message": "Draft page",
"description": "The draft content banner title"
},
"theme.contentVisibility.draftBanner.message": {
"message": "This page is a draft. It will only be visible in dev and be excluded from the production build.",
"description": "The draft content banner message"
},
"theme.ErrorPageContent.tryAgain": {
"message": "Попробуйте ещё раз",
"description": "The label of the button to try again rendering when the React error boundary captures an error"
},
"theme.common.skipToMainContent": {
"message": "Перейти к основному содержимому",
"description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation"
},
"theme.tags.tagsPageTitle": {
"message": "Теги",
"description": "The title of the tag list page"
}
}

View File

@@ -0,0 +1,14 @@
{
"version.label": {
"message": "Next",
"description": "The label for version current"
},
"sidebar.tutorialSidebar.category.Core Concepts": {
"message": "Core Concepts",
"description": "The label for category Core Concepts in sidebar tutorialSidebar"
},
"sidebar.tutorialSidebar.category.Advanced Features": {
"message": "Advanced Features",
"description": "The label for category Advanced Features in sidebar tutorialSidebar"
}
}

View File

@@ -0,0 +1,14 @@
---
sidebar_position: 9
---
# Дополнительные модули
CherryPick предоставляет набор официальных доп. модулей для расширенных и специфичных сценариев:
| Имя модуля | Описание |
|--------------------------|--------------------------------------------------------------|
| [**cherrypick_annotations**](https://pub.dev/packages/cherrypick_annotations) | Dart-аннотации для лаконичного DI и генерации кода. |
| [**cherrypick_generator**](https://pub.dev/packages/cherrypick_generator) | Генератор кода для автосборки DI-привязок по аннотациям. |
| [**cherrypick_flutter**](https://pub.dev/packages/cherrypick_flutter) | Интеграция DI с Flutter: виджеты-провайдеры, injection. |
| [**talker_cherrypick_logger**](https://pub.dev/packages/talker_cherrypick_logger) | Продвинутый логгер событий DI CherryPick с интеграцией в [Talker](https://pub.dev/packages/talker). Позволяет визуализировать состояние, ошибки и автоматически отслеживать DI прямо в UI и консоли. |

View File

@@ -0,0 +1,71 @@
---
sidebar_position: 3
---
# Обнаружение циклических зависимостей
CherryPick может обнаруживать циклические зависимости в вашей DI-конфигурации, помогая избежать бесконечных циклов и сложных для отладки ошибок.
## Как использовать:
### 1. Включите обнаружение во время разработки
**Локально (в рамках одного скоупа):**
```dart
final scope = CherryPick.openSafeRootScope(); // Локальное обнаружение включено по умолчанию
// или для существующего скоупа:
scope.enableCycleDetection();
```
**Глобально (между скоупами):**
```dart
CherryPick.enableGlobalCrossScopeCycleDetection();
final rootScope = CherryPick.openGlobalSafeRootScope();
```
### 2. Пример ошибки
Если вы объявите взаимозависимые сервисы:
```dart
class A { A(B b); }
class B { B(A a); }
scope.installModules([
Module((bind) {
bind<A>().to((s) => A(s.resolve<B>()));
bind<B>().to((s) => B(s.resolve<A>()));
}),
]);
scope.resolve<A>(); // выбросит CircularDependencyException
```
### 3. Общая рекомендация
- **Включайте обнаружение** всегда в debug и тестовой среде для максимальной безопасности.
- **Отключайте обнаружение** в production после завершения тестирования, ради производительности.
```dart
import 'package:flutter/foundation.dart';
void main() {
if (kDebugMode) {
CherryPick.enableGlobalCycleDetection();
CherryPick.enableGlobalCrossScopeCycleDetection();
}
runApp(MyApp());
}
```
### 4. Отладка и обработка ошибок
При обнаружении будет выброшено исключение `CircularDependencyException` с цепочкой зависимостей:
```dart
try {
scope.resolve<MyService>();
} on CircularDependencyException catch (e) {
print('Цепочка зависимостей: ${e.dependencyChain}');
}
```
<!-- **Подробнее:** смотрите [cycle_detection.ru.md](doc/cycle_detection.ru.md) -->

View File

@@ -0,0 +1,45 @@
---
sidebar_position: 1
---
# Иерархические подскоупы
CherryPick поддерживает иерархическую структуру скоупов, что позволяет строить сложные и модульные графы зависимостей для профессиональных архитектур приложений. Каждый подскоуп наследует зависимости родителя и позволяет переопределять их локально.
## Основные моменты
- **Подскоупы** — дочерние скоупы, открываемые от любого существующего (в том числе root).
- Зависимости подскоупа перекрывают родительские при разрешении.
- Если зависимость не найдена в подскоупе, CherryPick ищет её выше по иерархии.
- Подскоупы могут иметь собственные модули, "жизненный цикл", Disposable-объекты.
- Можно делать вложенность любой глубины для фич, компонентов и т.д.
## Пример
```dart
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
// Открыть подскоуп для функции/страницы
final userFeatureScope = rootScope.openSubScope('userFeature');
userFeatureScope.installModules([UserFeatureModule()]);
// В userFeatureScope сперва ищет в своей области
final userService = userFeatureScope.resolve<UserService>();
// Если не нашлось — идёт в rootScope
final sharedService = userFeatureScope.resolve<SharedService>();
// Подскоупы можно вкладывать друг в друга сколь угодно глубоко
final dialogScope = userFeatureScope.openSubScope('dialog');
dialogScope.installModules([DialogModule()]);
final dialogManager = dialogScope.resolve<DialogManager>();
```
## Применение
- Модульная изоляция частей/экранов с собственными зависимостями
- Переопределение сервисов для конкретных сценариев/навигации
- Управление жизнью и освобождением ресурсов по группам
**Совет:** Всегда закрывайте подскоупы, когда они больше не нужны, чтобы освободить ресурсы.

View File

@@ -0,0 +1,63 @@
---
sidebar_position: 2
---
# Логирование
CherryPick позволяет логировать все события и ошибки DI с помощью расширяемого observer-механизма.
## Кастомные Observer'ы
Вы можете передавать свою реализацию `CherryPickObserver` в root- или любой подскоуп.
Это позволяет централизовать и настраивать логирование, направлять логи в консоль, файл, сторонние сервисы или системы как [Talker](https://pub.dev/packages/talker).
### Пример: вывод всех событий в консоль
```dart
import 'package:cherrypick/cherrypick.dart';
void main() {
// Встроенный PrintCherryPickObserver для консоли
final observer = PrintCherryPickObserver();
final scope = CherryPick.openRootScope(observer: observer);
// Все события и ошибки DI будут выведены!
}
```
### Пример: расширенное логирование через Talker
Для более гибкого логирования или UI-оверлеев можно использовать observer наподобие [talker_cherrypick_logger](https://pub.dev/packages/talker_cherrypick_logger):
<!-- Для более гибкого логирования или UI-оверлеев можно использовать observer наподобие [talker_cherrypick_logger](../talker_cherrypick_logger): -->
```dart
import 'package:cherrypick/cherrypick.dart';
import 'package:talker/talker.dart';
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
void main() {
final talker = Talker();
final observer = TalkerCherryPickObserver(talker);
CherryPick.openRootScope(observer: observer);
// Все события попадают в Talker!
}
```
## Поведение по умолчанию
- По умолчанию логирование "тихое" (SilentCherryPickObserver) для production — нет вывода без observer'а.
- Можно назначить observer для любого скоупа.
## Возможности Observer'а
- Регистрация зависимостей
- Получение/создание/удаление экземпляров
- Установка/удаление модулей
- Открытие/закрытие скоупов
- Кэш-хиты/мимо
- Обнаружение циклов
- Диагностика, предупреждения, ошибки
## Когда применять
- Подробное логирование в dev/test окружениях
- Передача логов в основную систему/аналитику
- Отладка и профилирование DI

View File

@@ -0,0 +1,10 @@
---
sidebar_position: 4
---
# Улучшения производительности
> **Примечание по производительности:**
> **Начиная с версии 3.0.0**, CherryPick использует Map-индексатор для поиска зависимостей. Это означает, что вызовы `resolve<T>()` и связанные методы работают за O(1) независимо от количества модулей/биндингов в скоупе. Ранее библиотека просматривала все модули/биндинги, что могло замедлять DI в крупных проектах.
>
> Эта оптимизация полностью внутренняя: интерфейс библиотеки и пользовательский код не изменились, но производительность заметно выросла на больших графах зависимостей.

View File

@@ -0,0 +1,7 @@
---
sidebar_position: 10
---
# Вклад в проект
Вкладывайтесь! Открывайте задачи или отправляйте pull request'ы на [GitHub](https://github.com/pese-git/cherrypick).

View File

@@ -0,0 +1,107 @@
---
sidebar_position: 1
---
# Привязка (Binding)
**Binding** — это конфигурация, которая определяет, как создавать или предоставлять конкретную зависимость. Binding поддерживает:
* Прямое присваивание экземпляра (`toInstance()`, `toInstanceAsync()`)
* Ленивые провайдеры (синхронные/асинхронные функции)
* Провайдеры с поддержкой динамических параметров
* Именованные экземпляры для получения по строковому ключу
* Необязательное управление жизненным циклом синглтона
#### Пример
```dart
void builder(Scope scope) {
// Прямое предоставление экземпляра
bind<String>().toInstance("Hello world");
// Асинхронное предоставление экземпляра
bind<String>().toInstanceAsync(Future.value("Hello world"));
// Ленивое создание синхронного экземпляра через фабрику
bind<String>().toProvide(() => "Hello world");
// Ленивое создание асинхронного экземпляра через фабрику
bind<String>().toProvideAsync(() async => "Hello async world");
// Предоставление экземпляра с динамическими параметрами (синхронно)
bind<String>().toProvideWithParams((params) => "Hello $params");
// Предоставление экземпляра с динамическими параметрами (асинхронно)
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
// Именованный экземпляр для получения по имени
bind<String>().toProvide(() => "Hello world").withName("my_string");
// Пометить как синглтон (только один экземпляр в пределах скоупа)
bind<String>().toProvide(() => "Hello world").singleton();
}
```
> ⚠️ **Важное примечание об использовании `toInstance` в `builder` модуля:**
>
> Если вы регистрируете цепочку зависимостей через `toInstance` внутри `builder` модуля, **не вызывайте** `scope.resolve<T>()` для типов, которые также регистрируются в том же builder — в момент их регистрации.
>
> CherryPick инициализирует все привязки в builder последовательно. Зависимости, зарегистрированные ранее, еще не доступны для `resolve` в рамках того же выполнения builder. Попытка разрешить только что зарегистрированные типы приведет к ошибке (`Can't resolve dependency ...`).
>
> **Как делать правильно:**
> Вручную создайте полную цепочку зависимостей перед вызовом `toInstance`:
>
> ```dart
> void builder(Scope scope) {
> final a = A();
> final b = B(a);
> final c = C(b);
> bind<A>().toInstance(a);
> bind<B>().toInstance(b);
> bind<C>().toInstance(c);
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toInstance(A());
> // Ошибка! В этот момент A еще не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Неправильно:**
> ```dart
> void builder(Scope scope) {
> bind<A>().toProvide(() => A());
> // Ошибка! В этот момент A еще не зарегистрирован.
> bind<B>().toInstance(B(scope.resolve<A>()));
> }
> ```
>
> **Примечание:** Это ограничение применяется **только** к `toInstance`. С `toProvide`/`toProvideAsync` и подобными провайдерами вы можете безопасно использовать `scope.resolve<T>()` внутри builder.
> ⚠️ **Особое примечание относительно `.singleton()` с `toProvideWithParams()` / `toProvideAsyncWithParams()`:**
>
> Если вы объявляете привязку с помощью `.toProvideWithParams(...)` (или его асинхронного варианта) и затем добавляете `.singleton()`, только **самый первый** вызов `resolve<T>(params: ...)` использует свои параметры; каждый последующий вызов (независимо от параметров) вернет тот же (кешированный) экземпляр.
>
> **Пример:**
> ```dart
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
> final a = scope.resolve<Service>(params: 1); // создает Service(1)
> final b = scope.resolve<Service>(params: 2); // возвращает Service(1)
> print(identical(a, b)); // true
> ```
>
> Используйте этот паттерн только когда хотите получить "главный" синглтон. Если вы ожидаете новый экземпляр для каждого набора параметров, **не используйте** `.singleton()` с параметризованными провайдерами.
> **Примечание о `.singleton()` и `.toInstance()`:**
>
> Вызов `.singleton()` после `.toInstance()` **не** меняет поведение привязки: объект, переданный с `toInstance()`, уже является единым, постоянным экземпляром, который всегда будет возвращаться при каждом resolve.
>
> Не обязательно использовать `.singleton()` с существующим объектом — этот вызов не имеет эффекта.
>
> `.singleton()` имеет смысл только с провайдерами (такими как `toProvide`/`toProvideAsync`), чтобы гарантировать создание только одного экземпляра фабрикой.

View File

@@ -0,0 +1,52 @@
---
sidebar_position: 4
---
# Disposable
CherryPick может автоматически очищать любые зависимости, реализующие интерфейс `Disposable`. Это упрощает управление ресурсами (контроллеры, потоки, сокеты, файлы и др.) — особенно при закрытии скоупа или приложения.
Если вы регистрируете объект, реализующий `Disposable`, как синглтон или через DI-контейнер, CherryPick вызовет его метод `dispose()` при закрытии или очистке скоупа.
## Основные моменты
- Поддерживаются синхронная и асинхронная очистка (dispose может возвращать `void` или `Future`).
- Все объекты `Disposable` из текущего скоупа и подскоупов будут удалены в правильном порядке.
- Предотвращает утечки ресурсов и обеспечивает корректную очистку.
- Не нужно вручную связывать очистку — просто реализуйте интерфейс.
## Минимальный синхронный пример
```dart
class CacheManager implements Disposable {
void dispose() {
cache.clear();
print('CacheManager удалён!');
}
}
final scope = CherryPick.openRootScope();
scope.installModules([
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
]);
// ...спустя время
await CherryPick.closeRootScope(); // выведет: CacheManager удалён!
```
## Асинхронный пример
```dart
class MyServiceWithSocket implements Disposable {
@override
Future<void> dispose() async {
await socket.close();
print('Socket закрыт!');
}
}
scope.installModules([
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
]);
await CherryPick.closeRootScope(); // дождётся завершения async очистки
```
**Совет:** Всегда вызывайте `await CherryPick.closeRootScope()` или `await scope.closeSubScope(key)` в вашем shutdown/teardown-коде для гарантированной очистки ресурсов.

View File

@@ -0,0 +1,19 @@
---
sidebar_position: 2
---
# Модуль
**Модуль** — это логическая точка сбора для привязок (bindings), предназначенная для группирования и инициализации связанных зависимостей. Реализуйте метод `builder`, чтобы определить, как зависимости будут связываться внутри скоупа.
## Пример
```dart
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello world!");
}
}
```

View File

@@ -0,0 +1,31 @@
---
sidebar_position: 3
---
# Скоуп (Scope)
**Scope** управляет деревом модулей и экземпляров зависимостей. Скоупы могут быть вложенными (иерархия родитель-дочерний), обеспечивая модульную компоновку приложения и возможность переопределения зависимостей для отдельных контекстов.
Обычно вы работаете с корневым скоупом, но при необходимости можете создавать именованные подскоупы.
## Пример
```dart
// Открыть основной/корневой скоуп
final rootScope = CherryPick.openRootScope();
// Установить пользовательский модуль
rootScope.installModules([AppModule()]);
// Получить зависимость синхронно
final str = rootScope.resolve<String>();
// Получить зависимость асинхронно
final result = await rootScope.resolveAsync<String>();
// Рекомендуется: закрывать корневой скоуп и высвобождать все ресурсы
await CherryPick.closeRootScope();
// Либо вручную вызвать dispose на любом скоупе, которым вы управляете индивидуально
// await rootScope.dispose();
```

View File

@@ -0,0 +1,15 @@
---
sidebar_position: 4
---
# API разрешения зависимостей
- `resolve<T>()` — получает экземпляр зависимости или выбрасывает исключение, если не найдено.
- `resolveAsync<T>()` — асинхронный вариант для зависимостей с асинхронной инициализацией.
- `tryResolve<T>()` — возвращает `null`, если не найдено (синхронно).
- `tryResolveAsync<T>()` — возвращает `null` асинхронно, если не найдено.
Поддерживает:
- Синхронные и асинхронные зависимости
- Именованные зависимости
- Провайдеры с runtime-параметрами или без них

View File

@@ -0,0 +1,7 @@
---
sidebar_position: 8
---
# Ссылки на документацию
<!-- * Обнаружение циклических зависимостей [(En)](doc/cycle_detection.en.md)[(Ru)](doc/cycle_detection.ru.md) -->

View File

@@ -0,0 +1,124 @@
---
sidebar_position: 6
---
# Пример приложения
Ниже приведён полный пример с модулями, подскоупами, асинхронными провайдерами и разрешением зависимостей.
```dart
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:cherrypick/cherrypick.dart';
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().withName("apiClientMock").toInstance(ApiClientMock());
bind<ApiClient>().withName("apiClientImpl").toInstance(ApiClientImpl());
}
}
class FeatureModule extends Module {
final bool isMock;
FeatureModule({required this.isMock});
@override
void builder(Scope currentScope) {
// Асинхронный провайдер DataRepository с выбором зависимости по имени
bind<DataRepository>()
.withName("networkRepo")
.toProvideAsync(() async {
final client = await Future.delayed(
Duration(milliseconds: 100),
() => currentScope.resolve<ApiClient>(
named: isMock ? "apiClientMock" : "apiClientImpl",
),
);
return NetworkDataRepository(client);
})
.singleton();
// Вызов асинхронного провайдера для DataBloc
bind<DataBloc>().toProvideAsync(
() async {
final repo = await currentScope.resolveAsync<DataRepository>(
named: "networkRepo");
return DataBloc(repo);
},
);
}
}
void main() async {
final scope = CherryPick.openRootScope().installModules([AppModule()]);
final featureScope = scope.openSubScope("featureScope")
..installModules([FeatureModule(isMock: true)]);
final dataBloc = await featureScope.resolveAsync<DataBloc>();
dataBloc.data.listen(
(d) => print('Получены данные: $d'),
onError: (e) => print('Ошибка: $e'),
onDone: () => print('DONE'),
);
await dataBloc.fetchData();
}
class DataBloc {
final DataRepository _dataRepository;
Stream<String> get data => _dataController.stream;
final StreamController<String> _dataController = StreamController.broadcast();
DataBloc(this._dataRepository);
Future<void> fetchData() async {
try {
_dataController.sink.add(await _dataRepository.getData());
} catch (e) {
_dataController.sink.addError(e);
}
}
void dispose() {
_dataController.close();
}
}
abstract class DataRepository {
Future<String> getData();
}
class NetworkDataRepository implements DataRepository {
final ApiClient _apiClient;
final _token = 'token';
NetworkDataRepository(this._apiClient);
@override
Future<String> getData() async =>
await _apiClient.sendRequest(
url: 'www.google.com',
token: _token,
requestBody: {'type': 'data'},
);
}
abstract class ApiClient {
Future sendRequest({@required String? url, String? token, Map? requestBody});
}
class ApiClientMock implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Local Data';
}
}
class ApiClientImpl implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Network data';
}
}
```

View File

@@ -0,0 +1,10 @@
---
sidebar_position: 7
---
# Часто задаваемые вопросы
### В: Нужно ли использовать `await` с CherryPick.closeRootScope(), CherryPick.closeScope() или scope.dispose(), если у меня нет Disposable-сервисов?
**О:**
Да! Даже если ваши сервисы сейчас не реализуют `Disposable`, всегда используйте `await` при закрытии скоупов. Если вы позже добавите очистку ресурсов (реализовав dispose()), CherryPick всё обработает автоматически и ваш код останется без изменений. Это гарантирует надежное освобождение ресурсов для любого сценария.

View File

@@ -0,0 +1,27 @@
---
sidebar_position: 3
---
# Быстрый старт
Минимальный пример регистрации и получения зависимости:
```dart
import 'package:cherrypick/cherrypick.dart';
class AppModule extends Module {
@override
void builder(Scope currentScope) {
bind<ApiClient>().toInstance(ApiClientMock());
bind<String>().toProvide(() => "Hello, CherryPick!");
}
}
final rootScope = CherryPick.openRootScope();
rootScope.installModules([AppModule()]);
final greeting = rootScope.resolve<String>();
print(greeting); // напечатает: Hello, CherryPick!
await CherryPick.closeRootScope();
```

View File

@@ -0,0 +1,18 @@
---
sidebar_position: 2
---
# Установка
Добавьте в ваш `pubspec.yaml`:
```yaml
dependencies:
cherrypick: ^<latest_version>
```
Затем выполните команду:
```shell
dart pub get
```

View File

@@ -0,0 +1,41 @@
---
sidebar_position: 1
---
# CherryPick — Dependency Injection для Dart и Flutter
Добро пожаловать в документацию по **CherryPick** — лёгкой и гибкой библиотеке внедрения зависимостей для Dart и Flutter.
---
## О CherryPick
CherryPick — это модульный инструмент DI (Dependency Injection), созданный для:
- Чистой архитектуры
- Лёгкого и интуитивного API
- Мощной системы иерархических скоупов
- Быстрого синхронного и асинхронного внедрения зависимостей
- Генерации кода и аннотированного DI
CherryPick поможет вам построить чистую и поддерживаемую структуру проекта с минимальным количеством шаблонного кода как для backend, так и для Flutter-приложений.
## Быстрые ссылки
- [Ключевые возможности](key-features.md)
- [Быстрый старт](getting-started.md)
- [Базовые концепции](core-concepts/binding.md)
- [Расширенные возможности](advanced-features/hierarchical-subscopes.md)
- [Использование аннотаций](using-annotations.md)
- [FAQ](faq.md)
- [Пример приложения](example-application.md)
- [Репозиторий на GitHub](https://github.com/pese-git/cherrypick)
## Установка
Смотрите раздел инструкции [Установка](installation.md) по добавлению CherryPick в ваш Dart/Flutter проект.
---
CherryPick — open-source. Будем рады вашим вопросам и вкладу в развитие!
---

View File

@@ -0,0 +1,16 @@
---
sidebar_position: 1
---
# Ключевые возможности
- Главный скоуп и именованные подскоупы
- Привязка и разрешение экземпляров по имени
- Асинхронные и синхронные провайдеры
- Провайдеры с поддержкой параметров времени выполнения
- Управление жизненным циклом синглтонов
- Модульная и иерархическая композиция
- Null-safe разрешение зависимостей (tryResolve/tryResolveAsync)
- Обнаружение циклических зависимостей (локально и глобально)
- Подробное логирование состояния и действий DI-контейнера
- Автоматическое освобождение ресурсов для всех зарегистрированных Disposable зависимостей

View File

@@ -0,0 +1,9 @@
---
sidebar_position: 11
---
# Лицензия
Проект распространяется под [лицензией Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
**Важно:** При отсутствии специальных договорённостей поставляется "КАК ЕСТЬ", без каких-либо гарантий. Подробности см. в самой лицензии.

View File

@@ -0,0 +1,104 @@
---
sidebar_position: 5
---
# Использование аннотаций и генерация кода
CherryPick предоставляет продвинутую эргономику и безопасный DI благодаря **аннотациям Dart** и генерации кода. Это позволяет избавить вас от рутины — просто аннотируйте классы, поля и модули, запускайте генератор и используйте полностью автосвязанный DI!
## Как это работает
1. **Аннотируйте** сервисы, провайдеры и поля с помощью `cherrypick_annotations`.
2. **Генерируйте** код с помощью `cherrypick_generator` и `build_runner`.
3. **Используйте** автосгенерированные модули и миксины для автоматического внедрения.
---
## Поддерживаемые аннотации
| Аннотация | Target | Описание |
|---------------------|---------------|--------------------------------------------------------------|
| `@injectable()` | класс | Включает автоподстановку полей (генерируется mixin) |
| `@inject()` | поле | Автоподстановка через DI (работает с @injectable) |
| `@module()` | класс | DI-модуль: методы — провайдеры и сервисы |
| `@provide` | метод | Регистрирует как DI-провайдер (можно с параметрами) |
| `@instance` | метод/класс | Регистрирует новый экземпляр (на каждый resolve, factory) |
| `@singleton` | метод/класс | Регистрация как синглтон (один экземпляр на скоуп) |
| `@named` | поле/параметр | Использование именованных экземпляров для внедрения/resolve |
| `@scope` | поле/параметр | Внедрение/resolve из другого (именованного) скоупа |
| `@params` | параметр | Добавляет user-defined параметры во время resolve |
---
## Пример Field Injection
```dart
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
@injectable()
class ProfilePage with _\$ProfilePage {
@inject()
late final AuthService auth;
@inject()
@scope('profile')
late final ProfileManager manager;
@inject()
@named('admin')
late final UserService adminUserService;
}
```
- После запуска build_runner миксин `_ProfilePage` будет сгенерирован для внедрения.
- Вызовите `myProfilePage.injectFields();` чтобы все зависимости были внедрены автоматически.
## Пример модуля/провайдера
```dart
@module()
abstract class AppModule {
@singleton
AuthService provideAuth(Api api) => AuthService(api);
@named('logging')
@provide
Future<Logger> provideLogger(@params Map<String, dynamic> args) async => ...;
}
```
---
## Шаги использования
1. Добавьте зависимости в `pubspec.yaml`.
2. Аннотируйте классы и модули.
3. Генерируйте код командой build_runner.
4. Регистрируйте модули и используйте автосвязь.
---
## Расширенные возможности
- Используйте `@named` для внедрения по ключу.
- Используйте `@scope` для внедрения из разных скоупов.
- Используйте `@params` для передачи runtime-параметров.
---
## Советы и FAQ
- После изменений в DI-коде запускайте build_runner заново.
- Не редактируйте `.g.dart` вручную.
- Ошибки некорректных аннотаций определяются автоматически.
---
## Ссылки
<!--
- [Подробнее про аннотации (en)](doc/annotations_en.md)
- [cherrypick_annotations/README.md](../cherrypick_annotations/README.md)
- [cherrypick_generator/README.md](../cherrypick_generator/README.md)
- Полный пример: [`examples/postly`](../examples/postly)
-->

View File

@@ -0,0 +1,34 @@
{
"link.title.Docs": {
"message": "Docs",
"description": "The title of the footer links column with title=Docs in the footer"
},
"link.title.Community": {
"message": "Community",
"description": "The title of the footer links column with title=Community in the footer"
},
"link.title.More": {
"message": "More",
"description": "The title of the footer links column with title=More in the footer"
},
"link.item.label.Docs": {
"message": "Документация",
"description": "The label of footer link with label=Docs linking to /docs/intro"
},
"link.item.label.Telegram": {
"message": "Telegram",
"description": "The label of footer link with label=Telegram linking to https://t.me/+22IVT0vqXBg1NDdi"
},
"link.item.label.PubDev": {
"message": "PubDev",
"description": "The label of footer link with label=PubDev linking to https://pub.dev/packages/cherrypick"
},
"link.item.label.GitHub": {
"message": "GitHub",
"description": "The label of footer link with label=GitHub linking to https://github.com/pese-git/cherrypick"
},
"copyright": {
"message": "Copyright © 2025 CherryPick, Inc. Built with Docusaurus.",
"description": "The footer copyright"
}
}

View File

@@ -0,0 +1,18 @@
{
"title": {
"message": "CherryPick",
"description": "The title in the navbar"
},
"logo.alt": {
"message": "CherryPick Logo",
"description": "The alt text of navbar logo"
},
"item.label.Docs": {
"message": "Документация",
"description": "Navbar item with label Docs"
},
"item.label.GitHub": {
"message": "GitHub",
"description": "Navbar item with label GitHub"
}
}

17493
website/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

48
website/package.json Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "website",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids",
"typecheck": "tsc"
},
"dependencies": {
"@docusaurus/core": "3.8.1",
"@docusaurus/preset-classic": "3.8.1",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.0.0",
"prism-react-renderer": "^2.3.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.8.1",
"@docusaurus/tsconfig": "3.8.1",
"@docusaurus/types": "3.8.1",
"typescript": "~5.6.2"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=18.0"
},
"packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447"
}

33
website/sidebars.ts Normal file
View File

@@ -0,0 +1,33 @@
import type {SidebarsConfig} from '@docusaurus/plugin-content-docs';
// This runs in Node.js - Don't use client-side code here (browser APIs, JSX...)
/**
* Creating a sidebar enables you to:
- create an ordered group of docs
- render a sidebar for each doc of that group
- provide next/previous navigation
The sidebars can be generated from the filesystem, or explicitly defined here.
Create as many sidebars as you want.
*/
const sidebars: SidebarsConfig = {
// By default, Docusaurus generates a sidebar from the docs folder structure
tutorialSidebar: [{type: 'autogenerated', dirName: '.'}],
// But you can create a sidebar manually
/*
tutorialSidebar: [
'intro',
'hello',
{
type: 'category',
label: 'Tutorial',
items: ['tutorial-basics/create-a-document'],
},
],
*/
};
export default sidebars;

View File

@@ -0,0 +1,69 @@
import type {ReactNode} from 'react';
import clsx from 'clsx';
import Heading from '@theme/Heading';
import Translate from '@docusaurus/Translate';
import styles from './styles.module.css';
type FeatureItem = {
title: ReactNode;
Svg: React.ComponentType<React.ComponentProps<'svg'>>;
description: ReactNode;
};
const FeatureList: FeatureItem[] = [
{
title: <Translate id="feature.modular">Modular & Hierarchical</Translate>,
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<Translate id="feature.modular.desc">
CherryPick supports modular DI bindings and true hierarchical scopes. Build scalable apps by composing advanced dependency trees with clear separation of concerns.
</Translate>
),
},
{
title: <Translate id="feature.syncAsync">Sync & Async DI, Zero Boilerplate</Translate>,
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<Translate id="feature.syncAsync.desc">
Register synchronous or asynchronous providers, named and singleton dependencies, and enjoy null-safe, testable resolution. Annotation-based code generation removes all manual wiring.
</Translate>
),
},
{
title: <Translate id="feature.dartFlutter">For Dart & Flutter</Translate>,
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<Translate id="feature.dartFlutter.desc">
Use CherryPick in backend, CLI, server or Flutter widget trees equally well. Deep Flutter integration for provider injection, async scope lifecycles, and easy testing.
</Translate>
),
},
];
function Feature({title, Svg, description}: FeatureItem) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<Heading as="h3">{title}</Heading>
<p>{description}</p>
</div>
</div>
);
}
export default function HomepageFeatures(): ReactNode {
return (
<section className={styles.features}>
<div className="container">
<div className="row">
{FeatureList.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
);
}

View File

@@ -0,0 +1,11 @@
.features {
display: flex;
align-items: center;
padding: 2rem 0;
width: 100%;
}
.featureSvg {
height: 200px;
width: 200px;
}

View File

@@ -0,0 +1,30 @@
/**
* Any CSS included here will be global. The classic template
* bundles Infima by default. Infima is a CSS framework designed to
* work well for content-centric websites.
*/
/* You can override the default Infima variables here. */
:root {
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;
--ifm-code-font-size: 95%;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
}
/* For readability concerns, you should choose a lighter palette in dark mode. */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
}

View File

@@ -0,0 +1,23 @@
/**
* CSS files with the .module.css suffix will be treated as CSS modules
* and scoped locally.
*/
.heroBanner {
padding: 4rem 0;
text-align: center;
position: relative;
overflow: hidden;
}
@media screen and (max-width: 996px) {
.heroBanner {
padding: 2rem;
}
}
.buttons {
display: flex;
align-items: center;
justify-content: center;
}

View File

@@ -0,0 +1,46 @@
import type {ReactNode} from 'react';
import clsx from 'clsx';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import Layout from '@theme/Layout';
import HomepageFeatures from '@site/src/components/HomepageFeatures';
import Heading from '@theme/Heading';
import Translate, {translate} from '@docusaurus/Translate';
import styles from './index.module.css';
function HomepageHeader() {
const {siteConfig} = useDocusaurusContext();
return (
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<Heading as="h1" className="hero__title">
<Translate id="homepage.title">CherryPick</Translate>
</Heading>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className="button button--secondary button--lg"
to="/docs/intro"
>
<Translate id="homepage.cta">Explore CherryPick Documentation 🍒</Translate>
</Link>
</div>
</div>
</header>
);
}
export default function Home(): ReactNode {
const {siteConfig} = useDocusaurusContext();
return (
<Layout
title={siteConfig.title}
description="CherryPick: Modular and lightweight dependency injection for Dart & Flutter. Fast, powerful, easy to integrate.">
<HomepageHeader />
<main>
<HomepageFeatures />
</main>
</Layout>
);
}

View File

@@ -0,0 +1,7 @@
---
title: Markdown page example
---
# Markdown page example
You don't need React to write simple standalone pages.

Some files were not shown because too many files have changed in this diff Show More