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/app-config-validate-client-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/app': patch
---

Allow `app config validate` to target configs by client ID and report the validated configuration.
46 changes: 46 additions & 0 deletions packages/app/src/cli/commands/app/config/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ function mockHealthyProject() {
}

describe('app config validate command', () => {
test('keeps --client-id mutually exclusive with --config', () => {
expect(Validate.flags['client-id']?.exclusive).toEqual(['config'])
})

test('calls validateApp with json: false by default', async () => {
const app = testAppLinked()
mockHealthyProject()
Expand Down Expand Up @@ -72,6 +76,48 @@ describe('app config validate command', () => {
await expectValidationMetadataCalls({cmd_app_validate_json: true})
})

test('skips active config prompts when --client-id is passed', async () => {
const app = testAppLinked()
mockHealthyProject()
vi.mocked(selectActiveConfig).mockResolvedValue({
file: new TomlFile('shopify.app.staging.toml', {}),
} as any)
vi.mocked(linkedAppContext).mockResolvedValue({app} as Awaited<ReturnType<typeof linkedAppContext>>)
vi.mocked(validateApp).mockResolvedValue()

await Validate.run(['--client-id', 'api-key'], import.meta.url)

expect(selectActiveConfig).toHaveBeenCalledWith(expect.anything(), undefined, {
clientId: 'api-key',
skipPrompts: true,
})
expect(linkedAppContext).toHaveBeenCalledWith({
directory: expect.any(String),
clientId: 'api-key',
forceRelink: false,
userProvidedConfigName: 'shopify.app.staging.toml',
unsafeTolerateErrors: true,
})
expect(validateApp).toHaveBeenCalledWith(app, {json: false})
await expectValidationMetadataCalls({cmd_app_validate_json: false})
})

test('keeps active config prompts enabled when --client-id is not passed', async () => {
const app = testAppLinked()
mockHealthyProject()
vi.mocked(linkedAppContext).mockResolvedValue({app} as Awaited<ReturnType<typeof linkedAppContext>>)
vi.mocked(validateApp).mockResolvedValue()

await Validate.run([], import.meta.url)

expect(selectActiveConfig).toHaveBeenCalledWith(expect.anything(), undefined, {
clientId: undefined,
skipPrompts: false,
})
expect(validateApp).toHaveBeenCalledWith(app, {json: false})
await expectValidationMetadataCalls({cmd_app_validate_json: false})
})

test('outputs JSON issues when active config has TOML parse errors', async () => {
vi.mocked(Project.load).mockResolvedValue({errors: []} as unknown as Project)
vi.mocked(selectActiveConfig).mockResolvedValue({file: new TomlFile('shopify.app.toml', {})} as any)
Expand Down
8 changes: 6 additions & 2 deletions packages/app/src/cli/commands/app/config/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import metadata from '../../../metadata.js'
import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli'
import {AbortError, AbortSilentError} from '@shopify/cli-kit/node/error'
import {outputResult, stringifyMessage, unstyled} from '@shopify/cli-kit/node/output'
import {basename} from '@shopify/cli-kit/node/path'
import {renderError} from '@shopify/cli-kit/node/ui'

async function recordValidationFailure(issueCount: number, fileCount: number) {
Expand Down Expand Up @@ -56,7 +57,10 @@ export default class Validate extends AppLinkedCommand {
// Stage 2: Select active config and check for TOML parse errors scoped to it
let activeConfig
try {
activeConfig = await selectActiveConfig(project, flags.config)
activeConfig = await selectActiveConfig(project, flags.config, {
clientId: flags['client-id'],
skipPrompts: Boolean(flags['client-id']),
})
} catch (err) {
if (err instanceof AbortError && flags.json) {
await recordValidationFailure(1, 1)
Expand Down Expand Up @@ -90,7 +94,7 @@ export default class Validate extends AppLinkedCommand {
directory: flags.path,
clientId: flags['client-id'],
forceRelink: flags.reset,
userProvidedConfigName: flags.config,
userProvidedConfigName: flags.config ?? (flags['client-id'] ? basename(activeConfig.file.path) : undefined),
unsafeTolerateErrors: true,
})
app = context.app
Expand Down
48 changes: 48 additions & 0 deletions packages/app/src/cli/models/project/active-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,54 @@ describe('selectActiveConfig', () => {
})
})

test('selects config by client ID when cached config is stale and prompts are skipped', async () => {
await inTemporaryDirectory(async (dir) => {
await writeFile(joinPath(dir, 'shopify.app.2.toml'), 'client_id = "matching-client-id"')
await writeFile(joinPath(dir, 'shopify.app.3.toml'), 'client_id = "other-client-id"')
const project = await Project.load(dir)

vi.mocked(getCachedAppInfo).mockReturnValue({
directory: dir,
configFile: 'shopify.app.toml',
})

const config = await selectActiveConfig(project, undefined, {
clientId: 'matching-client-id',
skipPrompts: true,
})

expect(basename(config.file.path)).toBe('shopify.app.2.toml')
expect(config.file.content.client_id).toBe('matching-client-id')
expect(config.source).toBe('flag')
})
})

test('throws when no config matches the client ID', async () => {
await inTemporaryDirectory(async (dir) => {
await writeFile(joinPath(dir, 'shopify.app.toml'), 'client_id = "other-client-id"')
const project = await Project.load(dir)

await expect(selectActiveConfig(project, undefined, {clientId: 'missing-client-id'})).rejects.toThrow(
"The specified client ID couldn't be found in any TOML file, or the matching TOML file is malformed.",
)
})
})

test('throws when the config for the client ID is malformed', async () => {
await inTemporaryDirectory(async (dir) => {
await writeFile(joinPath(dir, 'shopify.app.toml'), 'client_id = "other-client-id"')
await writeFile(
joinPath(dir, 'shopify.app.malformed.toml'),
'client_id = "requested-client-id"\nembedded = invalid',
)
const project = await Project.load(dir)

await expect(selectActiveConfig(project, undefined, {clientId: 'requested-client-id'})).rejects.toThrow(
"The specified client ID couldn't be found in any TOML file, or the matching TOML file is malformed.",
)
})
})

test('falls back to default shopify.app.toml when no flag or cache', async () => {
await inTemporaryDirectory(async (dir) => {
await writeFile(joinPath(dir, 'shopify.app.toml'), 'client_id = "default-id"')
Expand Down
24 changes: 18 additions & 6 deletions packages/app/src/cli/models/project/active-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ export interface ActiveConfig {
*
* Resolution priority:
* 1. userProvidedConfigName (from --config flag)
* 2. Cached selection (from `app config use`)
* 3. Default (shopify.app.toml)
* 2. clientId (from --client-id flag)
* 3. Cached selection (from `app config use`)
* 4. Default (shopify.app.toml)
*
* If the cached config file no longer exists on disk, prompts the user
* to select a new one via `app config use`.
Expand All @@ -56,9 +57,10 @@ export interface ActiveConfig {
export async function selectActiveConfig(
project: Project,
userProvidedConfigName?: string,
options?: {skipPrompts?: boolean},
options?: {clientId?: string; skipPrompts?: boolean},
): Promise<ActiveConfig> {
let configName = userProvidedConfigName
const clientIdConfig = options?.clientId ? project.appConfigByClientId(options.clientId) : undefined

// Check cache for previously selected config
const cachedConfigName = getCachedAppInfo(project.directory)?.configFile
Expand All @@ -76,21 +78,31 @@ export async function selectActiveConfig(
configName = await use({directory: project.directory, warningContent, shouldRenderSuccess: false})
}

if (!configName && clientIdConfig) {
return buildActiveConfig(project, clientIdConfig, 'flag')
}

if (!configName && options?.clientId) {
throw new AbortError(
"The specified client ID couldn't be found in any TOML file, or the matching TOML file is malformed.",
)
}

// Don't fall back to stale cached name — it points to a non-existent file
configName = configName ?? (cacheIsStale ? undefined : cachedConfigName)
const resolvedConfigName = configName ?? (cacheIsStale ? undefined : cachedConfigName)

// Determine source after resolution so it reflects the actual selection path
let source: ConfigSource
if (userProvidedConfigName) {
source = 'flag'
} else if (configName) {
} else if (resolvedConfigName) {
source = 'cached'
} else {
source = 'default'
}

// Resolve the config file name and look it up in the project's pre-loaded files
const configurationFileName = getAppConfigurationFileName(configName)
const configurationFileName = getAppConfigurationFileName(resolvedConfigName)
const file = project.appConfigByName(configurationFileName)
if (!file) {
throw new AbortError(
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/cli/services/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ describe('validateApp', () => {
test('renders success when there are no errors', async () => {
const app = testAppLinked()
await validateApp(app)
expect(renderSuccess).toHaveBeenCalledWith({headline: 'App configuration is valid.'})
expect(renderSuccess).toHaveBeenCalledWith({headline: "App configuration 'shopify.app.toml' is valid."})
expect(renderError).not.toHaveBeenCalled()
expect(outputResult).not.toHaveBeenCalled()
await expectLastValidationMetadata({
Expand Down Expand Up @@ -197,7 +197,7 @@ describe('validateApp', () => {
const app = testAppLinked()
app.errors = errors
await validateApp(app)
expect(renderSuccess).toHaveBeenCalledWith({headline: 'App configuration is valid.'})
expect(renderSuccess).toHaveBeenCalledWith({headline: "App configuration 'shopify.app.toml' is valid."})
expect(outputResult).not.toHaveBeenCalled()
})

Expand Down
3 changes: 2 additions & 1 deletion packages/app/src/cli/services/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import metadata from '../metadata.js'
import {outputResult} from '@shopify/cli-kit/node/output'
import {renderError, renderSuccess} from '@shopify/cli-kit/node/ui'
import {AbortSilentError} from '@shopify/cli-kit/node/error'
import {basename} from '@shopify/cli-kit/node/path'

interface ValidateAppOptions {
json: boolean
Expand All @@ -30,7 +31,7 @@ export async function validateApp(app: AppLinkedInterface, options: ValidateAppO
return
}

renderSuccess({headline: 'App configuration is valid.'})
renderSuccess({headline: `App configuration '${basename(app.configPath)}' is valid.`})
return
}

Expand Down
Loading