Skip to content

Commit acc32e1

Browse files
authored
feat(commands): option groups and self-providing injection tokens (#6156)
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. A group provides itself at the root and reads its values lazily: injecting it before the command line is parsed is fine, reading it that early is an error. CliOptions is the group of process-level options, readable from startup. An InjectionToken may carry a factory, and then needs no registration. Its description is optional; a token without one resolves by identity. AndroidBundleValidatorHelper reads --aab through a group, as the worked example.
1 parent 5a9a505 commit acc32e1

33 files changed

Lines changed: 1564 additions & 226 deletions

‎defining-commands.md‎

Lines changed: 164 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,9 @@ Options
102102
-------
103103

104104
`options` is a schema keyed by the long option name — `output` is passed as
105-
`--output`. Declare each entry with one of the five helpers, which fix the
106-
value type:
105+
`--output`. It may also be a list of option groups and such schemas; see
106+
[Option groups](#option-groups). Declare each entry with one of the five
107+
helpers, which fix the value type:
107108

108109
| Helper | Declared with `default` | Declared without |
109110
| --------------- | ----------------------- | ----------------------- |
@@ -153,9 +154,12 @@ options: {
153154
The schema types `ctx.options` and nothing else: `ctx.options` carries exactly
154155
the declared keys, and a typo is a compile error. There is deliberately no
155156
"give me everything" escape hatch — a command declares every option it reads,
156-
CLI-wide ones (`--release`, `--path`, `--bundle`, …) included. Declaring one
157+
CLI-wide ones (`--release`, `--watch`, `--bundle`, …) included. Declaring one
157158
that the CLI already knows is supported and carries its value through to
158-
`ctx.options` exactly as a command-specific one does.
159+
`ctx.options` exactly as a command-specific one does. The process-level
160+
options (`--path`, `--log`, `--verbose` and the rest of `CliOptions`) are the
161+
exception: a command lists their group instead of redeclaring them. See
162+
[Process-level options](#process-level-options-clioptions).
159163

160164
### Sharing a schema between commands
161165

@@ -170,9 +174,108 @@ const buildOptions = {
170174
} satisfies CommandOptionsSchema;
171175
```
172176

177+
### Option groups
178+
179+
`defineOptions(schema)` declares an option group: a schema that is also an
180+
injection token. A command lists groups under `options`, next to inline
181+
schemas:
182+
183+
```ts
184+
import {
185+
booleanOption,
186+
defineCommand,
187+
defineOptions,
188+
stringOption,
189+
} from "nativescript/contracts";
190+
191+
export const WidgetOptions = defineOptions({
192+
theme: stringOption(),
193+
compact: booleanOption({ default: false }),
194+
});
195+
196+
export default defineCommand({
197+
name: "widget|add",
198+
options: [WidgetOptions, { output: stringOption({ alias: "o" }) }],
199+
run(ctx) {
200+
// ctx.options -> { theme: string | undefined; compact: boolean;
201+
// output: string | undefined }
202+
},
203+
});
204+
```
205+
206+
`ctx.options` is typed as the merged values of every part. The class form
207+
takes the same list, and types `this.options` the same way. A command that
208+
keeps a single schema object can spread a group's: `...WidgetOptions.schema`.
209+
210+
A group has no name: the exported object is the token, so declare it once and
211+
import it wherever it is listed or injected.
212+
213+
`defineOptions` validates the schema where it is written, as `defineCommand`
214+
does, and reports a problem as `Invalid option group: <problem>.` followed by
215+
the accepted form.
216+
217+
### Injecting a group
218+
219+
A service injects the group and reads the values of the command the user
220+
typed. The group provides itself at the root, so it needs no registration and
221+
the service stays a root singleton:
222+
223+
```ts
224+
class WidgetRenderer {
225+
private options = inject(WidgetOptions);
226+
227+
render() {
228+
if (this.options.compact) { /* … */ }
229+
}
230+
}
231+
```
232+
233+
- **Inject at any time, read once the command line is parsed.** Many services
234+
are built before the typed command's options are parsed. Holding the group is
235+
fine; reading a property that early throws `The option 'compact' was read
236+
before the command line was parsed`. So keep the object and read it in the
237+
method that needs it. Do not destructure it in a field or a constructor.
238+
- **The values never change.** They are fixed when the typed command is parsed,
239+
are read-only, and are the same in every later callback. Assigning to the
240+
options service does not change them.
241+
- **A command run in process does not change them.** Its own `ctx.options`
242+
holds its own values and defaults; a service still reads the typed command's.
243+
A command that needs a service to act on other values passes them to it.
244+
- **An option that was not given** reads as the group's `default`. When the
245+
typed command declares the option, its declaration decides.
246+
- **A process that uses the CLI as a library** has no typed command, so reading
247+
never throws and returns the options service's current value.
248+
249+
Prefer a parameter when the method already receives a data object that can
250+
carry the value; inject a group where passing it would mean threading it
251+
through callers that do not use it.
252+
253+
In a test, provide the value: `injector.register({ provide: WidgetOptions,
254+
useValue: { compact: true } })`.
255+
256+
### Collisions between parts
257+
258+
A spelling is an option's long name or one of its aliases. One spelling may
259+
appear in several parts of `options` only when every part declares it with an
260+
identical spec: the same type, `default`, `alias` and `hasSensitiveValue`.
261+
`description` is not compared. An alias may not equal another option's name
262+
or alias.
263+
264+
`defineCommand` and `Command()` check this when they are called, and
265+
`defineOptions` checks it within its own schema. The message names both
266+
declarations:
267+
268+
```
269+
Invalid command definition for 'widget|add': option '--compact' is declared
270+
by option group (--theme, --compact) and by the command's own options with
271+
different specs.
272+
```
273+
274+
followed by the accepted form.
275+
173276
### Redeclaring a CLI-wide option, and shadowing one
174277

175-
`--verbose`, `--path`, `--log`, `--release`, `--env` and friends are declared by
278+
`--release`, `--env`, `--watch`, `--device` and friends are declared by
176279
the CLI itself. A command's declaration is merged over the CLI-wide dictionary
177280
for the duration of that command, and that merge is the sanctioned way to give
178281
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
190293
spelling _means_:
191294

192295
- a declared option whose name matches a CLI-wide one but whose type differs —
193-
`verbose: stringOption()` against the CLI's boolean `--verbose`;
296+
`release: stringOption()` against the CLI's boolean `--release`;
194297
- an alias that belongs to a _different_ CLI-wide option — `output:
195-
stringOption({ alias: "p" })` steals `--path`'s shorthand. Restating an
196-
option's own shorthand (`path: stringOption({ alias: "p" })`) is fine.
298+
stringOption({ alias: "f" })` steals `--force`'s shorthand. Restating an
299+
option's own shorthand (`force: booleanOption({ alias: "f" })`) is fine.
197300

198301
A redeclaration that leaves `alias`, `default` or `hasSensitiveValue` unset
199-
keeps what the CLI-wide declaration carries for them, so `path: stringOption()`
200-
still answers to `-p` and stays out of the logs; set one only to change it.
302+
keeps what the CLI-wide declaration carries for them, so `release:
303+
booleanOption()` still answers to `-r`, and `device: stringOption()` stays out
304+
of the logs; set one only to change it.
305+
306+
None of this applies to the process-level options. Redeclaring one of those is
307+
an error, not a warning.
308+
309+
### Process-level options: `CliOptions`
310+
311+
`CliOptions` is the group of options the CLI parses once at startup, before a
312+
command is chosen: `--log`, `--verbose`, `--version` (`-v`), `--help` (`-h`),
313+
`--profileDir`, `--analyticsClient`, `--path` (`-p`) and `--config` (`-c`).
314+
The services that run for every command read them: the logger, analytics,
315+
project resolution. Its values can be read from startup, before a command's
316+
options are parsed:
317+
318+
```ts
319+
import { CliOptions, inject } from "nativescript/contracts";
320+
321+
class ProjectLocator {
322+
private cli = inject(CliOptions);
323+
324+
public locate(): string {
325+
return this.cli.path || process.cwd();
326+
}
327+
}
328+
```
329+
330+
A command may not redeclare any of these spellings, as a name or as an alias.
331+
The CLI refuses the command when it compiles it, on the first resolution of a
332+
registered command or when `runCommand` is given the definition:
333+
334+
```
335+
Command 'widget|add': '--path' is a process-level option; list CliOptions under 'options', or inject it, instead of redeclaring it
336+
```
337+
338+
To have the values on `ctx.options`, list the group itself. That is not a
339+
redeclaration: it reads the same declaration. `install` does this:
340+
341+
```ts
342+
const installCommandOptions = [
343+
CliOptions,
344+
{
345+
frameworkPath: stringOption(),
346+
disableNpmInstall: booleanOption(),
347+
ignoreScripts: booleanOption(),
348+
} satisfies CommandOptionsSchema,
349+
] satisfies CommandOptionsInput;
350+
```
351+
352+
`ctx.options.path` is then `string | undefined`.
201353

202354
### How validation behaves
203355

@@ -358,8 +510,8 @@ The run context
358510
declare, `{}` when there are none. It is spelled `params` because
359511
`arguments` is a reserved binding name in strict mode, so a destructuring
360512
`const { args, arguments } = ctx` would not even parse.
361-
- `ctx.options` — the current value of each declared option, read at the moment
362-
the command executes.
513+
- `ctx.options` — the value of each option the command declares, its groups and
514+
inline schemas merged, read when the invocation opens.
363515
- `ctx.injector` — this invocation's injector, a child of the one the command
364516
was registered against; see
365517
[Injection, and the first `await`](#injection-and-the-first-await).

‎dependency-injection.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,26 @@ Prefer a `@Contract` class when the dependency is a service: it also carries
102102
the service's shape. Reach for `InjectionToken` only when there is nothing to
103103
decorate.
104104

105+
### Tokens that provide themselves
106+
107+
A token may carry a `factory`, and then needs no registration:
108+
109+
```ts
110+
export const CLOCK = new InjectionToken<Clock>({
111+
factory: () => new SystemClock(inject(TimeZone)),
112+
});
113+
```
114+
115+
The factory runs the first time the token is resolved and nothing provides it.
116+
It runs once, in the root injector's injection context, and the root keeps the
117+
value: every injector of the tree shares it, whichever asked first. A provider
118+
registered for the token, at the root or in a child, is used instead, which is
119+
how a test replaces it.
120+
121+
The description is optional. A token without one has no string spelling and
122+
resolves by identity only, and a duplicated copy of it is a different token.
123+
`new InjectionToken("name", { factory })` has both.
124+
105125
Resolving: `inject()` and `Injector`
106126
------------------------------------
107127

‎lib/commands/build.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
defineCommand,
2424
stringOption,
2525
} from "../common/define-command";
26+
import { AndroidBundleOptions } from "../option-groups/android-bundle-options";
2627
import { inject } from "../common/di";
2728
import { ProjectData } from "../contracts/project-data";
2829

@@ -38,7 +39,7 @@ const buildCommandOptions = {
3839
hmr: booleanOption({ default: false }),
3940
force: booleanOption(),
4041
release: booleanOption(),
41-
aab: booleanOption(),
42+
...AndroidBundleOptions.schema,
4243
keyStorePath: stringOption(),
4344
keyStorePassword: stringOption(),
4445
keyStoreAlias: stringOption(),

‎lib/commands/create-project.ts‎

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ import { color } from "../color";
33
import {
44
booleanOption,
55
Command,
6+
CommandOptionsInput,
67
CommandOptionsSchema,
7-
CommandOptionValues,
8+
OptionValuesOf,
89
stringOption,
910
} from "../common/define-command";
11+
import { CliOptions } from "../common/contracts/cli-options";
1012
import { inject } from "../common/di";
1113
import { isInteractive } from "../common/helpers";
1214
import * as constants from "../constants";
@@ -27,27 +29,29 @@ const TABS_TEMPLATE_KEY = "Tabs";
2729
const TABS_TEMPLATE_DESCRIPTION =
2830
"An app with pre-built pages that uses tabs for navigation";
2931

30-
const createProjectCommandOptions = {
31-
js: booleanOption(),
32-
ng: booleanOption(),
33-
react: booleanOption(),
34-
solid: booleanOption(),
35-
svelte: booleanOption(),
36-
tsc: booleanOption(),
37-
vue: booleanOption(),
38-
vuejs: booleanOption(),
39-
vision: booleanOption(),
40-
"vision-ng": booleanOption(),
41-
"vision-react": booleanOption(),
42-
"vision-solid": booleanOption(),
43-
"vision-svelte": booleanOption(),
44-
"vision-vue": booleanOption(),
45-
template: stringOption(),
46-
appid: stringOption(),
47-
path: stringOption(),
48-
force: booleanOption(),
49-
ignoreScripts: booleanOption(),
50-
} satisfies CommandOptionsSchema;
32+
const createProjectCommandOptions = [
33+
CliOptions,
34+
{
35+
js: booleanOption(),
36+
ng: booleanOption(),
37+
react: booleanOption(),
38+
solid: booleanOption(),
39+
svelte: booleanOption(),
40+
tsc: booleanOption(),
41+
vue: booleanOption(),
42+
vuejs: booleanOption(),
43+
vision: booleanOption(),
44+
"vision-ng": booleanOption(),
45+
"vision-react": booleanOption(),
46+
"vision-solid": booleanOption(),
47+
"vision-svelte": booleanOption(),
48+
"vision-vue": booleanOption(),
49+
template: stringOption(),
50+
appid: stringOption(),
51+
force: booleanOption(),
52+
ignoreScripts: booleanOption(),
53+
} satisfies CommandOptionsSchema,
54+
] satisfies CommandOptionsInput;
5155

5256
interface ITemplateChoice {
5357
key?: string;
@@ -217,7 +221,7 @@ const flavorTemplates: { [flavorName: string]: () => ITemplateChoice[] } = {
217221

218222
/** The template a flavor flag selects, without asking anything. */
219223
function selectTemplateFromOptions(
220-
options: CommandOptionValues<typeof createProjectCommandOptions>,
224+
options: OptionValuesOf<typeof createProjectCommandOptions>,
221225
): string {
222226
if (options["vision-ng"] || (options.vision && options.ng)) {
223227
return constants.RESERVED_TEMPLATE_NAMES["vision-ng"];

‎lib/commands/debug.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
defineCommand,
99
stringOption,
1010
} from "../common/define-command";
11+
import { AndroidBundleOptions } from "../option-groups/android-bundle-options";
1112
import { inject } from "../common/di";
1213
import { hasValidAndroidSigning } from "../common/helpers";
1314
import { ANDROID_APP_BUNDLE_SIGNING_ERROR_MESSAGE } from "../constants";
@@ -41,7 +42,7 @@ const debugCommandOptions = {
4142
...platformSigningOptions,
4243
force: booleanOption(),
4344
release: booleanOption(),
44-
aab: booleanOption(),
45+
...AndroidBundleOptions.schema,
4546
start: booleanOption(),
4647
emulator: booleanOption(),
4748
forDevice: booleanOption(),

‎lib/commands/deploy.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
defineCommand,
1818
stringOption,
1919
} from "../common/define-command";
20+
import { AndroidBundleOptions } from "../option-groups/android-bundle-options";
2021
import { inject } from "../common/di";
2122
import { ProjectData } from "../contracts/project-data";
2223

@@ -26,7 +27,7 @@ const deployCommandOptions = {
2627
hmr: booleanOption({ default: false }),
2728
force: booleanOption(),
2829
release: booleanOption(),
29-
aab: booleanOption(),
30+
...AndroidBundleOptions.schema,
3031
keyStorePath: stringOption(),
3132
keyStorePassword: stringOption(),
3233
keyStoreAlias: stringOption(),

0 commit comments

Comments
 (0)