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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 164 additions & 12 deletions defining-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --------------- | ----------------------- | ----------------------- |
Expand Down Expand Up @@ -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

Expand All @@ -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: <problem>.` 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
Expand 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

Expand Down Expand Up @@ -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).
Expand Down
20 changes: 20 additions & 0 deletions dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Clock>({
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`
------------------------------------

Expand Down
3 changes: 2 additions & 1 deletion lib/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -38,7 +39,7 @@ const buildCommandOptions = {
hmr: booleanOption({ default: false }),
force: booleanOption(),
release: booleanOption(),
aab: booleanOption(),
...AndroidBundleOptions.schema,
keyStorePath: stringOption(),
keyStorePassword: stringOption(),
keyStoreAlias: stringOption(),
Expand Down
50 changes: 27 additions & 23 deletions lib/commands/create-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand Down Expand Up @@ -217,7 +221,7 @@ const flavorTemplates: { [flavorName: string]: () => ITemplateChoice[] } = {

/** The template a flavor flag selects, without asking anything. */
function selectTemplateFromOptions(
options: CommandOptionValues<typeof createProjectCommandOptions>,
options: OptionValuesOf<typeof createProjectCommandOptions>,
): string {
if (options["vision-ng"] || (options.vision && options.ng)) {
return constants.RESERVED_TEMPLATE_NAMES["vision-ng"];
Expand Down
3 changes: 2 additions & 1 deletion lib/commands/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -41,7 +42,7 @@ const debugCommandOptions = {
...platformSigningOptions,
force: booleanOption(),
release: booleanOption(),
aab: booleanOption(),
...AndroidBundleOptions.schema,
start: booleanOption(),
emulator: booleanOption(),
forDevice: booleanOption(),
Expand Down
3 changes: 2 additions & 1 deletion lib/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -26,7 +27,7 @@ const deployCommandOptions = {
hmr: booleanOption({ default: false }),
force: booleanOption(),
release: booleanOption(),
aab: booleanOption(),
...AndroidBundleOptions.schema,
keyStorePath: stringOption(),
keyStorePassword: stringOption(),
keyStoreAlias: stringOption(),
Expand Down
Loading
Loading