@contember/cli 2.2.0-alpha.18 → 2.2.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.cjs +1 -2
  2. package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.cjs.map +1 -1
  3. package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.js +2 -3
  4. package/dist/development/src/commands/tenant/policy/TenantAuthLogCommand.js.map +1 -1
  5. package/dist/development/src/commands/transfer/ExportCommand.cjs +2 -2
  6. package/dist/development/src/commands/transfer/ExportCommand.cjs.map +1 -1
  7. package/dist/development/src/commands/transfer/ImportCommand.cjs +2 -2
  8. package/dist/development/src/commands/transfer/ImportCommand.cjs.map +1 -1
  9. package/dist/development/src/lib/VersionChecker.cjs +2 -19
  10. package/dist/development/src/lib/VersionChecker.cjs.map +1 -1
  11. package/dist/development/src/lib/VersionChecker.js +2 -2
  12. package/dist/development/src/lib/VersionChecker.js.map +1 -1
  13. package/dist/development/src/lib/fs/FileSystem.cjs +36 -4
  14. package/dist/development/src/lib/fs/FileSystem.cjs.map +1 -1
  15. package/dist/development/src/lib/fs/FileSystem.js +35 -3
  16. package/dist/development/src/lib/fs/FileSystem.js.map +1 -1
  17. package/dist/development/src/lib/migrations/MigrationPrinter.cjs +9 -12
  18. package/dist/development/src/lib/migrations/MigrationPrinter.cjs.map +1 -1
  19. package/dist/development/src/lib/migrations/MigrationPrinter.js +10 -13
  20. package/dist/development/src/lib/migrations/MigrationPrinter.js.map +1 -1
  21. package/dist/development/src/lib/migrations/MigrationSnapshotFacade.cjs +1 -1
  22. package/dist/development/src/lib/migrations/MigrationSnapshotFacade.cjs.map +1 -1
  23. package/dist/development/src/lib/migrations/MigrationSnapshotFacade.js +1 -1
  24. package/dist/development/src/lib/migrations/MigrationSnapshotFacade.js.map +1 -1
  25. package/dist/development/src/lib/prompt/prompt.cjs +41 -7
  26. package/dist/development/src/lib/prompt/prompt.cjs.map +1 -1
  27. package/dist/development/src/lib/prompt/prompt.js +41 -7
  28. package/dist/development/src/lib/prompt/prompt.js.map +1 -1
  29. package/dist/development/src/lib/transfer/DataTransferClient.cjs +2 -2
  30. package/dist/development/src/lib/transfer/DataTransferClient.cjs.map +1 -1
  31. package/dist/development/src/lib/versionRange.cjs +276 -0
  32. package/dist/development/src/lib/versionRange.cjs.map +1 -0
  33. package/dist/development/src/lib/versionRange.js +276 -0
  34. package/dist/development/src/lib/versionRange.js.map +1 -0
  35. package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.cjs +1 -2
  36. package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.cjs.map +1 -1
  37. package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.js +2 -3
  38. package/dist/production/src/commands/tenant/policy/TenantAuthLogCommand.js.map +1 -1
  39. package/dist/production/src/commands/transfer/ExportCommand.cjs +2 -2
  40. package/dist/production/src/commands/transfer/ExportCommand.cjs.map +1 -1
  41. package/dist/production/src/commands/transfer/ImportCommand.cjs +2 -2
  42. package/dist/production/src/commands/transfer/ImportCommand.cjs.map +1 -1
  43. package/dist/production/src/lib/VersionChecker.cjs +2 -19
  44. package/dist/production/src/lib/VersionChecker.cjs.map +1 -1
  45. package/dist/production/src/lib/VersionChecker.js +2 -2
  46. package/dist/production/src/lib/VersionChecker.js.map +1 -1
  47. package/dist/production/src/lib/fs/FileSystem.cjs +36 -4
  48. package/dist/production/src/lib/fs/FileSystem.cjs.map +1 -1
  49. package/dist/production/src/lib/fs/FileSystem.js +35 -3
  50. package/dist/production/src/lib/fs/FileSystem.js.map +1 -1
  51. package/dist/production/src/lib/migrations/MigrationPrinter.cjs +9 -12
  52. package/dist/production/src/lib/migrations/MigrationPrinter.cjs.map +1 -1
  53. package/dist/production/src/lib/migrations/MigrationPrinter.js +10 -13
  54. package/dist/production/src/lib/migrations/MigrationPrinter.js.map +1 -1
  55. package/dist/production/src/lib/migrations/MigrationSnapshotFacade.cjs +1 -1
  56. package/dist/production/src/lib/migrations/MigrationSnapshotFacade.cjs.map +1 -1
  57. package/dist/production/src/lib/migrations/MigrationSnapshotFacade.js +1 -1
  58. package/dist/production/src/lib/migrations/MigrationSnapshotFacade.js.map +1 -1
  59. package/dist/production/src/lib/prompt/prompt.cjs +41 -7
  60. package/dist/production/src/lib/prompt/prompt.cjs.map +1 -1
  61. package/dist/production/src/lib/prompt/prompt.js +41 -7
  62. package/dist/production/src/lib/prompt/prompt.js.map +1 -1
  63. package/dist/production/src/lib/transfer/DataTransferClient.cjs +2 -2
  64. package/dist/production/src/lib/transfer/DataTransferClient.cjs.map +1 -1
  65. package/dist/production/src/lib/versionRange.cjs +276 -0
  66. package/dist/production/src/lib/versionRange.cjs.map +1 -0
  67. package/dist/production/src/lib/versionRange.js +276 -0
  68. package/dist/production/src/lib/versionRange.js.map +1 -0
  69. package/dist/types/commands/tenant/policy/TenantAuthLogCommand.d.ts.map +1 -1
  70. package/dist/types/lib/VersionChecker.d.ts.map +1 -1
  71. package/dist/types/lib/fs/FileSystem.d.ts +5 -0
  72. package/dist/types/lib/fs/FileSystem.d.ts.map +1 -1
  73. package/dist/types/lib/migrations/MigrationPrinter.d.ts.map +1 -1
  74. package/dist/types/lib/prompt/prompt.d.ts +17 -4
  75. package/dist/types/lib/prompt/prompt.d.ts.map +1 -1
  76. package/dist/types/lib/versionRange.d.ts +9 -0
  77. package/dist/types/lib/versionRange.d.ts.map +1 -0
  78. package/dist/types/tsconfig.tsbuildinfo +1 -1
  79. package/package.json +17 -21
  80. package/src/commands/tenant/policy/TenantAuthLogCommand.ts +2 -5
  81. package/src/lib/VersionChecker.ts +3 -2
  82. package/src/lib/fs/FileSystem.ts +46 -3
  83. package/src/lib/migrations/MigrationPrinter.ts +10 -15
  84. package/src/lib/migrations/MigrationSnapshotFacade.ts +1 -1
  85. package/src/lib/prompt/prompt.ts +55 -18
  86. package/src/lib/versionRange.ts +347 -0
  87. package/tests/cases/unit/MigrationDiffCommand.test.ts +3 -7
  88. package/tests/cases/unit/MigrationExecutionFacade.test.ts +20 -25
  89. package/tests/cases/unit/MigrationRebaseCommand.test.ts +1 -3
  90. package/tests/cases/unit/MigrationSnapshotFacade.test.ts +1 -3
  91. package/tests/cases/unit/MigrationsValidator.test.ts +2 -2
  92. package/tests/cases/unit/actions.test.ts +2 -2
  93. package/tests/cases/unit/deploy.test.ts +4 -28
  94. package/tests/cases/unit/fileSystem.test.ts +63 -0
  95. package/tests/cases/unit/fixtures/semverCorpus.json +1157 -0
  96. package/tests/cases/unit/project.test.ts +2 -2
  97. package/tests/cases/unit/prompt.test.ts +64 -0
  98. package/tests/cases/unit/transfer.test.ts +1 -3
  99. package/tests/cases/unit/versionRange.test.ts +57 -0
  100. package/dist/development/src/lib/prompt/prompt.internal.cjs +0 -21
  101. package/dist/development/src/lib/prompt/prompt.internal.cjs.map +0 -1
  102. package/dist/development/src/lib/prompt/prompt.internal.js +0 -21
  103. package/dist/development/src/lib/prompt/prompt.internal.js.map +0 -1
  104. package/dist/production/src/lib/prompt/prompt.internal.cjs +0 -21
  105. package/dist/production/src/lib/prompt/prompt.internal.cjs.map +0 -1
  106. package/dist/production/src/lib/prompt/prompt.internal.js +0 -21
  107. package/dist/production/src/lib/prompt/prompt.internal.js.map +0 -1
  108. package/dist/types/lib/prompt/prompt.internal.d.ts +0 -37
  109. package/dist/types/lib/prompt/prompt.internal.d.ts.map +0 -1
  110. package/dist/types/lib/prompt/prompt.test.d.ts +0 -2
  111. package/dist/types/lib/prompt/prompt.test.d.ts.map +0 -1
  112. package/src/lib/prompt/prompt.internal.ts +0 -69
  113. package/src/lib/prompt/prompt.test.ts +0 -100
  114. package/types/chalk-table/index.d.ts +0 -9
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@contember/cli",
3
- "version": "2.2.0-alpha.18",
3
+ "version": "2.2.0-alpha.19",
4
4
  "license": "Apache-2.0",
5
5
  "bin": {
6
6
  "contember": "./dist/production/run.js"
7
7
  },
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
8
11
  "type": "module",
9
12
  "exports": {
10
13
  ".": {
@@ -31,36 +34,29 @@
31
34
  "@tailwindcss/cli": "^4.2.1",
32
35
  "@types/js-yaml": "^4.0.9",
33
36
  "@types/node": "^24.12.0",
34
- "@types/prompts": "^2.4.9",
35
- "@types/semver": "^7.7.1",
36
37
  "tailwindcss": "^4.2.1"
37
38
  },
38
39
  "dependencies": {
39
- "@contember/cli-common": "2.2.0-alpha.18",
40
- "@contember/config-loader": "2.2.0-alpha.18",
41
- "@contember/database": "2.2.0-alpha.18",
42
- "@contember/dic": "2.2.0-alpha.18",
43
- "@contember/engine-common": "2.2.0-alpha.18",
44
- "@contember/engine-content-api": "2.2.0-alpha.18",
45
- "@contember/graphql-client": "2.2.0-alpha.18",
46
- "@contember/graphql-client-tenant": "2.2.0-alpha.18",
47
- "@contember/migrations-client": "2.2.0-alpha.18",
48
- "@contember/schema": "2.2.0-alpha.18",
49
- "@contember/schema-migrations": "2.2.0-alpha.18",
50
- "@contember/schema-utils": "2.2.0-alpha.18",
51
- "@contember/typesafe": "2.2.0-alpha.18",
40
+ "@contember/cli-common": "2.2.0-alpha.19",
41
+ "@contember/config-loader": "2.2.0-alpha.19",
42
+ "@contember/database": "2.2.0-alpha.19",
43
+ "@contember/dic": "2.2.0-alpha.19",
44
+ "@contember/engine-common": "2.2.0-alpha.19",
45
+ "@contember/engine-content-api": "2.2.0-alpha.19",
46
+ "@contember/graphql-client": "2.2.0-alpha.19",
47
+ "@contember/graphql-client-tenant": "2.2.0-alpha.19",
48
+ "@contember/migrations-client": "2.2.0-alpha.19",
49
+ "@contember/schema": "2.2.0-alpha.19",
50
+ "@contember/schema-migrations": "2.2.0-alpha.19",
51
+ "@contember/schema-utils": "2.2.0-alpha.19",
52
+ "@contember/typesafe": "2.2.0-alpha.19",
52
53
  "@graphql-tools/schema": "^10.0.31",
53
- "chalk": "^5.6.2",
54
- "chalk-table": "^1.0.2",
55
- "fast-glob": "^3.3.3",
56
54
  "graphql": "^16.13.1",
57
55
  "graphql-ts-client-api": "^3.1.17",
58
56
  "js-yaml": "^4.1.1",
59
57
  "pg": "^8.20.0",
60
58
  "preact": "^10.28.4",
61
59
  "preact-render-to-string": "^6.6.6",
62
- "prompts": "^2.4.2",
63
- "semver": "^7.7.4",
64
60
  "yawn-yaml": "^3.0.0"
65
61
  },
66
62
  "peerDependencies": {
@@ -1,8 +1,5 @@
1
- /// <reference path="../../../../types/chalk-table/index.d.ts" />
2
-
3
- import { Command, CommandConfiguration, Input, Output } from '@contember/cli-common'
1
+ import { Command, CommandConfiguration, formatTable, Input, Output } from '@contember/cli-common'
4
2
  import type { AuthLogFilter } from '@contember/graphql-client-tenant'
5
- import chalkTable from 'chalk-table'
6
3
  import { TenantClientProvider } from '../../../lib/TenantClientProvider.js'
7
4
  import { TenantAuthLogEntry } from '../../../lib/tenant/clients/index.js'
8
5
  import { GRAPHQL_INT_MAX, parsePaginationLimit, parsePaginationOffset } from '../../../lib/tenant/input/index.js'
@@ -120,7 +117,7 @@ const renderHuman = (page: AuthLogPageResult): string => {
120
117
  if (page.entries.length === 0) {
121
118
  return 'No auth log entries match the filter.'
122
119
  }
123
- const table = chalkTable({ columns: humanColumns }, page.entries.map(toHumanRow))
120
+ const table = formatTable(humanColumns, page.entries.map(toHumanRow))
124
121
  return page.hasMore ? `${table}\nMore entries available — rerun with --offset ${page.nextOffset}.` : table
125
122
  }
126
123
 
@@ -1,8 +1,8 @@
1
1
  import { join, relative } from 'node:path'
2
- import * as semver from 'semver'
3
2
  import { PackageWorkspaceResolver } from '@contember/cli-common'
4
3
  import { DockerComposeManager } from './fs/DockerComposeManager.js'
5
4
  import { contemberDockerImages } from '../consts.js'
5
+ import { satisfiesVersionRange } from './versionRange.js'
6
6
 
7
7
  export class VersionChecker {
8
8
  constructor(
@@ -28,7 +28,8 @@ export class VersionChecker {
28
28
  errors.push(`Package ${packageName} defined in ${jsonPath} is not installed.`)
29
29
  continue
30
30
  }
31
- if (pckg.defined.version !== 'workspace:*' && !semver.satisfies(pckg.installed.version, pckg.defined.version)) {
31
+ // A range we cannot parse (tags, aliases, protocols) skips this check quietly; the CLI version check below still runs.
32
+ if (pckg.defined.version !== 'workspace:*' && satisfiesVersionRange(pckg.installed.version, pckg.defined.version) === false) {
32
33
  errors.push(`Package ${packageName}@${pckg.installed.version} does not match constraint ${pckg.defined.version} defined in ${jsonPath}.`)
33
34
  continue
34
35
  }
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs/promises'
2
- import { access } from 'node:fs/promises'
3
- import glob from 'fast-glob'
2
+ import { access, glob, stat } from 'node:fs/promises'
3
+ import { join, posix, sep } from 'node:path'
4
4
 
5
5
  export class FileSystem {
6
6
  readDir = fs.readdir
@@ -13,7 +13,50 @@ export class FileSystem {
13
13
  return false
14
14
  }
15
15
  }
16
+
17
+ /**
18
+ * Directories under `dir` matching the workspace globs, relative and `/`-separated.
19
+ * A `!pattern` removes exactly what it matches (use `!dir/**` for a subtree);
20
+ * the glob base itself (`packages` for `packages/**`) is never returned.
21
+ */
16
22
  listDirectories = async (dir: string, patterns: string[]): Promise<string[]> => {
17
- return await glob(patterns, { onlyDirectories: true, cwd: dir })
23
+ const include = patterns.filter(it => !it.startsWith('!')).map(it => posix.normalize(it))
24
+ const exclude = patterns.filter(it => it.startsWith('!')).map(it => posix.normalize(it.slice(1)))
25
+ if (include.length === 0) {
26
+ return []
27
+ }
28
+ const literals = new Set(include.filter(it => !globCharacters.test(it)))
29
+ const bases = new Set(include.filter(it => globCharacters.test(it)).map(getGlobBase).filter(it => !literals.has(it)))
30
+ // `x/**` also matches `x` itself; Node's glob agrees, Bun's does not, so glob the prefix too.
31
+ const excludePatterns = [...exclude, ...exclude.filter(it => it.endsWith('/**')).map(it => it.slice(0, -3))]
32
+ const excluded = new Set(exclude.length > 0 ? await globPaths(dir, excludePatterns) : [])
33
+ const result = new Set<string>()
34
+ for (const path of await globPaths(dir, include)) {
35
+ if (bases.has(path) || excluded.has(path) || result.has(path)) {
36
+ continue
37
+ }
38
+ const stats = await stat(join(dir, path)).catch(() => null)
39
+ if (stats?.isDirectory()) {
40
+ result.add(path)
41
+ }
42
+ }
43
+ return [...result]
18
44
  }
19
45
  }
46
+
47
+ // Only the pattern list and `cwd`: an `exclude` array needs Node 22.14+, and Bun lacks `withFileTypes`.
48
+ const globPaths = async (cwd: string, patterns: string[]): Promise<string[]> => {
49
+ const paths: string[] = []
50
+ for await (const entry of glob(patterns, { cwd })) {
51
+ paths.push(entry.split(sep).join('/').replace(/^\.\//, ''))
52
+ }
53
+ return paths
54
+ }
55
+
56
+ const globCharacters = /[*?[\]{}()!+@]/
57
+
58
+ const getGlobBase = (pattern: string): string => {
59
+ const segments = pattern.split('/')
60
+ const firstGlob = segments.findIndex(it => globCharacters.test(it))
61
+ return (firstGlob === -1 ? segments : segments.slice(0, firstGlob)).join('/')
62
+ }
@@ -1,11 +1,7 @@
1
- /// <reference path="../../../types/chalk-table/index.d.ts" />
2
-
3
1
  import { Schema } from '@contember/schema'
4
- import chalk from 'chalk'
5
2
  import { AnyMigrationStatus, Migration, MigrationDescriber, MigrationState } from '@contember/migrations-client'
6
3
  import { emptyDatabaseMetadata } from '@contember/database'
7
- import chalkTable from 'chalk-table'
8
- import { escapeTerminalText, Output } from '@contember/cli-common'
4
+ import { escapeTerminalText, formatTable, Output, style } from '@contember/cli-common'
9
5
  import { assertNever } from '../assertNever.js'
10
6
 
11
7
  export interface MigrationDescriptionItem {
@@ -55,10 +51,9 @@ export class MigrationPrinter {
55
51
  return items.map(it => sanitizeMultiline(it.sql.trim())).filter(it => it !== '').join('\n')
56
52
  }
57
53
  return items.map(item => {
58
- const color = item.isDestructive ? chalk.red : chalk.blue
59
- const lines = [color(`${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)]
54
+ const lines = [style(item.isDestructive ? 'red' : 'blue', `${sanitizeMultiline(item.description)} [${sanitizeMultiline(item.modification)}]`)]
60
55
  if (item.failureWarning) {
61
- lines.push(chalk.bgWhite(chalk.redBright(sanitizeMultiline(item.failureWarning))))
56
+ lines.push(style('bgWhite', style('redBright', sanitizeMultiline(item.failureWarning))))
62
57
  }
63
58
  if (!options.noSql) {
64
59
  lines.push(item.sql.trim() ? sanitizeMultiline(item.sql) : 'No sql to execute')
@@ -86,30 +81,30 @@ export class MigrationPrinter {
86
81
  return migrations.map((it): MigrationStatusRow => {
87
82
  switch (it.state) {
88
83
  case MigrationState.EXECUTED_ERROR:
89
- return { status: chalk.bgRedBright.white('ERROR'), migration: it.name, info: it.errorMessage }
84
+ return { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }
90
85
  case MigrationState.EXECUTED_OK:
91
86
  return {
92
- status: chalk.bgGreen.blackBright('Executed'),
87
+ status: style(['bgGreen', 'blackBright'], 'Executed'),
93
88
  migration: it.name,
94
89
  info: `Executed at ${it.executedMigration.executedAt.toISOString()}`,
95
90
  }
96
91
  case MigrationState.EXECUTED_MISSING:
97
92
  return {
98
- status: chalk.bgRedBright.white('ERROR'),
93
+ status: style(['bgRedBright', 'white'], 'ERROR'),
99
94
  migration: it.name,
100
95
  info: it.errorMessage,
101
96
  }
102
97
  case MigrationState.TO_EXECUTE_OK:
103
98
  return {
104
- status: chalk.bgBlueBright.white('Not executed'),
99
+ status: style(['bgBlueBright', 'white'], 'Not executed'),
105
100
  migration: it.name,
106
101
  info: 'Will be executed during next deploy',
107
102
  }
108
103
  case MigrationState.TO_EXECUTE_ERROR:
109
- return { status: chalk.bgRedBright.white('ERROR'), migration: it.name, info: it.errorMessage }
104
+ return { status: style(['bgRedBright', 'white'], 'ERROR'), migration: it.name, info: it.errorMessage }
110
105
  case MigrationState.SKIP_EMPTY:
111
106
  return {
112
- status: chalk.bgYellow.white('Skip'),
107
+ status: style(['bgYellow', 'white'], 'Skip'),
113
108
  migration: it.name,
114
109
  info: `Skipped because empty`,
115
110
  }
@@ -120,7 +115,7 @@ export class MigrationPrinter {
120
115
  }
121
116
 
122
117
  formatStatusTable = (migrations: AnyMigrationStatus[]): string => {
123
- return chalkTable({ columns: migrationStatusColumns }, this.statusRows(migrations))
118
+ return formatTable(migrationStatusColumns, this.statusRows(migrations))
124
119
  }
125
120
  }
126
121
 
@@ -142,7 +142,7 @@ export class MigrationSnapshotFacade {
142
142
  // already has a relation), so a raw checksum (JSON.stringify) would report false mismatches
143
143
  // on schemas that are in fact deeply equal.
144
144
  const differences = deepCompare(replaySchema, snapshotSchema, [], path => {
145
- if (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index')) {
145
+ if (path[0] === 'model' && path[1] === 'entities' && (path[3] === 'unique' || path[3] === 'index' || path[3] === 'checks')) {
146
146
  return (a, b) => compareArraysIgnoreOrder(a, b, path)
147
147
  }
148
148
  return null
@@ -1,23 +1,60 @@
1
- import { Output } from '@contember/cli-common'
2
- import prompts from 'prompts'
3
- import {
4
- type ConfirmPromptOptions,
5
- type PromptAnswer,
6
- promptConfirmWithRunner,
7
- type PromptQuestion,
8
- promptSelectWithRunner,
9
- type SelectPromptChoice,
10
- type SelectPromptOptions,
11
- } from './prompt.internal.js'
1
+ import { Output, style } from '@contember/cli-common'
12
2
 
13
- export type { ConfirmPromptOptions, SelectPromptChoice, SelectPromptOptions } from './prompt.internal.js'
3
+ export interface ConfirmPromptOptions {
4
+ readonly message: string
5
+ /** The answer for an empty line. */
6
+ readonly initial?: boolean
7
+ }
14
8
 
15
- const runPrompt = async <Q extends PromptQuestion>(question: Q): Promise<PromptAnswer> => {
16
- const answer: { value?: unknown } = await prompts(question)
17
- return answer
9
+ export interface SelectPromptChoice<T extends string> {
10
+ readonly title: string
11
+ readonly value: T
18
12
  }
19
13
 
20
- export const promptConfirm = (output: Output, options: ConfirmPromptOptions): Promise<boolean> => promptConfirmWithRunner(output, options, runPrompt)
14
+ export interface SelectPromptOptions<T extends string> {
15
+ readonly message: string
16
+ readonly choices: readonly SelectPromptChoice<T>[]
17
+ }
21
18
 
22
- export const promptSelect = <const T extends string>(output: Output, options: SelectPromptOptions<T>): Promise<T | undefined> =>
23
- promptSelectWithRunner(output, options, runPrompt)
19
+ /** Asks a yes/no question until it gets `y`, `yes`, `n`, `no` or an empty line. A closed input answers no. */
20
+ export const promptConfirm = async (output: Output, { message, initial = false }: ConfirmPromptOptions): Promise<boolean> => {
21
+ const question = `${style('bold', message)} ${style('dim', initial ? '(Y/n)' : '(y/N)')} `
22
+ for (;;) {
23
+ const answer = await output.prompt(question)
24
+ if (answer === undefined) {
25
+ return false
26
+ }
27
+ const normalized = answer.trim().toLowerCase()
28
+ if (normalized === '') {
29
+ return initial
30
+ }
31
+ if (normalized === 'y' || normalized === 'yes') {
32
+ return true
33
+ }
34
+ if (normalized === 'n' || normalized === 'no') {
35
+ return false
36
+ }
37
+ }
38
+ }
39
+
40
+ /** Lists the choices with numbers and asks until one is picked. There is no default; a closed input picks nothing. */
41
+ export const promptSelect = async <const T extends string>(output: Output, { message, choices }: SelectPromptOptions<T>): Promise<T | undefined> => {
42
+ if (choices.length === 0) {
43
+ return undefined
44
+ }
45
+ const list = choices.map((choice, index) => ` ${style('cyan', String(index + 1))}) ${choice.title}\n`).join('')
46
+ const ask = `${style('dim', `Choose 1-${choices.length}:`)} `
47
+ let question = `${style('bold', message)}\n${list}${ask}`
48
+ for (;;) {
49
+ const answer = await output.prompt(question)
50
+ if (answer === undefined) {
51
+ return undefined
52
+ }
53
+ const trimmed = answer.trim()
54
+ const choice = /^\d+$/.test(trimmed) ? choices[Number(trimmed) - 1] : undefined
55
+ if (choice) {
56
+ return choice.value
57
+ }
58
+ question = `${style('dim', `Enter a number from 1 to ${choices.length}:`)} `
59
+ }
60
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * A subset of npm semver range matching (node-semver `satisfies` with default options), used by the CLI
3
+ * version check. Supported: exact versions, `=`, `<`, `<=`, `>`, `>=`, `~`, `^`, x-ranges (`x`, `X`, `*`,
4
+ * partial versions), hyphen ranges and `||`. Anything else is not parsed and yields `undefined`, so the
5
+ * caller can skip the check instead of guessing.
6
+ */
7
+
8
+ interface Version {
9
+ readonly major: number
10
+ readonly minor: number
11
+ readonly patch: number
12
+ readonly prerelease: readonly (string | number)[]
13
+ }
14
+
15
+ type Operator = '<' | '<=' | '>' | '>=' | '='
16
+
17
+ interface Comparator {
18
+ readonly operator: Operator
19
+ readonly version: Version
20
+ }
21
+
22
+ /** `null` stands for the "any version" comparator. */
23
+ type ComparatorSet = readonly (Comparator | null)[]
24
+
25
+ interface PartialVersion {
26
+ readonly major: number | undefined
27
+ readonly minor: number | undefined
28
+ readonly patch: number | undefined
29
+ readonly prerelease: readonly (string | number)[]
30
+ }
31
+
32
+ const numericPart = '0|[1-9]\\d*'
33
+ const prereleasePart = `(?:${numericPart}|\\d*[a-zA-Z-][a-zA-Z0-9-]*)`
34
+ const prereleaseSuffix = `(?:-(${prereleasePart}(?:\\.${prereleasePart})*))?`
35
+ const buildSuffix = '(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?'
36
+ const versionPattern = new RegExp(`^(${numericPart})\\.(${numericPart})\\.(${numericPart})${prereleaseSuffix}${buildSuffix}$`)
37
+ const xPart = `${numericPart}|[xX*]`
38
+ const partialPattern = new RegExp(`^(${xPart})(?:\\.(${xPart})(?:\\.(${xPart})${prereleaseSuffix}${buildSuffix})?)?$`)
39
+ const comparatorPattern = /^(\^|~>?|<=?|>=?|=)?(.*)$/
40
+
41
+ // semver throws on a bound above MAX_SAFE_INTEGER (e.g. `^MAX` → `<MAX+1`) and answers false; we skip instead.
42
+ const isInRange = (value: number): boolean => Number.isSafeInteger(value) && value < Number.MAX_SAFE_INTEGER
43
+
44
+ // semver rejects longer version strings and answers false; we skip instead.
45
+ const maxLength = 256
46
+
47
+ const parsePrerelease = (value: string | undefined): (string | number)[] =>
48
+ value === undefined ? [] : value.split('.').map(part => (/^\d+$/.test(part) ? Number(part) : part))
49
+
50
+ const parseVersion = (value: string): Version | undefined => {
51
+ const match = versionPattern.exec(value)
52
+ if (!match) {
53
+ return undefined
54
+ }
55
+ const [major, minor, patch] = [Number(match[1]), Number(match[2]), Number(match[3])]
56
+ if (![major, minor, patch].every(isInRange)) {
57
+ return undefined
58
+ }
59
+ return { major, minor, patch, prerelease: parsePrerelease(match[4]) }
60
+ }
61
+
62
+ const parseXPart = (value: string | undefined): number | undefined | null => {
63
+ if (value === undefined || value === 'x' || value === 'X' || value === '*') {
64
+ return undefined
65
+ }
66
+ const number = Number(value)
67
+ return isInRange(number) ? number : null
68
+ }
69
+
70
+ const parsePartial = (value: string): PartialVersion | undefined => {
71
+ const match = partialPattern.exec(value)
72
+ if (!match) {
73
+ return undefined
74
+ }
75
+ const major = parseXPart(match[1])
76
+ const minor = parseXPart(match[2])
77
+ const patch = parseXPart(match[3])
78
+ if (major === null || minor === null || patch === null) {
79
+ return undefined
80
+ }
81
+ const prerelease = parsePrerelease(match[4])
82
+ // A wildcard after a number-free part (`x.1`) or a prerelease on a wildcard is not something we interpret.
83
+ if ((major === undefined && (minor !== undefined || patch !== undefined)) || (minor === undefined && patch !== undefined)) {
84
+ return undefined
85
+ }
86
+ if (prerelease.length > 0 && patch === undefined) {
87
+ return undefined
88
+ }
89
+ return { major, minor, patch, prerelease }
90
+ }
91
+
92
+ const version = (major: number, minor: number, patch: number, prerelease: readonly (string | number)[] = []): Version => ({
93
+ major,
94
+ minor,
95
+ patch,
96
+ prerelease,
97
+ })
98
+
99
+ const comparator = (operator: Operator, value: Version): Comparator => ({ operator, version: value })
100
+
101
+ /** Upper bounds use a `-0` prerelease, so that prereleases of the next version stay excluded. */
102
+ const below = (major: number, minor: number, patch: number): Comparator => comparator('<', version(major, minor, patch, [0]))
103
+
104
+ const desugarTilde = ({ major, minor, patch, prerelease }: PartialVersion): ComparatorSet => {
105
+ if (major === undefined) {
106
+ return [null]
107
+ }
108
+ if (minor === undefined) {
109
+ return [comparator('>=', version(major, 0, 0)), below(major + 1, 0, 0)]
110
+ }
111
+ return [comparator('>=', version(major, minor, patch ?? 0, prerelease)), below(major, minor + 1, 0)]
112
+ }
113
+
114
+ const desugarCaret = ({ major, minor, patch, prerelease }: PartialVersion): ComparatorSet => {
115
+ if (major === undefined) {
116
+ return [null]
117
+ }
118
+ if (minor === undefined) {
119
+ return [comparator('>=', version(major, 0, 0)), below(major + 1, 0, 0)]
120
+ }
121
+ if (patch === undefined) {
122
+ return [comparator('>=', version(major, minor, 0)), major === 0 ? below(major, minor + 1, 0) : below(major + 1, 0, 0)]
123
+ }
124
+ const lower = comparator('>=', version(major, minor, patch, prerelease))
125
+ if (major !== 0) {
126
+ return [lower, below(major + 1, 0, 0)]
127
+ }
128
+ return [lower, minor === 0 ? below(major, minor, patch + 1) : below(major, minor + 1, 0)]
129
+ }
130
+
131
+ const desugarPrimitive = (operator: Operator | undefined, partial: PartialVersion): ComparatorSet => {
132
+ const { major, minor, patch, prerelease } = partial
133
+ if (major !== undefined && minor !== undefined && patch !== undefined) {
134
+ return [comparator(operator ?? '=', version(major, minor, patch, prerelease))]
135
+ }
136
+ if (major === undefined) {
137
+ return operator === '<' || operator === '>' ? [below(0, 0, 0)] : [null]
138
+ }
139
+ if (operator === undefined || operator === '=') {
140
+ return minor === undefined
141
+ ? [comparator('>=', version(major, 0, 0)), below(major + 1, 0, 0)]
142
+ : [comparator('>=', version(major, minor, 0)), below(major, minor + 1, 0)]
143
+ }
144
+ const next = minor === undefined ? version(major + 1, 0, 0) : version(major, minor + 1, 0)
145
+ const floor = version(major, minor ?? 0, 0)
146
+ switch (operator) {
147
+ case '>':
148
+ return [comparator('>=', next)]
149
+ case '>=':
150
+ return [comparator('>=', floor)]
151
+ case '<':
152
+ return [comparator('<', version(floor.major, floor.minor, 0, [0]))]
153
+ case '<=':
154
+ return [comparator('<', version(next.major, next.minor, next.patch, [0]))]
155
+ }
156
+ }
157
+
158
+ const desugarHyphen = (from: PartialVersion, to: PartialVersion): ComparatorSet => {
159
+ const lower: Comparator | null = from.major === undefined
160
+ ? null
161
+ : comparator('>=', version(from.major, from.minor ?? 0, from.patch ?? 0, from.prerelease))
162
+ let upper: Comparator | null
163
+ if (to.major === undefined) {
164
+ upper = null
165
+ } else if (to.minor === undefined) {
166
+ upper = below(to.major + 1, 0, 0)
167
+ } else if (to.patch === undefined) {
168
+ upper = below(to.major, to.minor + 1, 0)
169
+ } else {
170
+ upper = comparator('<=', version(to.major, to.minor, to.patch, to.prerelease))
171
+ }
172
+ return [lower, upper]
173
+ }
174
+
175
+ const parseComparator = (token: string): ComparatorSet | undefined => {
176
+ const match = comparatorPattern.exec(token)
177
+ if (!match) {
178
+ return undefined
179
+ }
180
+ const [, operator, rest] = match
181
+ const hasV = rest.startsWith('v')
182
+ const partial = parsePartial(hasV ? rest.slice(1) : rest)
183
+ if (!partial) {
184
+ return undefined
185
+ }
186
+ // semver turns only a literal `>=0.0.0` into "any"; `>=v0.0.0` stays a plain comparator there.
187
+ if (hasV && operator === '>=' && partial.major === 0 && partial.minor === 0 && partial.patch === 0 && partial.prerelease.length === 0) {
188
+ return undefined
189
+ }
190
+ if (operator === '^') {
191
+ return desugarCaret(partial)
192
+ }
193
+ if (operator === '~' || operator === '~>') {
194
+ return desugarTilde(partial)
195
+ }
196
+ if (operator === '<' || operator === '<=' || operator === '>' || operator === '>=' || operator === '=' || operator === undefined) {
197
+ return desugarPrimitive(operator, partial)
198
+ }
199
+ return undefined
200
+ }
201
+
202
+ const isNullComparator = (it: Comparator | null): boolean =>
203
+ it !== null && it.operator === '<' && it.version.major === 0 && it.version.minor === 0 && it.version.patch === 0
204
+ && it.version.prerelease.length === 1 && it.version.prerelease[0] === 0
205
+
206
+ const isGreaterOrEqualZero = (it: Comparator): boolean =>
207
+ it.operator === '>=' && it.version.major === 0 && it.version.minor === 0 && it.version.patch === 0 && it.version.prerelease.length === 0
208
+
209
+ const comparatorKey = (it: Comparator | null): string =>
210
+ it === null ? '' : `${it.operator}${it.version.major}.${it.version.minor}.${it.version.patch}-${it.version.prerelease.join('.')}`
211
+
212
+ /** Mirrors node-semver's set normalisation: `>=0.0.0` is "any", "nothing" wins, duplicates and redundant "any" go. */
213
+ const normalizeSet = (set: ComparatorSet): ComparatorSet => {
214
+ const nullComparator = set.find(isNullComparator)
215
+ if (nullComparator) {
216
+ return [nullComparator]
217
+ }
218
+ const unique = new Map<string, Comparator | null>()
219
+ for (const it of set) {
220
+ const normalized = it !== null && isGreaterOrEqualZero(it) ? null : it
221
+ unique.set(comparatorKey(normalized), normalized)
222
+ }
223
+ if (unique.size > 1) {
224
+ unique.delete('')
225
+ }
226
+ return [...unique.values()]
227
+ }
228
+
229
+ /** Mirrors node-semver's range normalisation: "nothing" sets drop out, and a bare "any" set replaces all others. */
230
+ const normalizeSets = (sets: readonly ComparatorSet[]): readonly ComparatorSet[] => {
231
+ if (sets.length <= 1) {
232
+ return sets
233
+ }
234
+ const meaningful = sets.filter(set => !isNullComparator(set[0] ?? null))
235
+ if (meaningful.length === 0) {
236
+ return [sets[0]]
237
+ }
238
+ const any = meaningful.find(set => set.length === 1 && set[0] === null)
239
+ return any ? [any] : meaningful
240
+ }
241
+
242
+ const parseSet = (value: string): ComparatorSet | undefined => {
243
+ const trimmed = value.trim()
244
+ if (trimmed === '') {
245
+ return [null]
246
+ }
247
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(trimmed)
248
+ if (hyphen) {
249
+ const from = parsePartial(hyphen[1])
250
+ const to = parsePartial(hyphen[2])
251
+ return from && to ? desugarHyphen(from, to) : undefined
252
+ }
253
+ const result: (Comparator | null)[] = []
254
+ for (const token of trimmed.split(/\s+/)) {
255
+ const parsed = parseComparator(token)
256
+ if (!parsed) {
257
+ return undefined
258
+ }
259
+ result.push(...parsed)
260
+ }
261
+ return result
262
+ }
263
+
264
+ const compareIdentifiers = (a: string | number, b: string | number): number => {
265
+ if (typeof a === 'number' && typeof b === 'number') {
266
+ return a - b
267
+ }
268
+ if (typeof a === 'number') {
269
+ return -1
270
+ }
271
+ if (typeof b === 'number') {
272
+ return 1
273
+ }
274
+ return a < b ? -1 : a > b ? 1 : 0
275
+ }
276
+
277
+ const compareVersions = (a: Version, b: Version): number => {
278
+ const main = a.major - b.major || a.minor - b.minor || a.patch - b.patch
279
+ if (main !== 0) {
280
+ return main
281
+ }
282
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) {
283
+ return b.prerelease.length - a.prerelease.length
284
+ }
285
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
286
+ const left = a.prerelease[i]
287
+ const right = b.prerelease[i]
288
+ if (left === undefined || right === undefined) {
289
+ return left === undefined ? -1 : 1
290
+ }
291
+ const result = compareIdentifiers(left, right)
292
+ if (result !== 0) {
293
+ return result
294
+ }
295
+ }
296
+ return 0
297
+ }
298
+
299
+ const testComparator = (value: Version, { operator, version: bound }: Comparator): boolean => {
300
+ const result = compareVersions(value, bound)
301
+ switch (operator) {
302
+ case '<':
303
+ return result < 0
304
+ case '<=':
305
+ return result <= 0
306
+ case '>':
307
+ return result > 0
308
+ case '>=':
309
+ return result >= 0
310
+ case '=':
311
+ return result === 0
312
+ }
313
+ }
314
+
315
+ const testSet = (value: Version, set: ComparatorSet): boolean => {
316
+ if (!set.every(it => it === null || testComparator(value, it))) {
317
+ return false
318
+ }
319
+ if (value.prerelease.length === 0) {
320
+ return true
321
+ }
322
+ // A prerelease only matches when the range names a prerelease of the same major.minor.patch.
323
+ return set.some(it =>
324
+ it !== null && it.version.prerelease.length > 0 && it.version.major === value.major && it.version.minor === value.minor
325
+ && it.version.patch === value.patch
326
+ )
327
+ }
328
+
329
+ /** Whether `installed` satisfies `range` as npm semver decides it, or `undefined` when either one is not understood. */
330
+ export const satisfiesVersionRange = (installed: string, range: string): boolean | undefined => {
331
+ if (installed.length > maxLength || range.length > maxLength) {
332
+ return undefined
333
+ }
334
+ const parsedVersion = parseVersion(installed.trim())
335
+ if (!parsedVersion) {
336
+ return undefined
337
+ }
338
+ const sets: ComparatorSet[] = []
339
+ for (const part of range.split('||')) {
340
+ const set = parseSet(part)
341
+ if (!set) {
342
+ return undefined
343
+ }
344
+ sets.push(normalizeSet(set))
345
+ }
346
+ return normalizeSets(sets).some(set => testSet(parsedVersion, set))
347
+ }