From 1ee70a18def97fa406c8b924405672641f0ebe61 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 17:06:22 -0500 Subject: [PATCH 01/13] test: add coverage for interactive user prompts Add a bunch of missing coverage for interactive prompts, in preparation for swapping the underlying implementation. --- .../commands/agents/agents-create.test.ts | 40 +- .../commands/deploy/deploy-api-routes.ts | 2 + .../commands/link/link-prompt.test.ts | 445 ++++++++++++++++++ tests/integration/commands/link/link.test.ts | 2 - .../commands/sites/sites-delete.test.ts | 202 ++++++++ tests/integration/utils/mock-api.ts | 16 +- tests/unit/utils/run-program.test.ts | 117 +++++ tests/unit/utils/scripted-commands.test.ts | 177 +++++-- 8 files changed, 956 insertions(+), 45 deletions(-) create mode 100644 tests/integration/commands/link/link-prompt.test.ts create mode 100644 tests/integration/commands/sites/sites-delete.test.ts create mode 100644 tests/unit/utils/run-program.test.ts diff --git a/tests/integration/commands/agents/agents-create.test.ts b/tests/integration/commands/agents/agents-create.test.ts index d9116d09220..80b269d5ff1 100644 --- a/tests/integration/commands/agents/agents-create.test.ts +++ b/tests/integration/commands/agents/agents-create.test.ts @@ -5,7 +5,7 @@ import { callCli } from '../../utils/call-cli.js' import { cliPath } from '../../utils/cli-path.js' import { getCLIOptions, withMockApi } from '../../utils/mock-api.js' import { withSiteBuilder } from '../../utils/site-builder.js' -import { answerWithValue, handleQuestions } from '../../utils/handle-questions.js' +import { CONFIRM, answerWithValue, handleQuestions } from '../../utils/handle-questions.js' import { mockSiteInfo, mockSiteInfoNoRepo, mockAgentRunner, mockAgentRunnerNoRepo } from './fixtures.js' // Mock spinner to avoid UI interference in tests @@ -122,6 +122,44 @@ describe('agents:create command', () => { }) }) + test('should prompt for agent selection when --agent is omitted', async (t) => { + const routes = [ + ...baseRoutes, + { + path: 'agent_runners', + method: 'POST' as const, + response: mockAgentRunner, + }, + ] + + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const childProcess = execa(cliPath, ['agents:create', 'Build a contact form', '--branch', 'main'], { + cwd: builder.directory, + env: { NETLIFY_API_URL: apiUrl, NETLIFY_SITE_ID: 'site_id', NETLIFY_AUTH_TOKEN: 'fake-token' }, + }) + + handleQuestions(childProcess, [ + { + question: 'Which agent would you like to use?', + answer: CONFIRM, + }, + ]) + + const result = await childProcess + + expect(result.stdout).toContain('Which agent would you like to use?') + expect(result.stdout).toContain('Agent task created successfully!') + expect(result.stdout).toContain('Agent: Claude') + + const createRequest = requests.find(({ method, path }) => method === 'POST' && path === '/api/v1/agent_runners') + expect(createRequest?.body).toMatchObject({ agent: 'claude', prompt: 'Build a contact form', branch: 'main' }) + }) + }) + }) + test('should validate prompt input', async (t) => { await withSiteBuilder(t, async (builder) => { await builder.build() diff --git a/tests/integration/commands/deploy/deploy-api-routes.ts b/tests/integration/commands/deploy/deploy-api-routes.ts index d927946a75d..6ceacc7a296 100644 --- a/tests/integration/commands/deploy/deploy-api-routes.ts +++ b/tests/integration/commands/deploy/deploy-api-routes.ts @@ -221,6 +221,7 @@ export const startDeployMockApi = ({ routes }: { routes: Route[] }): Promise ({ + askedPrompts: [] as AskedPrompt[], + exitCalls: [] as number[], + logMessages: [] as string[], + mockPromptSelect: vi.fn<(question: SelectQuestion) => Promise>(), + mockPromptText: vi.fn<(question: TextQuestion) => Promise>(), + mockTrack: vi.fn(), + promptAnswers: [] as unknown[], + }), +) + +vi.mock('@inquirer/prompts', async (importOriginal) => ({ + ...(await importOriginal()), + select: ({ message, choices }: { message: string; choices: (string | InquirerChoice)[] }) => + mockPromptSelect({ + message, + options: choices.map((choice) => + typeof choice === 'string' ? { value: choice, label: choice } : { value: choice.value, label: choice.name }, + ), + }), + input: ({ message }: TextQuestion) => mockPromptText({ message }), +})) + +vi.mock('../../../../src/utils/scripted-commands.js', async (importOriginal) => ({ + ...(await importOriginal()), + isInteractive: () => true, +})) + +vi.mock('../../../../src/utils/command-helpers.js', async (importOriginal) => ({ + ...(await importOriginal()), + log: (...args: string[]) => { + logMessages.push(args.join(' ')) + }, + exit: (code = 0) => { + exitCalls.push(code) + throw new Error(`process.exit(${code.toString()})`) + }, +})) + +vi.mock('../../../../src/utils/telemetry/telemetry.js', async (importOriginal) => ({ + ...(await importOriginal()), + track: mockTrack, +})) + +vi.mock('../../../../src/utils/telemetry/report-error.js', async (importOriginal) => ({ + ...(await importOriginal()), + reportError: vi.fn(), +})) + +const optionLabel = (option: AskedOption): string => option.label ?? String(option.value) + +const nextAnswer = (message: string): unknown => { + if (promptAnswers.length === 0) { + throw new Error(`Unexpected prompt "${message}" with no answer queued`) + } + return promptAnswers.shift() +} + +mockPromptSelect.mockImplementation((question) => { + askedPrompts.push({ type: 'select', message: question.message, options: question.options }) + return Promise.resolve().then(() => { + const answer = nextAnswer(question.message) + const option = question.options.find((item) => optionLabel(item) === answer) + if (option === undefined) { + throw new Error(`Prompt "${question.message}" did not offer a choice labelled '${String(answer)}'`) + } + return option.value + }) +}) + +mockPromptText.mockImplementation((question) => { + askedPrompts.push({ type: 'text', message: question.message }) + return Promise.resolve().then(() => String(nextAnswer(question.message))) +}) + +const queuePromptAnswers = (...answers: unknown[]) => { + promptAnswers.length = 0 + promptAnswers.push(...answers) +} + +const askedMessages = () => askedPrompts.map((prompt) => prompt.message) + +const offeredOptions = (message: string) => askedPrompts.find((prompt) => prompt.message === message)?.options + +const offeredChoices = (message: string) => offeredOptions(message)?.map(optionLabel) + +const output = () => stripAnsi(logMessages.join('\n')) + +const HOW_TO_LINK = 'How do you want to link this folder to a project?' +const WHICH_PROJECT = 'Which project do you want to link?' +const SEARCH_TERM = 'Enter the project name (or just part of it):' +const PROJECT_ID = 'What is the project ID?' + +const LINK_BY_NAME = 'Search by full or partial project name' +const LINK_FROM_LIST = 'Choose from a list of your recently updated projects' +const LINK_BY_ID = 'Enter a project ID' +const REPO_URL = 'https://github.com/owner/repo' +const LINK_BY_GIT_REMOTE = `Use current git remote origin (${REPO_URL})` + +const makeSite = (name: string, repoUrl?: string) => ({ + id: `${name}-id`, + name, + ssl_url: `https://${name}.netlify.app`, + admin_url: `https://app.netlify.com/projects/${name}`, + build_settings: repoUrl === undefined ? {} : { repo_url: repoUrl }, +}) + +type Site = ReturnType + +const routesWithSites = (sites: Site[], extra: Route[] = []): Route[] => [ + { path: 'accounts', response: [{ slug: 'test-account' }] }, + { path: 'sites', response: sites }, + ...extra, +] + +const NETLIFY_ENV_KEYS = ['NETLIFY_AUTH_TOKEN', 'NETLIFY_SITE_ID', 'NETLIFY_API_URL'] +// `--http-proxy` defaults to `HTTP_PROXY`/`HTTPS_PROXY`, which would route the in-process API client +// through that proxy instead of to the mock API. +const PROXY_ENV_KEYS = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'] +const MANAGED_ENV_KEYS = [...NETLIFY_ENV_KEYS, ...PROXY_ENV_KEYS] +let savedEnv: Record = {} + +const useMockApi = (apiUrl: string) => { + Object.assign(process.env, getEnvironmentVariables({ apiUrl }), { NETLIFY_SITE_ID: '' }) + for (const key of PROXY_ENV_KEYS) { + Reflect.deleteProperty(process.env, key) + } +} + +// The base command derives the repository root from `process.cwd()` rather than `--cwd`, and +// framework detection never finishes when the working directory lies outside that root. Worker +// threads cannot `chdir`, so point `cwd` at the fixture for the duration of the command. +const runLink = async (directory: string) => { + const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(directory) + try { + const program = new BaseCommand('netlify') + createLinkCommand(program) + await program.parseAsync(['', '', 'link', '--cwd', directory]) + } finally { + cwdSpy.mockRestore() + } +} + +const readLinkedSiteId = async (directory: string): Promise => { + try { + const state = JSON.parse(await readFile(join(directory, '.netlify', 'state.json'), 'utf8')) as { siteId?: string } + return state.siteId + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return undefined + } + throw error + } +} + +const getRequests = (requests: MockApiTestContext['requests'], path: string) => + requests.filter((request) => request.method === 'GET' && request.path === `/api/v1/${path}`) + +const expectLinkedTo = async (directory: string, site: Site, kind: string) => { + expect(await readLinkedSiteId(directory)).toBe(site.id) + expect(output()).toContain('Directory Linked') + expect(output()).toContain(`Admin url: ${site.admin_url}`) + expect(output()).toContain(site.ssl_url) + expect(mockTrack).toHaveBeenCalledTimes(1) + expect(mockTrack).toHaveBeenCalledWith('sites_linked', { siteId: site.id, linkType: 'prompt', kind }) +} + +const expectNotLinked = async (directory: string) => { + expect(await readLinkedSiteId(directory)).toBeUndefined() + expect(output()).not.toContain('Directory Linked') + expect(mockTrack).not.toHaveBeenCalled() +} + +describe('link command interactive prompts', () => { + beforeEach(() => { + savedEnv = Object.fromEntries(MANAGED_ENV_KEYS.map((key) => [key, process.env[key]])) + askedPrompts.length = 0 + exitCalls.length = 0 + logMessages.length = 0 + promptAnswers.length = 0 + mockTrack.mockClear() + }) + + afterEach(() => { + for (const key of MANAGED_ENV_KEYS) { + if (savedEnv[key] === undefined) { + Reflect.deleteProperty(process.env, key) + } else { + process.env[key] = savedEnv[key] + } + } + }) + + describe('by project ID', () => { + test('links to the project fetched by the entered ID', async (t) => { + const site = makeSite('by-id') + const routes = routesWithSites([], [{ path: `sites/${site.id}`, response: site }]) + + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_ID, site.id) + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK, PROJECT_ID]) + expect(offeredChoices(HOW_TO_LINK)).toEqual([LINK_BY_NAME, LINK_FROM_LIST, LINK_BY_ID]) + expect(getRequests(requests, `sites/${site.id}`)).toHaveLength(1) + expect(getRequests(requests, 'sites')).toHaveLength(0) + await expectLinkedTo(builder.directory, site, 'bySiteId') + }) + }) + }) + + test('fails without linking when no project has the entered ID', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi( + routesWithSites([]), + async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_ID, 'missing-id') + + await expect(runLink(builder.directory)).rejects.toThrow("Project ID 'missing-id' not found") + + expect(getRequests(requests, 'sites/missing-id')).toHaveLength(1) + await expectNotLinked(builder.directory) + }, + true, + ) + }) + }) + }) + + describe('by project name', () => { + test('links the project the user picks when several match the search term', async (t) => { + const sites = [makeSite('unicorn-prod'), makeSite('unicorn-staging')] + + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithSites(sites), async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_NAME, 'unicorn', 'unicorn-staging') + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK, SEARCH_TERM, WHICH_PROJECT]) + expect(offeredChoices(WHICH_PROJECT)).toEqual(['unicorn-prod', 'unicorn-staging']) + expect(output()).toContain("Looking for projects with names containing 'unicorn'") + expect(output()).toContain('Found 2 matching projects!') + expect(getRequests(requests, 'sites')).toMatchObject([{ query: { name: 'unicorn', filter: 'all' } }]) + await expectLinkedTo(builder.directory, sites[1], 'byName') + }) + }) + }) + + test('links the single match without asking the user to pick', async (t) => { + const site = makeSite('unicorn-prod') + + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithSites([site]), async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_NAME, 'unicorn') + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK, SEARCH_TERM]) + expect(getRequests(requests, 'sites')).toMatchObject([{ query: { name: 'unicorn', filter: 'all' } }]) + await expectLinkedTo(builder.directory, site, 'byName') + }) + }) + }) + + test('fails without linking when nothing matches the search term', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithSites([]), async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_NAME, 'nothing-here') + + await expect(runLink(builder.directory)).rejects.toThrow("No project names found containing 'nothing-here'") + + expect(askedMessages()).toEqual([HOW_TO_LINK, SEARCH_TERM]) + expect(getRequests(requests, 'sites')).toMatchObject([{ query: { name: 'nothing-here', filter: 'all' } }]) + await expectNotLinked(builder.directory) + }) + }) + }) + }) + + describe('from a list of recently updated projects', () => { + test('links the project the user picks from the list', async (t) => { + const sites = [makeSite('first-site'), makeSite('second-site'), makeSite('third-site')] + + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithSites(sites), async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_FROM_LIST, 'second-site') + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK, WHICH_PROJECT]) + expect(offeredChoices(WHICH_PROJECT)).toEqual(['first-site', 'second-site', 'third-site']) + expect(output()).toContain('Fetching recently updated projects...') + expect(getRequests(requests, 'sites')).toHaveLength(1) + await expectLinkedTo(builder.directory, sites[1], 'fromList') + }) + }) + }) + + test('fails without linking when the account has no projects', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithSites([]), async ({ apiUrl }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_FROM_LIST) + + await expect(runLink(builder.directory)).rejects.toThrow("You don't have any projects yet") + + expect(askedMessages()).toEqual([HOW_TO_LINK]) + await expectNotLinked(builder.directory) + }) + }) + }) + }) + + describe('by git remote origin', () => { + const unrelatedSite = makeSite('unrelated', 'https://github.com/someone/else') + + test('offers the remote first and links the project the user picks when several are connected to it', async (t) => { + const connected = [makeSite('repo-prod', REPO_URL), makeSite('repo-preview', REPO_URL)] + + await withSiteBuilder(t, async (builder) => { + await builder.withGit({ repoUrl: 'git@github.com:owner/repo.git' }).build() + + await withMockApi( + routesWithSites([connected[0], unrelatedSite, connected[1]]), + async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_GIT_REMOTE, `${connected[1].name} - ${connected[1].ssl_url}`) + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK, WHICH_PROJECT]) + expect(offeredChoices(HOW_TO_LINK)).toEqual([LINK_BY_GIT_REMOTE, LINK_BY_NAME, LINK_FROM_LIST, LINK_BY_ID]) + expect(offeredChoices(WHICH_PROJECT)).toEqual([ + `${connected[0].name} - ${connected[0].ssl_url}`, + `${connected[1].name} - ${connected[1].ssl_url}`, + ]) + expect(getRequests(requests, 'sites')).toHaveLength(1) + await expectLinkedTo(builder.directory, connected[1], 'gitRemote') + }, + ) + }) + }) + + test('links the single connected project without asking the user to pick', async (t) => { + const connected = makeSite('repo-prod', REPO_URL) + + await withSiteBuilder(t, async (builder) => { + await builder.withGit({ repoUrl: 'git@github.com:owner/repo.git' }).build() + + await withMockApi(routesWithSites([unrelatedSite, connected]), async ({ apiUrl, requests }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_GIT_REMOTE) + + await runLink(builder.directory) + + expect(askedMessages()).toEqual([HOW_TO_LINK]) + expect(getRequests(requests, 'sites')).toHaveLength(1) + await expectLinkedTo(builder.directory, connected, 'gitRemote') + }) + }) + }) + + test('prints guidance and exits with 1 when no project is connected to the remote', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.withGit({ repoUrl: 'git@github.com:owner/repo.git' }).build() + + await withMockApi(routesWithSites([unrelatedSite]), async ({ apiUrl }) => { + useMockApi(apiUrl) + queuePromptAnswers(LINK_BY_GIT_REMOTE) + + await expect(runLink(builder.directory)).rejects.toThrow('process.exit(1)') + + expect(exitCalls).toEqual([1]) + expect(askedMessages()).toEqual([HOW_TO_LINK]) + expect(output()).toContain('No matching project found') + expect(output()).toContain(`No project found with the remote ${REPO_URL}`) + expect(output()).toContain('link --id ') + await expectNotLinked(builder.directory) + }) + }) + }) + }) +}) diff --git a/tests/integration/commands/link/link.test.ts b/tests/integration/commands/link/link.test.ts index 5ef8310ce2c..ff2ca0a4701 100644 --- a/tests/integration/commands/link/link.test.ts +++ b/tests/integration/commands/link/link.test.ts @@ -128,8 +128,6 @@ describe('link command', () => { test.todo('should print an error and exit when no project with given `--git-remote-url` is found') - test.todo("should prompt user when a project matching the local git repo's remote origin HTTPS URL is found") - test('should create gitignore in repository root when is root', async (t) => { await withSiteBuilder(t, async (builder) => { await builder.withGit().build() diff --git a/tests/integration/commands/sites/sites-delete.test.ts b/tests/integration/commands/sites/sites-delete.test.ts new file mode 100644 index 00000000000..85eb9b7f242 --- /dev/null +++ b/tests/integration/commands/sites/sites-delete.test.ts @@ -0,0 +1,202 @@ +import execa from 'execa' +import { describe, expect, test } from 'vitest' + +import { cliPath } from '../../utils/cli-path.js' +import { CONFIRM, answerWithValue, handleQuestions } from '../../utils/handle-questions.js' +import { getCLIOptions, withMockApi, type MockApiTestContext, type Route } from '../../utils/mock-api.js' +import { withSiteBuilder } from '../../utils/site-builder.js' + +const siteInfo = { + admin_url: 'https://app.netlify.com/projects/site-name/overview', + ssl_url: 'https://site-name.netlify.app/', + id: 'site_id', + name: 'site-name', + build_settings: { env: {} }, +} + +const otherSiteInfo = { + ...siteInfo, + admin_url: 'https://app.netlify.com/projects/other-site/overview', + ssl_url: 'https://other-site.netlify.app/', + id: 'other_site', + name: 'other-site', +} + +const routes: Route[] = [ + { path: 'sites/site_id', response: siteInfo }, + { path: 'sites/site_id/service-instances', response: [] }, + { path: 'sites/site_id', method: 'DELETE', response: {} }, + { path: 'user', response: { name: 'test user', slug: 'test-user', email: 'user@test.com' } }, + { path: 'accounts', response: [{ slug: 'test-account' }] }, +] + +const routesWithOtherLinkedSite: Route[] = [ + ...routes, + { path: 'sites/other_site', response: otherSiteInfo }, + { path: 'sites/other_site/service-instances', response: [] }, +] + +const CONFIRM_QUESTION = 'Are you sure you want to delete the' +const VERIFY_QUESTION = 'Verify & Proceed with deletion of project' +const DELETED_MESSAGE = 'Project "site_id" successfully deleted!' + +const deleteRequests = (requests: MockApiTestContext['requests']) => + requests.filter(({ method, path }) => method === 'DELETE' && path === '/api/v1/sites/site_id') + +const promptingEnv = { TESTING_PROMPTS: 'true' } + +describe('sites:delete command', () => { + test('deletes the project when the user confirms', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const childProcess = execa( + cliPath, + ['sites:delete', 'site_id'], + getCLIOptions({ apiUrl, builder, env: promptingEnv }), + ) + + handleQuestions(childProcess, [{ question: CONFIRM_QUESTION, answer: answerWithValue('y') }]) + + const { stdout } = await childProcess + + expect(stdout).toContain('You are about to permanently delete "site-name"') + expect(stdout).toContain(CONFIRM_QUESTION) + expect(stdout).toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(1) + }) + }) + }) + + test('does not delete the project when the user declines', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const childProcess = execa( + cliPath, + ['sites:delete', 'site_id'], + getCLIOptions({ apiUrl, builder, env: promptingEnv }), + ) + + handleQuestions(childProcess, [{ question: CONFIRM_QUESTION, answer: CONFIRM }]) + + const { exitCode, stdout } = await childProcess + + expect(exitCode).toBe(0) + expect(stdout).toContain(CONFIRM_QUESTION) + expect(stdout).not.toContain('Deleting project') + expect(stdout).not.toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(0) + }) + }) + }) + + test('skips the confirmation prompt with --force', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const { stdout } = await execa( + cliPath, + ['sites:delete', 'site_id', '--force'], + getCLIOptions({ apiUrl, builder, env: promptingEnv }), + ) + + expect(stdout).not.toContain('Warning') + expect(stdout).not.toContain(CONFIRM_QUESTION) + expect(stdout).not.toContain(VERIFY_QUESTION) + expect(stdout).toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(1) + }) + }) + }) + + test('skips the confirmation prompt in a non-interactive shell', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const { stdout } = await execa(cliPath, ['sites:delete', 'site_id'], getCLIOptions({ apiUrl, builder })) + + expect(stdout).not.toContain(CONFIRM_QUESTION) + expect(stdout).toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(1) + }) + }) + }) + + test('asks for a second confirmation when the id differs from the linked project', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithOtherLinkedSite, async ({ apiUrl, requests }) => { + const childProcess = execa( + cliPath, + ['sites:delete', 'site_id'], + getCLIOptions({ apiUrl, builder, env: { ...promptingEnv, NETLIFY_SITE_ID: 'other_site' } }), + ) + + handleQuestions(childProcess, [ + { question: CONFIRM_QUESTION, answer: answerWithValue('y') }, + { question: VERIFY_QUESTION, answer: answerWithValue('y') }, + ]) + + const { stdout } = await childProcess + + expect(stdout).toContain('The project ID supplied does not match the current working directory project ID') + expect(stdout).toMatch(/Supplied:\s+"site_id"/) + expect(stdout).toMatch(/Current Project:\s+"other_site"/) + expect(stdout).toContain(VERIFY_QUESTION) + expect(stdout).toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(1) + }) + }) + }) + + test('does not delete the project when the second confirmation is declined', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithOtherLinkedSite, async ({ apiUrl, requests }) => { + const childProcess = execa( + cliPath, + ['sites:delete', 'site_id'], + getCLIOptions({ apiUrl, builder, env: { ...promptingEnv, NETLIFY_SITE_ID: 'other_site' } }), + ) + + handleQuestions(childProcess, [ + { question: CONFIRM_QUESTION, answer: answerWithValue('y') }, + { question: VERIFY_QUESTION, answer: CONFIRM }, + ]) + + const { exitCode, stdout } = await childProcess + + expect(exitCode).toBe(0) + expect(stdout).toContain(VERIFY_QUESTION) + expect(stdout).not.toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(0) + }) + }) + }) + + test('does not prompt for the linked-project mismatch with --force', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routesWithOtherLinkedSite, async ({ apiUrl, requests }) => { + const { stdout } = await execa( + cliPath, + ['sites:delete', 'site_id', '--force'], + getCLIOptions({ apiUrl, builder, env: { ...promptingEnv, NETLIFY_SITE_ID: 'other_site' } }), + ) + + expect(stdout).not.toContain(CONFIRM_QUESTION) + expect(stdout).not.toContain(VERIFY_QUESTION) + expect(stdout).toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(1) + }) + }) + }) +}) diff --git a/tests/integration/utils/mock-api.ts b/tests/integration/utils/mock-api.ts index 033f27e0e10..2909c9c69eb 100644 --- a/tests/integration/utils/mock-api.ts +++ b/tests/integration/utils/mock-api.ts @@ -22,14 +22,23 @@ interface MockApiOptions { export interface MockApi { apiUrl: string clearRequests: () => void - requests: { path: string; body: unknown; method: string; headers: IncomingHttpHeaders }[] + requests: { + path: string + query: express.Request['query'] + body: unknown + method: string + headers: IncomingHttpHeaders + }[] server: Server close: () => Promise } +export type MockApiTestContext = Pick + const addRequest = (requests: MockApi['requests'], request: express.Request) => { requests.push({ path: request.path, + query: request.query, body: request.body, method: request.method, headers: request.headers, @@ -131,10 +140,7 @@ export const startMockApi = ({ routes, silent }: MockApiOptions): Promise Promise, + testHandler: (options: MockApiTestContext) => Promise, silent = false, ) => { let mockApi: Awaited> | undefined diff --git a/tests/unit/utils/run-program.test.ts b/tests/unit/utils/run-program.test.ts new file mode 100644 index 00000000000..279cd1dc36b --- /dev/null +++ b/tests/unit/utils/run-program.test.ts @@ -0,0 +1,117 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' + +// ci-info computes `isCI` once at import time; pin it so results don't depend on where this suite runs. +vi.mock('ci-info', () => ({ isCI: false })) + +import { CI_FORCED_COMMANDS } from '../../../src/commands/main.js' +import { runProgram } from '../../../src/utils/run-program.js' + +const restoreTTYs: (() => void)[] = [] + +const stubStdinTTY = (isTTY: boolean | undefined) => { + const original = process.stdin.isTTY + Object.defineProperty(process.stdin, 'isTTY', { value: isTTY, configurable: true }) + restoreTTYs.push(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: original, configurable: true }) + }) +} + +const stubScriptedShell = () => { + stubStdinTTY(undefined) + vi.stubEnv('CI', undefined) + vi.stubEnv('TESTING_PROMPTS', undefined) +} + +const stubInteractiveShell = () => { + stubStdinTTY(true) + vi.stubEnv('CI', undefined) + vi.stubEnv('TESTING_PROMPTS', undefined) +} + +const createProgram = () => { + const parseAsync = vi.fn().mockResolvedValue(undefined) + const program = { parseAsync } as unknown as Parameters[0] + return { program, parseAsync } +} + +const run = async (argv: string[]) => { + const { program, parseAsync } = createProgram() + await runProgram(program, argv) + expect(parseAsync).toHaveBeenCalledOnce() + return parseAsync.mock.calls[0][0] as string[] +} + +afterEach(() => { + restoreTTYs.splice(0).forEach((restore) => { + restore() + }) + vi.unstubAllEnvs() +}) + +describe('runProgram', () => { + describe('CI-forced commands', () => { + test.each(Object.keys(CI_FORCED_COMMANDS))('should inject --force for `%s` when scripted', async (cmdName) => { + stubScriptedShell() + const argv = ['node', 'netlify', cmdName, 'FOO', 'bar'] + expect(await run(argv)).toEqual(['node', 'netlify', cmdName, 'FOO', 'bar', '--force']) + }) + + test('should inject --force when CI env var is set even if stdin is a TTY', async () => { + stubInteractiveShell() + vi.stubEnv('CI', 'true') + expect(await run(['node', 'netlify', 'env:set', 'FOO', 'bar'])).toEqual([ + 'node', + 'netlify', + 'env:set', + 'FOO', + 'bar', + '--force', + ]) + }) + + test('should not duplicate --force when already present', async () => { + stubScriptedShell() + expect(await run(['node', 'netlify', 'env:set', 'FOO', 'bar', '--force'])).toEqual([ + 'node', + 'netlify', + 'env:set', + 'FOO', + 'bar', + '--force', + ]) + }) + + test('should not inject --force when TESTING_PROMPTS is true', async () => { + stubScriptedShell() + vi.stubEnv('TESTING_PROMPTS', 'true') + expect(await run(['node', 'netlify', 'env:set', 'FOO', 'bar'])).toEqual([ + 'node', + 'netlify', + 'env:set', + 'FOO', + 'bar', + ]) + }) + + test('should not inject --force when interactive', async () => { + stubInteractiveShell() + expect(await run(['node', 'netlify', 'env:set', 'FOO', 'bar'])).toEqual([ + 'node', + 'netlify', + 'env:set', + 'FOO', + 'bar', + ]) + }) + }) + + describe('other commands', () => { + test.each(['link', 'env:list', 'sites:create', 'deploy'])( + 'should never inject --force for `%s` even when scripted', + async (cmdName) => { + stubScriptedShell() + expect(await run(['node', 'netlify', cmdName, '--json'])).toEqual(['node', 'netlify', cmdName, '--json']) + }, + ) + }) +}) diff --git a/tests/unit/utils/scripted-commands.test.ts b/tests/unit/utils/scripted-commands.test.ts index 0b2a5fed09e..74cf3994287 100644 --- a/tests/unit/utils/scripted-commands.test.ts +++ b/tests/unit/utils/scripted-commands.test.ts @@ -1,50 +1,153 @@ -import { describe, expect, test, vi, afterEach } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' -describe('isInteractive', () => { - afterEach(() => { - vi.restoreAllMocks() - vi.resetModules() +// ci-info computes `isCI` once at import time, so each test re-imports the module under test with a +// pinned value. +const loadModule = async ({ isCI = false } = {}) => { + vi.doMock('ci-info', () => ({ isCI })) + return import('../../../src/utils/scripted-commands.js') +} + +const restoreTTYs: (() => void)[] = [] + +const stubTTY = (stream: { isTTY?: boolean }, isTTY: boolean | undefined) => { + const original = stream.isTTY + Object.defineProperty(stream, 'isTTY', { value: isTTY, configurable: true }) + restoreTTYs.push(() => { + Object.defineProperty(stream, 'isTTY', { value: original, configurable: true }) }) +} - const loadModule = async () => { - const mod = await import('../../../src/utils/scripted-commands.js') - return mod.isInteractive - } +const stubInteractiveTerminal = () => { + stubTTY(process.stdin, true) + stubTTY(process.stdout, true) + vi.stubEnv('CI', undefined) + vi.stubEnv('TESTING_PROMPTS', undefined) +} + +afterEach(() => { + restoreTTYs.splice(0).forEach((restore) => { + restore() + }) + vi.unstubAllEnvs() + vi.doUnmock('ci-info') + vi.restoreAllMocks() + vi.resetModules() +}) + +describe('isInteractive', () => { + test('should return true when stdin and stdout are TTYs outside CI', async () => { + stubInteractiveTerminal() + const { isInteractive } = await loadModule() + expect(isInteractive()).toBe(true) + }) test('should return false when CI env var is set', async () => { - const originalCI = process.env.CI - process.env.CI = 'true' - try { - const isInteractive = await loadModule() - expect(isInteractive()).toBe(false) - } finally { - if (originalCI === undefined) { - delete process.env.CI - } else { - process.env.CI = originalCI - } - } + stubInteractiveTerminal() + vi.stubEnv('CI', 'true') + const { isInteractive } = await loadModule() + expect(isInteractive()).toBe(false) + }) + + test('should return false when ci-info detects a CI vendor', async () => { + stubInteractiveTerminal() + const { isInteractive } = await loadModule({ isCI: true }) + expect(isInteractive()).toBe(false) }) test('should return false when stdin is not a TTY', async () => { - const originalIsTTY = process.stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { value: undefined, configurable: true }) - try { - const isInteractive = await loadModule() - expect(isInteractive()).toBe(false) - } finally { - Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, configurable: true }) - } + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + const { isInteractive } = await loadModule() + expect(isInteractive()).toBe(false) }) test('should return false when stdout is not a TTY', async () => { - const originalIsTTY = process.stdout.isTTY - Object.defineProperty(process.stdout, 'isTTY', { value: undefined, configurable: true }) - try { - const isInteractive = await loadModule() - expect(isInteractive()).toBe(false) - } finally { - Object.defineProperty(process.stdout, 'isTTY', { value: originalIsTTY, configurable: true }) - } + stubInteractiveTerminal() + stubTTY(process.stdout, undefined) + const { isInteractive } = await loadModule() + expect(isInteractive()).toBe(false) + }) +}) + +describe('shouldForceFlagBeInjected', () => { + const argv = ['node', 'netlify', 'env:set', 'FOO', 'bar'] + + test('should return true when stdin is not a TTY and --force is absent', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + const { shouldForceFlagBeInjected } = await loadModule() + expect(shouldForceFlagBeInjected(argv)).toBe(true) + }) + + test('should return true when CI env var is set even if stdin is a TTY', async () => { + stubInteractiveTerminal() + vi.stubEnv('CI', 'true') + const { shouldForceFlagBeInjected } = await loadModule() + expect(shouldForceFlagBeInjected(argv)).toBe(true) + }) + + test('should return true when ci-info detects a CI vendor even if stdin is a TTY', async () => { + stubInteractiveTerminal() + const { shouldForceFlagBeInjected } = await loadModule({ isCI: true }) + expect(shouldForceFlagBeInjected(argv)).toBe(true) + }) + + test('should return false when --force is already present', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + const { shouldForceFlagBeInjected } = await loadModule() + expect(shouldForceFlagBeInjected([...argv, '--force'])).toBe(false) + }) + + test('should return false when TESTING_PROMPTS is true even if stdin is not a TTY', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + vi.stubEnv('TESTING_PROMPTS', 'true') + const { shouldForceFlagBeInjected } = await loadModule() + expect(shouldForceFlagBeInjected(argv)).toBe(false) + }) + + test('should return false when interactive', async () => { + stubInteractiveTerminal() + const { shouldForceFlagBeInjected } = await loadModule() + expect(shouldForceFlagBeInjected(argv)).toBe(false) + }) +}) + +describe('injectForceFlagIfScripted', () => { + test('should append --force to argv when scripted', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + const { injectForceFlagIfScripted } = await loadModule() + const argv = ['node', 'netlify', 'env:set', 'FOO', 'bar'] + injectForceFlagIfScripted(argv) + expect(argv).toEqual(['node', 'netlify', 'env:set', 'FOO', 'bar', '--force']) + }) + + test('should not duplicate --force when already present', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + const { injectForceFlagIfScripted } = await loadModule() + const argv = ['node', 'netlify', 'env:set', 'FOO', 'bar', '--force'] + injectForceFlagIfScripted(argv) + expect(argv).toEqual(['node', 'netlify', 'env:set', 'FOO', 'bar', '--force']) + }) + + test('should leave argv unchanged when TESTING_PROMPTS is true', async () => { + stubInteractiveTerminal() + stubTTY(process.stdin, undefined) + vi.stubEnv('TESTING_PROMPTS', 'true') + const { injectForceFlagIfScripted } = await loadModule() + const argv = ['node', 'netlify', 'env:set', 'FOO', 'bar'] + injectForceFlagIfScripted(argv) + expect(argv).toEqual(['node', 'netlify', 'env:set', 'FOO', 'bar']) + }) + + test('should leave argv unchanged when interactive', async () => { + stubInteractiveTerminal() + const { injectForceFlagIfScripted } = await loadModule() + const argv = ['node', 'netlify', 'env:set', 'FOO', 'bar'] + injectForceFlagIfScripted(argv) + expect(argv).toEqual(['node', 'netlify', 'env:set', 'FOO', 'bar']) }) }) From 5b96adc7012a7959191747f764229285dbc4024e Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:15 -0500 Subject: [PATCH 02/13] fix(completion): wait for .zshrc read before writing to it `completion:install` prepended the compinit line from inside an un-awaited `fs.readFile` callback, so it logged success before anything was written, and a failed read would have written `undefined` into ~/.zshrc. --- src/commands/completion/completion.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/commands/completion/completion.ts b/src/commands/completion/completion.ts index 00201fd2c9e..6579a2e1e75 100644 --- a/src/commands/completion/completion.ts +++ b/src/commands/completion/completion.ts @@ -61,12 +61,8 @@ export const completionGenerate = async (_options: OptionValues, command: BaseCo default: true, }) if (compinitAdded) { - fs.readFile(zshConfigFilepath, 'utf8', (_err, data) => { - const updatedZshFile = AUTOLOAD_COMPINIT + '\n' + data - - fs.writeFileSync(zshConfigFilepath, updatedZshFile, 'utf8') - }) - + const zshConfig = fs.readFileSync(zshConfigFilepath, 'utf8') + fs.writeFileSync(zshConfigFilepath, `${AUTOLOAD_COMPINIT}\n${zshConfig}`, 'utf8') log('Successfully added compinit line to .zshrc') } } From b361273b85bb79f4bdd67c2c4c5e9eeb9911e6a2 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:16 -0500 Subject: [PATCH 03/13] fix(functions): await edge function route registration The netlify.toml append wasn't awaited, so a write failure escaped the surrounding try/catch and we logged that the route was registered regardless. --- eslint-suppressions.json | 5 +---- src/commands/functions/functions-create.ts | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 73ba6024678..342420e2783 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -245,9 +245,6 @@ } }, "src/commands/functions/functions-create.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - }, "@typescript-eslint/no-unnecessary-condition": { "count": 2 }, @@ -1689,4 +1686,4 @@ "count": 4 } } -} \ No newline at end of file +} diff --git a/src/commands/functions/functions-create.ts b/src/commands/functions/functions-create.ts index 7c80691659a..303516271bb 100644 --- a/src/commands/functions/functions-create.ts +++ b/src/commands/functions/functions-create.ts @@ -605,7 +605,7 @@ const registerEFInToml = async (funcName, options) => { const functionRegister = `\n\n[[edge_functions]]\nfunction = "${funcName}"\npath = "${funcPath}"` try { - fs.promises.appendFile(configFilePath, functionRegister) + await fs.promises.appendFile(configFilePath, functionRegister) log( `${NETLIFYDEVLOG} Function '${funcName}' registered for route \`${funcPath}\`. To change, edit your \`${relConfigFilePath}\` file.`, ) From 1b390ca4842ffc6eff0fc047df3337bae4313156 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:16 -0500 Subject: [PATCH 04/13] fix(functions): remove stray `$` from download error message --- src/commands/functions/functions-create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/functions/functions-create.ts b/src/commands/functions/functions-create.ts index 303516271bb..709e805569f 100644 --- a/src/commands/functions/functions-create.ts +++ b/src/commands/functions/functions-create.ts @@ -496,7 +496,7 @@ const scaffoldFromTemplate = async function (command, options, argumentName, fun try { await downloadFromURL(command, options, argumentName, functionsDir) } catch { - return logAndThrowError(`$${NETLIFYDEVERR} Error downloading from URL: ${options.url}`) + return logAndThrowError(`${NETLIFYDEVERR} Error downloading from URL: ${options.url}`) } } else if (chosenTemplate === 'report') { log(`${NETLIFYDEVLOG} Open in browser: https://github.com/netlify/cli/issues/new`) From e1ac84ed724d39e01af0ad011ef919c69abc9494 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:16 -0500 Subject: [PATCH 05/13] refactor(functions): drop no-op template sort tiebreaker It subtracted two objects, which is always `NaN`, which `sort` treats as `0` anyway. The comment justifying it was about Node 10. --- src/commands/functions/functions-create.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/commands/functions/functions-create.ts b/src/commands/functions/functions-create.ts index 709e805569f..6375bc61d48 100644 --- a/src/commands/functions/functions-create.ts +++ b/src/commands/functions/functions-create.ts @@ -144,11 +144,7 @@ const formatRegistryArrayForInquirer = async function (lang, funcType) { return priorityDiff } - // This branch is needed because `Array.prototype.sort` was not stable - // until Node 11, so the original sorting order from `fs.readdirSync` - // was not respected. We can simplify this once we drop support for - // Node 10. - return templateA - templateB + return 0 }) .map((t) => { t.lang = lang From a29a9fe4f81dcce0b92df73cb7a4c2c3aa13acab Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:17 -0500 Subject: [PATCH 06/13] fix(recipes): await Deno extension install in vscode recipe A failed install skipped the handler that prints manual install instructions. --- eslint-suppressions.json | 5 +---- src/recipes/vscode/index.ts | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 342420e2783..ec5267b9655 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -732,9 +732,6 @@ } }, "src/recipes/vscode/index.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - }, "@typescript-eslint/no-unsafe-argument": { "count": 2 }, @@ -1686,4 +1683,4 @@ "count": 4 } } -} +} \ No newline at end of file diff --git a/src/recipes/vscode/index.ts b/src/recipes/vscode/index.ts index abe30ab8452..bb8095388c1 100644 --- a/src/recipes/vscode/index.ts +++ b/src/recipes/vscode/index.ts @@ -87,7 +87,7 @@ export const run = async ({ config, repositoryRoot }) => { if (!(await hasDenoVSCodeExt(repositoryRoot))) { const denoExtConfirm = await getDenoExtPrompt() if (denoExtConfirm) { - getDenoVSCodeExt(repositoryRoot) + await getDenoVSCodeExt(repositoryRoot) } } } catch { From 1d6f86d9e07764ae15b52d879be279b885c282c9 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:17 -0500 Subject: [PATCH 07/13] fix(link): suggest `--git-remote-url`, not `--gitRemoteUrl` The latter doesn't exist. --- src/commands/link/link.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/link/link.ts b/src/commands/link/link.ts index ceba30bb11f..d97173dfd63 100644 --- a/src/commands/link/link.ts +++ b/src/commands/link/link.ts @@ -363,7 +363,7 @@ Link by project name: ${chalk.cyanBright(`${netlifyCommand()} link --name `)} Link by git remote URL: - ${chalk.cyanBright(`${netlifyCommand()} link --gitRemoteUrl `)} + ${chalk.cyanBright(`${netlifyCommand()} link --git-remote-url `)} To search for projects: ${chalk.cyanBright(`${netlifyCommand()} sites:search `)} From 41e9112222c4c5b4b0cf90346dbd9a94bb382479 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:17 -0500 Subject: [PATCH 08/13] fix(init): remove stray backtick from base directory prompt --- src/utils/init/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/init/utils.ts b/src/utils/init/utils.ts index 077451c8dad..7145112ae80 100644 --- a/src/utils/init/utils.ts +++ b/src/utils/init/utils.ts @@ -89,7 +89,7 @@ export const getBuildSettings = async ({ const baseDir = defaultBaseDir === '' ? undefined - : await input({ message: 'Base directory `(blank for current dir):', default: defaultBaseDir }) + : await input({ message: 'Base directory (blank for current dir):', default: defaultBaseDir }) const buildCmdInput = await input({ message: 'Your build command (hugo build/yarn run build/etc):', default: defaultBuildCmd, From 1f6e13db3f5d42f946a4470c1d19268571aced1e Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:56:18 -0500 Subject: [PATCH 09/13] fix(sites): don't ask for a project name twice when left blank Leaving the name blank is supposed to get you a random one, but `sites:create` passed the blank answer back into the prompt helper, which treated it as missing and asked again. --- src/commands/sites/sites-create.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/sites/sites-create.ts b/src/commands/sites/sites-create.ts index db33e18ae07..d61b293d5a7 100644 --- a/src/commands/sites/sites-create.ts +++ b/src/commands/sites/sites-create.ts @@ -57,7 +57,7 @@ export const sitesCreate = async (options: OptionValues, command: BaseCommand) = const MAX_NAME_RETRIES = 2 const tryCreateSiteInteractive = async (nameToTry: string | undefined): Promise => { - const { name: attemptName } = await getSiteNameInput(nameToTry) + const attemptName = nameToTry ?? (await getSiteNameInput(undefined)).name const body: { name?: string } = {} if (attemptName.trim()) { body.name = attemptName.trim() From 18f7bd0b8e02b97e77e2bb36f9c9eca087d0864e Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:57:25 -0500 Subject: [PATCH 10/13] fix(database): don't prompt to overwrite files without a TTY `database init` asked whether to overwrite an existing drizzle.config.ts or db/schema.ts even with `--yes` or without a TTY, where nothing can answer. Now `--yes` overwrites, and a non-interactive run leaves the file alone and says so. --- src/commands/database/db-init.ts | 41 +++++++++++++------- tests/unit/commands/database/db-init.test.ts | 31 +++++++++++++++ 2 files changed, 59 insertions(+), 13 deletions(-) diff --git a/src/commands/database/db-init.ts b/src/commands/database/db-init.ts index de2107fc16a..d129a99f201 100644 --- a/src/commands/database/db-init.ts +++ b/src/commands/database/db-init.ts @@ -52,16 +52,27 @@ const success = (text: string): void => { log(chalk.green(`✓ ${text}`)) } -const carefullyWriteFile = async (filePath: string, data: string, projectRoot: string) => { - if (existsSync(filePath)) { - const overwrite = await confirm({ - message: `Overwrite existing file .${filePath.replace(projectRoot, '')}?`, - }) - if (overwrite) { - await writeFile(filePath, data) - } - } else { +type ExistingFilePolicy = 'ask' | 'overwrite' | 'keep' + +const carefullyWriteFile = async ( + filePath: string, + data: string, + projectRoot: string, + onExisting: ExistingFilePolicy, +) => { + if (!existsSync(filePath)) { + await writeFile(filePath, data) + return + } + const displayPath = `.${filePath.replace(projectRoot, '')}` + const overwrite = + onExisting === 'ask' + ? await confirm({ message: `Overwrite existing file ${displayPath}?` }) + : onExisting === 'overwrite' + if (overwrite) { await writeFile(filePath, data) + } else if (onExisting === 'keep') { + info(`${displayPath} already exists, leaving it unchanged`) } } @@ -111,6 +122,7 @@ const installDependencies = async ( projectRoot: string, migrationsDirectory: string, queryStyle: QueryStyle, + onExistingFile: ExistingFilePolicy, ): Promise => { sectionHeading('Install dependencies') info("We'll install the dependencies you need to use Netlify Database") @@ -145,7 +157,7 @@ const installDependencies = async ( if (queryStyle === 'drizzle') { const out = relativeToProject(projectRoot, migrationsDirectory) - await carefullyWriteFile(join(projectRoot, 'drizzle.config.ts'), drizzleConfigTs(out), projectRoot) + await carefullyWriteFile(join(projectRoot, 'drizzle.config.ts'), drizzleConfigTs(out), projectRoot, onExistingFile) success('drizzle.config.ts ready') } } @@ -157,6 +169,7 @@ const scaffoldStarter = async ( projectRoot: string, migrationsDirectory: string, queryStyle: QueryStyle, + onExistingFile: ExistingFilePolicy, ): Promise => { sectionHeading('Create a starter migration') @@ -166,7 +179,7 @@ const scaffoldStarter = async ( const schemaDir = join(projectRoot, 'db') await mkdir(schemaDir, { recursive: true }) - await carefullyWriteFile(join(schemaDir, 'schema.ts'), DRIZZLE_SCHEMA_TS, projectRoot) + await carefullyWriteFile(join(schemaDir, 'schema.ts'), DRIZZLE_SCHEMA_TS, projectRoot, onExistingFile) success('db/schema.ts ready') log('') @@ -307,6 +320,8 @@ export const initDatabase = async (options: DatabaseInitOptions, command: BaseCo } const yes = options.yes ?? false const interactive = isInteractive() && !yes + // `--yes` takes the overwrite prompt's default (yes); without it, a non-interactive run keeps existing files. + const onExistingFile: ExistingFilePolicy = interactive ? 'ask' : yes ? 'overwrite' : 'keep' const pm = getPackageManager(command) log(chalk.bold('Netlify Database')) @@ -339,12 +354,12 @@ export const initDatabase = async (options: DatabaseInitOptions, command: BaseCo const queryStyle = await promptForQueryStyle(interactive) - await installDependencies(pm, projectRoot, migrationsDirectory, queryStyle) + await installDependencies(pm, projectRoot, migrationsDirectory, queryStyle, onExistingFile) const withStarter = await promptForStarter(interactive) if (withStarter) { - await scaffoldStarter(pm, projectRoot, migrationsDirectory, queryStyle) + await scaffoldStarter(pm, projectRoot, migrationsDirectory, queryStyle, onExistingFile) sectionHeading('Apply the migration') info( diff --git a/tests/unit/commands/database/db-init.test.ts b/tests/unit/commands/database/db-init.test.ts index 4e1ea4b1129..0b0c511e09b 100644 --- a/tests/unit/commands/database/db-init.test.ts +++ b/tests/unit/commands/database/db-init.test.ts @@ -296,6 +296,37 @@ describe('initDatabase (integration)', () => { expect(mockApplyMigrations).toHaveBeenCalledOnce() }) + test('non-interactive keeps an existing drizzle.config.ts instead of blocking on a prompt', async () => { + mockIsInteractive.mockReturnValue(false) + await fs.writeFile(join(projectRoot(), 'drizzle.config.ts'), '// hand-written config') + + await initDatabase({}, createCommand(projectRoot())) + + expect(confirm).not.toHaveBeenCalled() + expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toBe('// hand-written config') + expect(logMessages.join('\n')).toContain('already exists, leaving it unchanged') + }) + + test('--yes overwrites an existing drizzle.config.ts without prompting', async () => { + await fs.writeFile(join(projectRoot(), 'drizzle.config.ts'), '// hand-written config') + + await initDatabase({ yes: true }, createCommand(projectRoot())) + + expect(confirm).not.toHaveBeenCalled() + expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toContain('defineConfig') + }) + + test('interactive still asks before overwriting an existing drizzle.config.ts', async () => { + vi.mocked(select).mockResolvedValueOnce('drizzle') + vi.mocked(confirm).mockResolvedValueOnce(false).mockResolvedValueOnce(false) + await fs.writeFile(join(projectRoot(), 'drizzle.config.ts'), '// hand-written config') + + await initDatabase({}, createCommand(projectRoot())) + + expect(vi.mocked(confirm).mock.calls[0][0].message).toContain('Overwrite existing file') + expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toBe('// hand-written config') + }) + test('throws when project root cannot be determined', async () => { const command = { project: { root: undefined, baseDirectory: undefined, packageManager: null }, From 45ab5839f6b2836d7e17a1e631de145cca4a93f1 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 16:58:01 -0500 Subject: [PATCH 11/13] fix(recipes): don't prompt for a typo suggestion without a TTY MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `recipes ` prompted "Did you mean …?" even when nothing could answer, so in CI it sat there for the full 10s timeout, then exited 0. It now prints the suggestion to stderr and exits 2 without a TTY, and exits 2 when the suggestion is declined, like the top-level did-you-mean. --- src/commands/recipes/recipes.ts | 20 +++++++++++++------ .../__snapshots__/recipes.test.ts.snap | 6 +----- .../commands/recipes/recipes.test.ts | 5 +++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/commands/recipes/recipes.ts b/src/commands/recipes/recipes.ts index 56e7d6784b8..1b67ade007f 100644 --- a/src/commands/recipes/recipes.ts +++ b/src/commands/recipes/recipes.ts @@ -4,7 +4,9 @@ import { OptionValues } from 'commander' import { closest } from 'fastest-levenshtein' import { confirm } from '@inquirer/prompts' -import { NETLIFYDEVERR, chalk, log } from '../../utils/command-helpers.js' +import { chalk, exit, logError } from '../../utils/command-helpers.js' +import { EXIT_CODES } from '../../utils/exit-codes.js' +import { isInteractive } from '../../utils/scripted-commands.js' import BaseCommand from '../base-command.js' import { getRecipe, listRecipes } from './common.js' @@ -46,13 +48,18 @@ export const recipesCommand = async (recipeName: string, options: OptionValues, throw error } - log(`${NETLIFYDEVERR} ${chalk.yellow(recipeName)} is not a valid recipe name.`) - const recipes = await listRecipes() - const recipeNames = recipes.map(({ name }) => name) - const suggestion = closest(recipeName, recipeNames) + const suggestion = closest( + recipeName, + recipes.map(({ name }) => name), + ) + const didYouMean = `${chalk.yellow(recipeName)} is not a valid recipe name. Did you mean ${chalk.blue(suggestion)}?` + if (!isInteractive()) { + logError(didYouMean) + return exit(EXIT_CODES.USAGE_ERROR) + } const applySuggestion = await confirm( - { message: `Did you mean ${chalk.blue(suggestion)}`, default: false }, + { message: didYouMean, default: false }, { signal: AbortSignal.timeout(SUGGESTION_TIMEOUT) }, ).catch((error: unknown) => { if (error instanceof Error && error.name === 'AbortPromptError') { @@ -64,5 +71,6 @@ export const recipesCommand = async (recipeName: string, options: OptionValues, if (applySuggestion) { return recipesCommand(suggestion, options, command) } + return exit(EXIT_CODES.USAGE_ERROR) } } diff --git a/tests/integration/commands/recipes/__snapshots__/recipes.test.ts.snap b/tests/integration/commands/recipes/__snapshots__/recipes.test.ts.snap index e8d4d91dcfa..b92762e601b 100644 --- a/tests/integration/commands/recipes/__snapshots__/recipes.test.ts.snap +++ b/tests/integration/commands/recipes/__snapshots__/recipes.test.ts.snap @@ -12,8 +12,4 @@ exports[`commands/recipes > Shows a list of all the available recipes 1`] = ` '-----------------------------------------------------------------------------------------'" `; -exports[`commands/recipes > Suggests closest matching recipe on typo 1`] = ` -"⬥ vsc is not a valid recipe name. -? Did you mean vscode (y/N) -[?25h" -`; +exports[`commands/recipes > Suggests closest matching recipe on typo 1`] = `"› Error: vsc is not a valid recipe name. Did you mean vscode?"`; diff --git a/tests/integration/commands/recipes/recipes.test.ts b/tests/integration/commands/recipes/recipes.test.ts index b2d59544f60..98949a4c562 100644 --- a/tests/integration/commands/recipes/recipes.test.ts +++ b/tests/integration/commands/recipes/recipes.test.ts @@ -150,8 +150,9 @@ describe.concurrent('commands/recipes', () => { }) test('Suggests closest matching recipe on typo', async (t) => { - const cliResponse = (await callCli(['recipes', 'vsc'])) as string + const error = await (callCli(['recipes', 'vsc']) as Promise).catch((error_: unknown) => error_) - t.expect(normalize(cliResponse)).toMatchSnapshot() + t.expect(error).toHaveProperty('exitCode', 2) + t.expect(normalize((error as { stderr: string }).stderr)).toMatchSnapshot() }) }) From 11ae2ab7440d128e79861d636a6525ede64d4eec Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 17:02:14 -0500 Subject: [PATCH 12/13] feat: swap inquirer for clack Every prompt now goes through a small wrapper around @clack/prompts in `src/utils/prompts`. It handles the stuff each call site used to handle (or not) on its own: - Ctrl+C or Esc prints "Cancelled." and exits 130, after running any shutdown work a command already registered (e.g. `netlify dev`'s database) - piped stdin works: a line feed submits, and stdin is released afterwards so the process can exit - confirms take a `timeout` after which they count as declined (the did-you-mean prompts use this) - `defaultValue` doubles as the placeholder, and it's what gets validated when the input is left empty - autocomplete filters on what's displayed (label and hint), not on the stringified value Importing @clack/prompts anywhere else is now a lint error. The prompts look and behave a bit differently, on purpose: confirms submit on `y`/`n` without Enter, select options show details as hints instead of `name - url` labels, and `env:list` prints revealed values below the table instead of redrawing it in place. Also drops @inquirer/prompts, fuzzy, log-update and ansi-escapes, and pins `TERM` in tests so snapshots don't depend on the terminal they were recorded in. --- eslint-suppressions.json | 35 +- eslint.config.js | 5 + package-lock.json | 513 ++---------------- package.json | 5 +- src/commands/agents/agents-create.ts | 26 +- src/commands/base-command.ts | 24 +- src/commands/clone/clone.ts | 9 +- src/commands/completion/completion.ts | 7 +- src/commands/create/create-action.ts | 21 +- src/commands/database/db-init.ts | 18 +- src/commands/database/db-migration-new.ts | 19 +- src/commands/database/db-migration-pull.ts | 7 +- src/commands/database/db-reset.ts | 7 +- src/commands/deploy/deploy.ts | 24 +- src/commands/deploy/remote-deploy.ts | 4 +- src/commands/env/env-list.ts | 16 +- src/commands/functions/functions-create.ts | 127 ++--- src/commands/functions/functions-invoke.ts | 19 +- src/commands/init/init.ts | 14 +- src/commands/link/link.ts | 43 +- src/commands/logs/build.ts | 8 +- src/commands/main.ts | 20 +- src/commands/recipes/recipes.ts | 14 +- src/commands/sites/sites-create.ts | 16 +- src/commands/sites/sites-delete.ts | 10 +- src/commands/switch/switch.ts | 8 +- src/lib/edge-functions/editor-helper.ts | 10 +- src/lib/secure-storage.ts | 16 +- src/recipes/ai-context/index.ts | 14 +- src/recipes/blobs-migrate/index.ts | 9 +- src/recipes/vscode/index.ts | 16 +- src/utils/build-info.ts | 36 +- src/utils/dev.ts | 8 - src/utils/exit-codes.ts | 2 +- src/utils/gh-auth.ts | 8 +- src/utils/init/agent-mcp.ts | 11 +- src/utils/init/config-manual.ts | 16 +- src/utils/init/utils.ts | 46 +- src/utils/prompts/confirm-prompt.ts | 8 +- src/utils/prompts/index.ts | 112 ++++ src/utils/shell.ts | 21 +- .../framework-detection.test.ts.snap | 38 +- tests/integration/auth-token-storage.test.ts | 2 +- .../commands/blobs/blobs-delete.test.ts | 36 +- .../commands/blobs/blobs-set.test.ts | 38 +- .../completion/completion-install.test.ts | 2 +- .../__snapshots__/didyoumean.test.ts.snap | 8 +- .../env/__snapshots__/env.test.ts.snap | 71 ++- .../commands/env/env-clone.test.ts | 27 +- .../integration/commands/env/env-set.test.ts | 27 +- .../commands/env/env-unset.test.ts | 27 +- tests/integration/commands/env/env.test.ts | 4 +- .../help/__snapshots__/help.test.ts.snap | 2 +- tests/integration/commands/init/init.test.ts | 10 +- .../commands/link/link-prompt.test.ts | 29 +- .../commands/recipes/recipes.test.ts | 6 +- .../commands/sites/sites-delete.test.ts | 34 +- .../integration/commands/sites/sites.test.ts | 12 +- tests/integration/utils/handle-questions.ts | 22 +- .../integration/utils/inquirer-mock-prompt.ts | 8 - tests/integration/utils/mock-prompts.ts | 7 + tests/integration/utils/snapshots.ts | 4 + .../unit/commands/base-command-on-end.test.ts | 13 - tests/unit/commands/database/db-init.test.ts | 48 +- .../database/db-migration-new.test.ts | 48 +- .../database/db-migration-pull.test.ts | 46 +- tests/unit/commands/database/db-reset.test.ts | 26 +- .../unit/commands/sites/sites-create.test.ts | 6 +- tests/unit/commands/switch/switch.test.ts | 25 +- tests/unit/lib/secure-storage.test.ts | 12 +- tests/unit/recipes/ai-context/index.test.ts | 6 +- tests/unit/utils/init/agent-mcp.test.ts | 9 - tests/unit/utils/init/config-manual.test.ts | 14 +- tests/unit/utils/prompts/prompts.test.ts | 283 ++++++++++ vitest.config.ts | 9 +- 75 files changed, 1079 insertions(+), 1232 deletions(-) create mode 100644 src/utils/prompts/index.ts delete mode 100644 tests/integration/utils/inquirer-mock-prompt.ts create mode 100644 tests/integration/utils/mock-prompts.ts create mode 100644 tests/unit/utils/prompts/prompts.test.ts diff --git a/eslint-suppressions.json b/eslint-suppressions.json index ec5267b9655..2e383a7f55d 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -252,28 +252,25 @@ "count": 1 }, "@typescript-eslint/no-unsafe-argument": { - "count": 36 + "count": 33 }, "@typescript-eslint/no-unsafe-assignment": { - "count": 38 + "count": 34 }, "@typescript-eslint/no-unsafe-call": { - "count": 8 + "count": 5 }, "@typescript-eslint/no-unsafe-member-access": { - "count": 47 + "count": 34 }, "@typescript-eslint/no-unsafe-return": { - "count": 11 + "count": 7 }, "@typescript-eslint/prefer-nullish-coalescing": { "count": 4 }, - "@typescript-eslint/restrict-plus-operands": { - "count": 6 - }, "@typescript-eslint/restrict-template-expressions": { - "count": 24 + "count": 22 }, "n/no-process-exit": { "count": 2 @@ -281,25 +278,19 @@ }, "src/commands/functions/functions-invoke.ts": { "@typescript-eslint/no-unsafe-argument": { - "count": 4 - }, - "@typescript-eslint/no-unsafe-assignment": { - "count": 13 - }, - "@typescript-eslint/no-unsafe-call": { "count": 3 }, - "@typescript-eslint/no-unsafe-member-access": { - "count": 5 + "@typescript-eslint/no-unsafe-assignment": { + "count": 7 }, "@typescript-eslint/no-unsafe-return": { - "count": 7 + "count": 3 }, "@typescript-eslint/prefer-nullish-coalescing": { "count": 3 }, "@typescript-eslint/restrict-template-expressions": { - "count": 3 + "count": 2 }, "no-empty": { "count": 1 @@ -343,7 +334,7 @@ "count": 1 }, "@typescript-eslint/no-unsafe-assignment": { - "count": 7 + "count": 6 }, "@typescript-eslint/no-unsafe-call": { "count": 1 @@ -781,7 +772,7 @@ "count": 5 }, "@typescript-eslint/restrict-template-expressions": { - "count": 4 + "count": 3 } }, "src/utils/command-helpers.ts": { @@ -888,7 +879,7 @@ }, "src/utils/dev.ts": { "@typescript-eslint/no-unsafe-argument": { - "count": 3 + "count": 2 }, "@typescript-eslint/no-unsafe-assignment": { "count": 9 diff --git a/eslint.config.js b/eslint.config.js index 5bedc42ec65..d423a7b83e4 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -110,6 +110,11 @@ export default tseslint.config( message: 'Use the safe chalk import that handles colors for json output: `import { chalk } from "src/utils/command-helpers.js"`', }, + { + name: '@clack/prompts', + message: + 'Use the wrappers in `src/utils/prompts/index.js`, which handle cancellation and non-interactive input.', + }, ], }, ], diff --git a/package-lock.json b/package-lock.json index 7c779cac4a0..c0ad2ca3a8a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,8 @@ "hasInstallScript": true, "license": "MIT", "dependencies": { + "@clack/prompts": "^1.8.1", "@fastify/static": "^10.0.0", - "@inquirer/prompts": "^8.7.2", "@netlify/ai": "^1.0.2", "@netlify/api": "^15.1.6", "@netlify/blobs": "^11.1.9", @@ -32,7 +32,6 @@ "@netlify/zip-it-and-ship-it": "^16.6.0", "@opentelemetry/api": "~1.9.0", "@pnpm/tabtab": "^0.5.4", - "ansi-escapes": "^7.3.0", "ansi-to-html": "^0.7.2", "ascii-table": "^0.0.9", "backoff": "^2.5.0", @@ -59,7 +58,6 @@ "fastify": "^5.8.5", "find-up": "^8.0.0", "folder-walker": "^3.2.0", - "fuzzy": "^0.1.3", "get-port": "^5.1.1", "git-repo-info": "^2.1.1", "gitconfiglocal": "^2.1.0", @@ -75,7 +73,6 @@ "jwt-decode": "^4.0.0", "lambda-local": "^2.2.0", "locate-path": "^8.0.0", - "log-update": "^8.0.0", "maxstache": "^1.0.7", "maxstache-stream": "^1.0.4", "modern-tar": "^0.8.0", @@ -618,6 +615,34 @@ "integrity": "sha512-ImA35rnM7bGr+J30R979FQ95BhRB4UO1KfJA0J2sVqc8nwnrS9hhE5mkTmQWMs8Vh1Da+hkLKs5jJB4JjNZp4A==", "license": "MIT" }, + "node_modules/@clack/core": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.5.1.tgz", + "integrity": "sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ==", + "license": "MIT", + "dependencies": { + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 20.12.0" + } + }, + "node_modules/@clack/prompts": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.8.1.tgz", + "integrity": "sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==", + "license": "MIT", + "dependencies": { + "@clack/core": "1.5.1", + "fast-string-width": "^3.0.2", + "fast-wrap-ansi": "^0.2.0", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 20.12.0" + } + }, "node_modules/@colors/colors": { "version": "1.6.0", "license": "MIT", @@ -2191,362 +2216,6 @@ "version": "2.0.0", "license": "MIT" }, - "node_modules/@inquirer/ansi": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.9.tgz", - "integrity": "sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==", - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - } - }, - "node_modules/@inquirer/checkbox": { - "version": "5.2.7", - "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.7.tgz", - "integrity": "sha512-/+QmGE/9bvE/EobaZDnzYe+T+QWoJrnmxwBQNtoi2OVSUR9d1znYsNyEoUrOZvFSxDYttrhzRIpXpaLkN+iIsg==", - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/core": "^12.0.5", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/confirm": { - "version": "6.3.4", - "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.3.4.tgz", - "integrity": "sha512-ZwnaZZDa1zxsyVrN32s447ydMnKcw7e8WWNT+R+Qsu0zAn8Rs6yi9d1B80Kob1Ul2cfUi7t8JD2t4/K7uEZpqA==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/core": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.5.tgz", - "integrity": "sha512-c0ZSnO9oVk/IlEGoZK3u8b3IZQeu9I6jUkXJSQnQEVRXsjKvtAq3AGqFL2LgfJhlzMZne08pZHWRWasIcI3Rew==", - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0", - "cli-width": "^4.1.0", - "fast-wrap-ansi": "^0.2.0", - "mute-stream": "^3.0.0", - "signal-exit": "^4.1.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/core/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@inquirer/editor": { - "version": "5.3.5", - "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.3.5.tgz", - "integrity": "sha512-6lU3/pPx5z3lHWejFW061MV4qZooBQYv/+EeGhNOPiP/i+hrYsHfxxBnnDGsAfg8YdLUd69YckoeOjtr3QuAUg==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/external-editor": "^3.0.6", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/expand": { - "version": "5.1.7", - "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.7.tgz", - "integrity": "sha512-eiJ31YFCaB6fLoJCqLIn8S6eqUyME6vwr8KcP5h8cxmA+bV9RRVPO+kywoxb7G63HduDXV6sN/SM7o2R+ahEcQ==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/external-editor": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.6.tgz", - "integrity": "sha512-rWmw6WG8JZ7LMn/srXEylYGhL6EXXJeROE7/4x4GREh6NgzqJBDbIgpNGsYoLPfobeb4VZtEYzPGnT5EFNYhiQ==", - "license": "MIT", - "dependencies": { - "chardet": "^2.1.1", - "iconv-lite": "^0.7.2" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/external-editor/node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/@inquirer/figures": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.9.tgz", - "integrity": "sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==", - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - } - }, - "node_modules/@inquirer/input": { - "version": "5.1.8", - "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.8.tgz", - "integrity": "sha512-psOSTgkL8y/OtgJJYbqJ0oISr2QBE0U1Ro/qQdA/EKjeJiwiUTQgQmq8o4ESNzVOWthIeh3YLD7BCUR9dKnR5g==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/number": { - "version": "4.2.5", - "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.2.5.tgz", - "integrity": "sha512-lEy7LWsdF5qHx5QjHZqabUqM9P7i5uTMCt8GRzqxmwXXKbapKJDA+ucVflVVPAyj4snD5DTAD4L+sct85XOlOQ==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/password": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.2.4.tgz", - "integrity": "sha512-T7ir3fflSSVCYEVqNyMBq+pIMsilQRtbZcD5gxn6Ewsin5TJWBxrGBdXveWtmeXVAeoInfhS+BhBUZaL4sFSDg==", - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/prompts": { - "version": "8.7.4", - "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.7.4.tgz", - "integrity": "sha512-SAJt+QhY5rOJAIgZBw9TrHWfgrp6wsb9cqRCyqax+Hl6EiFfRXmD9EsIWkST8yq/dQ8H46Is2Sr/JG7Ls/LQ+Q==", - "license": "MIT", - "dependencies": { - "@inquirer/checkbox": "^5.2.7", - "@inquirer/confirm": "^6.3.4", - "@inquirer/editor": "^5.3.5", - "@inquirer/expand": "^5.1.7", - "@inquirer/input": "^5.1.8", - "@inquirer/number": "^4.2.5", - "@inquirer/password": "^5.2.4", - "@inquirer/rawlist": "^5.3.7", - "@inquirer/search": "^4.3.5", - "@inquirer/select": "^5.2.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/rawlist": { - "version": "5.3.7", - "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.7.tgz", - "integrity": "sha512-XveEe8v3BHj9ec00n+9i8FHjWhXjS6+jCTizYvXCqKUKtgkrq9xid8S5j3mYGW96qfxG3mwNoud3m3v8GDk9Pw==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/search": { - "version": "4.3.5", - "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.3.5.tgz", - "integrity": "sha512-kIUecMugEN2YTvTmff+uYz0nAE0f9RFNDVZknfrh264vAQM9P8tnsXiUp7z8XbGuNIBEtFMJhvc9QquawpC46A==", - "license": "MIT", - "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/select": { - "version": "5.2.7", - "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.7.tgz", - "integrity": "sha512-pRDWO4dTqSAvFQdO8yclKMtXNDm9K9HmvWB5UZmT3clw2OlOBNXveHzhyFmO/0d0yJMqlPcNITus1Jtpm6t8VQ==", - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/core": "^12.0.5", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/type": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.0.tgz", - "integrity": "sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==", - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "dev": true, @@ -9556,12 +9225,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/chardet": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz", - "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==", - "license": "MIT" - }, "node_modules/cheerio": { "version": "1.1.2", "dev": true, @@ -9678,15 +9341,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-width": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", - "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", - "license": "ISC", - "engines": { - "node": ">= 12" - } - }, "node_modules/clipanion": { "version": "4.0.0-rc.4", "dev": true, @@ -12633,12 +12287,6 @@ "url": "https://github.com/sponsors/krisk" } }, - "node_modules/fuzzy": { - "version": "0.1.3", - "engines": { - "node": ">= 0.6.0" - } - }, "node_modules/generator-function": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", @@ -14917,84 +14565,6 @@ "node": ">=16.17.0" } }, - "node_modules/log-update": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/log-update/-/log-update-8.0.0.tgz", - "integrity": "sha512-lddSgOt3bPASrylL54ZSpy8nBHns+vBVSoILlVOx+dei300pnLRN958rj/EdlVLKuWlSESU3qdnDZdAI7FXYGg==", - "license": "MIT", - "dependencies": { - "ansi-escapes": "^7.3.0", - "cli-cursor": "^5.0.0", - "slice-ansi": "^9.0.0", - "string-width": "^8.2.0", - "strip-ansi": "^7.2.0", - "wrap-ansi": "^10.0.0" - }, - "engines": { - "node": ">=22" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/cli-cursor": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", - "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", - "license": "MIT", - "dependencies": { - "restore-cursor": "^5.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/onetime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", - "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", - "license": "MIT", - "dependencies": { - "mimic-function": "^5.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/restore-cursor": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", - "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", - "license": "MIT", - "dependencies": { - "onetime": "^7.0.0", - "signal-exit": "^4.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/log-update/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/logform": { "version": "2.7.0", "license": "MIT", @@ -15308,16 +14878,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/mimic-function": { - "version": "5.0.1", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/mimic-response": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-4.0.0.tgz", @@ -15435,15 +14995,6 @@ "node": ">= 0.10" } }, - "node_modules/mute-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", - "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/nan": { "version": "2.23.0", "license": "MIT", @@ -18086,6 +17637,12 @@ "is-arrayish": "^0.3.1" } }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, "node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", diff --git a/package.json b/package.json index a82781d84c7..5938bfb5d18 100644 --- a/package.json +++ b/package.json @@ -52,8 +52,8 @@ "typecheck:watch": "node ./node_modules/typescript-native/bin/tsc --watch" }, "dependencies": { + "@clack/prompts": "^1.8.1", "@fastify/static": "^10.0.0", - "@inquirer/prompts": "^8.7.2", "@netlify/ai": "^1.0.2", "@netlify/api": "^15.1.6", "@netlify/blobs": "^11.1.9", @@ -74,7 +74,6 @@ "@netlify/zip-it-and-ship-it": "^16.6.0", "@opentelemetry/api": "~1.9.0", "@pnpm/tabtab": "^0.5.4", - "ansi-escapes": "^7.3.0", "ansi-to-html": "^0.7.2", "ascii-table": "^0.0.9", "backoff": "^2.5.0", @@ -101,7 +100,6 @@ "fastify": "^5.8.5", "find-up": "^8.0.0", "folder-walker": "^3.2.0", - "fuzzy": "^0.1.3", "get-port": "^5.1.1", "git-repo-info": "^2.1.1", "gitconfiglocal": "^2.1.0", @@ -117,7 +115,6 @@ "jwt-decode": "^4.0.0", "lambda-local": "^2.2.0", "locate-path": "^8.0.0", - "log-update": "^8.0.0", "maxstache": "^1.0.7", "maxstache-stream": "^1.0.4", "modern-tar": "^0.8.0", diff --git a/src/commands/agents/agents-create.ts b/src/commands/agents/agents-create.ts index 65ccd845569..182e0ea3f42 100644 --- a/src/commands/agents/agents-create.ts +++ b/src/commands/agents/agents-create.ts @@ -1,7 +1,7 @@ import type { OptionValues } from 'commander' -import { input, select } from '@inquirer/prompts' import { chalk, logAndThrowError, log, logJson } from '../../utils/command-helpers.js' +import { promptSelect, promptText } from '../../utils/prompts/index.js' import { startSpinner, stopSpinner } from '../../lib/spinner.js' import type BaseCommand from '../base-command.js' import type { AgentRunner } from './types.js' @@ -30,9 +30,12 @@ export const agentsCreate = async (promptArg: string, options: AgentCreateOption // Interactive prompt if not provided if (!prompt && !promptArg) { - finalPrompt = await input({ + finalPrompt = await promptText({ message: 'What would you like the agent to do?', - validate: validatePrompt, + validate: (value) => { + const result = validatePrompt(value ?? '') + return typeof result === 'string' ? result : undefined + }, }) } else { finalPrompt = (promptArg || prompt) ?? '' @@ -45,10 +48,10 @@ export const agentsCreate = async (promptArg: string, options: AgentCreateOption // Agent selection if not provided if (!agent) { - agent = await select({ + agent = await promptSelect({ message: 'Which agent would you like to use?', - choices: AVAILABLE_AGENTS, - default: 'claude', + options: AVAILABLE_AGENTS.map(({ name, value }) => ({ value, label: name })), + initialValue: 'claude', }) } else { agent = resolveAgentAlias(agent) @@ -62,15 +65,10 @@ export const agentsCreate = async (promptArg: string, options: AgentCreateOption if (!branch) { const defaultBranch = siteInfo.build_settings?.repo_branch - const branchInput = await input({ + const branchInput = await promptText({ message: 'Which branch would you like to work on?', - default: defaultBranch, - validate: (value: string) => { - if (!value || value.trim().length === 0) { - return 'Branch name is required' - } - return true - }, + defaultValue: defaultBranch, + validate: (value) => (value?.trim() ? undefined : 'Branch name is required'), }) branch = branchInput.trim() diff --git a/src/commands/base-command.ts b/src/commands/base-command.ts index c2294613d13..3fed13c7a49 100644 --- a/src/commands/base-command.ts +++ b/src/commands/base-command.ts @@ -9,7 +9,6 @@ import { NodeFS, NoopLogger } from '@netlify/build-info/node' import { resolveConfig } from '@netlify/config' import { getGlobalConfigStore, LocalState } from '@netlify/dev-utils' import { isCI } from 'ci-info' -import { search } from '@inquirer/prompts' import { Command, CommanderError, Help, Option, type OptionValues } from 'commander' import debug from 'debug' import { findUp } from 'find-up' @@ -36,7 +35,6 @@ import { logError, } from '../utils/command-helpers.js' import { handleOptionError, isOptionError } from '../utils/command-error-handler.js' -import { EXIT_CODES } from '../utils/exit-codes.js' import type { FeatureFlags } from '../utils/feature-flags.js' import { getFrameworksAPIPaths } from '../utils/frameworks-api.js' import { getSiteByName } from '../utils/get-site.js' @@ -44,6 +42,7 @@ import { showAgentSkillsRefreshNotice, startAgentSkillsRefresh } from '../utils/ import { getLocalApiTestOpts } from '../utils/local-api-test-opts.js' import { buildAuthorizeUrl } from '../utils/login-url.js' import openBrowser from '../utils/open-browser.js' +import { promptAutocomplete } from '../utils/prompts/index.js' import { isInteractive } from '../utils/scripted-commands.js' import { identify, reportError, setCommandForErrorReporting, track } from '../utils/telemetry/index.js' import type { NetlifyOptions } from './types.js' @@ -170,17 +169,13 @@ async function selectWorkspace(project: Project, filter?: string): Promise - (project.workspace?.packages || []) - .filter((pkg) => pkg.path.includes(input)) - .map((pkg) => ({ - name: `${pkg.name ? `${chalk.bold(pkg.name)} ` : ''}${pkg.path} ${chalk.dim( - `--filter ${pkg.name || pkg.path}`, - )}`, - value: pkg.path, - })), + options: (project.workspace?.packages || []).map((pkg) => ({ + value: pkg.path, + label: pkg.name ? `${chalk.bold(pkg.name)} ${pkg.path}` : pkg.path, + hint: `--filter ${pkg.name || pkg.path}`, + })), }) } return selected.path @@ -499,11 +494,6 @@ export default class BaseCommand extends Command { ) } - // Inquirer prompts reject with this on Ctrl+C, but the error class isn't exported. - if (error_ instanceof Error && error_.name === 'ExitPromptError') { - return exit(EXIT_CODES.INTERRUPTED) - } - if (error_ !== undefined) { logError(error_ instanceof Error ? error_ : format(error_)) exit(1) diff --git a/src/commands/clone/clone.ts b/src/commands/clone/clone.ts index 7d104a65145..3478673fcf9 100644 --- a/src/commands/clone/clone.ts +++ b/src/commands/clone/clone.ts @@ -1,10 +1,10 @@ import { resolve } from 'path' import { LocalState } from '@netlify/dev-utils' -import { input } from '@inquirer/prompts' import { normalizeRepoUrl } from '../../utils/normalize-repo-url.js' import { chalk, logAndThrowError, log, getToken, netlifyCommand, type APIError } from '../../utils/command-helpers.js' +import { promptText } from '../../utils/prompts/index.js' import { runGit } from '../../utils/run-git.js' import execa from '../../utils/execa.js' import type BaseCommand from '../base-command.js' @@ -14,12 +14,11 @@ import type { CloneOptionValues } from './option_values.js' import { startSpinner } from '../../lib/spinner.js' import type { SiteInfo } from '../../utils/types.js' -const getTargetDir = async (defaultDir: string): Promise => { - return await input({ +const getTargetDir = async (defaultDir: string): Promise => + promptText({ message: 'Where should we clone the repository?', - default: defaultDir, + defaultValue: defaultDir, }) -} const cloneRepo = async (repoUrl: string, targetDir: string, debug: boolean): Promise => { try { diff --git a/src/commands/completion/completion.ts b/src/commands/completion/completion.ts index 6579a2e1e75..97a16464238 100644 --- a/src/commands/completion/completion.ts +++ b/src/commands/completion/completion.ts @@ -2,7 +2,6 @@ import fs from 'fs' import { homedir } from 'os' import { dirname, join } from 'path' import { fileURLToPath } from 'url' -import { confirm } from '@inquirer/prompts' import type { OptionValues } from 'commander' import { install, uninstall } from '@pnpm/tabtab' @@ -16,6 +15,7 @@ import { TABTAB_CONFIG_LINE, AUTOLOAD_COMPINIT, } from '../../utils/command-helpers.js' +import { promptConfirm } from '../../utils/prompts/index.js' import type BaseCommand from '../base-command.js' const completer = join(dirname(fileURLToPath(import.meta.url)), '../../lib/completion/script.js') @@ -56,10 +56,7 @@ export const completionGenerate = async (_options: OptionValues, command: BaseCo ) { log(`To enable Tabtab autocompletion with zsh, the following line may need to be added to your ~/.zshrc:`) log(chalk.bold.cyan(`\n${AUTOLOAD_COMPINIT}\n`)) - const compinitAdded = await confirm({ - message: `Would you like to add it?`, - default: true, - }) + const compinitAdded = await promptConfirm({ message: `Would you like to add it?` }) if (compinitAdded) { const zshConfig = fs.readFileSync(zshConfigFilepath, 'utf8') fs.writeFileSync(zshConfigFilepath, `${AUTOLOAD_COMPINIT}\n${zshConfig}`, 'utf8') diff --git a/src/commands/create/create-action.ts b/src/commands/create/create-action.ts index 90fe5b1d67f..f8afe167a75 100644 --- a/src/commands/create/create-action.ts +++ b/src/commands/create/create-action.ts @@ -10,7 +10,6 @@ import { promisify } from 'util' import type { OptionValues } from 'commander' import fetch from 'node-fetch' -import { select } from '@inquirer/prompts' import type { NetlifyAPI } from '@netlify/api' import { LocalState } from '@netlify/dev-utils' @@ -18,6 +17,7 @@ import { chalk, logAndThrowError, log, logJson, warn, type APIError } from '../. import { ensureNetlifyIgnore } from '../../utils/gitignore.js' import { getGitHubToken as promptForGitHubToken } from '../../utils/gh-auth.js' import { requestGitHub, type GitHubUser } from '../../utils/github-api.js' +import { promptSelect } from '../../utils/prompts/index.js' import { startSpinner, stopSpinner } from '../../lib/spinner.js' import { isInteractive } from '../../utils/scripted-commands.js' import { track } from '../../utils/telemetry/index.js' @@ -150,14 +150,14 @@ const selectRepoOwner = async (ghToken: string, repoOwnerFlag?: string): Promise return user.login } - const choices = [ - { name: `${user.login} (personal)`, value: user.login }, - ...orgs.map((org) => ({ name: org.login, value: org.login })), + const options = [ + { value: user.login, label: `${user.login} (personal)` }, + ...orgs.map((org) => ({ value: org.login, label: org.login })), ] - return await select({ + return await promptSelect({ message: 'Where should the GitHub repo be created?', - choices, + options, }) } @@ -277,12 +277,9 @@ export const createAction = async (promptArg: string, options: CreateOptions, co if (accountSlugFlag) { accountSlug = accountSlugFlag } else if (accounts.length > 1) { - accountSlug = await select({ - message: 'Team:', - choices: accounts.map((account) => ({ - value: account.slug, - name: account.name, - })), + accountSlug = await promptSelect({ + message: 'Team', + options: accounts.map((account) => ({ value: account.slug, label: account.name })), }) } else { accountSlug = accounts[0]?.slug diff --git a/src/commands/database/db-init.ts b/src/commands/database/db-init.ts index d129a99f201..76f792ed32c 100644 --- a/src/commands/database/db-init.ts +++ b/src/commands/database/db-init.ts @@ -3,10 +3,10 @@ import { mkdir, readdir, writeFile } from 'fs/promises' import { join } from 'path' import { applyMigrations } from '@netlify/dev' -import { confirm, select } from '@inquirer/prompts' import { chalk, log, netlifyCommand } from '../../utils/command-helpers.js' import { startSpinner, stopSpinner } from '../../lib/spinner.js' +import { promptConfirm, promptSelect } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import BaseCommand from '../base-command.js' import { generateNextPrefix } from './db-migration-new.js' @@ -67,7 +67,7 @@ const carefullyWriteFile = async ( const displayPath = `.${filePath.replace(projectRoot, '')}` const overwrite = onExisting === 'ask' - ? await confirm({ message: `Overwrite existing file ${displayPath}?` }) + ? await promptConfirm({ message: `Overwrite existing file ${displayPath}?` }) : onExisting === 'overwrite' if (overwrite) { await writeFile(filePath, data) @@ -91,12 +91,12 @@ const promptForQueryStyle = async (interactive: boolean): Promise => } log('') - return await select({ + return await promptSelect({ message: 'What is your preferred style?', - default: 'drizzle', - choices: [ - { name: 'Drizzle ORM (recommended)', value: 'drizzle' }, - { name: 'Direct SQL', value: 'raw' }, + initialValue: 'drizzle', + options: [ + { value: 'drizzle', label: 'Drizzle ORM (recommended)' }, + { value: 'raw', label: 'Direct SQL' }, ], }) } @@ -111,9 +111,9 @@ const promptForStarter = async (interactive: boolean): Promise => { log('and then query it. Alternatively, you can do this yourself at any time.') log('') - return await confirm({ + return await promptConfirm({ message: 'Do you want to create sample data?', - default: true, + initialValue: true, }) } diff --git a/src/commands/database/db-migration-new.ts b/src/commands/database/db-migration-new.ts index 4bb752e0d2e..bdc19941c3e 100644 --- a/src/commands/database/db-migration-new.ts +++ b/src/commands/database/db-migration-new.ts @@ -1,9 +1,8 @@ import { readdir, mkdir, writeFile } from 'fs/promises' import { join } from 'path' -import { input, select } from '@inquirer/prompts' - import { log, logJson } from '../../utils/command-helpers.js' +import { promptSelect, promptText } from '../../utils/prompts/index.js' import BaseCommand from '../base-command.js' import { resolveMigrationsDirectory } from './util/migrations-path.js' import { utcTimestampPrefix } from './util/timestamp.js' @@ -91,9 +90,9 @@ export const migrationNew = async (options: MigrationNewOptions, command: BaseCo if (!description) { if (isInteractive()) { - description = await input({ + description = await promptText({ message: 'What is the purpose of this migration?', - validate: (value: string) => (value.trim().length > 0 ? true : 'Description cannot be empty'), + validate: (input) => (input?.trim() ? undefined : 'Description cannot be empty'), }) } else { throw new Error( @@ -106,13 +105,13 @@ export const migrationNew = async (options: MigrationNewOptions, command: BaseCo const defaultScheme = detectedScheme ?? 'timestamp' if (isInteractive()) { - scheme = await select({ - message: 'Numbering scheme:', - choices: [ - { name: 'Timestamp (e.g. 20260312143000) [Recommended]', value: 'timestamp' }, - { name: 'Sequential (e.g. 0001, 0002, ...)', value: 'sequential' }, + scheme = await promptSelect({ + message: 'Numbering scheme', + options: [ + { value: 'timestamp', label: 'Timestamp (e.g. 20260312143000) [Recommended]' }, + { value: 'sequential', label: 'Sequential (e.g. 0001, 0002, ...)' }, ], - default: defaultScheme, + initialValue: defaultScheme, }) } else { scheme = defaultScheme diff --git a/src/commands/database/db-migration-pull.ts b/src/commands/database/db-migration-pull.ts index 39ee31ca220..3a773201b05 100644 --- a/src/commands/database/db-migration-pull.ts +++ b/src/commands/database/db-migration-pull.ts @@ -1,10 +1,9 @@ import { rm, mkdir, writeFile } from 'fs/promises' import { dirname, resolve, isAbsolute } from 'path' -import { confirm } from '@inquirer/prompts' - import { log, logJson } from '../../utils/command-helpers.js' import execa from '../../utils/execa.js' +import { promptConfirm } from '../../utils/prompts/index.js' import BaseCommand from '../base-command.js' import { readApiErrorMessage } from './util/api-errors.js' import { PRODUCTION_BRANCH } from './util/constants.js' @@ -148,11 +147,11 @@ export const migrationPull = async (options: MigrationPullOptions, command: Base }) if (!force) { - const confirmed = await confirm({ + const confirmed = await promptConfirm({ message: `This will overwrite all local migrations in ${migrationsDirectory} with ${String( migrations.length, )} migration${migrations.length === 1 ? '' : 's'} from ${branch}. Continue?`, - default: false, + initialValue: false, }) if (!confirmed) { diff --git a/src/commands/database/db-reset.ts b/src/commands/database/db-reset.ts index 48fdab60972..805db05409d 100644 --- a/src/commands/database/db-reset.ts +++ b/src/commands/database/db-reset.ts @@ -1,10 +1,9 @@ import { rm } from 'fs/promises' -import { confirm } from '@inquirer/prompts' - import { resetDatabase } from '@netlify/dev' import { log, logJson } from '../../utils/command-helpers.js' +import { promptConfirm } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import BaseCommand from '../base-command.js' import { connectToDatabase, LocalDatabaseStartError } from './util/db-connection.js' @@ -25,9 +24,9 @@ const discardLocalDatabase = async (error: LocalDatabaseStartError, options: Res log(error.summary) - const confirmed = await confirm({ + const confirmed = await promptConfirm({ message: `Delete ${directory} and start from an empty database?`, - default: false, + initialValue: false, }) if (!confirmed) { diff --git a/src/commands/deploy/deploy.ts b/src/commands/deploy/deploy.ts index 3b1973f38f8..34f8fcf35e1 100644 --- a/src/commands/deploy/deploy.ts +++ b/src/commands/deploy/deploy.ts @@ -4,7 +4,6 @@ import { stat } from 'fs/promises' import { basename, resolve } from 'path' import { stdin, stdout } from 'process' -import { confirm, input, select } from '@inquirer/prompts' import type { NetlifyAPI } from '@netlify/api' import { type NetlifyConfig, type OnPostBuild, runCoreSteps } from '@netlify/build' import { parseAllHeaders } from '@netlify/headers-parser' @@ -53,6 +52,7 @@ import { import { getFeatureFlagsFromSiteInfo } from '../../utils/feature-flags.js' import { isEmpty } from '../../utils/object-utilities.js' import openBrowser from '../../utils/open-browser.js' +import { promptConfirm, promptSelect, promptText } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import { resolveTeamForNonInteractive } from '../../utils/team.js' import { @@ -170,9 +170,9 @@ const getDeployFolder = async ({ log(`\nTo specify directory non-interactively, use: ${copyableCommand}\n`) - const promptPath = await input({ + const promptPath = await promptText({ message: 'Publish directory', - default: '.', + defaultValue: '.', }) deployFolder = resolve(command.workingDir, promptPath) } @@ -401,9 +401,9 @@ const prepareProductionDeploy = async ({ log(` ${overrideCommand}`) log('\nWarning: Only use --prod-if-unlocked if you are absolutely sure you want to override the deployment lock.\n') - const unlockChoice = await confirm({ + const unlockChoice = await promptConfirm({ message: 'Would you like to "unlock" deployments for production context to proceed?', - default: false, + initialValue: false, }) if (!unlockChoice) exit(0) await api.unlockDeploy({ deploy_id: siteData.published_deploy.id }) @@ -1155,17 +1155,11 @@ const promptForSiteAction = async (options: DeployOptionValues, command: BaseCom log(`\nYou must pick a --team: ${availableTeams.map((team) => team.slug).join(', ')}`) } - const initChoice = await select({ + const initChoice = await promptSelect({ message: 'What would you like to do?', - choices: [ - { - name: '⇄ Link this directory to an existing project', - value: 'link', - }, - { - name: '+ Create & configure a new project', - value: 'create', - }, + options: [ + { value: 'link', label: '⇄ Link this directory to an existing project' }, + { value: 'create', label: '+ Create & configure a new project' }, ], }) diff --git a/src/commands/deploy/remote-deploy.ts b/src/commands/deploy/remote-deploy.ts index 04f2dc5e088..5a0641103ef 100644 --- a/src/commands/deploy/remote-deploy.ts +++ b/src/commands/deploy/remote-deploy.ts @@ -1,4 +1,3 @@ -import { confirm } from '@inquirer/prompts' import type { NetlifyAPI } from '@netlify/api' import { TimeoutError } from 'p-wait-for' import terminalLink from 'terminal-link' @@ -18,6 +17,7 @@ import { } from './remote/source.js' import { followDeploy } from './remote/follow.js' import { DeployStateError } from '../../utils/deploy/util.js' +import { promptConfirm } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import type { SiteInfo } from '../../utils/types.js' import type { DeployOptionValues } from './option_values.js' @@ -113,7 +113,7 @@ export const remoteDeploy = async ({ if (source.untracked.length !== 0) { warn(describeUntracked(source.untracked, shortSha, source.repoUrl)) - if (isInteractive() && !quiet && !(await confirm({ message: 'Deploy anyway?', default: true }))) { + if (isInteractive() && !quiet && !(await promptConfirm({ message: 'Deploy anyway?', initialValue: true }))) { exit(0) } } diff --git a/src/commands/env/env-list.ts b/src/commands/env/env-list.ts index 58ea9a83520..9abc13bf72c 100644 --- a/src/commands/env/env-list.ts +++ b/src/commands/env/env-list.ts @@ -1,12 +1,10 @@ -import ansiEscapes from 'ansi-escapes' import AsciiTable from 'ascii-table' import { isCI } from 'ci-info' import type { OptionValues } from 'commander' -import { confirm } from '@inquirer/prompts' -import logUpdate from 'log-update' import { chalk, log, logJson } from '../../utils/command-helpers.js' import { SUPPORTED_CONTEXTS, getEnvelopeEnv, getHumanReadableScopes } from '../../utils/env/index.js' +import { promptConfirm } from '../../utils/prompts/index.js' import type BaseCommand from '../base-command.js' import { EnvironmentVariables } from '../../utils/types.js' import { getSiteInfo } from './utils.js' @@ -100,16 +98,10 @@ export const envList = async (options: OptionValues, command: BaseCommand) => { return false } - logUpdate(getTable({ environment, hideValues: true, scopesColumn: true })) - const showValues = await confirm({ - message: 'Show values?', - default: false, - }) + log(getTable({ environment, hideValues: true, scopesColumn: true })) + const showValues = await promptConfirm({ message: 'Show values?', initialValue: false }) if (showValues) { - // since inquirer adds a prompt, we need to account for it when printing the table again - log(ansiEscapes.eraseLines(3)) - logUpdate(getTable({ environment, hideValues: false, scopesColumn: true })) - log(`${chalk.cyan('?')} Show values? ${chalk.cyan('Yes')}`) + log(getTable({ environment, hideValues: false, scopesColumn: true })) } } diff --git a/src/commands/functions/functions-create.ts b/src/commands/functions/functions-create.ts index 6375bc61d48..08076910c8e 100644 --- a/src/commands/functions/functions-create.ts +++ b/src/commands/functions/functions-create.ts @@ -6,10 +6,8 @@ import path, { dirname, join, relative } from 'path' import process from 'process' import { fileURLToPath, pathToFileURL } from 'url' -import { input, search, select, Separator } from '@inquirer/prompts' import { OptionValues } from 'commander' import { findUp } from 'find-up' -import fuzzy from 'fuzzy' import fetch from 'node-fetch' import { createSpinner } from 'nanospinner' @@ -25,6 +23,7 @@ import { import { copyTemplateDir } from '../../utils/copy-template-dir/copy-template-dir.js' import { getDotEnvVariables, injectEnvVariables } from '../../utils/dev.js' import execa from '../../utils/execa.js' +import { promptAutocomplete, promptSelect, promptText } from '../../utils/prompts/index.js' import { readRepoURL, validateRepoURL } from '../../utils/read-repo-url.js' import BaseCommand from '../base-command.js' @@ -37,8 +36,8 @@ const templatesDir = path.resolve(dirname(fileURLToPath(import.meta.url)), '../. * each `value` property in this list. */ const languages = [ - { name: 'JavaScript', value: 'javascript' }, - { name: 'TypeScript', value: 'typescript' }, + { label: 'JavaScript', value: 'javascript' }, + { label: 'TypeScript', value: 'typescript' }, ] const MOON_SPINNER = { @@ -80,45 +79,22 @@ const getNameFromArgs = async function (argumentName, options, defaultName) { return argumentName } - return await input({ - message: 'Name your function:', - default: defaultName, - // this has some nuance i have ignored, eg crossenv and i18n concerns - validate: (val) => isValidFunctionName(val), + return await promptText({ + message: 'Name your function', + defaultValue: defaultName, + validate: (value) => + isValidFunctionName(value) + ? undefined + : 'Function names must only contain letters, numbers, hyphens, underscores, or dots.', }) } -// @ts-expect-error TS(7006) FIXME: Parameter 'registry' implicitly has an 'any' type. -const filterRegistry = function (registry, input) { - // @ts-expect-error TS(7006) FIXME: Parameter 'value' implicitly has an 'any' type. - const temp = registry.map((value) => value.name + value.description) - const filteredTemplates = fuzzy.filter(input, temp) - const filteredTemplateNames = new Set( - filteredTemplates.map((filteredTemplate) => (input ? filteredTemplate.string : filteredTemplate)), - ) - return ( - registry - // @ts-expect-error TS(7006) FIXME: Parameter 't' implicitly has an 'any' type. - .filter((t) => filteredTemplateNames.has(t.name + t.description)) - // @ts-expect-error TS(7006) FIXME: Parameter 't' implicitly has an 'any' type. - .map((t) => { - // add the score - // @ts-expect-error TS(2339) FIXME: Property 'score' does not exist on type 'FilterRes... Remove this comment to see the full error message - const { score } = filteredTemplates.find( - (filteredTemplate) => filteredTemplate.string === t.name + t.description, - ) - t.score = score - return t - }) - ) -} - /** * @param {string} lang * @param {'edge' | 'serverless'} funcType */ // @ts-expect-error TS(7006) FIXME: Parameter 'lang' implicitly has an 'any' type. -const formatRegistryArrayForInquirer = async function (lang, funcType) { +const formatTemplateOptions = async function (lang, funcType) { const folders = await readdir(path.join(templatesDir, lang), { withFileTypes: true }) const imports = await Promise.all( @@ -131,7 +107,7 @@ const formatRegistryArrayForInquirer = async function (lang, funcType) { const template = await import(pathToFileURL(templatePath)) return template.default } catch { - // noop if import fails we don't break the whole inquirer + // A broken template shouldn't break the whole prompt. } }), ) @@ -149,10 +125,8 @@ const formatRegistryArrayForInquirer = async function (lang, funcType) { .map((t) => { t.lang = lang return { - // confusing but this is the format inquirer wants - name: `[${t.name}] ${t.description}`, + label: `[${t.name}] ${t.description}`, value: t, - short: `${lang}-${t.name}`, } }) return registry @@ -166,18 +140,16 @@ const formatRegistryArrayForInquirer = async function (lang, funcType) { // @ts-expect-error TS(7031) FIXME: Binding element 'languageFromFlag' implicitly has ... Remove this comment to see the full error message const pickTemplate = async function ({ language: languageFromFlag, template: templateFromFlag }, funcType) { const specialCommands = [ - new Separator(), { - name: `Clone template from GitHub URL`, + label: 'Clone template from GitHub URL', value: 'url', - short: 'gh-url', + hint: 'prompts for a URL', }, { - name: `Report issue with, or suggest a new template`, + label: 'Report issue with, or suggest a new template', value: 'report', - short: 'gh-report', + hint: 'github.com/netlify/cli/issues', }, - new Separator(), ] let language = languageFromFlag @@ -188,16 +160,16 @@ const pickTemplate = async function ({ language: languageFromFlag, template: tem ? languages.filter((lang) => lang.value === 'javascript' || lang.value === 'typescript') : languages.filter(Boolean) - language = await select({ - choices: langs, + language = await promptSelect({ message: 'Select the language of your function', + options: langs, }) } let templatesForLanguage try { - templatesForLanguage = await formatRegistryArrayForInquirer(language, funcType) + templatesForLanguage = await formatTemplateOptions(language, funcType) } catch { return logAndThrowError(`Invalid language: ${language}`) } @@ -214,41 +186,25 @@ const pickTemplate = async function ({ language: languageFromFlag, template: tem return match.value } - const chosenTemplate = await search({ + const parsedSpecialCommands = + funcType === 'edge' ? specialCommands.filter((cmd) => cmd.value !== 'url') : specialCommands + + return await promptAutocomplete({ message: 'Pick a template', - source(input: string | undefined) { - // if Edge Functions template, don't show url option - // @ts-expect-error TS(2339) FIXME: Property 'value' does not exist on type 'Separator... Remove this comment to see the full error message - const edgeCommands = specialCommands.filter((val) => val.value !== 'url') - const parsedSpecialCommands = funcType === 'edge' ? edgeCommands : specialCommands - - if (!input || input === '') { - // show separators - return [...templatesForLanguage, ...parsedSpecialCommands] - } - // only show filtered results sorted by score - const answers = [...filterRegistry(templatesForLanguage, input), ...parsedSpecialCommands].sort( - (answerA, answerB) => answerB.score - answerA.score, - ) - return answers - }, + options: [...templatesForLanguage, ...parsedSpecialCommands], }) - return chosenTemplate } const DEFAULT_PRIORITY = 999 -const selectTypeOfFunc = async (): Promise<'edge' | 'serverless'> => { - const functionTypes = [ - { name: 'Edge function (Deno)', value: 'edge' as const }, - { name: 'Serverless function (Node)', value: 'serverless' as const }, - ] - - return await select({ +const selectTypeOfFunc = async (): Promise<'edge' | 'serverless'> => + promptSelect<'edge' | 'serverless'>({ message: "Select the type of function you'd like to create", - choices: functionTypes, + options: [ + { label: 'Edge function (Deno)', value: 'edge' }, + { label: 'Serverless function (Node)', value: 'serverless' }, + ], }) -} /** * @param {import('../base-command.js').default} command @@ -298,9 +254,9 @@ const promptFunctionsDirectory = async (command) => { ) } - const functionsDir = await input({ - message: 'Enter the path, relative to your project, where your functions should live:', - default: 'netlify/functions', + const functionsDir = await promptText({ + message: 'Enter the path, relative to your project, where your functions should live', + defaultValue: 'netlify/functions', }) try { @@ -484,9 +440,9 @@ const scaffoldFromTemplate = async function (command, options, argumentName, fun // pull the rest of the metadata from the template const chosenTemplate = await pickTemplate(options, funcType) if (chosenTemplate === 'url') { - const chosenUrl = await input({ - message: 'URL to clone: ', - validate: (val) => Boolean(validateRepoURL(val)), + const chosenUrl = await promptText({ + message: 'URL to clone', + validate: (value) => (validateRepoURL(value ?? '') ? undefined : 'Enter a GitHub repository URL'), }) options.url = chosenUrl.trim() try { @@ -586,11 +542,10 @@ const registerEFInToml = async (funcName, options) => { log(`${NETLIFYDEVLOG} \`${relConfigFilePath}\` file does not exist yet. Creating it...`) } - let funcPath = await input({ - message: `What route do you want your edge function to be invoked on?`, - default: '/test', - // Todo: add more validation? - validate: (val) => Boolean(val), + let funcPath = await promptText({ + message: 'What route do you want your edge function to be invoked on?', + defaultValue: '/test', + validate: (value) => (value ? undefined : 'Enter a route'), }) // Make sure path begins with a '/' diff --git a/src/commands/functions/functions-invoke.ts b/src/commands/functions/functions-invoke.ts index 1449d0c88d0..8160c31fdfd 100644 --- a/src/commands/functions/functions-invoke.ts +++ b/src/commands/functions/functions-invoke.ts @@ -2,12 +2,12 @@ import fs from 'fs' import { createRequire } from 'module' import path from 'path' -import { select } from '@inquirer/prompts' import { OptionValues } from 'commander' import fetch from 'node-fetch' import { APIError, NETLIFYDEVWARN, chalk, logAndThrowError, exit } from '../../utils/command-helpers.js' import { BACKGROUND, CLOCKWORK_USERAGENT, getFunctions } from '../../utils/functions/index.js' +import { promptSelect } from '../../utils/prompts/index.js' import BaseCommand from '../base-command.js' const require = createRequire(import.meta.url) @@ -95,10 +95,12 @@ const processPayloadFromFlag = function (payloadString, workingDir) { * @param {string} [argumentName] The name that might be provided as argument (optional argument) * @returns {Promise} */ -// @ts-expect-error TS(7006) FIXME: Parameter 'functions' implicitly has an 'any' type... Remove this comment to see the full error message -const getNameFromArgs = async function (functions, options, argumentName) { +const getNameFromArgs = async function ( + functions: { name: string }[], + options: OptionValues, + argumentName?: string, +): Promise { const functionToTrigger = getFunctionToTrigger(options, argumentName) - // @ts-expect-error TS(7031) FIXME: Binding element 'name' implicitly has an 'any' typ... Remove this comment to see the full error message const functionNames = functions.map(({ name }) => name) if (functionToTrigger) { @@ -113,9 +115,9 @@ const getNameFromArgs = async function (functions, options, argumentName) { ) } - return await select({ + return await promptSelect({ message: 'Pick a function to trigger', - choices: functionNames, + options: functionNames.map((name) => ({ value: name })), }) } @@ -125,15 +127,14 @@ const getNameFromArgs = async function (functions, options, argumentName) { * @param {string} [argumentName] The name that might be provided as argument (optional argument) * @returns {string} */ -// @ts-expect-error TS(7006) FIXME: Parameter 'options' implicitly has an 'any' type. -const getFunctionToTrigger = function (options, argumentName) { +const getFunctionToTrigger = function (options: OptionValues, argumentName?: string): string | undefined { if (options.name) { if (argumentName) { console.error('function name specified in both flag and arg format, pick one') exit(1) } - return options.name + return options.name as string } return argumentName diff --git a/src/commands/init/init.ts b/src/commands/init/init.ts index 22aa199758a..55729f0191b 100644 --- a/src/commands/init/init.ts +++ b/src/commands/init/init.ts @@ -1,11 +1,11 @@ import { OptionValues } from 'commander' -import { confirm, select } from '@inquirer/prompts' import { isEmpty } from '../../utils/object-utilities.js' import { type APIError, chalk, exit, log, logAndThrowError, netlifyCommand, warn } from '../../utils/command-helpers.js' import getRepoData, { type RepoData, type RepoDataError } from '../../utils/get-repo-data.js' import { ensureNetlifyIgnore } from '../../utils/gitignore.js' import { configureRepo } from '../../utils/init/config.js' +import { promptConfirm, promptSelect } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import { track } from '../../utils/telemetry/index.js' import type BaseCommand from '../base-command.js' @@ -196,7 +196,7 @@ const createNewSiteAndExit = async ({ persistState({ state, siteInfo }) if (!disableLinking) { - const shouldConfigureBuild = await confirm({ + const shouldConfigureBuild = await promptConfirm({ message: `Do you want to configure build settings? We'll suggest settings for your project automatically`, }) if (shouldConfigureBuild) { @@ -287,9 +287,9 @@ git remote add origin https://github.com/YourUserName/RepoName.git const NEW_SITE_NO_GIT = 'Yes, create and deploy project manually' const NO_ABORT = 'No, I will connect this directory with GitHub first' - const noGitRemoteChoice = await select({ + const noGitRemoteChoice = await promptSelect({ message: 'Do you want to create a Netlify project without a git repository?', - choices: [NEW_SITE_NO_GIT, NO_ABORT], + options: [{ value: NEW_SITE_NO_GIT }, { value: NO_ABORT }], }) if (noGitRemoteChoice === NEW_SITE_NO_GIT) { @@ -306,11 +306,9 @@ const createOrLinkSiteToRepo = async (command: BaseCommand) => { const NEW_SITE = '+ Create & configure a new project' const EXISTING_SITE = '⇄ Connect this directory to an existing Netlify project' - const initializeOpts = [EXISTING_SITE, NEW_SITE] as const - - const initChoice = await select({ + const initChoice = await promptSelect({ message: 'What would you like to do?', - choices: initializeOpts, + options: [{ value: EXISTING_SITE }, { value: NEW_SITE }], }) // create site or search for one diff --git a/src/commands/link/link.ts b/src/commands/link/link.ts index d97173dfd63..3dcfef35e98 100644 --- a/src/commands/link/link.ts +++ b/src/commands/link/link.ts @@ -1,6 +1,5 @@ import assert from 'node:assert' -import { input, select } from '@inquirer/prompts' import { isEmpty } from '../../utils/object-utilities.js' import type { NetlifyAPI } from '@netlify/api' @@ -10,6 +9,7 @@ import { chalk, logAndThrowError, exit, log, APIError, netlifyCommand } from '.. import { ensureNetlifyIgnore } from '../../utils/gitignore.js' import getRepoData from '../../utils/get-repo-data.js' import { matchesRepoUrl } from '../../utils/match-repo-url.js' +import { promptSelect, promptText } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import { track } from '../../utils/telemetry/index.js' import type { SiteInfo } from '../../utils/types.js' @@ -73,19 +73,14 @@ ${matchingSites .join('\n')}`) } - const selectedSite = await select({ + return promptSelect({ message: 'Which project do you want to link?', - choices: matchingSites.map((matchingSite) => ({ - name: `${matchingSite.name} - ${matchingSite.ssl_url}`, + options: matchingSites.map((matchingSite) => ({ value: matchingSite, + label: matchingSite.name, + hint: matchingSite.ssl_url, })), }) - - if (!selectedSite) { - return logAndThrowError('No project selected') - } - - return selectedSite } const linkPrompt = async (command: BaseCommand, options: LinkOptionValues): Promise => { @@ -111,9 +106,9 @@ const linkPrompt = async (command: BaseCommand, options: LinkOptionValues): Prom log() log(`${chalk.cyanBright(`${netlifyCommand()} link`)} will connect this folder to a project on Netlify`) log() - const linkType = await select({ + const linkType = await promptSelect({ message: 'How do you want to link this folder to a project?', - choices: linkChoices, + options: linkChoices.map((choice) => ({ value: choice })), }) let kind @@ -128,9 +123,7 @@ const linkPrompt = async (command: BaseCommand, options: LinkOptionValues): Prom } case SITE_NAME_PROMPT: { kind = 'byName' - const searchTerm = await input({ - message: 'Enter the project name (or just part of it):', - }) + const searchTerm = await promptText({ message: 'Enter the project name (or just part of it):' }) log(`Looking for projects with names containing '${searchTerm}'...`) log() @@ -163,14 +156,10 @@ To create a new project: if (matchingSites.length > 1) { log(`Found ${matchingSites.length} matching projects!`) - const selectedSite = await select({ + site = await promptSelect({ message: 'Which project do you want to link?', - choices: matchingSites.map((matchingSite) => ({ name: matchingSite.name, value: matchingSite })), + options: matchingSites.map((matchingSite) => ({ value: matchingSite, label: matchingSite.name })), }) - if (!selectedSite) { - return logAndThrowError('No project selected') - } - site = selectedSite } else { const [firstSite] = matchingSites site = firstSite @@ -197,21 +186,15 @@ To create a new project: ) } - const selectedSite = await select({ + site = await promptSelect({ message: 'Which project do you want to link?', - choices: sites.map((matchingSite) => ({ name: matchingSite.name, value: matchingSite })), + options: sites.map((matchingSite) => ({ value: matchingSite, label: matchingSite.name })), }) - if (!selectedSite) { - return logAndThrowError('No project selected') - } - site = selectedSite break } case SITE_ID_PROMPT: { kind = 'bySiteId' - const siteId = await input({ - message: 'What is the project ID?', - }) + const siteId = await promptText({ message: 'What is the project ID?' }) try { site = await api.getSite({ siteId }) diff --git a/src/commands/logs/build.ts b/src/commands/logs/build.ts index cc277b7e738..8f69e659ccd 100644 --- a/src/commands/logs/build.ts +++ b/src/commands/logs/build.ts @@ -1,7 +1,7 @@ import type { OptionValues } from 'commander' -import { select } from '@inquirer/prompts' import { log, chalk } from '../../utils/command-helpers.js' +import { promptSelect } from '../../utils/prompts/index.js' import { getWebSocket } from '../../utils/websockets/index.js' import { SOCKETEER_URL } from '../../utils/socketeer.js' import type BaseCommand from '../base-command.js' @@ -54,11 +54,11 @@ export const logsBuild = async (_options: OptionValues, command: BaseCommand) => let [deploy] = deploys if (deploys.length > 1) { - const result = await select({ + const result = await promptSelect({ message: `Select a deploy\n\n${chalk.yellow('*')} indicates a deploy created by you`, - choices: deploys.map((dep: any) => ({ - name: getName({ deploy: dep, userId }), + options: deploys.map((dep: any) => ({ value: dep.id, + label: getName({ deploy: dep, userId }), })), }) diff --git a/src/commands/main.ts b/src/commands/main.ts index 2dee95c0396..4236b859f89 100644 --- a/src/commands/main.ts +++ b/src/commands/main.ts @@ -3,7 +3,6 @@ import process from 'process' import { Option, CommanderError } from 'commander' import envinfo from 'envinfo' import { closest } from 'fastest-levenshtein' -import { confirm } from '@inquirer/prompts' import { getGlobalConfigStore } from '@netlify/dev-utils' @@ -22,6 +21,7 @@ import { EXIT_CODES } from '../utils/exit-codes.js' import getCLIPackageJson from '../utils/get-cli-package-json.js' import { didEnableCompileCache } from '../utils/nodejs-compile-cache.js' import { handleOptionError, isOptionError } from '../utils/command-error-handler.js' +import { promptConfirm } from '../utils/prompts/index.js' import { isInteractive } from '../utils/scripted-commands.js' import { track, reportError } from '../utils/telemetry/index.js' @@ -217,17 +217,11 @@ const mainCommand = async function (options, command) { exit(EXIT_CODES.USAGE_ERROR) } - let applySuggestion = false - try { - applySuggestion = await confirm( - { message: `Did you mean ${chalk.blue(suggestion)}`, default: false }, - { signal: AbortSignal.timeout(SUGGESTION_TIMEOUT) }, - ) - } catch (error) { - if (!(error instanceof Error && error.name === 'AbortPromptError')) { - throw error - } - } + const applySuggestion = await promptConfirm({ + message: `Did you mean ${chalk.blue(suggestion)}?`, + initialValue: false, + timeout: SUGGESTION_TIMEOUT, + }) // create new log line log() @@ -296,7 +290,7 @@ export const createMainCommand = (): BaseCommand => { return `To get started run: ${NETLIFY_CYAN('netlify login')} To ask a human for credentials: ${NETLIFY_CYAN('netlify login --request ')} -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit ${NETLIFY_CYAN( terminalLink(cliDocsEntrypointUrl, cliDocsEntrypointUrl, { fallback: false }), diff --git a/src/commands/recipes/recipes.ts b/src/commands/recipes/recipes.ts index 1b67ade007f..16ab158cf24 100644 --- a/src/commands/recipes/recipes.ts +++ b/src/commands/recipes/recipes.ts @@ -2,10 +2,10 @@ import { basename } from 'path' import { OptionValues } from 'commander' import { closest } from 'fastest-levenshtein' -import { confirm } from '@inquirer/prompts' import { chalk, exit, logError } from '../../utils/command-helpers.js' import { EXIT_CODES } from '../../utils/exit-codes.js' +import { promptConfirm } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import BaseCommand from '../base-command.js' @@ -58,14 +58,10 @@ export const recipesCommand = async (recipeName: string, options: OptionValues, logError(didYouMean) return exit(EXIT_CODES.USAGE_ERROR) } - const applySuggestion = await confirm( - { message: didYouMean, default: false }, - { signal: AbortSignal.timeout(SUGGESTION_TIMEOUT) }, - ).catch((error: unknown) => { - if (error instanceof Error && error.name === 'AbortPromptError') { - return false - } - throw error + const applySuggestion = await promptConfirm({ + message: didYouMean, + initialValue: false, + timeout: SUGGESTION_TIMEOUT, }) if (applySuggestion) { diff --git a/src/commands/sites/sites-create.ts b/src/commands/sites/sites-create.ts index d61b293d5a7..5132dc1cb44 100644 --- a/src/commands/sites/sites-create.ts +++ b/src/commands/sites/sites-create.ts @@ -1,11 +1,11 @@ import type { OptionValues } from 'commander' -import { input, select } from '@inquirer/prompts' import { pick } from '../../utils/object-utilities.js' import prettyjson from 'prettyjson' import { chalk, logAndThrowError, log, logJson, warn, type APIError } from '../../utils/command-helpers.js' import getRepoData from '../../utils/get-repo-data.js' import { configureRepo } from '../../utils/init/config.js' +import { promptSelect, promptText } from '../../utils/prompts/index.js' import { isInteractive } from '../../utils/scripted-commands.js' import { requireTeams, resolveTeamForNonInteractive } from '../../utils/team.js' import { track } from '../../utils/telemetry/index.js' @@ -16,10 +16,10 @@ import { link } from '../link/link.js' export const getSiteNameInput = async (name: string | undefined): Promise<{ name: string }> => { if (!name) { - name = await input({ - message: 'Project name (leave blank for a random name; you can change it later):', + name = await promptText({ + message: 'Project name (leave blank for a random name; you can change it later)', validate: (value) => - !value || /^[a-zA-Z\d-]+$/.test(value) || 'Only alphanumeric characters and hyphens are allowed', + !value || /^[a-zA-Z\d-]+$/.test(value) ? undefined : 'Only alphanumeric characters and hyphens are allowed', }) } @@ -42,11 +42,11 @@ export const sitesCreate = async (options: OptionValues, command: BaseCommand) = log(`Using team: ${team.name}`) } else { const teams = requireTeams(accounts) - accountSlug = await select({ - message: 'Team:', - choices: teams.map((account) => ({ + accountSlug = await promptSelect({ + message: 'Team', + options: teams.map((account) => ({ value: account.slug, - name: account.name, + label: account.name, })), }) } diff --git a/src/commands/sites/sites-delete.ts b/src/commands/sites/sites-delete.ts index a98b36fc761..09da1ca5d07 100644 --- a/src/commands/sites/sites-delete.ts +++ b/src/commands/sites/sites-delete.ts @@ -1,7 +1,7 @@ import type { OptionValues } from 'commander' -import { confirm } from '@inquirer/prompts' import { chalk, logAndThrowError, exit, log, type APIError } from '../../utils/command-helpers.js' +import { promptConfirm } from '../../utils/prompts/index.js' import type BaseCommand from '../base-command.js' export const sitesDelete = async (siteId: string, options: OptionValues, command: BaseCommand) => { @@ -34,9 +34,9 @@ export const sitesDelete = async (siteId: string, options: OptionValues, command log() log(chalk.bold('Be careful here. There is no undo!')) log() - const wantsToDelete = await confirm({ + const wantsToDelete = await promptConfirm({ message: `WARNING: Are you sure you want to delete the "${siteData.name}" project?`, - default: false, + initialValue: false, }) log() if (!wantsToDelete) { @@ -55,9 +55,9 @@ export const sitesDelete = async (siteId: string, options: OptionValues, command log() log(`Verify this project ID "${siteId}" supplied is correct and proceed.`) log('To skip this prompt, pass a --force flag to the delete command') - const wantsToDelete = await confirm({ + const wantsToDelete = await promptConfirm({ message: `Verify & Proceed with deletion of project "${siteId}"?`, - default: false, + initialValue: false, }) if (!wantsToDelete) { exit() diff --git a/src/commands/switch/switch.ts b/src/commands/switch/switch.ts index 563bddb0f33..5919f17f34c 100644 --- a/src/commands/switch/switch.ts +++ b/src/commands/switch/switch.ts @@ -1,7 +1,7 @@ import { OptionValues } from 'commander' -import { select } from '@inquirer/prompts' import { chalk, log } from '../../utils/command-helpers.js' +import { promptSelect } from '../../utils/prompts/index.js' import BaseCommand from '../base-command.js' import { login } from '../login/login.js' @@ -30,9 +30,9 @@ export const switchCommand = async (options: OptionValues, command: BaseCommand) log('') } - const accountSwitchChoice = await select({ - message: 'Please select the account you want to use:', - choices: [...Object.entries(availableUsersChoices).map(([, val]) => val), LOGIN_NEW], + const accountSwitchChoice = await promptSelect({ + message: 'Please select the account you want to use', + options: [...Object.entries(availableUsersChoices).map(([, val]) => ({ value: val })), { value: LOGIN_NEW }], }) if (accountSwitchChoice === LOGIN_NEW) { diff --git a/src/lib/edge-functions/editor-helper.ts b/src/lib/edge-functions/editor-helper.ts index 45c676965b4..21a21fb5e60 100644 --- a/src/lib/edge-functions/editor-helper.ts +++ b/src/lib/edge-functions/editor-helper.ts @@ -1,8 +1,7 @@ import { env, stdin, stdout } from 'process' -import { confirm } from '@inquirer/prompts' - import { runRecipe } from '../../commands/recipes/recipes.js' +import { promptConfirm } from '../../utils/prompts/index.js' const STATE_PROMPT_PROPERTY = 'promptVSCodeSettings' @@ -25,12 +24,9 @@ export const promptEditorHelper = async ({ NETLIFYDEVLOG, chalk, config, log, re state.set(STATE_PROMPT_PROPERTY, true) const message = 'Would you like to configure VS Code to use Edge Functions?' - const confirmed = await confirm({ - message, - default: true, - }) + const confirm = await promptConfirm({ message }) - if (!confirmed) { + if (!confirm) { log( `${NETLIFYDEVLOG} You can start this configuration manually by running ${chalk.magenta.bold( 'netlify recipes vscode', diff --git a/src/lib/secure-storage.ts b/src/lib/secure-storage.ts index ac9e7e20e44..5e1709b3626 100644 --- a/src/lib/secure-storage.ts +++ b/src/lib/secure-storage.ts @@ -1,4 +1,3 @@ -import { confirm } from '@inquirer/prompts' import { getGlobalConfigStore, getLegacyConfigFilePath, @@ -9,8 +8,9 @@ import { } from '@netlify/dev-utils' import { chalk, isLogSuppressed, log, warn } from '../utils/command-helpers.js' +import { promptConfirm } from '../utils/prompts/index.js' import { isInteractive } from '../utils/scripted-commands.js' -import { reportError, track } from '../utils/telemetry/index.js' +import { track } from '../utils/telemetry/index.js' export type TokenStorageMode = 'keychain' | 'legacy' @@ -41,8 +41,6 @@ export const skipKeychainMigrationPrompt = (): void => { const canUseKeychainInteractively = (env: NodeJS.ProcessEnv): boolean => isInteractive() || env.TESTING_PROMPTS === 'true' -const isPromptExit = (error: unknown): boolean => error instanceof Error && error.name === 'ExitPromptError' - const attemptMigration = async (token: string, env: NodeJS.ProcessEnv): Promise => { if ( isLegacyAuthStorageForced(env) || @@ -64,15 +62,7 @@ const attemptMigration = async (token: string, env: NodeJS.ProcessEnv): Promise< `The CLI can move it to your operating system's keychain, which is more secure. You may be asked to allow access.`, ) log() - let confirmed: boolean - try { - confirmed = await confirm({ message: 'Move the token to the keychain now?', default: true }) - } catch (error) { - if (isPromptExit(error)) throw error - void reportError(error, { severity: 'error' }) - return false - } - + const confirmed = await promptConfirm({ message: 'Move the token to the keychain now?', initialValue: true }) if (!confirmed) { globalConfig.set(skipMigrationKey(userId), true) log( diff --git a/src/recipes/ai-context/index.ts b/src/recipes/ai-context/index.ts index 7580d3932bc..cecc8589831 100644 --- a/src/recipes/ai-context/index.ts +++ b/src/recipes/ai-context/index.ts @@ -1,10 +1,10 @@ import { resolve } from 'node:path' -import { input, select } from '@inquirer/prompts' import execa from 'execa' import type { RunRecipeOptions } from '../../commands/recipes/recipes.js' import { logAndThrowError, log, version } from '../../utils/command-helpers.js' +import { promptSelect, promptText } from '../../utils/prompts/index.js' import { track } from '../../utils/telemetry/index.js' import { @@ -34,17 +34,17 @@ const rulesForDefaultConsumer = allContextConsumers.find((consumer) => consumer. } const presets = cliContextConsumers.map((consumer) => ({ - name: consumer.presentedName, value: consumer.key, + label: consumer.presentedName, })) // always add the custom location option (not preset from API) -presets.push({ name: 'Custom location', value: rulesForDefaultConsumer.key }) +presets.push({ value: rulesForDefaultConsumer.key, label: 'Custom location' }) const promptForContextConsumerSelection = async (): Promise => { - const consumerKey = await select({ + const consumerKey = await promptSelect({ message: 'Where should we put the context files?', - choices: presets, + options: presets, }) const contextConsumer = consumerKey ? cliContextConsumers.find((consumer) => consumer.key === consumerKey) : null @@ -52,9 +52,9 @@ const promptForContextConsumerSelection = async (): Promise => { return contextConsumer } - const customPath = await input({ + const customPath = await promptText({ message: 'Enter the path, relative to the project root, where the context files should be placed', - default: './ai-context', + defaultValue: './ai-context', }) if (customPath) { diff --git a/src/recipes/blobs-migrate/index.ts b/src/recipes/blobs-migrate/index.ts index 8490ad3de2a..baf8d95a595 100644 --- a/src/recipes/blobs-migrate/index.ts +++ b/src/recipes/blobs-migrate/index.ts @@ -1,9 +1,9 @@ import { getStore, listStores } from '@netlify/blobs' -import { confirm } from '@inquirer/prompts' import pMap from 'p-map' import BaseCommand from '../../commands/base-command.js' import { logAndThrowError, log } from '../../utils/command-helpers.js' +import { promptConfirm } from '../../utils/prompts/index.js' export const description = 'Migrate legacy Netlify Blobs stores' @@ -48,9 +48,9 @@ export const run = async ({ args, command }: Options) => { const { stores } = await listStores(clientOptions) if (stores.includes(storeName)) { - const confirmExistingStore = await confirm({ + const confirmExistingStore = await promptConfirm({ message: `The store '${storeName}' already exists in the new format, which means it has already been migrated or it has been used with a newer version of the Netlify Blobs client. If you continue with the migration, any blobs from the legacy store will overwrite newer entries that have the same key. Do you want to proceed?`, - default: false, + initialValue: false, }) if (!confirmExistingStore) { @@ -58,9 +58,8 @@ export const run = async ({ args, command }: Options) => { } } - const confirmMigration = await confirm({ + const confirmMigration = await promptConfirm({ message: `You're about to migrate the store '${storeName}' with ${blobs.length} blobs. Do you want to proceed?`, - default: true, }) if (!confirmMigration) { diff --git a/src/recipes/vscode/index.ts b/src/recipes/vscode/index.ts index bb8095388c1..6450272d89a 100644 --- a/src/recipes/vscode/index.ts +++ b/src/recipes/vscode/index.ts @@ -2,9 +2,9 @@ import { join } from 'path' import { DenoBridge } from '@netlify/edge-bundler' import execa from 'execa' -import { confirm } from '@inquirer/prompts' import { NETLIFYDEVLOG, NETLIFYDEVWARN, chalk, logAndThrowError, log } from '../../utils/command-helpers.js' +import { promptConfirm } from '../../utils/prompts/index.js' import { applySettings, getSettings, writeSettings } from './settings.js' @@ -17,10 +17,7 @@ const getPrompt = ({ fileExists, path }) => { ? `There is a VS Code settings file at ${formattedPath}. Can we update it?` : `A new VS Code settings file will be created at ${formattedPath}` - return confirm({ - message, - default: true, - }) + return promptConfirm({ message }) } // @ts-expect-error TS(7031) FIXME: Binding element 'config' implicitly has an 'any' t... Remove this comment to see the full error message @@ -53,10 +50,7 @@ const getDenoVSCodeExt = async (repositoryRoot) => { const getDenoExtPrompt = () => { const message = 'The Deno VS Code extension is recommended. Would you like to install it now?' - return confirm({ - message, - default: true, - }) + return promptConfirm({ message }) } /** @@ -77,9 +71,9 @@ export const run = async ({ config, repositoryRoot }) => { const edgeFunctionsPath = getEdgeFunctionsPath({ config, repositoryRoot }) const { fileExists, settings: existingSettings } = await getSettings(settingsPath) const settings = applySettings(existingSettings, { denoBinary, edgeFunctionsPath, repositoryRoot }) - const confirmed = await getPrompt({ fileExists, path: settingsPath }) + const confirm = await getPrompt({ fileExists, path: settingsPath }) - if (!confirmed) { + if (!confirm) { return } diff --git a/src/utils/build-info.ts b/src/utils/build-info.ts index ac10355b940..5eb25735297 100644 --- a/src/utils/build-info.ts +++ b/src/utils/build-info.ts @@ -1,38 +1,17 @@ import type { Settings } from '@netlify/build-info' -import { search } from '@inquirer/prompts' import { isCI } from 'ci-info' -import fuzzy from 'fuzzy' import type BaseCommand from '../commands/base-command.js' import { chalk, log } from './command-helpers.js' +import { promptAutocomplete } from './prompts/index.js' import type { DefaultConfig } from '../lib/build.js' -/** - * Filters the inquirer settings based on the input - */ -const filterSettings = function ( - scriptInquirerOptions: ReturnType, - input: string, -) { - const filterOptions = scriptInquirerOptions.map((scriptInquirerOption) => scriptInquirerOption.name) - // TODO: remove once https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1394 is fixed - const filteredSettings = fuzzy.filter(input, filterOptions) - const filteredSettingNames = new Set( - filteredSettings.map((filteredSetting) => (input ? filteredSetting.string : filteredSetting)), - ) - return scriptInquirerOptions.filter((t) => filteredSettingNames.has(t.name)) -} - -/** - * Formats the settings to present it as an array for the inquirer input so that it can choose one - */ -const formatSettingsArrForInquirer = function (settings: Settings[], type = 'dev') { +const formatSettingsOptions = function (settings: Settings[], type = 'dev') { return settings.map((setting) => { const cmd = type === 'dev' ? setting.devCommand : setting.buildCommand return { - name: `[${chalk.yellow(setting.framework.name)}] '${cmd}'`, + label: `[${chalk.yellow(setting.framework.name)}] '${cmd}'`, value: { ...setting, commands: [cmd] }, - short: `${setting.name}-${cmd}`, } }) } @@ -95,14 +74,9 @@ export const detectFrameworkSettings = async ( } // multiple matching detectors, make the user choose - const scriptInquirerOptions = formatSettingsArrForInquirer(settings, type) - const chosenSettings = await search({ + const chosenSettings = await promptAutocomplete({ message: `Multiple possible ${type} commands found`, - source(input = '') { - if (!input) return scriptInquirerOptions - // only show filtered results - return filterSettings(scriptInquirerOptions, input) - }, + options: formatSettingsOptions(settings, type), }) log(` diff --git a/src/utils/dev.ts b/src/utils/dev.ts index 7cd816f4d09..acdc90199c6 100644 --- a/src/utils/dev.ts +++ b/src/utils/dev.ts @@ -239,12 +239,4 @@ export const acquirePort = async ({ return acquiredPort } -// @ts-expect-error TS(7006) FIXME: Parameter 'fn' implicitly has an 'any' type. -export const processOnExit = (fn) => { - const signals = ['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGHUP', 'exit'] - signals.forEach((signal) => { - process.on(signal, fn) - }) -} - export const UNLINKED_SITE_MOCK_ID = 'unlinked' diff --git a/src/utils/exit-codes.ts b/src/utils/exit-codes.ts index 19c440b868f..bd297421809 100644 --- a/src/utils/exit-codes.ts +++ b/src/utils/exit-codes.ts @@ -20,7 +20,7 @@ export const EXIT_CODES = { USAGE_ERROR: 2, /** An interactive prompt was required but the session is non-interactive (CI or `--non-interactive`) */ NON_INTERACTIVE_PROMPT: 4, - /** The user cancelled an interactive prompt with Ctrl+C, matching a SIGINT-terminated process */ + /** The user cancelled an interactive prompt (Ctrl+C / Esc), matching a SIGINT-terminated process */ INTERRUPTED: 130, } as const diff --git a/src/utils/gh-auth.ts b/src/utils/gh-auth.ts index 03ceee127dc..5d5a0ace001 100644 --- a/src/utils/gh-auth.ts +++ b/src/utils/gh-auth.ts @@ -2,13 +2,13 @@ import http from 'http' import process from 'process' -import { password, select } from '@inquirer/prompts' import getPort from 'get-port' import { log } from './command-helpers.js' import createDeferred from './create-deferred.js' import { requestGitHub, type GitHubUser } from './github-api.js' import openBrowser from './open-browser.js' +import { promptPassword, promptSelect } from './prompts/index.js' const SERVER_PORT = 3000 @@ -23,11 +23,11 @@ const promptForAuthMethod = async () => { const authChoiceToken = 'Authorize with a GitHub personal access token' const authChoices = [authChoiceNetlify, authChoiceToken] as const - const authMethod = await select({ + const authMethod = await promptSelect({ message: 'Netlify CLI needs access to your GitHub account to configure Webhooks and Deploy Keys. ' + 'What would you like to do?', - choices: authChoices, + options: authChoices.map((value) => ({ value })), }) return authMethod === authChoiceNetlify @@ -79,7 +79,7 @@ export const authWithNetlify = async (): Promise => { } const getPersonalAccessToken = async (): Promise<{ token: string }> => { - const token = await password({ message: 'Your GitHub personal access token:' }) + const token = await promptPassword({ message: 'Your GitHub personal access token' }) return { token: token.trim() } } diff --git a/src/utils/init/agent-mcp.ts b/src/utils/init/agent-mcp.ts index 89d5a086f03..9aebd71d15e 100644 --- a/src/utils/init/agent-mcp.ts +++ b/src/utils/init/agent-mcp.ts @@ -2,12 +2,12 @@ import { promises as fs } from 'node:fs' import { homedir } from 'node:os' import path from 'node:path' -import { checkbox } from '@inquirer/prompts' import { isexe } from 'isexe' import { type CanonicalAgentName, getDrivingAgent } from '../agent-detection.js' import { chalk, log, netlifyCommand, warn } from '../command-helpers.js' import execa from '../execa.js' +import { promptMultiselect } from '../prompts/index.js' import { isInteractive } from '../scripted-commands.js' import { type ProjectConfigFile, addToProjectConfig, readProjectConfig } from './agent-mcp-config.js' @@ -212,9 +212,11 @@ const where = (scope: McpScope): string => (scope === 'project' ? 'this project' const chooseWithPrompt = (scope: McpScope): ChooseAgents => async (candidates) => - await checkbox({ + await promptMultiselect({ message: `Add the Netlify MCP server for ${where(scope)} to which AI agents?`, - choices: candidates.map(({ agent, detected }) => ({ name: agent.label, value: agent, checked: detected })), + options: candidates.map(({ agent }) => ({ label: agent.label, value: agent })), + initialValues: candidates.filter(({ detected }) => detected).map(({ agent }) => agent), + required: false, }) const pathExists = async (target: string): Promise => { @@ -735,9 +737,6 @@ export const setupAgentMcp = async ({ } log(`Your choices are saved for this project. ${resetHint()}`) } catch (error) { - if (error instanceof Error && error.name === 'ExitPromptError') { - throw error - } warn(`Could not set up the Netlify MCP server: ${error instanceof Error ? error.message : String(error)}`) summary.failed = true } diff --git a/src/utils/init/config-manual.ts b/src/utils/init/config-manual.ts index c6432b01726..0f09e901f98 100644 --- a/src/utils/init/config-manual.ts +++ b/src/utils/init/config-manual.ts @@ -1,6 +1,5 @@ -import { confirm, input } from '@inquirer/prompts' - import { exit, log } from '../command-helpers.js' +import { promptConfirm, promptText } from '../prompts/index.js' import type BaseCommand from '../../commands/base-command.js' import type { RepoData } from '../get-repo-data.js' @@ -15,27 +14,26 @@ const addDeployKey = async (deployKey: DeployKey) => { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions log(`\n${deployKey.public_key}\n\n`) - const sshKeyAdded = await confirm({ message: 'Continue?', default: true }) + const sshKeyAdded = await promptConfirm({ message: 'Continue?' }) if (!sshKeyAdded) { return exit() } } -const getRepoPath = async ({ repoData }: { repoData: RepoData }): Promise => { - return await input({ +const getRepoPath = async ({ repoData }: { repoData: RepoData }): Promise => + promptText({ message: 'The SSH URL of the remote git repo:', - default: repoData.url, - validate: (url: string) => (SSH_URL_REGEXP.test(url) ? true : 'The URL provided does not use the SSH protocol'), + defaultValue: repoData.url, + validate: (url) => (SSH_URL_REGEXP.test(url ?? '') ? undefined : 'The URL provided does not use the SSH protocol'), }) -} const addDeployHook = async (deployHook: string | undefined): Promise => { log('\nConfigure the following webhook for your repository:\n') // FIXME(serhalp): Handle nullish `deployHook` by throwing user-facing error or fixing upstream type. // eslint-disable-next-line @typescript-eslint/restrict-template-expressions log(`\n${deployHook}\n\n`) - return await confirm({ message: 'Continue?', default: true }) + return promptConfirm({ message: 'Continue?' }) } const isSupportedProvider = (provider: string | null): provider is 'github' | 'gitlab' => diff --git a/src/utils/init/utils.ts b/src/utils/init/utils.ts index 7145112ae80..795ffe13ede 100644 --- a/src/utils/init/utils.ts +++ b/src/utils/init/utils.ts @@ -4,13 +4,13 @@ import path from 'path' import type { NetlifyAPI } from '@netlify/api' import type { Settings } from '@netlify/build-info' import cleanDeep from 'clean-deep' -import { confirm, input } from '@inquirer/prompts' import type BaseCommand from '../../commands/base-command.js' import { fileExistsAsync } from '../../lib/fs.js' import { normalizeBackslash } from '../../lib/path.js' import { detectBuildSettings } from '../build-info.js' import { chalk, logAndThrowError, log, type NormalizedCachedConfigConfig, warn } from '../command-helpers.js' +import { promptConfirm, promptText } from '../prompts/index.js' import type { Plugin } from '../types.js' import { getRecommendPlugins, getUIPlugins } from './plugins.js' @@ -62,6 +62,34 @@ const normalizeSettings = (settings: Partial, config: NormalizedCached } } +const promptBuildSettings = async ({ + defaultBaseDir, + defaultBuildCmd, + defaultBuildDir, +}: { + defaultBaseDir: string + defaultBuildCmd?: string | undefined + defaultBuildDir?: string | undefined +}) => { + const baseDir = + defaultBaseDir === '' + ? undefined + : await promptText({ + message: 'Base directory (blank for current dir):', + defaultValue: defaultBaseDir, + }) + const buildCmd = await promptText({ + message: 'Your build command (hugo build/yarn run build/etc):', + defaultValue: defaultBuildCmd, + }) + const buildDir = await promptText({ + message: 'Directory to deploy (blank for current dir):', + defaultValue: defaultBuildDir, + }) + + return { baseDir, buildCmd: buildCmd === '' ? '# no build command' : buildCmd, buildDir } +} + export const getBuildSettings = async ({ command, config, @@ -86,16 +114,11 @@ export const getBuildSettings = async ({ log() } - const baseDir = - defaultBaseDir === '' - ? undefined - : await input({ message: 'Base directory (blank for current dir):', default: defaultBaseDir }) - const buildCmdInput = await input({ - message: 'Your build command (hugo build/yarn run build/etc):', - default: defaultBuildCmd, + const { baseDir, buildCmd, buildDir } = await promptBuildSettings({ + defaultBaseDir, + defaultBuildCmd, + defaultBuildDir, }) - const buildCmd = buildCmdInput === '' ? '# no build command' : buildCmdInput - const buildDir = await input({ message: 'Directory to deploy (blank for current dir):', default: defaultBuildDir }) const pluginsToInstall = recommendedPlugins.map((plugin) => ({ package: plugin })) const normalizedBaseDir = baseDir ? normalizeBackslash(baseDir) : undefined @@ -163,9 +186,8 @@ export const saveNetlifyToml = async ({ return } - const makeNetlifyTOML = await confirm({ + const makeNetlifyTOML = await promptConfirm({ message: 'No netlify.toml detected. Would you like to create one with these build settings?', - default: true, }) if (makeNetlifyTOML) { try { diff --git a/src/utils/prompts/confirm-prompt.ts b/src/utils/prompts/confirm-prompt.ts index 88ffcb96e3f..7a5cde4a0ec 100644 --- a/src/utils/prompts/confirm-prompt.ts +++ b/src/utils/prompts/confirm-prompt.ts @@ -1,11 +1,11 @@ -import { confirm } from '@inquirer/prompts' - import { log, exit } from '../command-helpers.js' +import { promptConfirm } from './index.js' + export const confirmPrompt = async (message: string): Promise => { - const confirmed = await confirm({ message, default: false }) + const confirm = await promptConfirm({ message, initialValue: false }) log() - if (!confirmed) { + if (!confirm) { exit() } } diff --git a/src/utils/prompts/index.ts b/src/utils/prompts/index.ts new file mode 100644 index 00000000000..11540a96dc7 --- /dev/null +++ b/src/utils/prompts/index.ts @@ -0,0 +1,112 @@ +import process from 'process' +import { stripVTControlCharacters } from 'util' + +// eslint-disable-next-line no-restricted-imports -- this module is the wrapper everything else uses +import * as clack from '@clack/prompts' + +import { EXIT_CODES } from '../exit-codes.js' +import { exitAfterCleanup } from '../shell.js' + +type Cancellable = T | typeof clack.CANCEL_SYMBOL +type Prompt = (signal: AbortSignal) => Promise> +type TextValidator = Extract, (...args: never[]) => unknown> + +// Node stops reading a piped stdin only on a `pause` event, and `pause()` emits none once the prompt has +// left the stream paused, so the still-reading handle would keep the process alive. +const releaseStdin = (): void => { + process.stdin.emit('pause') +} + +// clack submits only on readline's `return` key (CR); a pipe or here-doc sends LF, which readline names `enter`. +const treatLineFeedAsEnter = (_char: string | undefined, key: { name?: string } | undefined): void => { + if (key?.name === 'enter') { + key.name = 'return' + } +} + +const cancelAndExit = async (): Promise => { + clack.cancel('Cancelled.') + return exitAfterCleanup(EXIT_CODES.INTERRUPTED) +} + +const ask = async (prompt: Prompt, timeout?: { after: number; answer: T }): Promise => { + const controller = new AbortController() + + const timer = + timeout && + setTimeout(() => { + controller.abort() + }, timeout.after) + + const piped = !process.stdin.isTTY + if (piped) { + process.stdin.prependListener('keypress', treatLineFeedAsEnter) + } + + let value: Cancellable + try { + value = await prompt(controller.signal) + } finally { + // clack never removes its abort listener, so a late abort would close the settled prompt again and + // reset the terminal under whatever runs next. + clearTimeout(timer) + if (piped) { + process.stdin.removeListener('keypress', treatLineFeedAsEnter) + releaseStdin() + } + } + + if (!clack.isCancel(value)) return value + if (timeout && controller.signal.aborted) return timeout.answer + return cancelAndExit() +} + +const withDefaultValue = (options: clack.TextOptions): clack.TextOptions => { + const { defaultValue, validate } = options + if (defaultValue === undefined) { + return options + } + // clack's text prompt never displays `defaultValue`; it only applies it on submit. + const shown = { placeholder: defaultValue, ...options } + if (typeof validate !== 'function') { + return shown + } + // clack validates the raw input before falling back to `defaultValue`, so a validator requiring a value + // would otherwise reject accepting the default. + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- clack submits an empty answer as '' + const validateWithDefault: TextValidator = (value) => validate(value || defaultValue) + return { ...shown, validate: validateWithDefault } +} + +export const promptText = (options: clack.TextOptions): Promise => + ask((signal) => clack.text({ ...withDefaultValue(options), signal })) + +export const promptPassword = (options: clack.PasswordOptions): Promise => + ask((signal) => clack.password({ ...options, signal })) + +export type ConfirmOptions = Omit & { + /** Treat the prompt as declined when it goes unanswered for this many milliseconds. */ + timeout?: number +} + +export const promptConfirm = ({ timeout, ...options }: ConfirmOptions): Promise => + ask( + (signal) => clack.confirm({ ...options, signal }), + timeout === undefined ? undefined : { after: timeout, answer: false }, + ) + +export const promptMultiselect = (options: clack.MultiSelectOptions): Promise => + ask((signal) => clack.multiselect({ ...options, signal })) + +export const promptSelect = (options: clack.SelectOptions): Promise => + ask((signal) => clack.select({ ...options, signal })) + +// clack's default filter also matches `String(value)`, so every object option matches "[object Object]", +// and it matches the label with its ANSI styling, so a query spanning a colour change never matches. +const matchesLabelOrHint = (search: string, option: clack.Option): boolean => + stripVTControlCharacters(`${option.label ?? String(option.value)} ${option.hint ?? ''}`) + .toLowerCase() + .includes(search.toLowerCase()) + +export const promptAutocomplete = (options: clack.AutocompleteOptions): Promise => + ask((signal) => clack.autocomplete({ filter: matchesLabelOrHint, ...options, signal })) diff --git a/src/utils/shell.ts b/src/utils/shell.ts index 0be071980d7..93bbdf755f0 100644 --- a/src/utils/shell.ts +++ b/src/utils/shell.ts @@ -6,8 +6,7 @@ import execa from 'execa' import { type Spinner } from '../lib/spinner.js' -import { chalk, log, NETLIFYDEVERR, NETLIFYDEVWARN } from './command-helpers.js' -import { processOnExit } from './dev.js' +import { chalk, exit, log, NETLIFYDEVERR, NETLIFYDEVWARN } from './command-helpers.js' const isErrnoException = (value: unknown): value is NodeJS.ErrnoException => value instanceof Error && Object.hasOwn(value, 'code') @@ -86,12 +85,24 @@ const cleanupBeforeExit = async ({ exitCode }: { exitCode?: number | undefined } const ensureCleanupOnExit = () => { if (!cleanupRegistered) { cleanupRegistered = true - processOnExit(async () => { - await cleanupBeforeExit({}) - }) + for (const signal of ['SIGINT', 'SIGTERM', 'SIGQUIT', 'SIGHUP', 'exit']) { + process.on(signal, () => { + void cleanupBeforeExit({}) + }) + } } } +/** + * Runs the work registered with `runBeforeProcessExit`, then exits with `exitCode`. + * `process.exit` would abandon that work, such as stopping a dev server. + */ +export const exitAfterCleanup = async (exitCode: number): Promise => { + await cleanupBeforeExit({ exitCode }) + // Reached only when cleanup is already running elsewhere; exiting here cuts it short. + return exit(exitCode) +} + /** * Registers a cleanup function to run before the process exits. The process * will call `process.exit()` after all registered cleanup functions complete. diff --git a/tests/integration/__snapshots__/framework-detection.test.ts.snap b/tests/integration/__snapshots__/framework-detection.test.ts.snap index 70f0fc2c2db..0cfc27040f4 100644 --- a/tests/integration/__snapshots__/framework-detection.test.ts.snap +++ b/tests/integration/__snapshots__/framework-detection.test.ts.snap @@ -86,30 +86,20 @@ exports[`frameworks/framework-detection > should print specific error when comma `; exports[`frameworks/framework-detection > should prompt when multiple frameworks are detected 1`] = ` -"? Multiple possible dev commands found - -↑↓ navigate • ⏎ select? Multiple possible dev commands found -> [Gatsby] 'npm run develop' - [Create React App] 'npm run start' - -↑↓ navigate • ⏎ select? Multiple possible dev commands found -> [Gatsby] 'npm run develop' - [Create React App] 'npm run start' - -↑↓ navigate • ⏎ select? Multiple possible dev commands found - [Gatsby] 'npm run develop' -> [Create React App] 'npm run start' - -↑↓ navigate • ⏎ select? Multiple possible dev commands found - [Gatsby] 'npm run develop' -> [Create React App] 'npm run start' - -↑↓ navigate • ⏎ select? Multiple possible dev commands found - [Gatsby] 'npm run develop' -> [Create React App] 'npm run start' - -↑↓ navigate • ⏎ select√ Multiple possible dev commands found Create React App-npm run start -[?25h +"[?25l│ +◆ Multiple possible dev commands found +│ +│ Search: _ +│ ● [Gatsby] 'npm run develop' +│ ○ [Create React App] 'npm run start' +│ ↑/↓ to select • Enter: confirm • Type: to search +└│ Search: +│ ○ [Gatsby] 'npm run develop' +│ ● [Create React App] 'npm run start' +│ ↑/↓ to select • Enter: confirm • Type: to search +└◇ Multiple possible dev commands found +│ [Create React App] 'npm run start' +[?25h Update your netlify.toml to avoid this selection prompt next time: [build] diff --git a/tests/integration/auth-token-storage.test.ts b/tests/integration/auth-token-storage.test.ts index 683f29adfc9..9efc51b0301 100644 --- a/tests/integration/auth-token-storage.test.ts +++ b/tests/integration/auth-token-storage.test.ts @@ -276,7 +276,7 @@ describe('migration prompt interactive flow', () => { timeout: 60_000, }) - handleQuestions(childProcess, [{ question: 'Move the token to the keychain', answer: NO + CONFIRM }]) + handleQuestions(childProcess, [{ question: 'Move the token to the keychain', answer: NO }]) await childProcess diff --git a/tests/integration/commands/blobs/blobs-delete.test.ts b/tests/integration/commands/blobs/blobs-delete.test.ts index a320d28e529..2752eae3c96 100644 --- a/tests/integration/commands/blobs/blobs-delete.test.ts +++ b/tests/integration/commands/blobs/blobs-delete.test.ts @@ -16,9 +16,7 @@ import { setTestingPrompts, } from '../../utils/mock-api.js' import { runMockProgram } from '../../utils/mock-program.js' -import { mockConfirm, spyOnConfirm } from '../../utils/inquirer-mock-prompt.js' - -vi.mock('@inquirer/prompts') +import { mockConfirmPrompt, spyOnConfirmPrompt } from '../../utils/mock-prompts.js' const siteInfo = { account_slug: 'test-account', @@ -30,6 +28,12 @@ const siteInfo = { functions_config: { timeout: 1 }, } +// vi.resetModules() would otherwise hand the dynamically imported subcommands a fresh copy of the prompt wrapper that +// the spy from mock-prompts.js is not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), +})) + vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), log: vi.fn(), @@ -101,14 +105,13 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = mockConfirm(true) + const promptSpy = mockConfirmPrompt(true) await runMockProgram(['', '', 'blobs:delete', storeName, key]) - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(overwriteNotice) @@ -126,7 +129,7 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = mockConfirm(false) + const promptSpy = mockConfirmPrompt(false) try { await runMockProgram(['', '', 'blobs:delete', storeName, key]) @@ -136,10 +139,9 @@ describe('blobs:delete command', () => { expect((error as Error).message).toContain('process.exit unexpectedly called') } - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(overwriteNotice) @@ -157,7 +159,7 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:delete', storeName, key, '--force']) @@ -182,7 +184,7 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() try { await runMockProgram(['', '', 'blobs:delete', storeName, key, '--force']) @@ -218,7 +220,7 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:delete', storeName, key]) expect(promptSpy).not.toHaveBeenCalled() @@ -240,7 +242,7 @@ describe('blobs:delete command', () => { delete: mockDelete, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:delete', storeName, key]) diff --git a/tests/integration/commands/blobs/blobs-set.test.ts b/tests/integration/commands/blobs/blobs-set.test.ts index 0db49333e65..bb57425dc29 100644 --- a/tests/integration/commands/blobs/blobs-set.test.ts +++ b/tests/integration/commands/blobs/blobs-set.test.ts @@ -16,9 +16,7 @@ import { setTestingPrompts, } from '../../utils/mock-api.js' import { runMockProgram } from '../../utils/mock-program.js' -import { mockConfirm, spyOnConfirm } from '../../utils/inquirer-mock-prompt.js' - -vi.mock('@inquirer/prompts') +import { mockConfirmPrompt, spyOnConfirmPrompt } from '../../utils/mock-prompts.js' const siteInfo = { account_slug: 'test-account', @@ -30,6 +28,12 @@ const siteInfo = { functions_config: { timeout: 1 }, } +// vi.resetModules() would otherwise hand the dynamically imported subcommands a fresh copy of the prompt wrapper that +// the spy from mock-prompts.js is not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), +})) + vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), log: vi.fn(), @@ -105,7 +109,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:set', storeName, key, value]) @@ -129,14 +133,13 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = mockConfirm(true) + const promptSpy = mockConfirmPrompt(true) await runMockProgram(['', '', 'blobs:set', storeName, key, newValue]) - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(successMessage) expect(log).toHaveBeenCalledWith(warningMessage) @@ -157,7 +160,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = mockConfirm(false) + const promptSpy = mockConfirmPrompt(false) try { await runMockProgram(['', '', 'blobs:set', storeName, key, newValue]) @@ -167,10 +170,9 @@ describe('blobs:set command', () => { expect((error as Error).message).toContain('process.exit unexpectedly called with "0"') } - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(overwriteNotice) @@ -191,7 +193,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:set', storeName, key, newValue, '--force']) @@ -213,7 +215,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() try { await runMockProgram(['', '', 'blobs:set', storeName, key, newValue, '--force']) @@ -249,7 +251,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:set', storeName, key, newValue]) @@ -275,7 +277,7 @@ describe('blobs:set command', () => { set: mockSet, }) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'blobs:set', storeName, key, newValue]) expect(promptSpy).not.toHaveBeenCalled() diff --git a/tests/integration/commands/completion/completion-install.test.ts b/tests/integration/commands/completion/completion-install.test.ts index 00572999ea9..7443a1b1f56 100644 --- a/tests/integration/commands/completion/completion-install.test.ts +++ b/tests/integration/commands/completion/completion-install.test.ts @@ -67,7 +67,7 @@ describe('completion:install command', () => { }, { question: 'Would you like to add it?', - answer: answerWithValue(NO), + answer: NO, }, ]) diff --git a/tests/integration/commands/didyoumean/__snapshots__/didyoumean.test.ts.snap b/tests/integration/commands/didyoumean/__snapshots__/didyoumean.test.ts.snap index c80463ac37e..48e7219db4b 100644 --- a/tests/integration/commands/didyoumean/__snapshots__/didyoumean.test.ts.snap +++ b/tests/integration/commands/didyoumean/__snapshots__/didyoumean.test.ts.snap @@ -51,7 +51,7 @@ COMMANDS To get started run: netlify login To ask a human for credentials: netlify login --request -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit https://developers.netlify.com/cli → For help with Netlify, visit https://docs.netlify.com @@ -112,7 +112,7 @@ COMMANDS To get started run: netlify login To ask a human for credentials: netlify login --request -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit https://developers.netlify.com/cli → For help with Netlify, visit https://docs.netlify.com @@ -173,7 +173,7 @@ COMMANDS To get started run: netlify login To ask a human for credentials: netlify login --request -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit https://developers.netlify.com/cli → For help with Netlify, visit https://docs.netlify.com @@ -234,7 +234,7 @@ COMMANDS To get started run: netlify login To ask a human for credentials: netlify login --request -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit https://developers.netlify.com/cli → For help with Netlify, visit https://docs.netlify.com diff --git a/tests/integration/commands/env/__snapshots__/env.test.ts.snap b/tests/integration/commands/env/__snapshots__/env.test.ts.snap index 5d09f440d90..cee1642fdb8 100644 --- a/tests/integration/commands/env/__snapshots__/env.test.ts.snap +++ b/tests/integration/commands/env/__snapshots__/env.test.ts.snap @@ -11,55 +11,48 @@ exports[`commands/env > env:clone > should return without clone if there's no en exports[`commands/env > env:list > should hide variables values and prompt to show 1`] = ` "2 environment variables for project site-name in the dev context -.------------------------------------------------------------------------------- ---------. -| Environment variables - | -|------------------------------------------------------------------------------- ---------| -| Key | Value | Scop -e | -|--------------|----------------------------------------------------|----------- ---------| -| EXISTING_VAR | ************************************************** | Builds, Fu -nctions | -| OTHER_VAR | ************************************************** | All - | -'------------------------------------------------------------------------------- ---------' -? Show values? (y/N)√ Show values? No -[?25h" +.---------------------------------------------------------------------------------------. +| Environment variables | +|---------------------------------------------------------------------------------------| +| Key | Value | Scope | +|--------------|----------------------------------------------------|-------------------| +| EXISTING_VAR | ************************************************** | Builds, Functions | +| OTHER_VAR | ************************************************** | All | +'---------------------------------------------------------------------------------------' +[?25l│ +◆ Show values? +│ ○ Yes / ● No +└ +◇ Show values? +│ No +[?25h" `; exports[`commands/env > env:list > should hide variables values and show on confirm 1`] = ` "2 environment variables for project site-name in the dev context -.------------------------------------------------------------------------------- ---------. -| Environment variables - | -|------------------------------------------------------------------------------- ---------| -| Key | Value | Scop -e | -|--------------|----------------------------------------------------|----------- ---------| -| EXISTING_VAR | ************************************************** | Builds, Fu -nctions | -| OTHER_VAR | ************************************************** | All - | -'------------------------------------------------------------------------------- ---------' -? Show values? (y/N)? Show values? (y/N) y√ Show values? Yes -[?25h -.----------------------------------------------. +.---------------------------------------------------------------------------------------. +| Environment variables | +|---------------------------------------------------------------------------------------| +| Key | Value | Scope | +|--------------|----------------------------------------------------|-------------------| +| EXISTING_VAR | ************************************************** | Builds, Functions | +| OTHER_VAR | ************************************************** | All | +'---------------------------------------------------------------------------------------' +[?25l│ +◆ Show values? +│ ○ Yes / ● No +└ + +[?25h◇ Show values? +│ Yes +.----------------------------------------------. | Environment variables | |----------------------------------------------| | Key | Value | Scope | |--------------|-----------|-------------------| | EXISTING_VAR | dev-value | Builds, Functions | | OTHER_VAR | all-value | All | -'----------------------------------------------' -? Show values? Yes" +'----------------------------------------------'" `; exports[`commands/env > env:list > should not prompt on CI 1`] = ` diff --git a/tests/integration/commands/env/env-clone.test.ts b/tests/integration/commands/env/env-clone.test.ts index 7af30c7a6f5..41163ddcd12 100644 --- a/tests/integration/commands/env/env-clone.test.ts +++ b/tests/integration/commands/env/env-clone.test.ts @@ -9,9 +9,13 @@ import { getEnvironmentVariables, withMockApi, setTTYMode, setCI, setTestingProm import { existingVar, routes, secondSiteInfo } from './api-routes.js' import { runMockProgram } from '../../utils/mock-program.js' -import { mockConfirm, spyOnConfirm } from '../../utils/inquirer-mock-prompt.js' +import { mockConfirmPrompt, spyOnConfirmPrompt } from '../../utils/mock-prompts.js' -vi.mock('@inquirer/prompts') +// vi.resetModules() would otherwise hand the dynamically imported subcommands a fresh copy of the prompt wrapper that +// the spy from mock-prompts.js is not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), +})) vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), @@ -60,14 +64,13 @@ describe('env:clone command', () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(true) + const promptSpy = mockConfirmPrompt(true) await runMockProgram(['', '', 'env:clone', '-t', siteIdTwo]) - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(noticeEnvVars) @@ -83,7 +86,7 @@ describe('env:clone command', () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:clone', '--force', '-t', siteIdTwo]) @@ -103,7 +106,7 @@ describe('env:clone command', () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(false) + const promptSpy = mockConfirmPrompt(false) try { await runMockProgram(['', '', 'env:clone', '-t', siteIdTwo]) @@ -132,7 +135,7 @@ describe('env:clone command', () => { 'site-name', )} to ${chalk.green('site-name-3')}` - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:clone', '-t', 'site_id_3']) @@ -156,7 +159,7 @@ describe('env:clone command', () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:clone', '-t', siteIdTwo]) @@ -174,7 +177,7 @@ describe('env:clone command', () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:clone', '-t', siteIdTwo]) diff --git a/tests/integration/commands/env/env-set.test.ts b/tests/integration/commands/env/env-set.test.ts index 448ff9ef017..3609de51da7 100644 --- a/tests/integration/commands/env/env-set.test.ts +++ b/tests/integration/commands/env/env-set.test.ts @@ -9,9 +9,13 @@ import { FixtureTestContext, setupFixtureTests } from '../../utils/fixture.js' import { getEnvironmentVariables, withMockApi, setTTYMode, setCI, setTestingPrompts } from '../../utils/mock-api.js' import { runMockProgram } from '../../utils/mock-program.js' import { routes } from './api-routes.js' -import { mockConfirm, spyOnConfirm } from '../../utils/inquirer-mock-prompt.js' +import { mockConfirmPrompt, spyOnConfirmPrompt } from '../../utils/mock-prompts.js' -vi.mock('@inquirer/prompts') +// vi.resetModules() would otherwise hand the dynamically imported subcommands a fresh copy of the prompt wrapper that +// the spy from mock-prompts.js is not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), +})) vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), @@ -308,14 +312,13 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(true) + const promptSpy = mockConfirmPrompt(true) await runMockProgram(['', '', 'env:set', existingVar, newEnvValue]) - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(overwriteNotice) @@ -327,7 +330,7 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:set', 'NEW_ENV_VAR', 'NEW_VALUE']) @@ -345,7 +348,7 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:set', existingVar, newEnvValue, '--force']) @@ -361,7 +364,7 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(false) + const promptSpy = mockConfirmPrompt(false) try { await runMockProgram(['', '', 'env:set', existingVar, newEnvValue]) @@ -387,7 +390,7 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:set', existingVar, newEnvValue]) @@ -405,7 +408,7 @@ describe('env:set command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:set', existingVar, newEnvValue]) expect(promptSpy).not.toHaveBeenCalled() diff --git a/tests/integration/commands/env/env-unset.test.ts b/tests/integration/commands/env/env-unset.test.ts index 845351a8a4b..d0d5382df82 100644 --- a/tests/integration/commands/env/env-unset.test.ts +++ b/tests/integration/commands/env/env-unset.test.ts @@ -9,9 +9,13 @@ import { getEnvironmentVariables, withMockApi, setTTYMode, setCI, setTestingProm import { routes } from './api-routes.js' import { runMockProgram } from '../../utils/mock-program.js' -import { mockConfirm, spyOnConfirm } from '../../utils/inquirer-mock-prompt.js' +import { mockConfirmPrompt, spyOnConfirmPrompt } from '../../utils/mock-prompts.js' -vi.mock('@inquirer/prompts') +// vi.resetModules() would otherwise hand the dynamically imported subcommands a fresh copy of the prompt wrapper that +// the spy from mock-prompts.js is not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), +})) vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), @@ -114,14 +118,13 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(true) + const promptSpy = mockConfirmPrompt(true) await runMockProgram(['', '', 'env:unset', existingVar]) - expect(promptSpy).toHaveBeenCalledWith({ - message: expect.stringContaining(overwriteConfirmation), - default: false, - }) + expect(promptSpy).toHaveBeenCalledWith( + expect.objectContaining({ message: expect.stringContaining(overwriteConfirmation), initialValue: false }), + ) expect(log).toHaveBeenCalledWith(warningMessage) expect(log).toHaveBeenCalledWith(overwriteNotice) @@ -133,7 +136,7 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:unset', existingVar, '--force']) @@ -149,7 +152,7 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = mockConfirm(false) + const promptSpy = mockConfirmPrompt(false) try { await runMockProgram(['', '', 'env:unset', existingVar]) @@ -171,7 +174,7 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:unset', 'NEW_ENV_VAR']) @@ -191,7 +194,7 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:unset', existingVar]) expect(promptSpy).not.toHaveBeenCalled() @@ -208,7 +211,7 @@ describe('env:unset command', async () => { await withMockApi(routes, async ({ apiUrl }) => { Object.assign(process.env, getEnvironmentVariables({ apiUrl })) - const promptSpy = spyOnConfirm() + const promptSpy = spyOnConfirmPrompt() await runMockProgram(['', '', 'env:unset', existingVar]) expect(promptSpy).not.toHaveBeenCalled() diff --git a/tests/integration/commands/env/env.test.ts b/tests/integration/commands/env/env.test.ts index a4784306f28..bdb530538d4 100644 --- a/tests/integration/commands/env/env.test.ts +++ b/tests/integration/commands/env/env.test.ts @@ -5,7 +5,7 @@ import { describe, test } from 'vitest' import { callCli } from '../../utils/call-cli.js' import { cliPath } from '../../utils/cli-path.js' -import { CONFIRM, answerWithValue, handleQuestions } from '../../utils/handle-questions.js' +import { CONFIRM, YES, handleQuestions } from '../../utils/handle-questions.js' import { getCLIOptions, withMockApi } from '../../utils/mock-api.js' import { withSiteBuilder } from '../../utils/site-builder.js' import { normalize } from '../../utils/snapshots.js' @@ -188,7 +188,7 @@ describe('commands/env', () => { const questions = [ { question: 'Show values', - answer: answerWithValue('y'), + answer: YES, }, ] diff --git a/tests/integration/commands/help/__snapshots__/help.test.ts.snap b/tests/integration/commands/help/__snapshots__/help.test.ts.snap index 490ee5dac81..c8d466717f6 100644 --- a/tests/integration/commands/help/__snapshots__/help.test.ts.snap +++ b/tests/integration/commands/help/__snapshots__/help.test.ts.snap @@ -46,7 +46,7 @@ COMMANDS To get started run: netlify login To ask a human for credentials: netlify login --request -Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input +Exit codes: 0 ok, 1 error, 2 usage, 4 needs-input, 130 cancelled → For more help with the CLI, visit https://developers.netlify.com/cli → For help with Netlify, visit https://docs.netlify.com diff --git a/tests/integration/commands/init/init.test.ts b/tests/integration/commands/init/init.test.ts index a085ab4d7fd..4fc3bd1d72b 100644 --- a/tests/integration/commands/init/init.test.ts +++ b/tests/integration/commands/init/init.test.ts @@ -214,7 +214,7 @@ describe.concurrent('commands/init', () => { question: 'Create & configure a new project', answer: answerWithValue(DOWN), }, - { question: 'Team:', answer: CONFIRM }, + { question: 'Team', answer: CONFIRM }, { question: 'Project name (leave blank for a random name; you can change it later)', answer: answerWithValue('test-site-name'), @@ -310,7 +310,7 @@ describe.concurrent('commands/init', () => { question: 'Yes, create and deploy project manually', answer: CONFIRM, // List selection only needs one CONFIRM, not answerWithValue }, - { question: 'Team:', answer: CONFIRM }, + { question: 'Team', answer: CONFIRM }, { question: 'Project name (leave blank for a random name; you can change it later)', answer: answerWithValue('test-site-name'), @@ -393,7 +393,7 @@ describe.concurrent('commands/init', () => { question: 'Create & configure a new project', answer: answerWithValue(DOWN), }, - { question: 'Team:', answer: CONFIRM }, + { question: 'Team', answer: CONFIRM }, { question: 'Project name (leave blank for a random name; you can change it later)', answer: answerWithValue('test-site-name'), @@ -498,7 +498,7 @@ describe.concurrent('commands/init', () => { question: 'Create & configure a new project', answer: answerWithValue(DOWN), }, - { question: 'Team:', answer: CONFIRM }, + { question: 'Team', answer: CONFIRM }, { question: 'Project name (leave blank for a random name; you can change it later)', answer: answerWithValue('test-site-name'), @@ -696,7 +696,7 @@ describe.concurrent('commands/init', () => { question: 'Create & configure a new project', answer: answerWithValue(DOWN), }, - { question: 'Team:', answer: CONFIRM }, + { question: 'Team', answer: CONFIRM }, { question: 'Project name (leave blank for a random name; you can change it later)', answer: answerWithValue('test-site-name'), diff --git a/tests/integration/commands/link/link-prompt.test.ts b/tests/integration/commands/link/link-prompt.test.ts index 4ba4cad1d7b..ef4f49981bf 100644 --- a/tests/integration/commands/link/link-prompt.test.ts +++ b/tests/integration/commands/link/link-prompt.test.ts @@ -21,11 +21,6 @@ interface SelectQuestion { options: AskedOption[] } -interface InquirerChoice { - name?: string - value: unknown -} - interface TextQuestion { message: string } @@ -48,16 +43,10 @@ const { askedPrompts, exitCalls, logMessages, mockPromptSelect, mockPromptText, }), ) -vi.mock('@inquirer/prompts', async (importOriginal) => ({ - ...(await importOriginal()), - select: ({ message, choices }: { message: string; choices: (string | InquirerChoice)[] }) => - mockPromptSelect({ - message, - options: choices.map((choice) => - typeof choice === 'string' ? { value: choice, label: choice } : { value: choice.value, label: choice.name }, - ), - }), - input: ({ message }: TextQuestion) => mockPromptText({ message }), +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptSelect: (question: SelectQuestion) => mockPromptSelect(question), + promptText: (question: TextQuestion) => mockPromptText(question), })) vi.mock('../../../../src/utils/scripted-commands.js', async (importOriginal) => ({ @@ -123,6 +112,8 @@ const offeredOptions = (message: string) => askedPrompts.find((prompt) => prompt const offeredChoices = (message: string) => offeredOptions(message)?.map(optionLabel) +const offeredHints = (message: string) => offeredOptions(message)?.map((option) => option.hint) + const output = () => stripAnsi(logMessages.join('\n')) const HOW_TO_LINK = 'How do you want to link this folder to a project?' @@ -386,16 +377,14 @@ describe('link command interactive prompts', () => { routesWithSites([connected[0], unrelatedSite, connected[1]]), async ({ apiUrl, requests }) => { useMockApi(apiUrl) - queuePromptAnswers(LINK_BY_GIT_REMOTE, `${connected[1].name} - ${connected[1].ssl_url}`) + queuePromptAnswers(LINK_BY_GIT_REMOTE, connected[1].name) await runLink(builder.directory) expect(askedMessages()).toEqual([HOW_TO_LINK, WHICH_PROJECT]) expect(offeredChoices(HOW_TO_LINK)).toEqual([LINK_BY_GIT_REMOTE, LINK_BY_NAME, LINK_FROM_LIST, LINK_BY_ID]) - expect(offeredChoices(WHICH_PROJECT)).toEqual([ - `${connected[0].name} - ${connected[0].ssl_url}`, - `${connected[1].name} - ${connected[1].ssl_url}`, - ]) + expect(offeredChoices(WHICH_PROJECT)).toEqual([connected[0].name, connected[1].name]) + expect(offeredHints(WHICH_PROJECT)).toEqual([connected[0].ssl_url, connected[1].ssl_url]) expect(getRequests(requests, 'sites')).toHaveLength(1) await expectLinkedTo(builder.directory, connected[1], 'gitRemote') }, diff --git a/tests/integration/commands/recipes/recipes.test.ts b/tests/integration/commands/recipes/recipes.test.ts index 98949a4c562..5e03b483cd5 100644 --- a/tests/integration/commands/recipes/recipes.test.ts +++ b/tests/integration/commands/recipes/recipes.test.ts @@ -7,7 +7,7 @@ import { describe, test } from 'vitest' import { callCli } from '../../utils/call-cli.js' import { cliPath } from '../../utils/cli-path.js' -import { CONFIRM, NO, answerWithValue, handleQuestions } from '../../utils/handle-questions.js' +import { CONFIRM, NO, handleQuestions } from '../../utils/handle-questions.js' import { withSiteBuilder } from '../../utils/site-builder.js' import { normalize } from '../../utils/snapshots.js' @@ -92,7 +92,7 @@ describe.concurrent('commands/recipes', () => { handleQuestions(childProcess, [ { question: `A new VS Code settings file will be created at ${settingsPath}`, - answer: answerWithValue(NO), + answer: NO, }, ]) @@ -132,7 +132,7 @@ describe.concurrent('commands/recipes', () => { }, { question: 'The Deno VS Code extension is recommended. Would you like to install it now?', - answer: answerWithValue(NO), + answer: NO, }, ]) diff --git a/tests/integration/commands/sites/sites-delete.test.ts b/tests/integration/commands/sites/sites-delete.test.ts index 85eb9b7f242..f1041b6b946 100644 --- a/tests/integration/commands/sites/sites-delete.test.ts +++ b/tests/integration/commands/sites/sites-delete.test.ts @@ -2,7 +2,7 @@ import execa from 'execa' import { describe, expect, test } from 'vitest' import { cliPath } from '../../utils/cli-path.js' -import { CONFIRM, answerWithValue, handleQuestions } from '../../utils/handle-questions.js' +import { CONFIRM, YES, handleQuestions } from '../../utils/handle-questions.js' import { getCLIOptions, withMockApi, type MockApiTestContext, type Route } from '../../utils/mock-api.js' import { withSiteBuilder } from '../../utils/site-builder.js' @@ -57,7 +57,7 @@ describe('sites:delete command', () => { getCLIOptions({ apiUrl, builder, env: promptingEnv }), ) - handleQuestions(childProcess, [{ question: CONFIRM_QUESTION, answer: answerWithValue('y') }]) + handleQuestions(childProcess, [{ question: CONFIRM_QUESTION, answer: YES }]) const { stdout } = await childProcess @@ -93,6 +93,30 @@ describe('sites:delete command', () => { }) }) + // Not `y\n`: the `y` submits on its own, so only a bare line feed exercises submitting the default ("No"). + test('submits a prompt answered with a bare line feed, as a pipe sends it', async (t) => { + await withSiteBuilder(t, async (builder) => { + await builder.build() + + await withMockApi(routes, async ({ apiUrl, requests }) => { + const childProcess = execa( + cliPath, + ['sites:delete', 'site_id'], + getCLIOptions({ apiUrl, builder, env: promptingEnv }), + ) + + handleQuestions(childProcess, [{ question: CONFIRM_QUESTION, answer: '\n' }]) + + const { exitCode, stdout } = await childProcess + + expect(exitCode).toBe(0) + expect(stdout).toContain(CONFIRM_QUESTION) + expect(stdout).not.toContain(DELETED_MESSAGE) + expect(deleteRequests(requests)).toHaveLength(0) + }) + }) + }) + test('skips the confirmation prompt with --force', async (t) => { await withSiteBuilder(t, async (builder) => { await builder.build() @@ -139,8 +163,8 @@ describe('sites:delete command', () => { ) handleQuestions(childProcess, [ - { question: CONFIRM_QUESTION, answer: answerWithValue('y') }, - { question: VERIFY_QUESTION, answer: answerWithValue('y') }, + { question: CONFIRM_QUESTION, answer: YES }, + { question: VERIFY_QUESTION, answer: YES }, ]) const { stdout } = await childProcess @@ -167,7 +191,7 @@ describe('sites:delete command', () => { ) handleQuestions(childProcess, [ - { question: CONFIRM_QUESTION, answer: answerWithValue('y') }, + { question: CONFIRM_QUESTION, answer: YES }, { question: VERIFY_QUESTION, answer: CONFIRM }, ]) diff --git a/tests/integration/commands/sites/sites.test.ts b/tests/integration/commands/sites/sites.test.ts index bafb48091da..a5f34a558ee 100644 --- a/tests/integration/commands/sites/sites.test.ts +++ b/tests/integration/commands/sites/sites.test.ts @@ -4,6 +4,7 @@ import { afterAll, beforeEach, describe, expect, test, vi } from 'vitest' import BaseCommand from '../../../../src/commands/base-command.js' import { createSitesCommand, createSitesCreateCommand } from '../../../../src/commands/sites/sites.js' +import * as prompts from '../../../../src/utils/prompts/index.js' import { getEnvironmentVariables, withMockApi } from '../../utils/mock-api.js' vi.mock('../../../../src/utils/command-helpers.js', async () => ({ @@ -11,11 +12,16 @@ vi.mock('../../../../src/utils/command-helpers.js', async () => ({ log: () => {}, })) -vi.mock('@inquirer/prompts', () => ({ - input: vi.fn().mockResolvedValue(''), - select: vi.fn().mockResolvedValue('test-account'), +// vi.resetModules() would otherwise hand the dynamically imported subcommand a fresh copy of the prompt +// wrapper that these spies are not attached to; a mocked module keeps a single instance across resets. +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), })) +// No test here should reach a prompt; these make an accidental regression fail instead of hang. +vi.spyOn(prompts, 'promptSelect').mockRejectedValue(new Error('unexpected prompt: promptSelect')) +vi.spyOn(prompts, 'promptText').mockRejectedValue(new Error('unexpected prompt: promptText')) + const siteInfo = { admin_url: 'https://app.netlify.com/projects/site-name/overview', ssl_url: 'https://site-name.netlify.app/', diff --git a/tests/integration/utils/handle-questions.ts b/tests/integration/utils/handle-questions.ts index 6576766ebf9..37e8a39f9e2 100644 --- a/tests/integration/utils/handle-questions.ts +++ b/tests/integration/utils/handle-questions.ts @@ -1,6 +1,8 @@ import { Buffer } from 'node:buffer' +import { stripVTControlCharacters } from 'node:util' interface Stdin { + writable: boolean write(data: Buffer): boolean } @@ -13,6 +15,12 @@ interface Process { stdout: Stdout | null } +// clack wraps long messages and prefixes each continuation line with its guide bar. +const CLACK_LINE_CONTINUATION = /\r?\n[│|] {2}/g + +const normalize = (output: string): string => + stripVTControlCharacters(output).replace(CLACK_LINE_CONTINUATION, '').replace(/\r?\n/g, '') + /** * Utility to mock the stdin of the cli. You must provide the correct number of * questions correctly typed or the process will keep waiting for input. @@ -30,9 +38,10 @@ export const handleQuestions = ( let buffer = '' process.stdout.on('data', (data: Buffer) => { - buffer = (buffer + data.toString()).replace(/\n/g, '') + buffer += data.toString() + const normalized = normalize(buffer) const index = questions.findIndex( - ({ question }, questionIndex) => buffer.includes(question) && !prompts.includes(questionIndex), + ({ question }, questionIndex) => normalized.includes(question) && !prompts.includes(questionIndex), ) if (index >= 0) { prompts.push(index) @@ -50,7 +59,8 @@ const writeResponse = (process: Process, responses: string[]) => { } const response = responses.shift() - if (response) process.stdin.write(Buffer.from(response)) + // The CLI may already have exited (a `y`/`n` answer submits on its own); writing then would crash the test. + if (response && process.stdin.writable) process.stdin.write(Buffer.from(response)) if (responses.length !== 0) setTimeout(() => { writeResponse(process, responses) @@ -59,6 +69,10 @@ const writeResponse = (process: Process, responses: string[]) => { export const answerWithValue = (value = '') => [value, CONFIRM].flat() -export const CONFIRM = '\n' +/** Enter, as a terminal sends it. */ +export const CONFIRM = '\r' export const DOWN = '\u001B[B' +/** Answers a confirm prompt with "No" and submits immediately; do not follow it with CONFIRM. */ export const NO = 'n' +/** Answers a confirm prompt with "Yes" and submits immediately; do not follow it with CONFIRM. */ +export const YES = 'y' diff --git a/tests/integration/utils/inquirer-mock-prompt.ts b/tests/integration/utils/inquirer-mock-prompt.ts deleted file mode 100644 index ed475493a7d..00000000000 --- a/tests/integration/utils/inquirer-mock-prompt.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { confirm } from '@inquirer/prompts' -import { vi } from 'vitest' - -// Callers must mock the module in their own test file with `vi.mock('@inquirer/prompts')`, -// because `vi.mock` is hoisted per file. -export const mockConfirm = (answer: boolean) => vi.mocked(confirm).mockReset().mockResolvedValue(answer) - -export const spyOnConfirm = () => vi.mocked(confirm).mockReset() diff --git a/tests/integration/utils/mock-prompts.ts b/tests/integration/utils/mock-prompts.ts new file mode 100644 index 00000000000..4add620a1b1 --- /dev/null +++ b/tests/integration/utils/mock-prompts.ts @@ -0,0 +1,7 @@ +import { vi } from 'vitest' + +import * as prompts from '../../../src/utils/prompts/index.js' + +export const mockConfirmPrompt = (answer = true) => vi.spyOn(prompts, 'promptConfirm').mockResolvedValue(answer) + +export const spyOnConfirmPrompt = () => vi.spyOn(prompts, 'promptConfirm') diff --git a/tests/integration/utils/snapshots.ts b/tests/integration/utils/snapshots.ts index 0f7cc0977aa..f51a15aa7ae 100644 --- a/tests/integration/utils/snapshots.ts +++ b/tests/integration/utils/snapshots.ts @@ -1,4 +1,8 @@ const baseNormalizers: Normalizer[] = [ + // Node < 22.15 `styleText` ignores disabled colours for array formats, which clack uses for its cursor. + // Remove once the Node floor is 22.15+. + // eslint-disable-next-line no-control-regex + { pattern: /\u001B\[[\d;]*m/g, value: '' }, // Information about the package and the OS { pattern: /netlify-cli\/.+node-.+/g, value: 'netlify-cli/test-version test-os test-node-version' }, { pattern: /@netlify\/build (\d+\.\d+\.\d+)/g, value: '@netlify/build 0.0.0' }, diff --git a/tests/unit/commands/base-command-on-end.test.ts b/tests/unit/commands/base-command-on-end.test.ts index a1ce27ce997..2223c383e33 100644 --- a/tests/unit/commands/base-command-on-end.test.ts +++ b/tests/unit/commands/base-command-on-end.test.ts @@ -15,12 +15,6 @@ vi.mock('../../../src/utils/telemetry/index.js', async () => ({ track: vi.fn(), })) -const createExitPromptError = () => { - const error = new Error('User force closed the prompt with SIGINT') - error.name = 'ExitPromptError' - return error -} - describe('BaseCommand.onEnd', () => { beforeEach(() => { vi.mocked(exit).mockClear() @@ -31,13 +25,6 @@ describe('BaseCommand.onEnd', () => { vi.clearAllMocks() }) - test('exits with the interrupted code without logging when a prompt is cancelled with Ctrl+C', async () => { - await new BaseCommand('netlify').onEnd(createExitPromptError()) - - expect(logError).not.toHaveBeenCalled() - expect(exit).toHaveBeenCalledWith(EXIT_CODES.INTERRUPTED) - }) - test('logs other errors and exits with code 1', async () => { const error = new Error('Something broke') diff --git a/tests/unit/commands/database/db-init.test.ts b/tests/unit/commands/database/db-init.test.ts index 0b0c511e09b..12c86de8aea 100644 --- a/tests/unit/commands/database/db-init.test.ts +++ b/tests/unit/commands/database/db-init.test.ts @@ -15,6 +15,8 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' const { mockSpawnAsync, mockConnectRawClient, + mockPromptConfirm, + mockPromptSelect, mockIsInteractive, mockFormatQueryResult, mockApplyMigrations, @@ -24,6 +26,8 @@ const { } = vi.hoisted(() => ({ mockSpawnAsync: vi.fn(), mockConnectRawClient: vi.fn(), + mockPromptConfirm: vi.fn<(...args: unknown[]) => Promise>(), + mockPromptSelect: vi.fn<(...args: unknown[]) => Promise>(), mockIsInteractive: vi.fn().mockReturnValue(true), mockFormatQueryResult: vi.fn(), mockApplyMigrations: vi.fn(), @@ -32,7 +36,11 @@ const { logMessages: [] as string[], })) -vi.mock('@inquirer/prompts') +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptConfirm: (...args: unknown[]) => mockPromptConfirm(...args), + promptSelect: (...args: unknown[]) => mockPromptSelect(...args), +})) vi.mock('../../../../src/commands/database/util/spawn-async.js', async (importOriginal) => ({ ...(await importOriginal()), @@ -72,8 +80,6 @@ vi.mock('../../../../src/utils/command-helpers.js', async () => ({ }, })) -import { confirm, select } from '@inquirer/prompts' - import { initDatabase } from '../../../../src/commands/database/db-init.js' import { utcTimestampPrefix } from '../../../../src/commands/database/util/timestamp.js' @@ -94,9 +100,9 @@ function createCommand(projectRoot: string) { } as unknown as Parameters[1] } -const answerPrompts = ({ queryStyle, createSampleData }: { queryStyle: string; createSampleData: boolean }) => { - vi.mocked(select).mockResolvedValueOnce(queryStyle) - vi.mocked(confirm).mockResolvedValueOnce(createSampleData) +const setPrompts = (queryStyle: 'raw' | 'drizzle', withStarter: boolean) => { + mockPromptSelect.mockResolvedValueOnce(queryStyle) + mockPromptConfirm.mockResolvedValueOnce(withStarter) } const exists = async (path: string): Promise => { @@ -122,8 +128,6 @@ beforeEach(async () => { logMessages.length = 0 vi.clearAllMocks() - vi.mocked(select).mockReset().mockRejectedValue(new Error('Unexpected select prompt — no answer queued')) - vi.mocked(confirm).mockReset().mockRejectedValue(new Error('Unexpected confirm prompt — no answer queued')) // Simulate `drizzle-kit generate` by writing a timestamp-prefixed directory // with a migration.sql under the configured out dir. Anything else (package @@ -168,7 +172,7 @@ afterEach(async () => { describe('initDatabase (integration)', () => { test('raw SQL + starter writes a timestamp-prefixed migration with a CREATE TABLE and seed data', async () => { - answerPrompts({ queryStyle: 'raw', createSampleData: true }) + setPrompts('raw', true) await initDatabase({}, createCommand(projectRoot())) @@ -192,7 +196,7 @@ describe('initDatabase (integration)', () => { }) test('Drizzle + starter writes schema/config, runs drizzle-kit generate, and seeds after it', async () => { - answerPrompts({ queryStyle: 'drizzle', createSampleData: true }) + setPrompts('drizzle', true) await initDatabase({}, createCommand(projectRoot())) @@ -235,7 +239,7 @@ describe('initDatabase (integration)', () => { }) test('Drizzle without starter scaffolds drizzle.config.ts only (no schema, no migration, no generate)', async () => { - answerPrompts({ queryStyle: 'drizzle', createSampleData: false }) + setPrompts('drizzle', false) await initDatabase({}, createCommand(projectRoot())) @@ -253,7 +257,7 @@ describe('initDatabase (integration)', () => { }) test('raw without starter writes nothing extra; next steps point at `database migrations new`', async () => { - answerPrompts({ queryStyle: 'raw', createSampleData: false }) + setPrompts('raw', false) await initDatabase({}, createCommand(projectRoot())) @@ -275,8 +279,8 @@ describe('initDatabase (integration)', () => { await initDatabase({}, createCommand(projectRoot())) expect(await readMigrations(projectRoot())).toEqual(['0001_existing.sql']) - expect(select).not.toHaveBeenCalled() - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(mockSpawnAsync).not.toHaveBeenCalled() expect(mockConnectRawClient).not.toHaveBeenCalled() expect(logMessages.join('\n')).toContain('you already have migrations set up') @@ -287,8 +291,8 @@ describe('initDatabase (integration)', () => { await initDatabase({}, createCommand(projectRoot())) - expect(select).not.toHaveBeenCalled() - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(await exists(join(projectRoot(), 'drizzle.config.ts'))).toBe(true) expect(await exists(join(projectRoot(), 'db', 'schema.ts'))).toBe(true) expect((await readMigrations(projectRoot())).some((name) => name.includes('seed_planets'))).toBe(true) @@ -302,28 +306,30 @@ describe('initDatabase (integration)', () => { await initDatabase({}, createCommand(projectRoot())) - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toBe('// hand-written config') expect(logMessages.join('\n')).toContain('already exists, leaving it unchanged') }) test('--yes overwrites an existing drizzle.config.ts without prompting', async () => { + mockIsInteractive.mockReturnValue(true) await fs.writeFile(join(projectRoot(), 'drizzle.config.ts'), '// hand-written config') await initDatabase({ yes: true }, createCommand(projectRoot())) - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toContain('defineConfig') }) test('interactive still asks before overwriting an existing drizzle.config.ts', async () => { - vi.mocked(select).mockResolvedValueOnce('drizzle') - vi.mocked(confirm).mockResolvedValueOnce(false).mockResolvedValueOnce(false) + setPrompts('drizzle', false) + mockPromptConfirm.mockResolvedValueOnce(false) await fs.writeFile(join(projectRoot(), 'drizzle.config.ts'), '// hand-written config') await initDatabase({}, createCommand(projectRoot())) - expect(vi.mocked(confirm).mock.calls[0][0].message).toContain('Overwrite existing file') + const [{ message }] = mockPromptConfirm.mock.calls[0] as [{ message: string }] + expect(message).toContain('Overwrite existing file') expect(await fs.readFile(join(projectRoot(), 'drizzle.config.ts'), 'utf-8')).toBe('// hand-written config') }) diff --git a/tests/unit/commands/database/db-migration-new.test.ts b/tests/unit/commands/database/db-migration-new.test.ts index f3a37dc4bf5..7c92c06aede 100644 --- a/tests/unit/commands/database/db-migration-new.test.ts +++ b/tests/unit/commands/database/db-migration-new.test.ts @@ -1,13 +1,16 @@ import { describe, expect, test, vi, beforeEach } from 'vitest' -const { mockReaddir, mockMkdir, mockWriteFile, logMessages, jsonMessages } = vi.hoisted(() => { - const mockReaddir = vi.fn().mockResolvedValue([]) - const mockMkdir = vi.fn().mockResolvedValue(undefined) - const mockWriteFile = vi.fn().mockResolvedValue(undefined) - const logMessages: string[] = [] - const jsonMessages: unknown[] = [] - return { mockReaddir, mockMkdir, mockWriteFile, logMessages, jsonMessages } -}) +const { mockReaddir, mockMkdir, mockWriteFile, mockPromptText, mockPromptSelect, logMessages, jsonMessages } = + vi.hoisted(() => { + const mockReaddir = vi.fn().mockResolvedValue([]) + const mockMkdir = vi.fn().mockResolvedValue(undefined) + const mockWriteFile = vi.fn().mockResolvedValue(undefined) + const mockPromptText = vi.fn<(...args: unknown[]) => Promise>() + const mockPromptSelect = vi.fn<(...args: unknown[]) => Promise>() + const logMessages: string[] = [] + const jsonMessages: unknown[] = [] + return { mockReaddir, mockMkdir, mockWriteFile, mockPromptText, mockPromptSelect, logMessages, jsonMessages } + }) vi.mock('fs/promises', async (importOriginal) => { const actual = await importOriginal() @@ -22,7 +25,11 @@ vi.mock('fs/promises', async (importOriginal) => { } }) -vi.mock('@inquirer/prompts') +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptSelect: (...args: unknown[]) => mockPromptSelect(...args), + promptText: (...args: unknown[]) => mockPromptText(...args), +})) vi.mock('../../../../src/utils/scripted-commands.js', () => ({ isInteractive: vi.fn(), @@ -40,7 +47,6 @@ vi.mock('../../../../src/utils/command-helpers.js', async () => ({ import { join } from 'path' -import { input, select } from '@inquirer/prompts' import { migrationNew, generateSlug, @@ -199,13 +205,13 @@ describe('migrationNew', () => { test('prompts for description when not provided', async () => { vi.mocked(isInteractive).mockReturnValue(true) - vi.mocked(input).mockResolvedValueOnce('create users table') - vi.mocked(select).mockResolvedValueOnce('sequential') + mockPromptText.mockResolvedValueOnce('create users table') + mockPromptSelect.mockResolvedValueOnce('sequential') await migrationNew({}, createMockCommand()) - expect(input).toHaveBeenCalledOnce() - expect(select).toHaveBeenCalledOnce() + expect(mockPromptText).toHaveBeenCalledTimes(1) + expect(mockPromptSelect).toHaveBeenCalledTimes(1) expect(mockMkdir).toHaveBeenCalledWith(expect.stringContaining('create-users-table'), expect.any(Object)) }) @@ -220,11 +226,12 @@ describe('migrationNew', () => { test('prompts for scheme with detected default when not provided', async () => { vi.mocked(isInteractive).mockReturnValue(true) mockReaddir.mockResolvedValue([dirEntry('0001_create-users'), dirEntry('0002_add-posts')]) - vi.mocked(select).mockResolvedValueOnce('sequential') + mockPromptSelect.mockResolvedValueOnce('sequential') await migrationNew({ description: 'add comments' }, createMockCommand()) - expect(select).toHaveBeenCalledWith(expect.objectContaining({ default: 'sequential' })) + expect(mockPromptText).not.toHaveBeenCalled() + expect(mockPromptSelect).toHaveBeenCalledWith(expect.objectContaining({ initialValue: 'sequential' })) }) test('defaults to timestamp scheme in non-interactive mode when no migrations exist', async () => { @@ -232,8 +239,7 @@ describe('migrationNew', () => { await migrationNew({ description: 'add posts table' }, createMockCommand()) - expect(input).not.toHaveBeenCalled() - expect(select).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() const mkdirCall = mockMkdir.mock.calls[0][0] as string const folderName = mkdirCall.split(/[/\\]/).pop() ?? '' expect(folderName).toMatch(/^\d{14}_add-posts-table$/) @@ -245,8 +251,7 @@ describe('migrationNew', () => { await migrationNew({ description: 'add comments' }, createMockCommand()) - expect(input).not.toHaveBeenCalled() - expect(select).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() expect(mockMkdir).toHaveBeenCalledWith(join('/project/netlify/database/migrations', '0003_add-comments'), { recursive: true, }) @@ -258,8 +263,7 @@ describe('migrationNew', () => { await migrationNew({ description: 'add comments' }, createMockCommand()) - expect(input).not.toHaveBeenCalled() - expect(select).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() const mkdirCall = mockMkdir.mock.calls[0][0] as string const folderName = mkdirCall.split(/[/\\]/).pop() ?? '' expect(folderName).toMatch(/^\d{14}_add-comments$/) diff --git a/tests/unit/commands/database/db-migration-pull.test.ts b/tests/unit/commands/database/db-migration-pull.test.ts index 8febc268a6c..01439a6381d 100644 --- a/tests/unit/commands/database/db-migration-pull.test.ts +++ b/tests/unit/commands/database/db-migration-pull.test.ts @@ -1,15 +1,17 @@ import { describe, expect, test, vi, beforeEach, afterEach } from 'vitest' -const { mockRm, mockMkdir, mockWriteFile, mockFetch, mockExeca, logMessages, jsonMessages } = vi.hoisted(() => { - const mockRm = vi.fn().mockResolvedValue(undefined) - const mockMkdir = vi.fn().mockResolvedValue(undefined) - const mockWriteFile = vi.fn().mockResolvedValue(undefined) - const mockFetch = vi.fn() - const mockExeca = vi.fn() - const logMessages: string[] = [] - const jsonMessages: unknown[] = [] - return { mockRm, mockMkdir, mockWriteFile, mockFetch, mockExeca, logMessages, jsonMessages } -}) +const { mockRm, mockMkdir, mockWriteFile, mockFetch, mockExeca, mockPromptConfirm, logMessages, jsonMessages } = + vi.hoisted(() => { + const mockRm = vi.fn().mockResolvedValue(undefined) + const mockMkdir = vi.fn().mockResolvedValue(undefined) + const mockWriteFile = vi.fn().mockResolvedValue(undefined) + const mockFetch = vi.fn() + const mockExeca = vi.fn() + const mockPromptConfirm = vi.fn<(...args: unknown[]) => Promise>() + const logMessages: string[] = [] + const jsonMessages: unknown[] = [] + return { mockRm, mockMkdir, mockWriteFile, mockFetch, mockExeca, mockPromptConfirm, logMessages, jsonMessages } + }) vi.mock('fs/promises', async (importOriginal) => { const actual = await importOriginal() @@ -24,7 +26,10 @@ vi.mock('fs/promises', async (importOriginal) => { } }) -vi.mock('@inquirer/prompts') +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptConfirm: (...args: unknown[]) => mockPromptConfirm(...args), +})) vi.mock('../../../../src/utils/command-helpers.js', async () => ({ ...(await vi.importActual('../../../../src/utils/command-helpers.js')), @@ -45,7 +50,6 @@ vi.stubGlobal('fetch', mockFetch) import { resolve } from 'path' -import { confirm } from '@inquirer/prompts' import { migrationPull } from '../../../../src/commands/database/db-migration-pull.js' interface SampleMigration { @@ -146,7 +150,7 @@ describe('migrationPull', () => { test('fetches migrations from the correct API endpoint', async () => { mockFetchResponse(sampleMigrations) - vi.mocked(confirm).mockResolvedValueOnce(true) + mockPromptConfirm.mockResolvedValueOnce(true) await migrationPull({}, createMockCommand()) @@ -248,11 +252,17 @@ describe('migrationPull', () => { test('prompts for confirmation before overwriting', async () => { mockFetchResponse(sampleMigrations) - vi.mocked(confirm).mockResolvedValueOnce(false) + mockPromptConfirm.mockResolvedValueOnce(false) await migrationPull({}, createMockCommand()) - expect(confirm).toHaveBeenCalledOnce() + expect(mockPromptConfirm).toHaveBeenCalledTimes(1) + expect(mockPromptConfirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining('overwrite all local migrations') as unknown as string, + initialValue: false, + }), + ) expect(mockRm).not.toHaveBeenCalled() expect(logMessages).toContain('Pull cancelled.') }) @@ -262,13 +272,13 @@ describe('migrationPull', () => { await migrationPull({ force: true }, createMockCommand()) - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(mockRm).toHaveBeenCalled() }) test('removes existing migrations directory and writes fetched migrations', async () => { mockFetchResponse(sampleMigrations) - vi.mocked(confirm).mockResolvedValueOnce(true) + mockPromptConfirm.mockResolvedValueOnce(true) const migrationsPath = '/project/netlify/database/migrations' const resolved = resolve(migrationsPath) @@ -293,7 +303,7 @@ describe('migrationPull', () => { test('logs pulled migration names', async () => { mockFetchResponse(sampleMigrations) - vi.mocked(confirm).mockResolvedValueOnce(true) + mockPromptConfirm.mockResolvedValueOnce(true) await migrationPull({}, createMockCommand()) diff --git a/tests/unit/commands/database/db-reset.test.ts b/tests/unit/commands/database/db-reset.test.ts index d8942a7e3b1..0ce5138709c 100644 --- a/tests/unit/commands/database/db-reset.test.ts +++ b/tests/unit/commands/database/db-reset.test.ts @@ -6,6 +6,7 @@ const { mockConnectToDatabase, mockExecutor, mockRm, + mockPromptConfirm, mockIsInteractive, logMessages, jsonMessages, @@ -15,6 +16,7 @@ const { const mockExecutor = {} const mockConnectToDatabase = vi.fn() const mockRm = vi.fn().mockResolvedValue(undefined) + const mockPromptConfirm = vi.fn<(...args: unknown[]) => Promise>() const mockIsInteractive = vi.fn().mockReturnValue(true) const logMessages: string[] = [] const jsonMessages: unknown[] = [] @@ -24,6 +26,7 @@ const { mockConnectToDatabase, mockExecutor, mockRm, + mockPromptConfirm, mockIsInteractive, logMessages, jsonMessages, @@ -47,7 +50,10 @@ vi.mock('fs/promises', async () => ({ rm: (...args: unknown[]) => mockRm(...args), })) -vi.mock('@inquirer/prompts') +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptConfirm: (...args: unknown[]) => mockPromptConfirm(...args), +})) vi.mock('../../../../src/utils/scripted-commands.js', () => ({ // eslint-disable-next-line @typescript-eslint/no-unsafe-return @@ -64,8 +70,6 @@ vi.mock('../../../../src/utils/command-helpers.js', async () => ({ }, })) -import { confirm } from '@inquirer/prompts' - import { reset } from '../../../../src/commands/database/db-reset.js' import { LocalDatabaseStartError } from '../../../../src/commands/database/util/db-connection.js' @@ -138,15 +142,21 @@ describe('reset', () => { }) test('discards the data directory once the user confirms', async () => { - vi.mocked(confirm).mockResolvedValue(true) + mockPromptConfirm.mockResolvedValue(true) await reset({}, createMockCommand()) + expect(mockPromptConfirm).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining(DB_DIRECTORY) as unknown as string, + initialValue: false, + }), + ) expect(mockRm).toHaveBeenCalledWith(DB_DIRECTORY, { recursive: true, force: true }) }) test('explains the underlying startup failure before prompting', async () => { - vi.mocked(confirm).mockResolvedValue(true) + mockPromptConfirm.mockResolvedValue(true) await reset({}, createMockCommand()) @@ -154,7 +164,7 @@ describe('reset', () => { }) test('keeps the data directory when the user declines', async () => { - vi.mocked(confirm).mockResolvedValue(false) + mockPromptConfirm.mockResolvedValue(false) await reset({}, createMockCommand()) @@ -165,7 +175,7 @@ describe('reset', () => { test('discards without prompting when --force is set', async () => { await reset({ force: true }, createMockCommand()) - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(mockRm).toHaveBeenCalledWith(DB_DIRECTORY, { recursive: true, force: true }) }) @@ -186,7 +196,7 @@ describe('reset', () => { test('refuses to prompt when --json is set without --force', async () => { await expect(reset({ json: true }, createMockCommand())).rejects.toThrow('--force') - expect(confirm).not.toHaveBeenCalled() + expect(mockPromptConfirm).not.toHaveBeenCalled() expect(mockRm).not.toHaveBeenCalled() }) diff --git a/tests/unit/commands/sites/sites-create.test.ts b/tests/unit/commands/sites/sites-create.test.ts index 624ff3ada8d..426f70ac579 100644 --- a/tests/unit/commands/sites/sites-create.test.ts +++ b/tests/unit/commands/sites/sites-create.test.ts @@ -4,9 +4,9 @@ const { mockSelect } = vi.hoisted(() => ({ mockSelect: vi.fn(), })) -vi.mock('@inquirer/prompts', () => ({ - input: vi.fn(), - select: mockSelect, +vi.mock('../../../../src/utils/prompts/index.js', () => ({ + promptText: vi.fn(), + promptSelect: mockSelect, })) vi.mock('../../../../src/utils/scripted-commands.js', () => ({ diff --git a/tests/unit/commands/switch/switch.test.ts b/tests/unit/commands/switch/switch.test.ts index 4a67d023544..69d020c499b 100644 --- a/tests/unit/commands/switch/switch.test.ts +++ b/tests/unit/commands/switch/switch.test.ts @@ -1,13 +1,14 @@ import { beforeEach, describe, expect, test, vi } from 'vitest' -const { logMessages, mockSelect, mockLogin } = vi.hoisted(() => ({ +const { logMessages, mockPromptSelect, mockLogin } = vi.hoisted(() => ({ logMessages: [] as string[], - mockSelect: vi.fn(), + mockPromptSelect: vi.fn<(...args: unknown[]) => Promise>(), mockLogin: vi.fn(), })) -vi.mock('@inquirer/prompts', () => ({ - select: mockSelect, +vi.mock('../../../../src/utils/prompts/index.js', async (importOriginal) => ({ + ...(await importOriginal()), + promptSelect: (...args: unknown[]) => mockPromptSelect(...args), })) vi.mock('../../../../src/utils/command-helpers.js', async () => ({ @@ -54,42 +55,42 @@ describe('switchCommand', () => { expect(mockSet).toHaveBeenCalledWith('userId', 'user-1') expect(logMessages.some((m) => m.includes('Alice'))).toBe(true) - expect(mockSelect).not.toHaveBeenCalled() + expect(mockPromptSelect).not.toHaveBeenCalled() }) test('--email falls through to prompt when no match is found', async () => { const { command } = createCommand() - mockSelect.mockResolvedValueOnce('Bob (bob@corp.com)') + mockPromptSelect.mockResolvedValueOnce('Bob (bob@corp.com)') await switchCommand({ email: 'nobody@example.com' }, command) expect(logMessages.some((m) => m.includes('No account found matching'))).toBe(true) - expect(mockSelect).toHaveBeenCalled() + expect(mockPromptSelect).toHaveBeenCalled() }) test('--email does not match partial email strings', async () => { const { command } = createCommand() - mockSelect.mockResolvedValueOnce('Bob (bob@corp.com)') + mockPromptSelect.mockResolvedValueOnce('Bob (bob@corp.com)') await switchCommand({ email: 'bob@corp' }, command) expect(logMessages.some((m) => m.includes('No account found matching'))).toBe(true) - expect(mockSelect).toHaveBeenCalled() + expect(mockPromptSelect).toHaveBeenCalled() }) test('without --email shows interactive prompt', async () => { const { command, mockSet } = createCommand() - mockSelect.mockResolvedValueOnce('Alice (alice@example.com)') + mockPromptSelect.mockResolvedValueOnce('Alice (alice@example.com)') await switchCommand({}, command) - expect(mockSelect).toHaveBeenCalled() + expect(mockPromptSelect).toHaveBeenCalled() expect(mockSet).toHaveBeenCalledWith('userId', 'user-1') }) test('selecting login new triggers login flow', async () => { const { command } = createCommand() - mockSelect.mockResolvedValueOnce('I would like to login to a new account') + mockPromptSelect.mockResolvedValueOnce('I would like to login to a new account') await switchCommand({}, command) diff --git a/tests/unit/lib/secure-storage.test.ts b/tests/unit/lib/secure-storage.test.ts index 14ff8098a7b..24f8e379fe9 100644 --- a/tests/unit/lib/secure-storage.test.ts +++ b/tests/unit/lib/secure-storage.test.ts @@ -35,7 +35,7 @@ vi.mock('@netlify/dev-utils', async () => ({ storeTokenInKeychain: mocks.storeTokenInKeychain, })) -vi.mock('@inquirer/prompts', () => ({ confirm: mocks.confirm })) +vi.mock('../../../src/utils/prompts/index.js', () => ({ promptConfirm: mocks.confirm })) vi.mock('../../../src/utils/scripted-commands.js', () => ({ isInteractive: () => mocks.interactive })) @@ -165,16 +165,6 @@ describe('plaintext token migration', () => { await expect(getStoredAPIToken({})).resolves.toEqual({ token: 'plain-tok', fromKeychain: false }) expect(mocks.confirm).not.toHaveBeenCalled() }) - - test('lets Ctrl+C at the prompt abort the command', async () => { - mocks.interactive = true - mocks.confirm.mockRejectedValue( - Object.assign(new Error('User force closed the prompt'), { name: 'ExitPromptError' }), - ) - const { getStoredAPIToken } = await loadSecureStorage() - - await expect(getStoredAPIToken({})).rejects.toMatchObject({ name: 'ExitPromptError' }) - }) }) describe('writeAuthTokenForStorage', () => { diff --git a/tests/unit/recipes/ai-context/index.test.ts b/tests/unit/recipes/ai-context/index.test.ts index 5638add1733..056f4819ec4 100644 --- a/tests/unit/recipes/ai-context/index.test.ts +++ b/tests/unit/recipes/ai-context/index.test.ts @@ -33,9 +33,9 @@ vi.mock('../../../../src/utils/telemetry/index.js', () => ({ track: vi.fn(), })) -vi.mock('@inquirer/prompts', () => ({ - input: vi.fn(), - select: vi.fn().mockResolvedValue('cursor'), +vi.mock('../../../../src/utils/prompts/index.js', () => ({ + promptSelect: vi.fn().mockResolvedValue('cursor'), + promptText: vi.fn(), })) import { downloadAndWriteContextFiles } from '../../../../src/recipes/ai-context/context.js' diff --git a/tests/unit/utils/init/agent-mcp.test.ts b/tests/unit/utils/init/agent-mcp.test.ts index 98771c846b7..8fc2e32ec57 100644 --- a/tests/unit/utils/init/agent-mcp.test.ts +++ b/tests/unit/utils/init/agent-mcp.test.ts @@ -828,15 +828,6 @@ describe('setupAgentMcp', () => { expect(execaMock).not.toHaveBeenCalled() }) - test('rethrows a cancelled prompt so init stops like any other prompt', async () => { - await install('claude') - const cancelled = Object.assign(new Error('User force closed the prompt'), { name: 'ExitPromptError' }) - - await expect(run({}, { interactive: true, choose: vi.fn(() => Promise.reject(cancelled)) })).rejects.toBe( - cancelled, - ) - }) - test('prints the generic command without a prompt when no terminal is attached', async () => { await install('claude') diff --git a/tests/unit/utils/init/config-manual.test.ts b/tests/unit/utils/init/config-manual.test.ts index e757aa89be2..8a9b2fb462f 100644 --- a/tests/unit/utils/init/config-manual.test.ts +++ b/tests/unit/utils/init/config-manual.test.ts @@ -3,8 +3,8 @@ import type { RepoData } from '../../../../src/utils/get-repo-data.js' import type { NetlifyAPI } from '@netlify/api' import type BaseCommand from '../../../../src/commands/base-command.js' -const mockConfirm = vi.fn() -const mockInput = vi.fn() +const mockPromptConfirm = vi.fn() +const mockPromptText = vi.fn() const mockLog = vi.fn() const mockExit = vi.fn() const mockCreateDeployKey = vi.fn() @@ -12,9 +12,9 @@ const mockGetBuildSettings = vi.fn() const mockSaveNetlifyToml = vi.fn() const mockSetupSite = vi.fn() -vi.mock('@inquirer/prompts', () => ({ - confirm: mockConfirm, - input: mockInput, +vi.mock('../../../../src/utils/prompts/index.js', () => ({ + promptConfirm: mockPromptConfirm, + promptText: mockPromptText, })) vi.mock('../../../../src/utils/command-helpers.js', () => ({ @@ -46,8 +46,8 @@ describe('config-manual', () => { } as BaseCommand['netlify'], } - mockConfirm.mockResolvedValue(true) - mockInput.mockResolvedValue('git@gitlab.com:test/repo.git') + mockPromptConfirm.mockResolvedValue(true) + mockPromptText.mockResolvedValue('git@gitlab.com:test/repo.git') mockCreateDeployKey.mockResolvedValue({ id: 'key-123', public_key: 'ssh-rsa test' }) mockGetBuildSettings.mockResolvedValue({ diff --git a/tests/unit/utils/prompts/prompts.test.ts b/tests/unit/utils/prompts/prompts.test.ts new file mode 100644 index 00000000000..289cf5d3f89 --- /dev/null +++ b/tests/unit/utils/prompts/prompts.test.ts @@ -0,0 +1,283 @@ +// eslint-disable-next-line no-restricted-imports -- tests the wrapper itself +import { CANCEL_SYMBOL } from '@clack/prompts' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +const { mockClack, mockExit } = vi.hoisted(() => ({ + mockClack: { + text: vi.fn(), + password: vi.fn(), + confirm: vi.fn(), + select: vi.fn(), + autocomplete: vi.fn(), + cancel: vi.fn(), + }, + mockExit: vi.fn((code?: number): never => { + throw new Error(`exit(${String(code)})`) + }), +})) + +vi.mock('@clack/prompts', async (importOriginal) => ({ + ...(await importOriginal()), + ...mockClack, +})) + +vi.mock('../../../../src/utils/shell.js', () => ({ + exitAfterCleanup: (code: number) => mockExit(code), +})) + +import { + promptAutocomplete, + promptConfirm, + promptPassword, + promptSelect, + promptText, +} from '../../../../src/utils/prompts/index.js' + +const originalIsTTY = process.stdin.isTTY +const setStdinTTY = (isTTY: boolean | undefined) => { + Object.defineProperty(process.stdin, 'isTTY', { value: isTTY, configurable: true }) +} + +let resumeSpy: ReturnType +let pauseSpy: ReturnType + +beforeEach(() => { + vi.clearAllMocks() + resumeSpy = vi.spyOn(process.stdin, 'resume').mockReturnValue(process.stdin) + pauseSpy = vi.spyOn(process.stdin, 'pause').mockReturnValue(process.stdin) + setStdinTTY(true) +}) + +afterEach(() => { + vi.restoreAllMocks() + setStdinTTY(originalIsTTY) +}) + +describe('promptText', () => { + test('returns the submitted value and forwards options', async () => { + mockClack.text.mockResolvedValue('my-fn') + + await expect(promptText({ message: 'Name your function', placeholder: 'hello' })).resolves.toBe('my-fn') + + expect(mockClack.text.mock.calls[0]?.[0]).toMatchObject({ message: 'Name your function', placeholder: 'hello' }) + }) + + test('shows the default value as the placeholder unless one is given', async () => { + mockClack.text.mockResolvedValue('') + + await promptText({ message: 'Publish directory', defaultValue: '.' }) + await promptText({ message: 'Publish directory', defaultValue: '.', placeholder: 'e.g. dist' }) + + expect(mockClack.text.mock.calls[0]?.[0]).toMatchObject({ placeholder: '.', defaultValue: '.' }) + expect(mockClack.text.mock.calls[1]?.[0]).toMatchObject({ placeholder: 'e.g. dist', defaultValue: '.' }) + }) + + test('validates the default value when the input is left empty', async () => { + const validate = vi.fn((value: string | undefined) => (value ? undefined : 'required')) + mockClack.text.mockResolvedValue('/test') + + await promptText({ message: 'Route', defaultValue: '/test', validate }) + + const forwarded = mockClack.text.mock.calls[0]?.[0] as { validate: (value: string | undefined) => unknown } + expect(forwarded.validate('')).toBeUndefined() + expect(forwarded.validate(undefined)).toBeUndefined() + expect(validate).toHaveBeenLastCalledWith('/test') + + expect(forwarded.validate('/typed')).toBeUndefined() + expect(validate).toHaveBeenLastCalledWith('/typed') + }) + + test('leaves the validator untouched when there is no default value', async () => { + const validate = () => undefined + mockClack.text.mockResolvedValue('x') + + await promptText({ message: 'Anything', validate }) + + expect(mockClack.text.mock.calls[0]?.[0]).toMatchObject({ message: 'Anything', validate }) + }) + + test('prints a cancel message and exits with 130 when the user cancels', async () => { + mockClack.text.mockResolvedValue(CANCEL_SYMBOL) + + await expect(promptText({ message: 'Anything' })).rejects.toThrow('exit(130)') + + expect(mockClack.cancel).toHaveBeenCalledWith('Cancelled.') + expect(mockExit).toHaveBeenCalledWith(130) + }) +}) + +describe('promptConfirm', () => { + test('returns the boolean answer', async () => { + mockClack.confirm.mockResolvedValue(false) + + await expect(promptConfirm({ message: 'Continue?', initialValue: false })).resolves.toBe(false) + }) + + test('treats a prompt left unanswered past its timeout as declining instead of exiting', async () => { + mockClack.confirm.mockImplementation( + ({ signal }: { signal: AbortSignal }) => + new Promise((resolve) => { + signal.addEventListener('abort', () => { + resolve(CANCEL_SYMBOL) + }) + }), + ) + + await expect(promptConfirm({ message: 'Did you mean?', timeout: 5 })).resolves.toBe(false) + + expect(mockClack.cancel).not.toHaveBeenCalled() + expect(mockExit).not.toHaveBeenCalled() + }) + + test('exits when the user cancels a prompt that has a timeout', async () => { + mockClack.confirm.mockResolvedValue(CANCEL_SYMBOL) + + await expect(promptConfirm({ message: 'Did you mean?', timeout: 10_000 })).rejects.toThrow('exit(130)') + + expect(mockClack.cancel).toHaveBeenCalledWith('Cancelled.') + }) + + test('stops the timeout once answered, so the prompt is not closed a second time', async () => { + vi.useFakeTimers() + try { + let abortedAfterAnswer = false + mockClack.confirm.mockImplementation(({ signal }: { signal: AbortSignal }) => { + signal.addEventListener('abort', () => { + abortedAfterAnswer = true + }) + return Promise.resolve(true) + }) + + await expect(promptConfirm({ message: 'Did you mean?', timeout: 10_000 })).resolves.toBe(true) + vi.advanceTimersByTime(60_000) + + expect(abortedAfterAnswer).toBe(false) + } finally { + vi.useRealTimers() + } + }) +}) + +describe('promptSelect, promptAutocomplete, promptPassword', () => { + test('return the chosen value', async () => { + mockClack.select.mockResolvedValue({ id: 1 }) + mockClack.autocomplete.mockResolvedValue('apps/web') + mockClack.password.mockResolvedValue('s3cret') + + await expect(promptSelect({ message: 'Pick', options: [{ value: { id: 1 }, label: 'one' }] })).resolves.toEqual({ + id: 1, + }) + await expect(promptAutocomplete({ message: 'Search', options: [{ value: 'apps/web' }] })).resolves.toBe('apps/web') + await expect(promptPassword({ message: 'Token' })).resolves.toBe('s3cret') + }) + + test.each([ + ['promptSelect', () => promptSelect({ message: 'Pick', options: [{ value: 'a' }] }), mockClack.select], + [ + 'promptAutocomplete', + () => promptAutocomplete({ message: 'Search', options: [{ value: 'a' }] }), + mockClack.autocomplete, + ], + ['promptPassword', () => promptPassword({ message: 'Token' }), mockClack.password], + ])('%s exits with 130 when cancelled', async (_name, run, mock) => { + mock.mockResolvedValue(CANCEL_SYMBOL) + + await expect(run()).rejects.toThrow('exit(130)') + + expect(mockExit).toHaveBeenCalledWith(130) + }) +}) + +describe('promptAutocomplete filtering', () => { + const filterOf = async () => { + mockClack.autocomplete.mockResolvedValue('x') + await promptAutocomplete({ + message: 'Pick a template', + options: [{ value: { name: 'hello-world' }, label: '[hello-world] Basic function', hint: 'starter' }], + }) + const [{ filter }] = mockClack.autocomplete.mock.calls[0] as [ + { filter: (search: string, option: { value: unknown; label?: string; hint?: string }) => boolean }, + ] + return filter + } + + test('matches the label and the hint', async () => { + const filter = await filterOf() + const option = { value: { name: 'hello-world' }, label: '[hello-world] Basic function', hint: 'starter' } + + expect(filter('hello', option)).toBe(true) + expect(filter('BASIC', option)).toBe(true) + expect(filter('starter', option)).toBe(true) + }) + + test('does not match the stringified value, which is the same for every object option', async () => { + const filter = await filterOf() + const option = { value: { name: 'hello-world' }, label: '[hello-world] Basic function' } + + expect(filter('j', option)).toBe(false) + expect(filter('object', option)).toBe(false) + }) + + test('matches a query spanning styled text, which the raw label would break apart', async () => { + const filter = await filterOf() + const styledLabel = "[\u001B[33mGatsby\u001B[39m] 'npm run develop'" + + expect(filter('[gatsby', { value: { name: 'gatsby' }, label: styledLabel })).toBe(true) + }) + + test('lets a caller override the filter', async () => { + const filter = () => true + mockClack.autocomplete.mockResolvedValue('x') + + await promptAutocomplete({ message: 'Pick', options: [{ value: 'a' }], filter }) + + expect(mockClack.autocomplete.mock.calls[0]?.[0]).toMatchObject({ filter }) + }) +}) + +describe('piped stdin', () => { + test('signals a pause after a prompt so a piped stdin does not keep the process alive', async () => { + setStdinTTY(undefined) + mockClack.text.mockResolvedValue('value') + const paused = vi.fn() + process.stdin.on('pause', paused) + + try { + await promptText({ message: 'Anything' }) + + expect(paused).toHaveBeenCalledOnce() + } finally { + process.stdin.off('pause', paused) + } + }) + + test('submits on a line feed, which is what a pipe sends for Enter', async () => { + setStdinTTY(undefined) + const key = { name: 'enter' } + mockClack.text.mockImplementation(() => { + process.stdin.emit('keypress', '\n', key) + return Promise.resolve('value') + }) + + await promptText({ message: 'Anything' }) + + expect(key.name).toBe('return') + }) + + test('leaves a TTY stdin alone', async () => { + setStdinTTY(true) + mockClack.confirm.mockResolvedValue(true) + const paused = vi.fn() + process.stdin.on('pause', paused) + + try { + await promptConfirm({ message: 'Continue?' }) + + expect(paused).not.toHaveBeenCalled() + expect(resumeSpy).not.toHaveBeenCalled() + expect(pauseSpy).not.toHaveBeenCalled() + } finally { + process.stdin.off('pause', paused) + } + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts index 7ef06818b98..d7643bb4fb3 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,9 +2,14 @@ import { defineConfig } from 'vitest/config' export default defineConfig({ test: { - // Spawned CLI processes inherit this, so test runs never send real telemetry or error reports. - env: { NETLIFY_TELEMETRY_DISABLED: 'true' }, include: ['tests/**/*.test.js', 'tests/**/*.test.ts'], + env: { + // Spawned CLI processes inherit this, so test runs never send real telemetry or error reports. + NETLIFY_TELEMETRY_DISABLED: 'true', + // clack draws ASCII glyphs for some terminals (`TERM=linux`, most on Windows); `xterm-256color` + // gets Unicode everywhere, so snapshots don't depend on the recording terminal. + TERM: 'xterm-256color', + }, testTimeout: 90_000, hookTimeout: 90_000, server: { From 895bc1304f37ec140d0f960e6d4070d2f70fbe73 Mon Sep 17 00:00:00 2001 From: Philippe Serhal Date: Fri, 13 Nov 2026 17:02:14 -0500 Subject: [PATCH 13/13] fix: exit 4 instead of hanging when stdin closes mid-prompt A prompt reading from a stdin that had already closed (` => { return exitAfterCleanup(EXIT_CODES.INTERRUPTED) } -const ask = async (prompt: Prompt, timeout?: { after: number; answer: T }): Promise => { +const exitOnClosedInput = async (message: string): Promise => { + logError( + `Input ended before "${stripVTControlCharacters(message)}" was answered. Run this command in an interactive terminal, or pass the value with a flag if it has one.`, + ) + return exitAfterCleanup(EXIT_CODES.NON_INTERACTIVE_PROMPT) +} + +const ask = async (message: string, prompt: Prompt, timeout?: { after: number; answer: T }): Promise => { const controller = new AbortController() + let abortReason: 'timeout' | 'input-ended' | undefined + const abort = (reason: NonNullable) => { + abortReason = reason + controller.abort() + } const timer = timeout && setTimeout(() => { - controller.abort() + abort('timeout') }, timeout.after) + let inputEnded: NodeJS.Immediate | undefined + // clack ignores the end of input, so without this a closed stdin leaves the prompt waiting forever. + // Deferred because `end` can fire before an answer in the same final chunk settles the prompt. + const onInputEnd = () => { + inputEnded = setImmediate(() => { + abort('input-ended') + }) + } const piped = !process.stdin.isTTY if (piped) { process.stdin.prependListener('keypress', treatLineFeedAsEnter) + if (process.stdin.readableEnded) { + onInputEnd() + } else { + process.stdin.once('end', onInputEnd) + } } let value: Cancellable @@ -50,14 +76,17 @@ const ask = async (prompt: Prompt, timeout?: { after: number; answer: T }) // clack never removes its abort listener, so a late abort would close the settled prompt again and // reset the terminal under whatever runs next. clearTimeout(timer) + clearImmediate(inputEnded) if (piped) { process.stdin.removeListener('keypress', treatLineFeedAsEnter) + process.stdin.removeListener('end', onInputEnd) releaseStdin() } } if (!clack.isCancel(value)) return value - if (timeout && controller.signal.aborted) return timeout.answer + if (timeout && abortReason === 'timeout') return timeout.answer + if (abortReason === 'input-ended') return exitOnClosedInput(message) return cancelAndExit() } @@ -79,10 +108,10 @@ const withDefaultValue = (options: clack.TextOptions): clack.TextOptions => { } export const promptText = (options: clack.TextOptions): Promise => - ask((signal) => clack.text({ ...withDefaultValue(options), signal })) + ask(options.message, (signal) => clack.text({ ...withDefaultValue(options), signal })) export const promptPassword = (options: clack.PasswordOptions): Promise => - ask((signal) => clack.password({ ...options, signal })) + ask(options.message, (signal) => clack.password({ ...options, signal })) export type ConfirmOptions = Omit & { /** Treat the prompt as declined when it goes unanswered for this many milliseconds. */ @@ -91,15 +120,16 @@ export type ConfirmOptions = Omit & { export const promptConfirm = ({ timeout, ...options }: ConfirmOptions): Promise => ask( + options.message, (signal) => clack.confirm({ ...options, signal }), timeout === undefined ? undefined : { after: timeout, answer: false }, ) export const promptMultiselect = (options: clack.MultiSelectOptions): Promise => - ask((signal) => clack.multiselect({ ...options, signal })) + ask(options.message, (signal) => clack.multiselect({ ...options, signal })) export const promptSelect = (options: clack.SelectOptions): Promise => - ask((signal) => clack.select({ ...options, signal })) + ask(options.message, (signal) => clack.select({ ...options, signal })) // clack's default filter also matches `String(value)`, so every object option matches "[object Object]", // and it matches the label with its ANSI styling, so a query spanning a colour change never matches. @@ -109,4 +139,4 @@ const matchesLabelOrHint = (search: string, option: clack.Option): .includes(search.toLowerCase()) export const promptAutocomplete = (options: clack.AutocompleteOptions): Promise => - ask((signal) => clack.autocomplete({ filter: matchesLabelOrHint, ...options, signal })) + ask(options.message, (signal) => clack.autocomplete({ filter: matchesLabelOrHint, ...options, signal })) diff --git a/tests/unit/utils/prompts/prompts.test.ts b/tests/unit/utils/prompts/prompts.test.ts index 289cf5d3f89..b9375a4d187 100644 --- a/tests/unit/utils/prompts/prompts.test.ts +++ b/tests/unit/utils/prompts/prompts.test.ts @@ -2,7 +2,8 @@ import { CANCEL_SYMBOL } from '@clack/prompts' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -const { mockClack, mockExit } = vi.hoisted(() => ({ +const { mockClack, mockExit, mockLogError } = vi.hoisted(() => ({ + mockLogError: vi.fn(), mockClack: { text: vi.fn(), password: vi.fn(), @@ -21,6 +22,13 @@ vi.mock('@clack/prompts', async (importOriginal) => ({ ...mockClack, })) +vi.mock('../../../../src/utils/command-helpers.js', async (importOriginal) => ({ + ...(await importOriginal()), + logError: (message: unknown) => { + mockLogError(message) + }, +})) + vi.mock('../../../../src/utils/shell.js', () => ({ exitAfterCleanup: (code: number) => mockExit(code), })) @@ -264,6 +272,41 @@ describe('piped stdin', () => { expect(key.name).toBe('return') }) + test('exits with the non-interactive code instead of hanging when stdin ends unanswered', async () => { + setStdinTTY(undefined) + mockClack.select.mockImplementation( + ({ signal }: { signal: AbortSignal }) => + new Promise((resolve) => { + signal.addEventListener('abort', () => { + resolve(CANCEL_SYMBOL) + }) + process.stdin.emit('end') + }), + ) + + await expect(promptSelect({ message: 'Pick a team', options: [{ value: 'a' }] })).rejects.toThrow('exit(4)') + + expect(mockLogError).toHaveBeenCalledWith(expect.stringContaining('"Pick a team"')) + expect(mockClack.cancel).not.toHaveBeenCalled() + }) + + test('lets an answer in the final chunk win over the end of input that follows it', async () => { + setStdinTTY(undefined) + let aborted = false + mockClack.text.mockImplementation(({ signal }: { signal: AbortSignal }) => { + signal.addEventListener('abort', () => { + aborted = true + }) + process.stdin.emit('end') + return Promise.resolve('last answer') + }) + + await expect(promptText({ message: 'Anything' })).resolves.toBe('last answer') + await new Promise((resolve) => setImmediate(resolve)) + + expect(aborted).toBe(false) + }) + test('leaves a TTY stdin alone', async () => { setStdinTTY(true) mockClack.confirm.mockResolvedValue(true)