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/function-json.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/cli': minor
---

Add typed JSON output to `app function` commands
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 @@ -2445,9 +2445,18 @@
"description": "The name of the app configuration.",
"isOptional": true,
"environmentValue": "SHOPIFY_FLAG_APP_CONFIG"
},
{
"filePath": "docs-shopify.dev/commands/interfaces/app-function-typegen.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 appfunctiontypegen {\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 function 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}"
"value": "export interface appfunctiontypegen {\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 function 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}"
}
},
"appgenerateextension": {
Expand Down
145 changes: 145 additions & 0 deletions packages/app/src/cli/commands/app/function/typegen.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import FunctionTypegen from './typegen.js'
import {chooseFunction} from '../../../services/function/common.js'
import {localAppContext} from '../../../services/app-context.js'
import {testApp, testFunctionExtension, testProject} from '../../../models/app/app.test-data.js'
import {functionTypegenJsonOutputSchema} from '../../../services/function/typegen/types.js'
import {Config} from '@oclif/core'
import {afterEach, expect, test, vi} from 'vitest'
import {inTemporaryDirectory, readFile, writeFile} from '@shopify/cli-kit/node/fs'
import {joinPath} from '@shopify/cli-kit/node/path'
import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output'
import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events'
import {ExternalError, AbortError, handler} from '@shopify/cli-kit/node/error'
import {exec} from '@shopify/cli-kit/node/system'
import {packageManagerBinaryCommandForDirectory} from '@shopify/cli-kit/node/node-package-manager'
import {unstyled} from '@shopify/cli-kit/node/output'

// eslint-disable-next-line no-restricted-imports
import {resolve} from 'node:path'

vi.mock('../../../services/app-context.js')
vi.mock('@shopify/cli-kit/node/system', async (importOriginal) => ({
...(await importOriginal<typeof import('@shopify/cli-kit/node/system')>()),
exec: vi.fn(),
}))
vi.mock('@shopify/cli-kit/node/node-package-manager', async (importOriginal) => ({
...(await importOriginal<typeof import('@shopify/cli-kit/node/node-package-manager')>()),
packageManagerBinaryCommandForDirectory: vi.fn(),
}))
vi.mock('../../../services/function/common.js', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../services/function/common.js')>()),
chooseFunction: vi.fn(),
}))
afterEach(() => vi.unstubAllEnvs())

async function command(argv: string[], directory: string, custom = false) {
const app = testApp({directory})
const extension = await testFunctionExtension({dir: directory, entryPath: 'src/index.js'})
if (custom) extension.configuration.build!.typegen_command = 'custom-codegen --target test'
vi.mocked(localAppContext).mockResolvedValue({app, project: testProject(), activeConfig: {} as never})
vi.mocked(chooseFunction).mockResolvedValue(extension)
vi.mocked(packageManagerBinaryCommandForDirectory).mockResolvedValue({
command: 'codegen',
args: ['--config', 'package.json'],
})
return {instance: new FunctionTypegen(argv, await Config.load()), extension, app}
}

test.each([
{custom: true, argv: ['--json', '--no-input']},
{custom: true, argv: ['--json']},
{custom: false, argv: ['--json', '--no-input']},
{custom: false, argv: ['--json']},
{custom: true, argv: ['-jcstaging']},
{custom: false, argv: ['-jcstaging']},
{custom: true, argv: ['-j']},
{custom: false, argv: ['-j']},
])('emits one result and codegen side events: %j', async ({custom, argv}) => {
await inTemporaryDirectory(async (directory) => {
const {instance, extension, app} = await command(argv, directory, custom)
vi.mocked(exec).mockImplementation(async (_command, _args, options) => {
if (options?.stdout && options.stdout !== 'inherit') options.stdout.write('Generating types\n')
if (options?.stderr && options.stderr !== 'inherit') options.stderr.write('Codegen warning\n')
await writeFile(joinPath(directory, 'generated.ts'), 'export type Input = {}\n')
})
await withCapturedStandardStreams(async ({stdout, stderr}) => {
await expect(runWithCommandEventsForCommand(argv, () => instance.run())).resolves.toEqual({app})
expect(JSON.parse(stdout())).toEqual({
status: 'success',
function: {handle: extension.configuration.handle ?? null, name: extension.name, directory: resolve(directory)},
})
const events = stderr()
.trim()
.split('\n')
.map((line) => JSON.parse(line))
expect(events).toContainEqual(
expect.objectContaining({type: 'diagnostic', message: expect.stringContaining('Codegen warning')}),
)
if (custom)
expect(events).toContainEqual(
expect.objectContaining({type: 'diagnostic', message: expect.stringContaining('Generating types')}),
)
expect(stderr()).not.toContain('GraphQL types generated successfully.')
})
await expect(readFile(joinPath(directory, 'generated.ts'))).resolves.toBe('export type Input = {}\n')
expect(exec).toHaveBeenCalledWith(
custom ? 'custom-codegen' : 'codegen',
custom ? ['--target', 'test'] : ['--config', 'package.json'],
expect.objectContaining({cwd: directory}),
)
})
})

test.each([[], ['--no-input']])('keeps custom codegen text output and the success banner: %j', async (...argv) => {
await inTemporaryDirectory(async (directory) => {
const {instance} = await command(argv, directory, true)
vi.mocked(exec).mockImplementation(async (_command, _args, options) => {
if (options?.stdout && options.stdout !== 'inherit') options.stdout.write('Native codegen output\n')
})
await withCapturedStandardStreams(async ({stdout, stderr}) => {
await instance.run()
expect(stdout()).toBe('Native codegen output\n')
expect(unstyled(stderr())).toContain('GraphQL types generated successfully.')
})
})
})

test('emits one fatal document when the custom generator fails', async () => {
vi.stubEnv('SHOPIFY_FLAG_JSON', '1')
await inTemporaryDirectory(async (directory) => {
const {instance} = await command(['--json'], directory, true)
vi.mocked(exec).mockRejectedValue(new ExternalError('Generator failed', 'custom-codegen', []))
await withCapturedStandardStreams(async ({stdout}) => {
await runWithCommandEventsForCommand(instance.argv, async () => {
try {
await instance.run()
expect.unreachable('Expected typegen to fail')
} catch (error) {
if (!(error instanceof ExternalError)) throw error
await handler(error)
}
})
expect(JSON.parse(stdout())).toMatchObject({error: {type: 'external', message: 'Generator failed'}})
expect(stdout()).not.toContain('"status":"success"')
})
})
})

test('keeps the missing custom generator error for non-JavaScript functions', async () => {
await inTemporaryDirectory(async (directory) => {
const {instance, extension} = await command(['--json'], directory)
extension.entrySourceFilePath = 'src/main.rs'
await withCapturedStandardStreams(async ({stdout}) => {
await expect(runWithCommandEventsForCommand(instance.argv, () => instance.run())).rejects.toThrow(AbortError)
expect(stdout()).toBe('')
})
expect(exec).not.toHaveBeenCalled()
})
})

test('exposes the result schema and retains inherited flags', () => {
expect(FunctionTypegen.flags.json).toBeDefined()
expect(FunctionTypegen.flags['no-input']).toBeDefined()
expect(FunctionTypegen.jsonOutputSchema).toBe(functionTypegenJsonOutputSchema)
expect(FunctionTypegen.descriptionForHelp()).toContain('FunctionTypegenResult')
})
31 changes: 26 additions & 5 deletions packages/app/src/cli/commands/app/function/typegen.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import {chooseFunction, functionFlags} from '../../../services/function/common.js'
import {buildGraphqlTypes} from '../../../services/function/build.js'
import {generateFunctionTypes} from '../../../services/function/typegen.js'
import {functionTypegenJsonOutputSchema} from '../../../services/function/typegen/types.js'
import {renderFunctionTypegenResult} from '../../../services/function/typegen/result.js'
import {appFlags} from '../../../flags.js'
import AppUnlinkedCommand, {AppUnlinkedCommandOutput} from '../../../utilities/app-unlinked-command.js'
import {localAppContext} from '../../../services/app-context.js'
import {globalFlags} from '@shopify/cli-kit/node/cli'
import {renderSuccess} from '@shopify/cli-kit/node/ui'
import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli'
import {renderConcurrent} from '@shopify/cli-kit/node/ui'
import {renderCommandEventAsJson, runWithCommandEvents} from '@shopify/cli-kit/node/command-events'
import {Writable} from 'stream'

export default class FunctionTypegen extends AppUnlinkedCommand {
static get jsonOutputSchema() {
return functionTypegenJsonOutputSchema
}

static summary = 'Generate GraphQL types for a function.'

static descriptionWithMarkdown = `Creates GraphQL types based on your [input query](https://shopify.dev/docs/apps/functions/input-output#input) for a function. Supports JavaScript functions out of the box, or any language via the \`build.typegen_command\` configuration.`
Expand All @@ -17,6 +25,7 @@ export default class FunctionTypegen extends AppUnlinkedCommand {
...globalFlags,
...appFlags,
...functionFlags,
...jsonFlag,
Comment thread
gonzaloriestra marked this conversation as resolved.
}

public async run(): Promise<AppUnlinkedCommandOutput> {
Expand All @@ -29,8 +38,20 @@ export default class FunctionTypegen extends AppUnlinkedCommand {

const ourFunction = await chooseFunction(app, flags.path)

await buildGraphqlTypes(ourFunction, {stdout: process.stdout, stderr: process.stderr, app})
renderSuccess({headline: 'GraphQL types generated successfully.'})
const execute = async (stdout: Writable, stderr: Writable) => {
const result = await generateFunctionTypes(ourFunction, {stdout, stderr, app})
renderFunctionTypegenResult(result, flags.json)
}
if (flags.json) {
await runWithCommandEvents({outputMode: 'json', sink: renderCommandEventAsJson}, () =>
renderConcurrent({
processes: [{prefix: ourFunction.localIdentifier, action: execute}],
showTimestamps: false,
}),
)
} else {
await execute(process.stdout, process.stderr)
Comment thread
isaacroldan marked this conversation as resolved.
}

return {app}
}
Expand Down
23 changes: 23 additions & 0 deletions packages/app/src/cli/services/function/typegen.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {generateFunctionTypes} from './typegen.js'
import {buildGraphqlTypes} from './build.js'
import {testApp, testFunctionExtension} from '../../models/app/app.test-data.js'
import {expect, test, vi} from 'vitest'

// eslint-disable-next-line no-restricted-imports
import {resolve} from 'node:path'

vi.mock('./build.js')

test('returns a typed Function identity after generation', async () => {
const extension = await testFunctionExtension()
const options = {app: testApp(), stdout: process.stdout, stderr: process.stderr}
await expect(generateFunctionTypes(extension, options)).resolves.toEqual({
status: 'success',
function: {
handle: extension.configuration.handle ?? null,
name: extension.name,
directory: resolve(extension.directory),
},
})
expect(buildGraphqlTypes).toHaveBeenCalledWith(extension, options)
})
22 changes: 22 additions & 0 deletions packages/app/src/cli/services/function/typegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {buildGraphqlTypes} from './build.js'
import {type FunctionTypegenResult} from './typegen/types.js'
import {type ExtensionBuildOptions} from '../build/extension.js'
import {ExtensionInstance} from '../../models/extensions/extension-instance.js'
import {FunctionConfigType} from '../../models/extensions/specifications/function.js'
// eslint-disable-next-line no-restricted-imports
import {resolve} from 'node:path'

export async function generateFunctionTypes(
extension: ExtensionInstance<FunctionConfigType>,
options: Pick<ExtensionBuildOptions, 'app' | 'stdout' | 'stderr' | 'signal'>,
): Promise<FunctionTypegenResult> {
await buildGraphqlTypes(extension, options)
return {
status: 'success',
function: {
handle: extension.configuration.handle ?? null,
name: extension.name,
directory: resolve(extension.directory),
},
}
}
21 changes: 21 additions & 0 deletions packages/app/src/cli/services/function/typegen/result.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {functionTypegenJsonOutputSchema} from './types.js'
import {expect, test} from 'vitest'

function fixture() {
return {status: 'success' as const, function: {handle: null, name: 'My Function', directory: '/function'}}
}

test.each([
{field: 'directory', value: 'relative/path'},
{field: 'handle', value: 123},
{field: 'unexpected', value: true},
])('rejects invalid Function $field values', ({field, value}) => {
const result = fixture()
expect(() =>
functionTypegenJsonOutputSchema.validate({...result, function: {...result.function, [field]: value}}),
).toThrow()
})

test('rejects unknown root fields', () => {
expect(() => functionTypegenJsonOutputSchema.validate({...fixture(), unexpected: true})).toThrow()
})
8 changes: 8 additions & 0 deletions packages/app/src/cli/services/function/typegen/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {functionTypegenJsonOutputSchema, type FunctionTypegenResult} from './types.js'
import {outputResult} from '@shopify/cli-kit/node/output'
import {renderSuccess} from '@shopify/cli-kit/node/ui'

export function renderFunctionTypegenResult(result: FunctionTypegenResult, json: boolean): void {
if (json) outputResult(functionTypegenJsonOutputSchema.encode(result))
else renderSuccess({headline: 'GraphQL types generated successfully.'})
}
16 changes: 16 additions & 0 deletions packages/app/src/cli/services/function/typegen/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {functionIdentitySchema} from '../types.js'
import {defineJsonOutputSchema, type InferJsonOutputSchema} from '@shopify/cli-kit/node/json-output-schema'
import {zod} from '@shopify/cli-kit/node/schema'

export const functionTypegenJsonOutputSchema = defineJsonOutputSchema({
name: 'FunctionTypegenResult',
schema: zod
.object({
status: zod.literal('success'),
function: functionIdentitySchema,
})
.strict(),
definitions: {Function: functionIdentitySchema},
})

export type FunctionTypegenResult = InferJsonOutputSchema<typeof functionTypegenJsonOutputSchema>
Loading
Loading