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
5 changes: 5 additions & 0 deletions .changeset/json-app-release.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/cli': minor
---

Add typed JSON output to app release.
11 changes: 10 additions & 1 deletion docs-shopify.dev/generated/generated_docs_data_v2.json
Original file line number Diff line number Diff line change
Expand Up @@ -3416,9 +3416,18 @@
"description": "The name of the app configuration.",
"isOptional": true,
"environmentValue": "SHOPIFY_FLAG_APP_CONFIG"
},
{
"filePath": "docs-shopify.dev/commands/interfaces/app-release.interface.ts",
"syntaxKind": "PropertySignature",
"name": "-j, --json",
"value": "''",
"description": "Output the result as JSON. Automatically disables color output.",
"isOptional": true,
"environmentValue": "SHOPIFY_FLAG_JSON"
}
],
"value": "export interface apprelease {\n /**\n * Allows removing extensions and configuration without requiring user confirmation. For CI/CD environments, the recommended flag is --allow-updates. Required in non-interactive environments unless --allow-updates is provided.\n * @environment SHOPIFY_FLAG_ALLOW_DELETES\n */\n '--allow-deletes'?: ''\n\n /**\n * Allows adding and updating extensions and configuration without requiring user confirmation. Recommended option for CI/CD environments. Required in non-interactive environments unless --allow-deletes is provided.\n * @environment SHOPIFY_FLAG_ALLOW_UPDATES\n */\n '--allow-updates'?: ''\n\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias <value>'?: string\n\n /**\n * The Client ID of your app.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id <value>'?: string\n\n /**\n * The name of the app configuration.\n * @environment SHOPIFY_FLAG_APP_CONFIG\n */\n '-c, --config <value>'?: string\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * The path to your app directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path <value>'?: string\n\n /**\n * Reset all your settings.\n * @environment SHOPIFY_FLAG_RESET\n */\n '--reset'?: ''\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n\n /**\n * The name of the app version to release.\n * @environment SHOPIFY_FLAG_VERSION\n */\n '--version <value>': string\n}"
"value": "export interface apprelease {\n /**\n * Allows removing extensions and configuration without requiring user confirmation. For CI/CD environments, the recommended flag is --allow-updates. Required in non-interactive environments unless --allow-updates is provided.\n * @environment SHOPIFY_FLAG_ALLOW_DELETES\n */\n '--allow-deletes'?: ''\n\n /**\n * Allows adding and updating extensions and configuration without requiring user confirmation. Recommended option for CI/CD environments. Required in non-interactive environments unless --allow-deletes is provided.\n * @environment SHOPIFY_FLAG_ALLOW_UPDATES\n */\n '--allow-updates'?: ''\n\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias <value>'?: string\n\n /**\n * The Client ID of your app.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id <value>'?: string\n\n /**\n * The name of the app configuration.\n * @environment SHOPIFY_FLAG_APP_CONFIG\n */\n '-c, --config <value>'?: string\n\n /**\n * Output the result as JSON. Automatically disables color output.\n * @environment SHOPIFY_FLAG_JSON\n */\n '-j, --json'?: ''\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * The path to your app directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path <value>'?: string\n\n /**\n * Reset all your settings.\n * @environment SHOPIFY_FLAG_RESET\n */\n '--reset'?: ''\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n\n /**\n * The name of the app version to release.\n * @environment SHOPIFY_FLAG_VERSION\n */\n '--version <value>': string\n}"
}
},
"appsecuritycheck": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {JsonMapType} from '@shopify/cli-kit/node/toml'
import {TypedDocumentNode as DocumentNode} from '@graphql-typed-document-node/core'

export type AppVersionByTagQueryVariables = Types.Exact<{
appId: Types.Scalars['ID']['input']
versionTag: Types.Scalars['String']['input']
}>

Expand Down Expand Up @@ -37,6 +38,11 @@ export const AppVersionByTag = {
operation: 'query',
name: {kind: 'Name', value: 'AppVersionByTag'},
variableDefinitions: [
{
kind: 'VariableDefinition',
variable: {kind: 'Variable', name: {kind: 'Name', value: 'appId'}},
type: {kind: 'NonNullType', type: {kind: 'NamedType', name: {kind: 'Name', value: 'ID'}}},
},
{
kind: 'VariableDefinition',
variable: {kind: 'Variable', name: {kind: 'Name', value: 'versionTag'}},
Expand All @@ -50,6 +56,11 @@ export const AppVersionByTag = {
kind: 'Field',
name: {kind: 'Name', value: 'versionByTag'},
arguments: [
{
kind: 'Argument',
name: {kind: 'Name', value: 'appId'},
value: {kind: 'Variable', name: {kind: 'Name', value: 'appId'}},
},
{
kind: 'Argument',
name: {kind: 'Name', value: 'tag'},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
query AppVersionByTag($versionTag: String!) {
versionByTag(tag: $versionTag) {
query AppVersionByTag($appId: ID!, $versionTag: String!) {
versionByTag(appId: $appId, tag: $versionTag) {
Comment thread
gonzaloriestra marked this conversation as resolved.
Resolved
...VersionInfo
}
}
242 changes: 242 additions & 0 deletions packages/app/src/cli/commands/app/release.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
import Release from './release.js'
import {release} from '../../services/release.js'
import {linkedAppContext} from '../../services/app-context.js'
import {testAppLinked, testOrganizationApp} from '../../models/app/app.test-data.js'
import {AppManagementClient} from '../../utilities/developer-platform-client/app-management-client.js'
import {appManagementRequestDoc} from '@shopify/cli-kit/node/api/app-management'
import {graphqlRequestDoc} from '@shopify/cli-kit/node/api/graphql'
import {inTemporaryDirectory} from '@shopify/cli-kit/node/fs'
import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output'
import {renderError} from '@shopify/cli-kit/node/ui'
import {outputInfo} from '@shopify/cli-kit/node/output'
import {reportAnalyticsEvent} from '@shopify/cli-kit/node/analytics'
import {Config} from '@oclif/core'
import {dirname, joinPath} from '@shopify/cli-kit/node/path'
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'
import {ClientError} from 'graphql-request'
import {GraphQLError} from 'graphql'
import {fileURLToPath} from 'node:url'

const {rawRequest} = vi.hoisted(() => ({rawRequest: vi.fn()}))

vi.mock('graphql-request', async (importOriginal) => ({
...(await importOriginal<typeof import('graphql-request')>()),
GraphQLClient: class {
requestConfig = {}
rawRequest = rawRequest
},
}))

vi.mock('../../services/release.js')
vi.mock('../../services/app-context.js')
vi.mock('@shopify/cli-kit/node/api/app-management')
vi.mock('@shopify/cli-kit/node/analytics')

const version = {
id: 123,
uuid: 'gid://shopify/Version/123',
versionTag: 'v1',
message: 'Release message',
location: 'https://dev.shopify.com/dashboard/1/apps/1/versions/123',
appModuleVersions: [],
}

const originalExitCode = process.exitCode
afterEach(() => {
process.exitCode = originalExitCode
vi.unstubAllEnvs()
AppManagementClient.resetInstance()
})

describe('app release command', () => {
beforeEach(() => {
vi.mocked(appManagementRequestDoc).mockImplementation((options) =>
graphqlRequestDoc({
...options,
api: 'App Management',
url: 'https://app-management.example/graphql',
preferredBehaviour: 'non-blocking',
}),
)
vi.mocked(linkedAppContext).mockResolvedValue({
app: testAppLinked(),
remoteApp: testOrganizationApp(),
} as Awaited<ReturnType<typeof linkedAppContext>>)
vi.mocked(release).mockResolvedValue({status: 'success', version})
})

test('writes one JSON result and sends diagnostics to stderr', async () => {
vi.mocked(release).mockImplementationOnce(async () => {
outputInfo('Releasing an app version')
return {status: 'success', version}
})
await inTemporaryDirectory(async (tmp) => {
await withCapturedStandardStreams(async ({stdout, stderr}) => {
await runRelease(['--path', tmp, '--version', 'v1', '--json', '--allow-updates'])
expect(JSON.parse(stdout())).toEqual({
status: 'success',
app: {name: 'app1', clientId: 'api-key'},
release: {version: {gid: version.uuid, name: 'v1', message: 'Release message', url: version.location}},
})
expect(JSON.parse(stderr())).toMatchObject({type: 'diagnostic', message: 'Releasing an app version'})
})
})
})

test('release rejection uses one shared error document', async () => {
vi.stubEnv('SHOPIFY_FLAG_JSON', '1')
const userErrors = [{message: 'Release failed.', category: 'validation', details: [], field: ['version']}]
vi.mocked(release).mockResolvedValue({status: 'failed', version, userErrors})
await inTemporaryDirectory(async (tmp) => {
await withCapturedStandardStreams(async ({stdout, stderr}) => {
await expect(runRelease(['--path', tmp, '--version', 'v1', '--json', '--allow-updates'])).rejects.toThrow()
expect(JSON.parse(stdout())).toMatchObject({
error: {type: 'abort', message: "Version couldn't be released.", details: {userErrors}},
})
expect(stderr()).toBe('')
})
})
})

test.each(['json', 'text'])('missing version retains the %s error output', async (format) => {
vi.stubEnv('SHOPIFY_FLAG_JSON', format === 'json' ? '1' : '0')
const {release: releaseService} =
await vi.importActual<typeof import('../../services/release.js')>('../../services/release.js')
vi.mocked(release).mockImplementationOnce(releaseService)
const client = AppManagementClient.getInstance()
client.token = () => Promise.resolve('token')
rawRequest.mockRejectedValueOnce(
new ClientError(
{
status: 200,
headers: new Headers(),
errors: [
new GraphQLError('Query errors', {
path: ['versionByTag'],
extensions: {app_errors: {errors: [{category: 'not_found', message: 'The entity could not be found.'}]}},
}),
],
},
{query: 'query AppVersionByTag { versionByTag { id } }'},
),
)
vi.mocked(linkedAppContext).mockResolvedValueOnce({
app: testAppLinked(),
remoteApp: testOrganizationApp(),
developerPlatformClient: client,
} as unknown as Awaited<ReturnType<typeof linkedAppContext>>)
await inTemporaryDirectory(async (directory) => {
await withCapturedStandardStreams(async ({stdout, stderr}) => {
const argv = ['--path', directory, '--version', 'missing', '--allow-updates']
if (format === 'json') argv.push('--json')
await expect(runRelease(argv)).rejects.toThrow()
expect(reportAnalyticsEvent).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
errorMessage: format === 'json' ? 'Version missing could not be found.' : "Version couldn't be released.",
exitMode: 'expected_error',
}),
)
expect(rawRequest).toHaveBeenCalledWith(expect.stringContaining('versionByTag(appId: $appId'), {
appId: testOrganizationApp().id,
versionTag: 'missing',
})
if (format === 'json') {
expect(JSON.parse(stdout())).toEqual({error: {type: 'abort', message: 'Version missing could not be found.'}})
expect(stderr()).toBe('')
} else {
expect(stdout()).toBe('')
const actualBanner = stderr()
await withCapturedStandardStreams(async ({stderr: expectedStderr}) => {
renderError({
headline: "Version couldn't be released.",
body: ['Version', {userInput: 'missing'}, 'could not be found.'],
})
expect(actualBanner).toBe(expectedStderr())
})
}
})
})
})

test.each([
{status: 503, message: 'Service unavailable'},
{status: 403, message: 'Access denied'},
{status: 404, message: 'Cannot find a valid organization'},
])('preserves the lookup failure in JSON: HTTP $status', async ({status, message}) => {
vi.stubEnv('SHOPIFY_FLAG_JSON', '1')
const {release: releaseService} =
await vi.importActual<typeof import('../../services/release.js')>('../../services/release.js')
vi.mocked(release).mockImplementationOnce(releaseService)
const client = AppManagementClient.getInstance()
client.token = () => Promise.resolve('token')
const releaseRequest = vi.spyOn(client, 'release')
rawRequest.mockRejectedValueOnce(
new ClientError(
{status, headers: new Headers({'x-request-id': 'lookup-request-id'}), errors: [new GraphQLError(message)]},
{query: 'query AppVersionByTag { versionByTag { id } }'},
),
)
vi.mocked(linkedAppContext).mockResolvedValueOnce({
app: testAppLinked(),
remoteApp: testOrganizationApp(),
developerPlatformClient: client,
} as unknown as Awaited<ReturnType<typeof linkedAppContext>>)
await inTemporaryDirectory(async (directory) => {
await withCapturedStandardStreams(async ({stdout, stderr}) => {
await expect(
runRelease([
'--path',
directory,
'--version',
'v1',
'--json',
'--allow-updates',
'--allow-deletes',
'--no-input',
]),
).rejects.toThrow()
const {error} = JSON.parse(stdout())
expect(error).toMatchObject({type: 'abort', message: expect.stringContaining(message)})
expect(error.message).toContain('Request ID: lookup-request-id')
if (status === 403) expect(error.tryMessage).toContain('shopify auth login')
expect(stderr()).toBe('')
expect(releaseRequest).not.toHaveBeenCalled()
})
})
})

test('cancelled JSON runs postrun without an explicit exit', async () => {
vi.mocked(release).mockResolvedValue({status: 'cancelled'})
const exit = vi.spyOn(process, 'exit').mockReturnValue(undefined as never)
try {
await inTemporaryDirectory(async (directory) => {
await withCapturedStandardStreams(async ({stdout, stderr}) => {
const config = await releaseConfig()
const metadata = config.findCommand('app:release')!
vi.spyOn(config, 'findCommand').mockReturnValue({...metadata, id: 'app:release', load: async () => Release})
const hooks = vi.spyOn(config, 'runHook').mockResolvedValue({successes: [], failures: []})
const argv = ['--path', directory, '--version', 'v1', '--json', '--allow-updates']
const result = await config.runCommand('app:release', argv)
expect(result).toEqual({app: testAppLinked()})
expect(hooks).toHaveBeenCalledWith('postrun', {argv, Command: Release, result})
expect(exit).not.toHaveBeenCalled()
expect(JSON.parse(stdout())).toEqual({status: 'cancelled'})
expect(stderr()).toBe('')
})
})
} finally {
exit.mockRestore()
}
})
})

async function runRelease(argv: string[]) {
return Release.run(argv, await releaseConfig())
}

async function releaseConfig() {
const config = await Config.load({root: joinPath(dirname(fileURLToPath(import.meta.url)), '../../../..')})
// The source package is bundled in the installed CLI, not a custom plugin.
config.plugins.delete('@shopify/app')
return config
}
15 changes: 11 additions & 4 deletions packages/app/src/cli/commands/app/release.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {appFlags} from '../../flags.js'
import {release} from '../../services/release.js'
import {appReleaseJsonOutputSchema} from '../../services/release/types.js'
import {renderAppReleaseError, renderAppReleaseResult} from '../../services/release/result.js'
import AppLinkedCommand, {AppLinkedCommandOutput} from '../../utilities/app-linked-command.js'
import {linkedAppContext} from '../../services/app-context.js'
import {Flags} from '@oclif/core'
import {globalFlags} from '@shopify/cli-kit/node/cli'
import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli'
import {addPublicMetadata} from '@shopify/cli-kit/node/metadata'
import type {NonTTYFlagRequirement} from '@shopify/cli-kit/node/base-command'

Expand All @@ -14,11 +16,16 @@ export default class Release extends AppLinkedCommand {

static descriptionWithMarkdown = `Releases an existing app version. Pass the name of the version that you want to release using the \`--version\` flag.`

static get jsonOutputSchema() {
return appReleaseJsonOutputSchema
}

static description = this.descriptionForHelp()

static flags = {
...globalFlags,
...appFlags,
...jsonFlag,
'allow-updates': Flags.boolean({
hidden: false,
description:
Expand Down Expand Up @@ -64,16 +71,16 @@ export default class Release extends AppLinkedCommand {
userProvidedConfigName: flags.config,
})

await release({
const result = await release({
app,
remoteApp,
developerPlatformClient,
force,
allowUpdates,
allowDeletes,
version: flags.version,
})

}).catch((error: unknown) => renderAppReleaseError(error, flags.json ? 'json' : 'text'))
renderAppReleaseResult(result, remoteApp, flags.json ? 'json' : 'text')
return {app}
}
}
Loading
Loading