mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-24 13:47:24 +00:00
Compare commits
44 Commits
cherrypick
...
talker_che
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99e662124f | ||
|
|
03f54981f3 | ||
|
|
349efe6ba6 | ||
|
|
c2f0e027b6 | ||
|
|
f85036d20f | ||
|
|
db4d128d04 | ||
|
|
2c4e2ed251 | ||
|
|
7b4642f407 | ||
|
|
7d45d00d6a | ||
|
|
884df50a34 | ||
|
|
5710af2f9b | ||
|
|
9312ef46ea | ||
|
|
900cd68663 | ||
|
|
57e4196b95 | ||
|
|
358da8f96b | ||
|
|
ea2b6687f4 | ||
|
|
df00a2a5d2 | ||
|
|
d5983a4a0b | ||
|
|
125bccfa5a | ||
|
|
12b97c9368 | ||
|
|
424aaa3e22 | ||
|
|
2ec3a86a2f | ||
|
|
efed72cc39 | ||
|
|
4dc9e269cd | ||
|
|
d153ab4255 | ||
|
|
6924ccd07b | ||
|
|
26b843f791 | ||
|
|
8eafba4e4b | ||
|
|
ad6e9bbc3d | ||
|
|
bea8affcab | ||
|
|
1d7b9a9166 | ||
|
|
016c212063 | ||
|
|
d93d4173a2 | ||
|
|
85aa23d7ed | ||
|
|
51cf4a0dc0 | ||
|
|
8f980ff111 | ||
|
|
4d872d7c25 | ||
|
|
450f4231cb | ||
|
|
cd1b9cf49d | ||
|
|
33775f5748 | ||
|
|
e5848784ac | ||
|
|
a4b0ddfa54 | ||
|
|
547a15fa4e | ||
|
|
a9c95f6a89 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -18,5 +18,7 @@ pubspec_overrides.yaml
|
|||||||
melos_cherrypick.iml
|
melos_cherrypick.iml
|
||||||
melos_cherrypick_workspace.iml
|
melos_cherrypick_workspace.iml
|
||||||
melos_cherrypick_flutter.iml
|
melos_cherrypick_flutter.iml
|
||||||
|
melos_benchmark_di.iml
|
||||||
|
melos_talker_cherrypick_logger.iml
|
||||||
|
|
||||||
coverage
|
coverage
|
||||||
161
CHANGELOG.md
161
CHANGELOG.md
@@ -3,6 +3,167 @@
|
|||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||||
|
|
||||||
|
## 2025-08-13
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Packages with breaking changes:
|
||||||
|
|
||||||
|
- There are no breaking changes in this release.
|
||||||
|
|
||||||
|
Packages with other changes:
|
||||||
|
|
||||||
|
- [`talker_cherrypick_logger` - `v1.1.0-dev.3`](#talker_cherrypick_logger---v110-dev3)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `talker_cherrypick_logger` - `v1.1.0-dev.3`
|
||||||
|
|
||||||
|
|
||||||
|
## 2025-08-13
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Packages with breaking changes:
|
||||||
|
|
||||||
|
- There are no breaking changes in this release.
|
||||||
|
|
||||||
|
Packages with other changes:
|
||||||
|
|
||||||
|
- [`talker_cherrypick_logger` - `v1.1.0-dev.2`](#talker_cherrypick_logger---v110-dev2)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `talker_cherrypick_logger` - `v1.1.0-dev.2`
|
||||||
|
|
||||||
|
- Bump "talker_cherrypick_logger" to `1.1.0-dev.2`.
|
||||||
|
|
||||||
|
|
||||||
|
## 2025-08-13
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Packages with breaking changes:
|
||||||
|
|
||||||
|
- [`cherrypick_generator` - `v2.0.0-dev.0`](#cherrypick_generator---v200-dev0)
|
||||||
|
|
||||||
|
Packages with other changes:
|
||||||
|
|
||||||
|
- [`cherrypick` - `v3.0.0-dev.9`](#cherrypick---v300-dev9)
|
||||||
|
- [`cherrypick_annotations` - `v1.1.2-dev.0`](#cherrypick_annotations---v112-dev0)
|
||||||
|
- [`cherrypick_flutter` - `v1.1.3-dev.9`](#cherrypick_flutter---v113-dev9)
|
||||||
|
- [`talker_cherrypick_logger` - `v1.1.0-dev.0`](#talker_cherrypick_logger---v110-dev0)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `cherrypick_generator` - `v2.0.0-dev.0`
|
||||||
|
|
||||||
|
- **BREAKING** **DOCS**(generator): improve and unify English documentation and examples for all DI source files.
|
||||||
|
|
||||||
|
#### `cherrypick` - `v3.0.0-dev.9`
|
||||||
|
|
||||||
|
- **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section.
|
||||||
|
- **DOCS**(api): improve all DI core code documentation with English dartdoc and examples.
|
||||||
|
|
||||||
|
#### `cherrypick_annotations` - `v1.1.2-dev.0`
|
||||||
|
|
||||||
|
- **DOCS**(annotations): unify and improve English DartDoc for all DI annotations.
|
||||||
|
|
||||||
|
#### `cherrypick_flutter` - `v1.1.3-dev.9`
|
||||||
|
|
||||||
|
- **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration.
|
||||||
|
|
||||||
|
#### `talker_cherrypick_logger` - `v1.1.0-dev.0`
|
||||||
|
|
||||||
|
- **FEAT**(logging): add talker_dio_logger and talker_bloc_logger integration, improve cherrypick logger structure, add UI log screen for DI and network/bloc debug.
|
||||||
|
- **DOCS**: add full English documentation and usage guide to README.md.
|
||||||
|
- **DOCS**: add detailed English documentation and usage examples for TalkerCherryPickObserver.
|
||||||
|
|
||||||
|
|
||||||
|
## 2025-08-12
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Packages with breaking changes:
|
||||||
|
|
||||||
|
- There are no breaking changes in this release.
|
||||||
|
|
||||||
|
Packages with other changes:
|
||||||
|
|
||||||
|
- [`cherrypick` - `v3.0.0-dev.8`](#cherrypick---v300-dev8)
|
||||||
|
- [`cherrypick_flutter` - `v1.1.3-dev.8`](#cherrypick_flutter---v113-dev8)
|
||||||
|
|
||||||
|
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` - `v1.1.3-dev.8`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `cherrypick` - `v3.0.0-dev.8`
|
||||||
|
|
||||||
|
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||||
|
- **FIX**(doc): remove hide symbol.
|
||||||
|
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||||
|
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||||
|
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||||
|
- **DOCS**(README): add section with overview table for additional modules.
|
||||||
|
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||||
|
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||||
|
|
||||||
|
|
||||||
|
## 2025-08-11
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Packages with breaking changes:
|
||||||
|
|
||||||
|
- [`cherrypick` - `v3.0.0-dev.7`](#cherrypick---v300-dev7)
|
||||||
|
|
||||||
|
Packages with other changes:
|
||||||
|
|
||||||
|
- [`cherrypick_annotations` - `v1.1.1`](#cherrypick_annotations---v111)
|
||||||
|
- [`cherrypick_flutter` - `v1.1.3-dev.7`](#cherrypick_flutter---v113-dev7)
|
||||||
|
- [`cherrypick_generator` - `v1.1.1`](#cherrypick_generator---v111)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### `cherrypick` - `v3.0.0-dev.7`
|
||||||
|
|
||||||
|
- **FIX**(comment): fix warnings.
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
- **FEAT**: add Disposable interface source and usage example.
|
||||||
|
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
|
||||||
|
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
|
||||||
|
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||||
|
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||||
|
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
|
||||||
|
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
|
||||||
|
|
||||||
|
#### `cherrypick_annotations` - `v1.1.1`
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
|
#### `cherrypick_flutter` - `v1.1.3-dev.7`
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
|
#### `cherrypick_generator` - `v1.1.1`
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
|
|
||||||
## 2025-08-08
|
## 2025-08-08
|
||||||
|
|
||||||
### Changes
|
### Changes
|
||||||
|
|||||||
2
LICENSE
2
LICENSE
@@ -192,7 +192,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ packages:
|
|||||||
path: "../cherrypick"
|
path: "../cherrypick"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "3.0.0-dev.3"
|
version: "3.0.0-dev.8"
|
||||||
collection:
|
collection:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -1,3 +1,33 @@
|
|||||||
|
## 3.0.0-dev.9
|
||||||
|
|
||||||
|
- **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section.
|
||||||
|
- **DOCS**(api): improve all DI core code documentation with English dartdoc and examples.
|
||||||
|
|
||||||
|
## 3.0.0-dev.8
|
||||||
|
|
||||||
|
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||||
|
- **FIX**(doc): remove hide symbol.
|
||||||
|
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||||
|
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||||
|
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||||
|
- **DOCS**(README): add section with overview table for additional modules.
|
||||||
|
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||||
|
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||||
|
|
||||||
|
## 3.0.0-dev.7
|
||||||
|
|
||||||
|
> Note: This release has breaking changes.
|
||||||
|
|
||||||
|
- **FIX**(comment): fix warnings.
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
- **FEAT**: add Disposable interface source and usage example.
|
||||||
|
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
|
||||||
|
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
|
||||||
|
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||||
|
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||||
|
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
|
||||||
|
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
|
||||||
|
|
||||||
## 3.0.0-dev.6
|
## 3.0.0-dev.6
|
||||||
|
|
||||||
> Note: This release has breaking changes.
|
> Note: This release has breaking changes.
|
||||||
|
|||||||
@@ -192,7 +192,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -1,18 +1,103 @@
|
|||||||
# CherryPick
|
# CherryPick
|
||||||
|
|
||||||
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter. It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
|
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter.
|
||||||
|
It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
|
||||||
|
|
||||||
## Key Concepts
|
---
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
- [Key Features](#key-features)
|
||||||
|
- [Installation](#installation)
|
||||||
|
- [Getting Started](#getting-started)
|
||||||
|
- [Core Concepts](#core-concepts)
|
||||||
|
- [Binding](#binding)
|
||||||
|
- [Module](#module)
|
||||||
|
- [Scope](#scope)
|
||||||
|
- [Disposable](#disposable)
|
||||||
|
- [Dependency Resolution API](#dependency-resolution-api)
|
||||||
|
- [Using Annotations & Code Generation](#using-annotations--code-generation)
|
||||||
|
- [Advanced Features](#advanced-features)
|
||||||
|
- [Hierarchical Subscopes](#hierarchical-subscopes)
|
||||||
|
- [Logging](#logging)
|
||||||
|
- [Circular Dependency Detection](#circular-dependency-detection)
|
||||||
|
- [Performance Improvements](#performance-improvements)
|
||||||
|
- [Example Application](#example-application)
|
||||||
|
- [FAQ](#faq)
|
||||||
|
- [Documentation Links](#documentation-links)
|
||||||
|
- [Additional Modules](#additional-modules)
|
||||||
|
- [Contributing](#contributing)
|
||||||
|
- [License](#license)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Add to your `pubspec.yaml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
dependencies:
|
||||||
|
cherrypick: ^<latest_version>
|
||||||
|
````
|
||||||
|
|
||||||
|
Then run:
|
||||||
|
|
||||||
|
```shell
|
||||||
|
dart pub get
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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();
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Concepts
|
||||||
|
|
||||||
### Binding
|
### Binding
|
||||||
|
|
||||||
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
||||||
|
|
||||||
- Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
* Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
||||||
- Lazy providers (sync/async functions)
|
* Lazy providers (sync/async functions)
|
||||||
- Provider functions supporting dynamic parameters
|
* Provider functions supporting dynamic parameters
|
||||||
- Named instances for resolving by string key
|
* Named instances for resolving by string key
|
||||||
- Optional singleton lifecycle
|
* Optional singleton lifecycle
|
||||||
|
|
||||||
#### Example
|
#### Example
|
||||||
|
|
||||||
@@ -79,29 +164,67 @@ final str = rootScope.resolve<String>();
|
|||||||
// Resolve a dependency asynchronously
|
// Resolve a dependency asynchronously
|
||||||
final result = await rootScope.resolveAsync<String>();
|
final result = await rootScope.resolveAsync<String>();
|
||||||
|
|
||||||
// Close the root scope once done
|
// Recommended: Close the root scope and release all resources
|
||||||
CherryPick.closeRootScope();
|
await CherryPick.closeRootScope();
|
||||||
|
|
||||||
|
// Alternatively, you may manually call dispose on any scope you manage individually
|
||||||
|
// await rootScope.dispose();
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Working with Subscopes
|
---
|
||||||
|
|
||||||
|
### 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
|
```dart
|
||||||
// Open a named child scope (e.g., for a feature/module)
|
class CacheManager implements Disposable {
|
||||||
final subScope = rootScope.openSubScope('featureScope')
|
void dispose() {
|
||||||
..installModules([FeatureModule()]);
|
cache.clear();
|
||||||
|
print('CacheManager disposed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Resolve from subScope, with fallback to parents if missing
|
final scope = CherryPick.openRootScope();
|
||||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
scope.installModules([
|
||||||
|
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// ...later
|
||||||
|
await CherryPick.closeRootScope(); // prints: CacheManager disposed!
|
||||||
```
|
```
|
||||||
|
|
||||||
### Fast Dependency Lookup (Performance Improvement)
|
#### Async Example
|
||||||
|
```dart
|
||||||
|
class MyServiceWithSocket implements Disposable {
|
||||||
|
@override
|
||||||
|
Future<void> dispose() async {
|
||||||
|
await socket.close();
|
||||||
|
print('Socket closed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
> **Performance Note:**
|
scope.installModules([
|
||||||
> **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.
|
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
|
||||||
>
|
]);
|
||||||
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.
|
|
||||||
|
|
||||||
### Dependency Lookup API
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency Resolution API
|
||||||
|
|
||||||
- `resolve<T>()` — Locates a dependency instance or throws if missing.
|
- `resolve<T>()` — Locates a dependency instance or throws if missing.
|
||||||
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
|
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
|
||||||
@@ -113,6 +236,335 @@ Supports:
|
|||||||
- Named dependencies
|
- Named dependencies
|
||||||
- Provider functions with and without runtime parameters
|
- Provider functions with and without runtime parameters
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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](../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.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Example Application
|
## Example Application
|
||||||
|
|
||||||
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
|
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
|
||||||
@@ -234,129 +686,52 @@ class ApiClientImpl implements ApiClient {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Logging
|
---
|
||||||
|
|
||||||
CherryPick supports centralized logging of all dependency injection (DI) events and errors. You can globally enable logs for your application or test environment with:
|
## FAQ
|
||||||
|
|
||||||
```dart
|
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
|
||||||
import 'package:cherrypick/cherrypick.dart';
|
|
||||||
|
|
||||||
void main() {
|
**A:**
|
||||||
// Set a global logger before any scopes are created
|
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.
|
||||||
CherryPick.setGlobalLogger(PrintLogger()); // or your custom logger
|
|
||||||
|
|
||||||
final scope = CherryPick.openRootScope();
|
---
|
||||||
// All DI actions and errors will now be logged!
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- All dependency resolution, scope creation, module installation, and circular dependency errors will be sent to your logger (via info/error method).
|
|
||||||
- By default, logs are off (SilentLogger is used in production).
|
|
||||||
|
|
||||||
If you want fine-grained, test-local, or isolated logging, you can provide a logger directly to each scope:
|
## Documentation Links
|
||||||
|
|
||||||
```dart
|
* Circular Dependency Detection [(En)](doc/cycle_detection.en.md)[(Ru)](doc/cycle_detection.ru.md)
|
||||||
final logger = MockLogger();
|
|
||||||
final scope = Scope(null, logger: logger); // works in tests for isolation
|
|
||||||
scope.installModules([...]);
|
|
||||||
```
|
|
||||||
|
|
||||||
## Features
|
---
|
||||||
|
|
||||||
- [x] Main Scope and Named Subscopes
|
## Additional Modules
|
||||||
- [x] Named Instance Binding and Resolution
|
|
||||||
- [x] Asynchronous and Synchronous Providers
|
|
||||||
- [x] Providers Supporting Runtime Parameters
|
|
||||||
- [x] Singleton Lifecycle Management
|
|
||||||
- [x] Modular and Hierarchical Composition
|
|
||||||
- [x] Null-safe Resolution (tryResolve/tryResolveAsync)
|
|
||||||
- [x] Circular Dependency Detection (Local and Global)
|
|
||||||
- [x] Comprehensive logging of dependency injection state and actions
|
|
||||||
|
|
||||||
## Quick Guide: Circular Dependency Detection
|
CherryPick provides a set of official add-on modules for advanced use cases and specific platforms:
|
||||||
|
|
||||||
CherryPick can detect circular dependencies in your DI configuration, helping you avoid infinite loops and hard-to-debug errors.
|
| 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. |
|
||||||
|
|
||||||
**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)
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
- [Circular Dependency Detection (English)](doc/cycle_detection.en.md)
|
|
||||||
- [Обнаружение циклических зависимостей (Русский)](doc/cycle_detection.ru.md)
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
|
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
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.
|
**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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Links
|
## Links
|
||||||
|
|
||||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class AppModule extends Module {
|
|||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
// Set a global logger for the DI system
|
// Set a global logger for the DI system
|
||||||
CherryPick.setGlobalLogger(PrintLogger());
|
CherryPick.setGlobalObserver(PrintCherryPickObserver());
|
||||||
|
|
||||||
// Open the root scope
|
// Open the root scope
|
||||||
final rootScope = CherryPick.openRootScope();
|
final rootScope = CherryPick.openRootScope();
|
||||||
@@ -32,6 +32,6 @@ void main() {
|
|||||||
subScope.closeSubScope('feature.profile');
|
subScope.closeSubScope('feature.profile');
|
||||||
|
|
||||||
// Demonstrate disabling and re-enabling logging
|
// Demonstrate disabling and re-enabling logging
|
||||||
CherryPick.setGlobalLogger(const SilentLogger());
|
CherryPick.setGlobalObserver(SilentCherryPickObserver());
|
||||||
rootScope.resolve<UserRepository>(); // now without logs
|
rootScope.resolve<UserRepository>(); // now without logs
|
||||||
}
|
}
|
||||||
|
|||||||
40
cherrypick/example/disposable_example.dart
Normal file
40
cherrypick/example/disposable_example.dart
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
|
||||||
|
/// Ваш сервис с освобождением ресурсов
|
||||||
|
class MyService implements Disposable {
|
||||||
|
bool wasDisposed = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
// Например: закрыть соединение, остановить таймер, освободить память
|
||||||
|
wasDisposed = true;
|
||||||
|
print('MyService disposed!');
|
||||||
|
}
|
||||||
|
|
||||||
|
void doSomething() => print('Doing something...');
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final scope = CherryPick.openRootScope();
|
||||||
|
|
||||||
|
// Регистрируем биндинг (singleton для примера)
|
||||||
|
scope.installModules([
|
||||||
|
ModuleImpl(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Получаем зависимость
|
||||||
|
final service = scope.resolve<MyService>();
|
||||||
|
service.doSomething(); // «Doing something...»
|
||||||
|
|
||||||
|
// Освобождаем все ресурсы
|
||||||
|
scope.dispose();
|
||||||
|
print('Service wasDisposed = ${service.wasDisposed}'); // true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Пример модуля CherryPick
|
||||||
|
class ModuleImpl extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<MyService>().toProvide(() => MyService()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ library;
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -20,4 +20,5 @@ export 'package:cherrypick/src/global_cycle_detector.dart';
|
|||||||
export 'package:cherrypick/src/helper.dart';
|
export 'package:cherrypick/src/helper.dart';
|
||||||
export 'package:cherrypick/src/module.dart';
|
export 'package:cherrypick/src/module.dart';
|
||||||
export 'package:cherrypick/src/scope.dart';
|
export 'package:cherrypick/src/scope.dart';
|
||||||
export 'package:cherrypick/src/logger.dart';
|
export 'package:cherrypick/src/disposable.dart';
|
||||||
|
export 'package:cherrypick/src/observer.dart';
|
||||||
|
|||||||
Binary file not shown.
@@ -1,40 +1,82 @@
|
|||||||
|
//
|
||||||
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
// 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 the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
//
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
/// Represents a direct instance or an async instance ([T] or [Future<T>]).
|
||||||
|
/// Used for both direct and async bindings.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// Instance<String> sync = "hello";
|
||||||
|
/// Instance<MyApi> async = Future.value(MyApi());
|
||||||
|
/// ```
|
||||||
typedef Instance<T> = FutureOr<T>;
|
typedef Instance<T> = FutureOr<T>;
|
||||||
|
|
||||||
/// RU: Синхронный или асинхронный провайдер без параметров, возвращающий [T] или [Future<T>].
|
/// Provider function type for synchronous or asynchronous, parameterless creation of [T].
|
||||||
/// ENG: Synchronous or asynchronous provider without parameters, returning [T] or [Future<T>].
|
/// Can return [T] or [Future<T>].
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// Provider<MyService> provider = () => MyService();
|
||||||
|
/// Provider<Api> asyncProvider = () async => await Api.connect();
|
||||||
|
/// ```
|
||||||
typedef Provider<T> = FutureOr<T> Function();
|
typedef Provider<T> = FutureOr<T> Function();
|
||||||
|
|
||||||
/// RU: Провайдер с динамическим параметром, возвращающий [T] или [Future<T>] в зависимости от реализации.
|
/// Provider function type that accepts a dynamic parameter, for factory/parametrized injection.
|
||||||
/// ENG: Provider with dynamic parameter, returning [T] or [Future<T>] depending on implementation.
|
/// Returns [T] or [Future<T>].
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// ProviderWithParams<User> provider = (params) => User(params["name"]);
|
||||||
|
/// ```
|
||||||
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
||||||
|
|
||||||
/// RU: Абстрактный интерфейс для классов, которые разрешают зависимости типа [T].
|
/// Abstract interface for dependency resolvers used by [Binding].
|
||||||
/// ENG: Abstract interface for classes that resolve dependencies of type [T].
|
/// Defines how to resolve instances of type [T].
|
||||||
|
///
|
||||||
|
/// You usually don't use this directly; it's used internally for advanced/low-level DI.
|
||||||
abstract class BindingResolver<T> {
|
abstract class BindingResolver<T> {
|
||||||
/// RU: Синхронное разрешение зависимости с параметром [params].
|
/// Synchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||||
/// ENG: Synchronous resolution of the dependency with [params].
|
/// Throws if implementation does not support sync resolution.
|
||||||
T? resolveSync([dynamic params]);
|
T? resolveSync([dynamic params]);
|
||||||
|
|
||||||
/// RU: Асинхронное разрешение зависимости с параметром [params].
|
/// Asynchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||||
/// ENG: Asynchronous resolution of the dependency with [params].
|
/// If instance is already a [Future], returns it directly.
|
||||||
Future<T>? resolveAsync([dynamic params]);
|
Future<T>? resolveAsync([dynamic params]);
|
||||||
|
|
||||||
/// RU: Помечает текущий резолвер как синглтон — результат будет закеширован.
|
/// Marks this resolver as singleton: instance(s) will be cached and reused inside the scope.
|
||||||
/// ENG: Marks this resolver as singleton — result will be cached.
|
|
||||||
void toSingleton();
|
void toSingleton();
|
||||||
|
|
||||||
|
/// Returns true if this resolver is marked as singleton.
|
||||||
bool get isSingleton;
|
bool get isSingleton;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Резолвер, оборачивающий конкретный экземпляр [T] (или Future<T>), без вызова провайдера.
|
/// Concrete resolver for direct instance ([T] or [Future<T>]). No provider is called.
|
||||||
/// ENG: Resolver that wraps a concrete instance of [T] (or Future<T>), without provider invocation.
|
///
|
||||||
|
/// Used for [Binding.toInstance].
|
||||||
|
/// Supports both sync and async resolution; sync will throw if underlying instance is [Future].
|
||||||
|
/// Examples:
|
||||||
|
/// ```dart
|
||||||
|
/// var resolver = InstanceResolver("hello");
|
||||||
|
/// resolver.resolveSync(); // == "hello"
|
||||||
|
/// var asyncResolver = InstanceResolver(Future.value(7));
|
||||||
|
/// asyncResolver.resolveAsync(); // Future<int>
|
||||||
|
/// ```
|
||||||
class InstanceResolver<T> implements BindingResolver<T> {
|
class InstanceResolver<T> implements BindingResolver<T> {
|
||||||
final Instance<T> _instance;
|
final Instance<T> _instance;
|
||||||
|
|
||||||
/// RU: Создаёт резолвер, оборачивающий значение [instance].
|
/// Wraps the given instance (sync or async) in a resolver.
|
||||||
/// ENG: Creates a resolver that wraps the given [instance].
|
|
||||||
InstanceResolver(this._instance);
|
InstanceResolver(this._instance);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -49,7 +91,6 @@ class InstanceResolver<T> implements BindingResolver<T> {
|
|||||||
@override
|
@override
|
||||||
Future<T> resolveAsync([_]) {
|
Future<T> resolveAsync([_]) {
|
||||||
if (_instance is Future<T>) return _instance;
|
if (_instance is Future<T>) return _instance;
|
||||||
|
|
||||||
return Future.value(_instance);
|
return Future.value(_instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,8 +101,23 @@ class InstanceResolver<T> implements BindingResolver<T> {
|
|||||||
bool get isSingleton => true;
|
bool get isSingleton => true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Резолвер, оборачивающий провайдер, с возможностью синглтон-кеширования.
|
/// Resolver for provider functions (sync/async/factory), with optional singleton caching.
|
||||||
/// ENG: Resolver that wraps a provider, with optional singleton caching.
|
/// Used for [Binding.toProvide], [Binding.toProvideWithParams], [Binding.singleton].
|
||||||
|
///
|
||||||
|
/// Examples:
|
||||||
|
/// ```dart
|
||||||
|
/// // No param, sync:
|
||||||
|
/// var r = ProviderResolver((_) => 5, withParams: false);
|
||||||
|
/// r.resolveSync(); // == 5
|
||||||
|
/// // With param:
|
||||||
|
/// var rp = ProviderResolver((p) => p * 2, withParams: true);
|
||||||
|
/// rp.resolveSync(2); // == 4
|
||||||
|
/// // Singleton:
|
||||||
|
/// r.toSingleton();
|
||||||
|
/// // Async:
|
||||||
|
/// var ra = ProviderResolver((_) async => await Future.value(10), withParams: false);
|
||||||
|
/// await ra.resolveAsync(); // == 10
|
||||||
|
/// ```
|
||||||
class ProviderResolver<T> implements BindingResolver<T> {
|
class ProviderResolver<T> implements BindingResolver<T> {
|
||||||
final ProviderWithParams<T> _provider;
|
final ProviderWithParams<T> _provider;
|
||||||
final bool _withParams;
|
final bool _withParams;
|
||||||
@@ -69,8 +125,7 @@ class ProviderResolver<T> implements BindingResolver<T> {
|
|||||||
FutureOr<T>? _cache;
|
FutureOr<T>? _cache;
|
||||||
bool _singleton = false;
|
bool _singleton = false;
|
||||||
|
|
||||||
/// RU: Создаёт резолвер из произвольной функции [raw], поддерживающей ноль или один параметр.
|
/// Creates a resolver from [provider], optionally accepting dynamic params.
|
||||||
/// ENG: Creates a resolver from arbitrary function [raw], supporting zero or one parameter.
|
|
||||||
ProviderResolver(
|
ProviderResolver(
|
||||||
ProviderWithParams<T> provider, {
|
ProviderWithParams<T> provider, {
|
||||||
required bool withParams,
|
required bool withParams,
|
||||||
@@ -80,16 +135,13 @@ class ProviderResolver<T> implements BindingResolver<T> {
|
|||||||
@override
|
@override
|
||||||
T resolveSync([dynamic params]) {
|
T resolveSync([dynamic params]) {
|
||||||
_checkParams(params);
|
_checkParams(params);
|
||||||
|
|
||||||
final result = _cache ?? _provider(params);
|
final result = _cache ?? _provider(params);
|
||||||
|
|
||||||
if (result is T) {
|
if (result is T) {
|
||||||
if (_singleton) {
|
if (_singleton) {
|
||||||
_cache ??= result;
|
_cache ??= result;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw StateError(
|
throw StateError(
|
||||||
'Provider [$_provider] return Future<$T>. Use resolveAsync() instead.',
|
'Provider [$_provider] return Future<$T>. Use resolveAsync() instead.',
|
||||||
);
|
);
|
||||||
@@ -98,14 +150,11 @@ class ProviderResolver<T> implements BindingResolver<T> {
|
|||||||
@override
|
@override
|
||||||
Future<T> resolveAsync([dynamic params]) {
|
Future<T> resolveAsync([dynamic params]) {
|
||||||
_checkParams(params);
|
_checkParams(params);
|
||||||
|
|
||||||
final result = _cache ?? _provider(params);
|
final result = _cache ?? _provider(params);
|
||||||
final target = result is Future<T> ? result : Future<T>.value(result);
|
final target = result is Future<T> ? result : Future<T>.value(result);
|
||||||
|
|
||||||
if (_singleton) {
|
if (_singleton) {
|
||||||
_cache ??= target;
|
_cache ??= target;
|
||||||
}
|
}
|
||||||
|
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,8 +166,7 @@ class ProviderResolver<T> implements BindingResolver<T> {
|
|||||||
@override
|
@override
|
||||||
bool get isSingleton => _singleton;
|
bool get isSingleton => _singleton;
|
||||||
|
|
||||||
/// RU: Проверяет, был ли передан параметр, если провайдер требует его.
|
/// Throws if params required but not supplied.
|
||||||
/// ENG: Checks if parameter is passed when the provider expects it.
|
|
||||||
void _checkParams(dynamic params) {
|
void _checkParams(dynamic params) {
|
||||||
if (_withParams && params == null) {
|
if (_withParams && params == null) {
|
||||||
throw StateError(
|
throw StateError(
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -12,19 +12,22 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import 'dart:collection';
|
import 'dart:collection';
|
||||||
import 'package:cherrypick/src/logger.dart';
|
import 'package:cherrypick/src/observer.dart';
|
||||||
import 'package:cherrypick/src/log_format.dart';
|
|
||||||
|
|
||||||
/// RU: Исключение, выбрасываемое при обнаружении циклической зависимости.
|
/// Exception thrown when a circular dependency is detected during dependency resolution.
|
||||||
/// ENG: Exception thrown when a circular dependency is detected.
|
///
|
||||||
|
/// Contains a [message] and the [dependencyChain] showing the resolution cycle.
|
||||||
|
///
|
||||||
|
/// Example diagnostic:
|
||||||
|
/// ```
|
||||||
|
/// CircularDependencyException: Circular dependency detected for A
|
||||||
|
/// Dependency chain: A -> B -> C -> A
|
||||||
|
/// ```
|
||||||
class CircularDependencyException implements Exception {
|
class CircularDependencyException implements Exception {
|
||||||
final String message;
|
final String message;
|
||||||
final List<String> dependencyChain;
|
final List<String> dependencyChain;
|
||||||
|
|
||||||
CircularDependencyException(this.message, this.dependencyChain) {
|
CircularDependencyException(this.message, this.dependencyChain);
|
||||||
// DEBUG
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String toString() {
|
String toString() {
|
||||||
@@ -33,134 +36,161 @@ class CircularDependencyException implements Exception {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Детектор циклических зависимостей для CherryPick DI контейнера.
|
/// Circular dependency detector for CherryPick DI containers.
|
||||||
/// ENG: Circular dependency detector for CherryPick DI container.
|
///
|
||||||
|
/// Tracks dependency resolution chains to detect and prevent infinite recursion caused by cycles.
|
||||||
|
/// Whenever a resolve chain re-enters a started dependency, a [CircularDependencyException] is thrown with the full chain.
|
||||||
|
///
|
||||||
|
/// This class is used internally, but you can interact with it through [CycleDetectionMixin].
|
||||||
|
///
|
||||||
|
/// Example usage (pseudocode):
|
||||||
|
/// ```dart
|
||||||
|
/// final detector = CycleDetector(observer: myObserver);
|
||||||
|
/// try {
|
||||||
|
/// detector.startResolving<A>();
|
||||||
|
/// // ... resolving A which depends on B, etc
|
||||||
|
/// detector.startResolving<B>();
|
||||||
|
/// detector.startResolving<A>(); // BOOM: throws exception
|
||||||
|
/// } finally {
|
||||||
|
/// detector.finishResolving<B>();
|
||||||
|
/// detector.finishResolving<A>();
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
class CycleDetector {
|
class CycleDetector {
|
||||||
final CherryPickLogger _logger;
|
final CherryPickObserver _observer;
|
||||||
final Set<String> _resolutionStack = HashSet<String>();
|
final Set<String> _resolutionStack = HashSet<String>();
|
||||||
final List<String> _resolutionHistory = [];
|
final List<String> _resolutionHistory = [];
|
||||||
|
|
||||||
CycleDetector({required CherryPickLogger logger}): _logger = logger;
|
CycleDetector({required CherryPickObserver observer}) : _observer = observer;
|
||||||
|
|
||||||
/// RU: Начинает отслеживание разрешения зависимости.
|
/// Starts tracking dependency resolution for type [T] and optional [named] qualifier.
|
||||||
/// ENG: Starts tracking dependency resolution.
|
///
|
||||||
///
|
/// Throws [CircularDependencyException] if a cycle is found.
|
||||||
/// Throws [CircularDependencyException] if circular dependency is detected.
|
|
||||||
void startResolving<T>({String? named}) {
|
void startResolving<T>({String? named}) {
|
||||||
final dependencyKey = _createDependencyKey<T>(named);
|
final dependencyKey = _createDependencyKey<T>(named);
|
||||||
print('[DEBUG] CycleDetector logger type=${_logger.runtimeType} hash=${_logger.hashCode}');
|
_observer.onDiagnostic(
|
||||||
_logger.info(formatLogMessage(
|
'CycleDetector startResolving: $dependencyKey',
|
||||||
type: 'CycleDetector',
|
details: {
|
||||||
name: dependencyKey.toString(),
|
'event': 'startResolving',
|
||||||
params: {'event': 'startResolving', 'stackSize': _resolutionStack.length},
|
'stackSize': _resolutionStack.length,
|
||||||
description: 'start resolving',
|
},
|
||||||
));
|
);
|
||||||
if (_resolutionStack.contains(dependencyKey)) {
|
if (_resolutionStack.contains(dependencyKey)) {
|
||||||
// Найдена циклическая зависимость
|
|
||||||
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
|
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
|
||||||
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||||
// print removed (trace)
|
_observer.onCycleDetected(cycle);
|
||||||
final msg = formatLogMessage(
|
_observer.onError('Cycle detected for $dependencyKey', null, null);
|
||||||
type: 'CycleDetector',
|
|
||||||
name: dependencyKey.toString(),
|
|
||||||
params: {'chain': cycle.join('->')},
|
|
||||||
description: 'cycle detected',
|
|
||||||
);
|
|
||||||
_logger.error(msg);
|
|
||||||
throw CircularDependencyException(
|
throw CircularDependencyException(
|
||||||
'Circular dependency detected for $dependencyKey',
|
'Circular dependency detected for $dependencyKey',
|
||||||
cycle,
|
cycle,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
_resolutionStack.add(dependencyKey);
|
_resolutionStack.add(dependencyKey);
|
||||||
_resolutionHistory.add(dependencyKey);
|
_resolutionHistory.add(dependencyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Завершает отслеживание разрешения зависимости.
|
/// Stops tracking dependency resolution for type [T] and optional [named] qualifier.
|
||||||
/// ENG: Finishes tracking dependency resolution.
|
/// Should always be called after [startResolving], including for errors.
|
||||||
void finishResolving<T>({String? named}) {
|
void finishResolving<T>({String? named}) {
|
||||||
final dependencyKey = _createDependencyKey<T>(named);
|
final dependencyKey = _createDependencyKey<T>(named);
|
||||||
_logger.info(formatLogMessage(
|
_observer.onDiagnostic(
|
||||||
type: 'CycleDetector',
|
'CycleDetector finishResolving: $dependencyKey',
|
||||||
name: dependencyKey.toString(),
|
details: {'event': 'finishResolving'},
|
||||||
params: {'event': 'finishResolving'},
|
);
|
||||||
description: 'finish resolving',
|
|
||||||
));
|
|
||||||
_resolutionStack.remove(dependencyKey);
|
_resolutionStack.remove(dependencyKey);
|
||||||
// Удаляем из истории только если это последний элемент
|
// Only remove from history if it's the last one
|
||||||
if (_resolutionHistory.isNotEmpty &&
|
if (_resolutionHistory.isNotEmpty && _resolutionHistory.last == dependencyKey) {
|
||||||
_resolutionHistory.last == dependencyKey) {
|
|
||||||
_resolutionHistory.removeLast();
|
_resolutionHistory.removeLast();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Очищает все состояние детектора.
|
/// Clears all resolution state and resets the cycle detector.
|
||||||
/// ENG: Clears all detector state.
|
|
||||||
void clear() {
|
void clear() {
|
||||||
_logger.info(formatLogMessage(
|
_observer.onDiagnostic(
|
||||||
type: 'CycleDetector',
|
'CycleDetector clear',
|
||||||
params: {'event': 'clear'},
|
details: {
|
||||||
description: 'resolution stack cleared',
|
'event': 'clear',
|
||||||
));
|
'description': 'resolution stack cleared',
|
||||||
|
},
|
||||||
|
);
|
||||||
_resolutionStack.clear();
|
_resolutionStack.clear();
|
||||||
_resolutionHistory.clear();
|
_resolutionHistory.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Проверяет, находится ли зависимость в процессе разрешения.
|
/// Returns true if dependency [T] (and [named], if specified) is being resolved right now.
|
||||||
/// ENG: Checks if dependency is currently being resolved.
|
|
||||||
bool isResolving<T>({String? named}) {
|
bool isResolving<T>({String? named}) {
|
||||||
final dependencyKey = _createDependencyKey<T>(named);
|
final dependencyKey = _createDependencyKey<T>(named);
|
||||||
return _resolutionStack.contains(dependencyKey);
|
return _resolutionStack.contains(dependencyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Возвращает текущую цепочку разрешения зависимостей.
|
/// Gets the current dependency resolution chain (for diagnostics or debugging).
|
||||||
/// ENG: Returns current dependency resolution chain.
|
|
||||||
List<String> get currentResolutionChain => List.unmodifiable(_resolutionHistory);
|
List<String> get currentResolutionChain => List.unmodifiable(_resolutionHistory);
|
||||||
|
|
||||||
/// RU: Создает уникальный ключ для зависимости.
|
/// Returns a unique string key for type [T] (+name).
|
||||||
/// ENG: Creates unique key for dependency.
|
|
||||||
String _createDependencyKey<T>(String? named) {
|
String _createDependencyKey<T>(String? named) {
|
||||||
final typeName = T.toString();
|
final typeName = T.toString();
|
||||||
return named != null ? '$typeName@$named' : typeName;
|
return named != null ? '$typeName@$named' : typeName;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Миксин для добавления поддержки обнаружения циклических зависимостей.
|
/// Mixin for adding circular dependency detection support to custom DI containers/classes.
|
||||||
/// ENG: Mixin for adding circular dependency detection support.
|
///
|
||||||
|
/// Fields:
|
||||||
|
/// - `observer`: must be implemented by your class (used for diagnostics and error reporting)
|
||||||
|
///
|
||||||
|
/// Example usage:
|
||||||
|
/// ```dart
|
||||||
|
/// class MyContainer with CycleDetectionMixin {
|
||||||
|
/// @override
|
||||||
|
/// CherryPickObserver get observer => myObserver;
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// final c = MyContainer();
|
||||||
|
/// c.enableCycleDetection();
|
||||||
|
/// c.withCycleDetection(String, null, () {
|
||||||
|
/// // ... dependency resolution code
|
||||||
|
/// });
|
||||||
|
/// ```
|
||||||
mixin CycleDetectionMixin {
|
mixin CycleDetectionMixin {
|
||||||
CycleDetector? _cycleDetector;
|
CycleDetector? _cycleDetector;
|
||||||
CherryPickLogger get logger;
|
CherryPickObserver get observer;
|
||||||
|
|
||||||
/// RU: Включает обнаружение циклических зависимостей.
|
/// Turns on circular dependency detection for this class/container.
|
||||||
/// ENG: Enables circular dependency detection.
|
|
||||||
void enableCycleDetection() {
|
void enableCycleDetection() {
|
||||||
_cycleDetector = CycleDetector(logger: logger);
|
_cycleDetector = CycleDetector(observer: observer);
|
||||||
logger.info(formatLogMessage(
|
observer.onDiagnostic(
|
||||||
type: 'CycleDetection',
|
'CycleDetection enabled',
|
||||||
params: {'event': 'enable'},
|
details: {
|
||||||
description: 'cycle detection enabled',
|
'event': 'enable',
|
||||||
));
|
'description': 'cycle detection enabled',
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Отключает обнаружение циклических зависимостей.
|
/// Shuts off detection and clears any cycle history for this container.
|
||||||
/// ENG: Disables circular dependency detection.
|
|
||||||
void disableCycleDetection() {
|
void disableCycleDetection() {
|
||||||
_cycleDetector?.clear();
|
_cycleDetector?.clear();
|
||||||
logger.info(formatLogMessage(
|
observer.onDiagnostic(
|
||||||
type: 'CycleDetection',
|
'CycleDetection disabled',
|
||||||
params: {'event': 'disable'},
|
details: {
|
||||||
description: 'cycle detection disabled',
|
'event': 'disable',
|
||||||
));
|
'description': 'cycle detection disabled',
|
||||||
|
},
|
||||||
|
);
|
||||||
_cycleDetector = null;
|
_cycleDetector = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Проверяет, включено ли обнаружение циклических зависимостей.
|
/// Returns true if detection is currently enabled.
|
||||||
/// ENG: Checks if circular dependency detection is enabled.
|
|
||||||
bool get isCycleDetectionEnabled => _cycleDetector != null;
|
bool get isCycleDetectionEnabled => _cycleDetector != null;
|
||||||
|
|
||||||
/// RU: Выполняет действие с отслеживанием циклических зависимостей.
|
/// Executes [action] while tracking for circular DI cycles for [dependencyType] and [named].
|
||||||
/// ENG: Executes action with circular dependency tracking.
|
///
|
||||||
|
/// Throws [CircularDependencyException] if a dependency cycle is detected.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// withCycleDetection(String, 'api', () => resolveApi());
|
||||||
|
/// ```
|
||||||
T withCycleDetection<T>(
|
T withCycleDetection<T>(
|
||||||
Type dependencyType,
|
Type dependencyType,
|
||||||
String? named,
|
String? named,
|
||||||
@@ -178,12 +208,8 @@ mixin CycleDetectionMixin {
|
|||||||
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
|
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
|
||||||
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
|
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
|
||||||
..add(dependencyKey);
|
..add(dependencyKey);
|
||||||
logger.error(formatLogMessage(
|
observer.onCycleDetected(cycle);
|
||||||
type: 'CycleDetector',
|
observer.onError('Cycle detected for $dependencyKey', null, null);
|
||||||
name: dependencyKey.toString(),
|
|
||||||
params: {'chain': cycle.join('->')},
|
|
||||||
description: 'cycle detected',
|
|
||||||
));
|
|
||||||
throw CircularDependencyException(
|
throw CircularDependencyException(
|
||||||
'Circular dependency detected for $dependencyKey',
|
'Circular dependency detected for $dependencyKey',
|
||||||
cycle,
|
cycle,
|
||||||
@@ -204,8 +230,7 @@ mixin CycleDetectionMixin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Возвращает текущую цепочку разрешения зависимостей.
|
/// Gets the current active dependency resolution chain.
|
||||||
/// ENG: Returns current dependency resolution chain.
|
|
||||||
List<String> get currentResolutionChain =>
|
List<String> get currentResolutionChain =>
|
||||||
_cycleDetector?.currentResolutionChain ?? [];
|
_cycleDetector?.currentResolutionChain ?? [];
|
||||||
}
|
}
|
||||||
|
|||||||
63
cherrypick/lib/src/disposable.dart
Normal file
63
cherrypick/lib/src/disposable.dart
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
//
|
||||||
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
// 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 the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
//
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
/// An interface for resources that require explicit cleanup, used by the CherryPick dependency injection container.
|
||||||
|
///
|
||||||
|
/// If an object implements [Disposable], the CherryPick DI container will automatically call [dispose]
|
||||||
|
/// when the corresponding scope is cleaned up. Use [Disposable] for closing streams, files, controllers, services, etc.
|
||||||
|
/// Both synchronous and asynchronous cleanup is supported:
|
||||||
|
/// - For sync disposables, implement [dispose] as a `void` or simply return nothing.
|
||||||
|
/// - For async disposables, implement [dispose] returning a [Future].
|
||||||
|
///
|
||||||
|
/// Example: Synchronous Disposable
|
||||||
|
/// ```dart
|
||||||
|
/// class MyLogger implements Disposable {
|
||||||
|
/// void dispose() {
|
||||||
|
/// print('Logger closed!');
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Example: Asynchronous Disposable
|
||||||
|
/// ```dart
|
||||||
|
/// class MyConnection implements Disposable {
|
||||||
|
/// @override
|
||||||
|
/// Future<void> dispose() async {
|
||||||
|
/// await connection.close();
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Usage with CherryPick DI Module
|
||||||
|
/// ```dart
|
||||||
|
/// final scope = openRootScope();
|
||||||
|
/// scope.installModules([
|
||||||
|
/// Module((b) {
|
||||||
|
/// b.bind<MyLogger>((_) => MyLogger());
|
||||||
|
/// b.bindAsync<MyConnection>((_) async => MyConnection());
|
||||||
|
/// }),
|
||||||
|
/// ]);
|
||||||
|
/// // ...
|
||||||
|
/// await scope.close(); // will automatically call dispose on all Disposables
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// This pattern ensures that all resources are released safely and automatically when the scope is destroyed.
|
||||||
|
abstract class Disposable {
|
||||||
|
/// Releases all resources held by this object.
|
||||||
|
///
|
||||||
|
/// Implement cleanup logic (closing streams, sockets, files, etc.) within this method.
|
||||||
|
/// Return a [Future] for async cleanup, or nothing (`void`) for synchronous cleanup.
|
||||||
|
FutureOr<void> dispose();
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -12,6 +12,28 @@
|
|||||||
//
|
//
|
||||||
import 'package:cherrypick/src/scope.dart';
|
import 'package:cherrypick/src/scope.dart';
|
||||||
|
|
||||||
|
/// Abstract factory interface for creating objects of type [T] using a [Scope].
|
||||||
|
///
|
||||||
|
/// Can be implemented for advanced dependency injection scenarios where
|
||||||
|
/// the resolution requires contextual information from the DI [Scope].
|
||||||
|
///
|
||||||
|
/// Often used to supply complex objects, runtime-bound services,
|
||||||
|
/// or objects depending on dynamic configuration.
|
||||||
|
///
|
||||||
|
/// Example usage:
|
||||||
|
/// ```dart
|
||||||
|
/// class MyServiceFactory implements Factory<MyService> {
|
||||||
|
/// @override
|
||||||
|
/// MyService createInstance(Scope scope) {
|
||||||
|
/// final db = scope.resolve<Database>(named: "main");
|
||||||
|
/// return MyService(db);
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // Usage in a module:
|
||||||
|
/// bind<MyService>().toProvide(() => MyServiceFactory().createInstance(scope));
|
||||||
|
/// ```
|
||||||
abstract class Factory<T> {
|
abstract class Factory<T> {
|
||||||
|
/// Implement this to provide an instance of [T], with access to the resolving [scope].
|
||||||
T createInstance(Scope scope);
|
T createInstance(Scope scope);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -13,36 +13,49 @@
|
|||||||
|
|
||||||
import 'dart:collection';
|
import 'dart:collection';
|
||||||
import 'package:cherrypick/cherrypick.dart';
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
import 'package:cherrypick/src/log_format.dart';
|
|
||||||
|
|
||||||
|
|
||||||
/// RU: Глобальный детектор циклических зависимостей для всей иерархии скоупов.
|
/// GlobalCycleDetector detects and prevents circular dependencies across an entire DI scope hierarchy.
|
||||||
/// ENG: Global circular dependency detector for entire scope hierarchy.
|
///
|
||||||
|
/// This is particularly important for modular/feature-based applications
|
||||||
|
/// where subscopes can introduce indirect cycles that span different scopes.
|
||||||
|
///
|
||||||
|
/// The detector tracks resolution chains and throws [CircularDependencyException]
|
||||||
|
/// when a cycle is found, showing the full chain (including scope context).
|
||||||
|
///
|
||||||
|
/// Example usage via [GlobalCycleDetectionMixin]:
|
||||||
|
/// ```dart
|
||||||
|
/// class MyScope with GlobalCycleDetectionMixin { /* ... */ }
|
||||||
|
///
|
||||||
|
/// final scope = MyScope();
|
||||||
|
/// scope.setScopeId('feature');
|
||||||
|
/// scope.enableGlobalCycleDetection();
|
||||||
|
///
|
||||||
|
/// scope.withGlobalCycleDetection(String, null, () {
|
||||||
|
/// // ... resolve dependencies here, will detect cross-scope cycles
|
||||||
|
/// });
|
||||||
|
/// ```
|
||||||
class GlobalCycleDetector {
|
class GlobalCycleDetector {
|
||||||
static GlobalCycleDetector? _instance;
|
static GlobalCycleDetector? _instance;
|
||||||
|
|
||||||
final CherryPickLogger _logger;
|
final CherryPickObserver _observer;
|
||||||
|
|
||||||
// Глобальный стек разрешения зависимостей
|
// Global set and chain history for all resolutions
|
||||||
final Set<String> _globalResolutionStack = HashSet<String>();
|
final Set<String> _globalResolutionStack = HashSet<String>();
|
||||||
|
|
||||||
// История разрешения для построения цепочки зависимостей
|
|
||||||
final List<String> _globalResolutionHistory = [];
|
final List<String> _globalResolutionHistory = [];
|
||||||
|
|
||||||
// Карта активных детекторов по скоупам
|
// Map of active detectors for subscopes (rarely used directly)
|
||||||
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>();
|
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>();
|
||||||
|
|
||||||
GlobalCycleDetector._internal({required CherryPickLogger logger}): _logger = logger;
|
GlobalCycleDetector._internal({required CherryPickObserver observer}): _observer = observer;
|
||||||
|
|
||||||
/// RU: Получить единственный экземпляр глобального детектора.
|
/// Returns the singleton global detector instance, initializing it if needed.
|
||||||
/// ENG: Get singleton instance of global detector.
|
|
||||||
static GlobalCycleDetector get instance {
|
static GlobalCycleDetector get instance {
|
||||||
_instance ??= GlobalCycleDetector._internal(logger: CherryPick.globalLogger);
|
_instance ??= GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
|
||||||
return _instance!;
|
return _instance!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Сбросить глобальный детектор (полезно для тестов).
|
/// Reset internal state (useful for testing).
|
||||||
/// ENG: Reset global detector (useful for tests).
|
|
||||||
static void reset() {
|
static void reset() {
|
||||||
_instance?._globalResolutionStack.clear();
|
_instance?._globalResolutionStack.clear();
|
||||||
_instance?._globalResolutionHistory.clear();
|
_instance?._globalResolutionHistory.clear();
|
||||||
@@ -50,46 +63,38 @@ class GlobalCycleDetector {
|
|||||||
_instance = null;
|
_instance = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Начать отслеживание разрешения зависимости в глобальном контексте.
|
/// Start tracking resolution of dependency [T] with optional [named] and [scopeId].
|
||||||
/// ENG: Start tracking dependency resolution in global context.
|
/// Throws [CircularDependencyException] on cycle.
|
||||||
void startGlobalResolving<T>({String? named, String? scopeId}) {
|
void startGlobalResolving<T>({String? named, String? scopeId}) {
|
||||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||||
|
|
||||||
if (_globalResolutionStack.contains(dependencyKey)) {
|
if (_globalResolutionStack.contains(dependencyKey)) {
|
||||||
// Найдена глобальная циклическая зависимость
|
|
||||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||||
_logger.error(formatLogMessage(
|
_observer.onCycleDetected(cycle, scopeName: scopeId);
|
||||||
type: 'CycleDetector',
|
_observer.onError('Global circular dependency detected for $dependencyKey', null, null);
|
||||||
name: dependencyKey.toString(),
|
|
||||||
params: {'chain': cycle.join('->')},
|
|
||||||
description: 'cycle detected',
|
|
||||||
));
|
|
||||||
throw CircularDependencyException(
|
throw CircularDependencyException(
|
||||||
'Global circular dependency detected for $dependencyKey',
|
'Global circular dependency detected for $dependencyKey',
|
||||||
cycle,
|
cycle,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
_globalResolutionStack.add(dependencyKey);
|
_globalResolutionStack.add(dependencyKey);
|
||||||
_globalResolutionHistory.add(dependencyKey);
|
_globalResolutionHistory.add(dependencyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Завершить отслеживание разрешения зависимости в глобальном контексте.
|
/// Finish tracking a dependency. Should always be called after [startGlobalResolving].
|
||||||
/// ENG: Finish tracking dependency resolution in global context.
|
|
||||||
void finishGlobalResolving<T>({String? named, String? scopeId}) {
|
void finishGlobalResolving<T>({String? named, String? scopeId}) {
|
||||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||||
_globalResolutionStack.remove(dependencyKey);
|
_globalResolutionStack.remove(dependencyKey);
|
||||||
|
|
||||||
// Удаляем из истории только если это последний элемент
|
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) {
|
||||||
if (_globalResolutionHistory.isNotEmpty &&
|
|
||||||
_globalResolutionHistory.last == dependencyKey) {
|
|
||||||
_globalResolutionHistory.removeLast();
|
_globalResolutionHistory.removeLast();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Выполнить действие с глобальным отслеживанием циклических зависимостей.
|
/// Internally execute [action] with global cycle detection for [dependencyType], [named], [scopeId].
|
||||||
/// ENG: Execute action with global circular dependency tracking.
|
/// Throws [CircularDependencyException] on cycle.
|
||||||
T withGlobalCycleDetection<T>(
|
T withGlobalCycleDetection<T>(
|
||||||
Type dependencyType,
|
Type dependencyType,
|
||||||
String? named,
|
String? named,
|
||||||
@@ -97,17 +102,12 @@ class GlobalCycleDetector {
|
|||||||
T Function() action,
|
T Function() action,
|
||||||
) {
|
) {
|
||||||
final dependencyKey = _createDependencyKeyFromType(dependencyType, named, scopeId);
|
final dependencyKey = _createDependencyKeyFromType(dependencyType, named, scopeId);
|
||||||
|
|
||||||
if (_globalResolutionStack.contains(dependencyKey)) {
|
if (_globalResolutionStack.contains(dependencyKey)) {
|
||||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
|
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||||
..add(dependencyKey);
|
_observer.onCycleDetected(cycle, scopeName: scopeId);
|
||||||
_logger.error(formatLogMessage(
|
_observer.onError('Global circular dependency detected for $dependencyKey', null, null);
|
||||||
type: 'CycleDetector',
|
|
||||||
name: dependencyKey.toString(),
|
|
||||||
params: {'chain': cycle.join('->')},
|
|
||||||
description: 'cycle detected',
|
|
||||||
));
|
|
||||||
throw CircularDependencyException(
|
throw CircularDependencyException(
|
||||||
'Global circular dependency detected for $dependencyKey',
|
'Global circular dependency detected for $dependencyKey',
|
||||||
cycle,
|
cycle,
|
||||||
@@ -121,38 +121,32 @@ class GlobalCycleDetector {
|
|||||||
return action();
|
return action();
|
||||||
} finally {
|
} finally {
|
||||||
_globalResolutionStack.remove(dependencyKey);
|
_globalResolutionStack.remove(dependencyKey);
|
||||||
if (_globalResolutionHistory.isNotEmpty &&
|
if (_globalResolutionHistory.isNotEmpty && _globalResolutionHistory.last == dependencyKey) {
|
||||||
_globalResolutionHistory.last == dependencyKey) {
|
|
||||||
_globalResolutionHistory.removeLast();
|
_globalResolutionHistory.removeLast();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Получить детектор для конкретного скоупа.
|
/// Get per-scope detector (not usually needed by consumers).
|
||||||
/// ENG: Get detector for specific scope.
|
|
||||||
CycleDetector getScopeDetector(String scopeId) {
|
CycleDetector getScopeDetector(String scopeId) {
|
||||||
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(logger: CherryPick.globalLogger));
|
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(observer: CherryPick.globalObserver));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Удалить детектор для скоупа.
|
/// Remove detector for a given scope.
|
||||||
/// ENG: Remove detector for scope.
|
|
||||||
void removeScopeDetector(String scopeId) {
|
void removeScopeDetector(String scopeId) {
|
||||||
_scopeDetectors.remove(scopeId);
|
_scopeDetectors.remove(scopeId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Проверить, находится ли зависимость в процессе глобального разрешения.
|
/// Returns true if dependency [T] is currently being resolved in the global scope.
|
||||||
/// ENG: Check if dependency is currently being resolved globally.
|
|
||||||
bool isGloballyResolving<T>({String? named, String? scopeId}) {
|
bool isGloballyResolving<T>({String? named, String? scopeId}) {
|
||||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||||
return _globalResolutionStack.contains(dependencyKey);
|
return _globalResolutionStack.contains(dependencyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Получить текущую глобальную цепочку разрешения зависимостей.
|
/// Get current global dependency resolution chain (for debugging or diagnostics).
|
||||||
/// ENG: Get current global dependency resolution chain.
|
|
||||||
List<String> get globalResolutionChain => List.unmodifiable(_globalResolutionHistory);
|
List<String> get globalResolutionChain => List.unmodifiable(_globalResolutionHistory);
|
||||||
|
|
||||||
/// RU: Очистить все состояние детектора.
|
/// Clears all global and per-scope state in this detector.
|
||||||
/// ENG: Clear all detector state.
|
|
||||||
void clear() {
|
void clear() {
|
||||||
_globalResolutionStack.clear();
|
_globalResolutionStack.clear();
|
||||||
_globalResolutionHistory.clear();
|
_globalResolutionHistory.clear();
|
||||||
@@ -162,14 +156,7 @@ class GlobalCycleDetector {
|
|||||||
|
|
||||||
void _detectorClear(detector) => detector.clear();
|
void _detectorClear(detector) => detector.clear();
|
||||||
|
|
||||||
/// RU: Создать уникальный ключ для зависимости с учетом скоупа.
|
/// Creates a unique dependency key string including scope and name (for diagnostics/cycle checks).
|
||||||
/// ENG: Create unique key for dependency including scope.
|
|
||||||
//String _createDependencyKey<T>(String? named, String? scopeId) {
|
|
||||||
// return _createDependencyKeyFromType(T, named, scopeId);
|
|
||||||
//}
|
|
||||||
|
|
||||||
/// RU: Создать уникальный ключ для зависимости по типу с учетом скоупа.
|
|
||||||
/// ENG: Create unique key for dependency by type including scope.
|
|
||||||
String _createDependencyKeyFromType(Type type, String? named, String? scopeId) {
|
String _createDependencyKeyFromType(Type type, String? named, String? scopeId) {
|
||||||
final typeName = type.toString();
|
final typeName = type.toString();
|
||||||
final namePrefix = named != null ? '@$named' : '';
|
final namePrefix = named != null ? '@$named' : '';
|
||||||
@@ -178,40 +165,53 @@ class GlobalCycleDetector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Улучшенный миксин для глобального обнаружения циклических зависимостей.
|
/// Enhanced mixin for global circular dependency detection, to be mixed into
|
||||||
/// ENG: Enhanced mixin for global circular dependency detection.
|
/// DI scopes or containers that want cross-scope protection.
|
||||||
|
///
|
||||||
|
/// Typical usage pattern:
|
||||||
|
/// ```dart
|
||||||
|
/// class MySubscope with GlobalCycleDetectionMixin { ... }
|
||||||
|
///
|
||||||
|
/// final scope = MySubscope();
|
||||||
|
/// scope.setScopeId('user_profile');
|
||||||
|
/// scope.enableGlobalCycleDetection();
|
||||||
|
///
|
||||||
|
/// scope.withGlobalCycleDetection(UserService, null, () {
|
||||||
|
/// // ... resolve user service and friends, auto-detects global cycles
|
||||||
|
/// });
|
||||||
|
/// ```
|
||||||
mixin GlobalCycleDetectionMixin {
|
mixin GlobalCycleDetectionMixin {
|
||||||
String? _scopeId;
|
String? _scopeId;
|
||||||
bool _globalCycleDetectionEnabled = false;
|
bool _globalCycleDetectionEnabled = false;
|
||||||
|
|
||||||
/// RU: Установить идентификатор скоупа для глобального отслеживания.
|
/// Set the scope's unique identifier for global tracking (should be called at scope initialization).
|
||||||
/// ENG: Set scope identifier for global tracking.
|
|
||||||
void setScopeId(String scopeId) {
|
void setScopeId(String scopeId) {
|
||||||
_scopeId = scopeId;
|
_scopeId = scopeId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Получить идентификатор скоупа.
|
/// Get the scope's id, if configured.
|
||||||
/// ENG: Get scope identifier.
|
|
||||||
String? get scopeId => _scopeId;
|
String? get scopeId => _scopeId;
|
||||||
|
|
||||||
/// RU: Включить глобальное обнаружение циклических зависимостей.
|
/// Enable global cross-scope circular dependency detection.
|
||||||
/// ENG: Enable global circular dependency detection.
|
|
||||||
void enableGlobalCycleDetection() {
|
void enableGlobalCycleDetection() {
|
||||||
_globalCycleDetectionEnabled = true;
|
_globalCycleDetectionEnabled = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Отключить глобальное обнаружение циклических зависимостей.
|
/// Disable global cycle detection (no cycle checks will be performed globally).
|
||||||
/// ENG: Disable global circular dependency detection.
|
|
||||||
void disableGlobalCycleDetection() {
|
void disableGlobalCycleDetection() {
|
||||||
_globalCycleDetectionEnabled = false;
|
_globalCycleDetectionEnabled = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Проверить, включено ли глобальное обнаружение циклических зависимостей.
|
/// Returns true if global cycle detection is currently enabled for this scope/container.
|
||||||
/// ENG: Check if global circular dependency detection is enabled.
|
|
||||||
bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
||||||
|
|
||||||
/// RU: Выполнить действие с глобальным отслеживанием циклических зависимостей.
|
/// Executes [action] with global cycle detection for [dependencyType] and [named].
|
||||||
/// ENG: Execute action with global circular dependency tracking.
|
/// Throws [CircularDependencyException] if a cycle is detected.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// withGlobalCycleDetection(UserService, null, () => resolveUser());
|
||||||
|
/// ```
|
||||||
T withGlobalCycleDetection<T>(
|
T withGlobalCycleDetection<T>(
|
||||||
Type dependencyType,
|
Type dependencyType,
|
||||||
String? named,
|
String? named,
|
||||||
@@ -229,8 +229,7 @@ mixin GlobalCycleDetectionMixin {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Получить текущую глобальную цепочку разрешения зависимостей.
|
/// Access the current global dependency resolution chain for diagnostics.
|
||||||
/// ENG: Get current global dependency resolution chain.
|
List<String> get globalResolutionChain =>
|
||||||
List<String> get globalResolutionChain =>
|
|
||||||
GlobalCycleDetector.instance.globalResolutionChain;
|
GlobalCycleDetector.instance.globalResolutionChain;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
import 'package:cherrypick/src/scope.dart';
|
import 'package:cherrypick/src/scope.dart';
|
||||||
import 'package:cherrypick/src/global_cycle_detector.dart';
|
import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||||
import 'package:cherrypick/src/logger.dart';
|
import 'package:cherrypick/src/observer.dart';
|
||||||
import 'package:meta/meta.dart';
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ Scope? _rootScope;
|
|||||||
/// Global logger for all [Scope]s managed by [CherryPick].
|
/// Global logger for all [Scope]s managed by [CherryPick].
|
||||||
///
|
///
|
||||||
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
|
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
|
||||||
CherryPickLogger _globalLogger = const SilentLogger();
|
CherryPickObserver _globalObserver = SilentCherryPickObserver();
|
||||||
|
|
||||||
/// Whether global local-cycle detection is enabled for all Scopes ([Scope.enableCycleDetection]).
|
/// Whether global local-cycle detection is enabled for all Scopes ([Scope.enableCycleDetection]).
|
||||||
bool _globalCycleDetectionEnabled = false;
|
bool _globalCycleDetectionEnabled = false;
|
||||||
@@ -59,12 +59,12 @@ class CherryPick {
|
|||||||
/// ```dart
|
/// ```dart
|
||||||
/// CherryPick.setGlobalLogger(DefaultLogger());
|
/// CherryPick.setGlobalLogger(DefaultLogger());
|
||||||
/// ```
|
/// ```
|
||||||
static void setGlobalLogger(CherryPickLogger logger) {
|
static void setGlobalObserver(CherryPickObserver observer) {
|
||||||
_globalLogger = logger;
|
_globalObserver = observer;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the current global logger used by CherryPick.
|
/// Returns the current global logger used by CherryPick.
|
||||||
static CherryPickLogger get globalLogger => _globalLogger;
|
static CherryPickObserver get globalObserver => _globalObserver;
|
||||||
|
|
||||||
/// Returns the singleton root [Scope], creating it if needed.
|
/// Returns the singleton root [Scope], creating it if needed.
|
||||||
///
|
///
|
||||||
@@ -75,7 +75,7 @@ class CherryPick {
|
|||||||
/// final root = CherryPick.openRootScope();
|
/// final root = CherryPick.openRootScope();
|
||||||
/// ```
|
/// ```
|
||||||
static Scope openRootScope() {
|
static Scope openRootScope() {
|
||||||
_rootScope ??= Scope(null, logger: _globalLogger);
|
_rootScope ??= Scope(null, observer: _globalObserver);
|
||||||
// Apply cycle detection settings
|
// Apply cycle detection settings
|
||||||
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
|
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
|
||||||
_rootScope!.enableCycleDetection();
|
_rootScope!.enableCycleDetection();
|
||||||
@@ -94,8 +94,11 @@ class CherryPick {
|
|||||||
/// ```dart
|
/// ```dart
|
||||||
/// CherryPick.closeRootScope();
|
/// CherryPick.closeRootScope();
|
||||||
/// ```
|
/// ```
|
||||||
static void closeRootScope() {
|
static Future<void> closeRootScope() async {
|
||||||
_rootScope = null;
|
if (_rootScope != null) {
|
||||||
|
await _rootScope!.dispose(); // Автоматический вызов dispose для rootScope!
|
||||||
|
_rootScope = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
|
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
|
||||||
@@ -249,9 +252,9 @@ class CherryPick {
|
|||||||
/// CherryPick.closeScope(scopeName: 'network.super.api');
|
/// CherryPick.closeScope(scopeName: 'network.super.api');
|
||||||
/// ```
|
/// ```
|
||||||
@experimental
|
@experimental
|
||||||
static void closeScope({String scopeName = '', String separator = '.'}) {
|
static Future<void> closeScope({String scopeName = '', String separator = '.'}) async {
|
||||||
if (scopeName.isEmpty) {
|
if (scopeName.isEmpty) {
|
||||||
closeRootScope();
|
await closeRootScope();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final nameParts = scopeName.split(separator);
|
final nameParts = scopeName.split(separator);
|
||||||
@@ -264,9 +267,9 @@ class CherryPick {
|
|||||||
openRootScope(),
|
openRootScope(),
|
||||||
(Scope previous, String element) => previous.openSubScope(element)
|
(Scope previous, String element) => previous.openSubScope(element)
|
||||||
);
|
);
|
||||||
scope.closeSubScope(lastPart);
|
await scope.closeSubScope(lastPart);
|
||||||
} else {
|
} else {
|
||||||
openRootScope().closeSubScope(nameParts.first);
|
await openRootScope().closeSubScope(nameParts.first);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
//
|
|
||||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
// 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 the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
//
|
|
||||||
|
|
||||||
|
|
||||||
/// Formats a log message string for CherryPick's logging system.
|
|
||||||
///
|
|
||||||
/// This function provides a unified structure for framework logs (info, warn, error, debug, etc.),
|
|
||||||
/// making it easier to parse and analyze events related to DI operations such as resolving bindings,
|
|
||||||
/// scope creation, module installation, etc.
|
|
||||||
///
|
|
||||||
/// All parameters except [name] and [params] are required.
|
|
||||||
///
|
|
||||||
/// Example:
|
|
||||||
/// ```dart
|
|
||||||
/// final msg = formatLogMessage(
|
|
||||||
/// type: 'Binding',
|
|
||||||
/// name: 'MyService',
|
|
||||||
/// params: {'parent': 'AppModule', 'lifecycle': 'singleton'},
|
|
||||||
/// description: 'created',
|
|
||||||
/// );
|
|
||||||
/// // Result: [Binding:MyService] parent=AppModule lifecycle=singleton created
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Parameters:
|
|
||||||
/// - [type]: The type of the log event subject (e.g., 'Binding', 'Scope', 'Module'). Required.
|
|
||||||
/// - [name]: Optional name of the subject (binding/scope/module) to disambiguate multiple instances/objects.
|
|
||||||
/// - [params]: Optional map for additional context (e.g., id, parent, lifecycle, named, etc.).
|
|
||||||
/// - [description]: Concise description of the event. Required.
|
|
||||||
///
|
|
||||||
/// Returns a structured string:
|
|
||||||
/// [type(:name)] param1=val1 param2=val2 ... description
|
|
||||||
String formatLogMessage({
|
|
||||||
required String type, // Binding, Scope, Module, ...
|
|
||||||
String? name, // Имя binding/scope/module
|
|
||||||
Map<String, Object?>? params, // Дополнительные параметры (id, parent, named и др.)
|
|
||||||
required String description, // Краткое описание события
|
|
||||||
}) {
|
|
||||||
final label = name != null ? '$type:$name' : type;
|
|
||||||
final paramsStr = (params != null && params.isNotEmpty)
|
|
||||||
? params.entries.map((e) => '${e.key}=${e.value}').join(' ')
|
|
||||||
: '';
|
|
||||||
return '[$label]'
|
|
||||||
'${paramsStr.isNotEmpty ? ' $paramsStr' : ''}'
|
|
||||||
' $description';
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
//
|
|
||||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
// 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 the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
//
|
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// CherryPickLogger — интерфейс для логирования событий DI в CherryPick.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// Interface for dependency injection (DI) logger in CherryPick. Allows you to
|
|
||||||
/// receive information about the internal events and errors in the DI system.
|
|
||||||
/// Your implementation can use any logging framework or UI.
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// Интерфейс логгера для DI-контейнера CherryPick. Позволяет получать
|
|
||||||
/// сообщения о работе DI-контейнера, его ошибках и событиях, и
|
|
||||||
/// интегрировать любые готовые решения для логирования/сбора ошибок.
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
abstract class CherryPickLogger {
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// info — Информационное сообщение.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// Logs an informational message about DI operation or state.
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// Логирование информационного сообщения о событиях DI.
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
void info(String message);
|
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// warn — Предупреждение.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// Logs a warning related to DI events (for example, possible misconfiguration).
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// Логирование предупреждения, связанного с DI (например, возможная ошибка
|
|
||||||
/// конфигурации).
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
void warn(String message);
|
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// error — Ошибка.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// Logs an error message, may include error object and stack trace.
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// Логирование ошибки, дополнительно может содержать объект ошибки
|
|
||||||
/// и StackTrace.
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
void error(String message, [Object? error, StackTrace? stackTrace]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// SilentLogger — «тихий» логгер CherryPick. Сообщения игнорируются.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// SilentLogger ignores all log messages. Used by default in production to
|
|
||||||
/// avoid polluting logs with DI events.
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// SilentLogger игнорирует все события логгирования. Используется по умолчанию
|
|
||||||
/// на production, чтобы не засорять логи техническими сообщениями DI.
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
class SilentLogger implements CherryPickLogger {
|
|
||||||
const SilentLogger();
|
|
||||||
@override
|
|
||||||
void info(String message) {}
|
|
||||||
@override
|
|
||||||
void warn(String message) {}
|
|
||||||
@override
|
|
||||||
void error(String message, [Object? error, StackTrace? stackTrace]) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
/// PrintLogger — логгер CherryPick, выводящий все сообщения через print.
|
|
||||||
///
|
|
||||||
/// ENGLISH:
|
|
||||||
/// PrintLogger outputs all log messages to the console using `print()`.
|
|
||||||
/// Suitable for debugging, prototyping, or simple console applications.
|
|
||||||
///
|
|
||||||
/// RUSSIAN:
|
|
||||||
/// PrintLogger выводит все сообщения (info, warn, error) в консоль через print.
|
|
||||||
/// Удобен для отладки или консольных приложений.
|
|
||||||
/// ----------------------------------------------------------------------------
|
|
||||||
class PrintLogger implements CherryPickLogger {
|
|
||||||
const PrintLogger();
|
|
||||||
@override
|
|
||||||
void info(String message) => print('[info][CherryPick] $message');
|
|
||||||
@override
|
|
||||||
void warn(String message) => print('[warn][CherryPick] $message');
|
|
||||||
@override
|
|
||||||
void error(String message, [Object? error, StackTrace? stackTrace]) {
|
|
||||||
print('[error][CherryPick] $message');
|
|
||||||
if (error != null) print(' error: $error');
|
|
||||||
if (stackTrace != null) print(' stack: $stackTrace');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -15,39 +15,71 @@ import 'dart:collection';
|
|||||||
import 'package:cherrypick/src/binding.dart';
|
import 'package:cherrypick/src/binding.dart';
|
||||||
import 'package:cherrypick/src/scope.dart';
|
import 'package:cherrypick/src/scope.dart';
|
||||||
|
|
||||||
/// RU: Класс Module является основой для пользовательских модулей.
|
/// Represents a DI module—a reusable group of dependency bindings.
|
||||||
/// Этот класс нужен для инициализации [Scope].
|
///
|
||||||
///
|
/// Extend [Module] to declaratively group related [Binding] definitions,
|
||||||
/// RU: The Module class is the basis for custom modules.
|
/// then install your module(s) into a [Scope] for dependency resolution.
|
||||||
/// This class is needed to initialize [Scope].
|
///
|
||||||
|
/// Modules make it easier to organize your DI configuration for features, layers,
|
||||||
|
/// infrastructure, or integration, and support modular app architecture.
|
||||||
|
///
|
||||||
|
/// Usage example:
|
||||||
|
/// ```dart
|
||||||
|
/// class AppModule extends Module {
|
||||||
|
/// @override
|
||||||
|
/// void builder(Scope currentScope) {
|
||||||
|
/// bind<NetworkService>().toProvide(() => NetworkService());
|
||||||
|
/// bind<AuthService>().toProvide(() => AuthService(currentScope.resolve<NetworkService>()));
|
||||||
|
/// bind<Config>().toInstance(Config.dev());
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // Installing the module into the root DI scope:
|
||||||
|
/// final rootScope = CherryPick.openRootScope();
|
||||||
|
/// rootScope.installModules([AppModule()]);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Combine several modules and submodules to implement scalable architectures.
|
||||||
///
|
///
|
||||||
abstract class Module {
|
abstract class Module {
|
||||||
final Set<Binding> _bindingSet = HashSet();
|
final Set<Binding> _bindingSet = HashSet();
|
||||||
|
|
||||||
/// RU: Метод добавляет в коллекцию модуля [Binding] экземпляр.
|
/// Begins the declaration of a new binding within this module.
|
||||||
///
|
///
|
||||||
/// ENG: The method adds an instance to the collection of the [Binding] module.
|
/// Typically used within [builder] to register all needed dependency bindings.
|
||||||
///
|
///
|
||||||
/// return [Binding<T>]
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// bind<Api>().toProvide(() => MockApi());
|
||||||
|
/// bind<Config>().toInstance(Config.dev());
|
||||||
|
/// ```
|
||||||
Binding<T> bind<T>() {
|
Binding<T> bind<T>() {
|
||||||
final binding = Binding<T>();
|
final binding = Binding<T>();
|
||||||
_bindingSet.add(binding);
|
_bindingSet.add(binding);
|
||||||
return binding;
|
return binding;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Метод возвращает коллекцию [Binding] экземпляров.
|
/// Returns the set of all [Binding] instances registered in this module.
|
||||||
///
|
///
|
||||||
/// ENG: The method returns a collection of [Binding] instances.
|
/// This is typically used internally by [Scope] during module installation,
|
||||||
///
|
/// but can also be used for diagnostics or introspection.
|
||||||
/// return [Set<Binding>]
|
|
||||||
Set<Binding> get bindingSet => _bindingSet;
|
Set<Binding> get bindingSet => _bindingSet;
|
||||||
|
|
||||||
/// RU: Абстрактный метод для инициализации пользовательских экземпляров.
|
/// Abstract method where all dependency bindings are registered.
|
||||||
/// В этом методе осуществляется конфигурация зависимостей.
|
|
||||||
///
|
///
|
||||||
/// ENG: Abstract method for initializing custom instances.
|
/// Override this method in your custom module subclass to declare
|
||||||
/// This method configures dependencies.
|
/// all dependency bindings to be provided by this module.
|
||||||
///
|
///
|
||||||
/// return [void]
|
/// The provided [currentScope] can be used for resolving other dependencies,
|
||||||
|
/// accessing configuration, or controlling binding behavior dynamically.
|
||||||
|
///
|
||||||
|
/// Example (with dependency chaining):
|
||||||
|
/// ```dart
|
||||||
|
/// @override
|
||||||
|
/// void builder(Scope currentScope) {
|
||||||
|
/// bind<ApiClient>().toProvide(() => RestApi());
|
||||||
|
/// bind<UserRepo>().toProvide(() => UserRepo(currentScope.resolve<ApiClient>()));
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
void builder(Scope currentScope);
|
void builder(Scope currentScope);
|
||||||
}
|
}
|
||||||
|
|||||||
236
cherrypick/lib/src/observer.dart
Normal file
236
cherrypick/lib/src/observer.dart
Normal file
@@ -0,0 +1,236 @@
|
|||||||
|
//
|
||||||
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
// 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 the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
//
|
||||||
|
|
||||||
|
/// An abstract Observer for CherryPick DI container events.
|
||||||
|
///
|
||||||
|
/// Extend this class to react to and log various events inside the CherryPick Dependency Injection container.
|
||||||
|
/// Allows monitoring of registration, creation, disposal, module changes, cache hits/misses, cycles, and
|
||||||
|
/// errors/warnings for improved diagnostics and debugging.
|
||||||
|
///
|
||||||
|
/// All methods have detailed event information, including name, type, scope, and other arguments.
|
||||||
|
///
|
||||||
|
/// Example: Logging and debugging container events
|
||||||
|
/// ```dart
|
||||||
|
/// final CherryPickObserver observer = PrintCherryPickObserver();
|
||||||
|
/// // Pass observer to CherryPick during setup
|
||||||
|
/// CherryPick.openRootScope(observer: observer);
|
||||||
|
/// ```
|
||||||
|
abstract class CherryPickObserver {
|
||||||
|
// === Registration and instance lifecycle ===
|
||||||
|
/// Called when a binding is registered within the container (new dependency mapping).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onBindingRegistered('MyService', MyService, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onBindingRegistered(String name, Type type, {String? scopeName});
|
||||||
|
|
||||||
|
/// Called when an instance is requested (before it is created or retrieved from cache).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onInstanceRequested('MyService', MyService, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onInstanceRequested(String name, Type type, {String? scopeName});
|
||||||
|
|
||||||
|
/// Called when a new instance is successfully created.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onInstanceCreated('MyService', MyService, instance, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName});
|
||||||
|
|
||||||
|
/// Called when an instance is disposed (removed from cache and/or finalized).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onInstanceDisposed('MyService', MyService, instance, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName});
|
||||||
|
|
||||||
|
// === Module events ===
|
||||||
|
/// Called when modules are installed into the container.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onModulesInstalled(['NetworkModule', 'RepositoryModule'], scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onModulesInstalled(List<String> moduleNames, {String? scopeName});
|
||||||
|
|
||||||
|
/// Called when modules are removed from the container.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onModulesRemoved(['RepositoryModule'], scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onModulesRemoved(List<String> moduleNames, {String? scopeName});
|
||||||
|
|
||||||
|
// === Scope lifecycle ===
|
||||||
|
/// Called when a new DI scope is opened (for example, starting a new feature or screen).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onScopeOpened('user-session');
|
||||||
|
/// ```
|
||||||
|
void onScopeOpened(String name);
|
||||||
|
|
||||||
|
/// Called when an existing DI scope is closed.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onScopeClosed('user-session');
|
||||||
|
/// ```
|
||||||
|
void onScopeClosed(String name);
|
||||||
|
|
||||||
|
// === Cycle detection ===
|
||||||
|
/// Called if a dependency cycle is detected during resolution.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onCycleDetected(['A', 'B', 'C', 'A'], scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onCycleDetected(List<String> chain, {String? scopeName});
|
||||||
|
|
||||||
|
// === Cache events ===
|
||||||
|
/// Called when an instance is found in the cache.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onCacheHit('MyService', MyService, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onCacheHit(String name, Type type, {String? scopeName});
|
||||||
|
|
||||||
|
/// Called when an instance is not found in the cache and should be created.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onCacheMiss('MyService', MyService, scopeName: 'root');
|
||||||
|
/// ```
|
||||||
|
void onCacheMiss(String name, Type type, {String? scopeName});
|
||||||
|
|
||||||
|
// === Diagnostic ===
|
||||||
|
/// Used for custom diagnostic and debug messages.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onDiagnostic('Cache cleared', details: detailsObj);
|
||||||
|
/// ```
|
||||||
|
void onDiagnostic(String message, {Object? details});
|
||||||
|
|
||||||
|
// === Warnings & errors ===
|
||||||
|
/// Called on non-fatal, recoverable DI container warnings.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onWarning('Binding override', details: {...});
|
||||||
|
/// ```
|
||||||
|
void onWarning(String message, {Object? details});
|
||||||
|
|
||||||
|
/// Called on error (typically exceptions thrown during resolution, instantiation, or disposal).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// observer.onError('Failed to resolve dependency', errorObj, stackTraceObj);
|
||||||
|
/// ```
|
||||||
|
void onError(String message, Object? error, StackTrace? stackTrace);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Diagnostic/Debug observer that prints all events
|
||||||
|
class PrintCherryPickObserver implements CherryPickObserver {
|
||||||
|
@override
|
||||||
|
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||||
|
print('[binding][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onInstanceRequested(String name, Type type, {String? scopeName}) =>
|
||||||
|
print('[request][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) =>
|
||||||
|
print('[create][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) =>
|
||||||
|
print('[dispose][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onModulesInstalled(List<String> modules, {String? scopeName}) =>
|
||||||
|
print('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||||
|
@override
|
||||||
|
void onModulesRemoved(List<String> modules, {String? scopeName}) =>
|
||||||
|
print('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onScopeOpened(String name) => print('[scope opened][CherryPick] $name');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onScopeClosed(String name) => print('[scope closed][CherryPick] $name');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onCycleDetected(List<String> chain, {String? scopeName}) =>
|
||||||
|
print('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onCacheHit(String name, Type type, {String? scopeName}) =>
|
||||||
|
print('[cache hit][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
@override
|
||||||
|
void onCacheMiss(String name, Type type, {String? scopeName}) =>
|
||||||
|
print('[cache miss][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onDiagnostic(String message, {Object? details}) =>
|
||||||
|
print('[diagnostic][CherryPick] $message ${details ?? ''}');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onWarning(String message, {Object? details}) =>
|
||||||
|
print('[warn][CherryPick] $message ${details ?? ''}');
|
||||||
|
@override
|
||||||
|
void onError(String message, Object? error, StackTrace? stackTrace) {
|
||||||
|
print('[error][CherryPick] $message');
|
||||||
|
if (error != null) print(' error: $error');
|
||||||
|
if (stackTrace != null) print(' stack: $stackTrace');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Silent observer: ignores all events
|
||||||
|
class SilentCherryPickObserver implements CherryPickObserver {
|
||||||
|
@override
|
||||||
|
void onBindingRegistered(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onModulesInstalled(List<String> modules, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onModulesRemoved(List<String> modules, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onScopeOpened(String name) {}
|
||||||
|
@override
|
||||||
|
void onScopeClosed(String name) {}
|
||||||
|
@override
|
||||||
|
void onCycleDetected(List<String> chain, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onDiagnostic(String message, {Object? details}) {}
|
||||||
|
@override
|
||||||
|
void onWarning(String message, {Object? details}) {}
|
||||||
|
@override
|
||||||
|
void onError(String message, Object? error, StackTrace? stackTrace) {}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -14,39 +14,72 @@ import 'dart:collection';
|
|||||||
import 'dart:math';
|
import 'dart:math';
|
||||||
|
|
||||||
import 'package:cherrypick/src/cycle_detector.dart';
|
import 'package:cherrypick/src/cycle_detector.dart';
|
||||||
|
import 'package:cherrypick/src/disposable.dart';
|
||||||
import 'package:cherrypick/src/global_cycle_detector.dart';
|
import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||||
import 'package:cherrypick/src/binding_resolver.dart';
|
import 'package:cherrypick/src/binding_resolver.dart';
|
||||||
import 'package:cherrypick/src/module.dart';
|
import 'package:cherrypick/src/module.dart';
|
||||||
import 'package:cherrypick/src/logger.dart';
|
import 'package:cherrypick/src/observer.dart';
|
||||||
import 'package:cherrypick/src/log_format.dart';
|
// import 'package:cherrypick/src/log_format.dart';
|
||||||
|
|
||||||
|
/// Represents a DI scope (container) for modules, subscopes,
|
||||||
|
/// and dependency resolution (sync/async) in CherryPick.
|
||||||
|
///
|
||||||
|
/// Scopes provide hierarchical DI: you can resolve dependencies from parents,
|
||||||
|
/// override or isolate modules, and manage scope-specific singletons.
|
||||||
|
///
|
||||||
|
/// Each scope:
|
||||||
|
/// - Can install modules ([installModules]) that define [Binding]s
|
||||||
|
/// - Supports parent-child scope tree (see [openSubScope])
|
||||||
|
/// - Can resolve dependencies synchronously ([resolve]) or asynchronously ([resolveAsync])
|
||||||
|
/// - Cleans up resources for [Disposable] objects (see [dispose])
|
||||||
|
/// - Detects dependency cycles (local and global, if enabled)
|
||||||
|
///
|
||||||
|
/// Example usage:
|
||||||
|
/// ```dart
|
||||||
|
/// final rootScope = CherryPick.openRootScope();
|
||||||
|
/// rootScope.installModules([AppModule()]);
|
||||||
|
///
|
||||||
|
/// // Synchronous resolution:
|
||||||
|
/// final auth = rootScope.resolve<AuthService>();
|
||||||
|
///
|
||||||
|
/// // Asynchronous resolution:
|
||||||
|
/// final db = await rootScope.resolveAsync<Database>();
|
||||||
|
///
|
||||||
|
/// // Open a child scope (for a feature, page, or test):
|
||||||
|
/// final userScope = rootScope.openSubScope('user');
|
||||||
|
/// userScope.installModules([UserModule()]);
|
||||||
|
///
|
||||||
|
/// // Proper resource cleanup (calls dispose() on tracked objects)
|
||||||
|
/// await CherryPick.closeRootScope();
|
||||||
|
/// ```
|
||||||
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||||
final Scope? _parentScope;
|
final Scope? _parentScope;
|
||||||
|
|
||||||
late final CherryPickLogger _logger;
|
late final CherryPickObserver _observer;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
CherryPickLogger get logger => _logger;
|
CherryPickObserver get observer => _observer;
|
||||||
|
|
||||||
/// RU: Метод возвращает родительский [Scope].
|
/// COLLECTS all resolved instances that implement [Disposable].
|
||||||
///
|
final Set<Disposable> _disposables = HashSet();
|
||||||
/// ENG: The method returns the parent [Scope].
|
|
||||||
///
|
/// Returns the parent [Scope] if present, or null if this is the root scope.
|
||||||
/// return [Scope]
|
|
||||||
Scope? get parentScope => _parentScope;
|
Scope? get parentScope => _parentScope;
|
||||||
|
|
||||||
final Map<String, Scope> _scopeMap = HashMap();
|
final Map<String, Scope> _scopeMap = HashMap();
|
||||||
|
|
||||||
Scope(this._parentScope, {required CherryPickLogger logger}) : _logger = logger {
|
Scope(this._parentScope, {required CherryPickObserver observer}) : _observer = observer {
|
||||||
setScopeId(_generateScopeId());
|
setScopeId(_generateScopeId());
|
||||||
logger.info(formatLogMessage(
|
observer.onScopeOpened(scopeId ?? 'NO_ID');
|
||||||
type: 'Scope',
|
observer.onDiagnostic(
|
||||||
name: scopeId ?? 'NO_ID',
|
'Scope created: ${scopeId ?? 'NO_ID'}',
|
||||||
params: {
|
details: {
|
||||||
|
'type': 'Scope',
|
||||||
|
'name': scopeId ?? 'NO_ID',
|
||||||
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
|
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
|
||||||
|
'description': 'scope created',
|
||||||
},
|
},
|
||||||
description: 'scope created',
|
);
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
final Set<Module> _modulesList = HashSet();
|
final Set<Module> _modulesList = HashSet();
|
||||||
@@ -55,8 +88,9 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
||||||
|
|
||||||
|
|
||||||
/// RU: Генерирует уникальный идентификатор для скоупа.
|
/// Generates a unique identifier string for this scope instance.
|
||||||
/// ENG: Generates unique identifier for scope.
|
///
|
||||||
|
/// Used internally for diagnostics, logging and global scope tracking.
|
||||||
String _generateScopeId() {
|
String _generateScopeId() {
|
||||||
final random = Random();
|
final random = Random();
|
||||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||||
@@ -64,16 +98,20 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
return 'scope_${timestamp}_$randomPart';
|
return 'scope_${timestamp}_$randomPart';
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Метод открывает дочерний (дополнительный) [Scope].
|
/// Opens a named child [Scope] (subscope) as a descendant of the current scope.
|
||||||
///
|
///
|
||||||
/// ENG: The method opens child (additional) [Scope].
|
/// Subscopes inherit modules and DI context from their parent, but can override or extend bindings.
|
||||||
|
/// Useful for feature-isolation, screens, request/transaction lifetimes, and test separation.
|
||||||
///
|
///
|
||||||
/// return [Scope]
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final featureScope = rootScope.openSubScope('feature');
|
||||||
|
/// featureScope.installModules([FeatureModule()]);
|
||||||
|
/// final dep = featureScope.resolve<MyDep>();
|
||||||
|
/// ```
|
||||||
Scope openSubScope(String name) {
|
Scope openSubScope(String name) {
|
||||||
if (!_scopeMap.containsKey(name)) {
|
if (!_scopeMap.containsKey(name)) {
|
||||||
final childScope = Scope(this, logger: logger); // Наследуем логгер вниз по иерархии
|
final childScope = Scope(this, observer: observer);
|
||||||
// print removed (trace)
|
|
||||||
// Наследуем настройки обнаружения циклических зависимостей
|
|
||||||
if (isCycleDetectionEnabled) {
|
if (isCycleDetectionEnabled) {
|
||||||
childScope.enableCycleDetection();
|
childScope.enableCycleDetection();
|
||||||
}
|
}
|
||||||
@@ -81,64 +119,82 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
childScope.enableGlobalCycleDetection();
|
childScope.enableGlobalCycleDetection();
|
||||||
}
|
}
|
||||||
_scopeMap[name] = childScope;
|
_scopeMap[name] = childScope;
|
||||||
logger.info(formatLogMessage(
|
observer.onDiagnostic(
|
||||||
type: 'SubScope',
|
'SubScope created: $name',
|
||||||
name: name,
|
details: {
|
||||||
params: {
|
'type': 'SubScope',
|
||||||
|
'name': name,
|
||||||
'id': childScope.scopeId,
|
'id': childScope.scopeId,
|
||||||
if (scopeId != null) 'parent': scopeId,
|
if (scopeId != null) 'parent': scopeId,
|
||||||
|
'description': 'subscope created',
|
||||||
},
|
},
|
||||||
description: 'subscope created',
|
);
|
||||||
));
|
|
||||||
}
|
}
|
||||||
return _scopeMap[name]!;
|
return _scopeMap[name]!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Метод закрывает дочерний (дополнительный) [Scope].
|
/// Asynchronously closes and disposes a named child [Scope] (subscope).
|
||||||
///
|
///
|
||||||
/// ENG: The method closes child (additional) [Scope].
|
/// Ensures all [Disposable] objects and internal modules
|
||||||
|
/// in the subscope are properly cleaned up. Also removes any global cycle detectors associated with the subscope.
|
||||||
///
|
///
|
||||||
/// return [Scope]
|
/// Example:
|
||||||
void closeSubScope(String name) {
|
/// ```dart
|
||||||
|
/// await rootScope.closeSubScope('feature');
|
||||||
|
/// ```
|
||||||
|
Future<void> closeSubScope(String name) async {
|
||||||
final childScope = _scopeMap[name];
|
final childScope = _scopeMap[name];
|
||||||
if (childScope != null) {
|
if (childScope != null) {
|
||||||
// Очищаем детектор для дочернего скоупа
|
await childScope.dispose();
|
||||||
if (childScope.scopeId != null) {
|
if (childScope.scopeId != null) {
|
||||||
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
||||||
}
|
}
|
||||||
logger.info(formatLogMessage(
|
observer.onScopeClosed(childScope.scopeId ?? name);
|
||||||
type: 'SubScope',
|
observer.onDiagnostic(
|
||||||
name: name,
|
'SubScope closed: $name',
|
||||||
params: {
|
details: {
|
||||||
|
'type': 'SubScope',
|
||||||
|
'name': name,
|
||||||
'id': childScope.scopeId,
|
'id': childScope.scopeId,
|
||||||
if (scopeId != null) 'parent': scopeId,
|
if (scopeId != null) 'parent': scopeId,
|
||||||
|
'description': 'subscope closed',
|
||||||
},
|
},
|
||||||
description: 'subscope closed',
|
);
|
||||||
));
|
|
||||||
}
|
}
|
||||||
_scopeMap.remove(name);
|
_scopeMap.remove(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Метод инициализирует пользовательские модули в [Scope].
|
/// Installs a list of custom [Module]s into the [Scope].
|
||||||
///
|
///
|
||||||
/// ENG: The method initializes custom modules in [Scope].
|
/// Each module registers bindings and configuration for dependencies.
|
||||||
|
/// After calling this, bindings are immediately available for resolve/tryResolve.
|
||||||
///
|
///
|
||||||
/// return [Scope]
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// rootScope.installModules([AppModule(), NetworkModule()]);
|
||||||
|
/// ```
|
||||||
Scope installModules(List<Module> modules) {
|
Scope installModules(List<Module> modules) {
|
||||||
_modulesList.addAll(modules);
|
_modulesList.addAll(modules);
|
||||||
|
if (modules.isNotEmpty) {
|
||||||
|
observer.onModulesInstalled(
|
||||||
|
modules.map((m) => m.runtimeType.toString()).toList(),
|
||||||
|
scopeName: scopeId,
|
||||||
|
);
|
||||||
|
}
|
||||||
for (var module in modules) {
|
for (var module in modules) {
|
||||||
logger.info(formatLogMessage(
|
observer.onDiagnostic(
|
||||||
type: 'Module',
|
'Module installed: ${module.runtimeType}',
|
||||||
name: module.runtimeType.toString(),
|
details: {
|
||||||
params: {
|
'type': 'Module',
|
||||||
|
'name': module.runtimeType.toString(),
|
||||||
'scope': scopeId,
|
'scope': scopeId,
|
||||||
|
'description': 'module installed',
|
||||||
},
|
},
|
||||||
description: 'module installed',
|
);
|
||||||
));
|
|
||||||
module.builder(this);
|
module.builder(this);
|
||||||
// После builder: для всех новых биндингов
|
// Associate bindings with this scope's observer
|
||||||
for (final binding in module.bindingSet) {
|
for (final binding in module.bindingSet) {
|
||||||
binding.logger = logger;
|
binding.observer = observer;
|
||||||
binding.logAllDeferred();
|
binding.logAllDeferred();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -146,48 +202,56 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Метод удаляет пользовательские модули из [Scope].
|
/// Removes all installed [Module]s and their bindings from this [Scope].
|
||||||
///
|
///
|
||||||
/// ENG: This method removes custom modules from [Scope].
|
/// Typically used in tests or when resetting app configuration/runtime environment.
|
||||||
|
/// Note: this does not dispose resolved [Disposable]s (call [dispose] for that).
|
||||||
///
|
///
|
||||||
/// return [Scope]
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// testScope.dropModules();
|
||||||
|
/// ```
|
||||||
Scope dropModules() {
|
Scope dropModules() {
|
||||||
logger.info(formatLogMessage(
|
if (_modulesList.isNotEmpty) {
|
||||||
type: 'Scope',
|
observer.onModulesRemoved(
|
||||||
name: scopeId,
|
_modulesList.map((m) => m.runtimeType.toString()).toList(),
|
||||||
description: 'modules dropped',
|
scopeName: scopeId,
|
||||||
));
|
);
|
||||||
|
}
|
||||||
|
observer.onDiagnostic(
|
||||||
|
'Modules dropped for scope: $scopeId',
|
||||||
|
details: {
|
||||||
|
'type': 'Scope',
|
||||||
|
'name': scopeId,
|
||||||
|
'description': 'modules dropped',
|
||||||
|
},
|
||||||
|
);
|
||||||
_modulesList.clear();
|
_modulesList.clear();
|
||||||
_rebuildResolversIndex();
|
_rebuildResolversIndex();
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Возвращает найденную зависимость, определенную параметром типа [T].
|
/// Resolves a dependency of type [T], optionally by name and with params.
|
||||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
|
||||||
/// Если вы хотите получить [null], если зависимость не может быть найдена,
|
|
||||||
/// то используйте вместо этого [tryResolve]
|
|
||||||
/// return - возвращает объект типа [T] или [StateError]
|
|
||||||
///
|
///
|
||||||
/// ENG: Returns the found dependency specified by the type parameter [T].
|
/// Throws [StateError] if the dependency cannot be resolved. (Use [tryResolve] for fallible lookup).
|
||||||
/// Throws [StateError] if the dependency cannot be resolved.
|
/// Resolves from installed modules or recurses up the parent scope chain.
|
||||||
/// If you want to get [null] if the dependency cannot be found then use [tryResolve] instead
|
|
||||||
/// return - returns an object of type [T] or [StateError]
|
|
||||||
///
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final logger = scope.resolve<Logger>();
|
||||||
|
/// final special = scope.resolve<Service>(named: 'special');
|
||||||
|
/// ```
|
||||||
T resolve<T>({String? named, dynamic params}) {
|
T resolve<T>({String? named, dynamic params}) {
|
||||||
// Используем глобальное отслеживание, если включено
|
observer.onInstanceRequested(T.toString(), T, scopeName: scopeId);
|
||||||
|
T result;
|
||||||
if (isGlobalCycleDetectionEnabled) {
|
if (isGlobalCycleDetectionEnabled) {
|
||||||
try {
|
try {
|
||||||
return withGlobalCycleDetection<T>(T, named, () {
|
result = withGlobalCycleDetection<T>(T, named, () {
|
||||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||||
});
|
});
|
||||||
} catch (e, s) {
|
} catch (e, s) {
|
||||||
logger.error(
|
observer.onError(
|
||||||
formatLogMessage(
|
'Global cycle detection failed during resolve: $T',
|
||||||
type: 'Scope',
|
|
||||||
name: scopeId,
|
|
||||||
params: {'resolve': T.toString()},
|
|
||||||
description: 'global cycle detection failed during resolve',
|
|
||||||
),
|
|
||||||
e,
|
e,
|
||||||
s,
|
s,
|
||||||
);
|
);
|
||||||
@@ -195,50 +259,44 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
result = _resolveWithLocalDetection<T>(named: named, params: params);
|
||||||
} catch (e, s) {
|
} catch (e, s) {
|
||||||
logger.error(
|
observer.onError(
|
||||||
formatLogMessage(
|
'Failed to resolve: $T',
|
||||||
type: 'Scope',
|
|
||||||
name: scopeId,
|
|
||||||
params: {'resolve': T.toString()},
|
|
||||||
description: 'failed to resolve',
|
|
||||||
),
|
|
||||||
e,
|
e,
|
||||||
s,
|
s,
|
||||||
);
|
);
|
||||||
rethrow;
|
rethrow;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_trackDisposable(result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Разрешение с локальным детектором циклических зависимостей.
|
/// Resolves [T] using the local cycle detector for this scope.
|
||||||
/// ENG: Resolution with local circular dependency detector.
|
/// Throws [StateError] if not found or cycle is detected.
|
||||||
|
/// Used internally by [resolve].
|
||||||
T _resolveWithLocalDetection<T>({String? named, dynamic params}) {
|
T _resolveWithLocalDetection<T>({String? named, dynamic params}) {
|
||||||
return withCycleDetection<T>(T, named, () {
|
return withCycleDetection<T>(T, named, () {
|
||||||
var resolved = _tryResolveInternal<T>(named: named, params: params);
|
var resolved = _tryResolveInternal<T>(named: named, params: params);
|
||||||
if (resolved != null) {
|
if (resolved != null) {
|
||||||
logger.info(formatLogMessage(
|
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId);
|
||||||
type: 'Scope',
|
observer.onDiagnostic(
|
||||||
name: scopeId,
|
'Successfully resolved: $T',
|
||||||
params: {
|
details: {
|
||||||
|
'type': 'Scope',
|
||||||
|
'name': scopeId,
|
||||||
'resolve': T.toString(),
|
'resolve': T.toString(),
|
||||||
if (named != null) 'named': named,
|
if (named != null) 'named': named,
|
||||||
|
'description': 'successfully resolved',
|
||||||
},
|
},
|
||||||
description: 'successfully resolved',
|
);
|
||||||
));
|
|
||||||
return resolved;
|
return resolved;
|
||||||
} else {
|
} else {
|
||||||
logger.error(
|
observer.onError(
|
||||||
formatLogMessage(
|
'Failed to resolve: $T',
|
||||||
type: 'Scope',
|
null,
|
||||||
name: scopeId,
|
null,
|
||||||
params: {
|
|
||||||
'resolve': T.toString(),
|
|
||||||
if (named != null) 'named': named,
|
|
||||||
},
|
|
||||||
description: 'failed to resolve',
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
throw StateError(
|
throw StateError(
|
||||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||||
@@ -246,22 +304,30 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Возвращает найденную зависимость типа [T] или null, если она не может быть найдена.
|
/// Attempts to resolve a dependency of type [T], optionally by name and with params.
|
||||||
/// ENG: Returns found dependency of type [T] or null if it cannot be found.
|
|
||||||
///
|
///
|
||||||
|
/// Returns the resolved dependency, or `null` if not found.
|
||||||
|
/// Does not throw if missing (unlike [resolve]).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final maybeDb = scope.tryResolve<Database>();
|
||||||
|
/// ```
|
||||||
T? tryResolve<T>({String? named, dynamic params}) {
|
T? tryResolve<T>({String? named, dynamic params}) {
|
||||||
// Используем глобальное отслеживание, если включено
|
T? result;
|
||||||
if (isGlobalCycleDetectionEnabled) {
|
if (isGlobalCycleDetectionEnabled) {
|
||||||
return withGlobalCycleDetection<T?>(T, named, () {
|
result = withGlobalCycleDetection<T?>(T, named, () {
|
||||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
result = _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||||
}
|
}
|
||||||
|
if (result != null) _trackDisposable(result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Попытка разрешения с локальным детектором циклических зависимостей.
|
/// Attempts to resolve [T] using the local cycle detector. Returns null if not found or cycle.
|
||||||
/// ENG: Try resolution with local circular dependency detector.
|
/// Used internally by [tryResolve].
|
||||||
T? _tryResolveWithLocalDetection<T>({String? named, dynamic params}) {
|
T? _tryResolveWithLocalDetection<T>({String? named, dynamic params}) {
|
||||||
if (isCycleDetectionEnabled) {
|
if (isCycleDetectionEnabled) {
|
||||||
return withCycleDetection<T?>(T, named, () {
|
return withCycleDetection<T?>(T, named, () {
|
||||||
@@ -272,65 +338,89 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Внутренний метод для разрешения зависимостей без проверки циклических зависимостей.
|
/// Locates and resolves [T] without cycle detection (direct lookup).
|
||||||
/// ENG: Internal method for dependency resolution without circular dependency checking.
|
/// Returns null if not found. Used internally.
|
||||||
T? _tryResolveInternal<T>({String? named, dynamic params}) {
|
T? _tryResolveInternal<T>({String? named, dynamic params}) {
|
||||||
final resolver = _findBindingResolver<T>(named);
|
final resolver = _findBindingResolver<T>(named);
|
||||||
|
// 1 - Try from own modules; 2 - Fallback to parent
|
||||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
|
||||||
return resolver?.resolveSync(params) ??
|
return resolver?.resolveSync(params) ??
|
||||||
// 2 Поиск зависимостей в родительском скоупе
|
|
||||||
_parentScope?.tryResolve(named: named, params: params);
|
_parentScope?.tryResolve(named: named, params: params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Асинхронно возвращает найденную зависимость, определенную параметром типа [T].
|
/// Asynchronously resolves a dependency of type [T].
|
||||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
|
||||||
/// Если хотите получить [null], если зависимость не может быть найдена, используйте [tryResolveAsync].
|
|
||||||
/// return - возвращает объект типа [T] or [StateError]
|
|
||||||
///
|
///
|
||||||
/// ENG: Asynchronously returns the found dependency specified by the type parameter [T].
|
/// Throws [StateError] if not found. (Use [tryResolveAsync] for a fallible async resolve.)
|
||||||
/// Throws [StateError] if the dependency cannot be resolved.
|
|
||||||
/// If you want to get [null] if the dependency cannot be found, use [tryResolveAsync] instead.
|
|
||||||
/// return - returns an object of type [T] or [StateError]
|
|
||||||
///
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final db = await scope.resolveAsync<Database>();
|
||||||
|
/// final special = await scope.resolveAsync<Service>(named: "special");
|
||||||
|
/// ```
|
||||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||||
// Используем глобальное отслеживание, если включено
|
T result;
|
||||||
if (isGlobalCycleDetectionEnabled) {
|
if (isGlobalCycleDetectionEnabled) {
|
||||||
return withGlobalCycleDetection<Future<T>>(T, named, () async {
|
result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
result = await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||||
}
|
}
|
||||||
|
_trackDisposable(result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Асинхронное разрешение с локальным детектором циклических зависимостей.
|
/// Resolves [T] asynchronously using local cycle detector. Throws if not found.
|
||||||
/// ENG: Async resolution with local circular dependency detector.
|
/// Internal implementation for async [resolveAsync].
|
||||||
Future<T> _resolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
Future<T> _resolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
||||||
return withCycleDetection<Future<T>>(T, named, () async {
|
return withCycleDetection<Future<T>>(T, named, () async {
|
||||||
var resolved = await _tryResolveAsyncInternal<T>(named: named, params: params);
|
var resolved = await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||||
if (resolved != null) {
|
if (resolved != null) {
|
||||||
|
observer.onInstanceCreated(T.toString(), T, resolved, scopeName: scopeId);
|
||||||
|
observer.onDiagnostic(
|
||||||
|
'Successfully async resolved: $T',
|
||||||
|
details: {
|
||||||
|
'type': 'Scope',
|
||||||
|
'name': scopeId,
|
||||||
|
'resolve': T.toString(),
|
||||||
|
if (named != null) 'named': named,
|
||||||
|
'description': 'successfully resolved (async)',
|
||||||
|
},
|
||||||
|
);
|
||||||
return resolved;
|
return resolved;
|
||||||
} else {
|
} else {
|
||||||
|
observer.onError(
|
||||||
|
'Failed to async resolve: $T',
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
);
|
||||||
throw StateError(
|
throw StateError(
|
||||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Attempts to asynchronously resolve a dependency of type [T].
|
||||||
|
/// Returns the dependency or null if not present (never throws).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final user = await scope.tryResolveAsync<User>();
|
||||||
|
/// ```
|
||||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||||
// Используем глобальное отслеживание, если включено
|
T? result;
|
||||||
if (isGlobalCycleDetectionEnabled) {
|
if (isGlobalCycleDetectionEnabled) {
|
||||||
return withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
result = await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||||
}
|
}
|
||||||
|
if (result != null) _trackDisposable(result);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Асинхронная попытка разрешения с локальным детектором циклических зависимостей.
|
/// Attempts to resolve [T] asynchronously using local cycle detector. Returns null if missing.
|
||||||
/// ENG: Async try resolution with local circular dependency detector.
|
/// Internal implementation for async [tryResolveAsync].
|
||||||
Future<T?> _tryResolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
Future<T?> _tryResolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
||||||
if (isCycleDetectionEnabled) {
|
if (isCycleDetectionEnabled) {
|
||||||
return withCycleDetection<Future<T?>>(T, named, () async {
|
return withCycleDetection<Future<T?>>(T, named, () async {
|
||||||
@@ -341,21 +431,21 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RU: Внутренний метод для асинхронного разрешения зависимостей без проверки циклических зависимостей.
|
/// Direct async resolution for [T] without cycle check. Returns null if missing. Internal use only.
|
||||||
/// ENG: Internal method for async dependency resolution without circular dependency checking.
|
|
||||||
Future<T?> _tryResolveAsyncInternal<T>({String? named, dynamic params}) async {
|
Future<T?> _tryResolveAsyncInternal<T>({String? named, dynamic params}) async {
|
||||||
final resolver = _findBindingResolver<T>(named);
|
final resolver = _findBindingResolver<T>(named);
|
||||||
|
// 1 - Try from own modules; 2 - Fallback to parent
|
||||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
|
||||||
return resolver?.resolveAsync(params) ??
|
return resolver?.resolveAsync(params) ??
|
||||||
// 2 Поиск зависимостей в родительском скоупе
|
|
||||||
_parentScope?.tryResolveAsync(named: named, params: params);
|
_parentScope?.tryResolveAsync(named: named, params: params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Looks up the [BindingResolver] for [T] and [named] within this scope.
|
||||||
|
/// Returns null if none found. Internal use only.
|
||||||
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
||||||
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
||||||
|
|
||||||
// Индексируем все binding’и после каждого installModules/dropModules
|
/// Rebuilds the internal index of all [BindingResolver]s from installed modules.
|
||||||
|
/// Called after [installModules] and [dropModules]. Internal use only.
|
||||||
void _rebuildResolversIndex() {
|
void _rebuildResolversIndex() {
|
||||||
_bindingResolvers.clear();
|
_bindingResolvers.clear();
|
||||||
for (var module in _modulesList) {
|
for (var module in _modulesList) {
|
||||||
@@ -366,4 +456,37 @@ class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tracks resolved [Disposable] instances, to ensure dispose is called automatically.
|
||||||
|
/// Internal use only.
|
||||||
|
void _trackDisposable(Object? obj) {
|
||||||
|
if (obj is Disposable && !_disposables.contains(obj)) {
|
||||||
|
_disposables.add(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asynchronously disposes this [Scope], all tracked [Disposable] objects, and recursively
|
||||||
|
/// all its child subscopes.
|
||||||
|
///
|
||||||
|
/// This method should always be called when a scope is no longer needed
|
||||||
|
/// to guarantee timely resource cleanup (files, sockets, streams, handles, etc).
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// await myScope.dispose();
|
||||||
|
/// ```
|
||||||
|
Future<void> dispose() async {
|
||||||
|
// First dispose children scopes
|
||||||
|
for (final subScope in _scopeMap.values) {
|
||||||
|
await subScope.dispose();
|
||||||
|
}
|
||||||
|
_scopeMap.clear();
|
||||||
|
// Then dispose own disposables
|
||||||
|
for (final d in _disposables) {
|
||||||
|
try {
|
||||||
|
await d.dispose();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
_disposables.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
name: cherrypick
|
name: cherrypick
|
||||||
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
||||||
version: 3.0.0-dev.6
|
version: 3.0.0-dev.9
|
||||||
homepage: https://pese-git.github.io/cherrypick-site/
|
homepage: https://pese-git.github.io/cherrypick-site/
|
||||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||||
repository: https://github.com/pese-git/cherrypick
|
repository: https://github.com/pese-git/cherrypick
|
||||||
|
|||||||
@@ -23,38 +23,27 @@ class CyclicModule extends Module {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late MockLogger logger;
|
late MockObserver observer;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
logger = MockLogger();
|
observer = MockObserver();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Global logger receives Scope and Binding events', () {
|
test('Global logger receives Binding events', () {
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
scope.installModules([DummyModule()]);
|
scope.installModules([DummyModule()]);
|
||||||
final _ = scope.resolve<DummyService>(named: 'test');
|
final _ = scope.resolve<DummyService>(named: 'test');
|
||||||
|
|
||||||
// Новый стиль проверки для formatLogMessage:
|
// Проверяем, что биндинг DummyService зарегистрирован
|
||||||
expect(
|
expect(
|
||||||
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('created')),
|
observer.bindings.any((m) => m.contains('DummyService')),
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('created')),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('named') && m.contains('name=test')),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('resolve=DummyService') && m.contains('successfully resolved')),
|
|
||||||
isTrue,
|
isTrue,
|
||||||
);
|
);
|
||||||
|
// Можно добавить проверки diagnostics, если Scope что-то пишет туда
|
||||||
});
|
});
|
||||||
|
|
||||||
test('CycleDetector logs cycle detection error', () {
|
test('CycleDetector logs cycle detection error', () {
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
// print('[DEBUG] TEST SCOPE logger type=${scope.logger.runtimeType} hash=${scope.logger.hashCode}');
|
// print('[DEBUG] TEST SCOPE logger type=${scope.logger.runtimeType} hash=${scope.logger.hashCode}');
|
||||||
scope.enableCycleDetection();
|
scope.enableCycleDetection();
|
||||||
scope.installModules([CyclicModule()]);
|
scope.installModules([CyclicModule()]);
|
||||||
@@ -62,12 +51,11 @@ void main() {
|
|||||||
() => scope.resolve<A>(),
|
() => scope.resolve<A>(),
|
||||||
throwsA(isA<CircularDependencyException>()),
|
throwsA(isA<CircularDependencyException>()),
|
||||||
);
|
);
|
||||||
// Дополнительно ищем и среди info на случай если лог от CycleDetector ошибочно не попал в errors
|
// Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles
|
||||||
final foundInErrors = logger.errors.any((m) =>
|
final foundInErrors = observer.errors.any((m) => m.contains('cycle detected'));
|
||||||
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
|
final foundInDiagnostics = observer.diagnostics.any((m) => m.contains('cycle detected'));
|
||||||
final foundInInfos = logger.infos.any((m) =>
|
final foundCycleNotified = observer.cycles.isNotEmpty;
|
||||||
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
|
expect(foundInErrors || foundInDiagnostics || foundCycleNotified, isTrue,
|
||||||
expect(foundInErrors || foundInInfos, isTrue,
|
reason: 'Ожидаем хотя бы один лог о цикле! errors: ${observer.errors}\ndiag: ${observer.diagnostics}\ncycles: ${observer.cycles}');
|
||||||
reason: 'Ожидаем хотя бы один лог о цикле на уровне error или info; вот все errors: ${logger.errors}\ninfos: ${logger.infos}');
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,48 @@
|
|||||||
import 'package:cherrypick/cherrypick.dart';
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
|
||||||
class MockLogger implements CherryPickLogger {
|
class MockObserver implements CherryPickObserver {
|
||||||
final List<String> infos = [];
|
final List<String> diagnostics = [];
|
||||||
final List<String> warns = [];
|
final List<String> warnings = [];
|
||||||
final List<String> errors = [];
|
final List<String> errors = [];
|
||||||
|
final List<List<String>> cycles = [];
|
||||||
|
final List<String> bindings = [];
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void info(String message) => infos.add(message);
|
void onDiagnostic(String message, {Object? details}) =>
|
||||||
|
diagnostics.add(message);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void warn(String message) => warns.add(message);
|
void onWarning(String message, {Object? details}) => warnings.add(message);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void error(String message, [Object? e, StackTrace? s]) =>
|
void onError(String message, Object? error, StackTrace? stackTrace) =>
|
||||||
errors.add(
|
errors.add(
|
||||||
'$message${e != null ? ' $e' : ''}${s != null ? '\n$s' : ''}');
|
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onCycleDetected(List<String> chain, {String? scopeName}) =>
|
||||||
|
cycles.add(chain);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||||
|
bindings.add('$name $type');
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onModulesRemoved(List<String> moduleNames, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onScopeOpened(String name) {}
|
||||||
|
@override
|
||||||
|
void onScopeClosed(String name) {}
|
||||||
|
@override
|
||||||
|
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||||
|
@override
|
||||||
|
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,16 @@ import 'package:cherrypick/cherrypick.dart';
|
|||||||
import '../mock_logger.dart';
|
import '../mock_logger.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late MockLogger logger;
|
late MockObserver observer;
|
||||||
setUp(() {
|
setUp(() {
|
||||||
logger = MockLogger();
|
observer = MockObserver();
|
||||||
CherryPick.setGlobalLogger(logger);
|
CherryPick.setGlobalObserver(observer);
|
||||||
});
|
});
|
||||||
group('CycleDetector', () {
|
group('CycleDetector', () {
|
||||||
late CycleDetector detector;
|
late CycleDetector detector;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
detector = CycleDetector(logger: logger);
|
detector = CycleDetector(observer: observer);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should detect simple circular dependency', () {
|
test('should detect simple circular dependency', () {
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ import 'package:test/test.dart';
|
|||||||
import '../mock_logger.dart';
|
import '../mock_logger.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
late MockLogger logger;
|
late MockObserver observer;
|
||||||
setUp(() {
|
setUp(() {
|
||||||
logger = MockLogger();
|
observer = MockObserver();
|
||||||
CherryPick.setGlobalLogger(logger);
|
CherryPick.setGlobalObserver(observer);
|
||||||
});
|
});
|
||||||
group('CherryPick Cycle Detection Helper Methods', () {
|
group('CherryPick Cycle Detection Helper Methods', () {
|
||||||
setUp(() {
|
setUp(() {
|
||||||
|
|||||||
@@ -1,26 +1,138 @@
|
|||||||
import 'package:cherrypick/cherrypick.dart';
|
import 'package:cherrypick/cherrypick.dart' show Disposable, Module, Scope, CherryPick;
|
||||||
|
import 'dart:async';
|
||||||
import 'package:test/test.dart';
|
import 'package:test/test.dart';
|
||||||
import '../mock_logger.dart';
|
import '../mock_logger.dart';
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Вспомогательные классы для тестов
|
||||||
|
|
||||||
|
class AsyncExampleDisposable implements Disposable {
|
||||||
|
bool disposed = false;
|
||||||
|
@override
|
||||||
|
Future<void> dispose() async {
|
||||||
|
await Future.delayed(Duration(milliseconds: 10));
|
||||||
|
disposed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AsyncExampleModule extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<AsyncExampleDisposable>().toProvide(() => AsyncExampleDisposable()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestDisposable implements Disposable {
|
||||||
|
bool disposed = false;
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() {
|
||||||
|
disposed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AnotherDisposable implements Disposable {
|
||||||
|
bool disposed = false;
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() {
|
||||||
|
disposed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CountingDisposable implements Disposable {
|
||||||
|
int disposeCount = 0;
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() {
|
||||||
|
disposeCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ModuleCountingDisposable extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<CountingDisposable>().toProvide(() => CountingDisposable()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ModuleWithDisposable extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<TestDisposable>().toProvide(() => TestDisposable()).singleton();
|
||||||
|
bind<AnotherDisposable>().toProvide(() => AnotherDisposable()).singleton();
|
||||||
|
bind<String>().toProvide(() => 'super string').singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestModule<T> extends Module {
|
||||||
|
final T value;
|
||||||
|
final String? name;
|
||||||
|
TestModule({required this.value, this.name});
|
||||||
|
@override
|
||||||
|
void builder(Scope currentScope) {
|
||||||
|
if (name == null) {
|
||||||
|
bind<T>().toInstance(value);
|
||||||
|
} else {
|
||||||
|
bind<T>().withName(name!).toInstance(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _InlineModule extends Module {
|
||||||
|
final void Function(Module, Scope) _builder;
|
||||||
|
_InlineModule(this._builder);
|
||||||
|
@override
|
||||||
|
void builder(Scope s) => _builder(this, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
class AsyncCreatedDisposable implements Disposable {
|
||||||
|
bool disposed = false;
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
disposed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AsyncModule extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<AsyncCreatedDisposable>()
|
||||||
|
// ignore: deprecated_member_use_from_same_package
|
||||||
|
.toProvideAsync(() async {
|
||||||
|
await Future.delayed(Duration(milliseconds: 10));
|
||||||
|
return AsyncCreatedDisposable();
|
||||||
|
})
|
||||||
|
.singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Scope & Subscope Management', () {
|
group('Scope & Subscope Management', () {
|
||||||
test('Scope has no parent if constructed with null', () {
|
test('Scope has no parent if constructed with null', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
expect(scope.parentScope, null);
|
expect(scope.parentScope, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Can open and retrieve the same subScope by key', () {
|
test('Can open and retrieve the same subScope by key', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
|
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||||
|
});
|
||||||
|
test('closeSubScope removes subscope so next openSubScope returns new', () async {
|
||||||
|
final observer = MockObserver();
|
||||||
|
final scope = Scope(null, observer: observer);
|
||||||
|
final subScope = scope.openSubScope("child");
|
||||||
|
expect(scope.openSubScope("child"), same(subScope));
|
||||||
|
await scope.closeSubScope("child");
|
||||||
|
final newSubScope = scope.openSubScope("child");
|
||||||
|
expect(newSubScope, isNot(same(subScope)));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
|
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||||
// Нет необходимости тестировать open/closeSubScope в этом юните
|
// Нет необходимости тестировать open/closeSubScope в этом юните
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -28,54 +140,48 @@ void main() {
|
|||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Dependency Resolution (standard)', () {
|
group('Dependency Resolution (standard)', () {
|
||||||
test("Throws StateError if value can't be resolved", () {
|
test("Throws StateError if value can't be resolved", () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Resolves value after adding a dependency', () {
|
test('Resolves value after adding a dependency', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final expectedValue = 'test string';
|
final expectedValue = 'test string';
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
.installModules([TestModule<String>(value: expectedValue)]);
|
.installModules([TestModule<String>(value: expectedValue)]);
|
||||||
expect(scope.resolve<String>(), expectedValue);
|
expect(scope.resolve<String>(), expectedValue);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Returns a value from parent scope', () {
|
test('Returns a value from parent scope', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final expectedValue = 5;
|
final expectedValue = 5;
|
||||||
final parentScope = Scope(null, logger: logger);
|
final parentScope = Scope(null, observer: observer);
|
||||||
final scope = Scope(parentScope, logger: logger);
|
final scope = Scope(parentScope, observer: observer);
|
||||||
|
|
||||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||||
|
|
||||||
expect(scope.resolve<int>(), expectedValue);
|
expect(scope.resolve<int>(), expectedValue);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Returns several values from parent container', () {
|
test('Returns several values from parent container', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final expectedIntValue = 5;
|
final expectedIntValue = 5;
|
||||||
final expectedStringValue = 'Hello world';
|
final expectedStringValue = 'Hello world';
|
||||||
final parentScope = Scope(null, logger: logger).installModules([
|
final parentScope = Scope(null, observer: observer).installModules([
|
||||||
TestModule<int>(value: expectedIntValue),
|
TestModule<int>(value: expectedIntValue),
|
||||||
TestModule<String>(value: expectedStringValue)
|
TestModule<String>(value: expectedStringValue)
|
||||||
]);
|
]);
|
||||||
final scope = Scope(parentScope, logger: logger);
|
final scope = Scope(parentScope, observer: observer);
|
||||||
|
|
||||||
expect(scope.resolve<int>(), expectedIntValue);
|
expect(scope.resolve<int>(), expectedIntValue);
|
||||||
expect(scope.resolve<String>(), expectedStringValue);
|
expect(scope.resolve<String>(), expectedStringValue);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Throws StateError if parent hasn't value too", () {
|
test("Throws StateError if parent hasn't value too", () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final parentScope = Scope(null, logger: logger);
|
final parentScope = Scope(null, observer: observer);
|
||||||
final scope = Scope(parentScope, logger: logger);
|
final scope = Scope(parentScope, observer: observer);
|
||||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||||
});
|
});
|
||||||
|
|
||||||
test("After dropModules resolves fail", () {
|
test("After dropModules resolves fail", () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)..installModules([TestModule<int>(value: 5)]);
|
final scope = Scope(null, observer: observer)..installModules([TestModule<int>(value: 5)]);
|
||||||
expect(scope.resolve<int>(), 5);
|
expect(scope.resolve<int>(), 5);
|
||||||
scope.dropModules();
|
scope.dropModules();
|
||||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||||
@@ -85,8 +191,8 @@ void main() {
|
|||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Named Dependencies', () {
|
group('Named Dependencies', () {
|
||||||
test('Resolve named binding', () {
|
test('Resolve named binding', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
TestModule<String>(value: "first"),
|
TestModule<String>(value: "first"),
|
||||||
TestModule<String>(value: "second", name: "special")
|
TestModule<String>(value: "second", name: "special")
|
||||||
@@ -94,20 +200,18 @@ void main() {
|
|||||||
expect(scope.resolve<String>(named: "special"), "second");
|
expect(scope.resolve<String>(named: "special"), "second");
|
||||||
expect(scope.resolve<String>(), "first");
|
expect(scope.resolve<String>(), "first");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Named binding does not clash with unnamed', () {
|
test('Named binding does not clash with unnamed', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
TestModule<String>(value: "foo", name: "bar"),
|
TestModule<String>(value: "foo", name: "bar"),
|
||||||
]);
|
]);
|
||||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||||
expect(scope.resolve<String>(named: "bar"), "foo");
|
expect(scope.resolve<String>(named: "bar"), "foo");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("tryResolve returns null for missing named", () {
|
test("tryResolve returns null for missing named", () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
TestModule<String>(value: "foo"),
|
TestModule<String>(value: "foo"),
|
||||||
]);
|
]);
|
||||||
@@ -118,8 +222,8 @@ void main() {
|
|||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Provider with parameters', () {
|
group('Provider with parameters', () {
|
||||||
test('Resolve dependency using providerWithParams', () {
|
test('Resolve dependency using providerWithParams', () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
_InlineModule((m, s) {
|
_InlineModule((m, s) {
|
||||||
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
|
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
|
||||||
@@ -133,8 +237,8 @@ void main() {
|
|||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Async Resolution', () {
|
group('Async Resolution', () {
|
||||||
test('Resolve async instance', () async {
|
test('Resolve async instance', () async {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
_InlineModule((m, s) {
|
_InlineModule((m, s) {
|
||||||
m.bind<String>().toInstance(Future.value('async value'));
|
m.bind<String>().toInstance(Future.value('async value'));
|
||||||
@@ -142,10 +246,9 @@ void main() {
|
|||||||
]);
|
]);
|
||||||
expect(await scope.resolveAsync<String>(), "async value");
|
expect(await scope.resolveAsync<String>(), "async value");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Resolve async provider', () async {
|
test('Resolve async provider', () async {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
_InlineModule((m, s) {
|
_InlineModule((m, s) {
|
||||||
m.bind<int>().toProvide(() async => 7);
|
m.bind<int>().toProvide(() async => 7);
|
||||||
@@ -153,10 +256,9 @@ void main() {
|
|||||||
]);
|
]);
|
||||||
expect(await scope.resolveAsync<int>(), 7);
|
expect(await scope.resolveAsync<int>(), 7);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Resolve async provider with param', () async {
|
test('Resolve async provider with param', () async {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger)
|
final scope = Scope(null, observer: observer)
|
||||||
..installModules([
|
..installModules([
|
||||||
_InlineModule((m, s) {
|
_InlineModule((m, s) {
|
||||||
m.bind<int>().toProvideWithParams((x) async => (x as int) * 3);
|
m.bind<int>().toProvideWithParams((x) async => (x as int) * 3);
|
||||||
@@ -165,10 +267,9 @@ void main() {
|
|||||||
expect(await scope.resolveAsync<int>(params: 2), 6);
|
expect(await scope.resolveAsync<int>(params: 2), 6);
|
||||||
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('tryResolveAsync returns null for missing', () async {
|
test('tryResolveAsync returns null for missing', () async {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
final result = await scope.tryResolveAsync<String>();
|
final result = await scope.tryResolveAsync<String>();
|
||||||
expect(result, isNull);
|
expect(result, isNull);
|
||||||
});
|
});
|
||||||
@@ -177,46 +278,90 @@ void main() {
|
|||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
group('Optional resolution and error handling', () {
|
group('Optional resolution and error handling', () {
|
||||||
test("tryResolve returns null for missing dependency", () {
|
test("tryResolve returns null for missing dependency", () {
|
||||||
final logger = MockLogger();
|
final observer = MockObserver();
|
||||||
final scope = Scope(null, logger: logger);
|
final scope = Scope(null, observer: observer);
|
||||||
expect(scope.tryResolve<int>(), isNull);
|
expect(scope.tryResolve<int>(), isNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Не реализован:
|
|
||||||
// test("Container bind() throws state error (if it's parent already has a resolver)", () {
|
|
||||||
// final parentScope = new Scope(null).installModules([TestModule<String>(value: "string one")]);
|
|
||||||
// final scope = new Scope(parentScope);
|
|
||||||
|
|
||||||
// expect(
|
|
||||||
// () => scope.installModules([TestModule<String>(value: "string two")]),
|
|
||||||
// throwsA(isA<StateError>()));
|
|
||||||
// });
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// ----------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
// Вспомогательные модули
|
group('Disposable resource management', () {
|
||||||
|
test('scope.disposeAsync calls dispose on singleton disposable', () async {
|
||||||
|
final scope = CherryPick.openRootScope();
|
||||||
|
scope.installModules([ModuleWithDisposable()]);
|
||||||
|
final t = scope.resolve<TestDisposable>();
|
||||||
|
expect(t.disposed, isFalse);
|
||||||
|
await scope.dispose();
|
||||||
|
expect(t.disposed, isTrue);
|
||||||
|
});
|
||||||
|
test('scope.disposeAsync calls dispose on all unique disposables', () async {
|
||||||
|
final scope = Scope(null, observer: MockObserver());
|
||||||
|
scope.installModules([ModuleWithDisposable()]);
|
||||||
|
final t1 = scope.resolve<TestDisposable>();
|
||||||
|
final t2 = scope.resolve<AnotherDisposable>();
|
||||||
|
expect(t1.disposed, isFalse);
|
||||||
|
expect(t2.disposed, isFalse);
|
||||||
|
await scope.dispose();
|
||||||
|
expect(t1.disposed, isTrue);
|
||||||
|
expect(t2.disposed, isTrue);
|
||||||
|
});
|
||||||
|
test('calling disposeAsync twice does not throw and not call twice', () async {
|
||||||
|
final scope = CherryPick.openRootScope();
|
||||||
|
scope.installModules([ModuleWithDisposable()]);
|
||||||
|
final t = scope.resolve<TestDisposable>();
|
||||||
|
await scope.dispose();
|
||||||
|
await scope.dispose();
|
||||||
|
expect(t.disposed, isTrue);
|
||||||
|
});
|
||||||
|
test('Non-disposable dependency is ignored by scope.disposeAsync', () async {
|
||||||
|
final scope = CherryPick.openRootScope();
|
||||||
|
scope.installModules([ModuleWithDisposable()]);
|
||||||
|
final s = scope.resolve<String>();
|
||||||
|
expect(s, 'super string');
|
||||||
|
await scope.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
class TestModule<T> extends Module {
|
// --------------------------------------------------------------------------
|
||||||
final T value;
|
// Расширенные edge-тесты для dispose и subScope
|
||||||
final String? name;
|
group('Scope/subScope dispose edge cases', () {
|
||||||
|
test('Dispose called in closed subScope only', () async {
|
||||||
|
final root = CherryPick.openRootScope();
|
||||||
|
final sub = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
|
||||||
|
final d = sub.resolve<CountingDisposable>();
|
||||||
|
expect(d.disposeCount, 0);
|
||||||
|
|
||||||
TestModule({required this.value, this.name});
|
await root.closeSubScope('feature');
|
||||||
@override
|
expect(d.disposeCount, 1); // dispose должен быть вызван
|
||||||
void builder(Scope currentScope) {
|
|
||||||
if (name == null) {
|
|
||||||
bind<T>().toInstance(value);
|
|
||||||
} else {
|
|
||||||
bind<T>().withName(name!).toInstance(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Вспомогательный модуль для подстановки builder'а через конструктор
|
// Повторное закрытие не вызывает double-dispose
|
||||||
class _InlineModule extends Module {
|
await root.closeSubScope('feature');
|
||||||
final void Function(Module, Scope) _builder;
|
expect(d.disposeCount, 1);
|
||||||
_InlineModule(this._builder);
|
|
||||||
|
|
||||||
@override
|
// Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова)
|
||||||
void builder(Scope s) => _builder(this, s);
|
final sub2 = root.openSubScope('feature')..installModules([ModuleCountingDisposable()]);
|
||||||
}
|
final d2 = sub2.resolve<CountingDisposable>();
|
||||||
|
expect(identical(d, d2), isFalse);
|
||||||
|
await root.closeSubScope('feature');
|
||||||
|
expect(d2.disposeCount, 1);
|
||||||
|
});
|
||||||
|
test('Dispose for all nested subScopes on root disposeAsync', () async {
|
||||||
|
final root = CherryPick.openRootScope();
|
||||||
|
root.openSubScope('a').openSubScope('b').installModules([ModuleCountingDisposable()]);
|
||||||
|
final d = root.openSubScope('a').openSubScope('b').resolve<CountingDisposable>();
|
||||||
|
await root.dispose();
|
||||||
|
expect(d.disposeCount, 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// --------------------------------------------------------------------------
|
||||||
|
group('Async disposable (Future test)', () {
|
||||||
|
test('Async Disposable is awaited on disposeAsync', () async {
|
||||||
|
final scope = CherryPick.openRootScope()..installModules([AsyncExampleModule()]);
|
||||||
|
final d = scope.resolve<AsyncExampleDisposable>();
|
||||||
|
expect(d.disposed, false);
|
||||||
|
await scope.dispose();
|
||||||
|
expect(d.disposed, true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,3 +1,11 @@
|
|||||||
|
## 1.1.2-dev.0
|
||||||
|
|
||||||
|
- **DOCS**(annotations): unify and improve English DartDoc for all DI annotations.
|
||||||
|
|
||||||
|
## 1.1.1
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
## 1.1.0
|
## 1.1.0
|
||||||
|
|
||||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||||
|
|||||||
@@ -192,7 +192,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -12,6 +12,9 @@
|
|||||||
# The core lints are also what is used by pub.dev for scoring packages.
|
# The core lints are also what is used by pub.dev for scoring packages.
|
||||||
|
|
||||||
include: package:lints/recommended.yaml
|
include: package:lints/recommended.yaml
|
||||||
|
analyzer:
|
||||||
|
errors:
|
||||||
|
camel_case_types: ignore
|
||||||
|
|
||||||
# Uncomment the following section to specify additional rules.
|
# Uncomment the following section to specify additional rules.
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ library;
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -13,22 +13,30 @@
|
|||||||
|
|
||||||
import 'package:meta/meta.dart';
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
/// Annotation for field injection in CherryPick DI framework.
|
/// Marks a field for dependency injection by CherryPick's code generator.
|
||||||
/// Apply this to a field, and the code generator will automatically inject
|
|
||||||
/// the appropriate dependency into it.
|
|
||||||
///
|
///
|
||||||
/// ---
|
/// Use `@inject()` on fields within a class marked with `@injectable()`.
|
||||||
|
/// Such fields will be automatically injected from the DI [Scope]
|
||||||
|
/// when using the generated mixin or calling `.injectFields()`.
|
||||||
///
|
///
|
||||||
/// Аннотация для внедрения зависимости в поле через фреймворк CherryPick DI.
|
/// Example:
|
||||||
/// Поместите её на поле класса — генератор кода автоматически подставит нужную зависимость.
|
|
||||||
///
|
|
||||||
/// Example / Пример:
|
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// @inject()
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
/// late final SomeService service;
|
///
|
||||||
|
/// @injectable()
|
||||||
|
/// class LoginScreen with _\$LoginScreen {
|
||||||
|
/// @inject()
|
||||||
|
/// late final AuthService authService;
|
||||||
|
///
|
||||||
|
/// @inject()
|
||||||
|
/// @named('main')
|
||||||
|
/// late final ApiClient api;
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // After running build_runner, call:
|
||||||
|
/// // LoginScreen().injectFields();
|
||||||
/// ```
|
/// ```
|
||||||
@experimental
|
@experimental
|
||||||
// ignore: camel_case_types
|
|
||||||
final class inject {
|
final class inject {
|
||||||
const inject();
|
const inject();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -13,26 +13,31 @@
|
|||||||
|
|
||||||
import 'package:meta/meta.dart';
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
/// Marks a class as injectable for the CherryPick dependency injection framework.
|
/// Marks a class as injectable, enabling automatic field injection by CherryPick's code generator.
|
||||||
/// If a class is annotated with [@injectable()], the code generator will
|
|
||||||
/// create a mixin to perform automatic injection of fields marked with [@inject].
|
|
||||||
///
|
///
|
||||||
/// ---
|
/// Use `@injectable()` on a class whose fields (marked with `@inject`) you want to be automatically injected from the DI [Scope].
|
||||||
|
/// When used together with code generation (see cherrypick_generator), a mixin will be generated to inject fields.
|
||||||
///
|
///
|
||||||
/// Помечает класс как внедряемый для фреймворка внедрения зависимостей CherryPick.
|
/// Example:
|
||||||
/// Если класс помечен аннотацией [@injectable()], генератор создаст миксин
|
|
||||||
/// для автоматического внедрения полей, отмеченных [@inject].
|
|
||||||
///
|
|
||||||
/// Example / Пример:
|
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
/// @injectable()
|
/// @injectable()
|
||||||
/// class MyWidget extends StatelessWidget {
|
/// class ProfileScreen with _\$ProfileScreen {
|
||||||
/// @inject()
|
/// @inject()
|
||||||
/// late final MyService service;
|
/// late final UserManager manager;
|
||||||
|
///
|
||||||
|
/// @inject()
|
||||||
|
/// @named('main')
|
||||||
|
/// late final ApiClient api;
|
||||||
/// }
|
/// }
|
||||||
|
///
|
||||||
|
/// // After running build_runner, call:
|
||||||
|
/// // profileScreen.injectFields();
|
||||||
/// ```
|
/// ```
|
||||||
|
///
|
||||||
|
/// After running the generator, the mixin (`_\$ProfileScreen`) will be available to help auto-inject all [@inject] fields in your widget/service/controller.
|
||||||
@experimental
|
@experimental
|
||||||
// ignore: camel_case_types
|
|
||||||
final class injectable {
|
final class injectable {
|
||||||
const injectable();
|
const injectable();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,58 +11,39 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation to specify that a new instance should be provided on each request.
|
|
||||||
|
/// Marks a provider method or class to always create a new instance (factory) in CherryPick DI.
|
||||||
///
|
///
|
||||||
/// Use the `@instance()` annotation for methods or classes in your DI module
|
/// Use `@instance()` to annotate methods or classes in your DI module/class
|
||||||
/// to declare that the DI container must create a new object every time
|
/// when you want a new object to be created on every injection (no singleton caching).
|
||||||
/// the dependency is injected (i.e., no singleton behavior).
|
/// The default DI lifecycle is instance/factory unless otherwise specified.
|
||||||
///
|
///
|
||||||
/// Example:
|
/// ### Example (in a module method)
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
/// @module()
|
/// @module()
|
||||||
/// abstract class AppModule extends Module {
|
/// abstract class FeatureModule {
|
||||||
/// @instance()
|
/// @instance()
|
||||||
/// Foo foo() => Foo();
|
/// MyService provideService() => MyService();
|
||||||
|
///
|
||||||
|
/// @singleton()
|
||||||
|
/// Logger provideLogger() => Logger();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// This will generate:
|
/// ### Example (on a class, with @injectable)
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// final class $AppModule extends AppModule {
|
/// @injectable()
|
||||||
/// @override
|
/// @instance()
|
||||||
/// void builder(Scope currentScope) {
|
/// class MyFactoryClass {
|
||||||
/// bind<Foo>().toInstance(() => foo());
|
/// // ...
|
||||||
/// }
|
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// RUSSIAN (Русский):
|
/// See also: [@singleton]
|
||||||
/// Аннотация для создания нового экземпляра при каждом запросе.
|
@experimental
|
||||||
///
|
|
||||||
/// Используйте `@instance()` для методов или классов в DI-модуле,
|
|
||||||
/// чтобы указать, что контейнер внедрения зависимостей должен создавать
|
|
||||||
/// новый объект при каждом обращении к зависимости (то есть, не синглтон).
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
|
||||||
/// @module()
|
|
||||||
/// abstract class AppModule extends Module {
|
|
||||||
/// @instance()
|
|
||||||
/// Foo foo() => Foo();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Будет сгенерирован следующий код:
|
|
||||||
/// ```dart
|
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Foo>().toInstance(() => foo());
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class instance {
|
final class instance {
|
||||||
const instance();
|
const instance();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,59 +11,40 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation for marking Dart classes or libraries as modules.
|
|
||||||
|
/// Marks an abstract Dart class as a dependency injection module for CherryPick code generation.
|
||||||
///
|
///
|
||||||
/// Use the `@module()` annotation on abstract classes (or on a library)
|
/// Use `@module()` on your abstract class to indicate it provides DI bindings (via provider methods).
|
||||||
/// to indicate that the class represents a DI (Dependency Injection) module.
|
/// This enables code generation of a concrete module that registers all bindings from your methods.
|
||||||
/// This is commonly used in code generation tools to automatically register
|
|
||||||
/// and configure dependencies defined within the module.
|
|
||||||
///
|
///
|
||||||
/// Example:
|
/// Typical usage:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
/// @module()
|
/// @module()
|
||||||
/// abstract class AppModule extends Module {
|
/// abstract class AppModule {
|
||||||
/// // Dependency definitions go here.
|
/// @singleton()
|
||||||
|
/// Logger provideLogger() => Logger();
|
||||||
|
///
|
||||||
|
/// @named('mock')
|
||||||
|
/// ApiClient mockApi() => MockApiClient();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// Generates code like:
|
/// The generated code will look like:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// final class $AppModule extends AppModule {
|
/// final class $AppModule extends AppModule {
|
||||||
/// @override
|
/// @override
|
||||||
/// void builder(Scope currentScope) {
|
/// void builder(Scope currentScope) {
|
||||||
/// // Dependency registration...
|
/// // Dependency registration code...
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// RUSSIAN (Русский):
|
/// See also: [@provide], [@singleton], [@instance], [@named]
|
||||||
/// Аннотация для пометки классов или библиотек Dart как модуля.
|
@experimental
|
||||||
///
|
|
||||||
/// Используйте `@module()` для абстрактных классов (или библиотек), чтобы
|
|
||||||
/// показать, что класс реализует DI-модуль (Dependency Injection).
|
|
||||||
/// Обычно используется генераторами кода для автоматической регистрации
|
|
||||||
/// и конфигурирования зависимостей, определённых в модуле.
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
|
||||||
/// @module()
|
|
||||||
/// abstract class AppModule extends Module {
|
|
||||||
/// // Определения зависимостей
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Будет сгенерирован код:
|
|
||||||
/// ```dart
|
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// // Регистрация зависимостей...
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class module {
|
final class module {
|
||||||
/// Creates a [module] annotation.
|
/// Creates a [module] annotation for use on a DI module class.
|
||||||
const module();
|
const module();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,67 +11,52 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation to assign a name or identifier to a class, method, or other element.
|
|
||||||
|
/// Assigns a name or key identifier to a class, field, factory method or parameter
|
||||||
|
/// for use in multi-registration scenarios (named dependencies) in CherryPick DI.
|
||||||
///
|
///
|
||||||
/// The `@named('value')` annotation allows you to specify a string name
|
/// Use `@named('key')` to distinguish between multiple bindings/implementations
|
||||||
/// for a dependency, factory, or injectable. This is useful for distinguishing
|
/// of the same type—when registering and when injecting dependencies.
|
||||||
/// between multiple registrations of the same type in dependency injection,
|
|
||||||
/// code generation, and for providing human-readable metadata.
|
|
||||||
///
|
///
|
||||||
/// Example:
|
/// You can use `@named`:
|
||||||
|
/// - On provider/factory methods in a module
|
||||||
|
/// - On fields with `@inject()` to receive a named instance
|
||||||
|
/// - On function parameters (for method/constructor injection)
|
||||||
|
///
|
||||||
|
/// ### Example: On Provider Method
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// @module()
|
/// @module()
|
||||||
/// abstract class AppModule extends Module {
|
/// abstract class AppModule {
|
||||||
/// @named('dio')
|
/// @named('main')
|
||||||
/// Dio dio() => Dio();
|
/// ApiClient apiClient() => ApiClient();
|
||||||
|
///
|
||||||
|
/// @named('mock')
|
||||||
|
/// ApiClient mockApi() => MockApiClient();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// This will generate:
|
/// ### Example: On Injectable Field
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// final class $AppModule extends AppModule {
|
/// @injectable()
|
||||||
/// @override
|
/// class WidgetModel with _\$WidgetModel {
|
||||||
/// void builder(Scope currentScope) {
|
/// @inject()
|
||||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
/// @named('main')
|
||||||
/// }
|
/// late final ApiClient api;
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// RUSSIAN (Русский):
|
/// ### Example: On Parameter
|
||||||
/// Аннотация для задания имени или идентификатора классу, методу или другому элементу.
|
|
||||||
///
|
|
||||||
/// Аннотация `@named('значение')` позволяет указать строковое имя для зависимости,
|
|
||||||
/// фабрики или внедряемого значения. Это удобно для различения нескольких
|
|
||||||
/// регистраций одного типа в DI, генерации кода.
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// @module()
|
/// class UserScreen {
|
||||||
/// abstract class AppModule extends Module {
|
/// UserScreen(@named('current') User user);
|
||||||
/// @named('dio')
|
|
||||||
/// Dio dio() => Dio();
|
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
@experimental
|
||||||
/// Будет сгенерирован следующий код:
|
|
||||||
/// ```dart
|
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class named {
|
final class named {
|
||||||
/// EN: The assigned name or identifier for the element.
|
/// The assigned name or identifier for the dependency, provider, or parameter.
|
||||||
///
|
|
||||||
/// RU: Назначенное имя или идентификатор для элемента.
|
|
||||||
final String value;
|
final String value;
|
||||||
|
|
||||||
/// EN: Creates a [named] annotation with the given [value].
|
/// Creates a [named] annotation with the given [value] key or name.
|
||||||
///
|
|
||||||
/// RU: Создаёт аннотацию [named] с заданным значением [value].
|
|
||||||
const named(this.value);
|
const named(this.value);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,46 +11,33 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation to mark a method parameter for injection with run-time arguments.
|
|
||||||
|
/// Marks a parameter in a provider method to receive dynamic runtime arguments when resolving a dependency.
|
||||||
///
|
///
|
||||||
/// Use the `@params()` annotation to specify that a particular parameter of a
|
/// Use `@params()` in a DI module/factory method when the value must be supplied by the user/code at injection time,
|
||||||
/// provider method should be assigned a value supplied at resolution time,
|
/// not during static wiring (such as user input, navigation arguments, etc).
|
||||||
/// rather than during static dependency graph creation. This is useful in DI
|
///
|
||||||
/// when a dependency must receive dynamic data passed by the consumer
|
/// This enables CherryPick and its codegen to generate .withParams or .toProvideWithParams bindings — so your provider can access runtime values.
|
||||||
/// (via `.withParams(...)` in the generated code).
|
|
||||||
///
|
///
|
||||||
/// Example:
|
/// Example:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// @provide()
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
|
||||||
/// ```
|
|
||||||
///
|
///
|
||||||
/// This will generate:
|
/// @module()
|
||||||
|
/// abstract class FeatureModule {
|
||||||
|
/// @provide
|
||||||
|
/// UserManager createManager(@params Map<String, dynamic> runtimeParams) {
|
||||||
|
/// return UserManager.forUserId(runtimeParams['userId']);
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
/// Usage at injection/resolution:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
/// final manager = scope.resolve<UserManager>(params: {'userId': myId});
|
||||||
/// ```
|
/// ```
|
||||||
///
|
@experimental
|
||||||
/// RUSSIAN (Русский):
|
|
||||||
/// Аннотация для пометки параметра метода, который будет внедряться со значением во время выполнения.
|
|
||||||
///
|
|
||||||
/// Используйте `@params()` чтобы указать, что конкретный параметр метода-провайдера
|
|
||||||
/// должен получать значение, передаваемое в момент обращения к зависимости,
|
|
||||||
/// а не на этапе построения графа зависимостей. Это полезно, если зависимость
|
|
||||||
/// должна получать данные динамически от пользователя или другого процесса
|
|
||||||
/// через `.withParams(...)` в сгенерированном коде.
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
|
||||||
/// @provide()
|
|
||||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Будет сгенерировано:
|
|
||||||
/// ```dart
|
|
||||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class params {
|
final class params {
|
||||||
|
/// Marks a method/constructor parameter as supplied at runtime by the caller.
|
||||||
const params();
|
const params();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,60 +11,34 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation to declare a factory/provider method or class as a singleton.
|
|
||||||
|
/// Marks a method or class as a dependency provider (factory/provider) for CherryPick module code generation.
|
||||||
///
|
///
|
||||||
/// Use the `@singleton()` annotation on methods in your DI module to specify
|
/// Use `@provide` on any method inside a `@module()` annotated class when you want that method
|
||||||
/// that only one instance of the resulting object should be created and shared
|
/// to be used as a DI factory/provider during code generation.
|
||||||
/// for all consumers. This is especially useful in dependency injection
|
///
|
||||||
/// frameworks and service locators.
|
/// This should be used for methods that create dynamic, optional, or complex dependencies, especially
|
||||||
|
/// if you want to control the codegen/injection pipeline explicitly and support parameters.
|
||||||
///
|
///
|
||||||
/// Example:
|
/// Example:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
/// @module()
|
/// @module()
|
||||||
/// abstract class AppModule extends Module {
|
/// abstract class FeatureModule {
|
||||||
|
/// @provide
|
||||||
|
/// Future<Api> provideApi(@params Map<String, dynamic> args) async => ...;
|
||||||
|
///
|
||||||
/// @singleton()
|
/// @singleton()
|
||||||
/// Dio dio() => Dio();
|
/// @provide
|
||||||
|
/// Logger provideLogger() => Logger();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// This generates the following code:
|
/// See also: [@singleton], [@instance], [@params], [@named]
|
||||||
/// ```dart
|
@experimental
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// RUSSIAN (Русский):
|
|
||||||
/// Аннотация для объявления фабричного/провайдерного метода или класса синглтоном.
|
|
||||||
///
|
|
||||||
/// Используйте `@singleton()` для методов внутри DI-модуля, чтобы указать,
|
|
||||||
/// что соответствующий объект (экземпляр класса) должен быть создан только один раз
|
|
||||||
/// и использоваться всеми компонентами приложения (единый общий экземпляр).
|
|
||||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов.
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
|
||||||
/// @module()
|
|
||||||
/// abstract class AppModule extends Module {
|
|
||||||
/// @singleton()
|
|
||||||
/// Dio dio() => Dio();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Будет сгенерирован следующий код:
|
|
||||||
/// ```dart
|
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class provide {
|
final class provide {
|
||||||
|
/// Creates a [provide] annotation.
|
||||||
const provide();
|
const provide();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -13,25 +13,41 @@
|
|||||||
|
|
||||||
import 'package:meta/meta.dart';
|
import 'package:meta/meta.dart';
|
||||||
|
|
||||||
/// Annotation to specify a scope for dependency injection in CherryPick.
|
/// Specifies the DI scope or region from which a dependency should be resolved.
|
||||||
/// Use this on an injected field to indicate from which scope
|
|
||||||
/// the dependency must be resolved.
|
|
||||||
///
|
///
|
||||||
/// ---
|
/// Use `@scope('scopeName')` on an injected field, parameter, or provider method when you want
|
||||||
|
/// to resolve a dependency not from the current scope, but from another named scope/subcontainer.
|
||||||
///
|
///
|
||||||
/// Аннотация для указания области внедрения (scope) в CherryPick.
|
/// Useful for advanced DI scenarios: multi-feature/state isolation, navigation stacks, explicit subscopes, or testing.
|
||||||
/// Используйте её на инъецируемом поле, чтобы определить из какой области
|
|
||||||
/// должна быть получена зависимость.
|
|
||||||
///
|
///
|
||||||
/// Example / Пример:
|
/// Example (injected field):
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// @inject()
|
/// @injectable()
|
||||||
/// @scope('profile')
|
/// class ProfileScreen with _\$ProfileScreen {
|
||||||
/// late final ProfileManager profileManager;
|
/// @inject()
|
||||||
|
/// @scope('profile')
|
||||||
|
/// late final ProfileManager manager;
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Example (parameter):
|
||||||
|
/// ```dart
|
||||||
|
/// class TabBarModel {
|
||||||
|
/// TabBarModel(@scope('tabs') TabContext context);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Example (in a module):
|
||||||
|
/// ```dart
|
||||||
|
/// @module()
|
||||||
|
/// abstract class FeatureModule {
|
||||||
|
/// @provide
|
||||||
|
/// Service service(@scope('shared') SharedConfig config);
|
||||||
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@experimental
|
@experimental
|
||||||
// ignore: camel_case_types
|
|
||||||
final class scope {
|
final class scope {
|
||||||
|
/// The name/key of the DI scope from which to resolve this dependency.
|
||||||
final String? name;
|
final String? name;
|
||||||
const scope(this.name);
|
const scope(this.name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -11,63 +11,32 @@
|
|||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
|
||||||
/// ENGLISH:
|
import 'package:meta/meta.dart';
|
||||||
/// Annotation to declare a dependency as a singleton.
|
|
||||||
|
/// Marks a provider method or class so its instance is created only once and shared (singleton) for DI in CherryPick.
|
||||||
///
|
///
|
||||||
/// Use the `@singleton()` annotation on provider methods inside a module
|
/// Use `@singleton()` on provider methods or classes in your DI module to ensure only one instance is ever created
|
||||||
/// to indicate that only a single instance of this dependency should be
|
/// and reused across the application's lifetime (or scope lifetime).
|
||||||
/// created and shared throughout the application's lifecycle. This is
|
|
||||||
/// typically used in dependency injection frameworks or service locators
|
|
||||||
/// to guarantee a single shared instance.
|
|
||||||
///
|
///
|
||||||
/// Example:
|
/// Example:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
/// @module()
|
/// @module()
|
||||||
/// abstract class AppModule extends Module {
|
/// abstract class AppModule {
|
||||||
/// @singleton()
|
/// @singleton()
|
||||||
/// Dio dio() => Dio();
|
/// ApiClient createApi() => ApiClient();
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// This will generate code like:
|
/// The generated code will ensure:
|
||||||
/// ```dart
|
/// ```dart
|
||||||
/// final class $AppModule extends AppModule {
|
/// bind<ApiClient>().toProvide(() => createApi()).singleton();
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// RUSSIAN (Русский):
|
/// See also: [@instance], [@provide], [@named]
|
||||||
/// Аннотация для объявления зависимости как синглтона.
|
@experimental
|
||||||
///
|
|
||||||
/// Используйте `@singleton()` для методов-провайдеров внутри модуля,
|
|
||||||
/// чтобы указать, что соответствующий объект должен быть создан
|
|
||||||
/// единожды и использоваться во всём приложении (общий синглтон).
|
|
||||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов,
|
|
||||||
/// чтобы гарантировать один общий экземпляр.
|
|
||||||
///
|
|
||||||
/// Пример:
|
|
||||||
/// ```dart
|
|
||||||
/// @module()
|
|
||||||
/// abstract class AppModule extends Module {
|
|
||||||
/// @singleton()
|
|
||||||
/// Dio dio() => Dio();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Будет сгенерирован следующий код:
|
|
||||||
/// ```dart
|
|
||||||
/// final class $AppModule extends AppModule {
|
|
||||||
/// @override
|
|
||||||
/// void builder(Scope currentScope) {
|
|
||||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
// ignore: camel_case_types
|
|
||||||
final class singleton {
|
final class singleton {
|
||||||
/// Creates a [singleton] annotation.
|
/// Creates a [singleton] annotation for DI providers/classes.
|
||||||
const singleton();
|
const singleton();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
name: cherrypick_annotations
|
name: cherrypick_annotations
|
||||||
description: |
|
description: |
|
||||||
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
||||||
version: 1.1.0
|
version: 1.1.2-dev.0
|
||||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||||
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
|
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
|
||||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||||
|
|||||||
@@ -1,3 +1,15 @@
|
|||||||
|
## 1.1.3-dev.9
|
||||||
|
|
||||||
|
- **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration.
|
||||||
|
|
||||||
|
## 1.1.3-dev.8
|
||||||
|
|
||||||
|
- Update a dependency to the latest release.
|
||||||
|
|
||||||
|
## 1.1.3-dev.7
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
## 1.1.3-dev.6
|
## 1.1.3-dev.6
|
||||||
|
|
||||||
- Update a dependency to the latest release.
|
- Update a dependency to the latest release.
|
||||||
|
|||||||
@@ -192,7 +192,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -94,4 +94,4 @@ Contributions to improve this library are welcome. Feel free to open issues and
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
||||||
@@ -4,7 +4,7 @@ library;
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart';
|
|||||||
/// Licensed under the Apache License, Version 2.0 (the "License");
|
/// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
/// you may not use this file except in compliance with the License.
|
/// you may not use this file except in compliance with the License.
|
||||||
/// You may obtain a copy of the License at
|
/// You may obtain a copy of the License at
|
||||||
/// http://www.apache.org/licenses/LICENSE-2.0
|
/// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
/// Unless required by applicable law or agreed to in writing, software
|
/// Unless required by applicable law or agreed to in writing, software
|
||||||
/// distributed under the License is distributed on an "AS IS" BASIS,
|
/// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -14,29 +14,87 @@ import 'package:flutter/widgets.dart';
|
|||||||
/// limitations under the License.
|
/// limitations under the License.
|
||||||
///
|
///
|
||||||
|
|
||||||
|
/// {@template cherrypick_flutter_provider}
|
||||||
|
/// An [InheritedWidget] that provides convenient integration of CherryPick
|
||||||
|
/// dependency injection scopes into the Flutter widget tree.
|
||||||
|
///
|
||||||
|
/// Place `CherryPickProvider` at the top of your widget subtree to make a
|
||||||
|
/// [Scope] (or its descendants) available via `CherryPickProvider.of(context)`.
|
||||||
|
///
|
||||||
|
/// This is the recommended entry point for connecting CherryPick DI to your
|
||||||
|
/// Flutter app or feature area, enabling context-based scope management and
|
||||||
|
/// DI resolution in child widgets.
|
||||||
|
///
|
||||||
|
/// ### Example: Root Integration
|
||||||
|
/// ```dart
|
||||||
|
/// void main() {
|
||||||
|
/// final rootScope = CherryPick.openRootScope()
|
||||||
|
/// ..installModules([AppModule()]);
|
||||||
|
/// runApp(
|
||||||
|
/// CherryPickProvider(
|
||||||
|
/// child: MyApp(),
|
||||||
|
/// ),
|
||||||
|
/// );
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // In any widget:
|
||||||
|
/// final provider = CherryPickProvider.of(context);
|
||||||
|
/// final scope = provider.openRootScope();
|
||||||
|
/// final myService = scope.resolve<MyService>();
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ### Example: Subscope for a Feature/Screen
|
||||||
|
/// ```dart
|
||||||
|
/// Widget build(BuildContext context) {
|
||||||
|
/// final provider = CherryPickProvider.of(context);
|
||||||
|
/// final featureScope = provider.openSubScope(scopeName: 'featureA');
|
||||||
|
/// return MyFeatureScreen(scope: featureScope);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// You can use [openRootScope] and [openSubScope] as helpers to get/create scopes.
|
||||||
|
/// {@endtemplate}
|
||||||
final class CherryPickProvider extends InheritedWidget {
|
final class CherryPickProvider extends InheritedWidget {
|
||||||
|
/// Opens (or returns) the application-wide root [Scope].
|
||||||
|
///
|
||||||
|
/// Use to make all dependencies available at the top of your widget tree.
|
||||||
Scope openRootScope() => CherryPick.openRootScope();
|
Scope openRootScope() => CherryPick.openRootScope();
|
||||||
|
|
||||||
|
/// Opens a subscope (child [Scope]) with the given [scopeName].
|
||||||
|
///
|
||||||
|
/// Useful to create isolated feature/module scopes in widget subtrees.
|
||||||
|
/// If [scopeName] is empty, an unnamed scope is created.
|
||||||
Scope openSubScope({String scopeName = '', String separator = '.'}) =>
|
Scope openSubScope({String scopeName = '', String separator = '.'}) =>
|
||||||
CherryPick.openScope(scopeName: scopeName, separator: separator);
|
CherryPick.openScope(scopeName: scopeName, separator: separator);
|
||||||
|
|
||||||
// Constructor for CherryPickProvider. Initializes with a required rootScope and child widget.
|
/// Creates a [CherryPickProvider] and exposes it to the widget subtree.
|
||||||
|
///
|
||||||
|
/// Place near the root of your widget tree. Use [child] to provide the subtree.
|
||||||
const CherryPickProvider({
|
const CherryPickProvider({
|
||||||
super.key,
|
super.key,
|
||||||
required super.child,
|
required super.child,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Method to access the nearest CherryPickProvider instance from the context
|
/// Locates the nearest [CherryPickProvider] up the widget tree from [context].
|
||||||
|
///
|
||||||
|
/// Throws if not found. Use this to access DI [Scope] controls anywhere below the provider.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final provider = CherryPickProvider.of(context);
|
||||||
|
/// final scope = provider.openRootScope();
|
||||||
|
/// ```
|
||||||
static CherryPickProvider of(BuildContext context) {
|
static CherryPickProvider of(BuildContext context) {
|
||||||
// Looks up the widget tree for an instance of CherryPickProvider
|
|
||||||
final CherryPickProvider? result =
|
final CherryPickProvider? result =
|
||||||
context.dependOnInheritedWidgetOfExactType<CherryPickProvider>();
|
context.dependOnInheritedWidgetOfExactType<CherryPickProvider>();
|
||||||
// Assert to ensure a CherryPickProvider is present in the context
|
|
||||||
assert(result != null, 'No CherryPickProvider found in context');
|
assert(result != null, 'No CherryPickProvider found in context');
|
||||||
return result!;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determines whether the widget should notify dependents when it changes
|
/// Controls update notifications for dependent widgets.
|
||||||
|
///
|
||||||
|
/// Always returns false because the provider itself is stateless:
|
||||||
|
/// changes are to the underlying scopes, not the widget.
|
||||||
@override
|
@override
|
||||||
bool updateShouldNotify(CherryPickProvider oldWidget) {
|
bool updateShouldNotify(CherryPickProvider oldWidget) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
name: cherrypick_flutter
|
name: cherrypick_flutter
|
||||||
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
||||||
version: 1.1.3-dev.6
|
version: 1.1.3-dev.9
|
||||||
homepage: https://pese-git.github.io/cherrypick-site/
|
homepage: https://pese-git.github.io/cherrypick-site/
|
||||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||||
repository: https://github.com/pese-git/cherrypick
|
repository: https://github.com/pese-git/cherrypick
|
||||||
@@ -19,7 +19,7 @@ environment:
|
|||||||
dependencies:
|
dependencies:
|
||||||
flutter:
|
flutter:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
cherrypick: ^3.0.0-dev.6
|
cherrypick: ^3.0.0-dev.9
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
## 2.0.0-dev.0
|
||||||
|
|
||||||
|
> Note: This release has breaking changes.
|
||||||
|
|
||||||
|
- **BREAKING** **DOCS**(generator): improve and unify English documentation and examples for all DI source files.
|
||||||
|
|
||||||
|
## 1.1.1
|
||||||
|
|
||||||
|
- **FIX**(license): correct urls.
|
||||||
|
|
||||||
## 1.1.0
|
## 1.1.0
|
||||||
|
|
||||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||||
|
|||||||
@@ -192,7 +192,7 @@
|
|||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
|||||||
@@ -1,17 +1,37 @@
|
|||||||
library;
|
|
||||||
|
|
||||||
//
|
//
|
||||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
//
|
//
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// CherryPick code generation library: entry point for build_runner DI codegen.
|
||||||
|
///
|
||||||
|
/// This library exports generators for CherryPick dependency injection:
|
||||||
|
/// - [ModuleGenerator]: Generates DI module classes for all `@module()`-annotated classes.
|
||||||
|
/// - [InjectGenerator]: Generates field-injection mixins for classes annotated with `@injectable()`.
|
||||||
|
///
|
||||||
|
/// These generators are hooked into [build_runner] and cherrypick_generator's builder configuration.
|
||||||
|
/// Normally you do not import this directly; instead, add cherrypick_generator
|
||||||
|
/// as a dev_dependency and run `dart run build_runner build`.
|
||||||
|
///
|
||||||
|
/// Example usage in `build.yaml` or your project's workflow:
|
||||||
|
/// ```yaml
|
||||||
|
/// targets:
|
||||||
|
/// $default:
|
||||||
|
/// builders:
|
||||||
|
/// cherrypick_generator|cherrypick_generator:
|
||||||
|
/// generate_for:
|
||||||
|
/// - lib/**.dart
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// For annotation details, see `package:cherrypick_annotations`.
|
||||||
export 'module_generator.dart';
|
export 'module_generator.dart';
|
||||||
export 'inject_generator.dart';
|
export 'inject_generator.dart';
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -20,28 +20,85 @@ import 'package:source_gen/source_gen.dart';
|
|||||||
import 'package:analyzer/dart/element/element.dart';
|
import 'package:analyzer/dart/element/element.dart';
|
||||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||||
|
|
||||||
/// InjectGenerator generates a mixin for a class marked with @injectable()
|
/// CherryPick DI field injector generator for codegen.
|
||||||
/// and injects all fields annotated with @inject(), using CherryPick DI.
|
|
||||||
///
|
///
|
||||||
/// For Future<T> fields it calls .resolveAsync<T>(),
|
/// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`)
|
||||||
/// otherwise .resolve<T>() is used. Scope and named qualifiers are supported.
|
/// which contains the `_inject` method. This method will assign all fields annotated with `@inject()`
|
||||||
|
/// using the CherryPick DI container. Extra annotation qualifiers such as `@named` and `@scope` are respected
|
||||||
|
/// for each field. Nullable fields and Future/injectable async dependencies are also supported automatically.
|
||||||
///
|
///
|
||||||
/// ---
|
/// ---
|
||||||
///
|
///
|
||||||
/// InjectGenerator генерирует миксин для класса с аннотацией @injectable()
|
/// ### Example usage in a project:
|
||||||
/// и внедряет все поля, помеченные @inject(), используя DI-фреймворк CherryPick.
|
|
||||||
///
|
///
|
||||||
/// Для Future<T> полей вызывается .resolveAsync<T>(),
|
/// ```dart
|
||||||
/// для остальных — .resolve<T>(). Поддерживаются scope и named qualifier.
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
///
|
///
|
||||||
|
/// @injectable()
|
||||||
|
/// class MyScreen with _$MyScreen {
|
||||||
|
/// @inject()
|
||||||
|
/// late final Logger logger;
|
||||||
|
///
|
||||||
|
/// @inject()
|
||||||
|
/// @named('test')
|
||||||
|
/// late final HttpClient client;
|
||||||
|
///
|
||||||
|
/// @inject()
|
||||||
|
/// Future<Analytics>? analytics;
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// After running build_runner, this mixin will be auto-generated:
|
||||||
|
///
|
||||||
|
/// ```dart
|
||||||
|
/// mixin _$MyScreen {
|
||||||
|
/// void _inject(MyScreen instance) {
|
||||||
|
/// instance.logger = CherryPick.openRootScope().resolve<Logger>();
|
||||||
|
/// instance.client = CherryPick.openRootScope().resolve<HttpClient>(named: 'test');
|
||||||
|
/// instance.analytics = CherryPick.openRootScope().tryResolveAsync<Analytics>(); // nullable async inject
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// You may use the mixin (e.g., `myScreen._inject(myScreen)`) or expose your own public helper for instance field injection.
|
||||||
|
///
|
||||||
|
/// **Supported scenarios:**
|
||||||
|
/// - Ordinary injectable fields: `resolve<T>()`.
|
||||||
|
/// - Named qualifiers: `resolve<T>(named: ...)`.
|
||||||
|
/// - Scoping: `CherryPick.openScope(scopeName: ...).resolve<T>()`.
|
||||||
|
/// - Nullable/incomplete fields: `tryResolve`/`tryResolveAsync`.
|
||||||
|
/// - Async dependencies: `Future<T>`/`resolveAsync<T>()`.
|
||||||
|
///
|
||||||
|
/// See also:
|
||||||
|
/// * @inject
|
||||||
|
/// * @injectable
|
||||||
class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||||
const InjectGenerator();
|
const InjectGenerator();
|
||||||
|
|
||||||
/// The main entry point for code generation.
|
/// Main entry point for CherryPick field injection code generation.
|
||||||
///
|
///
|
||||||
/// Checks class validity, collects injectable fields, and produces injection code.
|
/// - Only triggers for classes marked with `@injectable()`.
|
||||||
|
/// - Throws an error if used on non-class elements.
|
||||||
|
/// - Scans all fields marked with `@inject()` and gathers qualifiers (if any).
|
||||||
|
/// - Generates Dart code for a mixin that injects all dependencies into the target class instance.
|
||||||
///
|
///
|
||||||
/// Основная точка входа генератора. Проверяет класс, собирает инъектируемые поля и создает код внедрения зависимостей.
|
/// Returns the Dart code as a String defining the new mixin.
|
||||||
|
///
|
||||||
|
/// Example input (user code):
|
||||||
|
/// ```dart
|
||||||
|
/// @injectable()
|
||||||
|
/// class UserBloc with _$UserBloc {
|
||||||
|
/// @inject() late final AuthRepository authRepository;
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
/// Example output (generated):
|
||||||
|
/// ```dart
|
||||||
|
/// mixin _$UserBloc {
|
||||||
|
/// void _inject(UserBloc instance) {
|
||||||
|
/// instance.authRepository = CherryPick.openRootScope().resolve<AuthRepository>();
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
@override
|
@override
|
||||||
FutureOr<String> generateForAnnotatedElement(
|
FutureOr<String> generateForAnnotatedElement(
|
||||||
Element element,
|
Element element,
|
||||||
@@ -63,8 +120,7 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
..writeln('mixin $mixinName {')
|
..writeln('mixin $mixinName {')
|
||||||
..writeln(' void _inject($className instance) {');
|
..writeln(' void _inject($className instance) {');
|
||||||
|
|
||||||
// Collect and process all @inject fields.
|
// Collect and process all @inject fields
|
||||||
// Собираем и обрабатываем все поля с @inject.
|
|
||||||
final injectFields =
|
final injectFields =
|
||||||
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
||||||
|
|
||||||
@@ -79,20 +135,20 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
return buffer.toString();
|
return buffer.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if a field has the @inject annotation.
|
/// Returns true if a field is annotated with `@inject`.
|
||||||
///
|
///
|
||||||
/// Проверяет, отмечено ли поле аннотацией @inject.
|
/// Used to detect which fields should be processed for injection.
|
||||||
static bool _isInjectField(FieldElement field) {
|
static bool _isInjectField(FieldElement field) {
|
||||||
return field.metadata.any(
|
return field.metadata.any(
|
||||||
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses the field for scope/named qualifiers and determines its type.
|
/// Parses `@inject()` field and extracts all injection metadata
|
||||||
/// Returns a [_ParsedInjectField] describing injection information.
|
/// (core type, qualifiers, scope, nullability, etc).
|
||||||
///
|
///
|
||||||
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
|
/// Converts Dart field declaration and all parameterizing injection-related
|
||||||
/// Возвращает [_ParsedInjectField] с информацией о внедрении.
|
/// annotations into a [_ParsedInjectField] which is used for codegen.
|
||||||
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
||||||
String? scopeName;
|
String? scopeName;
|
||||||
String? namedValue;
|
String? namedValue;
|
||||||
@@ -120,8 +176,7 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
isFuture = false;
|
isFuture = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ***
|
// Determine nullability for field types like T? or Future<T?>
|
||||||
// Добавим определение nullable для типа (например PostRepository? или Future<PostRepository?>)
|
|
||||||
bool isNullable = dartType.nullabilitySuffix ==
|
bool isNullable = dartType.nullabilitySuffix ==
|
||||||
NullabilitySuffix.question ||
|
NullabilitySuffix.question ||
|
||||||
(dartType is ParameterizedType &&
|
(dartType is ParameterizedType &&
|
||||||
@@ -139,13 +194,17 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates a line of code that performs the dependency injection for a field.
|
/// Generates Dart code for a single dependency-injected field based on its metadata.
|
||||||
/// Handles resolve/resolveAsync, scoping, and named qualifiers.
|
|
||||||
///
|
///
|
||||||
/// Генерирует строку кода, которая внедряет зависимость для поля.
|
/// This code will resolve the field from the CherryPick DI container and assign it to the class instance.
|
||||||
/// Учитывает resolve/resolveAsync, scoping и named qualifier.
|
/// Correctly dispatches to resolve, tryResolve, resolveAsync, or tryResolveAsync methods,
|
||||||
|
/// and applies container scoping or named resolution where required.
|
||||||
|
///
|
||||||
|
/// Returns literal Dart code as string (1 line).
|
||||||
|
///
|
||||||
|
/// Example output:
|
||||||
|
/// `instance.logger = CherryPick.openRootScope().resolve<Logger>();`
|
||||||
String _generateInjectionLine(_ParsedInjectField field) {
|
String _generateInjectionLine(_ParsedInjectField field) {
|
||||||
// Используем tryResolve для nullable, иначе resolve
|
|
||||||
final resolveMethod = field.isFuture
|
final resolveMethod = field.isFuture
|
||||||
? (field.isNullable
|
? (field.isNullable
|
||||||
? 'tryResolveAsync<${field.coreType}>'
|
? 'tryResolveAsync<${field.coreType}>'
|
||||||
@@ -166,29 +225,29 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Data structure representing all information required to generate
|
/// Internal structure: describes all required information for generating the injection
|
||||||
/// injection code for a field.
|
/// assignment for a given field.
|
||||||
///
|
///
|
||||||
/// Структура данных, содержащая всю информацию,
|
/// Not exported. Used as a DTO in the generator for each field.
|
||||||
/// необходимую для генерации кода внедрения для поля.
|
|
||||||
class _ParsedInjectField {
|
class _ParsedInjectField {
|
||||||
/// The name of the field / Имя поля.
|
/// The name of the field to be injected.
|
||||||
final String fieldName;
|
final String fieldName;
|
||||||
|
|
||||||
/// The base type name (T or Future<T>) / Базовый тип (T или тип из Future<T>).
|
/// The Dart type to resolve (e.g. `Logger` from `Logger` or `Future<Logger>`).
|
||||||
final String coreType;
|
final String coreType;
|
||||||
|
|
||||||
/// True if the field type is Future<T>; false otherwise
|
/// True if the field is an async dependency (Future<...>), otherwise false.
|
||||||
/// Истина, если поле — Future<T>, иначе — ложь.
|
|
||||||
final bool isFuture;
|
final bool isFuture;
|
||||||
|
|
||||||
/// Optional scope annotation argument / Опциональное имя scope.
|
/// True if the field accepts null (T?), otherwise false.
|
||||||
|
final bool isNullable;
|
||||||
|
|
||||||
|
/// The scoping for DI resolution, or null to use root scope.
|
||||||
final String? scopeName;
|
final String? scopeName;
|
||||||
|
|
||||||
/// Optional named annotation argument / Опциональное имя named.
|
/// Name qualifier for named resolution, or null if not set.
|
||||||
final String? namedValue;
|
final String? namedValue;
|
||||||
|
|
||||||
final bool isNullable;
|
|
||||||
|
|
||||||
_ParsedInjectField({
|
_ParsedInjectField({
|
||||||
required this.fieldName,
|
required this.fieldName,
|
||||||
@@ -200,8 +259,8 @@ class _ParsedInjectField {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builder factory. Used by build_runner.
|
/// Factory for creating the build_runner builder for DI field injection.
|
||||||
///
|
///
|
||||||
/// Фабрика билдера. Используется build_runner.
|
/// Add this builder in your build.yaml if you're invoking CherryPick generators manually.
|
||||||
Builder injectBuilder(BuilderOptions options) =>
|
Builder injectBuilder(BuilderOptions options) =>
|
||||||
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -19,75 +19,89 @@ import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
|||||||
import 'src/generated_class.dart';
|
import 'src/generated_class.dart';
|
||||||
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
/// ModuleGenerator for code generation of dependency-injected modules.
|
/// CherryPick Module Generator — Codegen for DI modules
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// This generator scans Dart classes annotated with `@module()` and generates
|
||||||
/// This generator scans for Dart classes annotated with `@module()` and
|
/// boilerplate for dependency injection registration automatically. Each public
|
||||||
/// automatically generates boilerplate code for dependency injection
|
/// method in such classes can be annotated to describe how an object should be
|
||||||
/// (DI) based on the public methods in those classes. Each method can be
|
/// bound to the DI container (singleton, factory, named, with parameters, etc).
|
||||||
/// annotated to describe how an object should be provided to the DI container.
|
|
||||||
/// The generated code registers those methods as bindings. This automates the
|
|
||||||
/// creation of factories, singletons, and named instances, reducing repetitive
|
|
||||||
/// manual code.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// The generated code collects all such bind methods and produces a Dart
|
||||||
/// Генератор зависимостей для DI-контейнера на основе аннотаций.
|
/// companion *module registration class* with a `.bindAll()` method, which you
|
||||||
/// Данный генератор автоматически создаёт код для внедрения зависимостей (DI)
|
/// can use from your DI root to automatically register those dependencies.
|
||||||
/// на основе аннотаций в вашем исходном коде. Когда вы отмечаете класс
|
///
|
||||||
/// аннотацией `@module()`, этот генератор обработает все его публичные методы
|
/// ## Example
|
||||||
/// и автоматически сгенерирует класс с биндингами (регистрациями зависимостей)
|
/// ```dart
|
||||||
/// для DI-контейнера. Это избавляет от написания однообразного шаблонного кода.
|
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
|
///
|
||||||
|
/// @module()
|
||||||
|
/// abstract class AppModule {
|
||||||
|
/// @singleton()
|
||||||
|
/// Logger logger() => Logger();
|
||||||
|
///
|
||||||
|
/// @provide()
|
||||||
|
/// ApiService api(Logger logger) => ApiService(logger);
|
||||||
|
///
|
||||||
|
/// @named('dev')
|
||||||
|
/// FakeService fake() => FakeService();
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// After codegen, you will get (simplified):
|
||||||
|
/// ```dart
|
||||||
|
/// class _\$AppModuleCherrypickModule extend AppModule {
|
||||||
|
/// static void bindAll(CherryPickScope scope, AppModule module) {
|
||||||
|
/// scope.addSingleton<Logger>(() => module.logger());
|
||||||
|
/// scope.addFactory<ApiService>(() => module.api(scope.resolve<Logger>()));
|
||||||
|
/// scope.addFactory<FakeService>(() => module.fake(), named: 'dev');
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Use it e.g. in your bootstrap:
|
||||||
|
/// ```dart
|
||||||
|
/// final scope = CherryPick.openRootScope()..intallModules([_\$AppModuleCherrypickModule()]);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Features supported:
|
||||||
|
/// - Singleton, factory, named, parametric, and async providers
|
||||||
|
/// - Eliminates all boilerplate for DI registration
|
||||||
|
/// - Works with abstract classes and real classes
|
||||||
|
/// - Error if @module() is applied to a non-class
|
||||||
|
///
|
||||||
|
/// See also: [@singleton], [@provide], [@named], [@module]
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
||||||
/// -------------------------------------------------------------------------
|
/// Generates Dart source for a class marked with the `@module()` annotation.
|
||||||
/// ENGLISH
|
|
||||||
/// Generates the Dart source for a class marked with the `@module()` annotation.
|
|
||||||
/// - [element]: the original Dart class element.
|
|
||||||
/// - [annotation]: the annotation parameters (not usually used here).
|
|
||||||
/// - [buildStep]: the current build step info.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Throws [InvalidGenerationSourceError] if used on anything except a class.
|
||||||
/// Генерирует исходный код для класса-модуля с аннотацией `@module()`.
|
///
|
||||||
/// [element] — исходный класс, помеченный аннотацией.
|
/// See file-level docs for usage and generated output example.
|
||||||
/// [annotation] — значения параметров аннотации.
|
|
||||||
/// [buildStep] — информация о текущем шаге генерации.
|
|
||||||
/// -------------------------------------------------------------------------
|
|
||||||
@override
|
@override
|
||||||
String generateForAnnotatedElement(
|
String generateForAnnotatedElement(
|
||||||
Element element,
|
Element element,
|
||||||
ConstantReader annotation,
|
ConstantReader annotation,
|
||||||
BuildStep buildStep,
|
BuildStep buildStep,
|
||||||
) {
|
) {
|
||||||
// Only classes are supported for @module() annotation
|
|
||||||
// Обрабатываются только классы (другие элементы — ошибка)
|
|
||||||
if (element is! ClassElement) {
|
if (element is! ClassElement) {
|
||||||
throw InvalidGenerationSourceError(
|
throw InvalidGenerationSourceError(
|
||||||
'@module() can only be applied to classes. / @module() может быть применён только к классам.',
|
'@module() can only be applied to classes.',
|
||||||
element: element,
|
element: element,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final classElement = element;
|
final classElement = element;
|
||||||
|
|
||||||
// Build a representation of the generated bindings based on class methods /
|
|
||||||
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса
|
|
||||||
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
||||||
|
|
||||||
// Generate the resulting Dart code / Генерирует итоговый Dart-код
|
|
||||||
return generatedClass.generate();
|
return generatedClass.generate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
/// ENGLISH
|
/// Codegen builder entry point: register this builder in build.yaml or your package.
|
||||||
/// Entry point for build_runner. Returns a Builder used to generate code for
|
|
||||||
/// every file with a @module() annotation.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Used by build_runner. Generates .module.cherrypick.g.dart files for each
|
||||||
/// Точка входа для генератора build_runner.
|
/// source file with an annotated @module() class.
|
||||||
/// Возвращает Builder, используемый build_runner для генерации кода для всех
|
|
||||||
/// файлов, где встречается @module().
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
Builder moduleBuilder(BuilderOptions options) =>
|
Builder moduleBuilder(BuilderOptions options) =>
|
||||||
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -15,9 +15,43 @@ import 'package:analyzer/dart/element/element.dart';
|
|||||||
import 'exceptions.dart';
|
import 'exceptions.dart';
|
||||||
import 'metadata_utils.dart';
|
import 'metadata_utils.dart';
|
||||||
|
|
||||||
/// Validates annotation combinations and usage patterns
|
/// Provides static utility methods for validating annotation usage in CherryPick
|
||||||
|
/// dependency injection code generation.
|
||||||
|
///
|
||||||
|
/// This validator helps ensure that `@provide`, `@instance`, `@singleton`, `@params`,
|
||||||
|
/// `@inject`, `@named`, `@module`, and `@injectable` annotations are correctly and safely
|
||||||
|
/// combined in your codebase, preventing common configuration and codegen errors before
|
||||||
|
/// code is generated.
|
||||||
|
///
|
||||||
|
/// #### Example Usage
|
||||||
|
/// ```dart
|
||||||
|
/// void processMethod(MethodElement method) {
|
||||||
|
/// AnnotationValidator.validateMethodAnnotations(method);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// All exceptions are thrown as [AnnotationValidationException] and will include
|
||||||
|
/// a helpful message and context.
|
||||||
|
///
|
||||||
|
/// ---
|
||||||
|
/// Typical checks performed by this utility:
|
||||||
|
/// - Mutual exclusivity (`@instance` vs `@provide`)
|
||||||
|
/// - Required presence for fields and methods
|
||||||
|
/// - Proper parameters for `@named` and `@params`
|
||||||
|
/// - Correct usage of injectable fields, module class methods, etc.
|
||||||
|
///
|
||||||
class AnnotationValidator {
|
class AnnotationValidator {
|
||||||
/// Validates annotations on a method element
|
/// Validates annotations for a given [MethodElement].
|
||||||
|
///
|
||||||
|
/// Checks:
|
||||||
|
/// - Mutual exclusivity of `@instance` and `@provide`.
|
||||||
|
/// - That a method is annotated with exactly one DI-producing annotation.
|
||||||
|
/// - If `@params` is present, that it is used together with `@provide`.
|
||||||
|
/// - Appropriate usage of `@singleton`.
|
||||||
|
/// - [@named] syntax and conventions.
|
||||||
|
/// - Parameter validation for method arguments.
|
||||||
|
///
|
||||||
|
/// Throws [AnnotationValidationException] on any violation.
|
||||||
static void validateMethodAnnotations(MethodElement method) {
|
static void validateMethodAnnotations(MethodElement method) {
|
||||||
final annotations = _getAnnotationNames(method.metadata);
|
final annotations = _getAnnotationNames(method.metadata);
|
||||||
|
|
||||||
@@ -26,14 +60,28 @@ class AnnotationValidator {
|
|||||||
_validateAnnotationParameters(method);
|
_validateAnnotationParameters(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates annotations on a field element
|
/// Validates that a [FieldElement] has correct injection annotations.
|
||||||
|
///
|
||||||
|
/// Specifically, ensures:
|
||||||
|
/// - Injectable fields are of valid type.
|
||||||
|
/// - No `void` injection.
|
||||||
|
/// - Correct scope naming if present.
|
||||||
|
///
|
||||||
|
/// Throws [AnnotationValidationException] if checks fail.
|
||||||
static void validateFieldAnnotations(FieldElement field) {
|
static void validateFieldAnnotations(FieldElement field) {
|
||||||
final annotations = _getAnnotationNames(field.metadata);
|
final annotations = _getAnnotationNames(field.metadata);
|
||||||
|
|
||||||
_validateInjectFieldAnnotations(field, annotations);
|
_validateInjectFieldAnnotations(field, annotations);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates annotations on a class element
|
/// Validates all class-level DI annotations.
|
||||||
|
///
|
||||||
|
/// Executes checks for:
|
||||||
|
/// - Module class validity (e.g. must have public DI methods if `@module`).
|
||||||
|
/// - Injectable class: at least one @inject field, field finalness, etc.
|
||||||
|
/// - Provides helpful context for error/warning reporting.
|
||||||
|
///
|
||||||
|
/// Throws [AnnotationValidationException] if checks fail.
|
||||||
static void validateClassAnnotations(ClassElement classElement) {
|
static void validateClassAnnotations(ClassElement classElement) {
|
||||||
final annotations = _getAnnotationNames(classElement.metadata);
|
final annotations = _getAnnotationNames(classElement.metadata);
|
||||||
|
|
||||||
@@ -41,6 +89,9 @@ class AnnotationValidator {
|
|||||||
_validateInjectableClassAnnotations(classElement, annotations);
|
_validateInjectableClassAnnotations(classElement, annotations);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Internal helpers follow (private) ---
|
||||||
|
|
||||||
|
/// Helper: Returns the names of all annotation types on `metadata`.
|
||||||
static List<String> _getAnnotationNames(List<ElementAnnotation> metadata) {
|
static List<String> _getAnnotationNames(List<ElementAnnotation> metadata) {
|
||||||
return metadata
|
return metadata
|
||||||
.map((m) => m.computeConstantValue()?.type?.getDisplayString())
|
.map((m) => m.computeConstantValue()?.type?.getDisplayString())
|
||||||
@@ -49,6 +100,9 @@ class AnnotationValidator {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates that mutually exclusive method annotations are not used together.
|
||||||
|
///
|
||||||
|
/// For example, `@instance` and `@provide` cannot both be present.
|
||||||
static void _validateMutuallyExclusiveAnnotations(
|
static void _validateMutuallyExclusiveAnnotations(
|
||||||
MethodElement method,
|
MethodElement method,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
@@ -68,6 +122,10 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates correct annotation combinations, e.g.
|
||||||
|
/// - `@params` must be with `@provide`
|
||||||
|
/// - One of `@instance` or `@provide` must be present for a registration method
|
||||||
|
/// - Validates singleton usage
|
||||||
static void _validateAnnotationCombinations(
|
static void _validateAnnotationCombinations(
|
||||||
MethodElement method,
|
MethodElement method,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
@@ -105,6 +163,7 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Singleton-specific method annotation checks.
|
||||||
static void _validateSingletonUsage(
|
static void _validateSingletonUsage(
|
||||||
MethodElement method,
|
MethodElement method,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
@@ -130,6 +189,7 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Validates extra requirements or syntactic rules for annotation arguments, like @named.
|
||||||
static void _validateAnnotationParameters(MethodElement method) {
|
static void _validateAnnotationParameters(MethodElement method) {
|
||||||
// Validate @named annotation parameters
|
// Validate @named annotation parameters
|
||||||
final namedValue = MetadataUtils.getNamedValue(method.metadata);
|
final namedValue = MetadataUtils.getNamedValue(method.metadata);
|
||||||
@@ -170,11 +230,11 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks that @params is used with compatible parameter type.
|
||||||
static void _validateParamsParameter(
|
static void _validateParamsParameter(
|
||||||
ParameterElement param, MethodElement method) {
|
ParameterElement param, MethodElement method) {
|
||||||
// @params parameter should typically be dynamic or Map<String, dynamic>
|
// @params parameter should typically be dynamic or Map<String, dynamic>
|
||||||
final paramType = param.type.getDisplayString();
|
final paramType = param.type.getDisplayString();
|
||||||
|
|
||||||
if (paramType != 'dynamic' &&
|
if (paramType != 'dynamic' &&
|
||||||
paramType != 'Map<String, dynamic>' &&
|
paramType != 'Map<String, dynamic>' &&
|
||||||
paramType != 'Map<String, dynamic>?') {
|
paramType != 'Map<String, dynamic>?') {
|
||||||
@@ -194,6 +254,7 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks field-level annotation for valid injectable fields.
|
||||||
static void _validateInjectFieldAnnotations(
|
static void _validateInjectFieldAnnotations(
|
||||||
FieldElement field,
|
FieldElement field,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
@@ -227,6 +288,7 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks @module usage: must have at least one DI method, each with DI-annotation.
|
||||||
static void _validateModuleClassAnnotations(
|
static void _validateModuleClassAnnotations(
|
||||||
ClassElement classElement,
|
ClassElement classElement,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
@@ -268,6 +330,7 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks @injectable usage on classes and their fields.
|
||||||
static void _validateInjectableClassAnnotations(
|
static void _validateInjectableClassAnnotations(
|
||||||
ClassElement classElement,
|
ClassElement classElement,
|
||||||
List<String> annotations,
|
List<String> annotations,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -12,57 +12,59 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
/// ----------------------------------------------------------------------------
|
/// ----------------------------------------------------------------------------
|
||||||
/// BindParameterSpec - describes a single method parameter and how to resolve it.
|
/// BindParameterSpec
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Describes a single parameter for a DI provider/factory/binding method,
|
||||||
/// Describes a single parameter for a provider/binding method in the DI system.
|
/// specifying how that parameter is to be resolved in generated code.
|
||||||
/// Stores the parameter type, its optional `@named` key for named resolution,
|
|
||||||
/// and whether it is a runtime "params" argument. Used to generate code that
|
|
||||||
/// resolves dependencies from the DI scope:
|
|
||||||
/// - If the parameter is a dependency type (e.g. SomeDep), emits:
|
|
||||||
/// currentScope.resolve<SomeDep>()
|
|
||||||
/// - If the parameter is named, emits:
|
|
||||||
/// currentScope.resolve<SomeDep>(named: 'yourName')
|
|
||||||
/// - If it's a runtime parameter (e.g. via @params()), emits:
|
|
||||||
/// args
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Stores the parameter's type name, optional `@named` identifier (for named DI resolution),
|
||||||
/// Описывает один параметр метода в DI, и его способ разрешения из контейнера.
|
/// and a flag for runtime (@params) arguments. Used in CherryPick generator
|
||||||
/// Сохраняет имя типа, дополнительное имя (если параметр аннотирован через @named),
|
/// for creating argument lists when invoking factories or provider methods.
|
||||||
/// и признак runtime-параметра (@params).
|
///
|
||||||
/// Для обычной зависимости типа (например, SomeDep) генерирует строку вида:
|
/// ## Example usage
|
||||||
/// currentScope.resolve<SomeDep>()
|
/// ```dart
|
||||||
/// Для зависимости с именем:
|
/// // Binding method: @provide() Logger provideLogger(@named('debug') Config config, @params Map<String, dynamic> args)
|
||||||
/// currentScope.resolve<SomeDep>(named: 'имя')
|
/// final namedParam = BindParameterSpec('Config', 'debug');
|
||||||
/// Для runtime-параметра:
|
/// final runtimeParam = BindParameterSpec('Map<String, dynamic>', null, isParams: true);
|
||||||
/// args
|
/// print(namedParam.generateArg()); // prints: currentScope.resolve<Config>(named: 'debug')
|
||||||
|
/// print(runtimeParam.generateArg()); // prints: args
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ## Code generation logic
|
||||||
|
/// - Injected: currentScope.resolve<Service>()
|
||||||
|
/// - Named: currentScope.resolve<Service>(named: 'name')
|
||||||
|
/// - @params: args
|
||||||
/// ----------------------------------------------------------------------------
|
/// ----------------------------------------------------------------------------
|
||||||
class BindParameterSpec {
|
class BindParameterSpec {
|
||||||
/// Type name of the parameter (e.g. SomeService)
|
/// The type name of the parameter (e.g., 'UserRepository')
|
||||||
/// Имя типа параметра (например, SomeService)
|
|
||||||
final String typeName;
|
final String typeName;
|
||||||
|
|
||||||
/// Optional name for named resolution (from @named)
|
/// If non-null, this is the named-key for DI resolution (from @named).
|
||||||
/// Необязательное имя для разрешения по имени (если аннотировано через @named)
|
|
||||||
final String? named;
|
final String? named;
|
||||||
|
|
||||||
/// True if this parameter uses @params and should be provided from runtime args
|
/// True if this parameter is a runtime param (annotated with @params and
|
||||||
/// Признак, что параметр — runtime (через @params)
|
/// filled by a runtime argument map).
|
||||||
final bool isParams;
|
final bool isParams;
|
||||||
|
|
||||||
BindParameterSpec(this.typeName, this.named, {this.isParams = false});
|
BindParameterSpec(this.typeName, this.named, {this.isParams = false});
|
||||||
|
|
||||||
/// --------------------------------------------------------------------------
|
/// Generates Dart code to resolve this parameter in the DI container.
|
||||||
/// generateArg
|
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// - For normal dependencies: resolves by type
|
||||||
/// Generates Dart code for resolving the dependency from the DI scope,
|
/// - For named dependencies: resolves by type and name
|
||||||
/// considering type, named, and param-argument.
|
/// - For @params: uses the supplied params variable (default 'args')
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// ## Example
|
||||||
/// Генерирует строку для получения зависимости из DI scope (с учётом имени
|
/// ```dart
|
||||||
/// и типа параметра или runtime-режима @params).
|
/// final a = BindParameterSpec('Api', null); // normal
|
||||||
/// --------------------------------------------------------------------------
|
/// print(a.generateArg()); // currentScope.resolve<Api>()
|
||||||
|
///
|
||||||
|
/// final b = BindParameterSpec('Api', 'prod'); // named
|
||||||
|
/// print(b.generateArg()); // currentScope.resolve<Api>(named: 'prod')
|
||||||
|
///
|
||||||
|
/// final c = BindParameterSpec('Map<String,dynamic>', null, isParams: true); // params
|
||||||
|
/// print(c.generateArg()); // args
|
||||||
|
/// ```
|
||||||
String generateArg([String paramsVar = 'args']) {
|
String generateArg([String paramsVar = 'args']) {
|
||||||
if (isParams) {
|
if (isParams) {
|
||||||
return paramsVar;
|
return paramsVar;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -19,62 +19,63 @@ import 'exceptions.dart';
|
|||||||
import 'type_parser.dart';
|
import 'type_parser.dart';
|
||||||
import 'annotation_validator.dart';
|
import 'annotation_validator.dart';
|
||||||
|
|
||||||
|
/// Enum representing the binding annotation applied to a module method.
|
||||||
enum BindingType {
|
enum BindingType {
|
||||||
|
/// Direct instance returned from the method (@instance).
|
||||||
instance,
|
instance,
|
||||||
|
/// Provider/factory function (@provide).
|
||||||
provide;
|
provide;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
/// BindSpec -- describes a binding specification generated for a dependency.
|
/// BindSpec
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Describes a DI container binding as generated from a single public factory,
|
||||||
/// Represents all the data necessary to generate a DI binding for a single
|
/// instance, or provider method of a module (annotated with @instance or @provide).
|
||||||
/// method in a module class. Each BindSpec corresponds to one public method
|
|
||||||
/// and contains information about its type, provider method, lifecycle (singleton),
|
|
||||||
/// parameters (with their annotations), binding strategy (instance/provide),
|
|
||||||
/// asynchronous mode, and named keys. It is responsible for generating the
|
|
||||||
/// correct Dart code to register this binding with the DI container, in both
|
|
||||||
/// sync and async cases, with and without named or runtime arguments.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Includes all annotation-driven parameters required to generate valid DI
|
||||||
/// Описывает параметры для создания одного биндинга зависимости (binding spec).
|
/// registration Dart code in CherryPick:
|
||||||
/// Каждый биндинг соответствует одному публичному методу класса-модуля и
|
/// - Return type
|
||||||
/// содержит всю информацию для генерации кода регистрации этого биндинга в
|
/// - Provider method name
|
||||||
/// DI-контейнере: тип возвращаемой зависимости, имя метода, параметры, аннотации
|
/// - Singleton flag
|
||||||
/// (@singleton, @named, @instance, @provide), асинхронность, признак runtime
|
/// - Named identifier (from @named)
|
||||||
/// аргументов и др. Генерирует правильный Dart-код для регистрации биндера.
|
/// - List of resolved or runtime (@params) parameters
|
||||||
|
/// - Binding mode (instance/provide)
|
||||||
|
/// - Async and parametric variants
|
||||||
|
///
|
||||||
|
/// ## Example usage
|
||||||
|
/// ```dart
|
||||||
|
/// // Suppose @provide() Api api(@named('test') Client client)
|
||||||
|
/// final bindSpec = BindSpec.fromMethod(methodElement);
|
||||||
|
/// print(bindSpec.generateBind(2)); // bind<Api>().toProvide(() => api(currentScope.resolve<Client>(named: 'test')));
|
||||||
|
/// ```
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
class BindSpec {
|
class BindSpec {
|
||||||
/// The type this binding provides (e.g. SomeService)
|
/// The type this binding provides (e.g. SomeService)
|
||||||
/// Тип, который предоставляет биндинг (например, SomeService)
|
|
||||||
final String returnType;
|
final String returnType;
|
||||||
|
|
||||||
/// Method name that implements the binding
|
/// Binding provider/factory method name
|
||||||
/// Имя метода, который реализует биндинг
|
|
||||||
final String methodName;
|
final String methodName;
|
||||||
|
|
||||||
/// Optional name for named dependency (from @named)
|
/// Named identifier for DI resolution (null if unnamed)
|
||||||
/// Необязательное имя, для именованной зависимости (используется с @named)
|
|
||||||
final String? named;
|
final String? named;
|
||||||
|
|
||||||
/// Whether the dependency is a singleton (@singleton annotation)
|
/// If true, binding is registered as singleton in DI
|
||||||
/// Является ли зависимость синглтоном (имеется ли аннотация @singleton)
|
|
||||||
final bool isSingleton;
|
final bool isSingleton;
|
||||||
|
|
||||||
/// List of method parameters to inject dependencies with
|
/// Provider/factory method parameters (in order)
|
||||||
/// Список параметров, которые требуются методу для внедрения зависимостей
|
|
||||||
final List<BindParameterSpec> parameters;
|
final List<BindParameterSpec> parameters;
|
||||||
|
|
||||||
/// Binding type: 'instance' or 'provide' (@instance or @provide)
|
/// Instance vs provider mode, from annotation choice
|
||||||
final BindingType bindingType; // 'instance' | 'provide'
|
final BindingType bindingType;
|
||||||
|
|
||||||
/// True if the method is asynchronous and uses instance binding (Future)
|
/// Async flag for .toInstanceAsync()
|
||||||
final bool isAsyncInstance;
|
final bool isAsyncInstance;
|
||||||
|
|
||||||
/// True if the method is asynchronous and uses provide binding (Future)
|
/// Async flag for .toProvideAsync()
|
||||||
final bool isAsyncProvide;
|
final bool isAsyncProvide;
|
||||||
|
|
||||||
/// True if the binding method accepts runtime "params" argument (@params)
|
/// True if a @params runtime parameter is present
|
||||||
final bool hasParams;
|
final bool hasParams;
|
||||||
|
|
||||||
BindSpec({
|
BindSpec({
|
||||||
@@ -89,20 +90,12 @@ class BindSpec {
|
|||||||
required this.hasParams,
|
required this.hasParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// -------------------------------------------------------------------------
|
/// Generates a Dart code line for binding registration.
|
||||||
/// generateBind
|
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Example (single-line):
|
||||||
/// Generates a line of Dart code registering the binding with the DI framework.
|
/// bind<Api>().toProvide(() => provideApi(currentScope.resolve<Client>(named: 'test'))).withName('prod').singleton();
|
||||||
/// Produces something like:
|
|
||||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
|
||||||
/// Indent parameter allows formatted multiline output.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// The [indent] argument sets the space indentation for pretty-printing.
|
||||||
/// Формирует dart-код для биндинга, например:
|
|
||||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
|
||||||
/// Параметр [indent] задаёт отступ для красивого форматирования кода.
|
|
||||||
/// -------------------------------------------------------------------------
|
|
||||||
String generateBind(int indent) {
|
String generateBind(int indent) {
|
||||||
final indentStr = ' ' * indent;
|
final indentStr = ' ' * indent;
|
||||||
final provide = _generateProvideClause(indent);
|
final provide = _generateProvideClause(indent);
|
||||||
@@ -151,7 +144,7 @@ class BindSpec {
|
|||||||
return _generatePlainProvideClause(indent);
|
return _generatePlainProvideClause(indent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// EN / RU: Supports runtime parameters (@params).
|
/// Generates code when using runtime parameters (@params).
|
||||||
String _generateWithParamsProvideClause(int indent) {
|
String _generateWithParamsProvideClause(int indent) {
|
||||||
// Safe variable name for parameters.
|
// Safe variable name for parameters.
|
||||||
const paramVar = 'args';
|
const paramVar = 'args';
|
||||||
@@ -178,7 +171,7 @@ class BindSpec {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// EN / RU: Supports only injected dependencies, not runtime (@params).
|
/// Generates code when only resolved (not runtime) arguments used.
|
||||||
String _generatePlainProvideClause(int indent) {
|
String _generatePlainProvideClause(int indent) {
|
||||||
final argsStr = parameters.map((p) => p.generateArg()).join(', ');
|
final argsStr = parameters.map((p) => p.generateArg()).join(', ');
|
||||||
|
|
||||||
@@ -241,16 +234,17 @@ class BindSpec {
|
|||||||
/// -------------------------------------------------------------------------
|
/// -------------------------------------------------------------------------
|
||||||
/// fromMethod
|
/// fromMethod
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Constructs a [BindSpec] from an analyzer [MethodElement].
|
||||||
/// Creates a BindSpec from a module class method by analyzing its return type,
|
|
||||||
/// annotations, list of parameters (with their own annotations), and async-ness.
|
|
||||||
/// Throws if a method does not have the required @instance() or @provide().
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Validates and parses all type annotations, method/parameter DI hints,
|
||||||
/// Создаёт спецификацию биндинга (BindSpec) из метода класса-модуля, анализируя
|
/// and derives async and parametric flags as needed.
|
||||||
/// возвращаемый тип, аннотации, параметры (и их аннотации), а также факт
|
///
|
||||||
/// асинхронности. Если нет @instance или @provide — кидает ошибку.
|
/// ## Example
|
||||||
/// -------------------------------------------------------------------------
|
/// ```dart
|
||||||
|
/// final bindSpec = BindSpec.fromMethod(methodElement);
|
||||||
|
/// print(bindSpec.returnType); // e.g., 'Logger'
|
||||||
|
/// ```
|
||||||
|
/// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid.
|
||||||
static BindSpec fromMethod(MethodElement method) {
|
static BindSpec fromMethod(MethodElement method) {
|
||||||
try {
|
try {
|
||||||
// Validate method annotations
|
// Validate method annotations
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -14,10 +14,36 @@
|
|||||||
import 'package:analyzer/dart/element/element.dart';
|
import 'package:analyzer/dart/element/element.dart';
|
||||||
import 'package:source_gen/source_gen.dart';
|
import 'package:source_gen/source_gen.dart';
|
||||||
|
|
||||||
/// Enhanced exception class for CherryPick generator with detailed context information
|
/// ---------------------------------------------------------------------------
|
||||||
|
/// CherryPickGeneratorException
|
||||||
|
///
|
||||||
|
/// The base exception for all CherryPick code generation and annotation
|
||||||
|
/// validation errors. This exception provides enhanced diagnostics including
|
||||||
|
/// the error category, helpful suggestions, and additional debugging context.
|
||||||
|
///
|
||||||
|
/// All errors are structured to be as helpful as possible for users
|
||||||
|
/// running build_runner and for CherryPick contributors debugging generators.
|
||||||
|
///
|
||||||
|
/// ## Example usage:
|
||||||
|
/// ```dart
|
||||||
|
/// if (someErrorCondition) {
|
||||||
|
/// throw AnnotationValidationException(
|
||||||
|
/// 'Custom message about what went wrong',
|
||||||
|
/// element: methodElement,
|
||||||
|
/// suggestion: 'Add @provide() or @instance() annotation',
|
||||||
|
/// context: {'found_annotations': annotations},
|
||||||
|
/// );
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
||||||
|
/// A string describing the error category (for grouping).
|
||||||
final String category;
|
final String category;
|
||||||
|
|
||||||
|
/// An optional suggestion string for resolving the error.
|
||||||
final String? suggestion;
|
final String? suggestion;
|
||||||
|
|
||||||
|
/// Arbitrary key-value map for additional debugging information.
|
||||||
final Map<String, dynamic>? context;
|
final Map<String, dynamic>? context;
|
||||||
|
|
||||||
CherryPickGeneratorException(
|
CherryPickGeneratorException(
|
||||||
@@ -50,7 +76,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
|||||||
buffer.writeln(' Type: ${element.runtimeType}');
|
buffer.writeln(' Type: ${element.runtimeType}');
|
||||||
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}');
|
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}');
|
||||||
|
|
||||||
// Note: enclosingElement may not be available in all analyzer versions
|
// Try to show enclosing element info for extra context
|
||||||
try {
|
try {
|
||||||
final enclosing = (element as dynamic).enclosingElement;
|
final enclosing = (element as dynamic).enclosingElement;
|
||||||
if (enclosing != null) {
|
if (enclosing != null) {
|
||||||
@@ -60,7 +86,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
|||||||
// Ignore if enclosingElement is not available
|
// Ignore if enclosingElement is not available
|
||||||
}
|
}
|
||||||
|
|
||||||
// Additional context
|
// Arbitrary user context
|
||||||
if (context != null && context.isNotEmpty) {
|
if (context != null && context.isNotEmpty) {
|
||||||
buffer.writeln('');
|
buffer.writeln('');
|
||||||
buffer.writeln('Additional Context:');
|
buffer.writeln('Additional Context:');
|
||||||
@@ -69,7 +95,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Suggestion
|
// Hint/suggestion if present
|
||||||
if (suggestion != null) {
|
if (suggestion != null) {
|
||||||
buffer.writeln('');
|
buffer.writeln('');
|
||||||
buffer.writeln('💡 Suggestion: $suggestion');
|
buffer.writeln('💡 Suggestion: $suggestion');
|
||||||
@@ -79,7 +105,24 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specific exception types for different error categories
|
/// ---------------------------------------------------------------------------
|
||||||
|
/// AnnotationValidationException
|
||||||
|
///
|
||||||
|
/// Thrown when annotation usage is invalid (e.g., missing required annotation,
|
||||||
|
/// mutually exclusive annotations, or incorrect @named format).
|
||||||
|
///
|
||||||
|
/// Grouped as category "ANNOTATION_VALIDATION".
|
||||||
|
///
|
||||||
|
/// ## Example:
|
||||||
|
/// ```dart
|
||||||
|
/// throw AnnotationValidationException(
|
||||||
|
/// '@instance and @provide cannot be used together',
|
||||||
|
/// element: method,
|
||||||
|
/// suggestion: 'Use only one of @instance or @provide.',
|
||||||
|
/// context: {'method_name': method.displayName},
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
class AnnotationValidationException extends CherryPickGeneratorException {
|
class AnnotationValidationException extends CherryPickGeneratorException {
|
||||||
AnnotationValidationException(
|
AnnotationValidationException(
|
||||||
super.message, {
|
super.message, {
|
||||||
@@ -89,6 +132,24 @@ class AnnotationValidationException extends CherryPickGeneratorException {
|
|||||||
}) : super(category: 'ANNOTATION_VALIDATION');
|
}) : super(category: 'ANNOTATION_VALIDATION');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
|
/// TypeParsingException
|
||||||
|
///
|
||||||
|
/// Thrown when a Dart type cannot be interpreted/parsed for DI,
|
||||||
|
/// or if it's not compatible (void, raw Future, etc).
|
||||||
|
///
|
||||||
|
/// Grouped as category "TYPE_PARSING".
|
||||||
|
///
|
||||||
|
/// ## Example:
|
||||||
|
/// ```dart
|
||||||
|
/// throw TypeParsingException(
|
||||||
|
/// 'Cannot parse injected type',
|
||||||
|
/// element: field,
|
||||||
|
/// suggestion: 'Specify a concrete type. Avoid dynamic and raw Future.',
|
||||||
|
/// context: {'type': field.type.getDisplayString()},
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
class TypeParsingException extends CherryPickGeneratorException {
|
class TypeParsingException extends CherryPickGeneratorException {
|
||||||
TypeParsingException(
|
TypeParsingException(
|
||||||
super.message, {
|
super.message, {
|
||||||
@@ -98,6 +159,23 @@ class TypeParsingException extends CherryPickGeneratorException {
|
|||||||
}) : super(category: 'TYPE_PARSING');
|
}) : super(category: 'TYPE_PARSING');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
|
/// CodeGenerationException
|
||||||
|
///
|
||||||
|
/// Thrown on unexpected code generation or formatting failures
|
||||||
|
/// during generator execution.
|
||||||
|
///
|
||||||
|
/// Grouped as category "CODE_GENERATION".
|
||||||
|
///
|
||||||
|
/// ## Example:
|
||||||
|
/// ```dart
|
||||||
|
/// throw CodeGenerationException(
|
||||||
|
/// 'Could not generate module binding',
|
||||||
|
/// element: classElement,
|
||||||
|
/// suggestion: 'Check module class methods and signatures.',
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
class CodeGenerationException extends CherryPickGeneratorException {
|
class CodeGenerationException extends CherryPickGeneratorException {
|
||||||
CodeGenerationException(
|
CodeGenerationException(
|
||||||
super.message, {
|
super.message, {
|
||||||
@@ -107,6 +185,23 @@ class CodeGenerationException extends CherryPickGeneratorException {
|
|||||||
}) : super(category: 'CODE_GENERATION');
|
}) : super(category: 'CODE_GENERATION');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
|
/// DependencyResolutionException
|
||||||
|
///
|
||||||
|
/// Thrown if dependency information (for example, types or names)
|
||||||
|
/// cannot be resolved during code generation analysis.
|
||||||
|
///
|
||||||
|
/// Grouped as category "DEPENDENCY_RESOLUTION".
|
||||||
|
///
|
||||||
|
/// ## Example:
|
||||||
|
/// ```dart
|
||||||
|
/// throw DependencyResolutionException(
|
||||||
|
/// 'Dependency type not found in scope',
|
||||||
|
/// element: someElement,
|
||||||
|
/// suggestion: 'Check CherryPick registration for this type.',
|
||||||
|
/// );
|
||||||
|
/// ```
|
||||||
|
/// ---------------------------------------------------------------------------
|
||||||
class DependencyResolutionException extends CherryPickGeneratorException {
|
class DependencyResolutionException extends CherryPickGeneratorException {
|
||||||
DependencyResolutionException(
|
DependencyResolutionException(
|
||||||
super.message, {
|
super.message, {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -12,45 +12,48 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import 'package:analyzer/dart/element/element.dart';
|
import 'package:analyzer/dart/element/element.dart';
|
||||||
|
|
||||||
import 'bind_spec.dart';
|
import 'bind_spec.dart';
|
||||||
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
/// GeneratedClass -- represents the result of processing a single module class.
|
/// GeneratedClass
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Represents a processed DI module class with all its binding methods analyzed.
|
||||||
/// Encapsulates all the information produced from analyzing a DI module class:
|
/// Stores:
|
||||||
/// - The original class name,
|
/// - The original class name,
|
||||||
/// - Its generated class name (e.g., `$SomeModule`),
|
/// - The generated implementation class name (with $ prefix),
|
||||||
/// - The collection of bindings (BindSpec) for all implemented provider methods.
|
/// - The list of all BindSpec for the module methods,
|
||||||
|
/// - The source file name for reference or directive generation.
|
||||||
///
|
///
|
||||||
/// Also provides code generation functionality, allowing to generate the source
|
/// Provides static and instance methods to construct from a ClassElement
|
||||||
/// code for the derived DI module class, including all binding registrations.
|
/// and generate Dart source code for the resulting DI registration class.
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// ## Example usage
|
||||||
/// Описывает результат обработки одного класса-модуля DI:
|
/// ```dart
|
||||||
/// - Имя оригинального класса,
|
/// final gen = GeneratedClass.fromClassElement(myModuleClassElement);
|
||||||
/// - Имя генерируемого класса (например, `$SomeModule`),
|
/// print(gen.generate());
|
||||||
/// - Список всех бидингов (BindSpec) — по публичным методам модуля.
|
/// /*
|
||||||
///
|
/// Produces:
|
||||||
/// Также содержит функцию генерации исходного кода для этого класса и
|
/// final class $MyModule extends MyModule {
|
||||||
/// регистрации всех зависимостей через bind(...).
|
/// @override
|
||||||
|
/// void builder(Scope currentScope) {
|
||||||
|
/// bind<Service>().toProvide(() => provideService(currentScope.resolve<Dep>()));
|
||||||
|
/// ...
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// */
|
||||||
|
/// ```
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
class GeneratedClass {
|
class GeneratedClass {
|
||||||
/// The name of the original module class.
|
/// Name of the original Dart module class.
|
||||||
/// Имя исходного класса-модуля
|
|
||||||
final String className;
|
final String className;
|
||||||
|
|
||||||
/// The name of the generated class (e.g., $SomeModule).
|
/// Name of the generated class, e.g. `$MyModule`
|
||||||
/// Имя генерируемого класса (например, $SomeModule)
|
|
||||||
final String generatedClassName;
|
final String generatedClassName;
|
||||||
|
|
||||||
/// List of all discovered bindings for the class.
|
/// Binding specs for all provider/factory methods in the class.
|
||||||
/// Список всех обнаруженных биндингов
|
|
||||||
final List<BindSpec> binds;
|
final List<BindSpec> binds;
|
||||||
|
|
||||||
/// Source file name for the part directive
|
/// Source filename of the module class (for code references).
|
||||||
/// Имя исходного файла для part директивы
|
|
||||||
final String sourceFile;
|
final String sourceFile;
|
||||||
|
|
||||||
GeneratedClass(
|
GeneratedClass(
|
||||||
@@ -63,16 +66,15 @@ class GeneratedClass {
|
|||||||
/// -------------------------------------------------------------------------
|
/// -------------------------------------------------------------------------
|
||||||
/// fromClassElement
|
/// fromClassElement
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Creates a [GeneratedClass] by analyzing a Dart [ClassElement].
|
||||||
/// Static factory: creates a GeneratedClass from a Dart ClassElement (AST representation).
|
/// Collects all public non-abstract methods, creates a [BindSpec] for each,
|
||||||
/// Discovers all non-abstract methods, builds BindSpec for each, and computes the
|
/// and infers the generated class name using a `$` prefix.
|
||||||
/// generated class name by prefixing `$`.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// ## Example usage
|
||||||
/// Строит объект класса по элементу AST (ClassElement): имя класса,
|
/// ```dart
|
||||||
/// сгенерированное имя, список BindSpec по всем не абстрактным методам.
|
/// final gen = GeneratedClass.fromClassElement(classElement);
|
||||||
/// Имя ген-класса строится с префиксом `$`.
|
/// print(gen.generatedClassName); // e.g. $AppModule
|
||||||
/// -------------------------------------------------------------------------
|
/// ```
|
||||||
static GeneratedClass fromClassElement(ClassElement element) {
|
static GeneratedClass fromClassElement(ClassElement element) {
|
||||||
final className = element.displayName;
|
final className = element.displayName;
|
||||||
// Generated class name with '$' prefix (standard for generated Dart code).
|
// Generated class name with '$' prefix (standard for generated Dart code).
|
||||||
@@ -91,16 +93,19 @@ class GeneratedClass {
|
|||||||
/// -------------------------------------------------------------------------
|
/// -------------------------------------------------------------------------
|
||||||
/// generate
|
/// generate
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Generates the Dart source code for the DI registration class.
|
||||||
/// Generates Dart source code for the DI module class. The generated class
|
/// The generated class extends the original module, and the `builder` method
|
||||||
/// inherits from the original, overrides the 'builder' method, and registers
|
/// registers all bindings (dependencies) into the DI scope.
|
||||||
/// all bindings in the DI scope.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// ## Example output
|
||||||
/// Генерирует исходный Dart-код для класса-модуля DI.
|
/// ```dart
|
||||||
/// Новая версия класса наследует оригинальный, переопределяет builder(Scope),
|
/// final class $UserModule extends UserModule {
|
||||||
/// и регистрирует все зависимости через методы bind<Type>()...
|
/// @override
|
||||||
/// -------------------------------------------------------------------------
|
/// void builder(Scope currentScope) {
|
||||||
|
/// bind<Service>().toProvide(() => provideService(currentScope.resolve<Dep>()));
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
String generate() {
|
String generate() {
|
||||||
final buffer = StringBuffer()
|
final buffer = StringBuffer()
|
||||||
..writeln('final class $generatedClassName extends $className {')
|
..writeln('final class $generatedClassName extends $className {')
|
||||||
@@ -108,7 +113,6 @@ class GeneratedClass {
|
|||||||
..writeln(' void builder(Scope currentScope) {');
|
..writeln(' void builder(Scope currentScope) {');
|
||||||
|
|
||||||
// For each binding, generate bind<Type>() code string.
|
// For each binding, generate bind<Type>() code string.
|
||||||
// Для каждого биндинга — генерируем строку bind<Type>()...
|
|
||||||
for (final bind in binds) {
|
for (final bind in binds) {
|
||||||
buffer.writeln(bind.generateBind(4));
|
buffer.writeln(bind.generateBind(4));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -14,30 +14,32 @@
|
|||||||
import 'package:analyzer/dart/element/element.dart';
|
import 'package:analyzer/dart/element/element.dart';
|
||||||
|
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
/// MetadataUtils -- utilities for analyzing method and parameter annotations.
|
/// MetadataUtils
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Static utilities for querying and extracting information from
|
||||||
/// Provides static utility methods to analyze Dart annotations on methods or
|
/// Dart annotations ([ElementAnnotation]) in the context of code generation,
|
||||||
/// parameters. For instance, helps to find if an element is annotated with
|
/// such as checking for the presence of specific DI-related annotations.
|
||||||
/// `@named()`, `@singleton()`, or other meta-annotations used in this DI framework.
|
/// Designed to be used internally by code generation and validation routines.
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// # Example usage
|
||||||
/// Утилиты для разбора аннотаций методов и параметров.
|
/// ```dart
|
||||||
/// Позволяют находить наличие аннотаций, например, @named() и @singleton(),
|
/// if (MetadataUtils.anyMeta(method.metadata, 'singleton')) {
|
||||||
/// у методов и параметров. Используется для анализа исходного кода при генерации.
|
/// // The method is annotated with @singleton
|
||||||
|
/// }
|
||||||
|
/// final name = MetadataUtils.getNamedValue(field.metadata);
|
||||||
|
/// if (name != null) print('@named value: $name');
|
||||||
|
/// ```
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
class MetadataUtils {
|
class MetadataUtils {
|
||||||
/// -------------------------------------------------------------------------
|
/// Checks whether any annotation in [meta] matches the [typeName]
|
||||||
/// anyMeta
|
/// (type name is compared in a case-insensitive manner and can be partial).
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Returns true if an annotation (such as @singleton, @provide, @named) is found.
|
||||||
/// Checks if any annotation in the list has a type name that contains
|
|
||||||
/// [typeName] (case insensitive).
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Example:
|
||||||
/// Проверяет: есть ли среди аннотаций метка, имя которой содержит [typeName]
|
/// ```dart
|
||||||
/// (регистр не учитывается).
|
/// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata, 'singleton');
|
||||||
/// -------------------------------------------------------------------------
|
/// ```
|
||||||
static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
|
static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
|
||||||
return meta.any((m) =>
|
return meta.any((m) =>
|
||||||
m
|
m
|
||||||
@@ -49,17 +51,15 @@ class MetadataUtils {
|
|||||||
false);
|
false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// -------------------------------------------------------------------------
|
/// Extracts the string value from a `@named('value')` annotation if present in [meta].
|
||||||
/// getNamedValue
|
|
||||||
///
|
///
|
||||||
/// ENGLISH
|
/// Returns the named value or `null` if not annotated.
|
||||||
/// Retrieves the value from a `@named('value')` annotation if present.
|
|
||||||
/// Returns the string value or null if not found.
|
|
||||||
///
|
///
|
||||||
/// RUSSIAN
|
/// Example:
|
||||||
/// Находит значение из аннотации @named('значение').
|
/// ```dart
|
||||||
/// Возвращает строку значения, если аннотация присутствует; иначе null.
|
/// // For: @named('dev') ApiClient provideApi() ...
|
||||||
/// -------------------------------------------------------------------------
|
/// final named = MetadataUtils.getNamedValue(method.metadata); // 'dev'
|
||||||
|
/// ```
|
||||||
static String? getNamedValue(List<ElementAnnotation> meta) {
|
static String? getNamedValue(List<ElementAnnotation> meta) {
|
||||||
for (final m in meta) {
|
for (final m in meta) {
|
||||||
final cv = m.computeConstantValue();
|
final cv = m.computeConstantValue();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
@@ -16,9 +16,35 @@ import 'package:analyzer/dart/element/nullability_suffix.dart';
|
|||||||
import 'package:analyzer/dart/element/type.dart';
|
import 'package:analyzer/dart/element/type.dart';
|
||||||
import 'exceptions.dart';
|
import 'exceptions.dart';
|
||||||
|
|
||||||
/// Enhanced type parser that uses AST analysis instead of regular expressions
|
/// Utility for analyzing and parsing Dart types for CherryPick DI code generation.
|
||||||
|
///
|
||||||
|
/// This type parser leverages the Dart analyzer AST to extract nuanced information
|
||||||
|
/// from Dart types encountered in the source code, in particular for dependency
|
||||||
|
/// injection purposes. It is capable of extracting nullability, generics,
|
||||||
|
/// and Future-related metadata with strong guarantees and handles even nested generics.
|
||||||
|
///
|
||||||
|
/// # Example usage for parsing types:
|
||||||
|
/// ```dart
|
||||||
|
/// final parsed = TypeParser.parseType(method.returnType, method);
|
||||||
|
/// print(parsed);
|
||||||
|
/// print(parsed.resolveMethodName); // e.g. "resolveAsync" or "tryResolve"
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// # Supported scenarios:
|
||||||
|
/// - Nullable types (e.g., `List<String>?`)
|
||||||
|
/// - Generic types (e.g., `Map<String, User>`)
|
||||||
|
/// - Async types (`Future<T>`, including nested generics)
|
||||||
|
/// - Validation for DI compatibility (throws for `void`, warns on `dynamic`)
|
||||||
class TypeParser {
|
class TypeParser {
|
||||||
/// Parses a DartType and extracts detailed type information
|
/// Parses a [DartType] and extracts detailed type information for use in code generation.
|
||||||
|
///
|
||||||
|
/// If a type is not suitable or cannot be parsed, a [TypeParsingException] is thrown.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final parsed = TypeParser.parseType(field.type, field);
|
||||||
|
/// if (parsed.isNullable) print('Field is nullable');
|
||||||
|
/// ```
|
||||||
static ParsedType parseType(DartType dartType, Element context) {
|
static ParsedType parseType(DartType dartType, Element context) {
|
||||||
try {
|
try {
|
||||||
return _parseTypeInternal(dartType, context);
|
return _parseTypeInternal(dartType, context);
|
||||||
@@ -49,7 +75,7 @@ class TypeParser {
|
|||||||
return _parseGenericType(dartType, context, isNullable);
|
return _parseGenericType(dartType, context, isNullable);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Simple type
|
// Simple type (non-generic, non-Future)
|
||||||
return ParsedType(
|
return ParsedType(
|
||||||
displayString: displayString,
|
displayString: displayString,
|
||||||
coreType: displayString.replaceAll('?', ''),
|
coreType: displayString.replaceAll('?', ''),
|
||||||
@@ -103,7 +129,15 @@ class TypeParser {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Validates that a type is suitable for dependency injection
|
/// Validates that a parsed type is suitable for dependency injection.
|
||||||
|
///
|
||||||
|
/// Throws [TypeParsingException] for void and may warn for dynamic.
|
||||||
|
///
|
||||||
|
/// Example:
|
||||||
|
/// ```dart
|
||||||
|
/// final parsed = TypeParser.parseType(field.type, field);
|
||||||
|
/// TypeParser.validateInjectableType(parsed, field);
|
||||||
|
/// ```
|
||||||
static void validateInjectableType(ParsedType parsedType, Element context) {
|
static void validateInjectableType(ParsedType parsedType, Element context) {
|
||||||
// Check for void type
|
// Check for void type
|
||||||
if (parsedType.coreType == 'void') {
|
if (parsedType.coreType == 'void') {
|
||||||
@@ -131,7 +165,7 @@ class TypeParser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents a parsed type with detailed information
|
/// Represents a parsed type with full metadata for code generation.
|
||||||
class ParsedType {
|
class ParsedType {
|
||||||
/// The full display string of the type (e.g., "Future<List<String>?>")
|
/// The full display string of the type (e.g., "Future<List<String>?>")
|
||||||
final String displayString;
|
final String displayString;
|
||||||
@@ -139,19 +173,19 @@ class ParsedType {
|
|||||||
/// The core type name without nullability and Future wrapper (e.g., "List<String>")
|
/// The core type name without nullability and Future wrapper (e.g., "List<String>")
|
||||||
final String coreType;
|
final String coreType;
|
||||||
|
|
||||||
/// Whether the type is nullable
|
/// True if nullable (has `?`)
|
||||||
final bool isNullable;
|
final bool isNullable;
|
||||||
|
|
||||||
/// Whether the type is wrapped in Future
|
/// True if this type is a `Future<T>`
|
||||||
final bool isFuture;
|
final bool isFuture;
|
||||||
|
|
||||||
/// Whether the type has generic parameters
|
/// True if the type is a generic type (`List<T>`)
|
||||||
final bool isGeneric;
|
final bool isGeneric;
|
||||||
|
|
||||||
/// Parsed type arguments for generic types
|
/// List of parsed type arguments in generics, if any.
|
||||||
final List<ParsedType> typeArguments;
|
final List<ParsedType> typeArguments;
|
||||||
|
|
||||||
/// For Future types, the inner type
|
/// For `Future<T>`, this is the type inside the `Future`.
|
||||||
final ParsedType? innerType;
|
final ParsedType? innerType;
|
||||||
|
|
||||||
const ParsedType({
|
const ParsedType({
|
||||||
@@ -164,7 +198,11 @@ class ParsedType {
|
|||||||
this.innerType,
|
this.innerType,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Returns the type string suitable for code generation
|
/// Generates the type string suitable for code generation.
|
||||||
|
///
|
||||||
|
/// - For futures, the codegen type of the inner type is returned
|
||||||
|
/// - For generics, returns e.g. `List<User>`
|
||||||
|
/// - For plain types, just the name
|
||||||
String get codeGenType {
|
String get codeGenType {
|
||||||
if (isFuture && innerType != null) {
|
if (isFuture && innerType != null) {
|
||||||
return innerType!.codeGenType;
|
return innerType!.codeGenType;
|
||||||
@@ -179,10 +217,10 @@ class ParsedType {
|
|||||||
return coreType;
|
return coreType;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns whether this type should use tryResolve instead of resolve
|
/// True if this type should use `tryResolve` instead of `resolve` for DI.
|
||||||
bool get shouldUseTryResolve => isNullable;
|
bool get shouldUseTryResolve => isNullable;
|
||||||
|
|
||||||
/// Returns the appropriate resolve method name
|
/// Returns the method name for DI, e.g. "resolve", "tryResolveAsync", etc.
|
||||||
String get resolveMethodName {
|
String get resolveMethodName {
|
||||||
if (isFuture) {
|
if (isFuture) {
|
||||||
return shouldUseTryResolve ? 'tryResolveAsync' : 'resolveAsync';
|
return shouldUseTryResolve ? 'tryResolveAsync' : 'resolveAsync';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ name: cherrypick_generator
|
|||||||
description: |
|
description: |
|
||||||
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
|
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
|
||||||
|
|
||||||
version: 1.1.0
|
version: 2.0.0-dev.0
|
||||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||||
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
|
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
|
||||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||||
@@ -18,7 +18,7 @@ environment:
|
|||||||
|
|
||||||
# Add regular dependencies here.
|
# Add regular dependencies here.
|
||||||
dependencies:
|
dependencies:
|
||||||
cherrypick_annotations: ^1.1.0
|
cherrypick_annotations: ^1.1.2-dev.0
|
||||||
analyzer: ^7.0.0
|
analyzer: ^7.0.0
|
||||||
dart_style: ^3.0.0
|
dart_style: ^3.0.0
|
||||||
build: ^2.4.1
|
build: ^2.4.1
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
// You may obtain a copy of the License at
|
// You may obtain a copy of the License at
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
|||||||
@@ -185,6 +185,41 @@ final service = scope.tryResolve<OptionalService>(); // returns null if not exis
|
|||||||
---
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## Automatic resource management: Disposable and dispose
|
||||||
|
|
||||||
|
CherryPick makes it easy to clean up resources for your singleton services and other objects registered in DI.
|
||||||
|
If your class implements the `Disposable` interface, always **await** `scope.dispose()` (or `CherryPick.closeRootScope()`) when you want to free all resources in your scope — CherryPick will automatically await `dispose()` for every object that implements `Disposable` and was resolved via DI.
|
||||||
|
This ensures safe and graceful resource management (including any async resource cleanup: streams, DB connections, sockets, etc.).
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class LoggingService implements Disposable {
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() async {
|
||||||
|
// Close files, streams, and perform async cleanup here.
|
||||||
|
print('LoggingService disposed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> main() async {
|
||||||
|
final scope = openRootScope();
|
||||||
|
scope.installModules([
|
||||||
|
_LoggingModule(),
|
||||||
|
]);
|
||||||
|
final logger = scope.resolve<LoggingService>();
|
||||||
|
// Use logger...
|
||||||
|
await scope.dispose(); // prints: LoggingService disposed!
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LoggingModule extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<LoggingService>().toProvide(() => LoggingService()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Dependency injection with annotations & code generation
|
## Dependency injection with annotations & code generation
|
||||||
|
|
||||||
CherryPick supports DI with annotations, letting you eliminate manual DI setup.
|
CherryPick supports DI with annotations, letting you eliminate manual DI setup.
|
||||||
@@ -425,6 +460,16 @@ You can use CherryPick in Dart CLI, server apps, and microservices. All major fe
|
|||||||
| `@inject` | Auto-injection | Class fields |
|
| `@inject` | Auto-injection | Class fields |
|
||||||
| `@scope` | Scope/realm | Class fields |
|
| `@scope` | Scope/realm | Class fields |
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Useful Links
|
## Useful Links
|
||||||
|
|||||||
@@ -185,6 +185,41 @@ final service = scope.tryResolve<OptionalService>(); // вернет null, ес
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Автоматическое управление ресурсами: Disposable и dispose
|
||||||
|
|
||||||
|
CherryPick позволяет автоматически очищать ресурсы для ваших синглтонов и любых сервисов, зарегистрированных через DI.
|
||||||
|
Если ваш класс реализует интерфейс `Disposable`, всегда вызывайте и **await**-те `scope.dispose()` (или `CherryPick.closeRootScope()`), когда хотите освободить все ресурсы — CherryPick дождётся завершения `dispose()` для всех объектов, которые реализуют Disposable и были резолвлены из DI.
|
||||||
|
Это позволяет избежать утечек памяти, корректно завершать процессы и грамотно освобождать любые ресурсы (файлы, потоки, соединения и т.д., включая async).
|
||||||
|
|
||||||
|
### Пример
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class LoggingService implements Disposable {
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() async {
|
||||||
|
// Закрыть файлы, потоки, соединения и т.д. (можно с await)
|
||||||
|
print('LoggingService disposed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> main() async {
|
||||||
|
final scope = openRootScope();
|
||||||
|
scope.installModules([
|
||||||
|
_LoggingModule(),
|
||||||
|
]);
|
||||||
|
final logger = scope.resolve<LoggingService>();
|
||||||
|
// Используем logger...
|
||||||
|
await scope.dispose(); // выведет: LoggingService disposed!
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LoggingModule extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<LoggingService>().toProvide(() => LoggingService()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Внедрение зависимостей через аннотации и автогенерацию
|
## Внедрение зависимостей через аннотации и автогенерацию
|
||||||
|
|
||||||
CherryPick поддерживает DI через аннотации, что позволяет полностью избавиться от ручного внедрения зависимостей.
|
CherryPick поддерживает DI через аннотации, что позволяет полностью избавиться от ручного внедрения зависимостей.
|
||||||
@@ -430,6 +465,15 @@ void main() {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
### В: Нужно ли использовать `await` для CherryPick.closeRootScope(), CherryPick.closeScope() или scope.dispose(), если ни один сервис не реализует Disposable?
|
||||||
|
|
||||||
|
**О:**
|
||||||
|
Да! Даже если в данный момент ни один сервис не реализует Disposable, всегда используйте `await` при закрытии скоупа. Если в будущем потребуется добавить освобождение ресурсов через dispose, CherryPick вызовет его автоматически без изменения завершения работы ваших скоупов. Такой подход делает управление ресурсами устойчивым и безопасным для любых изменений архитектуры.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Полезные ссылки
|
## Полезные ссылки
|
||||||
|
|
||||||
- [cherrypick](https://pub.dev/packages/cherrypick)
|
- [cherrypick](https://pub.dev/packages/cherrypick)
|
||||||
|
|||||||
@@ -75,8 +75,54 @@ Example:
|
|||||||
// or
|
// or
|
||||||
final str = rootScope.tryResolve<String>();
|
final str = rootScope.tryResolve<String>();
|
||||||
|
|
||||||
// close main scope
|
// Recommended: Close the root scope & automatically release all Disposable resources
|
||||||
Cherrypick.closeRootScope();
|
await Cherrypick.closeRootScope();
|
||||||
|
// Or, for advanced/manual scenarios:
|
||||||
|
// await rootScope.dispose();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Automatic resource management (`Disposable`, `dispose`)
|
||||||
|
|
||||||
|
If your service implements the `Disposable` interface, CherryPick will automatically await `dispose()` when you close a scope.
|
||||||
|
|
||||||
|
**Best practice:**
|
||||||
|
Always finish your work with `await Cherrypick.closeRootScope()` (for the root scope) or `await scope.closeSubScope('feature')` (for subscopes).
|
||||||
|
These methods will automatically await `dispose()` on all resolved objects implementing `Disposable`, ensuring safe and complete cleanup (sync and async).
|
||||||
|
|
||||||
|
Manual `await scope.dispose()` is available if you manage scopes yourself.
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class MyService implements Disposable {
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() async {
|
||||||
|
// release resources, close connections, perform async shutdown, etc.
|
||||||
|
print('MyService disposed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final scope = openRootScope();
|
||||||
|
scope.installModules([
|
||||||
|
ModuleImpl(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
final service = scope.resolve<MyService>();
|
||||||
|
|
||||||
|
// ... use service
|
||||||
|
|
||||||
|
// Recommended:
|
||||||
|
await Cherrypick.closeRootScope(); // will print: MyService disposed!
|
||||||
|
|
||||||
|
// Or, to close a subscope:
|
||||||
|
await scope.closeSubScope('feature');
|
||||||
|
|
||||||
|
class ModuleImpl extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<MyService>().toProvide(() => MyService()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Logging
|
## Logging
|
||||||
|
|||||||
@@ -75,8 +75,54 @@ Scope - это контейнер, который хранит все дерев
|
|||||||
// или
|
// или
|
||||||
final str = rootScope.tryResolve<String>();
|
final str = rootScope.tryResolve<String>();
|
||||||
|
|
||||||
// закрыть главный scope
|
// Рекомендуется: закрывайте главный scope для автоматического освобождения всех ресурсов
|
||||||
Cherrypick.closeRootScope();
|
await Cherrypick.closeRootScope();
|
||||||
|
// Или, для продвинутых/ручных сценариев:
|
||||||
|
// await rootScope.dispose();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Автоматическое управление ресурсами (`Disposable`, `dispose`)
|
||||||
|
|
||||||
|
Если ваш сервис реализует интерфейс `Disposable`, CherryPick автоматически дождётся выполнения `dispose()` при закрытии scope.
|
||||||
|
|
||||||
|
**Рекомендация:**
|
||||||
|
Завершайте работу через `await Cherrypick.closeRootScope()` (для root scope) или `await scope.closeSubScope('feature')` (для подскоупов).
|
||||||
|
Эти методы автоматически await-ят `dispose()` для всех разрешённых через DI объектов, реализующих `Disposable`, обеспечивая корректную очистку (sync и async) и высвобождение ресурсов.
|
||||||
|
|
||||||
|
Вызывайте `await scope.dispose()` если вы явно управляете custom-скоупом.
|
||||||
|
|
||||||
|
#### Пример
|
||||||
|
|
||||||
|
```dart
|
||||||
|
class MyService implements Disposable {
|
||||||
|
@override
|
||||||
|
FutureOr<void> dispose() async {
|
||||||
|
// закрытие ресурса, соединений, таймеров и т.п., async/await
|
||||||
|
print('MyService disposed!');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final scope = openRootScope();
|
||||||
|
scope.installModules([
|
||||||
|
ModuleImpl(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
final service = scope.resolve<MyService>();
|
||||||
|
|
||||||
|
// ... используем сервис ...
|
||||||
|
|
||||||
|
// Рекомендуемый финал:
|
||||||
|
await Cherrypick.closeRootScope(); // выведет в консоль 'MyService disposed!'
|
||||||
|
|
||||||
|
// Или для подскоупа:
|
||||||
|
await scope.closeSubScope('feature');
|
||||||
|
|
||||||
|
class ModuleImpl extends Module {
|
||||||
|
@override
|
||||||
|
void builder(Scope scope) {
|
||||||
|
bind<MyService>().toProvide(() => MyService()).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Логирование
|
## Логирование
|
||||||
|
|||||||
@@ -127,28 +127,28 @@ packages:
|
|||||||
path: "../../cherrypick"
|
path: "../../cherrypick"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "3.0.0-dev.3"
|
version: "3.0.0-dev.8"
|
||||||
cherrypick_annotations:
|
cherrypick_annotations:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "../../cherrypick_annotations"
|
path: "../../cherrypick_annotations"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "1.1.0"
|
version: "1.1.1"
|
||||||
cherrypick_flutter:
|
cherrypick_flutter:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "../../cherrypick_flutter"
|
path: "../../cherrypick_flutter"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "1.1.3-dev.3"
|
version: "1.1.3-dev.8"
|
||||||
cherrypick_generator:
|
cherrypick_generator:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
path: "../../cherrypick_generator"
|
path: "../../cherrypick_generator"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "1.1.0"
|
version: "1.1.1"
|
||||||
clock:
|
clock:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import 'package:cherrypick/cherrypick.dart';
|
|||||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:talker_flutter/talker_flutter.dart';
|
||||||
|
|
||||||
|
|
||||||
import 'domain/repository/post_repository.dart';
|
import 'domain/repository/post_repository.dart';
|
||||||
import 'presentation/bloc/post_bloc.dart';
|
import 'presentation/bloc/post_bloc.dart';
|
||||||
@@ -9,26 +11,38 @@ import 'router/app_router.dart';
|
|||||||
|
|
||||||
part 'app.inject.cherrypick.g.dart';
|
part 'app.inject.cherrypick.g.dart';
|
||||||
|
|
||||||
|
class TalkerProvider extends InheritedWidget {
|
||||||
|
final Talker talker;
|
||||||
|
const TalkerProvider({required this.talker, required super.child, super.key});
|
||||||
|
static Talker of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<TalkerProvider>()!.talker;
|
||||||
|
@override
|
||||||
|
bool updateShouldNotify(TalkerProvider oldWidget) => oldWidget.talker != talker;
|
||||||
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
class MyApp extends StatelessWidget with _$MyApp {
|
class MyApp extends StatelessWidget with _$MyApp {
|
||||||
final _appRouter = AppRouter();
|
final _appRouter = AppRouter();
|
||||||
|
final Talker talker;
|
||||||
|
|
||||||
@named('repo')
|
@named('repo')
|
||||||
@inject()
|
@inject()
|
||||||
late final PostRepository repository;
|
late final PostRepository repository;
|
||||||
|
|
||||||
MyApp({super.key}) {
|
MyApp({super.key, required this.talker}) {
|
||||||
_inject(this);
|
_inject(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return BlocProvider(
|
return TalkerProvider(
|
||||||
create: (_) => PostBloc(repository),
|
talker: talker,
|
||||||
child: MaterialApp.router(
|
child: BlocProvider(
|
||||||
routeInformationParser: _appRouter.defaultRouteParser(),
|
create: (_) => PostBloc(repository),
|
||||||
routerDelegate: _appRouter.delegate(),
|
child: MaterialApp.router(
|
||||||
theme: ThemeData.light(),
|
routeInformationParser: _appRouter.defaultRouteParser(),
|
||||||
|
routerDelegate: _appRouter.delegate(),
|
||||||
|
theme: ThemeData.light(),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:cherrypick/cherrypick.dart';
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
import 'package:talker_dio_logger/talker_dio_logger_interceptor.dart';
|
||||||
|
import 'package:talker_dio_logger/talker_dio_logger_settings.dart';
|
||||||
|
import 'package:talker_flutter/talker_flutter.dart';
|
||||||
import '../data/network/json_placeholder_api.dart';
|
import '../data/network/json_placeholder_api.dart';
|
||||||
import '../data/post_repository_impl.dart';
|
import '../data/post_repository_impl.dart';
|
||||||
import '../domain/repository/post_repository.dart';
|
import '../domain/repository/post_repository.dart';
|
||||||
@@ -9,6 +12,18 @@ part 'app_module.module.cherrypick.g.dart';
|
|||||||
|
|
||||||
@module()
|
@module()
|
||||||
abstract class AppModule extends Module {
|
abstract class AppModule extends Module {
|
||||||
|
@provide()
|
||||||
|
@singleton()
|
||||||
|
TalkerDioLoggerSettings talkerDioLoggerSettings() => TalkerDioLoggerSettings(
|
||||||
|
printRequestHeaders: true,
|
||||||
|
printResponseHeaders: true,
|
||||||
|
printResponseMessage: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
@provide()
|
||||||
|
@singleton()
|
||||||
|
TalkerDioLogger talkerDioLogger(Talker talker, TalkerDioLoggerSettings settings) => TalkerDioLogger(talker: talker, settings: settings);
|
||||||
|
|
||||||
@instance()
|
@instance()
|
||||||
int timeout() => 1000;
|
int timeout() => 1000;
|
||||||
|
|
||||||
@@ -35,8 +50,8 @@ abstract class AppModule extends Module {
|
|||||||
@provide()
|
@provide()
|
||||||
@singleton()
|
@singleton()
|
||||||
@named('dio')
|
@named('dio')
|
||||||
Dio dio(@named('baseUrl') String baseUrl) =>
|
Dio dio(@named('baseUrl') String baseUrl, TalkerDioLogger logger) =>
|
||||||
Dio(BaseOptions(baseUrl: baseUrl));
|
Dio(BaseOptions(baseUrl: baseUrl))..interceptors.add(logger);
|
||||||
|
|
||||||
@provide()
|
@provide()
|
||||||
@singleton()
|
@singleton()
|
||||||
|
|||||||
13
examples/postly/lib/di/core_module.dart
Normal file
13
examples/postly/lib/di/core_module.dart
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
import 'package:talker_flutter/talker_flutter.dart';
|
||||||
|
|
||||||
|
class CoreModule extends Module {
|
||||||
|
final Talker _talker;
|
||||||
|
|
||||||
|
CoreModule({required Talker talker}) : _talker = talker;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void builder(Scope currentScope) {
|
||||||
|
bind<Talker>().toProvide(() => _talker).singleton();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,30 @@
|
|||||||
import 'package:cherrypick/cherrypick.dart';
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:postly/app.dart';
|
import 'package:postly/app.dart';
|
||||||
|
import 'package:postly/di/core_module.dart';
|
||||||
|
import 'package:talker_bloc_logger/talker_bloc_logger_observer.dart';
|
||||||
|
import 'package:talker_flutter/talker_flutter.dart';
|
||||||
import 'di/app_module.dart';
|
import 'di/app_module.dart';
|
||||||
|
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
|
final talker = Talker();
|
||||||
|
final talkerLogger = TalkerCherryPickObserver(talker);
|
||||||
|
|
||||||
|
|
||||||
|
Bloc.observer = TalkerBlocObserver(talker: talker);
|
||||||
|
|
||||||
|
CherryPick.setGlobalObserver(talkerLogger);
|
||||||
// Включаем cycle-detection только в debug/test
|
// Включаем cycle-detection только в debug/test
|
||||||
if (kDebugMode) {
|
if (kDebugMode) {
|
||||||
CherryPick.setGlobalLogger(PrintLogger());
|
|
||||||
CherryPick.enableGlobalCycleDetection();
|
CherryPick.enableGlobalCycleDetection();
|
||||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Используем safe root scope для гарантии защиты
|
// Используем safe root scope для гарантии защиты
|
||||||
CherryPick.openRootScope().installModules([$AppModule()]);
|
CherryPick.openRootScope().installModules([CoreModule(talker: talker), $AppModule()]);
|
||||||
runApp(MyApp());
|
|
||||||
|
runApp(MyApp(talker: talker,));
|
||||||
}
|
}
|
||||||
|
|||||||
15
examples/postly/lib/presentation/pages/logs_page.dart
Normal file
15
examples/postly/lib/presentation/pages/logs_page.dart
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import 'package:auto_route/auto_route.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:talker_flutter/talker_flutter.dart';
|
||||||
|
import '../../app.dart';
|
||||||
|
|
||||||
|
@RoutePage()
|
||||||
|
class LogsPage extends StatelessWidget {
|
||||||
|
const LogsPage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final talker = TalkerProvider.of(context);
|
||||||
|
return TalkerScreen(talker: talker);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,18 @@ class PostsPage extends StatelessWidget {
|
|||||||
create: (context) =>
|
create: (context) =>
|
||||||
context.read<PostBloc>()..add(const PostEvent.fetchAll()),
|
context.read<PostBloc>()..add(const PostEvent.fetchAll()),
|
||||||
child: Scaffold(
|
child: Scaffold(
|
||||||
appBar: AppBar(title: const Text('Posts')),
|
appBar: AppBar(
|
||||||
|
title: const Text('Posts'),
|
||||||
|
actions: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.bug_report),
|
||||||
|
tooltip: 'Open logs',
|
||||||
|
onPressed: () {
|
||||||
|
AutoRouter.of(context).push(const LogsRoute());
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
body: BlocBuilder<PostBloc, PostState>(
|
body: BlocBuilder<PostBloc, PostState>(
|
||||||
builder: (context, state) {
|
builder: (context, state) {
|
||||||
return state.when(
|
return state.when(
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import 'package:auto_route/auto_route.dart';
|
import 'package:auto_route/auto_route.dart';
|
||||||
|
|
||||||
import 'app_router.gr.dart';
|
import 'app_router.gr.dart';
|
||||||
|
|
||||||
@AutoRouterConfig()
|
@AutoRouterConfig()
|
||||||
@@ -8,5 +7,6 @@ class AppRouter extends RootStackRouter {
|
|||||||
List<AutoRoute> get routes => [
|
List<AutoRoute> get routes => [
|
||||||
AutoRoute(page: PostsRoute.page, initial: true),
|
AutoRoute(page: PostsRoute.page, initial: true),
|
||||||
AutoRoute(page: PostDetailsRoute.page),
|
AutoRoute(page: PostDetailsRoute.page),
|
||||||
|
AutoRoute(page: LogsRoute.page),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "7.4.5"
|
version: "7.4.5"
|
||||||
|
ansi_styles:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: ansi_styles
|
||||||
|
sha256: "9c656cc12b3c27b17dd982b2cc5c0cfdfbdabd7bc8f3ae5e8542d9867b47ce8a"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.2+1"
|
||||||
|
ansicolor:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: ansicolor
|
||||||
|
sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.3"
|
||||||
args:
|
args:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -42,7 +58,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "9.3.0+1"
|
version: "9.3.0+1"
|
||||||
auto_route_generator:
|
auto_route_generator:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: auto_route_generator
|
name: auto_route_generator
|
||||||
sha256: c2e359d8932986d4d1bcad7a428143f81384ce10fef8d4aa5bc29e1f83766a46
|
sha256: c2e359d8932986d4d1bcad7a428143f81384ce10fef8d4aa5bc29e1f83766a46
|
||||||
@@ -98,7 +114,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "2.4.4"
|
version: "2.4.4"
|
||||||
build_runner:
|
build_runner:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: build_runner
|
name: build_runner
|
||||||
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
|
sha256: "058fe9dce1de7d69c4b84fada934df3e0153dd000758c4d65964d0166779aa99"
|
||||||
@@ -137,6 +153,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.0"
|
version: "1.4.0"
|
||||||
|
charcode:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: charcode
|
||||||
|
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.4.0"
|
||||||
checked_yaml:
|
checked_yaml:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -151,21 +175,37 @@ packages:
|
|||||||
path: "../../cherrypick"
|
path: "../../cherrypick"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "3.0.0-dev.3"
|
version: "3.0.0-dev.8"
|
||||||
cherrypick_annotations:
|
cherrypick_annotations:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "../../cherrypick_annotations"
|
path: "../../cherrypick_annotations"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "1.1.0"
|
version: "1.1.1"
|
||||||
cherrypick_generator:
|
cherrypick_generator:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "../../cherrypick_generator"
|
path: "../../cherrypick_generator"
|
||||||
relative: true
|
relative: true
|
||||||
source: path
|
source: path
|
||||||
version: "1.1.0"
|
version: "1.1.1"
|
||||||
|
cli_launcher:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: cli_launcher
|
||||||
|
sha256: "67d89e0a1c07b103d1253f6b953a43d3f502ee36805c8cfc21196282c9ddf177"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.2"
|
||||||
|
cli_util:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: cli_util
|
||||||
|
sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.4.2"
|
||||||
clock:
|
clock:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -190,6 +230,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
version: "1.19.1"
|
||||||
|
conventional_commit:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: conventional_commit
|
||||||
|
sha256: fad254feb6fb8eace2be18855176b0a4b97e0d50e416ff0fe590d5ba83735d34
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.6.1"
|
||||||
convert:
|
convert:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -198,6 +246,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.2"
|
version: "3.1.2"
|
||||||
|
cross_file:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: cross_file
|
||||||
|
sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.4+2"
|
||||||
crypto:
|
crypto:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -254,6 +310,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.3.2"
|
version: "1.3.2"
|
||||||
|
ffi:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: ffi
|
||||||
|
sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.4"
|
||||||
file:
|
file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -284,7 +348,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "9.1.1"
|
version: "9.1.1"
|
||||||
flutter_lints:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: flutter_lints
|
name: flutter_lints
|
||||||
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
|
sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1"
|
||||||
@@ -292,12 +356,17 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "5.0.0"
|
version: "5.0.0"
|
||||||
flutter_test:
|
flutter_test:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
|
description: flutter
|
||||||
|
source: sdk
|
||||||
|
version: "0.0.0"
|
||||||
|
flutter_web_plugins:
|
||||||
|
dependency: transitive
|
||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
freezed:
|
freezed:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: freezed
|
name: freezed
|
||||||
sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c"
|
sha256: "59a584c24b3acdc5250bb856d0d3e9c0b798ed14a4af1ddb7dc1c7b41df91c9c"
|
||||||
@@ -336,6 +405,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.3.2"
|
version: "2.3.2"
|
||||||
|
group_button:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: group_button
|
||||||
|
sha256: "0610fcf28ed122bfb4b410fce161a390f7f2531d55d1d65c5375982001415940"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.3.4"
|
||||||
http:
|
http:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -360,6 +437,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.0.2"
|
version: "4.0.2"
|
||||||
|
intl:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: intl
|
||||||
|
sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.19.0"
|
||||||
io:
|
io:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -385,7 +470,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "4.9.0"
|
version: "4.9.0"
|
||||||
json_serializable:
|
json_serializable:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: json_serializable
|
name: json_serializable
|
||||||
sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c
|
sha256: c50ef5fc083d5b5e12eef489503ba3bf5ccc899e487d691584699b4bdefeea8c
|
||||||
@@ -448,6 +533,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.11.1"
|
version: "0.11.1"
|
||||||
|
melos:
|
||||||
|
dependency: "direct dev"
|
||||||
|
description:
|
||||||
|
name: melos
|
||||||
|
sha256: "3f3ab3f902843d1e5a1b1a4dd39a4aca8ba1056f2d32fd8995210fa2843f646f"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.3.2"
|
||||||
meta:
|
meta:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -464,6 +557,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.0"
|
version: "2.0.0"
|
||||||
|
mustache_template:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: mustache_template
|
||||||
|
sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.0"
|
||||||
nested:
|
nested:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -488,6 +589,54 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.9.1"
|
version: "1.9.1"
|
||||||
|
path_provider:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider
|
||||||
|
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.5"
|
||||||
|
path_provider_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider_android
|
||||||
|
sha256: d0d310befe2c8ab9e7f393288ccbb11b60c019c6b5afc21973eeee4dda2b35e9
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.2.17"
|
||||||
|
path_provider_foundation:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider_foundation
|
||||||
|
sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.4.1"
|
||||||
|
path_provider_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider_linux
|
||||||
|
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.2.1"
|
||||||
|
path_provider_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider_platform_interface
|
||||||
|
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.2"
|
||||||
|
path_provider_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: path_provider_windows
|
||||||
|
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.3.0"
|
||||||
petitparser:
|
petitparser:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -496,6 +645,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.0.2"
|
version: "6.0.2"
|
||||||
|
platform:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: platform
|
||||||
|
sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.1.6"
|
||||||
|
plugin_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: plugin_platform_interface
|
||||||
|
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.1.8"
|
||||||
pool:
|
pool:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -504,6 +669,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.5.1"
|
version: "1.5.1"
|
||||||
|
process:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: process
|
||||||
|
sha256: c6248e4526673988586e8c00bb22a49210c258dc91df5227d5da9748ecf79744
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.0.5"
|
||||||
|
prompts:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: prompts
|
||||||
|
sha256: "3773b845e85a849f01e793c4fc18a45d52d7783b4cb6c0569fad19f9d0a774a1"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.0"
|
||||||
protobuf:
|
protobuf:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -528,6 +709,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.2.0"
|
||||||
|
pub_updater:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: pub_updater
|
||||||
|
sha256: "54e8dc865349059ebe7f163d6acce7c89eb958b8047e6d6e80ce93b13d7c9e60"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.4.0"
|
||||||
pubspec_parse:
|
pubspec_parse:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -545,13 +734,29 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "4.4.2"
|
version: "4.4.2"
|
||||||
retrofit_generator:
|
retrofit_generator:
|
||||||
dependency: "direct dev"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: retrofit_generator
|
name: retrofit_generator
|
||||||
sha256: "65d28d3a7b4db485f1c73fee8ee32f552ef23ee4ecb68ba491f39d80b73bdcbf"
|
sha256: "65d28d3a7b4db485f1c73fee8ee32f552ef23ee4ecb68ba491f39d80b73bdcbf"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "9.2.0"
|
version: "9.2.0"
|
||||||
|
share_plus:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: share_plus
|
||||||
|
sha256: b2961506569e28948d75ec346c28775bb111986bb69dc6a20754a457e3d97fa0
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "11.0.0"
|
||||||
|
share_plus_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: share_plus_platform_interface
|
||||||
|
sha256: "1032d392bc5d2095a77447a805aa3f804d2ae6a4d5eef5e6ebb3bd94c1bc19ef"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.0.0"
|
||||||
shelf:
|
shelf:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -597,6 +802,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.10.1"
|
version: "1.10.1"
|
||||||
|
sprintf:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: sprintf
|
||||||
|
sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "7.0.0"
|
||||||
stack_trace:
|
stack_trace:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -629,6 +842,53 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.1"
|
version: "1.4.1"
|
||||||
|
talker:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: talker
|
||||||
|
sha256: "028a753874d98df39f210cb74f0ee09a0a95e28f8bc2dc975c3c328e24fde23d"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.3"
|
||||||
|
talker_bloc_logger:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: talker_bloc_logger
|
||||||
|
sha256: cf1e3b1d70f9a47e061288f0d230ba0e04a0f6394629d5df1c7b0933b236e397
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.3"
|
||||||
|
talker_cherrypick_logger:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
path: "../../talker_cherrypick_logger"
|
||||||
|
relative: true
|
||||||
|
source: path
|
||||||
|
version: "1.0.0"
|
||||||
|
talker_dio_logger:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: talker_dio_logger
|
||||||
|
sha256: dcf784f1841e248c270ef741f8a07ca9cf562c6424ee43fc6e598c4eb7f18238
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.3"
|
||||||
|
talker_flutter:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: talker_flutter
|
||||||
|
sha256: "2cfee6661277d415a895b6258ecb0bf80d7b564e91ea7e769fc6d0f970a01c09"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.3"
|
||||||
|
talker_logger:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: talker_logger
|
||||||
|
sha256: "778ec673f1b71a6516e5576ae8d90ea23bbbcf9f405a97cc30e8ccdc33e26d27"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.9.3"
|
||||||
term_glyph:
|
term_glyph:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -661,6 +921,46 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.4.0"
|
version: "1.4.0"
|
||||||
|
url_launcher_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_linux
|
||||||
|
sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.2.1"
|
||||||
|
url_launcher_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_platform_interface
|
||||||
|
sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.3.2"
|
||||||
|
url_launcher_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_web
|
||||||
|
sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.4.1"
|
||||||
|
url_launcher_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: url_launcher_windows
|
||||||
|
sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.1.4"
|
||||||
|
uuid:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: uuid
|
||||||
|
sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.5.1"
|
||||||
vector_math:
|
vector_math:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -709,6 +1009,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.0.3"
|
version: "3.0.3"
|
||||||
|
win32:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: win32
|
||||||
|
sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "5.13.0"
|
||||||
|
xdg_directories:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: xdg_directories
|
||||||
|
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.0"
|
||||||
xml:
|
xml:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -725,6 +1041,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.3"
|
version: "3.1.3"
|
||||||
|
yaml_edit:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: yaml_edit
|
||||||
|
sha256: fb38626579fb345ad00e674e2af3a5c9b0cc4b9bfb8fd7f7ff322c7c9e62aef5
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.2.2"
|
||||||
sdks:
|
sdks:
|
||||||
dart: ">=3.7.0 <4.0.0"
|
dart: ">=3.7.0 <4.0.0"
|
||||||
flutter: ">=3.18.0-18.0.pre.54"
|
flutter: ">=3.27.0"
|
||||||
|
|||||||
@@ -24,9 +24,12 @@ dependencies:
|
|||||||
flutter_bloc: ^9.1.1
|
flutter_bloc: ^9.1.1
|
||||||
auto_route: ^9.3.0+1
|
auto_route: ^9.3.0+1
|
||||||
|
|
||||||
|
|
||||||
cupertino_icons: ^1.0.8
|
cupertino_icons: ^1.0.8
|
||||||
|
|
||||||
dev_dependencies:
|
talker_flutter: ^4.9.3
|
||||||
|
talker_cherrypick_logger:
|
||||||
|
path: ../../talker_cherrypick_logger
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
|
|
||||||
@@ -40,7 +43,11 @@ dev_dependencies:
|
|||||||
freezed: ^2.5.8
|
freezed: ^2.5.8
|
||||||
json_serializable: ^6.9.0
|
json_serializable: ^6.9.0
|
||||||
auto_route_generator: ^9.0.0
|
auto_route_generator: ^9.0.0
|
||||||
|
talker_dio_logger: ^4.9.3
|
||||||
|
talker_bloc_logger: ^4.9.3
|
||||||
|
|
||||||
flutter:
|
flutter:
|
||||||
|
|
||||||
uses-material-design: true
|
uses-material-design: true
|
||||||
|
dev_dependencies:
|
||||||
|
melos: ^6.3.2
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ packages:
|
|||||||
- cherrypick_flutter
|
- cherrypick_flutter
|
||||||
- cherrypick_annotations
|
- cherrypick_annotations
|
||||||
- cherrypick_generator
|
- cherrypick_generator
|
||||||
|
- talker_cherrypick_logger
|
||||||
- examples/client_app
|
- examples/client_app
|
||||||
- examples/postly
|
- examples/postly
|
||||||
|
|
||||||
|
|||||||
14
pubspec.lock
14
pubspec.lock
@@ -5,23 +5,23 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: _fe_analyzer_shared
|
name: _fe_analyzer_shared
|
||||||
sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab"
|
sha256: "45cfa8471b89fb6643fe9bf51bd7931a76b8f5ec2d65de4fb176dba8d4f22c77"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "76.0.0"
|
version: "73.0.0"
|
||||||
_macros:
|
_macros:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description: dart
|
description: dart
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.3.3"
|
version: "0.3.2"
|
||||||
analyzer:
|
analyzer:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: analyzer
|
name: analyzer
|
||||||
sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e"
|
sha256: "4959fec185fe70cce007c57e9ab6983101dbe593d2bf8bbfb4453aaec0cf470a"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.11.0"
|
version: "6.8.0"
|
||||||
ansi_styles:
|
ansi_styles:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -298,10 +298,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: macros
|
name: macros
|
||||||
sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656"
|
sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.1.3-main.0"
|
version: "0.1.2-main.4"
|
||||||
matcher:
|
matcher:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
26
talker_cherrypick_logger/.gitignore
vendored
Normal file
26
talker_cherrypick_logger/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# See https://www.dartlang.org/guides/libraries/private-files
|
||||||
|
|
||||||
|
# Files and directories created by pub
|
||||||
|
.dart_tool/
|
||||||
|
.packages
|
||||||
|
build/
|
||||||
|
# If you're building an application, you may want to check-in your pubspec.lock
|
||||||
|
pubspec.lock
|
||||||
|
|
||||||
|
# Directory created by dartdoc
|
||||||
|
# If you don't generate documentation locally you can remove this line.
|
||||||
|
doc/api/
|
||||||
|
|
||||||
|
# Avoid committing generated Javascript files:
|
||||||
|
*.dart.js
|
||||||
|
*.info.json # Produced by the --dump-info flag.
|
||||||
|
*.js # When generated by dart2js. Don't specify *.js if your
|
||||||
|
# project includes source files written in JavaScript.
|
||||||
|
*.js_
|
||||||
|
*.js.deps
|
||||||
|
*.js.map
|
||||||
|
|
||||||
|
# FVM Version Cache
|
||||||
|
.fvm/
|
||||||
|
|
||||||
|
pubspec_overrides.yaml
|
||||||
15
talker_cherrypick_logger/CHANGELOG.md
Normal file
15
talker_cherrypick_logger/CHANGELOG.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
## 1.1.0-dev.3
|
||||||
|
|
||||||
|
## 1.1.0-dev.2
|
||||||
|
|
||||||
|
- Bump "talker_cherrypick_logger" to `1.1.0-dev.2`.
|
||||||
|
|
||||||
|
## 1.1.0-dev.0
|
||||||
|
|
||||||
|
- **FEAT**(logging): add talker_dio_logger and talker_bloc_logger integration, improve cherrypick logger structure, add UI log screen for DI and network/bloc debug.
|
||||||
|
- **DOCS**: add full English documentation and usage guide to README.md.
|
||||||
|
- **DOCS**: add detailed English documentation and usage examples for TalkerCherryPickObserver.
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
- Initial version.
|
||||||
201
talker_cherrypick_logger/LICENSE
Normal file
201
talker_cherrypick_logger/LICENSE
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
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 the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
122
talker_cherrypick_logger/README.md
Normal file
122
talker_cherrypick_logger/README.md
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
# 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.
|
||||||
|
All CherryPick lifecycle events, instance creations, cache operations, module activities, cycles, and errors are routed directly to your Talker logger for easy debugging and advanced diagnostics.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Automatic DI container logging:**
|
||||||
|
All core CherryPick events (instance creation/disposal, cache hits/misses, module install/removal, scopes, cycles, errors) are logged through Talker.
|
||||||
|
- **Flexible log levels:**
|
||||||
|
Each event uses the appropriate Talker log level (`info`, `warning`, `verbose`, `handle` for errors).
|
||||||
|
- **Works with any Talker setup:**
|
||||||
|
No extra dependencies required except Talker and CherryPick.
|
||||||
|
- **Improves debugging and DI transparency** in both development and production.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
### 1. Add dependencies
|
||||||
|
|
||||||
|
In your `pubspec.yaml`:
|
||||||
|
```yaml
|
||||||
|
dependencies:
|
||||||
|
cherrypick: ^latest
|
||||||
|
talker: ^latest
|
||||||
|
talker_cherrypick_logger:
|
||||||
|
git:
|
||||||
|
url: https://github.com/pese-dot-work/cherrypick.git
|
||||||
|
path: talker_cherrypick_logger
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Import the package
|
||||||
|
```dart
|
||||||
|
import 'package:talker/talker.dart';
|
||||||
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Basic integration
|
||||||
|
|
||||||
|
1. **Create a Talker instance** (optionally customize Talker as you wish):
|
||||||
|
```dart
|
||||||
|
final talker = Talker();
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Create the observer and pass it to CherryPick:**
|
||||||
|
```dart
|
||||||
|
final observer = TalkerCherryPickObserver(talker);
|
||||||
|
|
||||||
|
// On DI setup, pass observer when opening (or re-opening) root or any custom scope
|
||||||
|
CherryPick.openRootScope(observer: observer);
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Now all DI events appear in your Talker logs!**
|
||||||
|
|
||||||
|
#### Example log output
|
||||||
|
|
||||||
|
- `[binding][CherryPick] MyService — MyServiceImpl (scope: root)`
|
||||||
|
- `[create][CherryPick] MyService — MyServiceImpl => Instance(...) (scope: root)`
|
||||||
|
- `[cache hit][CherryPick] MyService — MyServiceImpl (scope: root)`
|
||||||
|
- `[cycle][CherryPick] Detected: A -> B -> C -> A (scope: root)`
|
||||||
|
- `[error][CherryPick] Failed to resolve dependency`
|
||||||
|
- `[diagnostic][CherryPick] Cache cleared`
|
||||||
|
|
||||||
|
#### How it works
|
||||||
|
|
||||||
|
`TalkerCherryPickObserver` implements `CherryPickObserver` and routes all methods/events to Talker:
|
||||||
|
- Regular events: `.info()`
|
||||||
|
- DI Warnings and cycles: `.warning()`
|
||||||
|
- Diagnostics: `.verbose()`
|
||||||
|
- Errors: `.handle()` (so they are visible in Talker error console, with stack trace)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extended example
|
||||||
|
|
||||||
|
```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);
|
||||||
|
|
||||||
|
// Optionally: customize Talker output or filtering
|
||||||
|
// talker.settings.logLevel = TalkerLogLevel.debug;
|
||||||
|
|
||||||
|
CherryPick.openRootScope(observer: observer);
|
||||||
|
|
||||||
|
// ...setup your DI modules as usual
|
||||||
|
// All container events will appear in Talker logs for easy debugging!
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Additional information
|
||||||
|
|
||||||
|
- This package is especially useful for debugging large or layered projects using CherryPick.
|
||||||
|
- For advanced Talker configurations (UI, outputs to remote, filtering), see the [Talker documentation](https://pub.dev/packages/talker).
|
||||||
|
- This package does **not** interfere with DI graph construction or your app's behavior — it's purely diagnostic.
|
||||||
|
- For questions or issues, open an issue on the main [cherrypick repository](https://github.com/pese-dot-work/cherrypick).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Feel free to contribute improvements or report bugs via pull requests or issues!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
See [LICENSE](LICENSE) for details.
|
||||||
30
talker_cherrypick_logger/analysis_options.yaml
Normal file
30
talker_cherrypick_logger/analysis_options.yaml
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# This file configures the static analysis results for your project (errors,
|
||||||
|
# warnings, and lints).
|
||||||
|
#
|
||||||
|
# This enables the 'recommended' set of lints from `package:lints`.
|
||||||
|
# This set helps identify many issues that may lead to problems when running
|
||||||
|
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||||
|
# style and format.
|
||||||
|
#
|
||||||
|
# If you want a smaller set of lints you can change this to specify
|
||||||
|
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||||
|
# (the recommended set includes the core lints).
|
||||||
|
# The core lints are also what is used by pub.dev for scoring packages.
|
||||||
|
|
||||||
|
include: package:lints/recommended.yaml
|
||||||
|
|
||||||
|
# Uncomment the following section to specify additional rules.
|
||||||
|
|
||||||
|
# linter:
|
||||||
|
# rules:
|
||||||
|
# - camel_case_types
|
||||||
|
|
||||||
|
# analyzer:
|
||||||
|
# exclude:
|
||||||
|
# - path/to/excluded/files/**
|
||||||
|
|
||||||
|
# For more information about the core and recommended set of lints, see
|
||||||
|
# https://dart.dev/go/core-lints
|
||||||
|
|
||||||
|
# For additional information about configuring this file, see
|
||||||
|
# https://dart.dev/guides/language/analysis-options
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||||
|
import 'package:talker/talker.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final talker = Talker();
|
||||||
|
final logger = TalkerCherryPickObserver(talker);
|
||||||
|
|
||||||
|
logger.onDiagnostic('Hello from CherryPickLogger!');
|
||||||
|
logger.onWarning('Something might be wrong...');
|
||||||
|
logger.onError('Oops! An error occurred', Exception('Test error'), null);
|
||||||
|
|
||||||
|
// Вывод всех логов
|
||||||
|
print('\nВсе сообщения логирования через Talker:');
|
||||||
|
for (final log in talker.history) {
|
||||||
|
print(log); // Пример, либо log.toString(), либо log.message
|
||||||
|
}
|
||||||
|
}
|
||||||
141
talker_cherrypick_logger/lib/src/talker_cherrypick_observer.dart
Normal file
141
talker_cherrypick_logger/lib/src/talker_cherrypick_observer.dart
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
//
|
||||||
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
// 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 the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
//
|
||||||
|
|
||||||
|
import 'package:cherrypick/cherrypick.dart';
|
||||||
|
import 'package:talker/talker.dart';
|
||||||
|
|
||||||
|
/// An implementation of [CherryPickObserver] that logs all DI container events
|
||||||
|
/// through the [Talker] logging system.
|
||||||
|
///
|
||||||
|
/// This observer allows you to automatically route all important events from the
|
||||||
|
/// CherryPick DI container (such as instance creation, cache hits, errors, module install,
|
||||||
|
/// scope lifecycle events, and more) directly to your Talker logger. It is useful for
|
||||||
|
/// debugging, monitoring, and analytics.
|
||||||
|
///
|
||||||
|
/// ## Example usage
|
||||||
|
/// ```dart
|
||||||
|
/// import 'package:talker/talker.dart';
|
||||||
|
/// import 'package:cherrypick/cherrypick.dart';
|
||||||
|
/// import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||||
|
///
|
||||||
|
/// final talker = Talker();
|
||||||
|
/// final observer = TalkerCherryPickObserver(talker);
|
||||||
|
///
|
||||||
|
/// // Pass the observer to your CherryPick root scope (or any scope)
|
||||||
|
/// CherryPick.openRootScope(observer: observer);
|
||||||
|
///
|
||||||
|
/// // Now all DI container events will be logged with Talker
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// ## Logged event examples
|
||||||
|
/// - "[binding][CherryPick] MyService — MyServiceImpl (scope: root)"
|
||||||
|
/// - "[create][CherryPick] MyService — MyServiceImpl => Instance(...) (scope: root)"
|
||||||
|
/// - "[cache hit][CherryPick] MyService — MyServiceImpl (scope: root)"
|
||||||
|
/// - "[cycle][CherryPick] Detected: A -> B -> C -> A (scope: root)"
|
||||||
|
///
|
||||||
|
/// ## Log levels mapping
|
||||||
|
/// - `info`: regular events (registered, resolved, created, disposed, modules, scopes, cache hits/misses)
|
||||||
|
/// - `warning`: cycles, cherry pick warnings
|
||||||
|
/// - `verbose`: diagnostics
|
||||||
|
/// - `handle`: errors (includes error object/stack)
|
||||||
|
class TalkerCherryPickObserver implements CherryPickObserver {
|
||||||
|
/// The target [Talker] instance to send logs to.
|
||||||
|
final Talker talker;
|
||||||
|
|
||||||
|
/// Creates a [TalkerCherryPickObserver] that routes CherryPick DI events into the given [Talker] logger.
|
||||||
|
TalkerCherryPickObserver(this.talker);
|
||||||
|
|
||||||
|
/// Called when a binding (dependency mapping) is registered in the DI container.
|
||||||
|
@override
|
||||||
|
void onBindingRegistered(String name, Type type, {String? scopeName}) {
|
||||||
|
talker.info('[binding][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when an instance is requested (before creation or retrieval).
|
||||||
|
@override
|
||||||
|
void onInstanceRequested(String name, Type type, {String? scopeName}) {
|
||||||
|
talker.info('[request][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a new instance is created.
|
||||||
|
@override
|
||||||
|
void onInstanceCreated(String name, Type type, Object instance, {String? scopeName}) {
|
||||||
|
talker.info('[create][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when an instance is disposed.
|
||||||
|
@override
|
||||||
|
void onInstanceDisposed(String name, Type type, Object instance, {String? scopeName}) {
|
||||||
|
talker.info('[dispose][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when modules are installed.
|
||||||
|
@override
|
||||||
|
void onModulesInstalled(List<String> modules, {String? scopeName}) {
|
||||||
|
talker.info('[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when modules are removed.
|
||||||
|
@override
|
||||||
|
void onModulesRemoved(List<String> modules, {String? scopeName}) {
|
||||||
|
talker.info('[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a DI scope is opened.
|
||||||
|
@override
|
||||||
|
void onScopeOpened(String name) {
|
||||||
|
talker.info('[scope opened][CherryPick] $name');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when a DI scope is closed.
|
||||||
|
@override
|
||||||
|
void onScopeClosed(String name) {
|
||||||
|
talker.info('[scope closed][CherryPick] $name');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called if the DI container detects a cycle in the dependency graph.
|
||||||
|
@override
|
||||||
|
void onCycleDetected(List<String> chain, {String? scopeName}) {
|
||||||
|
talker.warning('[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when an instance is found in the cache.
|
||||||
|
@override
|
||||||
|
void onCacheHit(String name, Type type, {String? scopeName}) {
|
||||||
|
talker.info('[cache hit][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called when an instance is NOT found in the cache and will be created.
|
||||||
|
@override
|
||||||
|
void onCacheMiss(String name, Type type, {String? scopeName}) {
|
||||||
|
talker.info('[cache miss][CherryPick] $name — $type (scope: $scopeName)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called for generic diagnostic/debug events.
|
||||||
|
@override
|
||||||
|
void onDiagnostic(String message, {Object? details}) {
|
||||||
|
talker.verbose('[diagnostic][CherryPick] $message ${details ?? ''}');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called for non-fatal DI container warnings.
|
||||||
|
@override
|
||||||
|
void onWarning(String message, {Object? details}) {
|
||||||
|
talker.warning('[warn][CherryPick] $message ${details ?? ''}');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called for error events with optional stack trace.
|
||||||
|
@override
|
||||||
|
void onError(String message, Object? error, StackTrace? stackTrace) {
|
||||||
|
talker.handle(error ?? '[CherryPick] $message', stackTrace, '[error][CherryPick] $message');
|
||||||
|
}
|
||||||
|
}
|
||||||
18
talker_cherrypick_logger/lib/talker_cherrypick_logger.dart
Normal file
18
talker_cherrypick_logger/lib/talker_cherrypick_logger.dart
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
//
|
||||||
|
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
// 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 the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
//
|
||||||
|
|
||||||
|
library;
|
||||||
|
|
||||||
|
export 'src/talker_cherrypick_observer.dart';
|
||||||
|
|
||||||
|
// TODO: Export any libraries intended for clients of this package.
|
||||||
26
talker_cherrypick_logger/pubspec.yaml
Normal file
26
talker_cherrypick_logger/pubspec.yaml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
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.3
|
||||||
|
homepage: https://pese-git.github.io/cherrypick-site/
|
||||||
|
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||||
|
repository: https://github.com/pese-git/cherrypick
|
||||||
|
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||||
|
|
||||||
|
topics:
|
||||||
|
- cherrypick
|
||||||
|
- state
|
||||||
|
- logging
|
||||||
|
- log
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: ">=3.5.2 <4.0.0"
|
||||||
|
|
||||||
|
# Add regular dependencies here.
|
||||||
|
dependencies:
|
||||||
|
talker: ^4.9.3
|
||||||
|
cherrypick: ^3.0.0-dev.9
|
||||||
|
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
lints: ^5.0.0
|
||||||
|
test: ^1.24.0
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import 'package:test/test.dart';
|
||||||
|
import 'package:talker/talker.dart';
|
||||||
|
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('TalkerCherryPickObserver', () {
|
||||||
|
late Talker talker;
|
||||||
|
late TalkerCherryPickObserver observer;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
talker = Talker();
|
||||||
|
observer = TalkerCherryPickObserver(talker);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onInstanceRequested logs info', () {
|
||||||
|
observer.onInstanceRequested('A', String, scopeName: 'test');
|
||||||
|
final log = talker.history.last;
|
||||||
|
expect(log.message, contains('[request][CherryPick] A — String (scope: test)'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onCycleDetected logs warning', () {
|
||||||
|
observer.onCycleDetected(['A', 'B'], scopeName: 's');
|
||||||
|
final log = talker.history.last;
|
||||||
|
expect(log.message, contains('[cycle][CherryPick] Detected'));
|
||||||
|
//expect(log.level, TalkerLogLevel.warning);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onError calls handle', () {
|
||||||
|
final error = Exception('fail');
|
||||||
|
final stack = StackTrace.current;
|
||||||
|
observer.onError('Oops', error, stack);
|
||||||
|
final log = talker.history.last;
|
||||||
|
expect(log.message, contains('[error][CherryPick] Oops'));
|
||||||
|
expect(log.exception, error);
|
||||||
|
expect(log.stackTrace, stack);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onDiagnostic logs verbose', () {
|
||||||
|
observer.onDiagnostic('hello', details: 123);
|
||||||
|
final log = talker.history.last;
|
||||||
|
//expect(log.level, TalkerLogLevel.verbose);
|
||||||
|
expect(log.message, contains('hello'));
|
||||||
|
expect(log.message, contains('123'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user