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/commands/plugins/available.ts b/packages/cli/src/commands/plugins/available.ts index 7b87fced1..71f77fdee 100644 --- a/packages/cli/src/commands/plugins/available.ts +++ b/packages/cli/src/commands/plugins/available.ts @@ -44,6 +44,7 @@ export default class PluginsAvailable extends Command { cliux.Table.table(availablePlugins, { key: { header: 'PLUGIN (KEY)', minWidth: 20, get: row => (row.hidden ? clColor.dim : clColor).blueBright(row.name) }, description: { header: 'DESCRIPTION', get: row => (row.hidden ? clColor.dim(row.description) : row.description) }, + version: { header: 'VERSION', get: row => clColor.dim(row.version) }, }, { printLine: clUtil.log, }) @@ -62,25 +63,31 @@ type PluginRelease = { description: string; enabled: boolean; hidden?: boolean; - version?: string; + /** + * The versions of the plugin this CLI installs and updates: its major, as + * a range (^N). A new major of the plugin is never installed or updated to + * implicitly: the user asks for it (plugins:install --latest), + * or a CLI release raises the range here (a breaking change of the CLI). + */ + version: string; } const AvailablePlugins: PluginRelease[] = [ - { name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', enabled: true }, - { name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', enabled: true }, - { name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', enabled: true }, - { name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', enabled: true }, - { name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', enabled: true }, - { name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', enabled: true }, - { name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', enabled: true }, - { name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', enabled: true }, - { name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', enabled: true }, - { name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', enabled: true }, - { name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', enabled: true }, - { name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', enabled: true }, - { name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', enabled: true }, - { name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', enabled: true }, - { name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', enabled: true } + { name: 'resources', plugin: '@commercelayer/cli-plugin-resources', description: 'CRUD operations on API resources', version: '^7', enabled: true }, + { name: 'seeder', plugin: '@commercelayer/cli-plugin-seeder', description: 'Organization data seeder', version: '^6', enabled: true }, + { name: 'imports', plugin: '@commercelayer/cli-plugin-imports', description: 'Organization imports manager', version: '^5', enabled: true }, + { name: 'webhooks', plugin: '@commercelayer/cli-plugin-webhooks', description: 'Organization webhooks analyzer', version: '^5', enabled: true }, + { name: 'orders', plugin: '@commercelayer/cli-plugin-orders', description: 'Organization orders management', version: '^6', enabled: true }, + { name: 'checkout', plugin: '@commercelayer/cli-plugin-checkout', description: 'Checkout URLs generation', version: '^6', enabled: true }, + { name: 'triggers', plugin: '@commercelayer/cli-plugin-triggers', description: 'Execute actions on resources', version: '^5', enabled: true }, + { name: 'token', plugin: '@commercelayer/cli-plugin-token', description: 'Manage Commerce Layer access tokens', version: '^9', enabled: true }, + { name: 'microstore', plugin: '@commercelayer/cli-plugin-microstore', description: 'Microstore URLs generation', version: '^4', enabled: true }, + { name: 'exports', plugin: '@commercelayer/cli-plugin-exports', description: 'Organization exports manager', version: '^5', enabled: true }, + { name: 'cleanups', plugin: '@commercelayer/cli-plugin-cleanups', description: 'Organization cleanups manager', version: '^4', enabled: true }, + { name: 'tags', plugin: '@commercelayer/cli-plugin-tags', description: 'Manage resources tags', version: '^3', enabled: true }, + { name: 'provisioning', plugin: '@commercelayer/cli-plugin-provisioning', description: 'Add support for Provisioning API', version: '^3', enabled: true }, + { name: 'links', plugin: '@commercelayer/cli-plugin-links', description: 'Manage links to resources', version: '^2', enabled: true }, + { name: 'metrics', plugin: '@commercelayer/cli-plugin-metrics', description: 'Add support for Metrics APIs', version: '^2', enabled: true } ] 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/src/hooks/prerun/plugin.ts b/packages/cli/src/hooks/prerun/plugin.ts index 1491cf2ea..2b87615c6 100644 --- a/packages/cli/src/hooks/prerun/plugin.ts +++ b/packages/cli/src/hooks/prerun/plugin.ts @@ -1,8 +1,10 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' import { clColor, clOutput } from '@commercelayer/cli-core' import type { Hook, Interfaces } from '@oclif/core' import { Errors } from '@oclif/core' import inquirer from 'inquirer' -import { getAvailablePlugins, getInstalledPlugins, getPluginInfo, isPluginInstalled } from '../../commands/plugins/available' +import { getAvailablePlugins, getInstalledPlugins, getPluginInfo, isPluginInstalled, type PluginRelease } from '../../commands/plugins/available' const { CLIError } = Errors type Config = Interfaces.Config @@ -17,6 +19,9 @@ const hook: Hook<'prerun'> = async function (opts) { // Only plugins commands are affected by this hook if (!opts.Command.id.startsWith('plugins')) return + // Plugins installed by an older CLI, or with --latest, follow npm's latest: keep them on their major + if (opts.Command.id === 'plugins:update') pinInstalledPlugins(this.config) + if (['plugins:install', 'plugins:uninstall'].includes(opts.Command.id)) { @@ -30,6 +35,16 @@ const hook: Hook<'prerun'> = async function (opts) { opts.argv.splice(tgIndex, 2) } + // --latest: the latest version on npm (--tag latest), the explicit move to a new major + const ltIndex = opts.argv.indexOf('--latest') + if (ltIndex > -1) { + if (tgIndex > -1) this.error(`${clColor.cli.flag('--latest')} and ${clColor.cli.flag('--tag')} cannot be used together`) + if (command !== 'install') this.error(`${clColor.cli.flag('--latest')} is a flag of plugins:install only`) + tag = 'latest' + opts.argv.splice(ltIndex, 1) + } + const tagged = (tag !== undefined) + if (opts.argv.length === 0) { const arg = await promptPlugin(this.config, command) .catch((error: Error) => { this.error(error) }) @@ -42,6 +57,7 @@ const hook: Hook<'prerun'> = async function (opts) { let index = -1 let plugin: string = '' + let pluginInfo: PluginRelease | undefined let pluginArg: string = '' let testBuild: string | undefined @@ -62,7 +78,10 @@ const hook: Hook<'prerun'> = async function (opts) { } const p = getPluginInfo(pluginArg) if (p === undefined) this.error(`Unknown Commerce Layer CLI plugin: ${clColor.msg.error(a)}. Run '${clColor.italic(`${this.config.bin} plugins:available`)}' to get a list of all available plugins`) - else plugin = p.plugin + else { + plugin = p.plugin + pluginInfo = p + } return true @@ -74,18 +93,21 @@ const hook: Hook<'prerun'> = async function (opts) { if (found && plugin) { let errMsg: string = '' - if ((command === 'install') && isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin already installed' + // With --latest or --tag an installed plugin is installed again: the explicit move to another version (e.g. its next major) + if ((command === 'install') && !tagged && isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin already installed' else if ((command === 'uninstall') && !isPluginInstalled(plugin, this.config)) errMsg = 'Commerce Layer CLI plugin not installed' if (errMsg) { this.log(`\n${errMsg}: ${clColor.cli.plugin(pluginArg)}\n`) + if (command === 'install') this.log(`To install its latest version, a new major included, run '${clColor.italic(`${this.config.bin} plugins:install ${pluginArg} --latest`)}'\n`) throw new CLIError('HOOK_EXIT') } else this.log('') - // Set version - if (tgIndex > -1) plugin = `${plugin}@${tag}` + // Set version: the major of the plugin table unless the user asks for another (--latest, --tag) + if (tagged) plugin = `${plugin}@${tag}` + else if ((command === 'install') && pluginInfo) plugin = `${plugin}@${pluginInfo.version}` // Overwrite plugin short name whith its full name opts.argv[index] = plugin @@ -97,6 +119,40 @@ const hook: Hook<'prerun'> = async function (opts) { } +type PluginsManifest = { oclif?: { plugins?: Array<{ name: string; tag?: string; type?: string }> } } + +/** + * Pins the plugins of the plugin table that follow npm's latest (installed by + * an older CLI, or with --latest) to the major they have, so that + * plugins:update never moves them to a new major. Without a known installed + * version, to the range of the plugin table. Returns whether anything changed. + */ +const pinPlugins = (manifest: PluginsManifest, plugins: PluginRelease[], installed: Map): boolean => { + let changed = false + for (const entry of manifest.oclif?.plugins ?? []) { + const info = plugins.find(p => p.plugin === entry.name) + if (info && (entry.type === 'user') && ((entry.tag === undefined) || (entry.tag === 'latest'))) { + const major = installed.get(entry.name)?.split('.')[0] + entry.tag = major ? `^${major}` : info.version + changed = true + } + } + return changed +} + +/** pinPlugins on the user plugins of the CLI (package.json of its data folder, as oclif keeps it) */ +const pinInstalledPlugins = (config: Config): void => { + const file = join(config.dataDir, 'package.json') + const installed = new Map(config.getPluginsList().map(p => [p.name, p.version])) + try { + const manifest = JSON.parse(readFileSync(file, 'utf8')) as PluginsManifest + if (pinPlugins(manifest, getAvailablePlugins(), installed)) writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`) + } catch { + // No user plugins yet + } +} + + /** * The plugin a test build installs, when the argument is one: a pkg.pr.new * preview URL (preview.yml) or a local tarball (file:…/commercelayer-cli-plugin--.tgz, @@ -138,4 +194,4 @@ const promptPlugin = async (config: Config, command: string): Promise => export default hook -export { testBuildPlugin } +export { pinPlugins, testBuildPlugin } 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') + }) +}) diff --git a/packages/cli/test/hooks/prerun/plugin.test.ts b/packages/cli/test/hooks/prerun/plugin.test.ts index c0df9ae41..f1c23736d 100644 --- a/packages/cli/test/hooks/prerun/plugin.test.ts +++ b/packages/cli/test/hooks/prerun/plugin.test.ts @@ -1,5 +1,8 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' import { expect } from 'chai' -import { testBuildPlugin } from '../../../src/hooks/prerun/plugin' +import { getAvailablePlugins } from '../../../src/commands/plugins/available' +import { pinPlugins, testBuildPlugin } from '../../../src/hooks/prerun/plugin' describe('hooks:prerun:plugin', () => { describe('test builds', () => { @@ -21,3 +24,39 @@ describe('hooks:prerun:plugin', () => { }) }) }) + +describe('hooks:prerun:plugin pinning', () => { + const table = getAvailablePlugins() + const range = (name: string): string | undefined => table.find((p) => p.name === name)?.version + + it('pins the plugins that follow latest to their installed major, or else to the plugin table', () => { + const manifest = { + oclif: { + plugins: [ + { name: '@commercelayer/cli-plugin-tags', tag: 'latest', type: 'user' }, + { name: '@commercelayer/cli-plugin-orders', type: 'user' }, + { name: '@commercelayer/cli-plugin-imports', tag: '^4', type: 'user' }, + { name: 'some-other-plugin', tag: 'latest', type: 'user' }, + ], + }, + } + const installed = new Map([['@commercelayer/cli-plugin-orders', '5.7.0']]) + expect(pinPlugins(manifest, table, installed)).to.equal(true) + // orders keeps its major 5 even if the table installs ^6: a new major is never implicit + expect(manifest.oclif.plugins.map((p) => p.tag)).to.deep.equal([range('tags'), '^5', '^4', 'latest']) + expect(pinPlugins(manifest, table, installed)).to.equal(false) + }) +}) + +describe('plugin table', () => { + // A new major of a plugin reaches the table only explicitly: the table may + // lag behind the workspace, never get ahead of it + it('installs every plugin with a ^N range, N a major of the workspace plugin', () => { + for (const p of getAvailablePlugins()) { + const { name, version } = JSON.parse(readFileSync(join(__dirname, `../../../../../plugins/${p.name}/package.json`), 'utf8')) + expect(name).to.equal(p.plugin) + expect(p.version, p.name).to.match(/^\^\d+$/) + expect(Number(p.version.slice(1)), p.name).to.be.at.most(Number(version.split('.')[0])) + } + }) +})