diff --git a/packages/cli/bin/run.js b/packages/cli/bin/run.js index 047ca5658..0d2ab57e3 100755 --- a/packages/cli/bin/run.js +++ b/packages/cli/bin/run.js @@ -3,6 +3,14 @@ const OCLIF_PATCH = true const COMMAND_PATCH_ENABLED = true +// Before anything else: on an older Node.js the CLI fails while loading +// (ERR_REQUIRE_ESM), so say which Node.js it needs instead +const nodeError = require('../lib/engines').nodeErrorMessage(require('../package.json'), process.versions.node) +if (nodeError) { + console.error(nodeError) + process.exit(1) +} + // eslint-disable-next-line unicorn/prefer-top-level-await ; (async () => { @@ -13,4 +21,4 @@ const COMMAND_PATCH_ENABLED = true await oclif.execute({ development: false, dir: __dirname }) -})() \ No newline at end of file +})() diff --git a/packages/cli/docs/cli.md b/packages/cli/docs/cli.md index 179fec1d9..9367e718e 100644 --- a/packages/cli/docs/cli.md +++ b/packages/cli/docs/cli.md @@ -34,10 +34,11 @@ Update Commerce Layer CLI. ```sh-session USAGE - $ commercelayer cli:update [-v ] + $ commercelayer cli:update [-v | --latest] FLAGS -v, --version= update CLI to a specific version or tag + --latest update CLI to its latest version, a new major included DESCRIPTION Update Commerce Layer CLI @@ -47,6 +48,10 @@ ALIASES $ commercelayer latest EXAMPLES + $ commercelayer cli:update + + $ commercelayer cli:update --latest + $ commercelayer cli:update --version= ``` diff --git a/packages/cli/src/commands/cli/update.ts b/packages/cli/src/commands/cli/update.ts index 2cc892467..4fa3cff71 100644 --- a/packages/cli/src/commands/cli/update.ts +++ b/packages/cli/src/commands/cli/update.ts @@ -1,11 +1,27 @@ /* eslint-disable @typescript-eslint/no-misused-promises */ import { exec } from 'node:child_process' +import { promisify } from 'node:util' import { clColor } from '@commercelayer/cli-core' import { Command, ux as cliux, Flags } from '@oclif/core' +import { unsupportedNode } from '../../engines' + // import { detect as detectPackageManager } from 'detect-package-manager' +const CLI_PACKAGE = '@commercelayer/cli' + +type Release = { name?: string; version?: string; engines?: { node?: string } } + + +/** + * The version an update installs: by default the latest of the current + * major, a new major only when asked for (--latest, or --version) + */ +const updateTarget = (current: string, flags: { version?: string; latest?: boolean }): string => + flags.version ?? (flags.latest ? 'latest' : `^${current.split('.')[0]}`) + + export default class CliUpdate extends Command { static description = 'Update Commerce Layer CLI' @@ -13,6 +29,8 @@ export default class CliUpdate extends Command { static aliases = ['upgrade', 'latest'] static examples = [ + '<%= config.bin %> <%= command.id %>', + '<%= config.bin %> <%= command.id %> --latest', '<%= config.bin %> <%= command.id %> --version=', ] @@ -21,7 +39,12 @@ export default class CliUpdate extends Command { char: 'v', description: 'update CLI to a specific version or tag', required: false, - }) + exclusive: ['latest'], + }), + latest: Flags.boolean({ + description: 'update CLI to its latest version, a new major included', + exclusive: ['version'], + }), } @@ -29,13 +52,18 @@ export default class CliUpdate extends Command { const { flags } = await this.parse(CliUpdate) - const version = flags.version ? `@${flags.version}` : '' - // await detectPackageManager().then(pm => this.log) + const current = this.config.version + const target = updateTarget(current, flags) + + // A release that doesn't run on this Node.js isn't installed + const release = await this.fetchRelease(target) + const nodeRange = release && unsupportedNode(release, process.versions.node) + if (nodeRange) this.error(`Commerce Layer CLI ${release.version} requires Node.js ${nodeRange} (current: ${process.versions.node}): update Node.js first`) this.log() cliux.action.start('Updating Commerce Layer CLI') - const cp = exec(`npm install --location=global @commercelayer/cli${version}`, async (error, stdout, stderr) => { + const cp = exec(`npm install --location=global "${CLI_PACKAGE}@${target}"`, async (error, stdout, stderr) => { const errorMessage = this.getErrorMessage(error, stdout, stderr) @@ -45,7 +73,7 @@ export default class CliUpdate extends Command { this.error('CLI update failed.') } else { cliux.action.stop() - await this.showCliVersion() + await this.showUpdate(current, Boolean(flags.version || flags.latest)) } }) @@ -72,11 +100,57 @@ export default class CliUpdate extends Command { } - private async showCliVersion(): Promise { + /** The npm manifest of a version or tag (none for a range, or when npm can't be reached) */ + private async fetchRelease(versionOrTag: string): Promise { + if (/^[\^~<>=]/.test(versionOrTag)) { + // A range: its latest version, from the list of versions + const latest = await this.fetchRelease('latest') + return latest?.version?.split('.')[0] === versionOrTag.replace(/^\^/, '') ? latest : undefined + } + return fetch(`https://registry.npmjs.org/${CLI_PACKAGE}/${encodeURIComponent(versionOrTag)}`) + .then(async response => (response.ok ? (await response.json()) as Release : undefined)) + .catch(() => undefined) + } + + + /** The version npm installed: this process still runs the previous one, so config.version is no use */ + private async installedVersion(): Promise { try { - const verCmd = await this.config.findCommand('cli:version')?.load() - await verCmd?.run([]) // without [] the command uses args of command 'version' and it fails - } catch (_err) { this.log() } + const { stdout } = await promisify(exec)(`npm ls --location=global ${CLI_PACKAGE} --depth=0 --json`) + return JSON.parse(stdout).dependencies?.[CLI_PACKAGE]?.version + } catch { + return undefined + } + } + + + private async showUpdate(previous: string, explicit: boolean): Promise { + + const installed = await this.installedVersion() + + this.log() + if (!installed) this.log(`Commerce Layer CLI updated: run ${clColor.cyanBright(`${this.config.bin} version`)} to see its version`) + else if (installed === previous) this.log(`Commerce Layer CLI is up to date: ${clColor.cyanBright(installed)}`) + else this.log(`Commerce Layer CLI updated: ${clColor.dim(previous)} -> ${clColor.green(installed)}`) + + // A new major is never installed implicitly: say there is one + if (!explicit) { + const latest = await this.fetchRelease('latest') + const major = Number((installed ?? previous).split('.')[0]) + if (latest?.version && (Number(latest.version.split('.')[0]) > major)) { + const nodeRange = unsupportedNode(latest, process.versions.node) + this.log() + this.log(`A new major of Commerce Layer CLI is available: ${clColor.green(latest.version)}`) + if (nodeRange) this.log(`It requires Node.js ${nodeRange} (current: ${process.versions.node})`) + else this.log(`Run ${clColor.cyanBright(`${this.config.bin} cli:update --latest`)} to install it`) + } + } + + this.log() + } } + + +export { updateTarget } diff --git a/packages/cli/src/engines.ts b/packages/cli/src/engines.ts new file mode 100644 index 000000000..b89892f55 --- /dev/null +++ b/packages/cli/src/engines.ts @@ -0,0 +1,43 @@ +/** + * The Node.js version a CLI release requires (`engines.node`, as `>=22.13`). + * + * No imports: bin/run.js requires this before anything else, because on an + * older Node.js the CLI fails while loading (ERR_REQUIRE_ESM) with no useful + * message, and the update command checks a release before installing it. + */ + +type Manifest = { name?: string; version?: string; engines?: { node?: string } } + +const parts = (version: string): number[] => { + const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, '').split('.').map(Number) + return [major, minor, patch] +} + +/** The minimum version of an engines range of the form `>=x[.y[.z]]`, the only form the CLI uses */ +const minimumVersion = (range: string): string | undefined => /^>=\s*(\d+(?:\.\d+){0,2})$/.exec(range.trim())?.[1] + +/** Whether a Node.js version satisfies the engines range (true for a range of another form: npm decides) */ +const satisfiesNode = (range: string | undefined, node: string): boolean => { + const minimum = range ? minimumVersion(range) : undefined + if (!minimum) return true + const [a, b] = [parts(node), parts(minimum)] + for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i] + return true +} + +/** The Node.js range a release requires when the given Node.js version doesn't satisfy it */ +const unsupportedNode = (manifest: Manifest, node: string): string | undefined => { + const range = manifest.engines?.node + return satisfiesNode(range, node) ? undefined : range +} + +/** The message bin/run.js prints when the running Node.js is too old for this CLI */ +const nodeErrorMessage = (manifest: Manifest, node: string): string | undefined => { + const range = unsupportedNode(manifest, node) + if (!range) return undefined + const major = Number((manifest.version ?? '').split('.')[0]) + const previous = major > 1 ? `, or install the previous CLI major, which supports older Node.js versions:\n\n npm install -g ${manifest.name}@${major - 1}` : '' + return `\nCommerce Layer CLI ${manifest.version} requires Node.js ${range} (current: ${node}).\nUpdate Node.js${previous}\n` +} + +export { nodeErrorMessage, satisfiesNode, unsupportedNode } diff --git a/packages/cli/src/hooks/init/update.ts b/packages/cli/src/hooks/init/update.ts index 0100f7b98..59818cfa9 100644 --- a/packages/cli/src/hooks/init/update.ts +++ b/packages/cli/src/hooks/init/update.ts @@ -18,7 +18,8 @@ const hook: Hook<'init'> = async (opts) => { const notifier = updateNotifier({ pkg, updateCheckInterval: (process.env.CL_CLI_UPDATE_NOTIFY ? 0 : 1000 * 60 * 60) }) - const updateCommand = /* '{updateCommand}' */ 'commercelayer ' + UPDATE_COMMAND + // cli:update stays on the current major: a new one needs --latest + const updateCommand = /* '{updateCommand}' */ 'commercelayer ' + UPDATE_COMMAND + ((notifier.update?.type === 'major') ? ' --latest' : '') notifier.notify({ isGlobal: true, diff --git a/packages/cli/test/engines.test.ts b/packages/cli/test/engines.test.ts new file mode 100644 index 000000000..6c2c9d14a --- /dev/null +++ b/packages/cli/test/engines.test.ts @@ -0,0 +1,36 @@ +import { expect } from 'chai' +import { updateTarget } from '../src/commands/cli/update' +import { nodeErrorMessage, satisfiesNode, unsupportedNode } from '../src/engines' + +describe('engines', () => { + it('compares a Node.js version with a >= range', () => { + expect(satisfiesNode('>=22.13', '22.13.0')).to.equal(true) + expect(satisfiesNode('>=22.13', '24.1.0')).to.equal(true) + expect(satisfiesNode('>=22.13', 'v22.12.9')).to.equal(false) + expect(satisfiesNode('>=22.13', '20.5.1')).to.equal(false) + expect(satisfiesNode('>=20', '20.0.0')).to.equal(true) + // Another form of range, or none: npm decides + expect(satisfiesNode('^20 || ^22', '18.0.0')).to.equal(true) + expect(satisfiesNode(undefined, '18.0.0')).to.equal(true) + }) + + it('reports the range a release requires, when unsupported', () => { + expect(unsupportedNode({ engines: { node: '>=22.13' } }, '20.5.1')).to.equal('>=22.13') + expect(unsupportedNode({ engines: { node: '>=22.13' } }, '22.20.0')).to.equal(undefined) + }) + + it('explains how to go on with an older Node.js', () => { + const message = nodeErrorMessage({ name: '@commercelayer/cli', version: '7.0.0', engines: { node: '>=22.13' } }, '20.5.1') + expect(message).to.contain('Commerce Layer CLI 7.0.0 requires Node.js >=22.13 (current: 20.5.1)') + expect(message).to.contain('npm install -g @commercelayer/cli@6') + expect(nodeErrorMessage({ name: '@commercelayer/cli', version: '7.0.0', engines: { node: '>=22.13' } }, '22.13.1')).to.equal(undefined) + }) +}) + +describe('cli:update target', () => { + it('stays on the current major unless asked otherwise', () => { + expect(updateTarget('7.0.0', {})).to.equal('^7') + expect(updateTarget('7.2.1', { latest: true })).to.equal('latest') + expect(updateTarget('7.2.1', { version: '7.1.0' })).to.equal('7.1.0') + }) +})