# Magic Deeplink documentation > Magic Deeplink brings Universal Links on iOS and App Links on Android to a Magic app through one API on top of app_links. # Installation Add `magic_deeplink` to a Magic application, run its manifest installer, register a handler and finish the native setup an operating system needs before it hands your app a link. - [Quick Start](#quick-start) - [Requirements](#requirements) - [Running the Install Command](#running-the-install-command) - [Registering a Route Handler](#registering-a-route-handler) - [Platform Setup](#platform-setup) - [iOS: Associated Domains and Info.plist](#ios-associated-domains-and-infoplist) - [Android: Intent Filter and Manifest](#android-intent-filter-and-manifest) - [macOS](#macos) - [Verify](#verify) - [Related Documentation](#related-documentation) ## Quick Start ```bash flutter pub add magic_deeplink dart run magic:dowel plugin:install magic_deeplink dart run magic:dowel deeplink:doctor ``` `magic_deeplink` delegates link delivery to [`app_links`](https://pub.dev/packages/app_links) and ships no native plugin code of its own. That does not remove the platform setup an operating system requires: an iOS entitlement, an Android intent filter, and a switch on each platform that keeps Flutter's own deep link handler out of the way. See [Platform Setup](#platform-setup). ## Requirements | Requirement | Constraint | |:------------|:-----------| | Dart SDK | `>=3.13.0` | | Flutter | `>=3.47.0` | | `magic` | `^1.0.0`, installed and bootstrapped: `lib/config/app.dart` declares a `'providers'` list and `lib/main.dart` calls `Magic.init` with `configFactories` | ## Running the Install Command `plugin:install` runs the manifest in the package's `install.yaml` and registers `MagicDeeplinkDowelProvider` in `.dowel/plugins.json`, which is what makes the `deeplink:*` commands available in your project. The package must already be in `pubspec.yaml` and resolved by `flutter pub get`. ```bash dart run magic:dowel plugin:install magic_deeplink ``` The manifest: 1. Publishes `lib/config/deeplink.dart` from the bundled stub. See [Configuration](https://anilcancakir.com/magic/docs/deeplink/getting-started/configuration.md) for its keys. 2. Adds `(app) => DeeplinkServiceProvider(app)` and its import to the `'providers'` list in `lib/config/app.dart`. The install fails with an error naming the file when `app.dart` has no such list. 3. Adds `() => deeplinkConfig` and `import 'config/deeplink.dart';` to the `configFactories` list in `lib/main.dart`. 4. Sets `FlutterDeepLinkingEnabled` to `false` in `ios/Runner/Info.plist`. `dart run magic:dowel deeplink:install` runs the same manifest again, for a project that has already registered the provider. An existing `lib/config/deeplink.dart` that the installer did not write, or that changed since, is a conflict: the command exits with `1` until you pass `--force`. | Flag | Effect | |:-----|:-------| | `--force` | Bypass the conflict check and overwrite. | | `--dry-run` | Print the staged operations without writing. | | `--non-interactive` | Skip prompts and use defaults. | After the install, `DeeplinkServiceProvider` is in your providers list: ```dart import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; // RouteServiceProvider and AppServiceProvider are the host's own providers. final appConfig = { 'app': { 'providers': [ (app) => RouteServiceProvider(app), (app) => AppServiceProvider(app), (app) => DeeplinkServiceProvider(app), // added by the install ], }, }; ``` and `lib/main.dart` passes the config factory to `Magic.init`: ```dart import 'package:magic/magic.dart'; // appConfig and deeplinkConfig are the host's own, from lib/config/. Future main() async { await Magic.init( configFactories: [ () => appConfig, () => deeplinkConfig, // added by the install ], ); } ``` The provider binds `DeeplinkManager` as a singleton under the `'deeplinks'` key, so `app.make('deeplinks')` resolves it anywhere. ## Registering a Route Handler The install wires the driver and the provider but registers no handler: `DeeplinkServiceProvider` cannot know which paths your app serves, and a link that reaches the manager with no handler registered is dropped without an error. Register one in your own provider's `boot()`: ```dart import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { DeeplinkManager().registerHandler( RouteDeeplinkHandler( paths: ['/monitors/:id', '/invitations/:token/accept'], hosts: [Config.getOrFail('deeplink.domain')], ), ); } } ``` See [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md) for the contract, the path patterns and writing a custom handler. ## Platform Setup An operating system will not hand your app a link until you declare that the app owns the domain, and Flutter's own deep link handler races the `app_links` driver unless you switch it off. Only the iOS plist key is automated; the rest is a one-time edit to the native project. ### iOS: Associated Domains and Info.plist 1. **Add the Associated Domains capability.** In Xcode, open the `Runner` target's Signing & Capabilities tab, add "Associated Domains" and an entry of the form `applinks:`. This writes the `com.apple.developer.associated-domains` entitlement to `ios/Runner/Runner.entitlements`: ```xml com.apple.developer.associated-domains applinks:example.com ``` 2. **Turn off Flutter's own deep link handler.** Flutter has handled deep links itself by default since 3.27, and when it does the handler chain never sees the link. The `FlutterDeepLinkingEnabled` key in `ios/Runner/Info.plist` must be `false`: ```xml FlutterDeepLinkingEnabled ``` The install applies this key (`native.ios.info_plist` in `install.yaml`). Re-check it when something else in your project overwrites `Info.plist`. 3. **Host the `apple-app-site-association` file.** Generate it with [`deeplink:generate`](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md#generate) and serve it from `https:///.well-known/apple-app-site-association` over HTTPS with no redirect. ### Android: Intent Filter and Manifest 1. **Add the intent filter.** Inside the `` element of `android/app/src/main/AndroidManifest.xml`, add an autoVerify filter with a `` element for both `http` and `https`: ```xml ``` 2. **Turn off Flutter's own deep link handler, inside ``.** Add this element to the same ``, not to ``: ```xml ``` The install does not apply this one. The `meta_data` key of `install.yaml` inserts into ``, Flutter reads this entry from ``, and an automated entry in the wrong element would look applied while doing nothing. Add it by hand; [`deeplink:doctor`](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md#doctor) fails when it sits in the wrong element. 3. **Host the `assetlinks.json` file.** Generate it with `deeplink:generate` and serve it from `https:///.well-known/assetlinks.json`. Android verifies it at install time, not at link-click time. ### macOS `AppLinksDriver` reports itself supported on macOS, so the provider wires it there. Nothing else in this package covers macOS: the install does not touch the macOS project, `deeplink:doctor` inspects only `ios/` and `android/`, and `deeplink:generate` writes a single `appIDs` entry built from one `team_id` and `bundle_id`, so a macOS app with a different bundle identifier needs its own entry. Follow the macOS setup in the [`app_links`](https://pub.dev/packages/app_links) package for the entitlement. ## Verify ```bash dart run magic:dowel deeplink:doctor ``` Every way of getting this install wrong is silent: a `` on the wrong element, a missing `` scheme, an association file that names another bundle, a provider that never reached `lib/config/app.dart`. None throws or logs; the only symptom is a link that opens the browser. The doctor reads the project's own files and reports which prerequisite is missing. Add `--remote` to also fetch both association files from the live domain. It cannot prove that a real device matches a link to this app: `swcutil verify` needs root and Android verifies at install time, so the last mile is always a real device. See [CLI](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md#doctor) for every check. ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/deeplink/getting-started/configuration.md): the keys of `lib/config/deeplink.dart`. - [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md): `RouteDeeplinkHandler`, tenant switching and custom handlers. - [CLI](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md): `deeplink:install`, `deeplink:generate` and `deeplink:doctor`. - [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md): platform support of `AppLinksDriver`. - [Service Provider](https://anilcancakir.com/magic/docs/deeplink/architecture/service-provider.md): what `boot()` wires. - [Routing in Magic](https://anilcancakir.com/magic/docs/basics/routing): `MagicRoute` and the `url_strategy` setting. --- # Configuration `magic_deeplink` is configured by one Dart file, `lib/config/deeplink.dart`, whose `deeplink` map drives the runtime provider, the association files and the doctor. - [Quick Reference](#quick-reference) - [The Deeplink Config File](#deeplink-config-file) - [Driver Selection](#driver-selection) - [iOS Configuration](#ios-configuration) - [Android Configuration](#android-configuration) - [Paths](#paths) - [Accessing Configuration Values](#accessing-configuration-values) - [Related Documentation](#related-documentation) ## Quick Reference | Key | Type | Read by | |:----|:-----|:--------| | `deeplink.enabled` | `bool` | `DeeplinkServiceProvider.boot()`. An absent key means enabled; only an explicit `false` wires nothing. | | `deeplink.driver` | `String` | `DeeplinkServiceProvider.boot()`. `'app_links'` is the only built-in driver. | | `deeplink.domain` | `String` | `deeplink:doctor` (entitlement host, intent filter host, `--remote` fetch). Your own handler's `hosts` can read it too. | | `deeplink.ios.team_id`, `deeplink.ios.bundle_id` | `String` | `deeplink:generate` and `deeplink:doctor`. | | `deeplink.android.package_name`, `deeplink.android.sha256_fingerprints` | `String`, `List` | `deeplink:generate` and `deeplink:doctor`. | | `deeplink.paths` | `List` | `deeplink:generate`, for the `components` of the `apple-app-site-association` file. | The install command scaffolds the file with placeholder values (`example.com`, `YOUR_TEAM_ID`, `com.example.app`, `YOUR_SHA256_FINGERPRINT`); the doctor reports any that are left. ## The Deeplink Config File `lib/config/deeplink.dart` exports one top-level getter that returns a nested `Map`: ```dart Map get deeplinkConfig => { 'deeplink': { 'enabled': true, 'driver': 'app_links', 'domain': 'example.com', 'ios': { 'team_id': 'YOUR_TEAM_ID', 'bundle_id': 'com.example.app', }, 'android': { 'package_name': 'com.example.app', 'sha256_fingerprints': [ 'YOUR_SHA256_FINGERPRINT', ], }, 'paths': [ '/*', ], }, }; ``` A `'scheme': 'https'` entry in an older published config is read by nothing, so you can delete it. `lib/main.dart` hands the getter to `Magic.init` as a factory: ```dart import 'package:magic/magic.dart'; import 'config/app.dart'; import 'config/deeplink.dart'; // added by the install Future main() async { await Magic.init( configFactories: [ () => appConfig, () => deeplinkConfig, ], ); } ``` > [!NOTE] > The `deeplink:generate` and `deeplink:doctor` commands read this file as text, with single-quoted string literals. See [CLI](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md#config-merge-strategy). ## Driver Selection The `'driver'` key names the platform abstraction that receives incoming links: | Value | Package | Platforms | |:------|:--------|:----------| | `'app_links'` | `app_links` | Android, iOS and macOS. Web, Windows and Linux report the driver as unsupported. | `DeeplinkServiceProvider.boot()` creates `AppLinksDriver` for `'app_links'` and nothing for any other value, so a different name wires no driver and no link subscription. The provider then checks `driver.isSupported` before wiring further: on web, Windows and Linux no driver is set on the manager and no subscription is created, and `'driver': 'app_links'` stays the correct value on every platform. See [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md). > [!NOTE] > `'enabled'` gates all of this. `boot()` returns immediately when `Config.get('deeplink.enabled') == false`, which skips the driver, the link subscription and the push bridge regardless of `'driver'`. ## iOS Configuration iOS Universal Links need an `apple-app-site-association` (AASA) file hosted at your domain. The `ios` block holds the values the generator needs: | Key | Type | Description | |:----|:-----|:------------| | `team_id` | `String` | Your Apple Developer Team ID, from Membership in the Apple Developer portal. | | `bundle_id` | `String` | The bundle identifier of your iOS app, for example `com.example.app`. | The generator writes Apple's `appIDs` plus `components` shape, with the app identifier built as `TEAM_ID.BUNDLE_ID` and one `components` entry per path. It never writes the legacy `appID` plus `paths` entry or an `apps` key: mixing the two schemas may produce unexpected behaviour for universal links, and the doctor warns when a file does. ```json { "applinks": { "details": [ { "appIDs": ["ABCDE12345.com.example.app"], "components": [ { "/": "/*", "comment": "Matches any URL whose path matches /*" } ] } ] } } ``` > [!NOTE] > Serve the file over HTTPS at `https:///.well-known/apple-app-site-association` with `Content-Type: application/json` and no redirect. `deeplink:doctor --remote` checks the status, that the body parses as JSON and the content type. ## Android Configuration Android App Links need an `assetlinks.json` file hosted at your domain. The `android` block holds the values the generator needs: | Key | Type | Description | |:----|:-----|:------------| | `package_name` | `String` | The Android application ID, matching `applicationId` in `android/app/build.gradle`. | | `sha256_fingerprints` | `List` | One or more SHA-256 certificate fingerprints. Include every signing configuration you ship with, such as debug and release. | ```bash keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android ``` Each fingerprint produces its own entry in `assetlinks.json`: ```dart 'sha256_fingerprints': [ 'AA:BB:CC:...', // debug keystore 'DD:EE:FF:...', // release keystore ], ``` > [!NOTE] > Serve the file at `https:///.well-known/assetlinks.json` with `Content-Type: application/json`. Android verifies it at install time, not at link-click time. ## Paths `paths` is the list of URL path patterns written into the `components` of the iOS AASA file. It does not filter links at runtime: which paths your app routes is decided by the `paths` of the `RouteDeeplinkHandler` you register. See [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md#routedeeplinkhandler). ```dart 'paths': [ '/app/*', '/invite/*', '/reset-password', ], ``` | Pattern | Matches | |:--------|:--------| | `'/*'` | All paths | | `'/app/*'` | Any path starting with `/app/` | | `'/reset-password'` | Exactly `/reset-password` | > [!NOTE] > `assetlinks.json` grants the app the whole domain and carries no paths. On Android the path filter is the intent filter in `AndroidManifest.xml`. ## Accessing Configuration Values At runtime magic's `Config` facade reads every value with dot notation: ```dart import 'package:magic/magic.dart'; final bool enabled = Config.get('deeplink.enabled', true) ?? true; final String? domain = Config.get('deeplink.domain'); final String? teamId = Config.get('deeplink.ios.team_id'); ``` `DeeplinkServiceProvider` passes the whole `deeplink` map to `driver.initialize()` during `boot()`. `AppLinksDriver` does not read it; a custom driver can. ## Related Documentation - [CLI](https://anilcancakir.com/magic/docs/deeplink/basics/cli.md): `deeplink:generate` reads these keys and `deeplink:doctor` validates them. - [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md): the install command and the native setup. - [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md): what the `driver` key selects. - [Service Provider](https://anilcancakir.com/magic/docs/deeplink/architecture/service-provider.md): how `boot()` reads `enabled` and `driver`. - [Configuration in Magic](https://anilcancakir.com/magic/docs/getting-started/configuration): config factories and dot notation. --- # Drivers A driver turns a platform's link mechanism into a uniform `Stream` for `DeeplinkManager`, and `AppLinksDriver` is the one that ships with the package. - [Quick Reference](#quick-reference) - [The DeeplinkDriver Contract](#the-deeplink-driver-contract) - [AppLinksDriver](#applinksdriver) - [Platform Support](#platform-support) - [Web, in detail](#web) - [Custom Drivers](#custom-drivers) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference | Platform | `AppLinksDriver.isSupported` | Mechanism | |:---------|:-----------------------------|:----------| | Android | `true` | App Links (HTTPS intent filter) | | iOS | `true` | Universal Links (`apple-app-site-association`) | | macOS | `true` | Universal Links; the install and the doctor do not cover macOS | | Web | `false` | None; see [Web, in detail](#web) | | Windows, Linux | `false` | None | `DeeplinkServiceProvider` creates `AppLinksDriver` when `deeplink.driver` is `'app_links'`, and wires it only when `isSupported` is `true`. You rarely touch the driver directly. ## The DeeplinkDriver Contract Every driver extends `DeeplinkDriver`: ```dart abstract class DeeplinkDriver { String get name; bool get isSupported; Future initialize(Map config); Future getInitialLink(); Stream get onLink; void dispose(); } ``` | Member | Contract | |:-------|:---------| | `name` | A stable identifier. `AppLinksDriver` answers `'app_links'`. | | `isSupported` | Whether the driver can run on this platform. Synchronous. The provider skips `initialize`, the manager and the subscription for a driver of its own that answers `false`. | | `initialize` | Called once by the provider with the whole `deeplink` config map, before `onLink` is read. | | `getInitialLink` | The URI that cold-started the app, or `null`. Called by `DeeplinkManager.getInitialLink()`, which caches the answer; the provider does not call it. Return `null` on failure rather than throwing. | | `onLink` | A stream of every URI received while the app runs. Return `Stream.empty()` where the platform has none. | | `dispose` | Releases what the driver holds. `DeeplinkServiceProvider.dispose()` calls it for a driver the provider created. | ## AppLinksDriver The exported `AppLinksDriver` is a conditional-export barrel over platform arms chosen at compile time: ```dart export 'app_links_driver_stub.dart' if (dart.library.js_interop) 'app_links_driver_web.dart' if (dart.library.io) 'app_links_driver_io.dart'; ``` The `dart:io` arm wraps the [`app_links`](https://pub.dev/packages/app_links) package and is the only arm that talks to a platform channel. It answers `isSupported` from `Platform.isAndroid || Platform.isIOS || Platform.isMacOS`, creates its `AppLinks` instance in `initialize`, and takes `getInitialLink()` and `onLink` from `app_links`. The cold-start link is also the first emission of `onLink`. The web arm and the stub arm, which no shipped build target resolves to, are inert: `isSupported` is `false`, `getInitialLink()` returns `null`, `onLink` is `Stream.empty()`, and `initialize` and `dispose` do nothing. ```dart import 'package:magic_deeplink/magic_deeplink.dart'; Future main() async { final AppLinksDriver driver = AppLinksDriver(); await driver.initialize({}); final Uri? initial = await driver.getInitialLink(); if (initial != null) { // The link that launched the app. } driver.onLink.listen((Uri uri) { // Links received while the app runs. }); } ``` ### Platform Support On Android, iOS and macOS the barrel resolves to the `dart:io` arm. On Windows and Linux it resolves to the same arm, whose `Platform` check answers `false`, so the provider wires nothing there either. Native setup per platform is in [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md#platform-setup). ### Web, in detail "No driver" is not "no deep links". The web has routes into a screen that this package owns no driver for, so both are easy to leave half configured. **A tapped push, with the tab open, reaches the handler chain.** The push bridge is wired outside the `isSupported` gate in `DeeplinkServiceProvider.boot()`, so it exists on the web as on mobile: `OneSignalWebDriver` publishes the click, the notification manager republishes it, and `OneSignalDeeplinkHandler` routes it with `DeeplinkSource.push`. Put the link in the notification's `additionalData` under `url`, `deep_link`, `link` or `uri`, the keys mobile reads. A launch URL set on the OneSignal side alone is not read. **An address-bar link is GoRouter's job.** The driver is inert rather than wired to `app_links_web`, because that package reads `location.href` once at boot and never reacts to later navigation, so routing the same URI through both would duplicate it. GoRouter only receives a clean path when both of these outside this package hold, and neither fails loudly: 1. `routing.url_strategy` is `'path'` in the app's routing config. Without it Flutter uses the hash strategy and `https://app.example.com/incidents/5` is not a route. See [Routing in Magic](https://anilcancakir.com/magic/docs/basics/routing). 2. The web host rewrites unknown paths to `index.html`. Without it the same URL is a plain 404 from the host and Flutter never boots. A push clicked with no tab open runs no Dart code, so nothing in this package reads `additionalData`; whatever page the browser then opens is an ordinary page load and depends on the two points above. ## Custom Drivers A custom driver extends `DeeplinkDriver` and implements every member. The provider wires only the built-in driver, so a custom one does not feed the manager on its own: `manager.setDriver()` makes it the manager's driver (what `manager.driver` and `getInitialLink()` use), and you call `initialize`, subscribe to `onLink` and pass each URI to `handleUri` yourself. ```dart import 'dart:async'; import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; class QrDriver extends DeeplinkDriver { final StreamController _controller = StreamController.broadcast(); @override String get name => 'qr'; @override bool get isSupported => true; @override Future initialize(Map config) async {} @override Future getInitialLink() async => null; @override Stream get onLink => _controller.stream; /// Call this from the scanner callback. void emit(Uri uri) => _controller.add(uri); @override void dispose() => unawaited(_controller.close()); } class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { final DeeplinkManager manager = DeeplinkManager(); final QrDriver driver = QrDriver(); await driver.initialize({}); manager.setDriver(driver); driver.onLink.listen((Uri uri) { unawaited(manager.handleUri(uri, source: DeeplinkSource.manual)); }); } } ``` `setDriver()` replaces the previous driver without disposing it. `MagicRoute.to` throws until the router exists, which happens while the first frame is built, so a driver whose links can arrive that early should wait the way the provider does: capture `WidgetsFlutterBinding.ensureInitialized().endOfFrame` once and await it before `handleUri`. ## Gotchas | Mistake | Fix | |:--------|:----| | Expecting address-bar links on the web to reach the handlers. | They never do; GoRouter owns them. Set `routing.url_strategy` to `'path'` and make the host rewrite unknown paths to `index.html`. | | Calling `setDriver()` with a custom driver and waiting for links. | The provider wires only `AppLinksDriver`. Subscribe to the custom driver's `onLink` and call `handleUri` yourself. | | Setting `deeplink.driver` to any value other than `'app_links'`. | The provider creates no driver and no subscription, though the push bridge still runs. Keep `'app_links'`. | | Routing the result of `getInitialLink()` as well as listening to `onLink`. | The cold-start link is already the first emission of `onLink`, so the handler chain runs twice for one tap. Use one path. | | Expecting links on Windows or Linux. | `isSupported` is `false` there and nothing is wired. | | Assuming the install and the doctor set up macOS. | They cover iOS and Android only. Add the macOS entitlement by hand and verify on a device. | ## Related Documentation - [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md): what runs after a driver emits a link. - [Configuration](https://anilcancakir.com/magic/docs/deeplink/getting-started/configuration.md): the `driver` and `enabled` keys. - [Service Provider](https://anilcancakir.com/magic/docs/deeplink/architecture/service-provider.md): boot order, driver initialisation and stream wiring. - [DeeplinkManager](https://anilcancakir.com/magic/docs/deeplink/architecture/deeplink-manager.md): `setDriver()`, `handleUri()` and the cached initial link. --- # Handlers Handlers decide what an incoming link does: `DeeplinkManager` offers each URI to its registered handlers in order and the first one that claims it handles it. - [Quick Reference](#quick-reference) - [The DeeplinkHandler Contract](#the-deeplinkhandler-contract) - [canHandle](#canhandle) - [handle](#handle) - [DeeplinkSource](#deeplinksource) - [Built-in Handlers](#built-in-handlers) - [RouteDeeplinkHandler](#routedeeplinkhandler) - [Switching Tenants from a Push](#switching-tenants-from-a-push) - [Breadcrumb Events](#breadcrumb-events) - [OneSignalDeeplinkHandler](#onesignaldeeplinkhandler) - [Creating Custom Handlers](#creating-custom-handlers) - [Registering Handlers](#registering-handlers) - [Handler Execution Order](#handler-execution-order) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference ```dart import 'package:magic_deeplink/magic_deeplink.dart'; void main() { DeeplinkManager().registerHandler( RouteDeeplinkHandler( paths: ['/products/:id', '/shop/*'], hosts: ['example.com'], ), ); } ``` | Class | Role | |:------|:-----| | `DeeplinkHandler` | The contract: `canHandle(Uri)` and `handle(Uri, {source, payload})`. | | `RouteDeeplinkHandler` | Matches the path against patterns and navigates with `MagicRoute.to()`. | | `TenantSwitchGate` | Optional: lets a tapped push switch tenant before `RouteDeeplinkHandler` navigates. | | `OneSignalDeeplinkHandler` | Not a `DeeplinkHandler`: turns a tapped push into a `handleUri` call. | ## The DeeplinkHandler Contract ```dart abstract class DeeplinkHandler { bool canHandle(Uri uri); Future handle( Uri uri, { required DeeplinkSource source, Map? payload, }); } ``` ### canHandle A synchronous, side-effect-free predicate. Return `true` to claim the URI, `false` to pass it to the next handler. It runs on every incoming link, so keep it cheap. ### handle Called only after `canHandle` returned `true`. Return `true` when the URI was handled and `false` when it could not be, and never throw: the manager does not catch, so the exception reaches whoever called `handleUri`. For a link the provider delivers that means a logged error and a lost link, and no later handler gets a try. `source` and `payload` come from `DeeplinkManager.handleUri()` and say where the instruction came from; see [DeeplinkSource](#deeplinksource). ### DeeplinkSource ```dart enum DeeplinkSource { osLink, push, manual } ``` The sources are not equally trusted: | Value | Meaning | `payload` | |:------|:--------|:----------| | `osLink` | The operating system opened the app on a Universal Link or App Link. Anyone who can get the device to open a URI can craft one, so treat it as untrusted input. | Always `null`. | | `push` | The user tapped a push notification, and the payload is the server's own. | The full payload the notification arrived with. | | `manual` | The application asked for the link itself, in code or in a test. | Whatever the caller passed, or `null`. | `source` is required and has no default, so a handler cannot forget to ask. A handler that acts on more than the path it was given, such as switching the active team from a `team_id` key, may do so only when `source == DeeplinkSource.push`, because that is the one case where the payload was authored by the server rather than crafted into a URI. `RouteDeeplinkHandler` reads `source` and `payload` only when it was given a [`tenantGate`](#switching-tenants-from-a-push): navigating to a path you listed is safe whoever asked, moving the session's tenant is not. ## Built-in Handlers ### RouteDeeplinkHandler Matches the URI path against a list of patterns and navigates to the match with `MagicRoute.to()`. ```dart RouteDeeplinkHandler({ required List paths, List? hosts, bool caseSensitive = false, TenantSwitchGate? tenantGate, }) ``` **Pattern syntax.** Patterns are compiled to anchored regular expressions, and a trailing slash on the incoming path is dropped before matching: | Pattern | Matches | |:--------|:--------| | `/products` | Exactly `/products` | | `/products/:id` | One non-slash segment, as a named parameter | | `/products/*` | Anything after `/products/`, slashes included | | `/shop/*/detail` | `/shop/`, anything, then `/detail` | Matching ignores letter case unless `caseSensitive` is `true`. go_router routes are case-sensitive, so a project that mounted `/incidents/:id` can set it to stop `/INCIDENTS/5` being claimed and then landing on go_router's not-found page. **Hosts.** `hosts` defaults to `null`, which claims an absolute URI on any host whose path matches. Set it to gate `canHandle` on the address as well: - A relative URI (no scheme and no authority, the shape of a push payload path) is always accepted, since there is no host to check. - An absolute URI is accepted only over `http` or `https`, with no explicit port and no userinfo, and only when its host equals an entry of `hosts`, ignoring case. A different host, another scheme, a port or embedded credentials is refused before the path is matched. - A blank entry is ignored rather than treated as a wildcard: `hosts: ['']` refuses every absolute URI. ```dart import 'package:magic_deeplink/magic_deeplink.dart'; void main() { final RouteDeeplinkHandler handler = RouteDeeplinkHandler( paths: ['/monitors/:id'], hosts: ['example.com'], ); handler.canHandle(Uri.parse('/monitors/5')); // true, relative handler.canHandle(Uri.parse('https://EXAMPLE.com/monitors/5')); // true handler.canHandle(Uri.parse('https://evil.com/monitors/5')); // false, wrong host handler.canHandle(Uri.parse('https://example.com:8443/monitors/5')); // false, port } ``` **Navigation.** A matching link navigates with the parsed path, the same value `canHandle` matched, and forwards the query parameters: ```dart import 'package:magic/magic.dart'; void open(Uri uri) { MagicRoute.to(uri.path, query: uri.queryParameters); } ``` So `https://example.com/products/42?ref=email` opens `/products/42` with `Request.query('ref')` answering `email`. `handle` never throws. It re-checks `canHandle` and answers `false` for a path it does not serve, and a navigation that fails, such as the `StateError` of a router that is not built yet, is logged through `Log` when a `log` binding exists and answered `false`. ### Switching Tenants from a Push A multi-tenant backend resolves a page against the session's current tenant and answers 404 for another tenant's row, so a push that pages a user about another team's incident would land on that 404. Give `RouteDeeplinkHandler` a `TenantSwitchGate` and it switches first: ```dart import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; import 'package:magic_starter/magic_starter.dart'; final RouteDeeplinkHandler handler = RouteDeeplinkHandler( paths: ['/incidents/:id'], tenantGate: TenantSwitchGate( currentTenantId: MagicStarter.currentTeamId, switchTenant: MagicStarter.switchTeam, onSwitched: () => Magic.success('Switched team', 'Opened on the team it belongs to.'), onSwitchFailed: (String teamId) => Magic.error('Error', 'Could not switch team.'), ), ); ``` Any `String? Function()` and `Future Function(String)` will do; the sample uses `magic_starter`'s team switcher. | Field | Meaning | |:------|:--------| | `payloadKey` | The push payload key naming the owning tenant. Defaults to `'team_id'`. | | `currentTenantId` | The session's current tenant id, or `null` while it has not resolved. | | `switchTenant` | Moves the session onto a tenant and answers whether it took. | | `onSwitched` | Optional. Runs after a successful switch, before the navigation. One that throws is logged and the link still opens, because the session has already moved. | | `onSwitchFailed` | Optional. Runs with the requested tenant id when `switchTenant` answered `false` or threw. | The rules belong to the handler, and no gate configuration changes them: - **Only `DeeplinkSource.push` switches.** An `osLink` or `manual` link navigates without switching, whatever its payload or query carries. - **The tenant comes from the payload under `payloadKey`, never from the URI query.** The query is part of the link. - **Ids compare as trimmed strings**, so a wire `5` and a local `'5'` are the same tenant. - **No evidence, no switch.** An absent or blank payload tenant, or a `null` current tenant, navigates directly. - **A failed switch does not navigate.** `switchTenant` answering `false` or throwing calls `onSwitchFailed`, logs an error and answers `false`, since opening the page anyway would meet the same 404. ### Breadcrumb Events `RouteDeeplinkHandler` dispatches these events through `Event.dispatch`, unawaited, so a failing listener never costs the navigation: | Event | When | `breadcrumbCategory` | `breadcrumbData` | |:------|:-----|:---------------------|:-----------------| | `DeeplinkOpened` | After `canHandle` passed, before any switch or navigation | `deeplink.open` | `source`, `route`, `names_tenant` | | `DeeplinkNavigating` | Immediately before `MagicRoute.to` | `deeplink.navigate` | `route` | Both implement magic's `ReportsBreadcrumb`, so a crash reporter that listens to every event with `Event.listenAny`, as `magic_sentry` does, records them without this package depending on it. `DeeplinkNavigating` is the last breadcrumb before the router runs, which tells "the link never resolved" apart from "the page it named threw". `route` is the handler's own matched pattern (`/invitations/:token/accept`), not the concrete path, and the data never carries the query string or a payload value, since a link can carry an invite or reset token in any of them. ```dart import 'package:flutter/foundation.dart'; import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; void main() { Event.listenAny((MagicEvent event) { if (event is DeeplinkNavigating) { debugPrint('opening a link matching ${event.route}'); } }); } ``` ### OneSignalDeeplinkHandler Bridges push-notification clicks into the pipeline. It does not implement `DeeplinkHandler`: it is a listener that reads a URI from the notification payload and passes it to `DeeplinkManager.handleUri()` with `DeeplinkSource.push` and the whole payload. `DeeplinkServiceProvider.boot()` wires it for you when `app.bound('notifications')` is true, so an app with `magic_notifications` needs no code. The URI comes from the first of the payload keys `url`, `deep_link`, `link` and `uri` that holds a non-empty string. A push with no such key is not a failure: most notifications are meant to be read. To wire it yourself, call `setup()` once with the manager and the notification manager, and `dispose()` when done: ```dart void setup(DeeplinkManager manager, dynamic notifications) void dispose() ``` `notifications` is read structurally, so this package declares no dependency on `magic_notifications`. The handler subscribes to the notification manager's `onPushClicked` stream, which exists from construction, so it works whether or not the notifications provider has booted. A manager that publishes no such stream, or an event with no readable `data` payload, is reported at error level through `Log` when a `log` binding exists, rather than thrown or silently dropped. A click that arrives before the first frame waits for it, so a cold start from a push still finds the router. ## Creating Custom Handlers Extend `DeeplinkHandler` for any matching logic the path patterns cannot express: ```dart import 'package:magic/magic.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; class ProductDeeplinkHandler extends DeeplinkHandler { @override bool canHandle(Uri uri) { final List segments = uri.pathSegments; return segments.length == 2 && segments[0] == 'products' && int.tryParse(segments[1]) != null; } @override Future handle( Uri uri, { required DeeplinkSource source, Map? payload, }) async { try { MagicRoute.to('/products/${uri.pathSegments[1]}', query: uri.queryParameters); return true; } catch (error) { if (Magic.bound('log')) { Log.error('[ProductDeeplinkHandler] opening $uri failed: $error'); } return false; } } } ``` - `canHandle` is synchronous and free of side effects. - `handle` never throws; wrap what can fail and return `false`. - Read `payload` only when `source == DeeplinkSource.push`. ## Registering Handlers Register on the `DeeplinkManager` singleton. Registering the same instance twice has no effect, and `hasHandler()` and `forgetHandlers()` inspect and clear the list: ```dart import 'package:magic_deeplink/magic_deeplink.dart'; // ProductDeeplinkHandler is the host's own handler class. void main() { final DeeplinkManager manager = DeeplinkManager(); manager.registerHandler(ProductDeeplinkHandler()); manager.registerHandler(RouteDeeplinkHandler(paths: ['/products/*', '/shop/*'])); } ``` Do it in your own provider's `boot()`; see [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md#registering-a-route-handler). `DeeplinkServiceProvider` registers no handler of its own. ## Handler Execution Order Handlers run in registration order, and the manager stops at the first whose `canHandle` is `true`. `handleUri` also emits the URI on `manager.onLink` before the chain runs, so stream listeners see every link whether or not a handler claims it. It returns `false` when no handler does. Register specific handlers before generic ones. A wildcard `RouteDeeplinkHandler` registered first claims URIs a more specific handler registered after it never sees. ## Gotchas | Mistake | Fix | |:--------|:----| | No handler is registered. | Links reach the manager and are dropped, with no error. Register one in your provider's `boot()`; `deeplink:doctor` warns when it finds no `registerHandler(` call. | | A wildcard handler registered before a specific one. | Order is registration order and the first match wins. Register the specific handler first. | | Leaving `hosts` as `null` on `RouteDeeplinkHandler`. | A link on any host whose path matches is claimed. Set `hosts` to your domain. | | Reading `payload` or a query value to decide who the user acts as. | Only `source == DeeplinkSource.push` carries a server-authored payload, and a switch never reads the query. Leave tenant changes to `TenantSwitchGate`. | | Throwing from `handle`. | Return `false`. The manager does not catch; the provider logs the error and the link is lost. | | Reading `*` as one path segment. | `*` matches slashes too. Use `:name` for exactly one segment. | ## Related Documentation - [DeeplinkManager](https://anilcancakir.com/magic/docs/deeplink/architecture/deeplink-manager.md): the handler chain and `handleUri`. - [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md): where the links come from. - [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md): registering a first handler. - [Service Provider](https://anilcancakir.com/magic/docs/deeplink/architecture/service-provider.md): how the push bridge is wired and torn down. - [Channels in magic_notifications](https://anilcancakir.com/magic/docs/notifications/basics/channels): the push side of the bridge. - [Teams in magic_starter](https://anilcancakir.com/magic/docs/starter/basics/teams): the team switcher the tenant sample uses. --- # CLI The `deeplink:*` dowel commands install the plugin, generate the `apple-app-site-association` and `assetlinks.json` files, and check that an install is wired end to end. - [Quick Reference](#quick-reference) - [Commands](#commands) - [install](#install) - [generate](#generate) - [doctor](#doctor) - [Config Merge Strategy](#config-merge-strategy) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference The package has no `bin/` of its own. `dart run magic:dowel plugin:install magic_deeplink` registers `MagicDeeplinkDowelProvider` in `.dowel/plugins.json`, and the host app's dowel dispatcher then lists these commands: | Command | Purpose | |:--------|:--------| | `dart run magic:dowel deeplink:install` | Publish `lib/config/deeplink.dart` and wire the provider and config factory. | | `dart run magic:dowel deeplink:generate` | Write `apple-app-site-association` and `assetlinks.json`. | | `dart run magic:dowel deeplink:doctor` | Check the config, the Dart wiring, both platform trees and the association files. | `dart run magic:dowel list` shows what is registered. ## Commands ### install Runs the manifest in the package's `install.yaml` through dowel's transactional installer. ```bash dart run magic:dowel deeplink:install dart run magic:dowel deeplink:install --force dart run magic:dowel deeplink:install --dry-run ``` The manifest: 1. Publishes `lib/config/deeplink.dart` from the bundled stub. 2. Adds `DeeplinkServiceProvider` and its import to the `'providers'` list in `lib/config/app.dart`. 3. Adds `() => deeplinkConfig` and `import 'config/deeplink.dart';` to the `configFactories` list in `lib/main.dart`. 4. Sets `FlutterDeepLinkingEnabled` to `false` in `ios/Runner/Info.plist`. 5. Prints the post-install message. | Flag | Default | Description | |:-----|:--------|:------------| | `--force` | `false` | Bypass conflict detection and overwrite files the installer did not write or that changed since. | | `--dry-run` | `false` | Print the staged operations without writing. | | `--non-interactive` | `false` | Skip prompts and use defaults. | The command exits with `0` on success or a dry run, and `1` otherwise. It does not edit the Android manifest or register a handler; see [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md). ### generate Writes the server-side verification files: `apple-app-site-association` for iOS Universal Links and `assetlinks.json` for Android App Links. ```bash dart run magic:dowel deeplink:generate \ --team-id ABCDE12345 \ --bundle-id com.example.app \ --package-name com.example.app \ --sha256-fingerprints "AA:BB:CC:DD:..." \ --output public/.well-known ``` #### Options | Option | Type | Default | Description | |:-------|:-----|:--------|:------------| | `--output` | string | `public` | Output directory, relative to the project root. | | `--root` | string | `.` | Project root. `.` means the project found from the working directory. | | `--team-id` | string | none | Apple Developer Team ID. Needed for `apple-app-site-association`. | | `--bundle-id` | string | none | iOS bundle identifier. Needed for `apple-app-site-association`. | | `--package-name` | string | none | Android package name. Needed for `assetlinks.json`. | | `--sha256-fingerprints` | list | none | SHA-256 certificate fingerprints. Repeat the flag or comma-separate values. Needed for `assetlinks.json`. | | `--paths` | list | `/*` | Path patterns written into the AASA `components`. Repeat the flag or comma-separate values. | #### Output | File | Platform | Needs | |:-----|:---------|:------| | `/apple-app-site-association` | iOS | `--team-id` and `--bundle-id` | | `/assetlinks.json` | Android | `--package-name` and `--sha256-fingerprints` | Each value falls back to `lib/config/deeplink.dart` (see [Config Merge Strategy](#config-merge-strategy)). When a platform's values are still missing, that file is skipped with a warning and the command still exits with `0`, so one platform's file can be generated on its own. `apple-app-site-association`: ```json { "applinks": { "details": [ { "appIDs": ["."], "components": [ { "/": "/*", "comment": "Matches any URL whose path matches /*" } ] } ] } } ``` `assetlinks.json` has one entry per fingerprint: ```json [ { "relation": ["delegate_permission/common.handle_all_urls"], "target": { "namespace": "android_app", "package_name": "com.example.app", "sha256_cert_fingerprints": ["AA:BB:CC:DD:..."] } } ] ``` ### doctor Checks whether an install actually works, before a device is involved. The manifest installer can publish a file and inject a line, but it cannot place an `` inside a specific `` or notice a `` on the wrong element, and every way of getting that half wrong is silent: the link opens the browser, with no exception and no log line. ```bash dart run magic:dowel deeplink:doctor dart run magic:dowel deeplink:doctor --verbose dart run magic:dowel deeplink:doctor --remote ``` #### What it checks Local checks, always run: 1. `lib/config/deeplink.dart` exists and parses with the parser `generate` uses, and none of `domain`, `team_id`, `bundle_id`, `package_name` and `sha256_fingerprints` is still a scaffold placeholder. 2. Dart wiring: `DeeplinkServiceProvider` appears in `lib/config/app.dart` and `deeplinkConfig` in `lib/main.dart`. A missing `registerHandler(` call under `lib/` is a warning, not a failure, because handlers may be registered somewhere the scan cannot see. 3. iOS, when `ios/` exists: `FlutterDeepLinkingEnabled` is `false` in `Info.plist`, and `Runner.entitlements` carries `com.apple.developer.associated-domains` with an `applinks:` host equal to `deeplink.domain`. 4. Android, when `android/` exists: an `` inside an activity carries `VIEW`, `DEFAULT`, `BROWSABLE`, `` for both `http` and `https`, and a host equal to `deeplink.domain`; and `flutter_deeplinking_enabled` is `false` inside ``, not ``. The manifest is read by element position rather than searched as text, because a `` in the wrong element searches identically to one in the right element and does nothing. 5. The association files exist under `web/.well-known/` or `public/.well-known/` and agree with the config: the AASA claims `.`, and `assetlinks.json` lists the package name and every fingerprint. An AASA that mixes the legacy `appID` plus `paths` shape with the `appIDs` plus `components` shape is a warning. Remote check, only with `--remote`: 6. `GET https:///.well-known/apple-app-site-association` and `.../assetlinks.json` must answer `200` with no redirect and a body that parses as JSON. An AASA served with a content type other than `application/json` is a warning. The check never runs by default, so the doctor does not hang on DNS in CI or offline. macOS is not inspected. #### What it cannot prove No check can prove that a device matches a link to this app: `swcutil verify` needs root and Android verifies at install time. The report says so rather than letting a green run imply it. #### Options and exit codes | Flag | Default | Description | |:-----|:--------|:------------| | `--verbose` | `false` | Show per-issue detail under each section. | | `--remote` | `false` | Also fetch both association files from the live domain. | | Code | Meaning | |:-----|:--------| | `0` | Every check passed, or only warnings were raised. | | `1` | At least one check failed. | ## Config Merge Strategy `generate` and `doctor` read `lib/config/deeplink.dart` as text, and `generate` treats its values as defaults: a flag passed on the command line wins. | Config key | Flag | |:-----------|:-----| | `team_id` | `--team-id` | | `bundle_id` | `--bundle-id` | | `package_name` | `--package-name` | | `sha256_fingerprints` | `--sha256-fingerprints` | | `paths` | `--paths` | `--paths` defaults to `/*`, and the config's `paths` replaces it only while the flag is still exactly that default and the config lists at least one path. A `--paths '/*'` typed by hand is therefore indistinguishable from no flag, and the config wins. A project can commit every identifier in the config file and run `generate` with no flags in CI. The reader matches single-quoted literals with a regular expression, takes the first match in the file, and tolerates a generic type annotation before a list (`[...]`). ## Gotchas | Mistake | Fix | |:--------|:----| | `deeplink:*` commands are not listed. | Run `dart run magic:dowel plugin:install magic_deeplink` once; it registers the provider in `.dowel/plugins.json`. | | Re-running `deeplink:install` fails with a conflict over `lib/config/deeplink.dart`. | The file is not one the installer wrote, or it changed since. Pass `--force` only when you mean to overwrite it. | | `generate --output public` and the doctor still reports the association files missing. | The doctor looks in `web/.well-known/` and `public/.well-known/`. Generate with `--output public/.well-known`. | | The config uses double quotes, or builds a value from a variable. | `generate` and `doctor` read single-quoted literals only. Keep `team_id`, `bundle_id`, `package_name`, `sha256_fingerprints`, `paths` and `domain` as plain single-quoted strings. | | `generate` printed a warning and a file is missing from the output. | A platform's values were incomplete, and the file was skipped with exit code `0`. Supply the flags or fill the config. | | A green doctor, and the link still opens the browser. | The doctor reads files; it cannot match a device. Test on a real device, and on the live domain with `--remote`. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md): the install command and the native setup the doctor checks. - [Configuration](https://anilcancakir.com/magic/docs/deeplink/getting-started/configuration.md): every key of `lib/config/deeplink.dart`. - [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md): registering what the doctor looks for with `registerHandler(`. - [Magic CLI](https://anilcancakir.com/magic/docs/packages/magic-cli): the `magic:dowel` executable that dispatches plugin commands. --- # DeeplinkManager `DeeplinkManager` is the singleton that owns one platform driver, an ordered list of handlers and a broadcast stream of every incoming deep link. - [Quick Reference](#quick-reference) - [Singleton Pattern](#singleton-pattern) - [Driver Orchestration](#driver-orchestration) - [Setting a Driver](#setting-a-driver) - [Removing a Driver](#removing-a-driver) - [Handler Chain](#handler-chain) - [Registering Handlers](#registering-handlers) - [Removing Handlers](#removing-handlers) - [URI Stream](#uri-stream) - [handleUri Flow](#handleuri-flow) - [Initial Link Caching](#initial-link-caching) - [Data Flow](#data-flow) - [Related Documentation](#related-documentation) ## Quick Reference `DeeplinkServiceProvider` creates and wires the manager during boot, so consuming code rarely needs more than the singleton: ```dart import 'package:magic_deeplink/magic_deeplink.dart'; void main() { final DeeplinkManager manager = DeeplinkManager(); manager.onLink.listen((Uri uri) { // Your own code goes here, for instance a call to your analytics. }); } ``` | Member | Purpose | |:-------|:--------| | `driver` | The current `DeeplinkDriver`; throws `DeeplinkException` with code `NO_DRIVER` when none is set. | | `setDriver(driver)`, `forgetDriver()` | Assign or drop the driver. | | `registerHandler(handler)`, `hasHandler(handler)`, `forgetHandlers()` | Manage the ordered handler list. | | `onLink` | Broadcast stream of every URI passed to `handleUri`. | | `handleUri(uri, {source, payload})` | Emit on `onLink`, then offer the URI to the handlers. | | `getInitialLink()` | Ask the driver for the cold-start link, once, and cache it. | | `reset()` | `@visibleForTesting`: return the singleton to its constructed state. | ## Singleton Pattern The manager is a process-wide singleton. Every `DeeplinkManager()` call returns the same instance, and the provider also binds it in the container under `'deeplinks'`. Nothing creates a second one, so handlers and a driver set through one reference are visible through every other. **Testing reset.** The singleton persists across tests. `forgetHandlers()` and `forgetDriver()` alone leave the cached initial link behind, so a second `getInitialLink()` answers the previous test's URI without reaching the driver, and they leave the broadcast controller behind `onLink` in place. `reset()` clears both, along with the handlers and the driver. Call it in `setUp` so a test starts clean, and in `tearDown` so nothing leaks into the next one: ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic_deeplink/magic_deeplink.dart'; void main() { setUp(() { DeeplinkManager().reset(); }); tearDown(() { DeeplinkManager().reset(); }); } ``` ## Driver Orchestration The manager delegates platform I/O to a single `DeeplinkDriver`. It has none at construction: `DeeplinkServiceProvider.boot()` sets it once the container is ready, and only when the driver reports `isSupported`. ### Setting a Driver ```dart void setDriver(DeeplinkDriver driver) ``` Assigns the active driver, replacing any previous one without disposing it. `getInitialLink()` calls through whatever driver is set. ### Removing a Driver ```dart void forgetDriver() ``` Sets the driver to `null`. The `driver` getter then throws until a new one is set: ```dart throw DeeplinkException( 'No deep link driver configured. Make sure to call setDriver() or register the service provider.', code: 'NO_DRIVER', ); ``` The driver contract is in [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md#the-deeplink-driver-contract). ## Handler Chain The manager keeps an ordered `List`. A URI is offered in registration order, and the first handler whose `canHandle()` returns `true` wins; later handlers are skipped. ### Registering Handlers ```dart import 'package:magic_deeplink/magic_deeplink.dart'; void main() { final DeeplinkManager manager = DeeplinkManager(); manager.registerHandler(RouteDeeplinkHandler(paths: ['/products/:id'])); } ``` A handler already in the list, by identity, is ignored. `hasHandler(handler)` answers whether that exact instance is registered. The handler contract is in [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md#the-deeplinkhandler-contract). ### Removing Handlers `forgetHandlers()` clears the list. It is for test teardown and provider re-boot; there is no way to remove a single handler. ## URI Stream ```dart Stream get onLink; ``` `onLink` is a broadcast stream, so analytics, routing and tests can subscribe independently. It is never closed during normal operation and lives as long as the singleton; only `reset()` closes it and replaces it, after which `onLink` hands out the new stream. ## handleUri Flow ```dart Future handleUri( Uri uri, { required DeeplinkSource source, Map? payload, }); ``` 1. **Emit.** The URI goes onto `onLink` before any handler runs, so every subscriber sees every URI, handled or not. 2. **Dispatch.** The first handler whose `canHandle(uri)` is `true` receives `source` and `payload` and its answer is returned. When none matches, the result is `false`. `source` is required at the call site and `payload` is optional, because neither can be recovered from the URI. The provider's driver subscription passes `DeeplinkSource.osLink` and no payload; `OneSignalDeeplinkHandler` passes `DeeplinkSource.push` and the whole notification payload. See [DeeplinkSource](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md#deeplinksource). ## Initial Link Caching `getInitialLink()` asks the driver for the link that launched the app and caches the answer, including `null`, so later calls skip the driver: ```dart Future getInitialLink(); ``` | State | Behaviour | |:------|:----------| | First call | Delegates to `driver.getInitialLink()` and remembers the answer, `null` included. | | Later calls | Returns the cached value without touching the driver. | The provider does not call this method: `app_links` serves the cold-start link as the first emission of `onLink`, and routing it from both places would run the handler chain twice for one tap. It stays on the manager for a consumer that wants to ask directly. `forgetDriver()` does not clear the cache; `reset()` does. ## Data Flow ``` App launch │ ▼ DeeplinkServiceProvider.boot() │ ├─ return early if config.deeplink.enabled == false │ ├─ manager.setDriver(driver) (only when driver.isSupported) │ ├─ driver.initialize(config) │ └─ driver.onLink.listen(uri => deliver after endOfFrame) │ ▼ manager.handleUri(uri, source: DeeplinkSource.osLink) │ ├─ emit the uri ──► onLink stream subscribers │ └─ iterate the handlers in registration order │ ├─ handler.canHandle(uri) == false ──► next handler │ └─ handler.canHandle(uri) == true │ ▼ handler.handle(uri, source: source, payload: payload) │ └─ return bool ──► handleUri returns ``` ## Related Documentation - [Service Provider](https://anilcancakir.com/magic/docs/deeplink/architecture/service-provider.md): how the manager is bound and wired during boot. - [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md): the driver contract and `AppLinksDriver`. - [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md): the handler contract and the built-in handlers. --- # DeeplinkServiceProvider `DeeplinkServiceProvider` is the bootstrap entry point of `magic_deeplink`: it binds the manager, creates the platform driver, routes incoming links through the handler chain and bridges tapped pushes. - [Quick Reference](#quick-reference) - [Two-Phase Bootstrap](#two-phase-bootstrap) - [Register Phase](#register-phase) - [Boot Phase](#boot-phase) - [Driver Initialisation](#driver-initialization) - [Stream Wiring](#stream-wiring) - [Initial Link Handling](#initial-link-handling) - [OneSignal Handler Setup](#onesignal-handler-setup) - [Optional Dependency Handling](#optional-dependency-handling) - [Provider Teardown](#provider-teardown) - [Registering the Provider](#registering-the-provider) - [Related Documentation](#related-documentation) ## Quick Reference The provider extends `ServiceProvider` from `package:magic/magic.dart`. The install adds it to `lib/config/app.dart`; by hand: ```dart import 'package:magic_deeplink/magic_deeplink.dart'; Map get appConfig => { 'app': { 'providers': [ // ... other providers (app) => DeeplinkServiceProvider(app), ], }, }; ``` | Phase | What happens | |:------|:-------------| | `register()` | Binds `DeeplinkManager` under `'deeplinks'`. | | `boot()` | Reads `deeplink.enabled` and `deeplink.driver`, wires the driver and the link stream, bridges pushes when `magic_notifications` is bound. | | `dispose()` | Tears down what `boot()` wired. Nothing in the framework calls it. | The constructor takes an optional `driverFactory`, which defaults to `AppLinksDriver.new`, so a test can substitute a fake: the real driver reads `isSupported` from the host platform. ## Two-Phase Bootstrap Magic calls providers in two ordered phases: | Phase | Method | Constraint | |:------|:-------|:-----------| | 1 | `register()` | Synchronous. Only bind into the container; no other service is reachable yet. | | 2 | `boot()` | Asynchronous. Every provider has registered, so every binding is resolvable. | Application boot awaits each provider's `boot()` in a plain loop with no error handling, so an exception that escapes `boot()` aborts app boot and every provider registered after this one. ## Register Phase ```dart @override void register() { app.singleton('deeplinks', () => DeeplinkManager()); } ``` `register()` binds the manager and nothing else: config is not read and no driver is created. `DeeplinkManager()` is itself a singleton factory, so the closure and the factory share one instance. ## Boot Phase ```dart @override Future boot() async { final config = app.make('config'); final manager = app.make('deeplinks'); if (config.get('deeplink.enabled') == false) { return; } final driverName = config.get('deeplink.driver'); final driver = driverName == 'app_links' ? _driverFactory() : null; // ... driver and handler wiring } ``` An absent `deeplink.enabled` means enabled, so only an explicit `false` skips everything below, including the push bridge. ### Driver Initialisation `'app_links'` is the only value that creates a driver. The driver is wired further only when it also reports `isSupported`: ```dart if (driver != null && driver.isSupported) { manager.setDriver(driver); await driver.initialize(config.get>('deeplink') ?? {}); // ... } ``` A driver that answers `false` is never handed to the manager and never initialised, so `manager.driver` does not answer with something that can never deliver. The web arm of `AppLinksDriver` always answers `false`. The whole `deeplink` config map goes to `initialize()`, which is awaited before the stream is wired. ### Stream Wiring After initialisation the provider subscribes to `driver.onLink` and delivers each URI once the first frame has rendered. It captures `WidgetsFlutterBinding.ensureInitialized().endOfFrame` once and hands each URI to a delivery step that awaits that future, then calls `manager.handleUri(uri, source: DeeplinkSource.osLink)` inside a `try` and `catch` that reports a failure through `Log` (guarded by `Magic.bound('log')`) instead of letting it escape as an unhandled async error. Universal Links on iOS and App Links on Android take this one path. `handleUri` emits the URI on `manager.onLink`, then walks the registered handlers in registration order and returns after the first one whose `canHandle` succeeds: later handlers never receive that URI, so register the most specific handler first. ### Initial Link Handling A cold start from a link needs no separate read: `app_links` serves the launch link as the first emission of the same `onLink` stream the provider already subscribes to. The provider never calls `manager.getInitialLink()`, because a second delivery of the same link would run the handler chain twice for one tap. `DeeplinkManager.getInitialLink()` stays available for a consumer that wants to ask directly. The delivery waits because the router does not exist yet at boot: `MagicRoute.to` throws a `StateError` until the app builds the router, which happens while the first frame is built. `endOfFrame` names that event instead of guessing a duration, and it schedules a frame when the scheduler is idle, so a link delivered to an application nobody is drawing is not left waiting. The future is captured once, before the first link can arrive, so awaiting deliveries resume in the order they arrived. A cold-start link that arrives while a provider registered after this one is still booting can resume against a router that is not built; the `catch` around the delivery then logs the `StateError` rather than losing the link silently. ### OneSignal Handler Setup When `magic_notifications` is bound, the provider attaches a `OneSignalDeeplinkHandler` that converts tapped-push events into deep link calls: ```dart if (app.bound('notifications')) { final handler = OneSignalDeeplinkHandler(); try { handler.setup(manager, app.make('notifications')); // The provider keeps the handler in a field of its own, so that // dispose() can reach it. } catch (error) { handler.dispose(); if (Magic.bound('log')) { Log.error( '[deeplink] Resolving the bound `notifications` manager failed, so ' 'a tapped push notification cannot open a deep link: $error', ); } } } ``` The provider keeps the handler so `dispose()` can reach it. `setup()` takes the notification manager and subscribes to its `onPushClicked` stream, which the manager owns from construction. Only the `'notifications'` binding has to exist at this point, never a resolved push driver, so provider order does not matter. The handler reads a URI from the payload keys `url`, `deep_link`, `link` and `uri`, and calls `manager.handleUri(uri, source: DeeplinkSource.push, payload: data)` with the whole payload. This block sits outside the `isSupported` gate, so it runs on the web too. ## Optional Dependency Handling The `magic_notifications` integration is optional, and layered guards keep it from breaking boot: 1. **`app.bound('notifications')`** guards the whole block. Without the plugin the block is skipped. 2. **Structural access.** `app.make('notifications')` is handed over untyped and `OneSignalDeeplinkHandler` reads `onPushClicked` off it by name, so `magic_deeplink` imports nothing from `magic_notifications`. A manager that publishes no such stream, or publishes something that is not a `Stream`, is reported through `Log` instead of thrown, so a version mismatch degrades deep linking rather than breaking boot. 3. **A `try` and `catch` around the resolution**, reporting at error level through the same `Log` seam. `app.make('notifications')` runs the binding factory and `onPushClicked` is a getter, so either can throw, and the handler answers only `NoSuchMethodError` by name. Anything else, such as a `StateError` from an uninitialised manager, would otherwise abort app boot over an optional plugin. The `catch` names what failed and then lets boot continue. Follow the same pattern wherever `magic_deeplink` integrates with another optional plugin. ## Provider Teardown `DeeplinkServiceProvider.dispose()` drops everything `boot()` wired: the push-click handler, the driver's link subscription, the driver itself, and the manager's reference to it through `DeeplinkManager.forgetDriver()`. A delivery that is still waiting on `endOfFrame` checks, once the wait ends and before it hands the link over, whether the provider was disposed, since it has no handle a teardown could cancel. ```dart import 'package:magic_deeplink/magic_deeplink.dart'; Future tearDown(DeeplinkServiceProvider provider) async { await provider.dispose(); } ``` It is provider-level so that a consumer who tears down from the provider does not leave the driver running, and it is idempotent, because a consumer does not know which parts a given deployment wired. Nothing in the framework calls it; call it from whatever holds the provider instance. ## Registering the Provider Add the provider to the `providers` list in `lib/config/app.dart`, as in the Quick Reference. The `deeplink` config map comes from `lib/config/deeplink.dart` through `Magic.init(configFactories: [...])`; see [Configuration](https://anilcancakir.com/magic/docs/deeplink/getting-started/configuration.md). The provider's position relative to the provider that registers `'notifications'` does not matter. `app.bound('notifications')` is checked during boot, after every provider has registered, and the handler subscribes to the notification manager's own stream rather than to a driver. ## Related Documentation - [DeeplinkManager](https://anilcancakir.com/magic/docs/deeplink/architecture/deeplink-manager.md): the singleton the provider wires. - [Drivers](https://anilcancakir.com/magic/docs/deeplink/basics/drivers.md): the driver the provider creates. - [Handlers](https://anilcancakir.com/magic/docs/deeplink/basics/handlers.md): `OneSignalDeeplinkHandler` and the handler chain. - [Installation](https://anilcancakir.com/magic/docs/deeplink/getting-started/installation.md): adding the provider with the install command. - [Service Providers in Magic](https://anilcancakir.com/magic/docs/getting-started/service-providers): the two-phase lifecycle. - [Channels in magic_notifications](https://anilcancakir.com/magic/docs/notifications/basics/channels): the notification manager the push bridge reads.