Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 71 additions & 16 deletions dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,31 @@ Tokens: `@Contract`
-------------------

A token is an abstract class annotated with `@Contract`. The class is both the
compile-time type and the runtime lookup key; the decorator records the token's
canonical string name:
compile-time type and the runtime lookup key:

```ts
import { Contract } from "nativescript/contracts";

@Contract({ name: "doctorService" }) // canonical form, no `$`
@Contract()
export abstract class ReportWriter {
abstract write(report: string): Promise<void>;
}
```

Such a token resolves by the class and nothing else: it has no string spelling,
and a duplicated copy of the class is a different token.

Implementations do not become tokens by extending or implementing a contract;
only the decorated class itself is a token.

### Named contracts: `@LegacyContract`

`@LegacyContract` adds a canonical string name, which the token also answers to:

```ts
import { LegacyContract } from "nativescript/contracts";

@LegacyContract({ name: "doctorService" }) // canonical form, no `$`
export abstract class DoctorService {
abstract canExecuteLocalBuild(configuration?: {
platform?: string;
Expand All @@ -52,6 +70,15 @@ export abstract class DoctorService {
}
```

A name exists for compatibility. Use one only when the service has to stay
reachable by callers that cannot hold the class:

- code that resolves it by string — hook parameters, `$`-prefixed constructor
parameters, `resolve("name")`, string registrations;
- an extension whose dependency tree carries its own copy of the contract. This
is why the contracts exported from `nativescript/contracts` are named, the
recent ones included: without a name, such a copy cannot be resolved.

Rules:

- **The name is an explicit string literal** — never derived from `class.name`,
Expand All @@ -60,8 +87,34 @@ Rules:
same name **throws at load time**, because a duplicate would silently alias
two tokens.
- The options object leaves room for future fields without changing call sites.
- Implementations do not become tokens by extending or implementing a contract;
only the decorated class itself is a token.

`@Contract({ name })` is the deprecated spelling of `@LegacyContract({ name })`
and behaves identically.

### Internal contracts

Only what `nativescript/contracts` exports is a supported API. Contracts for the
CLI's own plumbing live in `lib/contracts/internal` and are never exported from
it: they may change or disappear in any release, even where a name keeps them
resolvable by string or a deep `require()` reaches the file. A public contract's
signature must not mention an internal one.

To move an existing service onto an internal contract:

1. Declare the contract in `lib/contracts/internal`, as a `@LegacyContract`
under the name the service is registered with.
2. Turn the ambient interface into an alias of it
(`interface IOsInfo extends OsInfo {}`).
3. Rename the implementation to `*Impl` and register it with
`injector.register(provide(OsInfo, OsInfoImpl))` — or by its name, while it
still takes `$`-prefixed constructor parameters. The `injector.require()`
entry in the bootstrap stays as it is.
4. Move consumers from `$osInfo` parameters to `inject(OsInfo)` fields, in as
many steps as convenient: both reach the same instance.

`lib/contracts/internal/os-info.ts` is the worked example. A service that never
had a string name takes a plain `@Contract()` and a `provideLazy()` registration
instead.

Tokens for non-classes: `InjectionToken`
----------------------------------------
Expand All @@ -81,12 +134,12 @@ class ProjectPatcher {
}
```

The description **is** the registry name, exactly as a contract's name is, so a
The description **is** the registry name, exactly as a named contract's is, so a
token is a typed alias onto an existing registration and nothing has to change
where the value is registered — `injector.register("xcode", xcode)` keeps
serving `inject(XCODE)`. A leading `$` in the description is stripped.

Names are minted in the same registry `@Contract` uses, so a token and a
Names are minted in the same registry `@LegacyContract` uses, so a token and a
contract cannot claim the same name: the second one **throws at load time**,
rather than silently aliasing one registration under two tokens.

Expand Down Expand Up @@ -193,7 +246,7 @@ instance. Transient instances are still retained by the container so

String keys are accepted anywhere a token is (`{ provide: "logger", useValue }`)
— that is how the legacy facade registers, and how per-call overrides address
not-yet-migrated dependencies. New registrations should mint a `@Contract`
not-yet-migrated dependencies. New registrations should declare a `@Contract`
class, or an `InjectionToken` when there is no class to decorate, instead of a
new string name.

Expand All @@ -217,13 +270,15 @@ Resolution semantics
injector level before delegating to the parent. Both keys index the same
provider record, so re-registering a service by its string name (as plugins
are documented to do with `$logger`) stays visible to `inject(Logger)`
consumers. This holds for `@Contract` classes and `InjectionToken`s alike.
consumers. This holds for `@LegacyContract` classes and `InjectionToken`s
alike; a `@Contract` class has no name and resolves by identity only.
- A leading `$` is stripped from string tokens: `get("$fs")` and `get("fs")`
are the same registration.
- The name fallback also makes **duplicated token copies interchangeable**: if
an extension's dependency tree carries its own copy of a contract class or
injection token, that copy resolves to the same provider by name. "Works
locally, breaks when installed" is not a failure mode of this design.
- The name fallback also makes **duplicated copies of a named token
interchangeable**: if an extension's dependency tree carries its own copy of a
`@LegacyContract` class or injection token, that copy resolves to the same
provider by name. "Works locally, breaks when installed" is not a failure mode
of the tokens `nativescript/contracts` exports.
- Cyclic dependencies fail with the full resolution path
(`Cyclic dependency detected on dependency 'a'. Resolution path: a -> b -> a`).

Expand Down Expand Up @@ -267,9 +322,9 @@ $injector.register(provide(DoctorService, DoctorServiceImpl));
runInInjectionContext($injector, () => inject(DoctorService));
```

- Legacy string names are permanent: a contract's token name is its interop
identity, used by hooks, plugins, and the public API. Nothing is deleted
per-service.
- Legacy string names stay while published plugins and hooks depend on them: a
named contract's name is its interop identity, used by hooks, plugins, and the
public API. Nothing is deleted per-service.
- Every legacy member (`resolve`, `register`, `require*`, the command-registry
surface) carries `@deprecated` JSDoc naming its replacement.
- Legacy usage at the external entry points (param-name hooks, require-time
Expand Down
4 changes: 2 additions & 2 deletions lib/common/contracts/commands-service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Contract } from "../di/contract";
import { LegacyContract } from "../di/contract";
import type { Injector } from "../di/injector";
import type { CommandReference } from "../define-command";

Expand All @@ -17,7 +17,7 @@ export interface CommandDispatchOptions {
* key shortcut or a plugin uses to run or consult another command. The command
* line's own entry points into the dispatcher are not part of it.
*/
@Contract({ name: "commandsService" })
@LegacyContract({ name: "commandsService" })
export abstract class CommandsService {
/**
* Whether the command running now was dispatched in process rather than by
Expand Down
4 changes: 2 additions & 2 deletions lib/common/contracts/key-shortcuts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Contract } from "../di/contract";
import { LegacyContract } from "../di/contract";
import type { Injector } from "../di/injector";

/**
Expand Down Expand Up @@ -53,7 +53,7 @@ export interface KeyShortcutRegistration {
* batch attach itself registered, so entries a lifecycle registered on its own
* survive until that lifecycle disposes them.
*/
@Contract({ name: "keyShortcutRegistry" })
@LegacyContract({ name: "keyShortcutRegistry" })
export abstract class KeyShortcutRegistry {
/** Later registrations shadow earlier ones per key; disposing restores what was shadowed. */
abstract add(...shortcuts: KeyShortcut[]): KeyShortcutRegistration;
Expand Down
2 changes: 1 addition & 1 deletion lib/common/contracts/module-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Contract } from "../di/contract";
* exists so its remaining consumers are typed against exactly what they use
* until the bootstrap migrates.
*/
@Contract({ name: "moduleRegistry" })
@Contract()
export abstract class ModuleRegistry {
abstract require(names: string | string[], file: string): void;
abstract overrideAlreadyRequiredModule: boolean;
Expand Down
2 changes: 1 addition & 1 deletion lib/common/contracts/public-api-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Contract } from "../di/contract";
* `require('nativescript')`. Bound by the compatibility constraints of the
* published library surface; do not add new entries through it.
*/
@Contract({ name: "publicApiBuilder" })
@Contract()
export abstract class PublicApiBuilder {
abstract requirePublic(names: string | string[], file: string): void;
abstract requirePublicClass(names: string | string[], file: string): void;
Expand Down
31 changes: 3 additions & 28 deletions lib/common/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { Errors } from "../contracts/errors";
import type { FileSystem } from "../contracts/file-system";
import type { HostInfo } from "../contracts/host-info";
import type { HttpClient } from "../contracts/http-client";
import type { OsInfo } from "../contracts/internal/os-info";

// tslint:disable-next-line:interface-name
interface Object {
Expand Down Expand Up @@ -1132,34 +1133,8 @@ interface IDependencyInformation {
saveInDependencies?: boolean;
}

/**
* Describes operating system-related utility methods
*/
interface IOsInfo {
/**
* Returns a string identifying the operating system name.
* @return {string} A string identifying the operating system name.
*/
type(): string;

/**
* Returns a string identifying the operating system release.
* @return {string} A string identifying the operating system release.
*/
release(): string;

/**
* Returns a string identifying the operating system bitness.
* @return {string} A string identifying the operating system bitness.
*/
arch(): string;

/**
* Returns a string identifying the operating system platform.
* @return {string} A string identifying the operating system platform.
*/
platform(): string;
}
/** @deprecated Kept so existing annotations compile; use the {@link OsInfo} contract. */
interface IOsInfo extends OsInfo {}

interface IPromiseActions<T> {
resolve(value?: T | PromiseLike<T>): void;
Expand Down
34 changes: 28 additions & 6 deletions lib/common/di/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
export const CONTRACT_NAME = Symbol.for("nativescript:di:contractName");

export interface IContractOptions {
export interface ILegacyContractOptions {
/**
* Canonical token name, without the `$` prefix. Must be an explicit string
* literal — never derive it from `class.name`, which changes under
Expand All @@ -16,6 +16,9 @@ export interface IContractOptions {
name: string;
}

/** @deprecated Use {@link ILegacyContractOptions}. */
export type IContractOptions = ILegacyContractOptions;

// Per module instance on purpose: a duplicated CLI copy in an extensions tree
// carries its own registry, so contracts redeclared by another copy never
// false-positive here.
Expand All @@ -29,7 +32,7 @@ function describeOwner(owner: object): string {
}

/**
* Claims a token name for `owner`. Both `@Contract` and `InjectionToken` mint
* Claims a token name for `owner`. Both `@LegacyContract` and `InjectionToken` mint
* here so the two kinds share one namespace: a contract and a token that claim
* the same name would be two tokens silently aliasing one registration.
*/
Expand All @@ -45,12 +48,31 @@ export function mintTokenName(name: string, owner: object): void {
}

/**
* Marks an abstract class as a DI token. The decorated class resolves by
* object identity first and by its name on a miss, so duplicated copies of a
* contract remain interchangeable across node_modules trees.
* Marks an abstract class as a DI token, resolved by object identity alone: it
* has no string spelling, and another copy of the class is a different token.
*/
export function Contract(): (target: Function) => void;
/** @deprecated Use {@link LegacyContract} for a contract that needs a name. */
export function Contract(
options: ILegacyContractOptions,
): (target: Function) => void;
export function Contract(
options: IContractOptions,
options?: ILegacyContractOptions,
): (target: Function) => void {
return options && options.name !== undefined
? LegacyContract(options)
: () => {};
}

/**
* A contract that also answers to a string name, for compatibility: with
* callers that resolve the service by string (hooks, `$`-prefixed parameters,
* string registrations), or with extensions whose own copy of the contract has
* to reach the running CLI's provider. Identity is tried first, the name on a
* miss.
*/
export function LegacyContract(
options: ILegacyContractOptions,
): (target: Function) => void {
const { name } = options;
return (target: Function): void => {
Expand Down
3 changes: 2 additions & 1 deletion lib/common/di/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ export { inject, getCurrentInjector, runInInjectionContext } from "./inject";
export { forwardRef, resolveForwardRef } from "./forward-ref";
export {
Contract,
LegacyContract,
getContractName,
CONTRACT_NAME,
clearMintedContractNames,
} from "./contract";
export type { IContractOptions } from "./contract";
export type { IContractOptions, ILegacyContractOptions } from "./contract";
export {
InjectionToken,
getInjectionTokenName,
Expand Down
7 changes: 4 additions & 3 deletions lib/common/os-info.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import * as os from "os";
import { IOsInfo } from "./declarations";
import { OsInfo } from "../contracts/internal/os-info";
import { provide } from "./di";
import { injector } from "./yok";

export class OsInfo implements IOsInfo {
export class OsInfoImpl implements OsInfo {
public type(): string {
return os.type();
}
Expand All @@ -20,4 +21,4 @@ export class OsInfo implements IOsInfo {
}
}

injector.register("osInfo", OsInfo);
injector.register(provide(OsInfo, OsInfoImpl));
8 changes: 5 additions & 3 deletions lib/common/services/net-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import {
IErrors,
INet,
IChildProcess,
IOsInfo,
IWaitForPortListenData,
IDictionary,
} from "../declarations";
import { OsInfo } from "../../contracts/internal/os-info";
import { inject } from "../di";
import { injector } from "../yok";

export class Net implements INet {
private static DEFAULT_INTERVAL = 1000;

private osInfo = inject(OsInfo);

constructor(
private $errors: IErrors,
private $childProcess: IChildProcess,
private $logger: ILogger,
private $osInfo: IOsInfo,
) {}

public async getFreePort(): Promise<number> {
Expand Down Expand Up @@ -118,7 +120,7 @@ export class Net implements INet {
},
};

const platform = this.$osInfo.platform();
const platform = this.osInfo.platform();
const currentPlatformData = platformData[platform];
if (!currentPlatformData) {
this.$errors.fail(
Expand Down
4 changes: 2 additions & 2 deletions lib/common/test/unit-tests/analytics-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Yok } from "../../yok";
import { AnalyticsService } from "../../../services/analytics/analytics-service";
import { setIsInteractive } from "../../helpers";
import { HostInfo } from "../../host-info";
import { OsInfo } from "../../os-info";
import { OsInfoImpl } from "../../os-info";
import { IInjector } from "../../definitions/yok";
import { IAnalyticsService } from "../../declarations";
import { assert } from "chai";
Expand Down Expand Up @@ -87,7 +87,7 @@ function createTestInjector(testScenario: ITestScenario): IInjector {
ANALYTICS_EXCEPTIONS_API_KEY: "AnalyticsExceptionsAPIKey",
});
testInjector.register("hostInfo", HostInfo);
testInjector.register("osInfo", OsInfo);
testInjector.register("osInfo", OsInfoImpl);
testInjector.register(
"userSettingsService",
new UserSettingsServiceStub(
Expand Down
Loading
Loading