diff --git a/docs/reference/error-reference.md b/docs/reference/error-reference.md index 5951ca59..c33fe74d 100644 --- a/docs/reference/error-reference.md +++ b/docs/reference/error-reference.md @@ -248,6 +248,14 @@ The `prisma telemetry status|enable|disable` commands could not resolve the user The typed path routed to no command (stricli's route failure, mapped at the adapter boundary) and no redirect claims it; next actions carry up to three "did you mean" suggestions ranked by edit distance over command paths and their prefixes, plus a pointer to `--help`. Exits 2. Meta: none. +### CLI.V7_COMMAND + +The user typed a Prisma 7 command path that Prisma 8 does not have, such as `prisma bootstrap` or `prisma postgres link`; instead of failing as unknown, the redirect table settles it with the summary "`prisma ` is a Prisma 7 command and is not available in Prisma 8". `why` says what the suggested Prisma 8 commands do and what they do not cover. Next actions, in order: the replacement commands as run-command actions (labelled "Use the replacement" for one, "Step 1", "Step 2", … for several), a run-command pointing at the suggested command's `--help`, and an open-url action to the CLI docs when Prisma 8 has no equivalent. Each command family declares the Prisma 7 paths that relate to its own commands. Exits 2. Meta: none. + +### CLI.V7_FLAG + +The user passed a Prisma 7 flag that the same-named Prisma 8 command does not accept, such as `--datasource-provider` on `prisma init`; instead of failing as an unknown flag, the redirect table settles it with the summary "`--` on `prisma ` is a Prisma 7 flag and is not available in Prisma 8". `why` and the next actions follow `CLI.V7_COMMAND`. Exits 2. Meta: none. + ## CONFIG These codes come from Composer, the command family behind `prisma dev` and `prisma deploy`. They report a problem with the `composer` section of `prisma.config.ts`, or with what its `config` and `secrets` adapters return, and are raised before Composer starts the app. diff --git a/packages/cli-engine/package.json b/packages/cli-engine/package.json index 82098d99..6dccc0e9 100644 --- a/packages/cli-engine/package.json +++ b/packages/cli-engine/package.json @@ -1,6 +1,6 @@ { "name": "@prisma/cli-engine", - "version": "0.9.0", + "version": "0.10.0", "description": "The execution engine of the unified Prisma CLI.", "type": "module", "exports": { diff --git a/packages/cli-engine/src/command-family.ts b/packages/cli-engine/src/command-family.ts index 0f90acb7..eaab0498 100644 --- a/packages/cli-engine/src/command-family.ts +++ b/packages/cli-engine/src/command-family.ts @@ -2,10 +2,9 @@ import type { AnyCommand } from "./commands"; import type { ConfigSection } from "./config-section"; /** - * A retired invocation and the invocation that replaced it. Redirects - * are metadata, never commands: they stay out of help and out of the - * command tree, and are consulted only when an invocation fails to - * resolve. + * A retired invocation. Redirects are metadata, never commands: they + * stay out of help and out of the command tree, and are consulted only + * when an invocation fails to resolve. */ export interface RedirectSpec { /** @@ -21,22 +20,25 @@ export interface RedirectSpec { * (rendered --kebab-case, as flag declarations are). */ readonly flag?: string; - /** - * The replacement invocation, written the way help examples are - * written: no binary name, `{bin}` available when the name has to sit - * mid-string. Placeholder arguments use angle brackets (``). - */ - readonly replacement: string; + readonly replacement?: string | readonly string[]; /** One sentence of context, surfaced as the error's `why`. */ readonly reason?: string; + readonly code?: `${string}.${string}`; + readonly summary?: string; + readonly help?: string; + readonly docsUrl?: string; } /** The normalized redirect a command family carries. */ export interface CommandRedirect { readonly from: string; readonly flag: string | undefined; - readonly replacement: string; + readonly replacement: readonly string[]; readonly reason: string | undefined; + readonly code: `${string}.${string}` | undefined; + readonly summary: string | undefined; + readonly help: string | undefined; + readonly docsUrl: string | undefined; } /** @@ -64,12 +66,26 @@ function normalizePath(from: string): string { return from.trim().replace(/\s+/g, " "); } +function replacementSteps(replacement: RedirectSpec["replacement"]): string[] { + if (replacement === undefined) { + return []; + } + if (typeof replacement === "string") { + return [replacement]; + } + return [...replacement]; +} + function normalizeRedirect(spec: RedirectSpec): CommandRedirect { return Object.freeze({ from: normalizePath(spec.from), flag: spec.flag, - replacement: spec.replacement, + replacement: Object.freeze(replacementSteps(spec.replacement)), reason: spec.reason, + code: spec.code, + summary: spec.summary, + help: spec.help, + docsUrl: spec.docsUrl, }); } diff --git a/packages/cli-engine/src/execution/command-tree.ts b/packages/cli-engine/src/execution/command-tree.ts index b41c4684..996add51 100644 --- a/packages/cli-engine/src/execution/command-tree.ts +++ b/packages/cli-engine/src/execution/command-tree.ts @@ -392,6 +392,12 @@ function addFlagRedirect( table.set(key, redirect); } +function describeRedirect(redirect: CommandRedirect): string { + return redirect.flag === undefined + ? `redirect '${redirect.from}'` + : `redirect for flag '${redirect.flag}' on '${redirect.from}'`; +} + export function buildRedirectTable(spec: EngineSpec): RedirectTable { const byPath = new Map(); const byFlag = new Map(); @@ -402,6 +408,15 @@ export function buildRedirectTable(spec: EngineSpec): RedirectTable { "redirect declares an empty path, so no invocation can produce it", ); } + if ( + redirect.replacement.length === 0 && + redirect.help === undefined && + redirect.docsUrl === undefined + ) { + throw constructionError( + `${describeRedirect(redirect)} names no replacement, help, or docs URL, so it gives the user nowhere to go`, + ); + } if (redirect.flag === undefined) { addVerbRedirect(spec, byPath, redirect); } else { diff --git a/packages/cli-engine/src/execution/engine.ts b/packages/cli-engine/src/execution/engine.ts index f287d4cf..77cf48c5 100644 --- a/packages/cli-engine/src/execution/engine.ts +++ b/packages/cli-engine/src/execution/engine.ts @@ -567,9 +567,7 @@ export class EngineImpl implements Engine { : undefined; } - /** stricli routed or parsed nothing runnable. When the redirect table - * claims the invocation the user typed, the run names its - * replacement; otherwise it settles as the usage error it is. */ + /** stricli routed or parsed nothing runnable. */ private settleRouting( invocation: Invocation, stricliExitCode: number | string | null | undefined, diff --git a/packages/cli-engine/src/execution/settlement.ts b/packages/cli-engine/src/execution/settlement.ts index f8410a68..3a77c30d 100644 --- a/packages/cli-engine/src/execution/settlement.ts +++ b/packages/cli-engine/src/execution/settlement.ts @@ -36,6 +36,7 @@ import { emitFrame } from "./reporting"; import { OWN_COMMAND_ROUTE, resolveExample, + substituteBinName, usageErrorCode, } from "./stricli-adapter"; @@ -455,9 +456,36 @@ function retiredInvocation(redirect: CommandRedirect): string { return `\`--${kebabCase(redirect.flag)}\` on \`${redirect.from}\``; } -/** A retired invocation the redirect table claims: the run names its - * replacement instead of failing as an unknown command or flag. A - * retired flag can name a server command, whose stdout belongs to a +function redirectNextActions( + redirect: CommandRedirect, + cliName: string, +): NextAction[] { + const steps: NextAction[] = redirect.replacement.map((step, index) => ({ + kind: "run-command", + label: + redirect.replacement.length === 1 + ? "Use the replacement" + : `Step ${index + 1}`, + command: resolveExample(step, cliName), + })); + const help: NextAction[] = + redirect.help === undefined + ? [] + : [ + { + kind: "run-command", + label: "Read its help", + command: resolveExample(`${redirect.help} --help`, cliName), + }, + ]; + const docs: NextAction[] = + redirect.docsUrl === undefined + ? [] + : [{ kind: "open-url", label: "Read the docs", url: redirect.docsUrl }]; + return [...steps, ...help, ...docs]; +} + +/** A retired flag can name a server command, whose stdout belongs to a * foreign client — so this settlement renders to stderr for the same * reason settleUnhandled does. */ export function settleCommandMoved( @@ -469,23 +497,22 @@ export function settleCommandMoved( if (spec.commands[redirect.from]?.kind === "server-command") { invocation.state.format = "human"; } - const useReplacement: NextAction = { - kind: "run-command", - label: "Use the replacement", - command: resolveExample(redirect.replacement, spec.name), - }; + const nextActions = redirectNextActions(redirect, spec.name); emitErrored(invocation, { ok: false, commandId, error: { - code: "CLI.COMMAND_MOVED", + code: redirect.code ?? "CLI.COMMAND_MOVED", severity: "error", - summary: `${retiredInvocation(redirect)} has been replaced`, + summary: + redirect.summary === undefined + ? `${retiredInvocation(redirect)} has been replaced` + : substituteBinName(redirect.summary, spec.name), ...(redirect.reason === undefined ? {} : { why: redirect.reason }), - nextActions: [useReplacement], + nextActions, }, diagnostics: [], - nextActions: [useReplacement], + nextActions, }); return 2; } diff --git a/packages/cli-engine/tests/engine.type-test.ts b/packages/cli-engine/tests/engine.type-test.ts index d0b080c9..8e8788db 100644 --- a/packages/cli-engine/tests/engine.type-test.ts +++ b/packages/cli-engine/tests/engine.type-test.ts @@ -393,8 +393,16 @@ export const normalizedRedirectFlag: string | undefined = familyWithRedirects.redirects[0].flag; export const normalizedRedirectReason: string | undefined = familyWithRedirects.redirects[0].reason; -// @ts-expect-error a redirect spec needs a replacement -export const redirectWithoutReplacement: RedirectSpec = { from: "migration" }; +export const redirectWithoutReplacement: RedirectSpec = { + from: "migration", + help: "migrate", +}; +export const redirectWithSteps: RedirectSpec = { + from: "migration", + replacement: ["migrate plan", "migrate apply"], +}; +export const normalizedRedirectReplacement: readonly string[] = + familyWithRedirects.redirects[0].replacement; // Normalized definitions: every field is always present export const normalizedHelp: MutuallyAssignable< diff --git a/packages/cli-engine/tests/redirects.test.ts b/packages/cli-engine/tests/redirects.test.ts index 84ddef20..470cbb7f 100644 --- a/packages/cli-engine/tests/redirects.test.ts +++ b/packages/cli-engine/tests/redirects.test.ts @@ -709,3 +709,214 @@ describe("redirects stay out of help", () => { expect(result.stdout).not.toContain("--graph"); }); }); + +describe("redirects with optional next actions", () => { + test("a redirect with no replacement, help, or docs URL fails construction", () => { + const family = defineCommandFamily({ + commands: { status }, + redirects: [{ from: "migration apply" }], + }); + + expect(() => + createTestCli({ + commandFamilies: [family], + commands: { "migration status": status }, + groups: MIGRATION_GROUP, + }), + ).toThrow( + "redirect 'migration apply' names no replacement, help, or docs URL, so it gives the user nowhere to go", + ); + }); + + test("a flag redirect with an empty replacement list and nothing else fails construction", () => { + const family = defineCommandFamily({ + commands: { status }, + redirects: [{ from: "migration status", flag: "graph", replacement: [] }], + }); + + expect(() => + createTestCli({ + commandFamilies: [family], + commands: { "migration status": status }, + groups: MIGRATION_GROUP, + }), + ).toThrow( + "redirect for flag 'graph' on 'migration status' names no replacement, help, or docs URL, so it gives the user nowhere to go", + ); + }); + + test("a replacement list renders each step in order", async () => { + const result = await redirectingCli([ + { + from: "migrate dev", + replacement: ["migration plan", "{bin} db migrate --db "], + }, + ]).run(["migrate", "dev", "--json"]); + + expect(result.exitCode).toBe(2); + const envelope = erroredEnvelope(result.json); + expect(envelope.error.code).toBe("CLI.COMMAND_MOVED"); + expect(envelope.nextActions).toEqual([ + { + kind: "run-command", + label: "Step 1", + command: "prisma-test migration plan", + }, + { + kind: "run-command", + label: "Step 2", + command: "prisma-test db migrate --db ", + }, + ]); + expect(envelope.error.nextActions).toEqual(envelope.nextActions); + }); + + test("a single-entry replacement list keeps the single-step label", async () => { + const result = await redirectingCli([ + { from: "migration apply", replacement: ["migrate --to "] }, + ]).run(["migration", "apply", "--json"]); + + expect(erroredEnvelope(result.json).nextActions).toEqual([ + { + kind: "run-command", + label: "Use the replacement", + command: "prisma-test migrate --to ", + }, + ]); + }); + + test("a redirect with no replacement points at a command's help", async () => { + const result = await redirectingCli([ + { from: "migrate status", help: "migration status" }, + ]).run(["migrate", "status", "--json"]); + + expect(result.exitCode).toBe(2); + expect(erroredEnvelope(result.json).nextActions).toEqual([ + { + kind: "run-command", + label: "Read its help", + command: "prisma-test migration status --help", + }, + ]); + }); + + test("a redirect with no replacement points at the docs", async () => { + const result = await redirectingCli([ + { from: "studio", docsUrl: "https://example.com/docs/cli" }, + ]).run(["studio", "--json"]); + + expect(result.exitCode).toBe(2); + expect(erroredEnvelope(result.json).nextActions).toEqual([ + { + kind: "open-url", + label: "Read the docs", + url: "https://example.com/docs/cli", + }, + ]); + }); + + test("steps come first, then help, then docs", async () => { + const result = await redirectingCli([ + { + from: "bootstrap", + replacement: ["project create ", "postgres create "], + help: "migration status", + docsUrl: "https://example.com/docs/cli", + }, + ]).run(["bootstrap", "--json"]); + + const envelope = erroredEnvelope(result.json); + expect(envelope.nextActions.map((action) => action.label)).toEqual([ + "Step 1", + "Step 2", + "Read its help", + "Read the docs", + ]); + expect(envelope.error.nextActions).toEqual(envelope.nextActions); + }); + + test("a custom code replaces CLI.COMMAND_MOVED", async () => { + const result = await redirectingCli([ + { + from: "generate", + replacement: "contract emit", + code: "CLI.TEST_REDIRECT", + }, + ]).run(["generate", "--json"]); + + expect(result.exitCode).toBe(2); + expect(erroredEnvelope(result.json).error.code).toBe("CLI.TEST_REDIRECT"); + }); + + test("a custom summary replaces the default and has {bin} substituted", async () => { + const result = await redirectingCli([ + { + from: "generate", + replacement: "contract emit", + summary: "`{bin} generate` is not available here", + }, + ]).run(["generate", "--json"]); + + expect(erroredEnvelope(result.json).error.summary).toBe( + "`prisma-test generate` is not available here", + ); + }); + + test("human mode renders every next action on stderr", async () => { + const result = await redirectingCli([ + { + from: "migrate dev", + replacement: ["migration plan", "db migrate --db "], + reason: "Planning and applying are separate steps.", + code: "CLI.TEST_REDIRECT", + summary: "`{bin} migrate dev` is not available", + help: "migration status", + docsUrl: "https://example.com/docs/cli", + }, + ]).run(["migrate", "dev"], { isTty: { stdout: true } }); + + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe( + "✘ [CLI.TEST_REDIRECT] `prisma-test migrate dev` is not available\n" + + " why: Planning and applying are separate steps.\n" + + "→ Step 1: prisma-test migration plan\n" + + "→ Step 2: prisma-test db migrate --db \n" + + "→ Read its help: prisma-test migration status --help\n" + + "→ Read the docs: https://example.com/docs/cli\n", + ); + }); + + test("a flag redirect carries the new fields", async () => { + const result = await redirectingCli([ + { + from: "migration status", + flag: "graph", + code: "CLI.TEST_FLAG_REDIRECT", + summary: "`--graph` is gone from `{bin} migration status`", + help: "migration status", + docsUrl: "https://example.com/docs/cli", + }, + ]).run(["migration", "status", "--graph", "--json"]); + + expect(result.exitCode).toBe(2); + const envelope = erroredEnvelope(result.json); + expect(envelope.commandId).toBe("migration.status"); + expect(envelope.error.code).toBe("CLI.TEST_FLAG_REDIRECT"); + expect(envelope.error.summary).toBe( + "`--graph` is gone from `prisma-test migration status`", + ); + expect(envelope.nextActions).toEqual([ + { + kind: "run-command", + label: "Read its help", + command: "prisma-test migration status --help", + }, + { + kind: "open-url", + label: "Read the docs", + url: "https://example.com/docs/cli", + }, + ]); + }); +}); diff --git a/packages/cli/package.json b/packages/cli/package.json index 79610d2c..7d7f9e22 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -49,7 +49,7 @@ }, "dependencies": { "@manypkg/tools": "^2.1.2", - "@prisma/cli-engine": "workspace:0.9.0", + "@prisma/cli-engine": "workspace:0.10.0", "@prisma/composer-cli": "0.38.0", "@prisma/compute-sdk": "0.43.0", "@prisma/management-api-sdk": "1.80.0", diff --git a/packages/cli/scripts/conformance.ts b/packages/cli/scripts/conformance.ts index 3403120d..370eb7ce 100644 --- a/packages/cli/scripts/conformance.ts +++ b/packages/cli/scripts/conformance.ts @@ -109,7 +109,24 @@ async function tarball(): Promise { shellPackage: "@prisma/cli", enginePackage: "@prisma/cli-engine", familyPackages: ["@prisma/composer-cli", "@prisma/orm-toolchain"], - exceptions: [], + exceptions: [ + { + familyPackage: "@prisma/composer-cli", + familyPin: "0.9.0", + shellPin: "0.10.0", + reason: "engine 0.10.0 must publish before composer-cli can peer it", + removeWhen: + "composer-cli releases peering 0.10.0 and the follow-up bump PR pins that release", + }, + { + familyPackage: "@prisma/orm-toolchain", + familyPin: "0.9.0", + shellPin: "0.10.0", + reason: "engine 0.10.0 must publish before orm-toolchain can peer it", + removeWhen: + "orm-toolchain releases peering 0.10.0 and the follow-up bump PR pins that release", + }, + ], channel: CHANNEL, sandboxDir: join(WORK_DIR, "sandbox"), }, diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 54c1ef68..32ea43ca 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -69,6 +69,7 @@ import { serviceVersionStartCommand } from "./commands/service/version-start"; import { serviceVersionStopCommand } from "./commands/service/version-stop"; import { skillsCommandFamily } from "./commands/skills/family"; import { getCliVersion } from "./lib/version"; +import { v7CommandFamily } from "./v7-redirects"; export const platformCommandFamily: CommandFamily = defineCommandFamily({ docsBaseUrl: DOCS_ERRORS_BASE_URL, @@ -479,6 +480,7 @@ export function buildCli(): Cli { composerCommandFamily, ormCommandFamily, skillsCommandFamily, + v7CommandFamily, ], groups: cliGroups, commands: mountedCommands, diff --git a/packages/cli/src/v7-redirects.ts b/packages/cli/src/v7-redirects.ts new file mode 100644 index 00000000..3b710838 --- /dev/null +++ b/packages/cli/src/v7-redirects.ts @@ -0,0 +1,112 @@ +import { + type CommandFamily, + defineCommandFamily, + type RedirectSpec, +} from "@prisma/cli-engine"; +import { CLI_DOCS_URL } from "./cli-name"; + +function v7Command( + from: string, + entry: Omit, +): RedirectSpec { + return { + from, + code: "CLI.V7_COMMAND", + summary: `\`{bin} ${from}\` is a Prisma 7 command and is not available in Prisma 8`, + ...entry, + }; +} + +function v7Flag( + command: string, + flag: string, + entry: Omit, +): RedirectSpec { + return { + from: command, + flag, + code: "CLI.V7_FLAG", + summary: `\`--${flag.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}\` on \`{bin} ${command}\` is a Prisma 7 flag and is not available in Prisma 8`, + ...entry, + }; +} + +const INIT_SCHEMA_REASON = + "`init` prepares this repository for Prisma: it writes prisma.config.ts, adds prisma as a dev dependency and installs the AI-agent skills. It sets up no database schema or client; `orm init` does that."; + +const INIT_SCHEMA_FLAGS: readonly string[] = [ + "datasourceProvider", + "generatorProvider", + "previewFeature", + "output", + "url", + "withModel", +]; + +export const v7CommandFamily: CommandFamily = defineCommandFamily({ + commands: {}, + redirects: [ + v7Command("bootstrap", { + replacement: [ + "{bin} project create ", + "{bin} postgres create ", + ], + help: "project create", + reason: + "Setting up a new app takes two commands: `project create` creates a Project, the container for one app's databases and services, and links this directory to it; `postgres create` then adds a Prisma Postgres database to that Project and prints its connection URL once, without writing it to a .env file. Neither sets up a database schema or the code your app queries the database with; `orm init` does that.", + }), + v7Command("version", { + replacement: "{bin} --version", + reason: + "`--version` prints only this CLI's version number. It does not report Node.js, operating system or engine details.", + }), + v7Command("debug", { + docsUrl: CLI_DOCS_URL, + reason: + "No command prints debugging information about this CLI and its environment.", + }), + v7Command("mcp", { + docsUrl: CLI_DOCS_URL, + reason: + "No command starts an MCP (Model Context Protocol) server for AI tools.", + }), + v7Command("complete", { + docsUrl: CLI_DOCS_URL, + reason: + "This CLI has no shell completion: no command prints or installs a completion script for your shell.", + }), + v7Command("platform status", { + docsUrl: CLI_DOCS_URL, + reason: + "No command reports the status of your Prisma Platform account. The docs list the commands that inspect workspaces, Projects and databases.", + }), + v7Command("postgres link", { + replacement: [ + "{bin} project link", + "{bin} postgres connection create ", + ], + help: "postgres connection create", + reason: + "Linking and connecting are two commands: `project link` points this directory at an existing Project, so commands run here act on it; `postgres connection create` creates a connection URL for one of its databases. The URL prints once, in that command's output; nothing writes it to a .env file.", + }), + v7Flag("init", "db", { + replacement: "{bin} postgres create ", + help: "postgres create", + reason: + "`init` creates no database. `postgres create` creates a Prisma Postgres database in the Project this directory is linked to.", + }), + v7Flag("init", "noSkills", { + replacement: "{bin} init --skills=none", + help: "init", + reason: + "`--skills=none` skips installing the AI-agent skills and records in prisma.config.ts that none are wanted, so later installs do not add them.", + }), + ...INIT_SCHEMA_FLAGS.map((flag) => + v7Flag("init", flag, { + replacement: "{bin} orm init", + help: "orm init", + reason: INIT_SCHEMA_REASON, + }), + ), + ], +}); diff --git a/packages/cli/tests/v7-redirects.test.ts b/packages/cli/tests/v7-redirects.test.ts new file mode 100644 index 00000000..9697f6bb --- /dev/null +++ b/packages/cli/tests/v7-redirects.test.ts @@ -0,0 +1,275 @@ +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { StreamEvent } from "@prisma/cli-engine"; +import type { NextAction } from "@prisma/cli-engine/protocol"; +import { describe, expect, it } from "vitest"; +import { buildCli, mountedCommands } from "../src/cli"; +import { CLI_DOCS_URL } from "../src/cli-name"; +import { assembleRuntime, type HostProcess } from "../src/runtime"; +import { v7CommandFamily } from "../src/v7-redirects"; + +const CONFIG_HOME = join(tmpdir(), "v7-redirects-test-config-home"); +const UPPERCASE_LETTER = /[A-Z]/g; +const WHY_LINE = /^ {2}why: /; +const WHITESPACE = /\s+/; +const PRISMA_7 = /Prisma 7|prisma@7/; +const PRISMA_7_PACKAGE = /prisma@7/; + +function makeProcess(argv: readonly string[], stdoutIsTty: boolean) { + const proc = { + argv: ["node", "bin.js", ...argv], + version: "v22.12.0", + versions: { node: "22.12.0" }, + platform: "linux", + arch: "x64", + env: { + PRISMA_DISABLE_TELEMETRY: "1", + XDG_CONFIG_HOME: CONFIG_HOME, + APPDATA: CONFIG_HOME, + }, + cwd: () => "/tmp/v7-redirects-test-cwd", + stdoutText: "", + stderrText: "", + stdout: { + isTTY: stdoutIsTty, + write(text: string) { + proc.stdoutText += text; + }, + }, + stderr: { + isTTY: false, + write(text: string) { + proc.stderrText += text; + }, + }, + stdin: { + isTTY: false, + async *[Symbol.asyncIterator]() {}, + } as unknown as HostProcess["stdin"], + on() { + return proc; + }, + off() { + return proc; + }, + exit(code: number): never { + throw new Error(`process.exit(${code})`); + }, + }; + return proc; +} + +async function run(argv: readonly string[], stdoutIsTty = false) { + const proc = makeProcess(argv, stdoutIsTty); + const runtime = await assembleRuntime(proc as unknown as HostProcess); + const exitCode = await buildCli().run(argv, runtime); + return { exitCode, stdout: proc.stdoutText, stderr: proc.stderrText }; +} + +function failedEnvelope(stdout: string) { + const frames = stdout + .split("\n") + .filter((line) => line !== "") + .map((line) => JSON.parse(line) as StreamEvent); + const last = frames.at(-1); + if (last?.kind !== "result" || last.envelope.ok) { + throw new Error(`expected a failed result frame, got: ${stdout}`); + } + return last.envelope; +} + +function step(label: string, command: string): NextAction { + return { kind: "run-command", label, command }; +} + +function help(path: string): NextAction { + return step("Read its help", `prisma ${path} --help`); +} + +const DOCS: NextAction = { + kind: "open-url", + label: "Read the docs", + url: CLI_DOCS_URL, +}; + +const ORM_INIT: readonly NextAction[] = [ + step("Use the replacement", "prisma orm init"), + help("orm init"), +]; + +const PATHS: Readonly> = { + bootstrap: [ + step("Step 1", "prisma project create "), + step("Step 2", "prisma postgres create "), + help("project create"), + ], + version: [step("Use the replacement", "prisma --version")], + debug: [DOCS], + mcp: [DOCS], + complete: [DOCS], + "platform status": [DOCS], + "postgres link": [ + step("Step 1", "prisma project link"), + step("Step 2", "prisma postgres connection create "), + help("postgres connection create"), + ], +}; + +const INIT_FLAGS: Readonly> = { + db: [ + step("Use the replacement", "prisma postgres create "), + help("postgres create"), + ], + "datasource-provider": ORM_INIT, + "generator-provider": ORM_INIT, + "preview-feature": ORM_INIT, + output: ORM_INIT, + url: ORM_INIT, + "with-model": ORM_INIT, + "no-skills": [ + step("Use the replacement", "prisma init --skills=none"), + help("init"), + ], +}; + +function humanLine(action: NextAction): string { + return `→ ${action.label}: ${action.command ?? action.url}`; +} + +describe("v7 command paths the shell owns", () => { + it("declares exactly the paths this test covers", () => { + expect( + v7CommandFamily.redirects + .filter((redirect) => redirect.flag === undefined) + .map((redirect) => redirect.from) + .sort(), + ).toEqual(Object.keys(PATHS).sort()); + }); + + it.each( + Object.entries(PATHS), + )("`%s` settles as CLI.V7_COMMAND in --json output", async (path, nextActions) => { + const result = await run([...path.split(" "), "--json"]); + + expect(result.exitCode).toBe(2); + const envelope = failedEnvelope(result.stdout); + expect(envelope.commandId).toBe(path.replaceAll(" ", ".")); + expect(envelope.error.code).toBe("CLI.V7_COMMAND"); + expect(envelope.error.summary).toBe( + `\`prisma ${path}\` is a Prisma 7 command and is not available in Prisma 8`, + ); + expect(envelope.error.why).toEqual(expect.any(String)); + expect(envelope.nextActions).toEqual(nextActions); + expect(envelope.error.nextActions).toEqual(nextActions); + }); + + it.each( + Object.entries(PATHS), + )("`%s` settles as CLI.V7_COMMAND in human output", async (path, nextActions) => { + const result = await run(path.split(" "), true); + + expect(result.exitCode).toBe(2); + expect(result.stdout).toBe(""); + const lines = result.stderr.trimEnd().split("\n"); + expect(lines[0]).toBe( + `✘ [CLI.V7_COMMAND] \`prisma ${path}\` is a Prisma 7 command and is not available in Prisma 8`, + ); + expect(lines[1]).toMatch(WHY_LINE); + expect(lines.slice(-nextActions.length)).toEqual( + nextActions.map(humanLine), + ); + }); +}); + +describe("v7 flags on the shell's init", () => { + it("declares exactly the flags this test covers", () => { + expect( + v7CommandFamily.redirects + .filter((redirect) => redirect.flag !== undefined) + .map((redirect) => { + expect(redirect.from).toBe("init"); + return redirect.flag?.replace( + UPPERCASE_LETTER, + (letter) => `-${letter.toLowerCase()}`, + ); + }) + .sort(), + ).toEqual(Object.keys(INIT_FLAGS).sort()); + }); + + it.each( + Object.entries(INIT_FLAGS), + )("`init --%s` settles as CLI.V7_FLAG in --json output", async (flag, nextActions) => { + const result = await run(["init", `--${flag}`, "--json"]); + + expect(result.exitCode).toBe(2); + const envelope = failedEnvelope(result.stdout); + expect(envelope.commandId).toBe("init"); + expect(envelope.error.code).toBe("CLI.V7_FLAG"); + expect(envelope.error.summary).toBe( + `\`--${flag}\` on \`prisma init\` is a Prisma 7 flag and is not available in Prisma 8`, + ); + expect(envelope.error.why).toEqual(expect.any(String)); + expect(envelope.nextActions).toEqual(nextActions); + }); + + it.each( + Object.entries(INIT_FLAGS), + )("`init --%s` settles as CLI.V7_FLAG in human output", async (flag, nextActions) => { + const result = await run(["init", `--${flag}`], true); + + expect(result.exitCode).toBe(2); + const lines = result.stderr.trimEnd().split("\n"); + expect(lines[0]).toBe( + `✘ [CLI.V7_FLAG] \`--${flag}\` on \`prisma init\` is a Prisma 7 flag and is not available in Prisma 8`, + ); + expect(lines.slice(-nextActions.length)).toEqual( + nextActions.map(humanLine), + ); + }); + + it("a value after the retired flag does not stop it matching", async () => { + const result = await run([ + "init", + "--datasource-provider", + "mysql", + "--json", + ]); + + expect(failedEnvelope(result.stdout).error.code).toBe("CLI.V7_FLAG"); + }); +}); + +function suggestedPath(invocation: string): string { + return invocation + .replaceAll("{bin}", "") + .split(WHITESPACE) + .filter( + (token) => + token !== "" && !token.startsWith("-") && !token.startsWith("<"), + ) + .join(" "); +} + +describe("every suggestion names a mounted command", () => { + const suggestions = v7CommandFamily.redirects.flatMap((redirect) => [ + ...redirect.replacement, + ...(redirect.help === undefined ? [] : [redirect.help]), + ]); + + it.each(suggestions)("`%s` is mounted", (suggestion) => { + if (suggestion === "{bin} --version") { + return; + } + expect(Object.keys(mountedCommands)).toContain(suggestedPath(suggestion)); + }); + + it("no entry mentions Prisma 7 outside its summary", () => { + for (const redirect of v7CommandFamily.redirects) { + expect(redirect.reason).not.toMatch(PRISMA_7); + for (const suggestion of redirect.replacement) { + expect(suggestion).not.toMatch(PRISMA_7_PACKAGE); + } + } + }); +}); diff --git a/packages/prisma/package.json b/packages/prisma/package.json index 154dd232..9fca1914 100644 --- a/packages/prisma/package.json +++ b/packages/prisma/package.json @@ -50,7 +50,7 @@ }, "dependencies": { "@manypkg/tools": "^2.1.2", - "@prisma/cli-engine": "workspace:0.9.0", + "@prisma/cli-engine": "workspace:0.10.0", "@prisma/composer-cli": "0.38.0", "@prisma/compute-sdk": "0.43.0", "@prisma/management-api-sdk": "1.80.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c41508e3..7241d39d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,7 +27,7 @@ importers: specifier: ^2.1.2 version: 2.1.2 '@prisma/cli-engine': - specifier: workspace:0.9.0 + specifier: workspace:0.10.0 version: link:../cli-engine '@prisma/composer-cli': specifier: 0.38.0 @@ -210,7 +210,7 @@ importers: specifier: ^2.1.2 version: 2.1.2 '@prisma/cli-engine': - specifier: workspace:0.9.0 + specifier: workspace:0.10.0 version: link:../cli-engine '@prisma/composer-cli': specifier: 0.38.0