From 661cf0421138bc3f76e3e83e484a1d0d6191d5b0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:13:49 -0300 Subject: [PATCH 1/4] feat(di): make the contract name optional, split out LegacyContract @Contract() declares a token resolved by the class alone. @LegacyContract ({ name }) is the form that also answers to a string name, for callers that resolve by string and for extensions carrying their own copy of a contract. @Contract({ name }) keeps working as a deprecated overload, since it was published. Every existing contract keeps its name and moves to @LegacyContract, with no change in behaviour. --- lib/common/contracts/command-registry.ts | 4 +- lib/common/contracts/commands-service.ts | 4 +- lib/common/contracts/key-shortcuts.ts | 4 +- lib/common/contracts/module-registry.ts | 4 +- lib/common/contracts/public-api-builder.ts | 4 +- lib/common/di/contract.ts | 34 +++++++++-- lib/common/di/index.ts | 3 +- lib/contracts/child-process.ts | 4 +- lib/contracts/devices-service.ts | 4 +- lib/contracts/doctor-service.ts | 4 +- lib/contracts/errors.ts | 4 +- lib/contracts/file-system.ts | 4 +- lib/contracts/host-info.ts | 4 +- lib/contracts/http-client.ts | 4 +- lib/contracts/index.ts | 9 ++- lib/contracts/logger.ts | 4 +- lib/contracts/package-manager.ts | 4 +- lib/contracts/project-data-service.ts | 4 +- lib/contracts/project-data.ts | 4 +- lib/contracts/project-name-service.ts | 4 +- lib/contracts/prompter.ts | 4 +- lib/contracts/temp-service.ts | 4 +- lib/contracts/vite-hmr-port-service.ts | 4 +- test/di.ts | 65 ++++++++++++++++++++-- 24 files changed, 139 insertions(+), 52 deletions(-) diff --git a/lib/common/contracts/command-registry.ts b/lib/common/contracts/command-registry.ts index 205d1248d0..b5edf2cc23 100644 --- a/lib/common/contracts/command-registry.ts +++ b/lib/common/contracts/command-registry.ts @@ -1,4 +1,4 @@ -import { Contract } from "../di/contract"; +import { LegacyContract } from "../di/contract"; import { InjectionToken } from "../di/injection-token"; import type { ICommand } from "../definitions/commands"; @@ -84,7 +84,7 @@ export type DeferredCommandResult = * facade later is a provider swap for this token, not a consumer migration. * Members slated for replacement keep their deprecation markers. */ -@Contract({ name: "commandRegistry" }) +@LegacyContract({ name: "commandRegistry" }) export abstract class CommandRegistry { /** * @deprecated Path-based command registration; use registerDeferredCommand, diff --git a/lib/common/contracts/commands-service.ts b/lib/common/contracts/commands-service.ts index 85449eebc1..a68baf90bc 100644 --- a/lib/common/contracts/commands-service.ts +++ b/lib/common/contracts/commands-service.ts @@ -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"; @@ -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 diff --git a/lib/common/contracts/key-shortcuts.ts b/lib/common/contracts/key-shortcuts.ts index d2aeae1dd6..4d1969b453 100644 --- a/lib/common/contracts/key-shortcuts.ts +++ b/lib/common/contracts/key-shortcuts.ts @@ -1,4 +1,4 @@ -import { Contract } from "../di/contract"; +import { LegacyContract } from "../di/contract"; import type { Injector } from "../di/injector"; /** @@ -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; diff --git a/lib/common/contracts/module-registry.ts b/lib/common/contracts/module-registry.ts index 2ebca751ab..660948a16c 100644 --- a/lib/common/contracts/module-registry.ts +++ b/lib/common/contracts/module-registry.ts @@ -1,4 +1,4 @@ -import { Contract } from "../di/contract"; +import { LegacyContract } from "../di/contract"; /** * @deprecated The lazy module-loader face of the injector facade — the @@ -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" }) +@LegacyContract({ name: "moduleRegistry" }) export abstract class ModuleRegistry { abstract require(names: string | string[], file: string): void; abstract overrideAlreadyRequiredModule: boolean; diff --git a/lib/common/contracts/public-api-builder.ts b/lib/common/contracts/public-api-builder.ts index 6ddb51cc53..fc8ff7fad3 100644 --- a/lib/common/contracts/public-api-builder.ts +++ b/lib/common/contracts/public-api-builder.ts @@ -1,11 +1,11 @@ -import { Contract } from "../di/contract"; +import { LegacyContract } from "../di/contract"; /** * The public-API-builder face of the injector facade: the machinery behind * `require('nativescript')`. Bound by the compatibility constraints of the * published library surface; do not add new entries through it. */ -@Contract({ name: "publicApiBuilder" }) +@LegacyContract({ name: "publicApiBuilder" }) export abstract class PublicApiBuilder { abstract requirePublic(names: string | string[], file: string): void; abstract requirePublicClass(names: string | string[], file: string): void; diff --git a/lib/common/di/contract.ts b/lib/common/di/contract.ts index cc03be9f02..27c10048d4 100644 --- a/lib/common/di/contract.ts +++ b/lib/common/di/contract.ts @@ -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 @@ -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. @@ -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. */ @@ -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 => { diff --git a/lib/common/di/index.ts b/lib/common/di/index.ts index f50e90a688..6f0927ceec 100644 --- a/lib/common/di/index.ts +++ b/lib/common/di/index.ts @@ -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, diff --git a/lib/contracts/child-process.ts b/lib/contracts/child-process.ts index 96b2a099bf..551dd5c315 100644 --- a/lib/contracts/child-process.ts +++ b/lib/contracts/child-process.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type * as child_process from "child_process"; import type { IExecOptions, @@ -9,7 +9,7 @@ import type { /** * Promise-based wrapper around Node's `child_process` module. */ -@Contract({ name: "childProcess" }) +@LegacyContract({ name: "childProcess" }) export abstract class ChildProcess { abstract exec( command: string, diff --git a/lib/contracts/devices-service.ts b/lib/contracts/devices-service.ts index 782ff5b4df..f9494b919a 100644 --- a/lib/contracts/devices-service.ts +++ b/lib/contracts/devices-service.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IAppInstalledInfo } from "../common/declarations"; /** @@ -12,7 +12,7 @@ export interface DevicesService extends NodeJS.EventEmitter {} /** * Discovers connected devices and emulators and executes actions against them. */ -@Contract({ name: "devicesService" }) +@LegacyContract({ name: "devicesService" }) export abstract class DevicesService { /** The platform the service has been initialized for. */ abstract platform: string; diff --git a/lib/contracts/doctor-service.ts b/lib/contracts/doctor-service.ts index 9a64fbd7a4..4c873a628c 100644 --- a/lib/contracts/doctor-service.ts +++ b/lib/contracts/doctor-service.ts @@ -1,11 +1,11 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { ISpawnResult } from "../common/declarations"; import type { IOptions } from "../declarations"; /** * Verifies the host OS configuration — the code behind `ns doctor`. */ -@Contract({ name: "doctorService" }) +@LegacyContract({ name: "doctorService" }) export abstract class DoctorService { /** * Verifies the host OS configuration and prints warnings to the users. diff --git a/lib/contracts/errors.ts b/lib/contracts/errors.ts index f2f4253bd1..dc4707d1ba 100644 --- a/lib/contracts/errors.ts +++ b/lib/contracts/errors.ts @@ -1,11 +1,11 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IFailOptions } from "../common/declarations"; /** * Raises CLI failures and wraps command execution so they are reported and * turned into a process exit code. */ -@Contract({ name: "errors" }) +@LegacyContract({ name: "errors" }) export abstract class Errors { abstract fail(formatStr: string, ...args: any[]): never; abstract fail(opts: IFailOptions, ...args: any[]): never; diff --git a/lib/contracts/file-system.ts b/lib/contracts/file-system.ts index 787f9b2383..5c525d7a54 100644 --- a/lib/contracts/file-system.ts +++ b/lib/contracts/file-system.ts @@ -1,11 +1,11 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IFsStats, IReadFileOptions } from "../common/declarations"; /** * Wraps the host file system — reads, writes, directory traversal and archive * handling used throughout the CLI. */ -@Contract({ name: "fs" }) +@LegacyContract({ name: "fs" }) export abstract class FileSystem { abstract zipFiles( zipFile: string, diff --git a/lib/contracts/host-info.ts b/lib/contracts/host-info.ts index b31bfa5477..725db9b073 100644 --- a/lib/contracts/host-info.ts +++ b/lib/contracts/host-info.ts @@ -1,9 +1,9 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; /** * Describes the host operating system the CLI runs on. */ -@Contract({ name: "hostInfo" }) +@LegacyContract({ name: "hostInfo" }) export abstract class HostInfo { abstract isWindows: boolean; abstract isWindows64: boolean; diff --git a/lib/contracts/http-client.ts b/lib/contracts/http-client.ts index 9176dcf7eb..73e746f1bd 100644 --- a/lib/contracts/http-client.ts +++ b/lib/contracts/http-client.ts @@ -1,10 +1,10 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IProxySettings, Server } from "../common/declarations"; /** * Performs HTTP requests, honouring the CLI's proxy settings. */ -@Contract({ name: "httpClient" }) +@LegacyContract({ name: "httpClient" }) export abstract class HttpClient { abstract httpRequest(url: string): Promise; abstract httpRequest( diff --git a/lib/contracts/index.ts b/lib/contracts/index.ts index 1c9bcf72f1..7eb5ff2af0 100644 --- a/lib/contracts/index.ts +++ b/lib/contracts/index.ts @@ -4,13 +4,20 @@ // This module must stay side-effect-free: an extension's duplicated CLI copy // may load it, and it must never boot a second runtime. In particular nothing // here may import lib/common/yok (whose import creates global.$injector). +// +// Contracts under ./internal are never exported from here: they carry no +// compatibility promise and change shape in any release. export { Contract, + LegacyContract, getContractName, CONTRACT_NAME, } from "../common/di/contract"; -export type { IContractOptions } from "../common/di/contract"; +export type { + IContractOptions, + ILegacyContractOptions, +} from "../common/di/contract"; export { InjectionToken, getInjectionTokenName, diff --git a/lib/contracts/logger.ts b/lib/contracts/logger.ts index db2bf4cc02..64904f5eda 100644 --- a/lib/contracts/logger.ts +++ b/lib/contracts/logger.ts @@ -1,9 +1,9 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; /** * Writes the CLI's output, filtered by the configured log level. */ -@Contract({ name: "logger" }) +@LegacyContract({ name: "logger" }) export abstract class Logger { abstract initialize(opts?: ILoggerOptions): void; diff --git a/lib/contracts/package-manager.ts b/lib/contracts/package-manager.ts index cae1a8eed2..7696b95a1c 100644 --- a/lib/contracts/package-manager.ts +++ b/lib/contracts/package-manager.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IDictionary } from "../common/declarations"; import type { INodePackageManagerInstallOptions, @@ -11,7 +11,7 @@ import type { * Dispatches package operations to the package manager selected for the current * process (npm, yarn, yarn2, pnpm or bun). */ -@Contract({ name: "packageManager" }) +@LegacyContract({ name: "packageManager" }) export abstract class PackageManager { /** * Installs dependency diff --git a/lib/contracts/project-data-service.ts b/lib/contracts/project-data-service.ts index cfdbe4964a..9147f5a5d0 100644 --- a/lib/contracts/project-data-service.ts +++ b/lib/contracts/project-data-service.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { SupportedPlatform } from "../constants"; import type { IProjectDir } from "../common/declarations"; import type { IBasePluginData } from "../definitions/plugins"; @@ -12,7 +12,7 @@ import type { * Reads and mutates the metadata of a NativeScript project - the `nativescript` * key in package.json, `nativescript.config` and the App_Resources assets. */ -@Contract({ name: "projectDataService" }) +@LegacyContract({ name: "projectDataService" }) export abstract class ProjectDataService { /** * Returns a value from `nativescript` key in project's package.json. diff --git a/lib/contracts/project-data.ts b/lib/contracts/project-data.ts index 976d8a0ec6..7063be95f3 100644 --- a/lib/contracts/project-data.ts +++ b/lib/contracts/project-data.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IStringDictionary } from "../common/declarations"; import type { BundlerType, INsConfig } from "../definitions/project"; @@ -6,7 +6,7 @@ import type { BundlerType, INsConfig } from "../definitions/project"; * Describes a NativeScript project — its layout on disk, its resolved * configuration and the dependencies declared in its package.json. */ -@Contract({ name: "projectData" }) +@LegacyContract({ name: "projectData" }) export abstract class ProjectData { /** Root directory of the project. */ abstract projectDir: string; diff --git a/lib/contracts/project-name-service.ts b/lib/contracts/project-name-service.ts index 84d4f9f9f9..765f8d21b1 100644 --- a/lib/contracts/project-name-service.ts +++ b/lib/contracts/project-name-service.ts @@ -1,6 +1,6 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; -@Contract({ name: "projectNameService" }) +@LegacyContract({ name: "projectNameService" }) export abstract class ProjectNameService { /** * Ensures the passed project name is valid; prompts for action otherwise. diff --git a/lib/contracts/prompter.ts b/lib/contracts/prompter.ts index 0687f4112c..8e6f304b22 100644 --- a/lib/contracts/prompter.ts +++ b/lib/contracts/prompter.ts @@ -1,4 +1,4 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { IAllowEmpty, IPrompterOptions, @@ -8,7 +8,7 @@ import type { /** * Asks the user questions on the terminal. */ -@Contract({ name: "prompter" }) +@LegacyContract({ name: "prompter" }) export abstract class Prompter { /** Closes the Ctrl+C reader the prompter installs on stdin. */ abstract dispose(): void; diff --git a/lib/contracts/temp-service.ts b/lib/contracts/temp-service.ts index 4b94c22a4e..796ed1a376 100644 --- a/lib/contracts/temp-service.ts +++ b/lib/contracts/temp-service.ts @@ -1,10 +1,10 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; import type { AffixOptions } from "../definitions/temp-service"; /** * Creates temporary files and directories that are cleaned up on exit. */ -@Contract({ name: "tempService" }) +@LegacyContract({ name: "tempService" }) export abstract class TempService { abstract mkdirSync(affixes: string | AffixOptions): Promise; diff --git a/lib/contracts/vite-hmr-port-service.ts b/lib/contracts/vite-hmr-port-service.ts index a23bbca69f..8cab600139 100644 --- a/lib/contracts/vite-hmr-port-service.ts +++ b/lib/contracts/vite-hmr-port-service.ts @@ -1,9 +1,9 @@ -import { Contract } from "../common/di/contract"; +import { LegacyContract } from "../common/di/contract"; /** * Chooses the local port the Vite HMR dev server binds for a platform. */ -@Contract({ name: "viteHmrPortService" }) +@LegacyContract({ name: "viteHmrPortService" }) export abstract class ViteHmrPortService { /** * Resolves the port the Vite dev server for `platform` listens on: the diff --git a/test/di.ts b/test/di.ts index 4222b3041b..defb359a51 100644 --- a/test/di.ts +++ b/test/di.ts @@ -4,12 +4,14 @@ import { inject, runInInjectionContext, Contract, + LegacyContract, + getContractName, InjectionToken, provide, forwardRef, } from "../lib/common/di"; -@Contract({ name: "diTestGreeter" }) +@LegacyContract({ name: "diTestGreeter" }) abstract class Greeter { abstract greet(): string; } @@ -20,7 +22,7 @@ class GreeterImpl extends Greeter { } } -@Contract({ name: "diTestDevice" }) +@LegacyContract({ name: "diTestDevice" }) abstract class Device { abstract id: string; } @@ -41,9 +43,64 @@ describe("di: tokens and resolution", () => { assert.throws(() => injector.get(GreeterImpl), /unable to resolve/); }); + describe("contracts without a name", () => { + it("resolve by the class only", () => { + @Contract() + abstract class Unnamed {} + class UnnamedImpl extends Unnamed {} + const injector = new Injector([provide(Unnamed, UnnamedImpl)]); + + assert.instanceOf(injector.get(Unnamed), UnnamedImpl); + assert.isUndefined(getContractName(Unnamed)); + assert.isFalse(injector.has("Unnamed")); + }); + + it("stay distinct when two classes share a class name", () => { + const declare = () => { + @Contract() + abstract class SameName {} + return SameName; + }; + const first = declare(); + const second = declare(); + const injector = new Injector([ + { provide: first, useValue: "first" }, + { provide: second, useValue: "second" }, + ]); + + assert.strictEqual(injector.get(first), "first"); + assert.strictEqual(injector.get(second), "second"); + }); + + it("name the class when unresolvable", () => { + @Contract() + abstract class Unregistered {} + + assert.throws( + () => new Injector().get(Unregistered), + "unable to resolve Unregistered", + ); + }); + }); + + it("still names a contract declared with the deprecated Contract({ name })", () => { + @Contract({ name: "diTestDeprecatedForm" }) + abstract class DeprecatedForm {} + class DeprecatedFormImpl extends DeprecatedForm {} + const injector = new Injector([ + provide(DeprecatedForm, DeprecatedFormImpl), + ]); + + assert.equal(getContractName(DeprecatedForm), "diTestDeprecatedForm"); + assert.strictEqual( + injector.get("diTestDeprecatedForm"), + injector.get(DeprecatedForm), + ); + }); + it("throws on a duplicate contract name at declaration time", () => { assert.throws(() => { - @Contract({ name: "diTestGreeter" }) + @LegacyContract({ name: "diTestGreeter" }) abstract class Duplicate {} void Duplicate; }, /already used/); @@ -183,7 +240,7 @@ describe("di: InjectionToken", () => { it("throws when a contract name collides with a token description", () => { assert.throws(() => { - @Contract({ name: "diTestModuleToken" }) + @LegacyContract({ name: "diTestModuleToken" }) abstract class Collides {} void Collides; }, /already used by an injection token/); From aa7430733b5753a7087ddbf59959e96462b7f933 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:13:49 -0300 Subject: [PATCH 2/4] feat(di): internal contracts, with osInfo as the first Contracts for the CLI's own plumbing live in lib/contracts/internal and are never exported from nativescript/contracts, so they carry no compatibility promise. A test fails when one is exported. osInfo is the worked example: the interface becomes an alias, the implementation is renamed, and two consumers move to inject(). --- dependency-injection.md | 87 +++++++++++++++---- lib/common/declarations.d.ts | 31 +------ lib/common/os-info.ts | 7 +- lib/common/services/net-service.ts | 8 +- .../test/unit-tests/analytics-service.ts | 4 +- lib/contracts/internal/os-info.ts | 19 ++++ lib/services/analytics-settings-service.ts | 12 +-- test/contracts.ts | 33 +++++++ 8 files changed, 144 insertions(+), 57 deletions(-) create mode 100644 lib/contracts/internal/os-info.ts diff --git a/dependency-injection.md b/dependency-injection.md index 56164068cd..4a815fa52d 100644 --- a/dependency-injection.md +++ b/dependency-injection.md @@ -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; +} +``` + +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; @@ -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`, @@ -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` ---------------------------------------- @@ -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. @@ -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. @@ -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`). @@ -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 diff --git a/lib/common/declarations.d.ts b/lib/common/declarations.d.ts index df4a19a1fb..9b2b0d45a5 100644 --- a/lib/common/declarations.d.ts +++ b/lib/common/declarations.d.ts @@ -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 { @@ -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 { resolve(value?: T | PromiseLike): void; diff --git a/lib/common/os-info.ts b/lib/common/os-info.ts index 94c94cbff1..209a95c009 100644 --- a/lib/common/os-info.ts +++ b/lib/common/os-info.ts @@ -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(); } @@ -20,4 +21,4 @@ export class OsInfo implements IOsInfo { } } -injector.register("osInfo", OsInfo); +injector.register(provide(OsInfo, OsInfoImpl)); diff --git a/lib/common/services/net-service.ts b/lib/common/services/net-service.ts index 2c08ee218c..8d6969ea04 100644 --- a/lib/common/services/net-service.ts +++ b/lib/common/services/net-service.ts @@ -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 { @@ -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( diff --git a/lib/common/test/unit-tests/analytics-service.ts b/lib/common/test/unit-tests/analytics-service.ts index 3dd3d5dfb9..6cdb59e8ca 100644 --- a/lib/common/test/unit-tests/analytics-service.ts +++ b/lib/common/test/unit-tests/analytics-service.ts @@ -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"; @@ -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( diff --git a/lib/contracts/internal/os-info.ts b/lib/contracts/internal/os-info.ts new file mode 100644 index 0000000000..336f0d3f36 --- /dev/null +++ b/lib/contracts/internal/os-info.ts @@ -0,0 +1,19 @@ +import { LegacyContract } from "../../common/di/contract"; + +/** + * Describes operating system-related utility methods. + */ +@LegacyContract({ name: "osInfo" }) +export abstract class OsInfo { + /** The operating system name. */ + abstract type(): string; + + /** The operating system release. */ + abstract release(): string; + + /** The operating system bitness. */ + abstract arch(): string; + + /** The operating system platform. */ + abstract platform(): string; +} diff --git a/lib/services/analytics-settings-service.ts b/lib/services/analytics-settings-service.ts index 1c44a8ffdf..ef53d7b63d 100644 --- a/lib/services/analytics-settings-service.ts +++ b/lib/services/analytics-settings-service.ts @@ -5,20 +5,22 @@ import { IAnalyticsSettingsService, IUserSettingsService, IHostInfo, - IOsInfo, } from "../common/declarations"; import * as _ from "lodash"; +import { inject } from "../common/di"; import { injector } from "../common/yok"; +import { OsInfo } from "../contracts/internal/os-info"; import { color } from "../color"; class AnalyticsSettingsService implements IAnalyticsSettingsService { private static SESSIONS_STARTED_KEY_PREFIX = "SESSIONS_STARTED_"; + private osInfo = inject(OsInfo); + constructor( private $userSettingsService: IUserSettingsService, private $staticConfig: IStaticConfig, private $hostInfo: IHostInfo, - private $osInfo: IOsInfo, private $logger: ILogger, ) {} @@ -65,7 +67,7 @@ class AnalyticsSettingsService implements IAnalyticsSettingsService { @exported("analyticsSettingsService") public getUserAgentString(identifier: string): string { let osString = ""; - const osRelease = this.$osInfo.release(); + const osRelease = this.osInfo.release(); if (this.$hostInfo.isWindows) { osString = `Windows NT ${osRelease}`; @@ -77,12 +79,12 @@ class AnalyticsSettingsService implements IAnalyticsSettingsService { } } else { osString = `Linux x86`; - if (this.$osInfo.arch() === "x64") { + if (this.osInfo.arch() === "x64") { osString += "_64"; } } - const userAgent = `${identifier} (${osString}; ${this.$osInfo.arch()})`; + const userAgent = `${identifier} (${osString}; ${this.osInfo.arch()})`; return userAgent; } diff --git a/test/contracts.ts b/test/contracts.ts index e07581e01e..ddd9cfbaf4 100644 --- a/test/contracts.ts +++ b/test/contracts.ts @@ -1,4 +1,6 @@ import { assert } from "chai"; +import * as fs from "fs"; +import * as path from "path"; import { getContractName, Injector, provide } from "../lib/common/di"; import type { InjectionToken, ProviderToken } from "../lib/common/di"; import { @@ -20,10 +22,13 @@ import { PBXPROJ_DOM_XCODE, XCODE, } from "../lib/contracts"; +import * as publicContracts from "../lib/contracts"; +import { OsInfo } from "../lib/contracts/internal/os-info"; import { Yok } from "../lib/common/yok"; import { Logger as LoggerImpl } from "../lib/common/logger/logger"; import { Errors as ErrorsImpl } from "../lib/common/errors"; import { FileSystem as FileSystemImpl } from "../lib/common/file-system"; +import { injector as globalInjector } from "../lib/common/yok"; import type { ISpawnResult } from "../lib/common/declarations"; const tranche: [ProviderToken, string][] = [ @@ -115,6 +120,34 @@ describe("contracts tranche", () => { } }); + describe("internal contracts", () => { + it("are not exported from the public entry point", () => { + const internalDir = path.join(__dirname, "../lib/contracts/internal"); + const modules = fs + .readdirSync(internalDir) + .filter((file) => file.endsWith(".js")); + const internal = modules.flatMap((file) => + Object.values(require(path.join(internalDir, file))), + ); + assert.isNotEmpty(internal); + + const published = new Set(Object.values(publicContracts)); + assert.deepEqual( + internal.filter((value) => published.has(value)), + [], + ); + }); + + it("resolve to one instance by class, by name and by $-spelling", () => { + const { OsInfoImpl } = require("../lib/common/os-info"); + const byToken = globalInjector.get(OsInfo); + + assert.instanceOf(byToken, OsInfoImpl); + assert.strictEqual(globalInjector.resolve("osInfo"), byToken); + assert.strictEqual(globalInjector.resolve("$osInfo"), byToken); + }); + }); + describe("against a real Yok container", () => { it("resolves the token and the legacy name to the same instance", () => { const injector = new Yok(); From 132fe87baee3e411000b6f316cd32ed63ad4590d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 12:48:36 -0300 Subject: [PATCH 3/4] refactor(di): drop the names of the injector facade contracts CommandRegistry, ModuleRegistry and PublicApiBuilder were never registered under a string, are not exported from nativescript/contracts, and are resolved by class everywhere. --- lib/common/contracts/command-registry.ts | 4 ++-- lib/common/contracts/module-registry.ts | 4 ++-- lib/common/contracts/public-api-builder.ts | 4 ++-- test/compat/injector-facade-surface.ts | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/common/contracts/command-registry.ts b/lib/common/contracts/command-registry.ts index b5edf2cc23..73440e4421 100644 --- a/lib/common/contracts/command-registry.ts +++ b/lib/common/contracts/command-registry.ts @@ -1,4 +1,4 @@ -import { LegacyContract } from "../di/contract"; +import { Contract } from "../di/contract"; import { InjectionToken } from "../di/injection-token"; import type { ICommand } from "../definitions/commands"; @@ -84,7 +84,7 @@ export type DeferredCommandResult = * facade later is a provider swap for this token, not a consumer migration. * Members slated for replacement keep their deprecation markers. */ -@LegacyContract({ name: "commandRegistry" }) +@Contract() export abstract class CommandRegistry { /** * @deprecated Path-based command registration; use registerDeferredCommand, diff --git a/lib/common/contracts/module-registry.ts b/lib/common/contracts/module-registry.ts index 660948a16c..abf3538bc2 100644 --- a/lib/common/contracts/module-registry.ts +++ b/lib/common/contracts/module-registry.ts @@ -1,4 +1,4 @@ -import { LegacyContract } from "../di/contract"; +import { Contract } from "../di/contract"; /** * @deprecated The lazy module-loader face of the injector facade — the @@ -6,7 +6,7 @@ import { LegacyContract } from "../di/contract"; * exists so its remaining consumers are typed against exactly what they use * until the bootstrap migrates. */ -@LegacyContract({ name: "moduleRegistry" }) +@Contract() export abstract class ModuleRegistry { abstract require(names: string | string[], file: string): void; abstract overrideAlreadyRequiredModule: boolean; diff --git a/lib/common/contracts/public-api-builder.ts b/lib/common/contracts/public-api-builder.ts index fc8ff7fad3..41fbb9cc4c 100644 --- a/lib/common/contracts/public-api-builder.ts +++ b/lib/common/contracts/public-api-builder.ts @@ -1,11 +1,11 @@ -import { LegacyContract } from "../di/contract"; +import { Contract } from "../di/contract"; /** * The public-API-builder face of the injector facade: the machinery behind * `require('nativescript')`. Bound by the compatibility constraints of the * published library surface; do not add new entries through it. */ -@LegacyContract({ name: "publicApiBuilder" }) +@Contract() export abstract class PublicApiBuilder { abstract requirePublic(names: string | string[], file: string): void; abstract requirePublicClass(names: string | string[], file: string): void; diff --git a/test/compat/injector-facade-surface.ts b/test/compat/injector-facade-surface.ts index 130ea2150e..c60d22b109 100644 --- a/test/compat/injector-facade-surface.ts +++ b/test/compat/injector-facade-surface.ts @@ -104,7 +104,7 @@ describe("injector facade surface", () => { for (const token of [CommandRegistry, ModuleRegistry, PublicApiBuilder]) { assert.strictEqual(inj.get(token), inj); } - assert.strictEqual(inj.resolve("commandRegistry"), inj); + assert.isFalse(inj.has("commandRegistry")); runInInjectionContext(inj, () => { assert.strictEqual(inject(CommandRegistry), inj); From e2a7a0395fd5a4aa539b25a9bd903500dcc8bc16 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 13:39:09 -0300 Subject: [PATCH 4/4] fix(di): keep the commandRegistry name Hooks can take $commandRegistry since 9.1.0, and one that does would be skipped without the name. --- lib/common/contracts/command-registry.ts | 2 +- test/compat/injector-facade-surface.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/contracts/command-registry.ts b/lib/common/contracts/command-registry.ts index 73440e4421..205d1248d0 100644 --- a/lib/common/contracts/command-registry.ts +++ b/lib/common/contracts/command-registry.ts @@ -84,7 +84,7 @@ export type DeferredCommandResult = * facade later is a provider swap for this token, not a consumer migration. * Members slated for replacement keep their deprecation markers. */ -@Contract() +@Contract({ name: "commandRegistry" }) export abstract class CommandRegistry { /** * @deprecated Path-based command registration; use registerDeferredCommand, diff --git a/test/compat/injector-facade-surface.ts b/test/compat/injector-facade-surface.ts index c60d22b109..130ea2150e 100644 --- a/test/compat/injector-facade-surface.ts +++ b/test/compat/injector-facade-surface.ts @@ -104,7 +104,7 @@ describe("injector facade surface", () => { for (const token of [CommandRegistry, ModuleRegistry, PublicApiBuilder]) { assert.strictEqual(inj.get(token), inj); } - assert.isFalse(inj.has("commandRegistry")); + assert.strictEqual(inj.resolve("commandRegistry"), inj); runInInjectionContext(inj, () => { assert.strictEqual(inject(CommandRegistry), inj);