From 84e5aebbb61268d0fb604888c921ca3ac709d8a7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:21:06 -0300 Subject: [PATCH 1/4] feat(di): injection tokens with a factory, and without a name A token may carry a factory that the root injector runs the first time the token is resolved and nothing provides it, so it needs no registration. The description becomes optional; a token without one resolves by identity. --- dependency-injection.md | 20 ++++++++ lib/common/di/index.ts | 3 ++ lib/common/di/injection-token.ts | 64 +++++++++++++++++++++++-- lib/common/di/injector.ts | 40 ++++++++++++++-- test/di.ts | 80 ++++++++++++++++++++++++++++++++ 5 files changed, 201 insertions(+), 6 deletions(-) diff --git a/dependency-injection.md b/dependency-injection.md index 56164068cd..cb18abe391 100644 --- a/dependency-injection.md +++ b/dependency-injection.md @@ -102,6 +102,26 @@ Prefer a `@Contract` class when the dependency is a service: it also carries the service's shape. Reach for `InjectionToken` only when there is nothing to decorate. +### Tokens that provide themselves + +A token may carry a `factory`, and then needs no registration: + +```ts +export const CLOCK = new InjectionToken({ + factory: () => new SystemClock(inject(TimeZone)), +}); +``` + +The factory runs the first time the token is resolved and nothing provides it. +It runs once, in the root injector's injection context, and the root keeps the +value: every injector of the tree shares it, whichever asked first. A provider +registered for the token, at the root or in a child, is used instead, which is +how a test replaces it. + +The description is optional. A token without one has no string spelling and +resolves by identity only, and a duplicated copy of it is a different token. +`new InjectionToken("name", { factory })` has both. + Resolving: `inject()` and `Injector` ------------------------------------ diff --git a/lib/common/di/index.ts b/lib/common/di/index.ts index f50e90a688..b667c2ce9f 100644 --- a/lib/common/di/index.ts +++ b/lib/common/di/index.ts @@ -13,7 +13,10 @@ export { InjectionToken, getInjectionTokenName, INJECTION_TOKEN_NAME, + getInjectionTokenFactory, + INJECTION_TOKEN_FACTORY, } from "./injection-token"; +export type { InjectionTokenOptions } from "./injection-token"; export { provide, provideLazy } from "./providers"; export type { Provider, diff --git a/lib/common/di/injection-token.ts b/lib/common/di/injection-token.ts index fa812d7564..aa37ff3308 100644 --- a/lib/common/di/injection-token.ts +++ b/lib/common/di/injection-token.ts @@ -9,6 +9,20 @@ export const INJECTION_TOKEN_NAME = Symbol.for( "nativescript:di:injectionTokenName", ); +/** Same `Symbol.for` reasoning as INJECTION_TOKEN_NAME. */ +export const INJECTION_TOKEN_FACTORY = Symbol.for( + "nativescript:di:injectionTokenFactory", +); + +export interface InjectionTokenOptions { + /** + * Builds the value when the token is resolved and nothing provides it. Runs + * once, in the root injector's injection context, and the root keeps the + * result. A provider registered for the token is used instead. + */ + factory?: () => T; +} + /** * A typed DI token for a dependency that is not a class — an imported module * namespace, a plain value, a function. `@Contract` covers services, which @@ -23,6 +37,13 @@ export const INJECTION_TOKEN_NAME = Symbol.for( * ); * inject(XCODE); // finds register("xcode", …) untouched * ``` + * + * Without a description the token is resolved by identity alone. With a + * `factory` it needs no registration: + * + * ```ts + * const CLOCK = new InjectionToken({ factory: () => new Clock() }); + * ``` */ export class InjectionToken { /** @@ -31,11 +52,33 @@ export class InjectionToken { */ declare private readonly resolvedType: T; + constructor(options?: InjectionTokenOptions); /** * @param description Canonical registry name. A leading `$` is stripped, so * the token always keys the same record the string spellings do. */ - constructor(description: string) { + constructor(description: string, options?: InjectionTokenOptions); + constructor( + descriptionOrOptions?: string | InjectionTokenOptions, + namedOptions?: InjectionTokenOptions, + ) { + const named = typeof descriptionOrOptions === "string"; + const options = named + ? namedOptions + : >descriptionOrOptions; + if (options && options.factory) { + Object.defineProperty(this, INJECTION_TOKEN_FACTORY, { + value: options.factory, + writable: false, + enumerable: false, + configurable: false, + }); + } + if (!named) { + return; + } + + const description = descriptionOrOptions; const name = description[0] === "$" ? description.slice(1) : description; mintTokenName(name, this); Object.defineProperty(this, INJECTION_TOKEN_NAME, { @@ -46,12 +89,15 @@ export class InjectionToken { }); } - public get description(): string { + /** The registry name, or undefined for a token without one. */ + public get description(): string | undefined { return (this)[INJECTION_TOKEN_NAME]; } public toString(): string { - return `InjectionToken(${this.description})`; + return this.description === undefined + ? "InjectionToken" + : `InjectionToken(${this.description})`; } } @@ -70,3 +116,15 @@ export function getInjectionTokenName(token: any): string | undefined { } return undefined; } + +/** Reads the constructor-set factory, by marker as the name is. */ +export function getInjectionTokenFactory(token: any): (() => any) | undefined { + if ( + token !== null && + typeof token === "object" && + Object.prototype.hasOwnProperty.call(token, INJECTION_TOKEN_FACTORY) + ) { + return token[INJECTION_TOKEN_FACTORY]; + } + return undefined; +} diff --git a/lib/common/di/injector.ts b/lib/common/di/injector.ts index 1c52d9add2..71cc4e8397 100644 --- a/lib/common/di/injector.ts +++ b/lib/common/di/injector.ts @@ -2,7 +2,10 @@ import { annotate } from "../helpers"; import { getContractName } from "./contract"; import { resolveForwardRef } from "./forward-ref"; import { runInInjectionContext } from "./inject"; -import { getInjectionTokenName } from "./injection-token"; +import { + getInjectionTokenFactory, + getInjectionTokenName, +} from "./injection-token"; import { normalizeProvider } from "./providers"; import type { InternalProvider, @@ -93,7 +96,8 @@ export class Injector { throw new Error("inject options cannot combine self and skipSelf"); } token = resolveForwardRef(token); - const found = this.findRecord(token, options); + const found = + this.findRecord(token, options) || this.selfProvided(token, options); if (!found) { if (options && options.optional) { return null; @@ -202,7 +206,10 @@ export class Injector { } public has(token: ProviderToken): boolean { - return !!this.findRecord(token); + return ( + !!this.findRecord(token) || + !!getInjectionTokenFactory(resolveForwardRef(token)) + ); } /** @@ -349,6 +356,30 @@ export class Injector { return this.parent ? this.parent.findRecord(token) : undefined; } + /** + * A token with a factory of its own is registered at the root the first + * time it is resolved without a provider, so every injector of the tree + * shares one value whichever of them asked first. + */ + private selfProvided( + token: ProviderToken, + options?: InjectOptions, + ): { record: IProviderRecord; owner: Injector } | undefined { + const factory = getInjectionTokenFactory(token); + const outOfReach = + options && + (options.self ? this.parent : options.skipSelf && !this.parent); + if (!factory || outOfReach) { + return undefined; + } + let root: Injector = this; + while (root.parent) { + root = root.parent; + } + root.register({ provide: token, useFactory: factory }); + return { record: root.findRecordLocal(token), owner: root }; + } + private instantiate( record: IProviderRecord, ctorArguments?: { [key: string]: any }, @@ -467,6 +498,9 @@ function displayNameOf(token: ProviderToken): string { if (injectionTokenName !== undefined) { return `InjectionToken(${injectionTokenName})`; } + if (typeof token === "object") { + return String(token); + } return ( getContractName(token) || (token).name || "" ); diff --git a/test/di.ts b/test/di.ts index 4222b3041b..eb98b95c3b 100644 --- a/test/di.ts +++ b/test/di.ts @@ -25,6 +25,86 @@ abstract class Device { abstract id: string; } +describe("di: injection tokens with a factory", () => { + it("provide themselves, once, for the whole tree", () => { + let built = 0; + const token = new InjectionToken({ + factory: () => ({ id: ++built }), + }); + const root = new Injector(); + + assert.isTrue(root.has(token)); + const value = root.createChild().createChild().get(token); + assert.strictEqual(root.get(token), value); + assert.strictEqual(built, 1); + }); + + it("run the factory against the root, whichever injector asked", () => { + const NAME = new InjectionToken("diTestFactoryName"); + const token = new InjectionToken({ factory: () => inject(NAME) }); + const root = new Injector([{ provide: NAME, useValue: "root" }]); + const child = root.createChild([{ provide: NAME, useValue: "child" }]); + + assert.strictEqual(child.get(token), "root"); + }); + + it("give way to a provider, at the root or in a child", () => { + const token = new InjectionToken({ factory: () => "factory" }); + const root = new Injector([{ provide: token, useValue: "root" }]); + const child = root.createChild([{ provide: token, useValue: "child" }]); + + assert.strictEqual(root.get(token), "root"); + assert.strictEqual(child.get(token), "child"); + }); + + it("respect self and skipSelf", () => { + const token = new InjectionToken({ factory: () => "factory" }); + const root = new Injector(); + const child = root.createChild(); + + assert.isNull(child.get(token, { self: true, optional: true })); + assert.isNull(root.get(token, { skipSelf: true, optional: true })); + assert.strictEqual(root.get(token, { self: true }), "factory"); + assert.strictEqual(child.get(token, { skipSelf: true }), "factory"); + }); + + it("keep a description as a registry name", () => { + const token = new InjectionToken("diTestFactoryNamed", { + factory: () => "factory", + }); + const root = new Injector(); + + assert.strictEqual(root.get(token), "factory"); + assert.strictEqual(root.get("$diTestFactoryNamed"), "factory"); + }); + + it("may be retried after a factory that threw", () => { + let fail = true; + const token = new InjectionToken({ + factory: () => { + if (fail) { + throw new Error("not yet"); + } + return "built"; + }, + }); + const root = new Injector(); + + assert.throws(() => root.get(token), "not yet"); + fail = false; + assert.strictEqual(root.get(token), "built"); + }); + + it("are told apart without names, and reported as tokens", () => { + const first = new InjectionToken(); + const second = new InjectionToken(); + const root = new Injector([{ provide: first, useValue: "first" }]); + + assert.strictEqual(root.get(first), "first"); + assert.throws(() => root.get(second), "unable to resolve InjectionToken"); + }); +}); + describe("di: tokens and resolution", () => { it("resolves one singleton via the class, the name, and the $-prefixed name", () => { const injector = new Injector([provide(Greeter, GreeterImpl)]); From ffa6bf4969b09738835122e972e71d9d3c8a8b06 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:21:06 -0300 Subject: [PATCH 2/4] feat(commands): option groups a service can inject defineOptions(schema) declares a schema that is also an injection token. A command lists groups under `options`, and a service injects the group to read the values of the command the user typed, typed from the same declaration. A group provides itself at the root and reads its values lazily: it can be injected before the command line is parsed, and reading it that early is an error. A process that uses the CLI as a library reads the live options. CliOptions is the group of process-level options, readable from startup. The built-in commands that redeclared one of its spellings list it instead. --- defining-commands.md | 176 ++++++- lib/commands/create-project.ts | 50 +- lib/commands/install.ts | 16 +- lib/commands/plugin/build-plugin.ts | 14 +- lib/commands/plugin/create-plugin.ts | 20 +- lib/commands/test-init.ts | 18 +- lib/common/commands/help.ts | 7 +- lib/common/contracts/cli-options.ts | 26 ++ lib/common/contracts/command-line-expected.ts | 10 + lib/common/contracts/index.ts | 1 + lib/common/define-command.ts | 396 +++++++++++++--- .../services/command-definition-adapter.ts | 111 +++-- lib/contracts/index.ts | 9 + lib/nativescript-cli.ts | 3 + lib/options.ts | 50 +- test/define-command.ts | 437 ++++++++++++++++-- test/options.ts | 78 ++++ test/type-fixtures/define-command-types.ts | 50 ++ 18 files changed, 1265 insertions(+), 207 deletions(-) create mode 100644 lib/common/contracts/cli-options.ts create mode 100644 lib/common/contracts/command-line-expected.ts diff --git a/defining-commands.md b/defining-commands.md index 5f8d5613dc..6f3e4e0398 100644 --- a/defining-commands.md +++ b/defining-commands.md @@ -102,8 +102,9 @@ Options ------- `options` is a schema keyed by the long option name — `output` is passed as -`--output`. Declare each entry with one of the five helpers, which fix the -value type: +`--output`. It may also be a list of option groups and such schemas; see +[Option groups](#option-groups). Declare each entry with one of the five +helpers, which fix the value type: | Helper | Declared with `default` | Declared without | | --------------- | ----------------------- | ----------------------- | @@ -153,9 +154,12 @@ options: { The schema types `ctx.options` and nothing else: `ctx.options` carries exactly the declared keys, and a typo is a compile error. There is deliberately no "give me everything" escape hatch — a command declares every option it reads, -CLI-wide ones (`--release`, `--path`, `--bundle`, …) included. Declaring one +CLI-wide ones (`--release`, `--watch`, `--bundle`, …) included. Declaring one that the CLI already knows is supported and carries its value through to -`ctx.options` exactly as a command-specific one does. +`ctx.options` exactly as a command-specific one does. The process-level +options (`--path`, `--log`, `--verbose` and the rest of `CliOptions`) are the +exception: a command lists their group instead of redeclaring them. See +[Process-level options](#process-level-options-clioptions). ### Sharing a schema between commands @@ -170,9 +174,108 @@ const buildOptions = { } satisfies CommandOptionsSchema; ``` +### Option groups + +`defineOptions(schema)` declares an option group: a schema that is also an +injection token. A command lists groups under `options`, next to inline +schemas: + +```ts +import { + booleanOption, + defineCommand, + defineOptions, + stringOption, +} from "nativescript/contracts"; + +export const WidgetOptions = defineOptions({ + theme: stringOption(), + compact: booleanOption({ default: false }), +}); + +export default defineCommand({ + name: "widget|add", + options: [WidgetOptions, { output: stringOption({ alias: "o" }) }], + run(ctx) { + // ctx.options -> { theme: string | undefined; compact: boolean; + // output: string | undefined } + }, +}); +``` + +`ctx.options` is typed as the merged values of every part. The class form +takes the same list, and types `this.options` the same way. A command that +keeps a single schema object can spread a group's: `...WidgetOptions.schema`. + +A group has no name: the exported object is the token, so declare it once and +import it wherever it is listed or injected. + +`defineOptions` validates the schema where it is written, as `defineCommand` +does, and reports a problem as `Invalid option group: .` followed by +the accepted form. + +### Injecting a group + +A service injects the group and reads the values of the command the user +typed. The group provides itself at the root, so it needs no registration and +the service stays a root singleton: + +```ts +class WidgetRenderer { + private options = inject(WidgetOptions); + + render() { + if (this.options.compact) { /* … */ } + } +} +``` + +- **Inject at any time, read once the command line is parsed.** Many services + are built before the typed command's options are parsed. Holding the group is + fine; reading a property that early throws `The option 'compact' was read + before the command line was parsed`. So keep the object and read it in the + method that needs it. Do not destructure it in a field or a constructor. +- **The values never change.** They are fixed when the typed command is parsed, + are read-only, and are the same in every later callback. Assigning to the + options service does not change them. +- **A command run in process does not change them.** Its own `ctx.options` + holds its own values and defaults; a service still reads the typed command's. + A command that needs a service to act on other values passes them to it. +- **An option that was not given** reads as the group's `default`. When the + typed command declares the option, its declaration decides. +- **A process that uses the CLI as a library** has no typed command, so reading + never throws and returns the options service's current value. + +Prefer a parameter when the method already receives a data object that can +carry the value; inject a group where passing it would mean threading it +through callers that do not use it. + +In a test, provide the value: `injector.register({ provide: WidgetOptions, +useValue: { compact: true } })`. + +### Collisions between parts + +A spelling is an option's long name or one of its aliases. One spelling may +appear in several parts of `options` only when every part declares it with an +identical spec: the same type, `default`, `alias` and `hasSensitiveValue`. +`description` is not compared. An alias may not equal another option's name +or alias. + +`defineCommand` and `Command()` check this when they are called, and +`defineOptions` checks it within its own schema. The message names both +declarations: + +``` +Invalid command definition for 'widget|add': option '--compact' is declared +by option group (--theme, --compact) and by the command's own options with +different specs. +``` + +followed by the accepted form. + ### Redeclaring a CLI-wide option, and shadowing one -`--verbose`, `--path`, `--log`, `--release`, `--env` and friends are declared by +`--release`, `--env`, `--watch`, `--device` and friends are declared by the CLI itself. A command's declaration is merged over the CLI-wide dictionary for the duration of that command, and that merge is the sanctioned way to give a global option a per-command default — `watch`, `hmr` and `skipNative` all @@ -190,14 +293,63 @@ still warns about at registration is a redeclaration that changes what the spelling _means_: - a declared option whose name matches a CLI-wide one but whose type differs — - `verbose: stringOption()` against the CLI's boolean `--verbose`; + `release: stringOption()` against the CLI's boolean `--release`; - an alias that belongs to a _different_ CLI-wide option — `output: -stringOption({ alias: "p" })` steals `--path`'s shorthand. Restating an - option's own shorthand (`path: stringOption({ alias: "p" })`) is fine. +stringOption({ alias: "f" })` steals `--force`'s shorthand. Restating an + option's own shorthand (`force: booleanOption({ alias: "f" })`) is fine. A redeclaration that leaves `alias`, `default` or `hasSensitiveValue` unset -keeps what the CLI-wide declaration carries for them, so `path: stringOption()` -still answers to `-p` and stays out of the logs; set one only to change it. +keeps what the CLI-wide declaration carries for them, so `release: +booleanOption()` still answers to `-r`, and `device: stringOption()` stays out +of the logs; set one only to change it. + +None of this applies to the process-level options. Redeclaring one of those is +an error, not a warning. + +### Process-level options: `CliOptions` + +`CliOptions` is the group of options the CLI parses once at startup, before a +command is chosen: `--log`, `--verbose`, `--version` (`-v`), `--help` (`-h`), +`--profileDir`, `--analyticsClient`, `--path` (`-p`) and `--config` (`-c`). +The services that run for every command read them: the logger, analytics, +project resolution. Its values can be read from startup, before a command's +options are parsed: + +```ts +import { CliOptions, inject } from "nativescript/contracts"; + +class ProjectLocator { + private cli = inject(CliOptions); + + public locate(): string { + return this.cli.path || process.cwd(); + } +} +``` + +A command may not redeclare any of these spellings, as a name or as an alias. +The CLI refuses the command when it compiles it, on the first resolution of a +registered command or when `runCommand` is given the definition: + +``` +Command 'widget|add': '--path' is a process-level option; list CliOptions under 'options', or inject it, instead of redeclaring it +``` + +To have the values on `ctx.options`, list the group itself. That is not a +redeclaration: it reads the same declaration. `install` does this: + +```ts +const installCommandOptions = [ + CliOptions, + { + frameworkPath: stringOption(), + disableNpmInstall: booleanOption(), + ignoreScripts: booleanOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; +``` + +`ctx.options.path` is then `string | undefined`. ### How validation behaves @@ -358,8 +510,8 @@ The run context declare, `{}` when there are none. It is spelled `params` because `arguments` is a reserved binding name in strict mode, so a destructuring `const { args, arguments } = ctx` would not even parse. -- `ctx.options` — the current value of each declared option, read at the moment - the command executes. +- `ctx.options` — the value of each option the command declares, its groups and + inline schemas merged, read when the invocation opens. - `ctx.injector` — this invocation's injector, a child of the one the command was registered against; see [Injection, and the first `await`](#injection-and-the-first-await). diff --git a/lib/commands/create-project.ts b/lib/commands/create-project.ts index 85c2eeec85..b8a504fa01 100644 --- a/lib/commands/create-project.ts +++ b/lib/commands/create-project.ts @@ -3,10 +3,12 @@ import { color } from "../color"; import { booleanOption, Command, + CommandOptionsInput, CommandOptionsSchema, - CommandOptionValues, + OptionValuesOf, stringOption, } from "../common/define-command"; +import { CliOptions } from "../common/contracts/cli-options"; import { inject } from "../common/di"; import { isInteractive } from "../common/helpers"; import * as constants from "../constants"; @@ -27,27 +29,29 @@ const TABS_TEMPLATE_KEY = "Tabs"; const TABS_TEMPLATE_DESCRIPTION = "An app with pre-built pages that uses tabs for navigation"; -const createProjectCommandOptions = { - js: booleanOption(), - ng: booleanOption(), - react: booleanOption(), - solid: booleanOption(), - svelte: booleanOption(), - tsc: booleanOption(), - vue: booleanOption(), - vuejs: booleanOption(), - vision: booleanOption(), - "vision-ng": booleanOption(), - "vision-react": booleanOption(), - "vision-solid": booleanOption(), - "vision-svelte": booleanOption(), - "vision-vue": booleanOption(), - template: stringOption(), - appid: stringOption(), - path: stringOption(), - force: booleanOption(), - ignoreScripts: booleanOption(), -} satisfies CommandOptionsSchema; +const createProjectCommandOptions = [ + CliOptions, + { + js: booleanOption(), + ng: booleanOption(), + react: booleanOption(), + solid: booleanOption(), + svelte: booleanOption(), + tsc: booleanOption(), + vue: booleanOption(), + vuejs: booleanOption(), + vision: booleanOption(), + "vision-ng": booleanOption(), + "vision-react": booleanOption(), + "vision-solid": booleanOption(), + "vision-svelte": booleanOption(), + "vision-vue": booleanOption(), + template: stringOption(), + appid: stringOption(), + force: booleanOption(), + ignoreScripts: booleanOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; interface ITemplateChoice { key?: string; @@ -217,7 +221,7 @@ const flavorTemplates: { [flavorName: string]: () => ITemplateChoice[] } = { /** The template a flavor flag selects, without asking anything. */ function selectTemplateFromOptions( - options: CommandOptionValues, + options: OptionValuesOf, ): string { if (options["vision-ng"] || (options.vision && options.ng)) { return constants.RESERVED_TEMPLATE_NAMES["vision-ng"]; diff --git a/lib/commands/install.ts b/lib/commands/install.ts index 7f861fa741..12b8aa1231 100644 --- a/lib/commands/install.ts +++ b/lib/commands/install.ts @@ -3,10 +3,12 @@ import { IFileSystem } from "../common/declarations"; import { booleanOption, CommandContext, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, } from "../common/define-command"; +import { CliOptions } from "../common/contracts/cli-options"; import { PlatformTypes } from "../constants"; import { INodePackageManager, @@ -19,12 +21,14 @@ import { IProjectDataService } from "../definitions/project"; import { ProjectData } from "../contracts/project-data"; import { provideProject } from "./command-base"; -const installCommandOptions = { - frameworkPath: stringOption(), - disableNpmInstall: booleanOption(), - ignoreScripts: booleanOption(), - path: stringOption(), -} satisfies CommandOptionsSchema; +const installCommandOptions = [ + CliOptions, + { + frameworkPath: stringOption(), + disableNpmInstall: booleanOption(), + ignoreScripts: booleanOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; async function installProjectDependencies( context: CommandContext, diff --git a/lib/commands/plugin/build-plugin.ts b/lib/commands/plugin/build-plugin.ts index 306fd77ed9..1f62f7326c 100644 --- a/lib/commands/plugin/build-plugin.ts +++ b/lib/commands/plugin/build-plugin.ts @@ -8,17 +8,21 @@ import { import { IFileSystem } from "../../common/declarations"; import { Command, + CommandOptionsInput, CommandOptionsSchema, stringOption, } from "../../common/define-command"; +import { CliOptions } from "../../common/contracts/cli-options"; import { inject } from "../../common/di"; import { ITempService } from "../../definitions/temp-service"; -const buildPluginCommandOptions = { - path: stringOption(), - gradlePath: stringOption(), - gradleArgs: stringOption(), -} satisfies CommandOptionsSchema; +const buildPluginCommandOptions = [ + CliOptions, + { + gradlePath: stringOption(), + gradleArgs: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; export class BuildPluginCommand extends Command({ name: "plugin|build", diff --git a/lib/commands/plugin/create-plugin.ts b/lib/commands/plugin/create-plugin.ts index f24d6b7b02..d003625cc1 100644 --- a/lib/commands/plugin/create-plugin.ts +++ b/lib/commands/plugin/create-plugin.ts @@ -4,9 +4,11 @@ import { INodePackageManager } from "../../declarations"; import { IErrors, IFileSystem, IChildProcess } from "../../common/declarations"; import { Command, + CommandOptionsInput, CommandOptionsSchema, stringOption, } from "../../common/define-command"; +import { CliOptions } from "../../common/contracts/cli-options"; import { inject } from "../../common/di"; import { ITerminalSpinnerService } from "../../definitions/terminal-spinner-service"; @@ -21,14 +23,16 @@ export const INCLUDE_ANGULAR_DEMO_MESSAGE = export const PATH_ALREADY_EXISTS_MESSAGE_TEMPLATE = "Path already exists and is not empty %s"; -const createPluginCommandOptions = { - path: stringOption(), - template: stringOption(), - username: stringOption(), - pluginName: stringOption(), - includeTypeScriptDemo: stringOption(), - includeAngularDemo: stringOption(), -} satisfies CommandOptionsSchema; +const createPluginCommandOptions = [ + CliOptions, + { + template: stringOption(), + username: stringOption(), + pluginName: stringOption(), + includeTypeScriptDemo: stringOption(), + includeAngularDemo: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; export class CreatePluginCommand extends Command({ name: "plugin|create", diff --git a/lib/commands/test-init.ts b/lib/commands/test-init.ts index e61837b359..970ff217d1 100644 --- a/lib/commands/test-init.ts +++ b/lib/commands/test-init.ts @@ -7,10 +7,12 @@ import { INodePackageManager } from "../declarations"; import { IPluginsService } from "../definitions/plugins"; import { Command, + CommandOptionsInput, CommandOptionsSchema, booleanOption, stringOption, } from "../common/define-command"; +import { CliOptions } from "../common/contracts/cli-options"; import { inject } from "../common/di"; import { IDictionary, @@ -26,13 +28,15 @@ const karmaConfigAdditionalFrameworks: IDictionary = { mocha: ["chai"], }; -const testInitCommandOptions = { - framework: stringOption(), - disableNpmInstall: booleanOption(), - frameworkPath: stringOption(), - ignoreScripts: booleanOption(), - path: stringOption(), -} satisfies CommandOptionsSchema; +const testInitCommandOptions = [ + CliOptions, + { + framework: stringOption(), + disableNpmInstall: booleanOption(), + frameworkPath: stringOption(), + ignoreScripts: booleanOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; export class TestInitCommand extends Command({ name: "test|init", diff --git a/lib/common/commands/help.ts b/lib/common/commands/help.ts index 97cf008244..2bda834ab3 100644 --- a/lib/common/commands/help.ts +++ b/lib/common/commands/help.ts @@ -1,15 +1,14 @@ import * as _ from "lodash"; import { CommandRegistry } from "../contracts/command-registry"; import { IHelpService } from "../declarations"; -import { booleanOption, defineCommand } from "../define-command"; +import { CliOptions } from "../contracts/cli-options"; +import { defineCommand } from "../define-command"; import { inject } from "../di"; export const helpCommandDefinition = defineCommand({ name: ["help", "/?"], description: "Shows the help for a command.", - options: { - help: booleanOption(), - }, + options: [CliOptions], // The command names whatever command it explains, so every argument after // the first is that command's own. params: "any", diff --git a/lib/common/contracts/cli-options.ts b/lib/common/contracts/cli-options.ts new file mode 100644 index 0000000000..ef54aa1c93 --- /dev/null +++ b/lib/common/contracts/cli-options.ts @@ -0,0 +1,26 @@ +import { + booleanOption, + type CommandOptionsSchema, + OptionsGroup, + stringOption, +} from "../define-command"; + +/** + * The process-level options: parsed once at startup, before a command is + * chosen, and read by the services that run for every command — the logger, + * analytics, project resolution. Readable as soon as the options service + * exists. Its spellings are protected: a command may not redeclare one. + */ +export const CliOptions = new OptionsGroup( + { + log: stringOption(), + verbose: booleanOption(), + version: booleanOption({ alias: "v" }), + help: booleanOption({ alias: "h" }), + profileDir: stringOption({ hasSensitiveValue: true }), + analyticsClient: stringOption(), + path: stringOption({ alias: "p", hasSensitiveValue: true }), + config: stringOption({ alias: "c", hasSensitiveValue: true }), + } satisfies CommandOptionsSchema, + "startup", +); diff --git a/lib/common/contracts/command-line-expected.ts b/lib/common/contracts/command-line-expected.ts new file mode 100644 index 0000000000..f1a9224267 --- /dev/null +++ b/lib/common/contracts/command-line-expected.ts @@ -0,0 +1,10 @@ +import { InjectionToken } from "../di/injection-token"; + +/** + * Whether this process is going to run a command line. Only the CLI's own + * entry point provides `true`; a process that uses the CLI as a library never + * parses a command's options, so nothing may wait for that parse. + */ +export const COMMAND_LINE_EXPECTED = new InjectionToken({ + factory: () => false, +}); diff --git a/lib/common/contracts/index.ts b/lib/common/contracts/index.ts index cbc83f14d2..8f61914e1b 100644 --- a/lib/common/contracts/index.ts +++ b/lib/common/contracts/index.ts @@ -14,6 +14,7 @@ export type { DeferredCommandRejection, DeferredCommandResult, } from "./command-registry"; +export { CliOptions } from "./cli-options"; export { COMMAND_CONTEXT } from "./command-context"; export { COMMAND_PRECONDITIONS } from "./command-preconditions"; export type { CommandPrecondition } from "./command-preconditions"; diff --git a/lib/common/define-command.ts b/lib/common/define-command.ts index db8bb2b257..1ef1fb0297 100644 --- a/lib/common/define-command.ts +++ b/lib/common/define-command.ts @@ -8,9 +8,12 @@ import { COMMAND_CONTEXT } from "./contracts/command-context"; import type { KeyShortcut } from "./contracts/key-shortcuts"; -import { inject } from "./di/inject"; +import type { IDashedOption, IDictionary } from "./declarations"; +import { getCurrentInjector, inject } from "./di/inject"; +import { InjectionToken } from "./di/injection-token"; import type { Injector } from "./di/injector"; import type { Provider } from "./di/providers"; +import { OptionType } from "./enums"; /** * Symbol.for so that a definition produced by one copy of the CLI is still @@ -84,6 +87,291 @@ export type CommandOptionValues = { [K in keyof TSchema]: CommandOptionValue; }; +/** + * Symbol.for, as COMMAND_DEFINITION_MARKER: an extension's copy of this module + * must recognise a group minted by the running copy. + */ +export const OPTIONS_GROUP_MARKER: unique symbol = Symbol.for( + "nativescript:cli:optionsGroup", +); + +/** + * Which parse a group's values come from. `"startup"` is the parse of the + * process-level options, done before a command is chosen. + */ +export type OptionsGroupSource = "commandLine" | "startup"; + +/** What a group reads its values from; the options service implements it. */ +export interface OptionValueReader { + readGroupOption(optionName: string, source: OptionsGroupSource): any; +} + +const spellingOf = (optionName: string): string => + `${optionName.length === 1 ? "-" : "--"}${optionName}`; + +/** + * A set of options declared once and used at both ends: a command lists the + * group under `options` and the parser fills it; a service injects the group + * and reads the parsed values, typed from the same declaration. The group is + * its own token and provides itself at the root, so it can be injected at any + * time; its values can be read once the command line is parsed. + */ +export class OptionsGroup< + TSchema extends CommandOptionsSchema = CommandOptionsSchema, +> extends InjectionToken>> { + readonly [OPTIONS_GROUP_MARKER] = true; + + constructor( + public readonly schema: TSchema, + source: OptionsGroupSource = "commandLine", + ) { + super({ factory: () => createGroupValues(schema, source) }); + } + + public toString(): string { + return `option group (${Object.keys(this.schema).map(spellingOf).join(", ")})`; + } +} + +// Getters rather than values: a service built before the command line is +// parsed may hold the group, and reads it afterwards. +function createGroupValues( + schema: TSchema, + source: OptionsGroupSource, +): Readonly> { + const injector = getCurrentInjector(); + const values: any = {}; + for (const optionName of Object.keys(schema)) { + Object.defineProperty(values, optionName, { + enumerable: true, + get: () => { + const value = injector + .get("options") + .readGroupOption(optionName, source); + return value === undefined ? schema[optionName].default : value; + }, + }); + } + return Object.freeze(values); +} + +export function isOptionsGroup(value: any): value is OptionsGroup { + return ( + !!value && + typeof value === "object" && + (value)[OPTIONS_GROUP_MARKER] === true + ); +} + +/** What `options` takes: one schema, or a list of groups and inline schemas. */ +export type CommandOptionsInput = + | CommandOptionsSchema + | ReadonlyArray | CommandOptionsSchema>; + +type UnionToIntersection = ( + U extends any ? (member: U) => void : never +) extends (member: infer I) => void + ? I + : never; + +type OptionsSchemaPart = + T extends OptionsGroup + ? TSchema + : T extends CommandOptionsSchema + ? T + : never; + +/** The one schema an `options` input declares: its groups and inline specs merged. */ +export type OptionsSchemaOf = ( + TOptions extends ReadonlyArray + ? UnionToIntersection> + : OptionsSchemaPart +) extends infer TSchema + ? TSchema extends CommandOptionsSchema + ? TSchema + : {} + : never; + +export type OptionValuesOf = CommandOptionValues< + OptionsSchemaOf +>; + +export interface ResolvedCommandOptions { + /** Every declared option, groups and inline specs merged, keyed by the long name. */ + schema: CommandOptionsSchema; + /** The groups and inline schemas as declared, in order. */ + parts: ReadonlyArray | CommandOptionsSchema>; +} + +const aliasesOf = (alias: string | string[] | undefined): string[] => + alias === undefined ? [] : Array.isArray(alias) ? alias : [alias]; + +const sameOptionSpec = (a: CommandOptionSpec, b: CommandOptionSpec): boolean => + a.type === b.type && + JSON.stringify(a.default) === JSON.stringify(b.default) && + JSON.stringify(aliasesOf(a.alias)) === JSON.stringify(aliasesOf(b.alias)) && + a.hasSensitiveValue === b.hasSensitiveValue && + a.required === b.required; + +/** + * Merges what `options` declares into one schema. A spelling — a name or an + * alias — may be declared once, or again with the same spec; two specs for one + * spelling would leave the parser with one meaning and the other declaration + * silently wrong, so that is reported instead. + */ +export function resolveCommandOptions( + options: CommandOptionsInput | undefined, + report: (problem: string) => never, + inlineSource: string = "the command's own options", +): ResolvedCommandOptions { + const parts: { source: string; schema: CommandOptionsSchema }[] = []; + const groups = new Set>(); + const list: ReadonlyArray | CommandOptionsSchema> = + options === undefined + ? [] + : Array.isArray(options) + ? options + : [options]; + + for (const part of list) { + if (isOptionsGroup(part)) { + if (!groups.has(part)) { + groups.add(part); + parts.push({ + source: String(part), + schema: part.schema, + }); + } + } else { + parts.push({ source: inlineSource, schema: part }); + } + } + + const schema: CommandOptionsSchema = {}; + const owners: IDictionary<{ optionName: string; source: string }> = {}; + for (const { source, schema: partSchema } of parts) { + for (const optionName of Object.keys(partSchema)) { + const spec = partSchema[optionName]; + const existing = schema[optionName]; + if (existing && !sameOptionSpec(existing, spec)) { + report( + `option '--${optionName}' is declared by ${owners[optionName].source} and by ${source} with different specs`, + ); + } + if (!existing) { + const owner = owners[optionName]; + if (owner) { + report( + `option '--${optionName}' (${source}) is already an alias of '--${owner.optionName}' (${owner.source})`, + ); + } + schema[optionName] = spec; + owners[optionName] = { optionName, source }; + } + for (const alias of aliasesOf(spec.alias)) { + const owner = owners[alias]; + if (owner && owner.optionName !== optionName) { + report( + `alias '-${alias}' of '--${optionName}' (${source}) is already the spelling of '--${owner.optionName}' (${owner.source})`, + ); + } + if (!owner) { + owners[alias] = { optionName, source }; + } + } + } + } + + return { schema, parts: list }; +} + +/** Every spelling a schema answers to: the long names and their aliases. */ +export function optionSpellingsOf(schema: CommandOptionsSchema): string[] { + const spellings: string[] = []; + for (const optionName of Object.keys(schema)) { + spellings.push(optionName, ...aliasesOf(schema[optionName].alias)); + } + return spellings; +} + +const DASHED_OPTION_TYPES: IDictionary = { + boolean: OptionType.Boolean, + string: OptionType.String, + number: OptionType.Number, + array: OptionType.Array, + object: OptionType.Object, +}; + +/** The parser's shape of one spec, as `dashedOptions` and the CLI-wide table hold it. */ +export function compileOptionSpec(spec: CommandOptionSpec): IDashedOption { + const dashedOption: IDashedOption = { + type: DASHED_OPTION_TYPES[spec.type], + hasSensitiveValue: spec.hasSensitiveValue === true, + }; + if (spec.default !== undefined) { + dashedOption.default = spec.default; + } + if (spec.alias !== undefined) { + dashedOption.alias = spec.alias; + } + if (spec.description !== undefined) { + dashedOption.describe = spec.description; + } + return dashedOption; +} + +export function compileOptionsSchema( + schema: CommandOptionsSchema, +): IDictionary { + const dashedOptions: IDictionary = {}; + for (const optionName of Object.keys(schema)) { + dashedOptions[optionName] = compileOptionSpec(schema[optionName]); + } + return dashedOptions; +} + +/** + * The parsed value of every option in `schema`, read off the option service's + * per-name accessors, and nothing else. + */ +export function readOptionValues( + schema: TSchema, + source: any, +): CommandOptionValues { + const values: any = {}; + for (const optionName of Object.keys(schema)) { + values[optionName] = source[optionName]; + } + return values; +} + +const OPTIONS_GROUP_FORM = "defineOptions({ watch: booleanOption() })"; + +/** + * Declares an option group: a schema that is also the token its parsed values + * are injected by. Validated here, like a command definition, so a bad + * spec is reported where it was written. + */ +export function defineOptions( + schema: TSchema, +): OptionsGroup { + const report = (problem: string): never => { + throw new Error( + `Invalid option group: ${problem}. Accepted form: ${OPTIONS_GROUP_FORM}`, + ); + }; + + if (!isPlainObject(schema)) { + report("the schema must be an object keyed by the long option name"); + } + for (const optionName of Object.keys(schema)) { + validateOptionSpec(report, optionName, schema[optionName]); + } + resolveCommandOptions(schema, report, "the group"); + + return new OptionsGroup(schema); +} + /** * Positional parameters keyed by the declaring spec's `name`. A variadic spec * always yields an array; a non-variadic optional one is absent when the @@ -100,7 +388,7 @@ export type CommandArgumentValues = CommandParamValues; * One positional parameter. Specs are matched strictly by position: the first * spec takes the first argument, and so on. */ -export interface ParamSpec { +export interface ParamSpec { /** Key under which the value appears on `ctx.params`. */ name: string; /** Defaults to false. A required spec may not follow an optional one. */ @@ -119,18 +407,18 @@ export interface ParamSpec { } /** @deprecated Use ParamSpec. */ -export type ArgumentSpec = +export type ArgumentSpec = ParamSpec; /** * `"none"` rejects positional arguments; `"any"` accepts any number of them; * an array declares them one by one. */ -export type ParamsPolicy = +export type ParamsPolicy = "none" | "any" | ParamSpec[]; /** @deprecated Use ParamsPolicy. */ -export type ArgumentsPolicy = +export type ArgumentsPolicy = ParamsPolicy; export interface CommandFailOptions { @@ -141,13 +429,16 @@ export interface CommandFailOptions { help?: boolean; } -export interface CommandContext { +export interface CommandContext { /** Positional arguments, after the command name has been consumed. */ args: string[]; /** The same arguments keyed by the names the `params` specs declare. */ params: CommandParamValues; - /** Current value of every option declared in the schema, and nothing else. */ - options: CommandOptionValues; + /** + * Current value of every option the command declares, its groups and inline + * specs merged, and nothing else. + */ + options: OptionValuesOf; /** * This invocation's injector, the one `inject()` resolves against before the * first `await`; after it, `inject()` stops working and this is the lookup. @@ -161,13 +452,18 @@ export interface CommandContext { } export interface CommandDefinition< - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, TResult = void, TSetup = void, > { /** `"widget|add"`; `|` separates hierarchy levels. Several names alias one command. */ name: CommandName; description?: string; + /** + * A schema keyed by the long option name, or a list of option groups and + * such schemas. One spelling may appear in several parts only with the same + * spec; a process-level spelling may not be redeclared at all. + */ options?: TSchema; /** * `"none"` (the default) rejects positional arguments; `"any"` accepts any @@ -230,7 +526,7 @@ export interface CommandDefinition< * define-time validation rather than any object of the right shape. */ export type DefinedCommand< - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, TResult = void, TSetup = void, > = CommandDefinition & { @@ -359,24 +655,25 @@ const validateName = (definition: any): void => { ); }; +const OPTION_HELPERS = + "booleanOption(), stringOption(), numberOption(), arrayOption() or objectOption()"; + const validateOptionSpec = ( - definition: any, + report: (problem: string) => never, optionName: string, spec: any, ): void => { if (!isPlainObject(spec)) { - invalid( - definition, - `option '${optionName}' must be declared with one of booleanOption(), stringOption(), numberOption(), arrayOption() or objectOption()`, + report( + `option '${optionName}' must be declared with one of ${OPTION_HELPERS}`, ); } if (OPTION_TYPES.indexOf(spec.type) === -1) { - invalid( - definition, + report( `option '${optionName}' has type '${spec.type}'; the supported types are ${OPTION_TYPES.join( ", ", - )} — declare it with one of booleanOption(), stringOption(), numberOption(), arrayOption() or objectOption()`, + )} — declare it with one of ${OPTION_HELPERS}`, ); } @@ -384,8 +681,7 @@ const validateOptionSpec = ( (field) => OPTION_SPEC_FIELDS.indexOf(field) === -1, ); if (unknownFields.length) { - invalid( - definition, + report( `option '${optionName}' has unknown field(s) ${unknownFields .map((field) => `'${field}'`) .join(", ")}; an option spec accepts ${OPTION_SPEC_FIELDS.join(", ")}`, @@ -393,11 +689,10 @@ const validateOptionSpec = ( } if (spec.required !== undefined && typeof spec.required !== "boolean") { - invalid(definition, `option '${optionName}': 'required' must be a boolean`); + report(`option '${optionName}': 'required' must be a boolean`); } if (spec.required === true && spec.default !== undefined) { - invalid( - definition, + report( `option '${optionName}' is required and has a default; one of the two`, ); } @@ -409,8 +704,7 @@ const validateOptionSpec = ( spec.alias.length > 0 && spec.alias.every((entry: any) => typeof entry === "string")); if (!aliasIsUsable) { - invalid( - definition, + report( `option '${optionName}' declares an 'alias' that is neither a string nor a non-empty array of strings`, ); } @@ -419,17 +713,11 @@ const validateOptionSpec = ( spec.hasSensitiveValue !== undefined && typeof spec.hasSensitiveValue !== "boolean" ) { - invalid( - definition, - `option '${optionName}' declares a non-boolean 'hasSensitiveValue'`, - ); + report(`option '${optionName}' declares a non-boolean 'hasSensitiveValue'`); } if (spec.description !== undefined && typeof spec.description !== "string") { - invalid( - definition, - `option '${optionName}' declares a non-string 'description'`, - ); + report(`option '${optionName}' declares a non-string 'description'`); } }; @@ -608,20 +896,24 @@ const validateDefinition = (definition: any): void => { } if (definition.options !== undefined) { - if (!isPlainObject(definition.options)) { - invalid( - definition, - "'options' must be an object keyed by the long option name", - ); - } - - for (const optionName of Object.keys(definition.options)) { - validateOptionSpec( - definition, - optionName, - definition.options[optionName], - ); + const report = (problem: string): never => invalid(definition, problem); + const parts: any[] = Array.isArray(definition.options) + ? definition.options + : [definition.options]; + for (const part of parts) { + if (isOptionsGroup(part)) { + continue; + } + if (!isPlainObject(part)) { + report( + "'options' must be an object keyed by the long option name, or an array of option groups and such objects", + ); + } + for (const optionName of Object.keys(part)) { + validateOptionSpec(report, optionName, part[optionName]); + } } + resolveCommandOptions(definition.options, report); } }; @@ -674,7 +966,7 @@ const validateMeta = (meta: any): void => { * `CommandDefinition` widens it straight back to `string`. */ export type NamedCommand< - TSchema extends CommandOptionsSchema, + TSchema extends CommandOptionsInput, TResult, TSetup, TName extends CommandName, @@ -704,7 +996,7 @@ export type CommandNamesOf = TDefinition extends { : never; export function defineCommand< - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, TResult = void, TSetup = void, const TName extends CommandName = CommandName, @@ -747,7 +1039,7 @@ const COMMAND_CLASS_DEFINITION = Symbol.for( */ export type CommandMeta< TName extends CommandName = CommandName, - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, > = Omit< CommandDefinition, "name" | "setup" | "canExecute" | "run" | "postRun" | "shortcuts" @@ -758,14 +1050,14 @@ export type CommandMeta< * every `Command()` class — a subclass's declaration emit refers to it — not * because anything should extend it directly. */ -export abstract class CommandBase { +export abstract class CommandBase { /** * The instance is built once per invocation, as that invocation's `setup`, * so the context captured here is the one its own run was handed. */ protected readonly context: CommandContext = inject(COMMAND_CONTEXT); - protected get options(): CommandOptionValues { + protected get options(): OptionValuesOf { return this.context.options; } @@ -787,7 +1079,7 @@ export abstract class CommandBase { */ export type CommandClass< TName extends CommandName = CommandName, - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, > = (abstract new () => CommandBase) & { readonly definition: NamedCommand, TName>; readonly [COMMAND_CLASS_MARKER]: true; @@ -911,7 +1203,7 @@ export type CommandReference = string | RegisterableCommand; */ export function Command< const TName extends CommandName, - TSchema extends CommandOptionsSchema = {}, + TSchema extends CommandOptionsInput = {}, >(meta: CommandMeta): CommandClass { validateMeta(meta); diff --git a/lib/common/services/command-definition-adapter.ts b/lib/common/services/command-definition-adapter.ts index 89539d8ad0..77ecd9b9e0 100644 --- a/lib/common/services/command-definition-adapter.ts +++ b/lib/common/services/command-definition-adapter.ts @@ -1,6 +1,6 @@ import { EOL } from "os"; -import { OptionType } from "../enums"; import { getRootInjector } from "../yok"; +import { CliOptions } from "../contracts/cli-options"; import { getCurrentInjector, runInInjectionContext } from "../di/inject"; import { Injector } from "../di/injector"; import { IDictionary, IDashedOption, IErrors } from "../declarations"; @@ -34,23 +34,21 @@ import { CommandName, CommandNamesOf, CommandOptionSpec, - CommandOptionType, + CommandOptionsInput, CommandOptionsSchema, + compileOptionSpec, DefinedCommand, + isOptionsGroup, + OptionsGroup, + optionSpellingsOf, + readOptionValues, RegisterableCommand, + resolveCommandOptions, defineCommand, toCommandDefinition, isPlainObject, } from "../define-command"; -const OPTION_TYPES: IDictionary = { - boolean: OptionType.Boolean, - string: OptionType.String, - number: OptionType.Number, - array: OptionType.Array, - object: OptionType.Object, -}; - const compileOptions = ( schema: CommandOptionsSchema, cliOptions?: IDictionary, @@ -59,34 +57,21 @@ const compileOptions = ( for (const optionName of Object.keys(schema)) { const spec = schema[optionName]; + const dashedOption = compileOptionSpec(spec); // Declaring an option the CLI already defines replaces its entry // wholesale (see setupOptions), so anything left unspecified here is // carried over rather than silently dropped for this command. const cliOption = cliOptions && cliOptions[optionName]; - const dashedOption: IDashedOption = { - type: OPTION_TYPES[spec.type], - hasSensitiveValue: - spec.hasSensitiveValue !== undefined - ? spec.hasSensitiveValue === true - : cliOption - ? cliOption.hasSensitiveValue === true - : false, - }; - - if (spec.default !== undefined) { - dashedOption.default = spec.default; - } else if (cliOption && cliOption.default !== undefined) { - dashedOption.default = cliOption.default; - } - - if (spec.alias !== undefined) { - dashedOption.alias = spec.alias; - } else if (cliOption && cliOption.alias !== undefined) { - dashedOption.alias = cliOption.alias; - } - - if (spec.description !== undefined) { - dashedOption.describe = spec.description; + if (cliOption) { + if (spec.hasSensitiveValue === undefined) { + dashedOption.hasSensitiveValue = cliOption.hasSensitiveValue === true; + } + if (spec.default === undefined && cliOption.default !== undefined) { + dashedOption.default = cliOption.default; + } + if (spec.alias === undefined && cliOption.alias !== undefined) { + dashedOption.alias = cliOption.alias; + } } dashedOptions[optionName] = dashedOption; @@ -108,7 +93,7 @@ const aliasList = (alias: string | string[]): string[] => const isRedeclarationOf = ( spec: CommandOptionSpec, cliOption: IDashedOption, -): boolean => OPTION_TYPES[spec.type] === cliOption.type; +): boolean => compileOptionSpec(spec).type === cliOption.type; const warnOnCliOptionCollisions = ( targetInjector: Injector, @@ -181,6 +166,32 @@ const warnOnCliOptionCollisions = ( ); }; +/** + * A process-level spelling is parsed at startup for every command, so a command + * redeclaring one would give it a second meaning for the length of its run. + * Listing CliOptions is not a redeclaration: it reads the same declaration. + */ +const guardCliOptionSpellings = ( + parts: ReadonlyArray | CommandOptionsSchema>, + report: (problem: string) => never, +): void => { + const protectedSpellings = new Set(optionSpellingsOf(CliOptions.schema)); + for (const part of parts) { + if (part === CliOptions) { + continue; + } + for (const spelling of optionSpellingsOf( + isOptionsGroup(part) ? part.schema : part, + )) { + if (protectedSpellings.has(spelling)) { + report( + `'${spelling.length === 1 ? "-" : "--"}${spelling}' is a process-level option; list CliOptions under 'options', or inject it, instead of redeclaring it`, + ); + } + } + } +}; + /** * Wraps a declarative definition in the ICommand shape the legacy registry and * CommandsService expect. @@ -197,7 +208,7 @@ const warnOnCliOptionCollisions = ( * lifetime, so that record is replaced per invocation. */ export function createCommandFromDefinition< - TSchema extends CommandOptionsSchema, + TSchema extends CommandOptionsInput, TResult = any, TSetup = any, >( @@ -205,7 +216,18 @@ export function createCommandFromDefinition< targetInjector: Injector = (getRootInjector()), providers: Provider[] = [], ): ICommand { - const schema = definition.options || {}; + const commandName = Array.isArray(definition.name) + ? definition.name[0] + : definition.name; + const compileError = (problem: string): never => { + throw new Error(`Command '${commandName}': ${problem}`); + }; + + const { schema, parts } = resolveCommandOptions( + definition.options, + compileError, + ); + guardCliOptionSpellings(parts, compileError); const optionNames = Object.keys(schema); // Only a definition that declares options may depend on the options service @@ -221,10 +243,6 @@ export function createCommandFromDefinition< warnOnCliOptionCollisions(targetInjector, definition, schema, optionsService); - const commandName = Array.isArray(definition.name) - ? definition.name[0] - : definition.name; - const fail = (message: string, options?: CommandFailOptions): never => { if (typeof message !== "string" || !message.trim()) { throw new Error( @@ -273,15 +291,10 @@ export function createCommandFromDefinition< // service only holds this command's parsed values once validateOptions has // run for it. const buildContext = (args: string[]): CommandContext => { - const options: any = {}; - for (const optionName of optionNames) { - options[optionName] = (optionsService)[optionName]; - } - return { args, params: mapParams(args), - options, + options: readOptionValues(schema, optionsService), // The invocation's child injector provides this very object under // COMMAND_CONTEXT, so it can only be created - and assigned here - // once the context exists. @@ -599,7 +612,7 @@ export function createCommandFromDefinition< * name, so the name is a parameter rather than read off the definition. */ export function registerDefinitionAs< - TSchema extends CommandOptionsSchema, + TSchema extends CommandOptionsInput, TResult = any, TSetup = any, >( @@ -650,7 +663,7 @@ const contextInjector = (): Injector => * CLI itself outside one. */ export function registerCommand< - TSchema extends CommandOptionsSchema, + TSchema extends CommandOptionsInput, TResult = any, TSetup = any, >( diff --git a/lib/contracts/index.ts b/lib/contracts/index.ts index 1c9bcf72f1..494d7ab2c9 100644 --- a/lib/contracts/index.ts +++ b/lib/contracts/index.ts @@ -16,6 +16,7 @@ export { getInjectionTokenName, INJECTION_TOKEN_NAME, } from "../common/di/injection-token"; +export type { InjectionTokenOptions } from "../common/di/injection-token"; export { inject, runInInjectionContext } from "../common/di/inject"; export { forwardRef, resolveForwardRef } from "../common/di/forward-ref"; export { Injector } from "../common/di/injector"; @@ -67,6 +68,8 @@ export { numberOption, arrayOption, objectOption, + defineOptions, + isOptionsGroup, } from "../common/define-command"; export type { ParamSpec, @@ -89,11 +92,17 @@ export type { CommandFailOptions, CommandOptionSpec, DefaultedCommandOptionSpec, + CommandOptionsInput, CommandOptionsSchema, CommandOptionSpecInit, CommandOptionType, CommandOptionValues, + OptionsSchemaOf, + OptionsGroup, + OptionValuesOf, } from "../common/define-command"; +// The process-level option group. +export { CliOptions } from "../common/contracts/cli-options"; // Promoted from the internal contracts index: the class form reads it in a // field initializer, and a per-command provider is written against it. export { COMMAND_CONTEXT } from "../common/contracts/command-context"; diff --git a/lib/nativescript-cli.ts b/lib/nativescript-cli.ts index cf122f948c..9a93b7a5b7 100644 --- a/lib/nativescript-cli.ts +++ b/lib/nativescript-cli.ts @@ -34,6 +34,7 @@ if (process.platform === "win32") { import { installUncaughtExceptionListener } from "./common/errors"; import { settlePromises } from "./common/helpers"; +import { COMMAND_LINE_EXPECTED } from "./common/contracts/command-line-expected"; import { injector } from "./common/yok"; import { IErrors, ICommandDispatcher } from "./common/declarations"; import { ErrorCodes } from "./common/enums"; @@ -47,6 +48,8 @@ installUncaughtExceptionListener( process.exit.bind(process, ErrorCodes.UNCAUGHT), ); +injector.register({ provide: COMMAND_LINE_EXPECTED, useValue: true }); + const logger: ILogger = injector.resolve("logger"); export const originalProcessOn = process.on.bind(process); diff --git a/lib/options.ts b/lib/options.ts index b367f0f01f..6734edccac 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -11,25 +11,29 @@ import { import { OptionType } from "./common/enums"; import { injector } from "./common/yok"; import { APP_FOLDER_NAME } from "./constants"; -export class Options { +import { inject } from "./common/di"; +import { CliOptions } from "./common/contracts/cli-options"; +import { COMMAND_LINE_EXPECTED } from "./common/contracts/command-line-expected"; +import { + compileOptionsSchema, + OptionsGroupSource, + OptionValueReader, +} from "./common/define-command"; +export class Options implements OptionValueReader { private static DASHED_OPTION_REGEX = /(.+?)([A-Z])(.*)/; private static NONDASHED_OPTION_REGEX = /(.+?)[-]([a-zA-Z])(.*)/; private optionsWhiteList = ["_", "$0"]; // yargs artifacts, not options private globalOptions: IDictionary = { - log: { type: OptionType.String, hasSensitiveValue: false }, - verbose: { type: OptionType.Boolean, hasSensitiveValue: false }, - version: { type: OptionType.Boolean, alias: "v", hasSensitiveValue: false }, - help: { type: OptionType.Boolean, alias: "h", hasSensitiveValue: false }, - profileDir: { type: OptionType.String, hasSensitiveValue: true }, - analyticsClient: { type: OptionType.String, hasSensitiveValue: false }, - path: { type: OptionType.String, alias: "p", hasSensitiveValue: true }, - config: { type: OptionType.String, alias: "c", hasSensitiveValue: true }, + ...compileOptionsSchema(CliOptions.schema), // This will parse all non-hyphenated values as strings. _: { type: OptionType.String, hasSensitiveValue: false }, }; private initialArgv: yargs.Arguments; + private startupArgv: yargs.Arguments; + private commandLineArgv: yargs.Arguments; + private commandLineExpected = inject(COMMAND_LINE_EXPECTED); public argv: yargs.Arguments; public options: IDictionary; @@ -72,6 +76,7 @@ export class Options { ) { this.options = _.extend({}, this.commonOptions, this.globalOptions); this.setArgv(); + this.startupArgv = _.cloneDeep(this.argv); } public get shorthands(): string[] { @@ -319,6 +324,33 @@ export class Options { ); } } + + // The first command validated in a process is the one the user typed; + // commands dispatched in process come later and must not change it. + if (!this.commandLineArgv) { + this.commandLineArgv = _.cloneDeep(this.argv); + } + } + + /** + * The value an option group reads. A process that runs a command line gets + * the values of the command the user typed, fixed from the moment they are + * parsed; a library process never parses one and reads the live table. + */ + public readGroupOption(optionName: string, source: OptionsGroupSource): any { + if (source === "startup") { + return this.startupArgv[optionName]; + } + if (!this.commandLineExpected) { + return this.getOptionValue(optionName); + } + if (!this.commandLineArgv) { + throw new Error( + `The option '${optionName}' was read before the command line was parsed. ` + + `Inject the option group and read it when it is needed.`, + ); + } + return this.commandLineArgv[optionName]; } // The name every spelling of an option collapses to. Unknown options keep diff --git a/test/define-command.ts b/test/define-command.ts index 75573b5eb4..3c0e35d8e6 100644 --- a/test/define-command.ts +++ b/test/define-command.ts @@ -9,6 +9,7 @@ import { runInInjectionContext, } from "../lib/common/di"; import { COMMAND_CONTEXT } from "../lib/common/contracts/command-context"; +import { CliOptions } from "../lib/common/contracts/cli-options"; import { COMMAND_PRECONDITIONS } from "../lib/common/contracts/command-preconditions"; import { COMMAND_OWNER, @@ -26,8 +27,10 @@ import { booleanOption, Command, defineCommand, + defineOptions, isCommandClass, isCommandDefinition, + isOptionsGroup, numberOption, stringOption, } from "../lib/common/define-command"; @@ -453,7 +456,7 @@ describe("defineCommand", () => { describe("execute", () => { it("passes args and the declared options through, inside an injection context", async () => { const testInjector = createTestInjector({ - verbose: true, + quiet: true, output: "dist", undeclared: "ignored", }); @@ -467,7 +470,7 @@ describe("defineCommand", () => { defineCommand({ name: "dctestexec", options: { - verbose: booleanOption(), + quiet: booleanOption(), output: stringOption(), }, run(context) { @@ -482,27 +485,27 @@ describe("defineCommand", () => { await command.execute(["one", "two"]); assert.deepEqual(capturedArgs, ["one", "two"]); - assert.deepEqual(capturedOptions, { verbose: true, output: "dist" }); + assert.deepEqual(capturedOptions, { quiet: true, output: "dist" }); assert.strictEqual(greeting, "hello"); }); it("reads option values at execution time", async () => { - const optionsService: any = { verbose: false }; + const optionsService: any = { quiet: false }; const testInjector = createTestInjector(optionsService); let seen: boolean; const command = createCommandFromDefinition( defineCommand({ name: "dctestlate", - options: { verbose: booleanOption() }, + options: { quiet: booleanOption() }, run: (context) => { - seen = context.options.verbose; + seen = context.options.quiet; }, }), testInjector, ); - optionsService.verbose = true; + optionsService.quiet = true; await command.execute([]); assert.isTrue(seen); @@ -530,7 +533,7 @@ describe("defineCommand", () => { it("carries the declared option values onto the run context", async () => { const testInjector = createTestInjector({ - verbose: true, + quiet: true, output: "dist", retries: 3, files: ["a.ts"], @@ -541,7 +544,7 @@ describe("defineCommand", () => { defineCommand({ name: "dctesttypes", options: { - verbose: booleanOption(), + quiet: booleanOption(), output: stringOption(), retries: numberOption(), files: arrayOption(), @@ -556,7 +559,7 @@ describe("defineCommand", () => { await command.execute([]); assert.deepEqual(seen, { - verbose: true, + quiet: true, output: "dist", retries: 3, files: ["a.ts"], @@ -729,7 +732,7 @@ describe("defineCommand", () => { defineCommand({ name: "dctestdashed", options: { - verbose: booleanOption({ default: false }), + quiet: booleanOption({ default: false }), output: stringOption({ alias: "o" }), retries: numberOption({ default: 3 }), files: arrayOption(), @@ -744,7 +747,7 @@ describe("defineCommand", () => { ); assert.deepEqual(command.dashedOptions, { - verbose: { type: "boolean", hasSensitiveValue: false, default: false }, + quiet: { type: "boolean", hasSensitiveValue: false, default: false }, output: { type: "string", hasSensitiveValue: false, alias: "o" }, retries: { type: "number", hasSensitiveValue: false, default: 3 }, files: { type: "array", hasSensitiveValue: false }, @@ -762,25 +765,25 @@ describe("defineCommand", () => { name: "dctestredeclare", options: { // Redeclared only to give this command its own default. - path: stringOption({ default: "./here" }), + output: stringOption({ default: "./here" }), watch: booleanOption({ default: false }), }, run: (): void => undefined, }), createTestInjector({ options: { - path: { type: "string", alias: "p", hasSensitiveValue: true }, + output: { type: "string", alias: "o", hasSensitiveValue: true }, watch: { type: "boolean", hasSensitiveValue: false }, }, }), ); assert.deepEqual(command.dashedOptions, { - path: { + output: { type: "string", hasSensitiveValue: true, default: "./here", - alias: "p", + alias: "o", }, watch: { type: "boolean", hasSensitiveValue: false, default: false }, }); @@ -791,19 +794,19 @@ describe("defineCommand", () => { defineCommand({ name: "dctestoverride", options: { - path: stringOption({ alias: "q", hasSensitiveValue: false }), + output: stringOption({ alias: "q", hasSensitiveValue: false }), }, run: (): void => undefined, }), createTestInjector({ options: { - path: { type: "string", alias: "p", hasSensitiveValue: true }, + output: { type: "string", alias: "o", hasSensitiveValue: true }, }, }), ); assert.deepEqual(command.dashedOptions, { - path: { type: "string", hasSensitiveValue: false, alias: "q" }, + output: { type: "string", hasSensitiveValue: false, alias: "q" }, }); }); @@ -819,8 +822,8 @@ describe("defineCommand", () => { it("warns when a declared option or alias shadows a CLI-wide one", () => { const testInjector = createTestInjector({ options: { - verbose: { type: "boolean" }, - path: { type: "string", alias: "p" }, + quiet: { type: "boolean" }, + output: { type: "string", alias: "o" }, }, }); @@ -828,8 +831,8 @@ describe("defineCommand", () => { defineCommand({ name: "dctestshadow", options: { - verbose: stringOption(), - output: stringOption({ alias: ["p", "o"] }), + quiet: stringOption(), + target: stringOption({ alias: ["o", "t"] }), fresh: booleanOption({ alias: "f" }), }, run: (): void => undefined, @@ -840,21 +843,21 @@ describe("defineCommand", () => { const logger: LoggerStub = testInjector.resolve("logger"); assert.include( logger.warnOutput, - "'--verbose' with the CLI option '--verbose'", + "'--quiet' with the CLI option '--quiet'", ); assert.include( logger.warnOutput, - "alias '-p' of '--output' with the CLI option '--path'", + "alias '-o' of '--target' with the CLI option '--output'", ); assert.notInclude(logger.warnOutput, "--fresh"); - assert.notInclude(logger.warnOutput, "'-o'"); + assert.notInclude(logger.warnOutput, "'-t'"); }); it("stays quiet when a command only redefines a CLI-wide option's default", () => { const testInjector = createTestInjector({ options: { watch: { type: "boolean" }, - path: { type: "string", alias: "p" }, + output: { type: "string", alias: "o" }, }, }); @@ -863,7 +866,7 @@ describe("defineCommand", () => { name: "dctestredeclare", options: { watch: booleanOption({ default: true }), - path: stringOption({ alias: "p" }), + output: stringOption({ alias: "o" }), }, run: (): void => undefined, }), @@ -1359,14 +1362,14 @@ describe("defineCommand", () => { }); it("validates the declared options and runs the command", async () => { - const testInjector = createCommandsServiceInjector({ verbose: true }); + const testInjector = createCommandsServiceInjector({ quiet: true }); let ran: any; runInInjectionContext(testInjector, () => registerCommand( defineCommand({ name: "dctest-e2e", - options: { verbose: booleanOption({ default: false }) }, + options: { quiet: booleanOption({ default: false }) }, params: "any", run: (context) => { ran = context; @@ -1380,10 +1383,10 @@ describe("defineCommand", () => { await commandsService.tryExecuteCommand("dctest-e2e", ["alpha"]); assert.deepEqual(validatedOptions, { - verbose: { type: "boolean", hasSensitiveValue: false, default: false }, + quiet: { type: "boolean", hasSensitiveValue: false, default: false }, }); assert.deepEqual(ran.args, ["alpha"]); - assert.deepEqual(ran.options, { verbose: true }); + assert.deepEqual(ran.options, { quiet: true }); }); it("rejects parameters when arguments are 'none'", async () => { @@ -3479,4 +3482,374 @@ describe("defineCommand", () => { assert.isTrue(await verdict); }); }); + + describe("option groups", () => { + describe("defineOptions", () => { + it("returns a token without a name that carries its schema", () => { + const schema = { watch: booleanOption() }; + const group = defineOptions(schema); + + assert.isTrue(isOptionsGroup(group)); + assert.instanceOf(group, InjectionToken); + assert.strictEqual(group.schema, schema); + assert.isUndefined(group.description); + assert.strictEqual(String(group), "option group (--watch)"); + assert.isFalse(isOptionsGroup(schema)); + assert.isFalse(isOptionsGroup(null)); + assert.isFalse(isOptionsGroup(new InjectionToken("dctest-grp-plain"))); + }); + + it("rejects an unusable schema or spec", () => { + assert.throws( + () => defineOptions(null), + /^Invalid option group: the schema must be an object keyed by the long option name.* Accepted form: defineOptions/, + ); + assert.throws( + () => defineOptions({ watch: { type: "bool" } }), + /^Invalid option group: option 'watch' has type 'bool'/, + ); + }); + + it("rejects a spelling two of its options would share", () => { + assert.throws( + () => + defineOptions({ + watch: booleanOption(), + wait: booleanOption({ alias: "watch" }), + }), + /^Invalid option group: alias '-watch' of '--wait' \(the group\) is already the spelling of '--watch' \(the group\)/, + ); + assert.throws( + () => + defineOptions({ + watch: booleanOption({ alias: "w" }), + w: booleanOption(), + }), + /^Invalid option group: option '--w' \(the group\) is already an alias of '--watch' \(the group\)/, + ); + }); + }); + + describe("injected values", () => { + const reader = (values: any) => ({ + readGroupOption: (optionName: string): any => values[optionName], + }); + + it("need no registration and are shared by the whole injector tree", () => { + const group = defineOptions({ watch: booleanOption() }); + const testInjector = createTestInjector(reader({ watch: true })); + + const fromChild = testInjector.createChild().get(group); + assert.isTrue(fromChild.watch); + assert.strictEqual(testInjector.get(group), fromChild); + }); + + it("are read from the options service when they are used", () => { + const group = defineOptions({ + watch: booleanOption({ default: true }), + device: stringOption(), + }); + const values: any = {}; + const testInjector = createTestInjector(reader(values)); + const injected = testInjector.get(group); + + assert.deepEqual({ ...injected }, { watch: true, device: undefined }); + values.watch = false; + values.device = "emulator-5554"; + assert.deepEqual( + { ...injected }, + { watch: false, device: "emulator-5554" }, + ); + }); + + it("cannot be written", () => { + const group = defineOptions({ watch: booleanOption() }); + const injected: any = createTestInjector(reader({})).get(group); + + assert.throws(() => { + "use strict"; + injected.watch = true; + }, TypeError); + }); + + it("give way to a registered value", () => { + const group = defineOptions({ watch: booleanOption() }); + const testInjector = createTestInjector(); + testInjector.register({ provide: group, useValue: { watch: true } }); + + assert.deepEqual(testInjector.get(group), { watch: true }); + }); + }); + + describe("options as a list", () => { + const runOptions = () => + defineOptions({ + watch: booleanOption({ default: true }), + device: stringOption({ alias: "d" }), + }); + + it("merges the groups and the inline specs onto ctx.options", async () => { + const RunOptions = runOptions(); + const testInjector = createTestInjector({ + watch: false, + device: "emulator-5554", + extra: true, + undeclared: "ignored", + }); + + let seen: any; + const command = createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-merge", + options: [RunOptions, { extra: booleanOption() }], + run: (ctx) => { + seen = ctx.options; + }, + }), + testInjector, + ); + await command.execute([]); + + assert.deepEqual(seen, { + watch: false, + device: "emulator-5554", + extra: true, + }); + }); + + it("compiles every part into dashedOptions", () => { + const RunOptions = runOptions(); + const command = createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-dashed", + options: [RunOptions, { extra: booleanOption() }], + run: (): void => undefined, + }), + createTestInjector(), + ); + + assert.deepEqual(command.dashedOptions, { + watch: { type: "boolean", hasSensitiveValue: false, default: true }, + device: { type: "string", hasSensitiveValue: false, alias: "d" }, + extra: { type: "boolean", hasSensitiveValue: false }, + }); + }); + }); + + describe("collisions", () => { + it("rejects one long name declared by two parts with different specs", () => { + const Shared = defineOptions({ + watch: booleanOption({ default: true }), + }); + const Other = defineOptions({ + watch: booleanOption(), + }); + + assert.throws( + () => + defineCommand({ + name: "dctest-grp-clash-inline", + options: [Shared, { watch: booleanOption() }], + run: (): void => undefined, + }), + /^Invalid command definition for 'dctest-grp-clash-inline': option '--watch' is declared by option group \(--watch\) and by the command's own options with different specs/, + ); + assert.throws( + () => + defineCommand({ + name: "dctest-grp-clash-groups", + options: [Shared, Other], + run: (): void => undefined, + }), + /option '--watch' is declared by option group \(--watch\) and by option group \(--watch\) with different specs/, + ); + }); + + it("treats a different alias, default or sensitivity as a different spec", () => { + const Output = defineOptions({ + output: stringOption({ alias: "o" }), + }); + + for (const redeclared of [ + stringOption({ alias: "O" }), + stringOption({ alias: "o", hasSensitiveValue: true }), + stringOption({ alias: "o", default: "dist" }), + ]) { + assert.throws( + () => + defineCommand({ + name: "dctest-grp-clash-spec", + options: [Output, { output: redeclared }], + run: (): void => undefined, + }), + /option '--output' is declared by option group \(--output\) and by the command's own options with different specs/, + ); + } + }); + + it("accepts the same spec declared by two parts", () => { + const Output = defineOptions({ + output: stringOption({ alias: "o" }), + }); + + const command = createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-same", + options: [Output, { output: stringOption({ alias: "o" }) }], + run: (): void => undefined, + }), + createTestInjector(), + ); + + assert.deepEqual(command.dashedOptions, { + output: { type: "string", hasSensitiveValue: false, alias: "o" }, + }); + }); + + it("rejects an alias of one part that is a spelling of another", () => { + const Output = defineOptions({ + output: stringOption({ alias: "o" }), + }); + + assert.throws( + () => + defineCommand({ + name: "dctest-grp-alias", + options: [Output, { target: stringOption({ alias: "output" }) }], + run: (): void => undefined, + }), + /alias '-output' of '--target' \(the command's own options\) is already the spelling of '--output' \(option group \(--output\)\)/, + ); + assert.throws( + () => + defineCommand({ + name: "dctest-grp-alias", + options: [Output, { o: booleanOption() }], + run: (): void => undefined, + }), + /option '--o' \(the command's own options\) is already an alias of '--output' \(option group \(--output\)\)/, + ); + }); + + it("applies the same rules to the Command() meta", () => { + const Watch = defineOptions({ + watch: booleanOption({ default: true }), + }); + + assert.throws( + () => + Command({ + name: "dctest-grp-clash-class", + options: [Watch, { watch: booleanOption() }], + }), + /^Invalid command definition for 'dctest-grp-clash-class': option '--watch' is declared by option group \(--watch\)/, + ); + }); + }); + + describe("process-level options", () => { + const compile = (options: any) => + createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-root", + options, + run: (): void => undefined, + }), + createTestInjector(), + ); + + it("refuses an inline option that redeclares a CliOptions name", () => { + assert.throws( + () => compile({ path: stringOption() }), + "Command 'dctest-grp-root': '--path' is a process-level option; list CliOptions under 'options', or inject it, instead of redeclaring it", + ); + }); + + it("refuses an alias that is a CliOptions shorthand", () => { + assert.throws( + () => compile({ project: stringOption({ alias: "p" }) }), + "Command 'dctest-grp-root': '-p' is a process-level option", + ); + }); + + it("refuses a group of the command's own that redeclares one", () => { + const Logging = defineOptions({ + verbose: booleanOption(), + }); + + assert.throws( + () => compile([Logging]), + "Command 'dctest-grp-root': '--verbose' is a process-level option", + ); + }); + + it("lets CliOptions itself be listed, reading its values onto ctx.options", async () => { + const testInjector = createTestInjector({ + verbose: true, + path: "/app", + output: "dist", + }); + + let seen: any; + const command = createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-root-listed", + options: [CliOptions, { output: stringOption() }], + run: (ctx) => { + seen = ctx.options; + }, + }), + testInjector, + ); + await command.execute([]); + + assert.sameMembers(Object.keys(seen), [ + ...Object.keys(CliOptions.schema), + "output", + ]); + assert.isTrue(seen.verbose); + assert.strictEqual(seen.path, "/app"); + assert.strictEqual(seen.output, "dist"); + assert.deepEqual(command.dashedOptions.path, { + type: "string", + hasSensitiveValue: true, + alias: "p", + }); + }); + }); + + describe("class form", () => { + it("types and merges this.options from a list of groups and specs", async () => { + const RunOptions = defineOptions({ + watch: booleanOption({ default: true }), + device: stringOption(), + }); + const testInjector = createTestInjector({ + watch: false, + device: "emulator-5554", + extra: true, + }); + const seen: any[] = []; + + class GroupedWidget extends Command({ + name: "dctest-grp-class", + options: [RunOptions, { extra: booleanOption({ default: false }) }], + }) { + public run(): void { + const watch: boolean = this.options.watch; + const extra: boolean = this.options.extra; + seen.push(watch, this.options.device, extra); + } + } + + const command = createCommandFromDefinition( + GroupedWidget.definition, + testInjector, + ); + await command.execute([]); + + assert.deepEqual(seen, [false, "emulator-5554", true]); + }); + }); + }); }); diff --git a/test/options.ts b/test/options.ts index e6e2557fd1..da10530b3a 100644 --- a/test/options.ts +++ b/test/options.ts @@ -10,6 +10,13 @@ import { } from "../lib/common/declarations"; import { OptionType } from "../lib/common/enums"; import * as _ from "lodash"; +import { + booleanOption, + defineOptions, + stringOption, +} from "../lib/common/define-command"; +import { CliOptions } from "../lib/common/contracts/cli-options"; +import { COMMAND_LINE_EXPECTED } from "../lib/common/contracts/command-line-expected"; let isExecutionStopped = false; let warnings: string[] = []; @@ -63,6 +70,77 @@ describe("options", () => { delete process.env.NS_STRICT_OPTIONS; }); + describe("option groups", () => { + const Group = defineOptions({ + release: booleanOption(), + device: stringOption({ default: "any" }), + }); + const argv = process.argv; + afterEach(() => { + process.argv = argv; + }); + + const setup = (args: string[], commandLine: boolean) => { + process.argv = ["node", "ns", ...args]; + testInjector.register({ + provide: COMMAND_LINE_EXPECTED, + useValue: commandLine, + }); + const injected = testInjector.get(Group); + const cli = testInjector.get(CliOptions); + testInjector.register("options", Options); + return { injected, cli, options: testInjector.resolve("options") }; + }; + + it("can be injected, but not read, before the command line is parsed", () => { + const { injected, options } = setup(["--release"], true); + + assert.throws( + () => injected.release, + /The option 'release' was read before the command line was parsed/, + ); + options.validateOptions({ device: { type: OptionType.String } }); + assert.isTrue(injected.release); + assert.strictEqual(injected.device, "any"); + }); + + it("keep the typed command's values when another command is validated", () => { + const { injected, options } = setup([], true); + options.validateOptions({ + device: { type: OptionType.String, default: "typed" }, + }); + options.validateOptions({ + device: { type: OptionType.String, default: "nested" }, + }); + + assert.strictEqual(options.device, "nested"); + assert.strictEqual(injected.device, "typed"); + }); + + it("do not see later writes to the options service", () => { + const { injected, options } = setup([], true); + options.validateOptions({ device: { type: OptionType.String } }); + options.device = "written"; + + assert.strictEqual(injected.device, "any"); + }); + + it("read the live values in a process without a command line", () => { + const { injected, options } = setup(["--release"], false); + + assert.isTrue(injected.release); + options.release = false; + assert.isFalse(injected.release); + }); + + it("make CliOptions readable from startup", () => { + const { cli } = setup(["--path", "app", "--log", "trace"], true); + + assert.strictEqual(cli.path, "app"); + assert.strictEqual(cli.log, "trace"); + }); + }); + describe("validateOptions", () => { it("breaks execution when option is not valid", () => { process.argv.push("--pathr"); diff --git a/test/type-fixtures/define-command-types.ts b/test/type-fixtures/define-command-types.ts index 6e6ac3282b..3051878064 100644 --- a/test/type-fixtures/define-command-types.ts +++ b/test/type-fixtures/define-command-types.ts @@ -11,6 +11,7 @@ import { booleanOption, Command, defineCommand, + defineOptions, numberOption, stringOption, } from "../../lib/common/define-command"; @@ -20,6 +21,7 @@ import { registerLazyCommand, } from "../../lib/common/services/command-definition-adapter"; import type { Injector } from "../../lib/common/di/injector"; +import { inject } from "../../lib/common/di/inject"; type IsExact = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 @@ -363,3 +365,51 @@ registerLazyCommand( "typefixture|class-vision2", () => require("./commands/clean").TypefixtureAliased, ); + +// An option group types its values off the same declaration at both ends: the +// command's ctx.options and whatever injects the group. +const TypefixtureRunOptions = defineOptions({ + watch: booleanOption({ default: true }), + device: stringOption(), +}); + +defineCommand({ + name: "typefixture|group", + options: [ + TypefixtureRunOptions, + { extra: booleanOption({ default: false }) }, + ], + run(ctx) { + expectExactType>(); + expectExactType>(); + expectExactType>(); + + const injected = inject(TypefixtureRunOptions); + expectExactType>(); + expectExactType>(); + // @ts-expect-error - the group's values hold the group's own keys only + injected.extra; + // @ts-expect-error - the group's values are read-only + injected.watch = true; + + // @ts-expect-error - neither the group nor the inline specs declare it + ctx.options.undeclared; + }, +}); + +class TypefixtureGroupClass extends Command({ + name: "typefixture|class-group", + options: [ + TypefixtureRunOptions, + { extra: booleanOption({ default: false }) }, + ], +}) { + run(): void { + expectExactType>(); + expectExactType>(); + expectExactType>(); + + // @ts-expect-error - neither the group nor the inline specs declare it + this.options.undeclared; + } +} From 9c9cefb4a96051c45d811e169309db3ecf5fc5b7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 11:21:06 -0300 Subject: [PATCH 3/4] refactor(android): read --aab through an option group The bundle validator helper is the worked example of a service moved off the options service. The five commands that declare the flag share its schema. --- lib/commands/build.ts | 3 ++- lib/commands/debug.ts | 3 ++- lib/commands/deploy.ts | 3 ++- lib/commands/run.ts | 3 ++- lib/commands/test.ts | 3 ++- lib/helpers/android-bundle-validator-helper.ts | 11 +++++++---- lib/option-groups/android-bundle-options.ts | 5 +++++ 7 files changed, 22 insertions(+), 9 deletions(-) create mode 100644 lib/option-groups/android-bundle-options.ts diff --git a/lib/commands/build.ts b/lib/commands/build.ts index 40f3ec2304..d39e5218e0 100644 --- a/lib/commands/build.ts +++ b/lib/commands/build.ts @@ -23,6 +23,7 @@ import { defineCommand, stringOption, } from "../common/define-command"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { ProjectData } from "../contracts/project-data"; @@ -38,7 +39,7 @@ const buildCommandOptions = { hmr: booleanOption({ default: false }), force: booleanOption(), release: booleanOption(), - aab: booleanOption(), + ...AndroidBundleOptions.schema, keyStorePath: stringOption(), keyStorePassword: stringOption(), keyStoreAlias: stringOption(), diff --git a/lib/commands/debug.ts b/lib/commands/debug.ts index 498a0737eb..d950b442a6 100644 --- a/lib/commands/debug.ts +++ b/lib/commands/debug.ts @@ -8,6 +8,7 @@ import { defineCommand, stringOption, } from "../common/define-command"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { hasValidAndroidSigning } from "../common/helpers"; import { ANDROID_APP_BUNDLE_SIGNING_ERROR_MESSAGE } from "../constants"; @@ -41,7 +42,7 @@ const debugCommandOptions = { ...platformSigningOptions, force: booleanOption(), release: booleanOption(), - aab: booleanOption(), + ...AndroidBundleOptions.schema, start: booleanOption(), emulator: booleanOption(), forDevice: booleanOption(), diff --git a/lib/commands/deploy.ts b/lib/commands/deploy.ts index fd3f280118..204f536d12 100644 --- a/lib/commands/deploy.ts +++ b/lib/commands/deploy.ts @@ -17,6 +17,7 @@ import { defineCommand, stringOption, } from "../common/define-command"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { ProjectData } from "../contracts/project-data"; @@ -26,7 +27,7 @@ const deployCommandOptions = { hmr: booleanOption({ default: false }), force: booleanOption(), release: booleanOption(), - aab: booleanOption(), + ...AndroidBundleOptions.schema, keyStorePath: stringOption(), keyStorePassword: stringOption(), keyStoreAlias: stringOption(), diff --git a/lib/commands/run.ts b/lib/commands/run.ts index 925bc298db..e872529ad1 100644 --- a/lib/commands/run.ts +++ b/lib/commands/run.ts @@ -8,6 +8,7 @@ import { defineCommand, stringOption, } from "../common/define-command"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { hasValidAndroidSigning } from "../common/helpers"; import { @@ -32,7 +33,7 @@ const runCommandOptions = { ...platformSigningOptions, force: booleanOption(), release: booleanOption(), - aab: booleanOption(), + ...AndroidBundleOptions.schema, keyStorePath: stringOption(), keyStorePassword: stringOption(), keyStoreAlias: stringOption(), diff --git a/lib/commands/test.ts b/lib/commands/test.ts index 73a3a28b27..7a37453900 100644 --- a/lib/commands/test.ts +++ b/lib/commands/test.ts @@ -10,6 +10,7 @@ import { defineCommand, stringOption, } from "../common/define-command"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { ErrorCodes } from "../common/enums"; import { hasValidAndroidSigning, isCIEnvironment } from "../common/helpers"; @@ -51,7 +52,7 @@ const testCommandOptions = { forDevice: booleanOption(), sdk: stringOption(), release: booleanOption(), - aab: booleanOption(), + ...AndroidBundleOptions.schema, keyStorePath: stringOption(), keyStorePassword: stringOption(), keyStoreAlias: stringOption(), diff --git a/lib/helpers/android-bundle-validator-helper.ts b/lib/helpers/android-bundle-validator-helper.ts index 1ee944b797..b59a492754 100644 --- a/lib/helpers/android-bundle-validator-helper.ts +++ b/lib/helpers/android-bundle-validator-helper.ts @@ -3,10 +3,12 @@ import { AndroidBundleValidatorMessages, PlatformTypes } from "../constants"; import { VersionValidatorHelper } from "./version-validator-helper"; import * as semver from "semver"; import { IProjectDataService, IProjectData } from "../definitions/project"; -import { IOptions, IAndroidBundleValidatorHelper } from "../declarations"; +import { IAndroidBundleValidatorHelper } from "../declarations"; import { IBuildData, IAndroidBuildData } from "../definitions/build"; import { IErrors } from "../common/declarations"; +import { inject } from "../common/di"; import { injector } from "../common/yok"; +import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; export class AndroidBundleValidatorHelper extends VersionValidatorHelper @@ -14,10 +16,11 @@ export class AndroidBundleValidatorHelper public static MIN_RUNTIME_VERSION = "5.0.0"; public static MIN_ANDROID_WITH_AAB_SUPPORT = "4.4.0"; + private options = inject(AndroidBundleOptions); + constructor( protected $projectData: IProjectData, protected $errors: IErrors, - protected $options: IOptions, protected $projectDataService: IProjectDataService, private $mobileHelper: Mobile.IMobileHelper ) { @@ -25,7 +28,7 @@ export class AndroidBundleValidatorHelper } public validateNoAab(): void { - if (this.$options.aab) { + if (this.options.aab) { this.$errors.failWithHelp( AndroidBundleValidatorMessages.AAB_NOT_SUPPORTED_BY_COMMNAND_MESSAGE ); @@ -33,7 +36,7 @@ export class AndroidBundleValidatorHelper } public validateRuntimeVersion(projectData: IProjectData): void { - if (this.$options.aab) { + if (this.options.aab) { const runtimePackage = this.$projectDataService.getRuntimePackage( projectData.projectDir, PlatformTypes.android diff --git a/lib/option-groups/android-bundle-options.ts b/lib/option-groups/android-bundle-options.ts new file mode 100644 index 0000000000..c492ddd689 --- /dev/null +++ b/lib/option-groups/android-bundle-options.ts @@ -0,0 +1,5 @@ +import { booleanOption, defineOptions } from "../common/define-command"; + +export const AndroidBundleOptions = defineOptions({ + aab: booleanOption(), +}); From 20775c536897d22c5db57142a9027d2ba107363c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Mon, 30 Nov 2026 13:01:33 -0300 Subject: [PATCH 4/4] fix(commands): take group values from the typed command only A command validated in process before the typed one, such as a canExecute check made while extensions load, fixed the values every option group then read. Only the typed command's own validation fixes them now. Option names and aliases that are Object.prototype members are accepted. --- lib/common/define-command.ts | 6 ++-- lib/common/services/commands-service.ts | 1 + lib/declarations.d.ts | 5 ++++ lib/options.ts | 5 ++-- test/commands-service.ts | 30 ++++++++++++++++--- test/define-command.ts | 15 ++++++++++ test/options.ts | 38 +++++++++++++++++++++---- 7 files changed, 86 insertions(+), 14 deletions(-) diff --git a/lib/common/define-command.ts b/lib/common/define-command.ts index 1ef1fb0297..2c727dedf9 100644 --- a/lib/common/define-command.ts +++ b/lib/common/define-command.ts @@ -247,8 +247,10 @@ export function resolveCommandOptions( } } - const schema: CommandOptionsSchema = {}; - const owners: IDictionary<{ optionName: string; source: string }> = {}; + // Null prototypes: an option may be called `constructor`. + const schema: CommandOptionsSchema = Object.create(null); + const owners: IDictionary<{ optionName: string; source: string }> = + Object.create(null); for (const { source, schema: partSchema } of parts) { for (const optionName of Object.keys(partSchema)) { const spec = partSchema[optionName]; diff --git a/lib/common/services/commands-service.ts b/lib/common/services/commands-service.ts index 50d25416c5..04ab1b8c71 100644 --- a/lib/common/services/commands-service.ts +++ b/lib/common/services/commands-service.ts @@ -263,6 +263,7 @@ export class CommandsService this.$options.validateOptions( dashedOptions, command && allowsUnknownOptions(command), + !this.isExecutingInProcess, ); } diff --git a/lib/declarations.d.ts b/lib/declarations.d.ts index 466f3830fe..d991028f54 100644 --- a/lib/declarations.d.ts +++ b/lib/declarations.d.ts @@ -614,9 +614,14 @@ interface IOptions IGenerateOptions, ITypingsOptions { argv: IYargArgv; + /** + * @param isCommandLine The options are those of the command the user typed, + * so option groups take their values from this parse. + */ validateOptions( commandSpecificDashedOptions?: IDictionary, allowUnknownOptions?: boolean, + isCommandLine?: boolean, ): void; options: IDictionary; shorthands: string[]; diff --git a/lib/options.ts b/lib/options.ts index 6734edccac..3395c70f01 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -266,6 +266,7 @@ export class Options implements OptionValueReader { public validateOptions( commandSpecificDashedOptions?: IDictionary, allowUnknownOptions?: boolean, + isCommandLine?: boolean, ): void { this.setupOptions(commandSpecificDashedOptions); @@ -325,9 +326,7 @@ export class Options implements OptionValueReader { } } - // The first command validated in a process is the one the user typed; - // commands dispatched in process come later and must not change it. - if (!this.commandLineArgv) { + if (isCommandLine && !this.commandLineArgv) { this.commandLineArgv = _.cloneDeep(this.argv); } } diff --git a/test/commands-service.ts b/test/commands-service.ts index d65e4671a4..028624ed20 100644 --- a/test/commands-service.ts +++ b/test/commands-service.ts @@ -6,12 +6,20 @@ import { OptionType } from "../lib/common/enums"; interface ITestSetup { injector: Yok; - validatedWith: { called: boolean; allowUnknown?: boolean }; + validatedWith: { + called: boolean; + allowUnknown?: boolean; + isCommandLine?: boolean; + }; } function createTestInjector(command: ICommand): ITestSetup { const injector = new Yok(); - const validatedWith: { called: boolean; allowUnknown?: boolean } = { + const validatedWith: { + called: boolean; + allowUnknown?: boolean; + isCommandLine?: boolean; + } = { called: false, }; @@ -26,9 +34,14 @@ function createTestInjector(command: ICommand): ITestSetup { injector.register("hooksService", {}); injector.register("logger", { warn: (): void => undefined }); injector.register("options", { - validateOptions: (dashedOptions: any, allowUnknown?: boolean): void => { + validateOptions: ( + dashedOptions: any, + allowUnknown?: boolean, + isCommandLine?: boolean, + ): void => { validatedWith.called = true; validatedWith.allowUnknown = allowUnknown; + validatedWith.isCommandLine = isCommandLine; }, }); injector.register("staticConfig", {}); @@ -43,6 +56,7 @@ function createTestInjector(command: ICommand): ITestSetup { /** What an in-process dispatch touched, recorded off the collaborators. */ interface IDispatchRecord { primedWith: { dashedOptions: any; allowUnknown?: boolean }[]; + commandLineParses: number; hooks: string[]; analytics: string[]; executed: string[][]; @@ -62,6 +76,7 @@ function createDispatchInjector(command: ICommand): { const injector = new Yok(); const record: IDispatchRecord = { primedWith: [], + commandLineParses: 0, hooks: [], analytics: [], executed: [], @@ -74,7 +89,12 @@ function createDispatchInjector(command: ICommand): { const options: any = { options: { watch: cliOption }, argv: initialArgv, - validateOptions(dashedOptions: any, allowUnknown?: boolean): void { + validateOptions( + dashedOptions: any, + allowUnknown?: boolean, + isCommandLine?: boolean, + ): void { + record.commandLineParses += isCommandLine ? 1 : 0; record.primedWith.push({ dashedOptions, allowUnknown }); // The real parser merges the command's declarations into the shared // table and re-parses, replacing both. @@ -173,6 +193,7 @@ describe("commands-service", () => { await (service).tryExecuteCommandAction("info", []); assert.isTrue(validatedWith.called); + assert.isTrue(validatedWith.isCommandLine); }); it("tolerates unknown options for a command that forwards them", async () => { @@ -200,6 +221,7 @@ describe("commands-service", () => { await service.runCommand("open|ios"); + assert.equal(record.commandLineParses, 0); assert.deepEqual(record.primedWith, [ { dashedOptions: command.dashedOptions, allowUnknown: true }, ]); diff --git a/test/define-command.ts b/test/define-command.ts index 3c0e35d8e6..96557600e0 100644 --- a/test/define-command.ts +++ b/test/define-command.ts @@ -3510,6 +3510,21 @@ describe("defineCommand", () => { ); }); + it("accepts spellings that are Object.prototype members", () => { + assert.doesNotThrow(() => + defineOptions({ + constructor: booleanOption({ alias: "toString" }), + }), + ); + assert.doesNotThrow(() => + defineCommand({ + name: "dctest-grp-proto", + options: { valueOf: booleanOption() }, + run: (): void => undefined, + }), + ); + }); + it("rejects a spelling two of its options would share", () => { assert.throws( () => diff --git a/test/options.ts b/test/options.ts index da10530b3a..b12aa4c88f 100644 --- a/test/options.ts +++ b/test/options.ts @@ -99,16 +99,22 @@ describe("options", () => { () => injected.release, /The option 'release' was read before the command line was parsed/, ); - options.validateOptions({ device: { type: OptionType.String } }); + options.validateOptions( + { device: { type: OptionType.String } }, + false, + true, + ); assert.isTrue(injected.release); assert.strictEqual(injected.device, "any"); }); it("keep the typed command's values when another command is validated", () => { const { injected, options } = setup([], true); - options.validateOptions({ - device: { type: OptionType.String, default: "typed" }, - }); + options.validateOptions( + { device: { type: OptionType.String, default: "typed" } }, + false, + true, + ); options.validateOptions({ device: { type: OptionType.String, default: "nested" }, }); @@ -119,12 +125,34 @@ describe("options", () => { it("do not see later writes to the options service", () => { const { injected, options } = setup([], true); - options.validateOptions({ device: { type: OptionType.String } }); + options.validateOptions( + { device: { type: OptionType.String } }, + false, + true, + ); options.device = "written"; assert.strictEqual(injected.device, "any"); }); + it("ignore a command validated before the typed one", () => { + const { injected, options } = setup([], true); + options.validateOptions({ + device: { type: OptionType.String, default: "probe" }, + }); + + assert.throws( + () => injected.device, + /before the command line was parsed/, + ); + options.validateOptions( + { device: { type: OptionType.String, default: "typed" } }, + false, + true, + ); + assert.strictEqual(injected.device, "typed"); + }); + it("read the live values in a process without a command line", () => { const { injected, options } = setup(["--release"], false);