diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md index 04fd6fa..5c2d8f8 100644 --- a/.changeset/first-release-cli.md +++ b/.changeset/first-release-cli.md @@ -4,6 +4,7 @@ First release of the Druxt command-line tool, with the binary `drx`. -- `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. +- `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. It warns when the commands the starter needs are not on `PATH`. +- `drx module list`, `drx module search` and `drx module info` read the Druxt module registry, and in a project show what is installed and whether each module's range admits the Druxt there. - `drx info` prints the versions of the CLI, Node and the packages of each part of a project. - The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/README.md b/README.md index 17c1f4c..f2b80bc 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,44 @@ Prints the versions of the CLI and Node. Inside a project it adds the layout and Outside a project it says so and prints the two versions. +### `drx module list` + +Lists the modules in the Druxt module registry: name, package, type, status and the Druxt versions each works with. + +```text +Name Package Type Status Druxt +auth druxt-auth official stable unknown +blocks druxt-blocks official stable ^0.25.1 +``` + +Inside a project it adds two columns for the frontend part: + +| Column | What it shows | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Installed` | The installed version, `declared` when `package.json` asks for the package and it is not installed, or `no` | +| `Compatible` | `yes` or `no` when the module's range can be compared with the part's Druxt version, and `unknown` when the module states no range or the part has no Druxt | + +The Druxt version compared is the one installed in the part, or the range the part asks for when none is installed. A module whose range is `unknown` or not stated is shown as `unknown`, never as compatible. + +| Option | What it does | +| ------------------------- | --------------------------------------------------------------- | +| `--all` | Include archived modules | +| `--type ` | Only modules of this type, such as `official` or `contrib` | +| `--category ` | Only modules in this category | +| `--module-registry ` | A module registry: a URL, or a name from the user configuration | +| `--refresh` | Read the registry again even when the cached copy is fresh | +| `--json` | Print the result as JSON on stdout | + +### `drx module search ` + +The same table, for the modules whose name, package name or description contains the text. Case is ignored. It takes the options of `drx module list`. + +### `drx module info ` + +Shows one module, found by its registry name or its package name: the package, type, status, category, Druxt range, repository and website, and the backend modules it needs, with the ones that are part of Drupal core marked. When the registry marks no module as core, the text says so and `core` is `null` in the JSON. It is `false` only in a registry that marks the modules that are core. Inside a project it adds the installed version and the compatibility. It takes `--module-registry`, `--refresh` and `--json`. + +A name that matches nothing exits with 1 and prints the closest names. + ### `drx --help`, `drx --help`, `drx --version` Usage for the CLI or one command, and the version. @@ -136,7 +174,8 @@ A registry is a URL that answers `/.json` for each starter, in the format ], "requires": { "node": "16.18.1", - "tools": ["PHP 8.3 or newer with Composer, or DDEV"] + "tools": ["PHP 8.3 or newer with Composer, or DDEV"], + "commands": [["php", "composer"], ["ddev"]] }, "maintained": "2026-11-15", "default": true, @@ -151,34 +190,63 @@ A registry is a URL that answers `/.json` for each starter, in the format `name`, `tar`, `defaultDir`, `url`, `subdir` and `headers` are giget's fields. giget ignores the `druxt` object, so the same file works with `GIGET_REGISTRY= npx giget quickstart`. -| Key in `druxt` | What it holds | -| ---------------- | -------------------------------------------------------------------------- | -| `line` | The Druxt release line | -| `layout` | The layout the starter has | -| `parts` | The parts of the starter, as in the project configuration | -| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | -| `requires.tools` | What else the site needs, each as a phrase to show the user | -| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | -| `default` | `true` for the starter `init` uses when none is named | -| `steps` | Optional. The commands to run in the new site, in order | -| `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one | -| `install.notes` | Optional. Lines printed under "Note" after an install | - -`index.json` is `{ "starters": ["quickstart"] }`. +| Key in `druxt` | What it holds | +| ------------------- | -------------------------------------------------------------------------- | +| `line` | The Druxt release line | +| `layout` | The layout the starter has | +| `parts` | The parts of the starter, as in the project configuration | +| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | +| `requires.tools` | What else the site needs, each as a phrase to show the user | +| `requires.commands` | Optional. The commands the site needs on `PATH`, as a list of alternatives | +| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | +| `default` | `true` for the starter `init` uses when none is named | +| `steps` | Optional. The commands to run in the new site, in order | +| `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one | +| `install.notes` | Optional. Lines printed under "Note" after an install | + +`index.json` is `{ "revision": 1, "starters": ["quickstart"] }`. The revision is a whole number that goes up whenever the entries gain something a version of `drx` depends on. A `drx` whose bundled copy has a higher revision than the default registry reads the bundled copy, so a build made ahead of what is published keeps working. + +`requires.commands` is a list of alternatives, and each alternative is a list of command names. The site can be set up when every command of one alternative is on `PATH`. `[["php", "composer"], ["ddev"]]` reads as `php` and `composer`, or `ddev`. A name is a bare command, and an entry with a path or arguments in one is rejected. + +`init` looks each command up on `PATH` without running it. On Windows it tries the extensions in `PATHEXT`. When no alternative is complete it prints one warning naming the missing commands, and still creates the site: + +```text +Warning: The quickstart starter needs php and composer, or ddev. Not found on PATH: php, composer, ddev. Install the commands of one alternative before you set up the site. +``` + +With `--json` the result has a `commands` object: `satisfied`, `alternatives`, `found` and `missing`. It is `null` for an entry with no `requires.commands`, which is not checked. `init` checks an entry before it downloads anything, and fails with a message naming the field that is wrong. It warns when the starter was last maintained more than a year ago, and when the running Node is not the one the starter needs. The package includes a copy of the public registry. When the public registry cannot be read, `init` uses the copy and says so. A registry you name with `--registry` is never replaced by the copy. +## The module registry + +The module commands read `https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json`, which the [druxt/modules](https://github.com/druxt/modules) repository publishes. The CLI reads `schemaVersion` 1. It refuses any other version with a message saying so, and ignores fields it has no use for. + +The names in an entry become arguments of a package manager or a backend tool, so each is checked as the registry is read. A package name has to be one npm takes, and the name of a Drupal module has to be a machine name. Anything else, such as a name that starts with a hyphen, makes the registry invalid, and the message names the entry and the field. + +The registry is cached on disk: + +- A copy under an hour old is used without a request. `--refresh` reads the registry anyway. +- An older copy is replaced by a new read. +- When the registry cannot be read, the copy is used whatever its age, and the command says so and how old it is. +- With no copy and no registry, the command fails. + +The copy is kept in `~/.cache/drx`, or under `XDG_CACHE_HOME` when that is set. `DRX_CACHE_DIR` names another directory. + ## The user configuration -`~/.config/drx/config.json` names registries and sources of your own. `DRX_CONFIG` points at another file, and `XDG_CONFIG_HOME` is used when it is set. +`~/.config/drx/config.json` names starter registries, module registries and sources of your own. `DRX_CONFIG` points at another file, and `XDG_CONFIG_HOME` is used when it is set. ```json { "registries": { "team": "https://example.com/starters" }, + "moduleRegistries": { + "team": "https://example.com/modules.json" + }, "sources": { "next": { "type": "npm", "tag": "next" }, "branch": { "type": "git", "url": "https://example.com/druxt.git", "ref": "main" } @@ -187,14 +255,18 @@ The package includes a copy of the public registry. When the public registry can ``` - `--registry team` reads starters from that URL. `GIGET_AUTH` is giget's own variable, and giget sends it as a bearer token with every tarball it downloads. The CLI also sends it to a registry you name, and never to the public registry. +- `--module-registry team` reads modules from that URL, with `GIGET_AUTH` sent to it in the same way. - `--source` takes `npm`, `git:#`, or a name defined here. Only `npm` creates a site in this version. The others are read and answer that they are not available yet. ## Not there yet - The `split` and `workspace` layouts. `--layout` accepts them and fails with a message. - Sources other than `npm`. -- Adding a module, making a wrapper component and upgrading a site. +- `drx module add`, `drx module remove` and `drx module configure`. The commands exist and fail with a message. +- Making a wrapper component and upgrading a site. - Kinds other than `nuxt` and `drupal`. +- A version check of the commands a starter needs. `init` checks that `php` is on `PATH`, not that it is 8.3 or newer. +- The same check in `drx info`. A project does not record what its starter requires, so `info` would have to read the registry again. - A published public registry. Until this repository is public, `init` reads the copy in the package. ## Development diff --git a/package-lock.json b/package-lock.json index bf3aa7f..2fa3220 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@commitlint/config-conventional": "21.2.4", "@eslint/js": "10.0.1", "@types/node": "24.19.2", + "@types/semver": "7.8.0", "@vitest/coverage-v8": "5.1.0", "cspell": "10.5.1", "eslint": "10.15.0", @@ -2901,6 +2902,13 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/unist": { "version": "2.0.11", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", @@ -6845,7 +6853,6 @@ "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -7529,7 +7536,8 @@ "@clack/prompts": "^1.9.0", "c12": "^3.3.4", "citty": "^0.2.2", - "giget": "^3.3.1" + "giget": "^3.3.1", + "semver": "^7.8.6" }, "bin": { "drx": "dist/bin.js" diff --git a/package.json b/package.json index 7df1050..23d4d46 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "@commitlint/config-conventional": "21.2.4", "@eslint/js": "10.0.1", "@types/node": "24.19.2", + "@types/semver": "7.8.0", "@vitest/coverage-v8": "5.1.0", "cspell": "10.5.1", "eslint": "10.15.0", diff --git a/packages/cli/README.md b/packages/cli/README.md index 335895d..215d0ac 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -9,10 +9,11 @@ npx @druxt/cli info The binary is `drx`. Install the package in a project to use that name: `npm install -D @druxt/cli`, then `drx ` in a package script. `npx drx` without the package installed downloads another package that holds the name on npm. -| Command | What it does | -| ---------------- | ------------------------------------------------------------------------- | -| `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | -| `drx info` | Prints the versions of the CLI, Node and the packages of each part | +| Command | What it does | +| ----------------------------------- | ------------------------------------------------------------------------- | +| `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | +| `drx info` | Prints the versions of the CLI, Node and the packages of each part | +| `drx module list`, `search`, `info` | Lists, searches and shows the modules in the Druxt module registry | The options, the registry format and the configuration files are in the [repository README](https://github.com/druxt/cli#readme). diff --git a/packages/cli/package.json b/packages/cli/package.json index cc6661e..168d7cc 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -45,6 +45,7 @@ "@clack/prompts": "^1.9.0", "c12": "^3.3.4", "citty": "^0.2.2", - "giget": "^3.3.1" + "giget": "^3.3.1", + "semver": "^7.8.6" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts index 623b547..e645f6f 100644 --- a/packages/cli/src/adapters/adapter.ts +++ b/packages/cli/src/adapters/adapter.ts @@ -10,6 +10,14 @@ export interface PackageVersion { installed: string | null } +/** A field that is not in the form it has to be, and what that form is. */ +export interface FieldProblem { + /** The field, as a path from the value that was checked. */ + field: string + /** What it must be, to follow the field's name in a message. */ + must: string +} + /** * Everything the CLI knows about one kind of part. The commands call this * interface and never a kind by name, so a new kind is a new file in this @@ -21,8 +29,24 @@ export interface KindAdapter { readonly role: Role /** True when the directory holds a part of this kind. */ detect(dir: string): Promise + /** + * What is wrong with a module a registry lists for this kind, or undefined. + * The values of one reach the tools of the part as arguments, so each is + * checked by its pattern where it is read, before any command is built. + */ + moduleProblem?(module: { name: string }): FieldProblem | undefined /** The packages `info` reports for a part of this kind. */ packages(dir: string): Promise + /** + * The Druxt package of the part: the range it asks for and the version + * installed. Undefined when the part has none, or its kind never holds one. + */ + druxt(dir: string): Promise + /** + * One package of the part by name, or undefined when the part neither + * asks for it nor has it installed. + */ + package(dir: string, name: string): Promise /** Installs a module into the part and registers it. Not available yet. */ addModule(dir: string, name: string): Promise } diff --git a/packages/cli/src/adapters/drupal-fields.ts b/packages/cli/src/adapters/drupal-fields.ts new file mode 100644 index 0000000..9058104 --- /dev/null +++ b/packages/cli/src/adapters/drupal-fields.ts @@ -0,0 +1,20 @@ +import type { FieldProblem } from './adapter.js' + +/** A module's machine name, as the backend itself defines one. */ +const MACHINE_NAME = /^[a-z][a-z0-9_]*$/ +const MACHINE_NAME_RULE = + 'must be a machine name: lower-case letters, digits and underscores, starting with a letter' + +/** + * What is wrong with a module the registry lists for this kind. Its name is + * handed to the backend's tools as an argument, so anything but a machine + * name is refused here: an option, a list, or a character a shell reads. + */ +export function moduleProblem(module: { + name: string +}): FieldProblem | undefined { + if (!MACHINE_NAME.test(module.name)) { + return { field: 'name', must: MACHINE_NAME_RULE } + } + return undefined +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts index e043157..66b22f1 100644 --- a/packages/cli/src/adapters/drupal.ts +++ b/packages/cli/src/adapters/drupal.ts @@ -5,6 +5,7 @@ import { type KindAdapter, type PackageVersion, } from './adapter.js' +import { moduleProblem } from './drupal-fields.js' import { readJsonObject, stringMap } from './read-json.js' /** Any of these in `require` makes a Composer project a Drupal site. */ @@ -44,6 +45,8 @@ export const drupalAdapter: KindAdapter = { return CORE.some((name) => name in requires) }, + moduleProblem, + async packages(dir) { const requires = await required(dir) const versions = await installed(dir) @@ -56,5 +59,9 @@ export const drupalAdapter: KindAdapter = { ) }, + // The Druxt packages a module registry lists are frontend packages. + druxt: async () => undefined, + package: async () => undefined, + addModule: addModuleNotAvailable, } diff --git a/packages/cli/src/adapters/index.ts b/packages/cli/src/adapters/index.ts index e8dfaef..95ad7da 100644 --- a/packages/cli/src/adapters/index.ts +++ b/packages/cli/src/adapters/index.ts @@ -1,3 +1,4 @@ +import type { Role } from '../parts.js' import type { KindAdapter } from './adapter.js' import { drupalAdapter } from './drupal.js' import { nuxtAdapter } from './nuxt.js' @@ -14,3 +15,10 @@ export function adapterFor(kind: string): KindAdapter | undefined { export function knownKinds(): string[] { return ADAPTERS.map((adapter) => adapter.kind) } + +/** The kinds a part of the given role can be. */ +export function kindsWithRole(role: Role): string[] { + return ADAPTERS.filter((adapter) => adapter.role === role).map( + (adapter) => adapter.kind + ) +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts index 7cfe1e6..da828b3 100644 --- a/packages/cli/src/adapters/nuxt.ts +++ b/packages/cli/src/adapters/nuxt.ts @@ -15,6 +15,9 @@ const CONFIG_FILES = ['js', 'ts', 'mjs', 'cjs', 'mts'].map( const FRAMEWORK = 'nuxt' const DRUXT_PACKAGE = /^(druxt|druxt-.+|@druxt\/.+)$/ +/** The package that is Druxt itself, under each naming scheme. */ +const DRUXT_CORE = ['druxt', '@druxt/core'] + async function declared(dir: string): Promise> { const manifest = await readJsonObject(join(dir, 'package.json')) return { @@ -37,6 +40,25 @@ async function installedManifest(dir: string, name: string) { } } +/** The version of a package installed for the part, or null. */ +async function installedVersion( + dir: string, + name: string +): Promise { + const manifest = await installedManifest(dir, name) + return typeof manifest?.version === 'string' ? manifest.version : null +} + +async function packageVersion( + dir: string, + name: string +): Promise { + const range = (await declared(dir))[name] ?? null + const installed = await installedVersion(dir, name) + if (range === null && installed === null) return undefined + return { name, range, installed } +} + export const nuxtAdapter: KindAdapter = { kind: 'nuxt', role: 'frontend', @@ -56,16 +78,24 @@ export const nuxtAdapter: KindAdapter = { const versions: PackageVersion[] = [] for (const name of names) { - const installed = await installedManifest(dir, name) versions.push({ name, range: ranges[name] ?? null, - installed: - typeof installed?.version === 'string' ? installed.version : null, + installed: await installedVersion(dir, name), }) } return versions }, + async druxt(dir) { + for (const name of DRUXT_CORE) { + const found = await packageVersion(dir, name) + if (found) return found + } + return undefined + }, + + package: packageVersion, + addModule: addModuleNotAvailable, } diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index b9b42b7..02b686e 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -2,6 +2,7 @@ import { stripVTControlCharacters } from 'node:util' import { defineCommand, renderUsage, runCommand, type CommandDef } from 'citty' import { infoCommand } from './commands/info.js' import { initCommand } from './commands/init.js' +import { moduleCommand } from './commands/module.js' import { defaultContext, type CliContext, type TextStream } from './context.js' import { DrxError } from './errors.js' import { cliVersion } from './package-root.js' @@ -16,6 +17,7 @@ function mainCommand(context: CliContext) { subCommands: { init: initCommand(context), info: infoCommand(context), + module: moduleCommand(context), }, }) } @@ -31,20 +33,32 @@ async function resolveMeta(command: CommandDef) { return typeof meta === 'function' ? await meta() : await meta } -/** The usage of the command the arguments name, or of `drx` itself. */ +/** + * The usage of the command the arguments name, or of `drx` itself. A command + * may hold commands of its own, so the names are followed as far as they go. + */ async function usage( main: CommandDef, - subCommands: Record, argv: string[], startedAs: CliContext['startedAs'] ): Promise { - const name = argv.find((argument) => !argument.startsWith('-')) - const command = name ? subCommands[name] : undefined - if (command && startedAs && startedAs.command === name) { + let command = main + let parent: CommandDef | undefined + let path = 'drx' + for (const name of argv.filter((argument) => !argument.startsWith('-'))) { + const next = ( + command.subCommands as Record | undefined + )?.[name] + if (!next) break + parent = { meta: { name: path } } + path = `${path} ${name}` + command = next + } + if (startedAs && path === `drx ${startedAs.command}`) { const meta = { ...(await resolveMeta(command)), name: startedAs.name } return renderUsage({ ...command, meta }) } - return command ? renderUsage(command, main) : renderUsage(main) + return renderUsage(command, parent) } /** The code and message to report for anything a command throws. */ @@ -77,13 +91,12 @@ export async function runCli( ): Promise { const context = { ...defaultContext(), ...overrides } const main = mainCommand(context) - const subCommands = main.subCommands as Record const { stdout, stderr } = context try { if (argv.includes('--help') || argv.includes('-h')) { stdout.write( - `${plain(stdout, await usage(main, subCommands, argv, context.startedAs))}\n` + `${plain(stdout, await usage(main, argv, context.startedAs))}\n` ) return 0 } diff --git a/packages/cli/src/commands-on-path.ts b/packages/cli/src/commands-on-path.ts new file mode 100644 index 0000000..445d21b --- /dev/null +++ b/packages/cli/src/commands-on-path.ts @@ -0,0 +1,107 @@ +import { accessSync, constants, statSync } from 'node:fs' +import { extname, join } from 'node:path' + +type Env = Record + +/** The extensions Windows tries when PATHEXT is not set. */ +const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD' + +/** A name a registry entry may ask to be looked up: no path, no spaces. */ +export function isCommandName(value: unknown): value is string { + return typeof value === 'string' && /^[a-z0-9][a-z0-9._+-]*$/i.test(value) +} + +function isRunnable(file: string, windows: boolean): boolean { + try { + if (!statSync(file).isFile()) return false + // Windows decides by extension, and has no executable bit to read. + if (!windows) accessSync(file, constants.X_OK) + return true + } catch { + return false + } +} + +/** + * The file a command name resolves to on PATH, or undefined. It reads the + * directories itself and runs nothing, so no shell is involved. + * + * On Windows the variable may be spelled `Path`, the separator is `;`, and a + * name with no extension is tried with each extension in PATHEXT. + */ +export function findOnPath( + name: string, + env: Env = process.env, + platform: string = process.platform +): string | undefined { + const windows = platform === 'win32' + const key = windows + ? Object.keys(env).find((candidate) => candidate.toUpperCase() === 'PATH') + : 'PATH' + const directories = (env[key ?? 'PATH'] ?? '') + .split(windows ? ';' : ':') + .filter(Boolean) + + let names = [name] + if (windows && extname(name) === '') { + names = (env.PATHEXT || DEFAULT_PATHEXT) + .split(';') + .filter(Boolean) + // The file system ignores case there. Trying the lower-case spelling + // first gives the same answer on one that does not. + .flatMap((extension) => [extension.toLowerCase(), extension]) + .map((extension) => name + extension) + } + + for (const directory of directories) { + for (const candidate of names) { + const file = join(directory, candidate) + if (isRunnable(file, windows)) return file + } + } + return undefined +} + +/** What a starter's commands look like on this machine. */ +export interface CommandCheck { + /** True when every command of at least one alternative was found. */ + satisfied: boolean + /** The alternatives, as the registry entry gives them. */ + alternatives: string[][] + found: string[] + missing: string[] +} + +/** + * Looks up every command of every alternative, each once, in the order the + * entry names them. + */ +export function checkCommands( + alternatives: string[][], + find: (name: string) => string | undefined +): CommandCheck { + const present = new Map() + for (const name of alternatives.flat()) { + if (!present.has(name)) present.set(name, find(name) !== undefined) + } + const names = [...present.keys()] + return { + satisfied: alternatives.some((commands) => + commands.every((name) => present.get(name)) + ), + alternatives, + found: names.filter((name) => present.get(name)), + missing: names.filter((name) => !present.get(name)), + } +} + +/** The alternatives as a phrase: "php and composer, or ddev". */ +export function describeAlternatives(alternatives: string[][]): string { + return alternatives + .map((commands) => + commands.length > 1 + ? `${commands.slice(0, -1).join(', ')} and ${commands.at(-1)}` + : (commands[0] ?? '') + ) + .join(', or ') +} diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index 5fe932e..c3dfd86 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -3,6 +3,11 @@ import { existsSync, readdirSync, statSync } from 'node:fs' import { isAbsolute, join, relative, resolve } from 'node:path' import { defineCommand, type ArgsDef } from 'citty' import { assertKnownOptions } from '../args.js' +import { + checkCommands, + describeAlternatives, + type CommandCheck, +} from '../commands-on-path.js' import type { CliContext } from '../context.js' import { DrxError } from '../errors.js' import { @@ -188,7 +193,7 @@ function warnAboutStarter( target: string, context: CliContext, output: Output -): void { +): CommandCheck | null { const { requires, maintained, parts } = entry.druxt if (!nodeSatisfies(context.nodeVersion, requires.node)) { output.warn( @@ -208,6 +213,19 @@ function warnAboutStarter( ) } } + + if (!requires.commands) return null + const commands = checkCommands(requires.commands, context.findCommand) + if (!commands.satisfied) { + const advice = + commands.alternatives.length > 1 + ? 'Install the commands of one alternative' + : 'Install what is missing' + output.warn( + `The ${entry.name} starter needs ${describeAlternatives(commands.alternatives)}. Not found on PATH: ${commands.missing.join(', ')}. ${advice} before you set up the site.` + ) + } + return commands } async function runInit( @@ -308,7 +326,7 @@ async function runInit( parts: entry.druxt.parts, } await writeProjectConfig(target, config) - warnAboutStarter(entry, target, context, output) + const commands = warnAboutStarter(entry, target, context, output) if (install) { output.note('Installing dependencies.') @@ -346,6 +364,7 @@ async function runInit( ...config, installed: install, requires, + commands, next, notes, }, diff --git a/packages/cli/src/commands/module.ts b/packages/cli/src/commands/module.ts new file mode 100644 index 0000000..d70a503 --- /dev/null +++ b/packages/cli/src/commands/module.ts @@ -0,0 +1,508 @@ +import { defineCommand, type ArgsDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import type { ModuleEntry } from '../modules/entry.js' +import { + moduleProject, + type ModuleInPart, + type ModuleProject, +} from '../modules/project.js' +import { + describeAge, + loadModules, + type LoadedModules, +} from '../modules/registry.js' +import { columns, createOutput, type Output } from '../output.js' +import { loadUserConfig, resolveModuleRegistryUrl } from '../user-config.js' + +const registryArgs = { + 'module-registry': { + type: 'string', + valueHint: 'url', + description: + 'A module registry: a URL, or a name from the user configuration', + }, + refresh: { + type: 'boolean', + description: 'Read the registry again even when the cached copy is fresh', + }, + json: { + type: 'boolean', + description: 'Print the result as JSON on stdout', + }, +} satisfies ArgsDef + +const filterArgs = { + all: { + type: 'boolean', + description: 'Include archived modules', + }, + type: { + type: 'string', + valueHint: 'type', + description: 'Only modules of this type, such as official or contrib', + }, + category: { + type: 'string', + valueHint: 'category', + description: 'Only modules in this category', + }, +} satisfies ArgsDef + +type Parsed = Record + +/** A string option's value, or an error when it was given with none. */ +function valueOf(parsed: Parsed, name: string): string | undefined { + const value = parsed[name] + if (value === undefined) return undefined + if (typeof value !== 'string' || value.trim() === '') { + throw new DrxError('usage', `--${name} needs a value.`) + } + return value +} + +/** Loads the registry the flags name and says on stderr where it came from. */ +async function openModules( + context: CliContext, + parsed: Parsed, + output: Output +): Promise { + const named = valueOf(parsed, 'module-registry') + const url = named + ? resolveModuleRegistryUrl(named, await loadUserConfig(context.env)) + : context.defaultModuleRegistry + + const loaded = await loadModules({ + url, + cacheDir: context.cacheDir, + now: context.now, + fetch: context.fetch, + refresh: parsed.refresh === true, + // The token goes to a registry the user named, never to the public one. + ...(named && context.env.GIGET_AUTH + ? { auth: context.env.GIGET_AUTH } + : {}), + }) + + const age = describeAge(loaded.ageMs) + if (loaded.reason) { + output.note(loaded.reason) + output.note(`Using the copy of the registry read ${age} ago.`) + } else if (loaded.origin === 'cache') { + output.note(`Modules from ${loaded.url}, read ${age} ago.`) + } else { + output.note(`Modules from ${loaded.url}.`) + } + return loaded +} + +/** Says on stderr which Druxt the modules are compared with. */ +function noteProject(project: ModuleProject, output: Output): void { + for (const part of project.parts) { + const druxt = part.druxt + const has = !druxt + ? 'has no druxt' + : druxt.installed + ? `has ${druxt.name} ${druxt.installed} installed` + : `asks for ${druxt.name} ${druxt.range} and has none installed` + output.note(`Project ${project.root}: ${part.path}/ ${has}.`) + } +} + +function registryReport(loaded: LoadedModules) { + const { url, origin, fetchedAt, ageMs, reason } = loaded + return { url, origin, fetchedAt, ageMs, ...(reason ? { reason } : {}) } +} + +function projectReport(project: ModuleProject | undefined) { + return project ? { root: project.root, parts: project.parts } : null +} + +function rowReport(module: ModuleEntry) { + return { + name: module.name, + npm: module.npm ?? null, + type: module.type, + status: module.status, + category: module.category, + archived: module.archived, + description: module.description, + druxt: module.druxt ?? null, + } +} + +const status = (module: ModuleEntry) => + module.archived ? `${module.status} (archived)` : module.status + +const YES_NO = { compatible: 'yes', incompatible: 'no', unknown: 'unknown' } + +/** One cell for all parts: the bare value for one part, labelled for more. */ +function acrossParts( + states: ModuleInPart[], + value: (state: ModuleInPart) => string +): string { + return states.length === 1 + ? value(states[0] as ModuleInPart) + : states.map((state) => `${state.path}: ${value(state)}`).join(', ') +} + +function installedCell(module: ModuleEntry, state: ModuleInPart): string { + if (!module.npm) return '-' + return state.installed ?? (state.declared ? 'declared' : 'no') +} + +/** Prints modules as a table, or as JSON, with their state in a project. */ +async function printModules( + modules: ModuleEntry[], + loaded: LoadedModules, + project: ModuleProject | undefined, + output: Output +): Promise { + const sorted = [...modules].sort((a, b) => a.name.localeCompare(b.name)) + const states = new Map() + if (project) { + for (const module of sorted) states.set(module, await project.state(module)) + } + + const header = ['Name', 'Package', 'Type', 'Status', 'Druxt'] + if (project) header.push('Installed', 'Compatible') + const rows = sorted.map((module) => { + const row = [ + module.name, + module.npm ?? '-', + module.type, + status(module), + module.druxt ?? 'not stated', + ] + const inParts = states.get(module) + if (inParts) { + row.push( + acrossParts(inParts, (state) => installedCell(module, state)), + acrossParts(inParts, (state) => YES_NO[state.compatibility]) + ) + } + return row + }) + + output.result( + { + registry: registryReport(loaded), + project: projectReport(project), + modules: sorted.map((module) => ({ + ...rowReport(module), + ...(project ? { parts: states.get(module) } : {}), + })), + }, + rows.length === 0 + ? 'No modules match.' + : columns([header, ...rows]).join('\n') + ) +} + +/** Applies `--all`, `--type` and `--category`. */ +function filtered(modules: ModuleEntry[], parsed: Parsed): ModuleEntry[] { + const type = valueOf(parsed, 'type')?.toLowerCase() + const category = valueOf(parsed, 'category')?.toLowerCase() + return modules.filter( + (module) => + (parsed.all === true || !module.archived) && + (!type || module.type.toLowerCase() === type) && + (!category || module.category.toLowerCase() === category) + ) +} + +function listCommand(context: CliContext) { + const args = { ...filterArgs, ...registryArgs } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'list', + description: 'List the modules in the registry', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module list') + const output = createOutput(context, parsed.json === true) + const loaded = await openModules(context, parsed, output) + const project = await moduleProject(context.cwd) + if (project) noteProject(project, output) + await printModules( + filtered(loaded.modules, parsed), + loaded, + project, + output + ) + }, + }) +} + +function searchCommand(context: CliContext) { + const args = { + text: { + type: 'positional', + required: false, + description: 'Text to find in a name, a package name or a description', + }, + ...filterArgs, + ...registryArgs, + } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'search', + description: 'Search the modules in the registry', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module search') + const text = String(parsed.text ?? '') + .trim() + .toLowerCase() + if (!text) { + throw new DrxError( + 'usage', + 'Give the text to search for, as in "drx module search menu".' + ) + } + const output = createOutput(context, parsed.json === true) + const loaded = await openModules(context, parsed, output) + const project = await moduleProject(context.cwd) + if (project) noteProject(project, output) + const matches = filtered(loaded.modules, parsed).filter((module) => + [module.name, module.npm ?? '', module.description].some((field) => + field.toLowerCase().includes(text) + ) + ) + await printModules(matches, loaded, project, output) + }, + }) +} + +/** The number of single-character edits between two strings. */ +function editDistance(a: string, b: string): number { + let previous = Array.from({ length: b.length + 1 }, (_, index) => index) + for (let i = 1; i <= a.length; i++) { + const current = [i] + for (let j = 1; j <= b.length; j++) { + current[j] = Math.min( + (previous[j] ?? 0) + 1, + (current[j - 1] ?? 0) + 1, + (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1) + ) + } + previous = current + } + return previous[b.length] ?? 0 +} + +/** Up to three registry names near a name that matched nothing. */ +function closestNames(modules: ModuleEntry[], wanted: string): string[] { + const limit = Math.max(2, Math.floor(wanted.length / 3)) + return modules + .map((module) => ({ + name: module.name, + distance: Math.min( + ...[module.name, module.npm ?? module.name].map((candidate) => + candidate.toLowerCase().includes(wanted) + ? 0 + : editDistance(wanted, candidate.toLowerCase()) + ) + ), + })) + .filter(({ distance }) => distance <= limit) + .sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name)) + .slice(0, 3) + .map(({ name }) => name) +} + +function findModule(modules: ModuleEntry[], wanted: string): ModuleEntry { + const name = wanted.toLowerCase() + const found = modules.find( + (module) => + module.name.toLowerCase() === name || module.npm?.toLowerCase() === name + ) + if (found) return found + const closest = closestNames(modules, name) + throw new DrxError( + 'unknown-module', + closest.length > 0 + ? `There is no module named "${wanted}". Closest: ${closest.join(', ')}.` + : `There is no module named "${wanted}". Run "drx module list --all" to see every name.` + ) +} + +/** A link to the module's source. The registry names a GitHub repository. */ +function repositoryUrl(module: ModuleEntry): string { + const base = /^https?:\/\//.test(module.repo) + ? module.repo + : `https://github.com/${module.repo}` + return module.path ? `${base}/tree/HEAD/${module.path}` : base +} + +/** + * Whether each backend module a module needs is part of core: true, false, + * or null when the registry does not say. A registry that marks any module as + * core is taken to mark them all, so in one that does, a module with no mark + * is not core. + */ +function backendReport(module: ModuleEntry, registry: ModuleEntry[]) { + const marked = registry.some((entry) => + entry.backend.some((needed) => needed.core) + ) + return module.backend.map((needed) => ({ + ...needed, + core: needed.core ?? (marked ? false : null), + })) +} + +function infoText( + module: ModuleEntry, + backend: ReturnType, + project: ModuleProject | undefined, + states: ModuleInPart[] +): string { + const lines = [module.name] + if (module.description) lines.push(module.description) + lines.push( + '', + ...columns( + [ + ['Package', module.npm ?? 'not published'], + ['Type', module.type], + ['Status', status(module)], + ['Category', module.category], + ['Druxt', module.druxt ?? 'not stated'], + ['Repository', repositoryUrl(module)], + ...(module.website ? [['Website', module.website]] : []), + ], + '' + ), + '' + ) + + if (backend.length === 0) { + lines.push('Backend modules it needs: none listed.') + } else { + lines.push( + 'Backend modules it needs:', + ...columns( + backend.map((needed) => [ + needed.kind, + needed.name, + needed.label, + [needed.core ? '(core)' : '', needed.url ?? ''].join(' ').trim(), + ]), + ' ' + ) + ) + if (backend.some((needed) => needed.core === null)) { + lines.push('The registry does not say which of these are part of core.') + } + } + + for (const [index, state] of states.entries()) { + const druxt = project?.parts[index]?.druxt + const asked = state.declared ? ` (asked for as ${state.declared})` : '' + lines.push( + '', + `In ${state.path}/:`, + ...columns( + [ + ['Installed', `${state.installed ?? 'no'}${asked}`], + [ + 'Druxt', + !druxt + ? 'none' + : druxt.installed + ? `${druxt.installed} installed` + : `${druxt.range} asked for, none installed`, + ], + ['Compatible', YES_NO[state.compatibility]], + ], + ' ' + ) + ) + } + return lines.join('\n') +} + +function infoCommand(context: CliContext) { + const args = { + name: { + type: 'positional', + required: false, + description: 'The name of a module, or of its package', + }, + ...registryArgs, + } satisfies ArgsDef + return defineCommand({ + meta: { + name: 'info', + description: 'Show one module: its package, range, needs and links', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'module info') + const wanted = String(parsed.name ?? '').trim() + if (!wanted) { + throw new DrxError( + 'usage', + 'Give the name of a module, as in "drx module info blocks".' + ) + } + const output = createOutput(context, parsed.json === true) + const loaded = await openModules(context, parsed, output) + const module = findModule(loaded.modules, wanted) + const project = await moduleProject(context.cwd) + const states = project ? await project.state(module) : [] + const backend = backendReport(module, loaded.modules) + + output.result( + { + registry: registryReport(loaded), + project: projectReport(project), + module: { + ...rowReport(module), + repository: repositoryUrl(module), + ...(module.website ? { website: module.website } : {}), + backend, + ...(project ? { parts: states } : {}), + }, + }, + infoText(module, backend, project, states) + ) + }, + }) +} + +/** + * A command that changes a project. The name is taken now, so scripts and + * documentation can rely on it, and it fails until it is built. + */ +function notAvailable(name: string, description: string) { + return defineCommand({ + meta: { name, description: `${description} (not available yet)` }, + run() { + throw new DrxError( + 'not-available', + `drx module ${name} is not available yet. Run "drx module --help" for the commands this version has.` + ) + }, + }) +} + +export function moduleCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'module', + description: 'List, search and show the modules in the Druxt registry', + }, + subCommands: { + list: listCommand(context), + search: searchCommand(context), + info: infoCommand(context), + add: notAvailable('add', 'Install a module and add it to the project'), + remove: notAvailable('remove', 'Take a module out of the project'), + configure: notAvailable('configure', 'Set the options of a module'), + }, + }) +} diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts index 1d4c344..fc82312 100644 --- a/packages/cli/src/context.ts +++ b/packages/cli/src/context.ts @@ -1,5 +1,9 @@ import { downloadTemplate } from 'giget' +import { findOnPath } from './commands-on-path.js' +import { homedir } from 'node:os' +import { join } from 'node:path' import { installDependencies } from './install.js' +import { DEFAULT_MODULE_REGISTRY } from './modules/registry.js' import { bundledRegistryDir } from './package-root.js' import { terminalPrompter } from './prompts.js' import { DEFAULT_REGISTRY } from './registry/registry.js' @@ -54,10 +58,16 @@ export interface CliContext { defaultRegistry: string /** The copy of the registry used when the default cannot be read. */ bundledRegistryDir: string + /** The module registry used when `--module-registry` is not given. */ + defaultModuleRegistry: string + /** The directory the CLI keeps what it can fetch again in. */ + cacheDir: string /** Fetches and unpacks a template. giget's `downloadTemplate`. */ download: typeof downloadTemplate /** Installs the dependencies of the site in a directory. */ install: (dir: string) => Promise + /** The file a command name resolves to on PATH, or undefined. */ + findCommand: (name: string) => string | undefined /** * Set by a binary that runs one command under a name of its own, so the * usage of that command is headed by the name the user typed. @@ -65,6 +75,17 @@ export interface CliContext { startedAs?: { command: string; name: string } } +/** + * `DRX_CACHE_DIR`, or `drx` under the user's cache directory. + */ +export function cacheDirectory( + env: Record +): string { + if (env.DRX_CACHE_DIR) return env.DRX_CACHE_DIR + const base = env.XDG_CACHE_HOME ?? join(env.HOME ?? homedir(), '.cache') + return join(base, 'drx') +} + export function defaultContext(): CliContext { return { cwd: process.cwd(), @@ -80,7 +101,10 @@ export function defaultContext(): CliContext { prompter: terminalPrompter(), defaultRegistry: DEFAULT_REGISTRY, bundledRegistryDir: bundledRegistryDir(), + defaultModuleRegistry: DEFAULT_MODULE_REGISTRY, + cacheDir: cacheDirectory(process.env), download: downloadTemplate, install: (dir) => installDependencies(dir), + findCommand: (name) => findOnPath(name), } } diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts index b6c7c57..1853c99 100644 --- a/packages/cli/src/errors.ts +++ b/packages/cli/src/errors.ts @@ -6,6 +6,7 @@ export type DrxErrorCode = | 'invalid-entry' | 'unknown-starter' | 'unknown-source' + | 'unknown-module' | 'directory-not-empty' | 'config' | 'download' diff --git a/packages/cli/src/fetch-json.ts b/packages/cli/src/fetch-json.ts new file mode 100644 index 0000000..70aa6ca --- /dev/null +++ b/packages/cli/src/fetch-json.ts @@ -0,0 +1,39 @@ +import { DrxError } from './errors.js' + +const TIMEOUT_MS = 10_000 + +/** + * Fetches a URL and parses it as JSON. Every way it can fail is one error + * that starts "Could not read ", so a caller can fall back on it. + */ +export async function fetchJson( + url: string, + fetcher: typeof fetch = fetch, + auth?: string +): Promise { + let response: Response + try { + response = await fetcher(url, { + headers: auth ? { authorization: `Bearer ${auth}` } : {}, + signal: AbortSignal.timeout(TIMEOUT_MS), + }) + } catch (error) { + const cause = error instanceof Error ? (error.cause ?? error) : error + const detail = cause instanceof Error ? cause.message : String(cause) + throw new DrxError('registry', `Could not read ${url}: ${detail}.`) + } + if (!response.ok) { + throw new DrxError( + 'registry', + `Could not read ${url}: ${response.status} ${response.statusText}.` + ) + } + try { + return JSON.parse(await response.text()) as unknown + } catch { + throw new DrxError( + 'registry', + `Could not read ${url}: it is not valid JSON.` + ) + } +} diff --git a/packages/cli/src/modules/compatibility.ts b/packages/cli/src/modules/compatibility.ts new file mode 100644 index 0000000..3464cfa --- /dev/null +++ b/packages/cli/src/modules/compatibility.ts @@ -0,0 +1,39 @@ +import semver from 'semver' +import type { PackageVersion } from '../adapters/index.js' + +/** + * Whether a module works with the Druxt of a part. `unknown` covers a module + * that states no range, and a part with no Druxt version to compare. It is + * never read as compatible. + */ +export type Compatibility = 'compatible' | 'incompatible' | 'unknown' + +/** + * Compares the range a module states with the Druxt a part's adapter + * reports: the installed version when there is one, and the range the part + * asks for when nothing is installed yet. + */ +export function compatibility( + moduleRange: string | undefined, + druxt: PackageVersion | undefined +): Compatibility { + if (!moduleRange || moduleRange === 'unknown') return 'unknown' + if (!druxt || semver.validRange(moduleRange) === null) return 'unknown' + + if (druxt.installed !== null) { + if (semver.valid(druxt.installed) === null) return 'unknown' + // A prerelease of a version inside the range counts as inside it. + return semver.satisfies(druxt.installed, moduleRange, { + includePrerelease: true, + }) + ? 'compatible' + : 'incompatible' + } + + if (druxt.range === null || semver.validRange(druxt.range) === null) { + return 'unknown' + } + return semver.intersects(druxt.range, moduleRange) + ? 'compatible' + : 'incompatible' +} diff --git a/packages/cli/src/modules/entry.ts b/packages/cli/src/modules/entry.ts new file mode 100644 index 0000000..e2729e1 --- /dev/null +++ b/packages/cli/src/modules/entry.ts @@ -0,0 +1,184 @@ +import { adapterFor, kindsWithRole } from '../adapters/index.js' +import { DrxError } from '../errors.js' +import { isNonEmptyString, isNpmName, isRecord } from '../validate.js' + +/** The registry format this version reads. */ +export const MODULE_SCHEMA_VERSION = 1 + +/** A backend module a Druxt module needs, and the kind of backend it is for. */ +export interface BackendModule { + kind: string + /** The machine name of the module. */ + name: string + label: string + /** + * Whether the backend ships the module itself, as the registry states it. + * Undefined when the registry does not say. + */ + core?: boolean + url?: string +} + +/** + * One module of the registry, with the fields the CLI uses. The registry + * holds more, and is free to add to them. + */ +export interface ModuleEntry { + name: string + /** The package to install. A module that is not released has none. */ + npm?: string + repo: string + /** Where the module is inside its repository. */ + path?: string + category: string + status: string + type: string + archived: boolean + description: string + website?: string + /** + * The Druxt versions the module works with, as the registry states it: a + * semver range, the word `unknown`, or undefined when it says nothing. + */ + druxt?: string + backend: BackendModule[] +} + +type Raw = Record + +class Invalid extends Error {} + +function requiredString(raw: Raw, key: string, at: string): string { + if (!isNonEmptyString(raw[key])) { + throw new Invalid(`${at}.${key} must be a non-empty string`) + } + return raw[key] +} + +function optionalString(raw: Raw, key: string, at: string): string | undefined { + const value = raw[key] + if (value !== undefined && typeof value !== 'string') { + throw new Invalid(`${at}.${key} must be a string`) + } + return value +} + +function optionalBoolean(raw: Raw, key: string, at: string): boolean { + const value = raw[key] + if (value !== undefined && typeof value !== 'boolean') { + throw new Invalid(`${at}.${key} must be true or false`) + } + return value ?? false +} + +/** + * The backend modules of an entry. The registry lists them under a key named + * after the kind of backend, so each backend kind that has an adapter is + * looked up by its own name. + */ +function backendModules(raw: Raw, at: string): BackendModule[] { + const modules: BackendModule[] = [] + for (const kind of kindsWithRole('backend')) { + const list = raw[kind] + if (list === undefined) continue + if (!Array.isArray(list)) + throw new Invalid(`${at}.${kind} must be an array`) + for (const [index, item] of list.entries()) { + const here = `${at}.${kind}[${index}]` + if (!isRecord(item)) throw new Invalid(`${here} must be an object`) + const url = optionalString(item, 'url', here) + // Checked for its type, and kept only when it is there. + const core = optionalBoolean(item, 'core', here) + const module: BackendModule = { + kind, + name: requiredString(item, 'name', here), + label: requiredString(item, 'label', here), + ...(item.core === undefined ? {} : { core }), + ...(url === undefined ? {} : { url }), + } + // The kind says what its tools take, so a value is never an option. + const problem = adapterFor(kind)?.moduleProblem?.(module) + if (problem) throw new Invalid(`${here}.${problem.field} ${problem.must}`) + modules.push(module) + } + } + return modules +} + +function moduleEntry(raw: unknown, at: string): ModuleEntry { + if (!isRecord(raw)) throw new Invalid(`${at} must be an object`) + + const compatibility = raw.compatibility + if (compatibility !== undefined && !isRecord(compatibility)) { + throw new Invalid(`${at}.compatibility must be an object`) + } + const druxt = compatibility + ? optionalString(compatibility, 'druxt', `${at}.compatibility`) + : undefined + + const name = requiredString(raw, 'name', at) + const repo = requiredString(raw, 'repo', at) + const category = requiredString(raw, 'category', at) + const status = requiredString(raw, 'status', at) + const type = requiredString(raw, 'type', at) + const npm = optionalString(raw, 'npm', at) + // An empty name is a module with no package. Any other is an argument of + // a package manager one day, so it has to be a name and nothing else. + if (npm !== undefined && npm !== '' && !isNpmName(npm)) { + throw new Invalid(`${at}.npm must be the name of an npm package`) + } + const path = optionalString(raw, 'path', at) + const website = optionalString(raw, 'website', at) + + return { + name, + ...(npm === undefined ? {} : { npm }), + repo, + ...(path === undefined ? {} : { path }), + category, + status, + type, + archived: optionalBoolean(raw, 'archived', at), + description: optionalString(raw, 'description', at) ?? '', + ...(website === undefined ? {} : { website }), + ...(druxt === undefined ? {} : { druxt }), + backend: backendModules(raw, at), + } +} + +/** + * Checks a module registry and returns its entries. A field the CLI does not + * use is ignored. A `schemaVersion` it does not know is refused, since the + * fields it does use may have changed meaning. + */ +export function parseModuleRegistry( + raw: unknown, + location: string +): ModuleEntry[] { + const invalid = (problem: string) => + new DrxError( + 'registry', + `The module registry at ${location} is invalid: ${problem}.` + ) + + if (!isRecord(raw)) throw invalid('it must be an object') + if (typeof raw.schemaVersion !== 'number') { + throw invalid('schemaVersion must be a number') + } + if (raw.schemaVersion !== MODULE_SCHEMA_VERSION) { + throw new DrxError( + 'registry', + `The module registry at ${location} has schemaVersion ${raw.schemaVersion}, and this version of the CLI reads schemaVersion ${MODULE_SCHEMA_VERSION}. Update @druxt/cli to read it.` + ) + } + if (!Array.isArray(raw.modules)) throw invalid('modules must be an array') + + try { + return raw.modules.map((entry, index) => + moduleEntry(entry, `modules[${index}]`) + ) + } catch (error) { + if (error instanceof Invalid) throw invalid(error.message) + throw error + } +} diff --git a/packages/cli/src/modules/project.ts b/packages/cli/src/modules/project.ts new file mode 100644 index 0000000..d117fa4 --- /dev/null +++ b/packages/cli/src/modules/project.ts @@ -0,0 +1,86 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { + adapterFor, + type KindAdapter, + type PackageVersion, +} from '../adapters/index.js' +import type { Part } from '../parts.js' +import { findProjectRoot, loadProjectConfig } from '../project.js' +import { compatibility, type Compatibility } from './compatibility.js' +import type { ModuleEntry } from './entry.js' + +/** A frontend part of the project, and the Druxt its adapter reports. */ +export interface ModulePart { + path: string + kind: string + druxt: PackageVersion | null +} + +/** One module in one part. */ +export interface ModuleInPart { + path: string + /** The version installed, or null. */ + installed: string | null + /** The range the part asks for, or null. */ + declared: string | null + compatibility: Compatibility +} + +export interface ModuleProject { + root: string + parts: ModulePart[] + /** How a module stands in each part, in the order of `parts`. */ + state(module: ModuleEntry): Promise +} + +/** + * The project around `cwd` as the module commands see it: its frontend parts + * that exist and have an adapter. Undefined outside a project, and in one + * with no such part. + */ +export async function moduleProject( + cwd: string +): Promise { + const root = findProjectRoot(cwd) + if (!root) return undefined + const config = await loadProjectConfig(root) + + const found: { + part: Part + adapter: KindAdapter + dir: string + druxt: PackageVersion | undefined + }[] = [] + for (const part of config.parts) { + const adapter = adapterFor(part.kind) + const dir = join(root, part.path) + if (part.role !== 'frontend' || !adapter || !existsSync(dir)) continue + found.push({ part, adapter, dir, druxt: await adapter.druxt(dir) }) + } + if (found.length === 0) return undefined + + return { + root, + parts: found.map(({ part, druxt }) => ({ + path: part.path, + kind: part.kind, + druxt: druxt ?? null, + })), + async state(module) { + const states: ModuleInPart[] = [] + for (const { part, adapter, dir, druxt } of found) { + const own = module.npm + ? await adapter.package(dir, module.npm) + : undefined + states.push({ + path: part.path, + installed: own?.installed ?? null, + declared: own?.range ?? null, + compatibility: compatibility(module.druxt, druxt), + }) + } + return states + }, + } +} diff --git a/packages/cli/src/modules/registry.ts b/packages/cli/src/modules/registry.ts new file mode 100644 index 0000000..db5770c --- /dev/null +++ b/packages/cli/src/modules/registry.ts @@ -0,0 +1,137 @@ +import { createHash } from 'node:crypto' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { DrxError } from '../errors.js' +import { fetchJson } from '../fetch-json.js' +import { isRecord } from '../validate.js' +import { parseModuleRegistry, type ModuleEntry } from './entry.js' + +/** The published Druxt module registry. */ +export const DEFAULT_MODULE_REGISTRY = + 'https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json' + +/** + * A cached copy younger than this is used with no request. The registry + * changes when a module is released, and the CDN in front of it holds a + * branch for hours, so asking more often than hourly finds nothing new. + */ +export const FRESH_FOR_MS = 60 * 60 * 1000 + +export interface LoadedModules { + modules: ModuleEntry[] + url: string + /** `remote` when the registry was read now, `cache` for the copy on disk. */ + origin: 'remote' | 'cache' + /** When the registry was read from its URL, as an ISO date and time. */ + fetchedAt: string + ageMs: number + /** Why the registry could not be read, when an old copy stood in for it. */ + reason?: string +} + +export interface LoadModulesOptions { + url: string + /** The directory the copy is kept in. */ + cacheDir: string + now?: () => Date + fetch?: typeof fetch + /** Read the registry even when the copy is fresh. */ + refresh?: boolean + /** A bearer token for a registry the user named. */ + auth?: string +} + +interface Cached { + modules: ModuleEntry[] + fetchedAt: Date +} + +/** One file per registry URL, named by a hash of the URL. */ +function cacheFile(cacheDir: string, url: string): string { + const key = createHash('sha256').update(url).digest('hex').slice(0, 16) + return join(cacheDir, 'modules', `${key}.json`) +} + +/** The copy on disk, or undefined when there is none that can be read. */ +async function readCache( + file: string, + url: string +): Promise { + try { + const stored: unknown = JSON.parse(await readFile(file, 'utf8')) + if (!isRecord(stored) || stored.url !== url) return undefined + const fetchedAt = new Date(String(stored.fetchedAt)) + if (Number.isNaN(fetchedAt.getTime())) return undefined + return { modules: parseModuleRegistry(stored.registry, url), fetchedAt } + } catch { + return undefined + } +} + +/** + * Loads the module registry. + * + * A copy on disk under an hour old is used as it is. Otherwise the registry + * is read from its URL and the copy replaced. When that read fails, a copy of + * any age is used and the result says why. A registry that is read but is + * invalid, or of another schema version, is an error and never falls back. + */ +export async function loadModules( + options: LoadModulesOptions +): Promise { + const { url, cacheDir } = options + const now = (options.now ?? (() => new Date()))() + const file = cacheFile(cacheDir, url) + const cached = await readCache(file, url) + + const fromCache = (copy: Cached, reason?: string): LoadedModules => ({ + modules: copy.modules, + url, + origin: 'cache', + fetchedAt: copy.fetchedAt.toISOString(), + ageMs: Math.max(0, now.getTime() - copy.fetchedAt.getTime()), + ...(reason === undefined ? {} : { reason }), + }) + + if ( + cached && + !options.refresh && + now.getTime() - cached.fetchedAt.getTime() < FRESH_FOR_MS + ) { + return fromCache(cached) + } + + let registry: unknown + try { + registry = await fetchJson(url, options.fetch, options.auth) + } catch (error) { + if (!(error instanceof DrxError)) throw error + if (cached) return fromCache(cached, error.message) + throw new DrxError( + 'registry', + `${error.message} There is no cached copy to use.` + ) + } + + const modules = parseModuleRegistry(registry, url) + const fetchedAt = now.toISOString() + try { + await mkdir(join(cacheDir, 'modules'), { recursive: true }) + await writeFile(file, JSON.stringify({ url, fetchedAt, registry })) + } catch { + // A cache directory that cannot be written costs a request next time. + } + return { modules, url, origin: 'remote', fetchedAt, ageMs: 0 } +} + +/** An age as a phrase: "less than a minute", "3 hours", "2 days". */ +export function describeAge(ms: number): string { + const count = (value: number, unit: string) => + `${value} ${unit}${value === 1 ? '' : 's'}` + const minutes = Math.floor(ms / 60_000) + if (minutes < 1) return 'less than a minute' + if (minutes < 60) return count(minutes, 'minute') + const hours = Math.floor(minutes / 60) + if (hours < 48) return count(hours, 'hour') + return count(Math.floor(hours / 24), 'day') +} diff --git a/packages/cli/src/registry/entry.ts b/packages/cli/src/registry/entry.ts index 9215bbf..f8bf231 100644 --- a/packages/cli/src/registry/entry.ts +++ b/packages/cli/src/registry/entry.ts @@ -1,3 +1,4 @@ +import { isCommandName } from '../commands-on-path.js' import { DrxError } from '../errors.js' import { isLayout, LAYOUTS, type Layout } from '../layouts.js' import { partsProblem, type Part } from '../parts.js' @@ -13,6 +14,12 @@ export interface StarterRequirements { node: string /** Other tools the site needs, each as a phrase to show the user. */ tools: string[] + /** + * The commands the site needs on PATH, as alternatives: the site can be set + * up when every command of any one inner list is there. `tools` is what the + * user reads, and this is what `init` checks. + */ + commands?: string[][] } /** What Druxt adds to a giget registry entry. giget ignores the key. */ @@ -58,6 +65,26 @@ function isIsoDate(value: unknown): boolean { return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(value) } +/** The first problem with `requires.commands`, or undefined. */ +function commandsProblem(value: unknown): string | undefined { + const at = 'druxt.requires.commands' + if (value === undefined) return undefined + if (!Array.isArray(value) || value.length === 0) { + return `${at} must be a non-empty array of alternatives` + } + for (const [index, alternative] of value.entries()) { + if (!Array.isArray(alternative) || alternative.length === 0) { + return `${at}[${index}] must be a non-empty array of command names` + } + for (const [position, name] of alternative.entries()) { + if (!isCommandName(name)) { + return `${at}[${index}][${position}] must be a command name with no path or spaces` + } + } + } + return undefined +} + /** The first problem with an entry, or undefined when it is valid. */ function entryProblem(entry: unknown): string | undefined { if (!isRecord(entry)) return 'the entry must be an object' @@ -93,6 +120,8 @@ function entryProblem(entry: unknown): string | undefined { if (!isStringArray(requires.tools)) { return 'druxt.requires.tools must be an array of strings' } + const commands = commandsProblem(requires.commands) + if (commands) return commands if (!isIsoDate(druxt.maintained)) { return 'druxt.maintained must be an ISO date (YYYY-MM-DD)' } diff --git a/packages/cli/src/registry/registry.ts b/packages/cli/src/registry/registry.ts index 9dba2e0..8341283 100644 --- a/packages/cli/src/registry/registry.ts +++ b/packages/cli/src/registry/registry.ts @@ -1,6 +1,7 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { DrxError } from '../errors.js' +import { fetchJson } from '../fetch-json.js' import { bundledRegistryDir } from '../package-root.js' import { isRecord, isStringArray } from '../validate.js' import { trimEndSlashes } from '../slashes.js' @@ -14,8 +15,6 @@ import { validateEntry, type StarterEntry } from './entry.js' export const DEFAULT_REGISTRY = 'https://raw.githubusercontent.com/druxt/cli/0.x/starters' -const TIMEOUT_MS = 10_000 - export interface Registry { /** `remote` for a URL, `bundled` for the copy inside the package. */ origin: 'remote' | 'bundled' @@ -55,34 +54,7 @@ function remoteReader( fetcher: typeof fetch, auth?: string ): ReadJson { - return async (file) => { - const url = `${base}/${file}` - let response: Response - try { - response = await fetcher(url, { - headers: auth ? { authorization: `Bearer ${auth}` } : {}, - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - } catch (error) { - const cause = error instanceof Error ? (error.cause ?? error) : error - const detail = cause instanceof Error ? cause.message : String(cause) - throw new DrxError('registry', `Could not read ${url}: ${detail}.`) - } - if (!response.ok) { - throw new DrxError( - 'registry', - `Could not read ${url}: ${response.status} ${response.statusText}.` - ) - } - try { - return JSON.parse(await response.text()) as unknown - } catch { - throw new DrxError( - 'registry', - `Could not read ${url}: it is not valid JSON.` - ) - } - } + return (file) => fetchJson(`${base}/${file}`, fetcher, auth) } function bundledReader(dir: string): ReadJson { @@ -101,6 +73,18 @@ function namesFrom(index: unknown, label: string): string[] { return starters } +/** + * The revision an index states: a whole number that goes up whenever the + * entries gain something a version of drx depends on. An index without one is + * at revision 0. + */ +function revisionOf(index: unknown): number { + const revision = isRecord(index) ? index.revision : undefined + return typeof revision === 'number' && Number.isInteger(revision) + ? revision + : 0 +} + function remoteRegistry(base: string, read: ReadJson): Registry { return { origin: 'remote', @@ -154,16 +138,26 @@ export async function openRegistry( } const base = trimEndSlashes(options.defaultUrl ?? DEFAULT_REGISTRY) - const remote = remoteRegistry(base, remoteReader(base, fetcher)) + const bundledDir = options.bundledDir ?? bundledRegistryDir() + const read = remoteReader(base, fetcher) try { - const names = await remote.names() - return { ...remote, names: async () => names } + const index = await read('index.json') + const names = namesFrom(index, `${base}/index.json`) + // A build made ahead of what is published, such as a branch that adds a + // field to the entries, has to read the entries it was built with. + const ours = await bundledReader(bundledDir)('index.json').catch( + () => undefined + ) + if (revisionOf(index) < revisionOf(ours)) { + return bundledRegistry( + bundledDir, + `${base} is older than this version of drx.` + ) + } + return { ...remoteRegistry(base, read), names: async () => names } } catch (error) { if (!(error instanceof DrxError)) throw error - return bundledRegistry( - options.bundledDir ?? bundledRegistryDir(), - error.message - ) + return bundledRegistry(bundledDir, error.message) } } diff --git a/packages/cli/src/user-config.ts b/packages/cli/src/user-config.ts index 33f600e..199659d 100644 --- a/packages/cli/src/user-config.ts +++ b/packages/cli/src/user-config.ts @@ -19,6 +19,8 @@ export interface UserConfig { /** The file the configuration was read from, or would be. */ path: string registries: Record + /** Module registries by name, for `--module-registry`. */ + moduleRegistries: Record sources: Record } @@ -35,11 +37,14 @@ export function userConfigPath(env: Env): string { function configProblem(config: unknown): string | undefined { if (!isRecord(config)) return 'it must hold an object' - const registries = config.registries ?? {} - if (!isRecord(registries)) return 'registries must be an object of URLs' - for (const [name, url] of Object.entries(registries)) { - if (!isHttpUrl(url)) - return `registries.${name} must be an http or https URL` + for (const key of ['registries', 'moduleRegistries']) { + const registries = config[key] ?? {} + if (!isRecord(registries)) return `${key} must be an object of URLs` + for (const [name, url] of Object.entries(registries)) { + if (!isHttpUrl(url)) { + return `${key}.${name} must be an http or https URL` + } + } } const sources = config.sources ?? {} @@ -78,7 +83,7 @@ export async function loadUserConfig(env: Env): Promise { `DRX_CONFIG names ${path}, which does not exist.` ) } - return { path, registries: {}, sources: {} } + return { path, registries: {}, moduleRegistries: {}, sources: {} } } const invalid = (problem: string) => @@ -97,22 +102,42 @@ export async function loadUserConfig(env: Env): Promise { return { path, registries: config.registries ?? {}, + moduleRegistries: config.moduleRegistries ?? {}, sources: config.sources ?? {}, } } -/** Turns a `--registry` value into a URL: a URL, or a configured name. */ -export function resolveRegistryUrl(value: string, config: UserConfig): string { +/** Turns the value of a registry flag into a URL: a URL, or a configured name. */ +function resolveNamedUrl( + flag: string, + value: string, + named: Record, + config: UserConfig +): string { // An own key only: every object has a `constructor`. - const named = Object.hasOwn(config.registries, value) - ? config.registries[value] - : undefined - if (named) return named + const url = Object.hasOwn(named, value) ? named[value] : undefined + if (url) return url if (isHttpUrl(value)) return value - const names = Object.keys(config.registries).sort() + const names = Object.keys(named).sort() const defined = names.length > 0 ? ` Defined names: ${names.join(', ')}.` : '' throw new DrxError( 'usage', - `--registry takes a URL or a name defined in ${config.path}. "${value}" is neither.${defined}` + `${flag} takes a URL or a name defined in ${config.path}. "${value}" is neither.${defined}` + ) +} + +export function resolveRegistryUrl(value: string, config: UserConfig): string { + return resolveNamedUrl('--registry', value, config.registries, config) +} + +export function resolveModuleRegistryUrl( + value: string, + config: UserConfig +): string { + return resolveNamedUrl( + '--module-registry', + value, + config.moduleRegistries, + config ) } diff --git a/packages/cli/src/validate.ts b/packages/cli/src/validate.ts index 263a2d7..d038459 100644 --- a/packages/cli/src/validate.ts +++ b/packages/cli/src/validate.ts @@ -20,3 +20,21 @@ export function isHttpUrl(value: unknown): value is string { return false } } + +/** npm's own limit on the length of a package name. */ +const NPM_NAME_LENGTH = 214 +const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/ + +/** + * True for a name npm takes for a new package: lower case, URL-safe, with an + * optional scope, and starting with a letter or a digit. A name is handed to + * a package manager as an argument, so one that starts with a hyphen, or has + * a space or a character a shell reads, is not a name. + */ +export function isNpmName(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length <= NPM_NAME_LENGTH && + NPM_NAME.test(value) + ) +} diff --git a/packages/cli/test/adapters/adapters.test.ts b/packages/cli/test/adapters/adapters.test.ts index ee4d6b2..96780bd 100644 --- a/packages/cli/test/adapters/adapters.test.ts +++ b/packages/cli/test/adapters/adapters.test.ts @@ -1,5 +1,9 @@ import { afterEach, describe, expect, test } from 'vitest' -import { adapterFor, knownKinds } from '../../src/adapters/index.js' +import { + adapterFor, + kindsWithRole, + knownKinds, +} from '../../src/adapters/index.js' import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' afterEach(cleanTmp) @@ -157,3 +161,97 @@ describe('the drupal adapter', () => { ) }) }) + +describe('kindsWithRole', () => { + test('lists the kinds of one role', () => { + expect(kindsWithRole('frontend')).toEqual(['nuxt']) + expect(kindsWithRole('backend')).toEqual(['drupal']) + }) +}) + +describe('the Druxt version of a part', () => { + const nuxt = adapterFor('nuxt')! + + test('is the range asked for and the version installed', async () => { + const dir = tmp() + writeTree(dir, { + 'package.json': { dependencies: { druxt: '^0.25.0' } }, + 'node_modules/druxt/package.json': { version: '0.25.2' }, + }) + expect(await nuxt.druxt(dir)).toEqual({ + name: 'druxt', + range: '^0.25.0', + installed: '0.25.2', + }) + }) + + test('is found when another package brought it in', async () => { + const dir = tmp() + writeTree(dir, { + 'package.json': { dependencies: { 'druxt-site': '^0.14.3' } }, + 'node_modules/druxt/package.json': { version: '0.25.2' }, + }) + expect(await nuxt.druxt(dir)).toEqual({ + name: 'druxt', + range: null, + installed: '0.25.2', + }) + }) + + test('is the scoped core package on a site that has that one', async () => { + const dir = tmp() + writeTree(dir, { + 'package.json': { dependencies: { '@druxt/core': '^2.0.0' } }, + }) + expect(await nuxt.druxt(dir)).toEqual({ + name: '@druxt/core', + range: '^2.0.0', + installed: null, + }) + }) + + test('is undefined when the part has no Druxt', async () => { + const dir = tmp() + writeTree(dir, { 'package.json': { dependencies: { nuxt: '2.15.8' } } }) + expect(await nuxt.druxt(dir)).toBeUndefined() + }) + + test('is undefined for a kind that holds no Druxt package', async () => { + expect(await adapterFor('drupal')!.druxt(tmp())).toBeUndefined() + }) +}) + +describe('one package of a part', () => { + const nuxt = adapterFor('nuxt')! + + test('is its range and installed version', async () => { + const dir = tmp() + writeTree(dir, { + 'package.json': { dependencies: { 'druxt-blocks': '^0.25.1' } }, + 'node_modules/druxt-blocks/package.json': { version: '0.25.3' }, + 'node_modules/druxt-router/package.json': { version: '0.25.1' }, + }) + expect(await nuxt.package(dir, 'druxt-blocks')).toEqual({ + name: 'druxt-blocks', + range: '^0.25.1', + installed: '0.25.3', + }) + expect(await nuxt.package(dir, 'druxt-router')).toEqual({ + name: 'druxt-router', + range: null, + installed: '0.25.1', + }) + }) + + test('is undefined when the part neither asks for it nor has it', async () => { + const dir = tmp() + writeTree(dir, { 'package.json': {} }) + expect(await nuxt.package(dir, 'druxt-blocks')).toBeUndefined() + }) + + test('is undefined for a kind with no such packages', async () => { + expect( + await adapterFor('drupal')!.package(tmp(), 'druxt-blocks') + ).toBeUndefined() + }) +}) diff --git a/packages/cli/test/commands-on-path.test.ts b/packages/cli/test/commands-on-path.test.ts new file mode 100644 index 0000000..b1299b4 --- /dev/null +++ b/packages/cli/test/commands-on-path.test.ts @@ -0,0 +1,138 @@ +import { chmodSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' +import { + checkCommands, + describeAlternatives, + findOnPath, +} from '../src/commands-on-path.js' +import { cleanTmp, tmp, writeTree } from './helpers/tmp.js' + +afterEach(cleanTmp) + +/** A directory holding the named files, each executable unless listed. */ +function bin(names: string[], notExecutable: string[] = []): string { + const dir = tmp('drx-path-') + writeTree(dir, Object.fromEntries(names.map((name) => [name, '#!/bin/sh\n']))) + for (const name of names) { + chmodSync(join(dir, name), notExecutable.includes(name) ? 0o644 : 0o755) + } + return dir +} + +describe.skipIf(process.platform === 'win32')('findOnPath on POSIX', () => { + test('finds an executable in a directory on PATH', () => { + const first = bin([]) + const second = bin(['php']) + expect(findOnPath('php', { PATH: `${first}:${second}` }, 'linux')).toBe( + join(second, 'php') + ) + }) + + test('is undefined for a command no directory holds', () => { + expect(findOnPath('ddev', { PATH: bin(['php']) }, 'linux')).toBeUndefined() + }) + + test('passes over a file that is not executable, and a directory', () => { + const dir = bin(['php'], ['php']) + writeTree(dir, { 'composer/README': '' }) + expect(findOnPath('php', { PATH: dir }, 'linux')).toBeUndefined() + expect(findOnPath('composer', { PATH: dir }, 'linux')).toBeUndefined() + }) + + test('is undefined when PATH is empty or not set', () => { + expect(findOnPath('php', { PATH: '' }, 'linux')).toBeUndefined() + expect(findOnPath('php', {}, 'linux')).toBeUndefined() + }) + + test('does not add the extensions Windows would', () => { + const dir = bin(['php.exe']) + expect( + findOnPath('php', { PATH: dir, PATHEXT: '.EXE' }, 'linux') + ).toBeUndefined() + }) +}) + +// The Windows rules, exercised with the platform passed in: `;` between +// directories, the PATH variable under any casing, and PATHEXT extensions. +describe('findOnPath on Windows', () => { + test('tries each extension in PATHEXT, in order', () => { + const dir = bin(['composer.bat', 'composer.cmd']) + expect( + findOnPath( + 'composer', + { Path: `${bin([])};${dir}`, PATHEXT: '.EXE;.CMD;.BAT' }, + 'win32' + ) + ).toBe(join(dir, 'composer.cmd')) + }) + + test('uses the usual extensions when PATHEXT is not set', () => { + const dir = bin(['php.exe'], ['php.exe']) + expect(findOnPath('php', { PATH: dir }, 'win32')).toBe(join(dir, 'php.exe')) + }) + + test('accepts a name that already has its extension', () => { + const dir = bin(['ddev.exe']) + expect(findOnPath('ddev.exe', { PATH: dir }, 'win32')).toBe( + join(dir, 'ddev.exe') + ) + }) + + test('does not match a file with no extension', () => { + expect(findOnPath('php', { PATH: bin(['php']) }, 'win32')).toBeUndefined() + }) +}) + +describe('checkCommands', () => { + const on = (present: string[]) => (name: string) => + present.includes(name) ? `/usr/bin/${name}` : undefined + const alternatives = [['php', 'composer'], ['ddev']] + + test('is satisfied when every command of one alternative is found', () => { + expect(checkCommands(alternatives, on(['php', 'composer']))).toEqual({ + satisfied: true, + alternatives, + found: ['php', 'composer'], + missing: ['ddev'], + }) + expect(checkCommands(alternatives, on(['ddev'])).satisfied).toBe(true) + }) + + test('is not satisfied when every alternative lacks a command', () => { + expect(checkCommands(alternatives, on(['composer']))).toEqual({ + satisfied: false, + alternatives, + found: ['composer'], + missing: ['php', 'ddev'], + }) + }) + + test('looks a command named twice up once', () => { + const looked: string[] = [] + const result = checkCommands( + [ + ['php', 'composer'], + ['php', 'ddev'], + ], + (name) => { + looked.push(name) + return undefined + } + ) + expect(looked).toEqual(['php', 'composer', 'ddev']) + expect(result.missing).toEqual(['php', 'composer', 'ddev']) + }) +}) + +describe('describeAlternatives', () => { + test('joins commands with and, and alternatives with or', () => { + expect(describeAlternatives([['php', 'composer'], ['ddev']])).toBe( + 'php and composer, or ddev' + ) + expect(describeAlternatives([['ddev']])).toBe('ddev') + expect(describeAlternatives([['php', 'composer', 'drush']])).toBe( + 'php, composer and drush' + ) + }) +}) diff --git a/packages/cli/test/commands/init.test.ts b/packages/cli/test/commands/init.test.ts index 6fcfde8..2e9d7aa 100644 --- a/packages/cli/test/commands/init.test.ts +++ b/packages/cli/test/commands/init.test.ts @@ -105,6 +105,7 @@ describe('drx init', () => { ...CONFIG, installed: false, requires: { node: '16.18.1', tools: ['DDEV'] }, + commands: null, next: ['cd site', 'npm run setup', 'npm run dev'], notes: [], }) @@ -537,3 +538,106 @@ describe('drx init warnings', () => { ) }) }) + +describe('drx init and the commands a starter needs', () => { + const needs = (commands: unknown) => async () => { + await registry.close() + registry = await fixtureRegistry(STARTER_FILES, (entry) => { + const druxt = entry.druxt as { requires: Record } + druxt.requires.commands = commands + }) + } + const on = (present: string[]) => (name: string) => + present.includes(name) ? `/usr/bin/${name}` : undefined + const quiet = { nodeVersion: '16.18.1' } + + describe('with alternatives', () => { + beforeEach(needs([['php', 'composer'], ['ddev']])) + + test('warns once when no alternative is complete, and still creates the site', async () => { + const result = await init(['site', '--yes'], { + ...quiet, + findCommand: on([]), + }) + expect(result.code).toBe(0) + expect(existsSync(join(cwd, 'site', 'drx.config.json'))).toBe(true) + expect(result.stderr.match(/Warning/g)).toHaveLength(1) + expect(result.stderr).toContain( + 'Warning: The quickstart starter needs php and composer, or ddev. Not found on PATH: php, composer, ddev. Install the commands of one alternative before you set up the site.' + ) + }) + + test('names only what is missing', async () => { + const result = await init(['site', '--yes'], { + ...quiet, + findCommand: on(['composer']), + }) + expect(result.stderr).toContain('Not found on PATH: php, ddev.') + }) + + test.each([[['php', 'composer']], [['ddev']]])( + 'does not warn when %j are present', + async (present) => { + const result = await init(['site', '--yes'], { + ...quiet, + findCommand: on(present), + }) + expect(result.code).toBe(0) + expect(result.stderr).not.toContain('Warning') + } + ) + + test('--json reports what was found and what was missing', async () => { + const result = await init(['site', '--yes', '--json'], { + ...quiet, + findCommand: on(['composer']), + }) + expect(result.code).toBe(0) + expect(JSON.parse(result.stdout).commands).toEqual({ + satisfied: false, + alternatives: [['php', 'composer'], ['ddev']], + found: ['composer'], + missing: ['php', 'ddev'], + }) + }) + + test('warns before it installs', async () => { + const install = vi.fn(async () => { + throw new Error('npm install exited with code 1') + }) + const result = await init(['site', '--yes', '--install'], { + ...quiet, + install, + findCommand: on([]), + }) + expect(result.code).toBe(1) + expect(result.stderr).toContain('Not found on PATH: php, composer, ddev.') + }) + }) + + describe('with one set of commands', () => { + beforeEach(needs([['php', 'composer']])) + + test('says to install what is missing', async () => { + const result = await init(['site', '--yes'], { + ...quiet, + findCommand: on(['php']), + }) + expect(result.stderr).toContain( + 'Warning: The quickstart starter needs php and composer. Not found on PATH: composer. Install what is missing before you set up the site.' + ) + }) + }) + + test('an entry that names no commands is not checked', async () => { + const findCommand = vi.fn() + const result = await init(['site', '--yes', '--json'], { + ...quiet, + findCommand, + }) + expect(result.code).toBe(0) + expect(findCommand).not.toHaveBeenCalled() + expect(JSON.parse(result.stdout).commands).toBeNull() + expect(result.stderr).not.toContain('Warning') + }) +}) diff --git a/packages/cli/test/commands/module.test.ts b/packages/cli/test/commands/module.test.ts new file mode 100644 index 0000000..5303e67 --- /dev/null +++ b/packages/cli/test/commands/module.test.ts @@ -0,0 +1,516 @@ +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import type { CliContext } from '../../src/context.js' +import { moduleRegistry } from '../helpers/modules.js' +import { run } from '../helpers/run.js' +import { serve, type TestServer } from '../helpers/server.js' +import { cleanTmp, tmp, writeTree } from '../helpers/tmp.js' + +let server: TestServer +let url: string + +beforeEach(async () => { + server = await serve({ '/modules.json': JSON.stringify(moduleRegistry()) }) + url = `${server.url}/modules.json` +}) + +afterEach(async () => { + await server.close() + cleanTmp() +}) + +const drx = (argv: string[], overrides: Partial = {}) => + run(argv, { defaultModuleRegistry: url, ...overrides }) + +/** + * A project whose frontend part has blocks installed, asks for node-preview + * without having it, and has druxt 0.25.2 brought in by another package. + */ +function project(): string { + const root = tmp('drx-project-') + writeTree(root, { + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [ + { role: 'frontend', kind: 'nuxt', path: 'nuxt' }, + { role: 'backend', kind: 'drupal', path: 'drupal' }, + ], + }, + 'nuxt/package.json': { + dependencies: { + nuxt: '2.15.8', + 'druxt-blocks': '^0.25.1', + '@druxt-contrib/node-preview': '^1.0.0', + }, + }, + 'nuxt/node_modules/druxt/package.json': { version: '0.25.2' }, + 'nuxt/node_modules/druxt-blocks/package.json': { version: '0.25.3' }, + 'drupal/composer.json': { require: { 'drupal/core-recommended': '~11' } }, + }) + return root +} + +describe('drx module list outside a project', () => { + test('lists the modules, without the archived ones', async () => { + const result = await drx(['module', 'list']) + expect(result.code).toBe(0) + expect(result.stdout).toBe( + [ + 'Name Package Type Status Druxt', + 'auth druxt-auth official stable unknown', + 'blocks druxt-blocks official stable ^0.25.1', + 'ckeditor - contrib unreleased unknown', + 'node-preview @druxt-contrib/node-preview contrib stable >=0.26.0 <1', + '', + ].join('\n') + ) + expect(result.stderr).toBe(`Modules from ${url}.\n`) + }) + + test('--all adds the archived ones, marked, with a range that is not stated', async () => { + const result = await drx(['module', 'list', '--all']) + expect(result.stdout).toMatch( + /^legacy +druxt-legacy +contrib +stable \(archived\) +not stated$/m + ) + }) + + test('--type and --category filter', async () => { + const contrib = await drx(['module', 'list', '--type', 'contrib']) + expect(contrib.stdout).not.toContain('auth') + expect(contrib.stdout).toContain('ckeditor') + expect(contrib.stdout).toContain('node-preview') + + const both = await drx([ + 'module', + 'list', + '--type', + 'Contrib', + '--category', + 'authoring-and-preview', + '--json', + ]) + expect( + JSON.parse(both.stdout).modules.map((m: { name: string }) => m.name) + ).toEqual(['ckeditor', 'node-preview']) + }) + + test('says so when nothing matches', async () => { + const result = await drx(['module', 'list', '--type', 'imaginary']) + expect(result.code).toBe(0) + expect(result.stdout).toBe('No modules match.\n') + }) + + test('--json gives the rows, the registry and no project', async () => { + const result = await drx(['module', 'list', '--json']) + const data = JSON.parse(result.stdout) + expect(result.code).toBe(0) + expect(data.project).toBeNull() + expect(data.registry).toMatchObject({ url, origin: 'remote', ageMs: 0 }) + expect(data.modules).toHaveLength(4) + expect(data.modules[2]).toEqual({ + name: 'ckeditor', + npm: null, + type: 'contrib', + status: 'unreleased', + category: 'authoring-and-preview', + archived: false, + description: 'Render CKEditor content with components', + druxt: 'unknown', + }) + }) +}) + +describe('drx module list in a project', () => { + test('adds what is installed and whether its range admits the Druxt there', async () => { + const root = project() + const result = await drx(['module', 'list'], { cwd: join(root, 'nuxt') }) + expect(result.code).toBe(0) + expect(result.stdout).toBe( + [ + 'Name Package Type Status Druxt Installed Compatible', + 'auth druxt-auth official stable unknown no unknown', + 'blocks druxt-blocks official stable ^0.25.1 0.25.3 yes', + 'ckeditor - contrib unreleased unknown - unknown', + 'node-preview @druxt-contrib/node-preview contrib stable >=0.26.0 <1 declared no', + '', + ].join('\n') + ) + expect(result.stderr).toContain( + `Project ${root}: nuxt/ has druxt 0.25.2 installed.` + ) + }) + + test('--json has a row per frontend part for each module', async () => { + const root = project() + const result = await drx(['module', 'list', '--json'], { cwd: root }) + const data = JSON.parse(result.stdout) + expect(data.project).toEqual({ + root, + parts: [ + { + path: 'nuxt', + kind: 'nuxt', + druxt: { name: 'druxt', range: null, installed: '0.25.2' }, + }, + ], + }) + expect(data.modules[1].parts).toEqual([ + { + path: 'nuxt', + installed: '0.25.3', + declared: '^0.25.1', + compatibility: 'compatible', + }, + ]) + expect(data.modules[0].parts[0]).toEqual({ + path: 'nuxt', + installed: null, + declared: null, + compatibility: 'unknown', + }) + expect(data.modules[3].parts[0]).toEqual({ + path: 'nuxt', + installed: null, + declared: '^1.0.0', + compatibility: 'incompatible', + }) + }) + + test('says when the part has no Druxt to compare with', async () => { + const root = tmp() + writeTree(root, { + 'drx.config.json': { + layout: 'monorepo', + line: '0.x', + starter: 'quickstart', + source: 'npm', + parts: [{ role: 'frontend', kind: 'nuxt', path: 'web' }], + }, + 'web/package.json': { dependencies: { nuxt: '2.15.8' } }, + }) + const result = await drx(['module', 'list'], { cwd: root }) + expect(result.stderr).toContain(`Project ${root}: web/ has no druxt.`) + expect(result.stdout).toMatch(/^blocks .* no +unknown$/m) + }) +}) + +describe('drx module search', () => { + test('matches the name, the package and the description, in any case', async () => { + const byName = await drx(['module', 'search', 'BLOCK']) + expect(byName.stdout).toContain('blocks') + expect(byName.stdout).not.toContain('auth') + + const byPackage = await drx(['module', 'search', 'druxt-contrib', '--json']) + expect( + JSON.parse(byPackage.stdout).modules.map((m: { name: string }) => m.name) + ).toEqual(['node-preview']) + + const byDescription = await drx(['module', 'search', 'unsaved content']) + expect(byDescription.stdout).toContain('node-preview') + expect(byDescription.stdout).not.toContain('blocks') + }) + + test('says so when nothing matches', async () => { + const result = await drx(['module', 'search', 'zzz']) + expect(result.code).toBe(0) + expect(result.stdout).toBe('No modules match.\n') + }) + + test('takes the same filters as list', async () => { + const hidden = await drx(['module', 'search', 'legacy']) + expect(hidden.stdout).toBe('No modules match.\n') + const shown = await drx(['module', 'search', 'legacy', '--all']) + expect(shown.stdout).toContain('druxt-legacy') + }) + + test('fails without text to search for', async () => { + const result = await drx(['module', 'search']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Give the text to search for, as in "drx module search menu".' + ) + }) +}) + +describe('drx module info', () => { + test('prints one module in full', async () => { + const result = await drx(['module', 'info', 'auth']) + expect(result.code).toBe(0) + expect(result.stdout).toBe( + [ + 'auth', + 'Authentication module for DruxtJS', + '', + 'Package druxt-auth', + 'Type official', + 'Status stable', + 'Category authentication', + 'Druxt unknown', + 'Repository https://github.com/druxt/druxt-auth', + 'Website https://github.com/druxt/druxt-auth', + '', + 'Backend modules it needs:', + ' drupal simple_oauth Simple OAuth https://www.drupal.org/project/simple_oauth', + '', + ].join('\n') + ) + }) + + test('finds a module by its package name, and marks core modules', async () => { + const result = await drx(['module', 'info', 'druxt-blocks']) + expect(result.code).toBe(0) + expect(result.stdout).toContain( + 'Repository https://github.com/druxt/druxt.js/tree/HEAD/packages/blocks' + ) + expect(result.stdout).toContain(' drupal block Block (core)') + }) + + test('core is unknown when the registry marks no module as core', async () => { + // The registry as it is published: no entry says which modules are core. + const registry = moduleRegistry() + for (const module of registry.modules) { + for (const need of (module.drupal ?? []) as Record[]) { + delete need.core + } + } + server.files['/modules.json'] = JSON.stringify(registry) + + const json = await drx(['module', 'info', 'blocks', '--json']) + expect(JSON.parse(json.stdout).module.backend).toEqual([ + { kind: 'drupal', name: 'block', label: 'Block', core: null }, + ]) + const text = await drx(['module', 'info', 'blocks']) + expect(text.stdout).toContain( + [ + 'Backend modules it needs:', + ' drupal block Block', + 'The registry does not say which of these are part of core.', + ].join('\n') + ) + }) + + test('a module is not core when the registry marks the ones that are', async () => { + const result = await drx(['module', 'info', 'auth', '--json']) + expect(JSON.parse(result.stdout).module.backend[0].core).toBe(false) + const text = await drx(['module', 'info', 'auth']) + expect(text.stdout).not.toContain('The registry does not say') + }) + + test('says what a module lacks', async () => { + const ckeditor = await drx(['module', 'info', 'ckeditor']) + expect(ckeditor.stdout).toContain('Package not published') + const legacy = await drx(['module', 'info', 'legacy']) + expect(legacy.stdout).toContain('Status stable (archived)') + expect(legacy.stdout).toContain('Druxt not stated') + expect(legacy.stdout).toContain('Backend modules it needs: none listed.') + }) + + test('in a project adds the installed version and the compatibility', async () => { + const root = project() + const blocks = await drx(['module', 'info', 'blocks'], { cwd: root }) + expect(blocks.stdout).toContain( + [ + 'In nuxt/:', + ' Installed 0.25.3 (asked for as ^0.25.1)', + ' Druxt 0.25.2 installed', + ' Compatible yes', + '', + ].join('\n') + ) + const preview = await drx(['module', 'info', 'node-preview'], { cwd: root }) + expect(preview.stdout).toContain( + [ + 'In nuxt/:', + ' Installed no (asked for as ^1.0.0)', + ' Druxt 0.25.2 installed', + ' Compatible no', + '', + ].join('\n') + ) + const auth = await drx(['module', 'info', 'auth'], { cwd: root }) + expect(auth.stdout).toContain(' Installed no\n') + expect(auth.stdout).toContain(' Compatible unknown') + }) + + test('--json has the whole entry', async () => { + const root = project() + const result = await drx(['module', 'info', 'blocks', '--json'], { + cwd: root, + }) + const data = JSON.parse(result.stdout) + expect(data.module).toEqual({ + name: 'blocks', + npm: 'druxt-blocks', + type: 'official', + status: 'stable', + category: 'site-and-layout', + archived: false, + description: 'Drupal Blocks, Block Regions and more', + druxt: '^0.25.1', + repository: 'https://github.com/druxt/druxt.js/tree/HEAD/packages/blocks', + website: 'https://druxtjs.org/modules/blocks', + backend: [{ kind: 'drupal', name: 'block', label: 'Block', core: true }], + parts: [ + { + path: 'nuxt', + installed: '0.25.3', + declared: '^0.25.1', + compatibility: 'compatible', + }, + ], + }) + expect(data.project.root).toBe(root) + }) + + test('fails on an unknown name, with the closest ones', async () => { + const result = await drx(['module', 'info', 'blok', '--json']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'There is no module named "blok". Closest: blocks.' + ) + expect(JSON.parse(result.stdout).error.code).toBe('unknown-module') + }) + + test('fails on a name nothing is close to', async () => { + const result = await drx(['module', 'info', 'zzzzzzzzzz']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'There is no module named "zzzzzzzzzz". Run "drx module list --all" to see every name.' + ) + }) + + test('fails without a name', async () => { + const result = await drx(['module', 'info']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Give the name of a module, as in "drx module info blocks".' + ) + }) +}) + +describe('the module registry the commands read', () => { + test('--module-registry takes a URL', async () => { + server.files['/other.json'] = JSON.stringify({ + schemaVersion: 1, + modules: [], + }) + const other = `${server.url}/other.json` + const result = await drx(['module', 'list', '--module-registry', other]) + expect(result.stderr).toBe(`Modules from ${other}.\n`) + expect(result.stdout).toBe('No modules match.\n') + }) + + test('--module-registry takes a name from the user configuration', async () => { + const home = tmp() + writeTree(home, { 'config.json': { moduleRegistries: { ours: url } } }) + const result = await drx(['module', 'list', '--module-registry', 'ours'], { + defaultModuleRegistry: 'http://127.0.0.1:9/unused.json', + env: { DRX_CONFIG: join(home, 'config.json') }, + }) + expect(result.code).toBe(0) + expect(result.stderr).toBe(`Modules from ${url}.\n`) + }) + + test('says when a fresh copy was used, and --refresh reads again', async () => { + const cacheDir = tmp('drx-cache-') + const start = new Date('2026-11-16T10:00:00Z') + await drx(['module', 'list'], { cacheDir, now: () => start }) + const later = { cacheDir, now: () => new Date(start.getTime() + 600_000) } + + const cached = await drx(['module', 'list'], later) + expect(cached.stderr).toBe(`Modules from ${url}, read 10 minutes ago.\n`) + expect(server.requests).toHaveLength(1) + + const refreshed = await drx(['module', 'list', '--refresh'], later) + expect(refreshed.stderr).toBe(`Modules from ${url}.\n`) + expect(server.requests).toHaveLength(2) + }) + + test('says when an old copy stood in for a registry that cannot be read', async () => { + const cacheDir = tmp('drx-cache-') + const start = new Date('2026-11-16T10:00:00Z') + await drx(['module', 'list'], { cacheDir, now: () => start }) + delete server.files['/modules.json'] + + const result = await drx(['module', 'list', '--json'], { + cacheDir, + now: () => new Date(start.getTime() + 3 * 86_400_000), + }) + expect(result.code).toBe(0) + expect(result.stderr).toBe( + `Could not read ${url}: 404 Not Found.\nUsing the copy of the registry read 3 days ago.\n` + ) + expect(JSON.parse(result.stdout).registry).toMatchObject({ + origin: 'cache', + ageMs: 3 * 86_400_000, + reason: `Could not read ${url}: 404 Not Found.`, + }) + }) + + test('fails on a schemaVersion it does not know', async () => { + server.files['/modules.json'] = JSON.stringify({ + schemaVersion: 2, + modules: [], + }) + const result = await drx(['module', 'list']) + expect(result.code).toBe(1) + expect(result.stderr).toContain('has schemaVersion 2') + }) +}) + +describe('the module commands that are not built', () => { + test.each(['add', 'remove', 'configure'])( + 'drx module %s says it is not available yet', + async (command) => { + const result = await drx(['module', command, 'blocks', '--json']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + `drx module ${command} is not available yet. Run "drx module --help" for the commands this version has.` + ) + expect(JSON.parse(result.stdout).error.code).toBe('not-available') + expect(server.requests).toEqual([]) + } + ) +}) + +describe('drx module usage', () => { + test('--help lists the module commands', async () => { + const result = await drx(['module', '--help']) + expect(result.code).toBe(0) + expect(result.stdout).toContain('USAGE drx module') + for (const name of [ + 'list', + 'search', + 'info', + 'add', + 'remove', + 'configure', + ]) { + expect(result.stdout).toMatch(new RegExp(`^ +${name} `, 'm')) + } + }) + + test(' --help describes that command', async () => { + const result = await drx(['module', 'list', '--help']) + expect(result.code).toBe(0) + expect(result.stdout).toContain('USAGE drx module list') + expect(result.stdout).toContain('--module-registry') + }) + + test('fails on an unknown option, naming it', async () => { + const result = await drx(['module', 'list', '--archived']) + expect(result.code).toBe(1) + expect(result.stderr).toContain( + 'Unknown option --archived. Run "drx module list --help" for the options.' + ) + }) + + test('fails with no module command', async () => { + const result = await drx(['module']) + expect(result.code).toBe(1) + expect(result.stderr).toContain('No command specified') + }) +}) diff --git a/packages/cli/test/e2e/modules.test.ts b/packages/cli/test/e2e/modules.test.ts new file mode 100644 index 0000000..883dcbe --- /dev/null +++ b/packages/cli/test/e2e/modules.test.ts @@ -0,0 +1,32 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { run } from '../helpers/run.js' +import { cleanTmp } from '../helpers/tmp.js' + +// Reads the published module registry over the network. Skipped unless +// DRX_E2E=1, which `npm run test:e2e` sets. +describe.skipIf(process.env.DRX_E2E !== '1')( + 'the published module registry', + () => { + afterEach(cleanTmp) + + test('is read and listed by drx module list', async () => { + const result = await run(['module', 'list', '--all', '--json']) + expect(result.stderr).toContain('Modules from https://cdn.jsdelivr.net/') + expect(result.code).toBe(0) + + const { registry, modules } = JSON.parse(result.stdout) + expect(registry.origin).toBe('remote') + expect(modules.length).toBeGreaterThan(0) + // The module that is Druxt itself is the one entry certain to stay. + expect(modules.map((module: { name: string }) => module.name)).toContain( + 'druxt' + ) + }, 60_000) + + test('has an entry drx module info can show by its package name', async () => { + const result = await run(['module', 'info', 'druxt', '--json']) + expect(result.code).toBe(0) + expect(JSON.parse(result.stdout).module.name).toBe('druxt') + }, 60_000) + } +) diff --git a/packages/cli/test/helpers/modules.ts b/packages/cli/test/helpers/modules.ts new file mode 100644 index 0000000..93e85f7 --- /dev/null +++ b/packages/cli/test/helpers/modules.ts @@ -0,0 +1,90 @@ +/** A module registry in the published shape, small enough to read. */ +export function moduleRegistry(): { + schemaVersion: number + modules: Record[] +} { + return { + schemaVersion: 1, + modules: [ + { + name: 'auth', + repo: 'druxt/druxt-auth', + category: 'authentication', + status: 'stable', + icon: 'auth.svg', + drupal: [ + { + name: 'simple_oauth', + label: 'Simple OAuth', + url: 'https://www.drupal.org/project/simple_oauth', + }, + ], + type: 'official', + archived: false, + description: 'Authentication module for DruxtJS', + npm: 'druxt-auth', + compatibility: { druxt: 'unknown' }, + website: 'https://github.com/druxt/druxt-auth', + }, + { + name: 'blocks', + repo: 'druxt/druxt.js', + path: 'packages/blocks', + category: 'site-and-layout', + status: 'stable', + drupal: [{ name: 'block', label: 'Block', core: true }], + type: 'official', + archived: false, + description: 'Drupal Blocks, Block Regions and more', + npm: 'druxt-blocks', + compatibility: { druxt: '^0.25.1' }, + website: 'https://druxtjs.org/modules/blocks', + }, + { + name: 'ckeditor', + repo: 'druxt-contrib/druxt-ckeditor', + category: 'authoring-and-preview', + status: 'unreleased', + drupal: [{ name: 'ckeditor5', label: 'CKEditor 5', core: true }], + type: 'contrib', + archived: false, + description: 'Render CKEditor content with components', + compatibility: { druxt: 'unknown' }, + }, + { + name: 'legacy', + repo: 'druxt-contrib/druxt-legacy', + category: 'site-and-layout', + status: 'stable', + type: 'contrib', + archived: true, + description: 'An archived module with no stated range', + npm: 'druxt-legacy', + }, + { + name: 'node-preview', + repo: 'druxt-contrib/druxt-node-preview', + category: 'authoring-and-preview', + status: 'stable', + drupal: [ + { name: 'jsonapi_node_preview', label: 'JSON:API Node Preview' }, + ], + type: 'contrib', + archived: false, + description: 'Preview unsaved content in the frontend', + npm: '@druxt-contrib/node-preview', + compatibility: { druxt: '>=0.26.0 <1' }, + }, + ], + } +} + +/** The fixture registry with one change made to one module. */ +export function moduleRegistryWith( + index: number, + change: (module: Record) => void +) { + const registry = moduleRegistry() + change(registry.modules[index] as Record) + return registry +} diff --git a/packages/cli/test/helpers/run.ts b/packages/cli/test/helpers/run.ts index 1b62217..966a2d6 100644 --- a/packages/cli/test/helpers/run.ts +++ b/packages/cli/test/helpers/run.ts @@ -1,3 +1,4 @@ +import { join } from 'node:path' import { stripVTControlCharacters } from 'node:util' import { runCli } from '../../src/cli.js' import type { CliContext } from '../../src/context.js' @@ -11,7 +12,7 @@ export interface RunResult { /** * Runs the CLI in-process with captured output, no terminal, a fixed Node - * version and a user configuration directory that is empty. + * version, and user configuration and cache directories that are empty. */ export async function run( argv: string[], @@ -22,10 +23,16 @@ export async function run( const code = await runCli(argv, { cwd: tmp(), env: { XDG_CONFIG_HOME: tmp('drx-config-') }, + cacheDir: tmp('drx-cache-'), stdout: { write: (chunk) => (stdout += chunk) }, stderr: { write: (chunk) => (stderr += chunk) }, interactive: false, nodeVersion: '24.18.0', + // A test that serves its own default registry is about that registry. With + // no bundled copy to compare revisions with, the one served is read. + ...(overrides.defaultRegistry && !overrides.bundledRegistryDir + ? { bundledRegistryDir: join(tmp(), 'no-bundled-copy') } + : {}), ...overrides, }) return { diff --git a/packages/cli/test/modules/compatibility.test.ts b/packages/cli/test/modules/compatibility.test.ts new file mode 100644 index 0000000..0713e81 --- /dev/null +++ b/packages/cli/test/modules/compatibility.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, test } from 'vitest' +import { compatibility } from '../../src/modules/compatibility.js' + +const druxt = (range: string | null, installed: string | null) => ({ + name: 'druxt', + range, + installed, +}) + +describe('compatibility', () => { + test('compares the installed version with the range', () => { + expect(compatibility('^0.25.1', druxt('^0.25.0', '0.25.2'))).toBe( + 'compatible' + ) + expect(compatibility('^0.25.1', druxt('^0.25.0', '0.25.0'))).toBe( + 'incompatible' + ) + expect(compatibility('>=0.21.0 <1', druxt(null, '0.25.2'))).toBe( + 'compatible' + ) + expect(compatibility('>=0.26.0 <1', druxt(null, '0.25.2'))).toBe( + 'incompatible' + ) + }) + + test('counts a prerelease of a version inside the range', () => { + expect(compatibility('>=0.25.0 <1', druxt(null, '0.26.0-next.1'))).toBe( + 'compatible' + ) + }) + + test('compares the range asked for when nothing is installed', () => { + expect(compatibility('^0.25.1', druxt('^0.25.0', null))).toBe('compatible') + expect(compatibility('^0.25.1', druxt('^0.24.0', null))).toBe( + 'incompatible' + ) + }) + + test.each([undefined, 'unknown', 'whenever', ''])( + 'is unknown, never compatible, when the module states %j', + (range) => { + expect(compatibility(range, druxt('^0.25.0', '0.25.2'))).toBe('unknown') + } + ) + + test('is unknown when the part has no Druxt version to compare', () => { + expect(compatibility('^0.25.1', undefined)).toBe('unknown') + expect(compatibility('^0.25.1', druxt(null, null))).toBe('unknown') + expect(compatibility('^0.25.1', druxt('github:druxt/druxt.js', null))).toBe( + 'unknown' + ) + expect(compatibility('^0.25.1', druxt(null, 'not-a-version'))).toBe( + 'unknown' + ) + }) +}) diff --git a/packages/cli/test/modules/entry.test.ts b/packages/cli/test/modules/entry.test.ts new file mode 100644 index 0000000..fd0aba4 --- /dev/null +++ b/packages/cli/test/modules/entry.test.ts @@ -0,0 +1,185 @@ +import { describe, expect, test } from 'vitest' +import { DrxError } from '../../src/errors.js' +import { parseModuleRegistry } from '../../src/modules/entry.js' +import { moduleRegistry, moduleRegistryWith } from '../helpers/modules.js' + +const AT = 'https://example.com/modules.json' +const NPM_NAME = 'modules[1].npm must be the name of an npm package' +const MODULE_NAME = + 'modules[1].drupal[0].name must be a machine name: lower-case letters, digits and underscores, starting with a letter' + +describe('parseModuleRegistry', () => { + test('reads an entry, keeping what the CLI uses', () => { + const [auth, blocks] = parseModuleRegistry(moduleRegistry(), AT) + expect(auth).toEqual({ + name: 'auth', + npm: 'druxt-auth', + repo: 'druxt/druxt-auth', + category: 'authentication', + status: 'stable', + type: 'official', + archived: false, + description: 'Authentication module for DruxtJS', + website: 'https://github.com/druxt/druxt-auth', + druxt: 'unknown', + backend: [ + { + kind: 'drupal', + name: 'simple_oauth', + label: 'Simple OAuth', + url: 'https://www.drupal.org/project/simple_oauth', + }, + ], + }) + expect(blocks?.path).toBe('packages/blocks') + expect(blocks?.druxt).toBe('^0.25.1') + expect(blocks?.backend).toEqual([ + { kind: 'drupal', name: 'block', label: 'Block', core: true }, + ]) + }) + + test('keeps core as the registry states it, and absent when it does not', () => { + const registry = moduleRegistryWith(0, (module) => { + module.drupal = [ + { name: 'one', label: 'One', core: false }, + { name: 'two', label: 'Two' }, + ] + }) + const [auth] = parseModuleRegistry(registry, AT) + expect(auth?.backend).toEqual([ + { kind: 'drupal', name: 'one', label: 'One', core: false }, + { kind: 'drupal', name: 'two', label: 'Two' }, + ]) + }) + + test.each([ + 'druxt', + 'druxt-blocks', + '@druxt-contrib/node-preview', + '@druxt/core', + 'druxt.js', + 'druxt_blocks', + '', + ])('takes %j as the name of a package', (npm) => { + const registry = moduleRegistryWith(1, (module) => { + module.npm = npm + }) + expect(parseModuleRegistry(registry, AT)[1]?.npm).toBe(npm) + }) + + test.each(['block', 'jsonapi_menu_items', 'ckeditor5', 'a'])( + 'takes %j as the name of a backend module', + (name) => { + const registry = moduleRegistryWith(1, (module) => { + module.drupal = [{ name, label: 'Block' }] + }) + expect(parseModuleRegistry(registry, AT)[1]?.backend[0]?.name).toBe(name) + } + ) + + test('fills in what an entry leaves out', () => { + const modules = parseModuleRegistry(moduleRegistry(), AT) + const ckeditor = modules.find(({ name }) => name === 'ckeditor') + const legacy = modules.find(({ name }) => name === 'legacy') + expect(ckeditor?.npm).toBeUndefined() + expect(legacy?.druxt).toBeUndefined() + expect(legacy?.backend).toEqual([]) + expect(legacy?.archived).toBe(true) + }) + + test('ignores fields it does not know', () => { + const registry = { + ...moduleRegistryWith(0, (module) => { + module.downloads = { weekly: 12 } + }), + generatedAt: '2026-11-16', + } + expect(parseModuleRegistry(registry, AT)).toEqual( + parseModuleRegistry(moduleRegistry(), AT) + ) + }) + + test('refuses a schemaVersion it does not know, saying so', () => { + const attempt = () => + parseModuleRegistry({ ...moduleRegistry(), schemaVersion: 2 }, AT) + expect(attempt).toThrow(DrxError) + expect(attempt).toThrow( + `The module registry at ${AT} has schemaVersion 2, and this version of the CLI reads schemaVersion 1. Update @druxt/cli to read it.` + ) + }) + + test.each([ + ['a string', 'it must be an object'], + [{ modules: [] }, 'schemaVersion must be a number'], + [{ schemaVersion: 1 }, 'modules must be an array'], + [{ schemaVersion: 1, modules: ['x'] }, 'modules[0] must be an object'], + ])('names what is wrong with %j', (registry, message) => { + expect(() => parseModuleRegistry(registry, AT)).toThrow( + `The module registry at ${AT} is invalid: ${message}.` + ) + }) + + test.each([ + ['name', undefined, 'modules[1].name must be a non-empty string'], + ['name', '', 'modules[1].name must be a non-empty string'], + ['repo', 7, 'modules[1].repo must be a non-empty string'], + ['category', undefined, 'modules[1].category must be a non-empty string'], + ['status', null, 'modules[1].status must be a non-empty string'], + ['type', [], 'modules[1].type must be a non-empty string'], + ['npm', 7, 'modules[1].npm must be a string'], + ['path', {}, 'modules[1].path must be a string'], + ['description', 7, 'modules[1].description must be a string'], + ['website', false, 'modules[1].website must be a string'], + ['archived', 'no', 'modules[1].archived must be true or false'], + ['compatibility', '^1', 'modules[1].compatibility must be an object'], + [ + 'compatibility', + { druxt: 1 }, + 'modules[1].compatibility.druxt must be a string', + ], + ['drupal', 'block', 'modules[1].drupal must be an array'], + ['drupal', ['block'], 'modules[1].drupal[0] must be an object'], + [ + 'drupal', + [{ label: 'Block' }], + 'modules[1].drupal[0].name must be a non-empty string', + ], + [ + 'drupal', + [{ name: 'block' }], + 'modules[1].drupal[0].label must be a non-empty string', + ], + [ + 'drupal', + [{ name: 'block', label: 'Block', core: 'yes' }], + 'modules[1].drupal[0].core must be true or false', + ], + [ + 'drupal', + [{ name: 'block', label: 'Block', url: 7 }], + 'modules[1].drupal[0].url must be a string', + ], + ['npm', '--registry=https://example.com', NPM_NAME], + ['npm', '-g', NPM_NAME], + ['npm', 'druxt-blocks & calc', NPM_NAME], + ['npm', 'Druxt-Blocks', NPM_NAME], + ['npm', '../druxt-blocks', NPM_NAME], + ['npm', '@druxt/', NPM_NAME], + ['npm', 'druxt-blocks@latest', NPM_NAME], + ['npm', 'a'.repeat(215), NPM_NAME], + ['drupal', [{ name: '--uri=example.com', label: 'Block' }], MODULE_NAME], + ['drupal', [{ name: 'block,node', label: 'Block' }], MODULE_NAME], + ['drupal', [{ name: 'block node', label: 'Block' }], MODULE_NAME], + ['drupal', [{ name: 'Block', label: 'Block' }], MODULE_NAME], + ['drupal', [{ name: '9lives', label: 'Block' }], MODULE_NAME], + ['drupal', [{ name: 'block|calc', label: 'Block' }], MODULE_NAME], + ])('names the bad field: %s = %j', (field, value, message) => { + const registry = moduleRegistryWith(1, (module) => { + if (value === undefined) delete module[field] + else module[field] = value + }) + expect(() => parseModuleRegistry(registry, AT)).toThrow( + `The module registry at ${AT} is invalid: ${message}.` + ) + }) +}) diff --git a/packages/cli/test/modules/registry.test.ts b/packages/cli/test/modules/registry.test.ts new file mode 100644 index 0000000..15cfb74 --- /dev/null +++ b/packages/cli/test/modules/registry.test.ts @@ -0,0 +1,172 @@ +import { readdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import { + DEFAULT_MODULE_REGISTRY, + describeAge, + FRESH_FOR_MS, + loadModules, +} from '../../src/modules/registry.js' +import { moduleRegistry } from '../helpers/modules.js' +import { serve, type TestServer } from '../helpers/server.js' +import { cleanTmp, tmp } from '../helpers/tmp.js' + +const MINUTE = 60 * 1000 +const START = new Date('2026-11-16T10:00:00Z') + +let server: TestServer +let cacheDir: string +let url: string + +beforeEach(async () => { + server = await serve({ '/modules.json': JSON.stringify(moduleRegistry()) }) + url = `${server.url}/modules.json` + cacheDir = tmp('drx-cache-') +}) + +afterEach(async () => { + await server.close() + cleanTmp() +}) + +const load = (after = 0, options: { refresh?: boolean; url?: string } = {}) => + loadModules({ + url: options.url ?? url, + cacheDir, + now: () => new Date(START.getTime() + after), + ...(options.refresh ? { refresh: true } : {}), + }) + +describe('loadModules', () => { + test('points at the published registry by default', () => { + expect(DEFAULT_MODULE_REGISTRY).toBe( + 'https://cdn.jsdelivr.net/gh/druxt/modules@main/modules.json' + ) + }) + + test('reads the registry and keeps a copy', async () => { + const loaded = await load() + expect(loaded.modules.map(({ name }) => name)).toEqual([ + 'auth', + 'blocks', + 'ckeditor', + 'legacy', + 'node-preview', + ]) + expect(loaded).toMatchObject({ + url, + origin: 'remote', + fetchedAt: START.toISOString(), + ageMs: 0, + }) + expect(loaded.reason).toBeUndefined() + expect(readdirSync(cacheDir, { recursive: true }).length).toBeGreaterThan(0) + }) + + test('uses the copy without a request while it is under an hour old', async () => { + await load() + const loaded = await load(59 * MINUTE) + expect(server.requests).toHaveLength(1) + expect(loaded).toMatchObject({ + origin: 'cache', + fetchedAt: START.toISOString(), + ageMs: 59 * MINUTE, + }) + expect(loaded.reason).toBeUndefined() + expect(loaded.modules).toHaveLength(5) + expect(FRESH_FOR_MS).toBe(60 * MINUTE) + }) + + test('reads the registry again once the copy is an hour old', async () => { + await load() + const loaded = await load(60 * MINUTE) + expect(server.requests).toHaveLength(2) + expect(loaded.origin).toBe('remote') + expect(loaded.ageMs).toBe(0) + }) + + test('reads the registry again when asked to refresh', async () => { + await load() + const loaded = await load(MINUTE, { refresh: true }) + expect(server.requests).toHaveLength(2) + expect(loaded.origin).toBe('remote') + }) + + test('falls back to an old copy when the registry cannot be read, and says why', async () => { + await load() + delete server.files['/modules.json'] + const loaded = await load(3 * 24 * 60 * MINUTE) + expect(loaded).toMatchObject({ + origin: 'cache', + fetchedAt: START.toISOString(), + ageMs: 3 * 24 * 60 * MINUTE, + reason: `Could not read ${url}: 404 Not Found.`, + }) + expect(loaded.modules).toHaveLength(5) + }) + + test('fails when the registry cannot be read and there is no copy', async () => { + delete server.files['/modules.json'] + await expect(load()).rejects.toThrow( + `Could not read ${url}: 404 Not Found. There is no cached copy to use.` + ) + }) + + test('keeps a copy per registry', async () => { + await load() + server.files['/other.json'] = JSON.stringify({ + schemaVersion: 1, + modules: [], + }) + const other = await load(MINUTE, { url: `${server.url}/other.json` }) + expect(other.origin).toBe('remote') + expect(other.modules).toEqual([]) + expect((await load(MINUTE)).modules).toHaveLength(5) + }) + + test('refuses an unknown schemaVersion and does not fall back to the copy', async () => { + await load() + server.files['/modules.json'] = JSON.stringify({ + schemaVersion: 2, + modules: [], + }) + await expect(load(2 * 60 * MINUTE)).rejects.toThrow( + 'has schemaVersion 2, and this version of the CLI reads schemaVersion 1' + ) + // The refused registry did not replace the copy. + expect((await load(2 * 60 * MINUTE - 61 * MINUTE)).origin).toBe('cache') + }) + + test('fails on a registry that is not JSON', async () => { + server.files['/modules.json'] = '' + await expect(load()).rejects.toThrow( + `Could not read ${url}: it is not valid JSON.` + ) + }) + + test('ignores a copy it cannot read', async () => { + await load() + const [file] = readdirSync(cacheDir, { recursive: true }).filter((name) => + String(name).endsWith('.json') + ) + writeFileSync(join(cacheDir, String(file)), '{ broken') + const loaded = await load(MINUTE) + expect(loaded.origin).toBe('remote') + expect(server.requests).toHaveLength(2) + }) +}) + +describe('describeAge', () => { + test.each([ + [0, 'less than a minute'], + [59_000, 'less than a minute'], + [MINUTE, '1 minute'], + [59 * MINUTE, '59 minutes'], + [60 * MINUTE, '1 hour'], + [47 * 60 * MINUTE, '47 hours'], + [48 * 60 * MINUTE, '2 days'], + [30 * 24 * 60 * MINUTE, '30 days'], + ])('%i ms is %s', (ms, text) => { + expect(describeAge(ms)).toBe(text) + }) +}) diff --git a/packages/cli/test/registry/entry.test.ts b/packages/cli/test/registry/entry.test.ts index 8013b46..12ee20e 100644 --- a/packages/cli/test/registry/entry.test.ts +++ b/packages/cli/test/registry/entry.test.ts @@ -16,6 +16,14 @@ describe('validateEntry', () => { expect(validateEntry(entry, 'quickstart')).toEqual(entry) }) + test('accepts alternatives of commands the site needs', () => { + const entry = entryWith('druxt.requires.commands', [ + ['php', 'composer'], + ['ddev'], + ]) + expect(validateEntry(entry, 'quickstart')).toEqual(entry) + }) + test('rejects a value that is not an object', () => { expect(() => validateEntry('nope', 'quickstart')).toThrow( 'Starter entry "quickstart" is invalid: the entry must be an object.' @@ -85,6 +93,41 @@ describe('validateEntry', () => { [1], 'druxt.requires.tools must be an array of strings', ], + [ + 'druxt.requires.commands', + 'php', + 'druxt.requires.commands must be a non-empty array of alternatives', + ], + [ + 'druxt.requires.commands', + [], + 'druxt.requires.commands must be a non-empty array of alternatives', + ], + [ + 'druxt.requires.commands', + [['php'], 'ddev'], + 'druxt.requires.commands[1] must be a non-empty array of command names', + ], + [ + 'druxt.requires.commands', + [[]], + 'druxt.requires.commands[0] must be a non-empty array of command names', + ], + [ + 'druxt.requires.commands', + [['php', '/usr/bin/composer']], + 'druxt.requires.commands[0][1] must be a command name with no path or spaces', + ], + [ + 'druxt.requires.commands', + [['php -v']], + 'druxt.requires.commands[0][0] must be a command name with no path or spaces', + ], + [ + 'druxt.requires.commands', + [[7]], + 'druxt.requires.commands[0][0] must be a command name with no path or spaces', + ], [ 'druxt.maintained', undefined, diff --git a/packages/cli/test/registry/registry.test.ts b/packages/cli/test/registry/registry.test.ts index 8e1e0aa..7131fe6 100644 --- a/packages/cli/test/registry/registry.test.ts +++ b/packages/cli/test/registry/registry.test.ts @@ -1,8 +1,15 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test } from 'vitest' -import { bundledRegistryDir } from '../../src/package-root.js' +import { bundledRegistryDir, packageRoot } from '../../src/package-root.js' import { DEFAULT_REGISTRY, defaultStarter, @@ -32,6 +39,58 @@ afterEach(async () => { rmSync(bundled, { recursive: true, force: true }) }) +describe('a default registry that is behind this build', () => { + const entries = { '/quickstart.json': entry } + + test('gives way to the bundled copy when its revision is lower', async () => { + writeFileSync( + join(bundled, 'index.json'), + JSON.stringify({ revision: 2, starters: ['quickstart'] }) + ) + server = await serve({ ...entries, '/index.json': index }) + const registry = await openRegistry({ + defaultUrl: server.url, + bundledDir: bundled, + }) + expect(registry.origin).toBe('bundled') + expect(registry.fallbackReason).toBe( + `${server.url} is older than this version of drx.` + ) + expect((await registry.entry('quickstart')).url).toBe( + 'https://example.com/bundled' + ) + }) + + test('is read when its revision is the same or higher', async () => { + writeFileSync( + join(bundled, 'index.json'), + JSON.stringify({ revision: 2, starters: ['quickstart'] }) + ) + for (const revision of [2, 3]) { + server = await serve({ + ...entries, + '/index.json': JSON.stringify({ revision, starters: ['quickstart'] }), + }) + const registry = await openRegistry({ + defaultUrl: server.url, + bundledDir: bundled, + }) + expect(registry.origin).toBe('remote') + await server.close() + } + server = undefined + }) + + test('is read when the bundled copy cannot be', async () => { + server = await serve({ ...entries, '/index.json': index }) + const registry = await openRegistry({ + defaultUrl: server.url, + bundledDir: join(bundled, 'missing'), + }) + expect(registry.origin).toBe('remote') + }) +}) + describe('a registry named by the user', () => { test('reads the index and an entry over HTTP', async () => { server = await serve({ '/index.json': index, '/quickstart.json': entry }) @@ -192,10 +251,31 @@ describe('the bundled registry', () => { 'https://codeload.github.com/druxt/quickstart/tar.gz/refs/heads/develop' ) expect(starter.druxt.default).toBe(true) + expect(starter.druxt.requires.commands).toEqual([ + ['php', 'composer'], + ['ddev'], + ]) expect((await defaultStarter(registry))?.name).toBe('quickstart') }) }) +describe('the copy of the registry the build puts in the package', () => { + const source = join(packageRoot(), '..', '..', 'starters') + const copy = join(packageRoot(), 'starters') + + // The copy exists only after a build. A stale one would be read by every + // other test here in place of starters/, so it has to match. + test.skipIf(!existsSync(copy))('equals starters/', () => { + const files = readdirSync(source).sort() + expect(readdirSync(copy).sort()).toEqual(files) + for (const file of files) { + expect(readFileSync(join(copy, file), 'utf8'), file).toBe( + readFileSync(join(source, file), 'utf8') + ) + } + }) +}) + describe('defaultStarter', () => { test('is undefined when no entry is marked as the default', async () => { server = await serve({ diff --git a/packages/cli/test/sources.test.ts b/packages/cli/test/sources.test.ts index 66c5ad7..f4c490c 100644 --- a/packages/cli/test/sources.test.ts +++ b/packages/cli/test/sources.test.ts @@ -6,6 +6,7 @@ import type { UserConfig } from '../src/user-config.js' const config: UserConfig = { path: '/home/me/.config/drx/config.json', registries: {}, + moduleRegistries: {}, sources: { next: { type: 'npm', tag: 'next' }, branch: { type: 'git', url: 'https://example.com/druxt.git', ref: 'x' }, diff --git a/packages/cli/test/user-config.test.ts b/packages/cli/test/user-config.test.ts index c9e040f..2ae3999 100644 --- a/packages/cli/test/user-config.test.ts +++ b/packages/cli/test/user-config.test.ts @@ -4,6 +4,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, test } from 'vitest' import { loadUserConfig, + resolveModuleRegistryUrl, resolveRegistryUrl, userConfigPath, } from '../src/user-config.js' @@ -58,6 +59,7 @@ describe('loadUserConfig', () => { expect(await loadUserConfig({ XDG_CONFIG_HOME: home })).toEqual({ path: join(home, 'drx', 'config.json'), registries: {}, + moduleRegistries: {}, sources: {}, }) }) @@ -66,6 +68,7 @@ describe('loadUserConfig', () => { const path = join(home, 'config.json') write(path, { registries: { team: 'https://example.com/starters' }, + moduleRegistries: { team: 'https://example.com/modules.json' }, sources: { next: { type: 'npm', tag: 'next' }, branch: { type: 'git', url: 'https://example.com/druxt.git', ref: 'x' }, @@ -74,6 +77,7 @@ describe('loadUserConfig', () => { expect(await loadUserConfig({ DRX_CONFIG: path })).toEqual({ path, registries: { team: 'https://example.com/starters' }, + moduleRegistries: { team: 'https://example.com/modules.json' }, sources: { next: { type: 'npm', tag: 'next' }, branch: { type: 'git', url: 'https://example.com/druxt.git', ref: 'x' }, @@ -96,6 +100,11 @@ describe('loadUserConfig', () => { '{"registries":{"a":"not a url"}}', 'registries.a must be an http or https URL', ], + ['{"moduleRegistries":7}', 'moduleRegistries must be an object of URLs'], + [ + '{"moduleRegistries":{"a":"ftp://x"}}', + 'moduleRegistries.a must be an http or https URL', + ], ['{"sources":[]}', 'sources must be an object'], ['{"sources":{"a":"npm"}}', 'sources.a must be an object'], [ @@ -127,6 +136,7 @@ describe('resolveRegistryUrl', () => { const config = { path: '/home/me/.config/drx/config.json', registries: { team: 'https://example.com/starters' }, + moduleRegistries: { ours: 'https://example.com/modules.json' }, sources: {}, } @@ -163,3 +173,27 @@ describe('resolveRegistryUrl', () => { ) }) }) + +describe('resolveModuleRegistryUrl', () => { + const config = { + path: '/home/me/.config/drx/config.json', + registries: {}, + moduleRegistries: { ours: 'https://example.com/modules.json' }, + sources: {}, + } + + test('takes a URL, or a name from the user configuration', () => { + expect(resolveModuleRegistryUrl('https://example.org/m.json', config)).toBe( + 'https://example.org/m.json' + ) + expect(resolveModuleRegistryUrl('ours', config)).toBe( + 'https://example.com/modules.json' + ) + }) + + test('fails on a name the configuration does not define', () => { + expect(() => resolveModuleRegistryUrl('theirs', config)).toThrow( + '--module-registry takes a URL or a name defined in /home/me/.config/drx/config.json. "theirs" is neither. Defined names: ours.' + ) + }) +}) diff --git a/starters/index.json b/starters/index.json index 66b657f..ffe14f6 100644 --- a/starters/index.json +++ b/starters/index.json @@ -1,3 +1,4 @@ { + "revision": 1, "starters": ["quickstart"] } diff --git a/starters/quickstart.json b/starters/quickstart.json index bfcdf7a..646ef6b 100644 --- a/starters/quickstart.json +++ b/starters/quickstart.json @@ -12,7 +12,8 @@ ], "requires": { "node": "16.18.1", - "tools": ["PHP 8.3 or newer with Composer, or DDEV"] + "tools": ["PHP 8.3 or newer with Composer, or DDEV"], + "commands": [["php", "composer"], ["ddev"]] }, "maintained": "2026-11-15", "default": true,