Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/json-alert-diagnostics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@shopify/cli-kit': patch
'@shopify/app': patch
'@shopify/store': patch
---

Emit info and warning banners as JSON diagnostics on stderr in JSON mode.
6 changes: 3 additions & 3 deletions docs/cli/json-output.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,9 @@ mode. Inheriting `--json-schema` or enabling `SHOPIFY_FLAG_JSON=1` doesn't conve
bypasses the JSON fatal error path and can leave stdout empty. Put command validation in the command lifecycle and
throw an `AbortError` so CLI Kit can encode the failure.
- In the command event context, `outputInfo`, `outputWarn`, and `outputDebug` use diagnostic events in JSON mode when
using their default logger. Banners such as `renderSuccess` and `renderWarning` still render terminal text to stderr;
they aren't automatically converted to events. Use `emitCommandEvent` from `@shopify/cli-kit/node/command-events`
for diagnostics, and keep human-only banners in the text presenter.
using their default logger. `renderInfo` and `renderWarning` also emit diagnostic events on stderr in JSON mode,
retaining their banners in text mode. Their messages include the alert's body, next steps, references, links, and
custom sections. `renderSuccess` and `renderError` still render terminal text; keep these banners in text presenters.
- Third-party loggers and child processes aren't automatically converted or silenced. Use `jsonOutputEnabled()` from
`@shopify/cli-kit/node/environment` to silence or capture their output in JSON mode. Reserve stdout for the encoded
result or fatal error document, and send diagnostics through the event helpers to stderr.
Expand Down
8 changes: 4 additions & 4 deletions packages/app/src/cli/services/logs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('logs', () => {
})

// Then
expect(outputInfo).toHaveBeenCalledWith('{"message":"Waiting for app logs..."}')
expect(outputInfo).toHaveBeenCalledWith('Waiting for app logs...\n')
expect(spy).toHaveBeenCalled()
})

Expand Down Expand Up @@ -157,7 +157,7 @@ describe('logs', () => {
expectedStoreMap.set('1', 'store-fqdn')
expectedStoreMap.set('2', 'other-fqdn')
expect(outputResult).toHaveBeenCalledWith('{"subscribedToStores":["store-fqdn","other-fqdn"]}')
expect(outputInfo).toHaveBeenCalledWith('{"message":"Waiting for app logs..."}')
expect(outputInfo).toHaveBeenCalledWith('Waiting for app logs...\n')
expect(spy).toHaveBeenCalledWith({
options: {
developerPlatformClient: expect.anything(),
Expand Down Expand Up @@ -212,15 +212,15 @@ describe('logs', () => {
})
})

test('should render custom info box', async () => {
test.each(['text', 'json'] as const)('renders configuration info in %s mode', async (format) => {
// Given
const sources = ['extensions.source']
await setupDevContext(sources)
vi.mocked(fetchStore).mockResolvedValueOnce(testOrganizationStore({shopId: '2', shopDomain: 'other-fqdn'}))

// When
await logs({
format: 'text',
format,
app,
remoteApp,
organization,
Expand Down
48 changes: 18 additions & 30 deletions packages/app/src/cli/services/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,18 @@ export async function logs(commandOptions: LogsOptions) {

if (commandOptions.format === 'json') {
outputResult(JSON.stringify({subscribedToStores: commandOptions.storeFqdns}))
outputInfo(JSON.stringify({message: 'Waiting for app logs...'}))
await renderJsonLogs({
options: {
variables,
developerPlatformClient,
},
pollOptions,
storeNameById: logsConfig.storeNameById,
organizationId: commandOptions.organization.id,
})
} else {
outputInfo('Waiting for app logs...\n')
await renderLogs({
options: {
variables,
developerPlatformClient,
},
pollOptions,
storeNameById: logsConfig.storeNameById,
organizationId: commandOptions.organization.id,
})
}
outputInfo('Waiting for app logs...\n')
const render = commandOptions.format === 'json' ? renderJsonLogs : renderLogs
await render({
options: {
variables,
developerPlatformClient,
},
pollOptions,
storeNameById: logsConfig.storeNameById,
organizationId: commandOptions.organization.id,
})
}

async function prepareForLogs(commandOptions: LogsOptions): Promise<{
Expand All @@ -98,15 +88,13 @@ async function prepareForLogs(commandOptions: LogsOptions): Promise<{
const {app, remoteApp, developerPlatformClient, primaryStore, organization} = commandOptions

const configFile = basename(app.configPath)
if (commandOptions.format === 'text') {
renderAppLogsConfigInfo(
remoteApp.title,
primaryStore.shopDomain,
commandOptions.storeFqdns,
configFile,
organization.businessName,
)
}
renderAppLogsConfigInfo(
remoteApp.title,
primaryStore.shopDomain,
commandOptions.storeFqdns,
configFile,
organization.businessName,
)
const storeNameById = new Map<string, string>()
storeNameById.set(primaryStore.shopId, primaryStore.shopDomain)
if (commandOptions.storeFqdns && commandOptions.storeFqdns.length > 1) {
Expand Down
31 changes: 1 addition & 30 deletions packages/cli-kit/src/private/node/json-error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {tokenItemToString, type Token, type TokenItem} from './ui/components/token-item.js'
import {tokenItemToJsonString, type TokenItem} from './ui/components/token-item.js'
import {FatalErrorType} from '../../public/node/error.js'
import {jsonErrorOutputSchema} from '../../public/node/error/schema.js'
import {outputResult, unstyled} from '../../public/node/output.js'
Expand Down Expand Up @@ -42,35 +42,6 @@ function jsonErrorType(error: FatalErrorLike, external: ExternalCommand | undefi
return 'bug'
}

function tokenToJsonString(token: Token): string {
if (typeof token === 'string') return token

if ('link' in token) {
const {label, url} = token.link
return label && label !== url ? `${label} (${url})` : url
}

if ('list' in token) {
const title = token.list.title ? tokenItemToJsonString(token.list.title).trim() : undefined
const items = token.list.items.map(tokenItemToJsonString).join('; ')
return title ? `${title}${items ? `: ${items}` : ''}` : items
}

return tokenItemToString(token)
}

function tokenItemToJsonString(token: TokenItem): string {
if (!Array.isArray(token)) return tokenToJsonString(token)

return token
.map((item, index) => {
const value = tokenToJsonString(item)
const needsLeadingSpace = index !== 0 && !(typeof item !== 'string' && 'char' in item)
return needsLeadingSpace ? ` ${value}` : value
})
.join('')
}

function jsonTokenItem(token: unknown): string | undefined {
if (token === null || token === undefined) return

Expand Down
54 changes: 40 additions & 14 deletions packages/cli-kit/src/private/node/ui/alert.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {Alert, AlertProps} from './components/Alert.js'
import {tokenItemToJsonString} from './components/token-item.js'
import {renderOnce} from '../ui.js'
import {LogLevel} from '../../../public/node/output.js'
import {commandEventOutputMode} from '../command-event-context.js'
import {LogLevel, outputInfo, outputWarn} from '../../../public/node/output.js'
import React from 'react'

import {RenderOptions} from 'ink'
Expand All @@ -16,19 +18,25 @@ export interface AlertOptions extends AlertProps {
renderOptions?: RenderOptions
}

export function alert({
type,
headline,
body,
nextSteps,
reference,
link,
customSections,
orderedNextSteps = false,
renderOptions,
}: AlertOptions) {
// eslint-disable-next-line prefer-rest-params
const {type: alertType, ..._eventProps} = arguments[0]
export function alert(options: AlertOptions) {
const {
type,
headline,
body,
nextSteps,
reference,
link,
customSections,
orderedNextSteps = false,
renderOptions,
} = options

if ((type === 'info' || type === 'warning') && commandEventOutputMode() === 'json') {
const message = alertMessage(options)
if (type === 'warning') outputWarn(message)
else outputInfo(message)
return message
}

return renderOnce(
<Alert
Expand All @@ -44,3 +52,21 @@ export function alert({
{logLevel: typeToLogLevel[type], renderOptions},
)
}

function alertMessage({headline, body, nextSteps, reference, link, customSections}: AlertProps): string {
const sections = [
headline ? tokenItemToJsonString(headline) : undefined,
body ? tokenItemToJsonString(body) : undefined,
nextSteps?.length ? `Next steps:\n${nextSteps.map(tokenItemToJsonString).join('\n')}` : undefined,
reference?.length ? `Reference:\n${reference.map(tokenItemToJsonString).join('\n')}` : undefined,
link ? tokenItemToJsonString({link}) : undefined,
...(customSections ?? []).map((section) => {
const content =
typeof section.body === 'object' && 'tabularData' in section.body
? section.body.tabularData.map((row) => row.map(tokenItemToJsonString).join('\t')).join('\n')
: tokenItemToJsonString(section.body)
return section.title ? `${section.title}:\n${content}` : content
}),
]
return sections.filter((section): section is string => section !== undefined).join('\n\n')
}
30 changes: 30 additions & 0 deletions packages/cli-kit/src/private/node/ui/components/token-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,33 @@ export function tokenItemToString(token: TokenItem): string {
export function appendToTokenItem(token: TokenItem, suffix: string): TokenItem {
return Array.isArray(token) ? [...token, {char: suffix}] : [token, {char: suffix}]
}

/** Converts tokens to JSON message text, retaining link URLs and list titles. */
export function tokenItemToJsonString(token: TokenItem): string {
if (!Array.isArray(token)) return tokenToJsonString(token)

return token
.map((item, index) => {
const value = tokenToJsonString(item)
const needsLeadingSpace = index !== 0 && !(typeof item !== 'string' && 'char' in item)
return needsLeadingSpace ? ` ${value}` : value
})
.join('')
}

function tokenToJsonString(token: Token): string {
if (typeof token === 'string') return token

if ('link' in token) {
const {label, url} = token.link
return label && label !== url ? `${label} (${url})` : url
}

if ('list' in token) {
const title = token.list.title ? tokenItemToJsonString(token.list.title).trim() : undefined
const items = token.list.items.map(tokenItemToJsonString).join('; ')
return title ? `${title}${items ? `: ${items}` : ''}` : items
}

return tokenItemToString(token)
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import {showMultipleCLIWarningIfNeeded} from './multiple-installation-warning.js'
import {jsonOutputEnabled} from './environment.js'
import {currentProcessIsGlobal} from './is-global.js'
import {renderInfo} from './ui.js'
import {globalCLIVersion, localCLIVersion} from './version.js'
import {runAtMinimumInterval} from '../../private/node/conf-store.js'
import {describe, expect, test, vi, beforeEach} from 'vitest'

vi.mock('./environment.js')
vi.mock('./is-global.js')
vi.mock('./ui.js')
vi.mock('./version.js')
Expand All @@ -18,7 +16,6 @@ describe('showMultipleCLIWarningIfNeeded', () => {
await task()
return true
})
vi.mocked(jsonOutputEnabled).mockReturnValue(false)
vi.mocked(currentProcessIsGlobal).mockReturnValue(false)
vi.mocked(globalCLIVersion).mockResolvedValue('3.68.0')
vi.mocked(localCLIVersion).mockResolvedValue('3.68.0')
Expand All @@ -35,18 +32,6 @@ describe('showMultipleCLIWarningIfNeeded', () => {
expect(renderInfo).not.toHaveBeenCalled()
})

test('does not run if json output is enabled', async () => {
// Given
vi.mocked(jsonOutputEnabled).mockReturnValue(true)
const dependencies = {'@shopify/cli': '3.68.0'}

// When
await showMultipleCLIWarningIfNeeded('dir', dependencies)

// Then
expect(renderInfo).not.toHaveBeenCalled()
})

test('does not run if global CLIVersion is not available and not in global process', async () => {
// Given
vi.mocked(globalCLIVersion).mockResolvedValue(undefined)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {jsonOutputEnabled} from './environment.js'
import {currentProcessIsGlobal} from './is-global.js'
import {renderInfo} from './ui.js'
import {globalCLIVersion, localCLIVersion} from './version.js'
Expand All @@ -7,7 +6,7 @@ import {runAtMinimumInterval} from '../../private/node/conf-store.js'

/**
* Shows a warning if there are two Shopify CLI installations found (global and local).
* Won't show anything if the user included the --json flag.
* Emits a diagnostic on stderr in JSON mode.
*
* @param directory - The directory of the project.
* @param dependencies - The dependencies of the project.
Expand All @@ -18,7 +17,7 @@ export async function showMultipleCLIWarningIfNeeded(
): Promise<void> {
// Show the warning only once per day
await runAtMinimumInterval('warn-on-multiple-versions', {days: 1}, async () => {
if (!dependencies['@shopify/cli'] || jsonOutputEnabled()) return
if (!dependencies['@shopify/cli']) return

const isGlobal = currentProcessIsGlobal()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {clearCache} from '../cli.js'
import {currentProcessIsGlobal} from '../is-global.js'
import {showMultipleCLIWarningIfNeeded} from '../multiple-installation-warning.js'
import {mockAndCaptureOutput} from '../testing/output.js'
import {mockAndCaptureOutput, withCapturedStandardStreams} from '../testing/output.js'
import {runWithCommandEventsForCommand} from '../command-events.js'
import {globalCLIVersion, localCLIVersion} from '../version.js'
import {CLI_KIT_VERSION} from '../../common/version.js'
import {describe, beforeEach, test, vi, expect} from 'vitest'
Expand Down Expand Up @@ -45,6 +46,25 @@ describe('showMultipleCLIWarningIfNeeded', () => {
mockOutput.clear()
})

test('emits the installation warning as a JSON diagnostic on stderr', async () => {
vi.mocked(currentProcessIsGlobal).mockReturnValue(true)
vi.mocked(localCLIVersion).mockResolvedValue('3.70.0')

await withCapturedStandardStreams(async ({stdout, stderr}) => {
await runWithCommandEventsForCommand(['--json'], () =>
showMultipleCLIWarningIfNeeded('path', {'@shopify/cli': '3.70.0'}),
)

expect(stdout()).toBe('')
expect(JSON.parse(stderr())).toMatchObject({
type: 'diagnostic',
level: 'info',
message: expect.stringContaining('Two Shopify CLI installations found'),
})
expect(JSON.parse(stderr()).message).toContain('https://shopify.dev/docs/apps/build/cli-for-apps')
})
})

test('shows warning if using local CLI but app has global dependency', async () => {
// Given
vi.mocked(currentProcessIsGlobal).mockReturnValue(false)
Expand Down
Loading
Loading