Skip to content

Commit 341e227

Browse files
authored
feat(di): contracts without a name and internal contracts (#6220)
@contract() declares a token resolved by the class alone. @LegacyContract({ name }) also answers to a string name, for code that resolves by string and for extensions carrying their own copy of a contract. @contract({ name }) is published and stays as a deprecated overload. Existing contracts keep their names, except ModuleRegistry and PublicApiBuilder, which were only ever resolved by class. Contracts for the CLI's own plumbing live in lib/contracts/internal and are never exported from nativescript/contracts. osInfo is the worked example.
1 parent acc32e1 commit 341e227

31 files changed

Lines changed: 279 additions & 105 deletions

‎dependency-injection.md‎

Lines changed: 71 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,31 @@ Tokens: `@Contract`
3737
-------------------
3838

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

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

46-
@Contract({ name: "doctorService" }) // canonical form, no `$`
45+
@Contract()
46+
export abstract class ReportWriter {
47+
abstract write(report: string): Promise<void>;
48+
}
49+
```
50+
51+
Such a token resolves by the class and nothing else: it has no string spelling,
52+
and a duplicated copy of the class is a different token.
53+
54+
Implementations do not become tokens by extending or implementing a contract;
55+
only the decorated class itself is a token.
56+
57+
### Named contracts: `@LegacyContract`
58+
59+
`@LegacyContract` adds a canonical string name, which the token also answers to:
60+
61+
```ts
62+
import { LegacyContract } from "nativescript/contracts";
63+
64+
@LegacyContract({ name: "doctorService" }) // canonical form, no `$`
4765
export abstract class DoctorService {
4866
abstract canExecuteLocalBuild(configuration?: {
4967
platform?: string;
@@ -52,6 +70,15 @@ export abstract class DoctorService {
5270
}
5371
```
5472

73+
A name exists for compatibility. Use one only when the service has to stay
74+
reachable by callers that cannot hold the class:
75+
76+
- code that resolves it by string — hook parameters, `$`-prefixed constructor
77+
parameters, `resolve("name")`, string registrations;
78+
- an extension whose dependency tree carries its own copy of the contract. This
79+
is why the contracts exported from `nativescript/contracts` are named, the
80+
recent ones included: without a name, such a copy cannot be resolved.
81+
5582
Rules:
5683

5784
- **The name is an explicit string literal** — never derived from `class.name`,
@@ -60,8 +87,34 @@ Rules:
6087
same name **throws at load time**, because a duplicate would silently alias
6188
two tokens.
6289
- The options object leaves room for future fields without changing call sites.
63-
- Implementations do not become tokens by extending or implementing a contract;
64-
only the decorated class itself is a token.
90+
91+
`@Contract({ name })` is the deprecated spelling of `@LegacyContract({ name })`
92+
and behaves identically.
93+
94+
### Internal contracts
95+
96+
Only what `nativescript/contracts` exports is a supported API. Contracts for the
97+
CLI's own plumbing live in `lib/contracts/internal` and are never exported from
98+
it: they may change or disappear in any release, even where a name keeps them
99+
resolvable by string or a deep `require()` reaches the file. A public contract's
100+
signature must not mention an internal one.
101+
102+
To move an existing service onto an internal contract:
103+
104+
1. Declare the contract in `lib/contracts/internal`, as a `@LegacyContract`
105+
under the name the service is registered with.
106+
2. Turn the ambient interface into an alias of it
107+
(`interface IOsInfo extends OsInfo {}`).
108+
3. Rename the implementation to `*Impl` and register it with
109+
`injector.register(provide(OsInfo, OsInfoImpl))` — or by its name, while it
110+
still takes `$`-prefixed constructor parameters. The `injector.require()`
111+
entry in the bootstrap stays as it is.
112+
4. Move consumers from `$osInfo` parameters to `inject(OsInfo)` fields, in as
113+
many steps as convenient: both reach the same instance.
114+
115+
`lib/contracts/internal/os-info.ts` is the worked example. A service that never
116+
had a string name takes a plain `@Contract()` and a `provideLazy()` registration
117+
instead.
65118

66119
Tokens for non-classes: `InjectionToken`
67120
----------------------------------------
@@ -81,12 +134,12 @@ class ProjectPatcher {
81134
}
82135
```
83136

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

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

@@ -213,7 +266,7 @@ instance. Transient instances are still retained by the container so
213266

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

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

@@ -287,9 +342,9 @@ $injector.register(provide(DoctorService, DoctorServiceImpl));
287342
runInInjectionContext($injector, () => inject(DoctorService));
288343
```
289344

290-
- Legacy string names are permanent: a contract's token name is its interop
291-
identity, used by hooks, plugins, and the public API. Nothing is deleted
292-
per-service.
345+
- Legacy string names stay while published plugins and hooks depend on them: a
346+
named contract's name is its interop identity, used by hooks, plugins, and the
347+
public API. Nothing is deleted per-service.
293348
- Every legacy member (`resolve`, `register`, `require*`, the command-registry
294349
surface) carries `@deprecated` JSDoc naming its replacement.
295350
- Legacy usage at the external entry points (param-name hooks, require-time

‎lib/common/contracts/commands-service.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Contract } from "../di/contract";
1+
import { LegacyContract } from "../di/contract";
22
import type { Injector } from "../di/injector";
33
import type { CommandReference } from "../define-command";
44

@@ -17,7 +17,7 @@ export interface CommandDispatchOptions {
1717
* key shortcut or a plugin uses to run or consult another command. The command
1818
* line's own entry points into the dispatcher are not part of it.
1919
*/
20-
@Contract({ name: "commandsService" })
20+
@LegacyContract({ name: "commandsService" })
2121
export abstract class CommandsService {
2222
/**
2323
* Whether the command running now was dispatched in process rather than by

‎lib/common/contracts/key-shortcuts.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Contract } from "../di/contract";
1+
import { LegacyContract } from "../di/contract";
22
import type { Injector } from "../di/injector";
33

44
/**
@@ -53,7 +53,7 @@ export interface KeyShortcutRegistration {
5353
* batch attach itself registered, so entries a lifecycle registered on its own
5454
* survive until that lifecycle disposes them.
5555
*/
56-
@Contract({ name: "keyShortcutRegistry" })
56+
@LegacyContract({ name: "keyShortcutRegistry" })
5757
export abstract class KeyShortcutRegistry {
5858
/** Later registrations shadow earlier ones per key; disposing restores what was shadowed. */
5959
abstract add(...shortcuts: KeyShortcut[]): KeyShortcutRegistration;

‎lib/common/contracts/module-registry.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Contract } from "../di/contract";
66
* exists so its remaining consumers are typed against exactly what they use
77
* until the bootstrap migrates.
88
*/
9-
@Contract({ name: "moduleRegistry" })
9+
@Contract()
1010
export abstract class ModuleRegistry {
1111
abstract require(names: string | string[], file: string): void;
1212
abstract overrideAlreadyRequiredModule: boolean;

‎lib/common/contracts/public-api-builder.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Contract } from "../di/contract";
55
* `require('nativescript')`. Bound by the compatibility constraints of the
66
* published library surface; do not add new entries through it.
77
*/
8-
@Contract({ name: "publicApiBuilder" })
8+
@Contract()
99
export abstract class PublicApiBuilder {
1010
abstract requirePublic(names: string | string[], file: string): void;
1111
abstract requirePublicClass(names: string | string[], file: string): void;

‎lib/common/declarations.d.ts‎

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { Errors } from "../contracts/errors";
1010
import type { FileSystem } from "../contracts/file-system";
1111
import type { HostInfo } from "../contracts/host-info";
1212
import type { HttpClient } from "../contracts/http-client";
13+
import type { OsInfo } from "../contracts/internal/os-info";
1314

1415
// tslint:disable-next-line:interface-name
1516
interface Object {
@@ -1132,34 +1133,8 @@ interface IDependencyInformation {
11321133
saveInDependencies?: boolean;
11331134
}
11341135

1135-
/**
1136-
* Describes operating system-related utility methods
1137-
*/
1138-
interface IOsInfo {
1139-
/**
1140-
* Returns a string identifying the operating system name.
1141-
* @return {string} A string identifying the operating system name.
1142-
*/
1143-
type(): string;
1144-
1145-
/**
1146-
* Returns a string identifying the operating system release.
1147-
* @return {string} A string identifying the operating system release.
1148-
*/
1149-
release(): string;
1150-
1151-
/**
1152-
* Returns a string identifying the operating system bitness.
1153-
* @return {string} A string identifying the operating system bitness.
1154-
*/
1155-
arch(): string;
1156-
1157-
/**
1158-
* Returns a string identifying the operating system platform.
1159-
* @return {string} A string identifying the operating system platform.
1160-
*/
1161-
platform(): string;
1162-
}
1136+
/** @deprecated Kept so existing annotations compile; use the {@link OsInfo} contract. */
1137+
interface IOsInfo extends OsInfo {}
11631138

11641139
interface IPromiseActions<T> {
11651140
resolve(value?: T | PromiseLike<T>): void;

‎lib/common/di/contract.ts‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88
export const CONTRACT_NAME = Symbol.for("nativescript:di:contractName");
99

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

19+
/** @deprecated Use {@link ILegacyContractOptions}. */
20+
export type IContractOptions = ILegacyContractOptions;
21+
1922
// Per module instance on purpose: a duplicated CLI copy in an extensions tree
2023
// carries its own registry, so contracts redeclared by another copy never
2124
// false-positive here.
@@ -29,7 +32,7 @@ function describeOwner(owner: object): string {
2932
}
3033

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

4750
/**
48-
* Marks an abstract class as a DI token. The decorated class resolves by
49-
* object identity first and by its name on a miss, so duplicated copies of a
50-
* contract remain interchangeable across node_modules trees.
51+
* Marks an abstract class as a DI token, resolved by object identity alone: it
52+
* has no string spelling, and another copy of the class is a different token.
5153
*/
54+
export function Contract(): (target: Function) => void;
55+
/** @deprecated Use {@link LegacyContract} for a contract that needs a name. */
56+
export function Contract(
57+
options: ILegacyContractOptions,
58+
): (target: Function) => void;
5259
export function Contract(
53-
options: IContractOptions,
60+
options?: ILegacyContractOptions,
61+
): (target: Function) => void {
62+
return options && options.name !== undefined
63+
? LegacyContract(options)
64+
: () => {};
65+
}
66+
67+
/**
68+
* A contract that also answers to a string name, for compatibility: with
69+
* callers that resolve the service by string (hooks, `$`-prefixed parameters,
70+
* string registrations), or with extensions whose own copy of the contract has
71+
* to reach the running CLI's provider. Identity is tried first, the name on a
72+
* miss.
73+
*/
74+
export function LegacyContract(
75+
options: ILegacyContractOptions,
5476
): (target: Function) => void {
5577
const { name } = options;
5678
return (target: Function): void => {

‎lib/common/di/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ export { inject, getCurrentInjector, runInInjectionContext } from "./inject";
44
export { forwardRef, resolveForwardRef } from "./forward-ref";
55
export {
66
Contract,
7+
LegacyContract,
78
getContractName,
89
CONTRACT_NAME,
910
clearMintedContractNames,
1011
} from "./contract";
11-
export type { IContractOptions } from "./contract";
12+
export type { IContractOptions, ILegacyContractOptions } from "./contract";
1213
export {
1314
InjectionToken,
1415
getInjectionTokenName,

‎lib/common/os-info.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import * as os from "os";
2-
import { IOsInfo } from "./declarations";
2+
import { OsInfo } from "../contracts/internal/os-info";
3+
import { provide } from "./di";
34
import { injector } from "./yok";
45

5-
export class OsInfo implements IOsInfo {
6+
export class OsInfoImpl implements OsInfo {
67
public type(): string {
78
return os.type();
89
}
@@ -20,4 +21,4 @@ export class OsInfo implements IOsInfo {
2021
}
2122
}
2223

23-
injector.register("osInfo", OsInfo);
24+
injector.register(provide(OsInfo, OsInfoImpl));

‎lib/common/services/net-service.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,22 @@ import {
55
IErrors,
66
INet,
77
IChildProcess,
8-
IOsInfo,
98
IWaitForPortListenData,
109
IDictionary,
1110
} from "../declarations";
11+
import { OsInfo } from "../../contracts/internal/os-info";
12+
import { inject } from "../di";
1213
import { injector } from "../yok";
1314

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

18+
private osInfo = inject(OsInfo);
19+
1720
constructor(
1821
private $errors: IErrors,
1922
private $childProcess: IChildProcess,
2023
private $logger: ILogger,
21-
private $osInfo: IOsInfo,
2224
) {}
2325

2426
public async getFreePort(): Promise<number> {
@@ -118,7 +120,7 @@ export class Net implements INet {
118120
},
119121
};
120122

121-
const platform = this.$osInfo.platform();
123+
const platform = this.osInfo.platform();
122124
const currentPlatformData = platformData[platform];
123125
if (!currentPlatformData) {
124126
this.$errors.fail(

0 commit comments

Comments
 (0)