From 1f370d01cf7fd410b3d282fd02d10ef602bae6ee Mon Sep 17 00:00:00 2001 From: Gonzalo Riestra Date: Thu, 24 Sep 2026 11:23:20 +0200 Subject: [PATCH] Add typed JSON output to theme preview --- .../generated/generated_docs_data_v2.json | 20 ++-- packages/cli/README.md | 35 +++++- packages/cli/oclif.manifest.json | 4 +- .../rules/json-output-command-exceptions.js | 1 - .../src/cli/commands/theme/preview.test.ts | 89 +++++++++++--- .../theme/src/cli/commands/theme/preview.ts | 20 +++- .../src/cli/services/dev-override.test.ts | 113 +++--------------- .../theme/src/cli/services/dev-override.ts | 35 +----- .../cli/services/dev-override/codec.test.ts | 25 ++++ .../src/cli/services/dev-override/codec.ts | 6 + .../cli/services/dev-override/result.test.ts | 66 ++++++++++ .../src/cli/services/dev-override/result.ts | 33 +++++ .../src/cli/services/dev-override/types.ts | 12 ++ 13 files changed, 299 insertions(+), 160 deletions(-) create mode 100644 packages/theme/src/cli/services/dev-override/codec.test.ts create mode 100644 packages/theme/src/cli/services/dev-override/codec.ts create mode 100644 packages/theme/src/cli/services/dev-override/result.test.ts create mode 100644 packages/theme/src/cli/services/dev-override/result.ts create mode 100644 packages/theme/src/cli/services/dev-override/types.ts diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index 2b142950461..b1fcb9fd440 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -8291,15 +8291,6 @@ "isOptional": true, "environmentValue": "SHOPIFY_FLAG_AUTH_ALIAS" }, - { - "filePath": "docs-shopify.dev/commands/interfaces/theme-preview.interface.ts", - "syntaxKind": "PropertySignature", - "name": "--json", - "value": "''", - "description": "Output the preview URL and identifier as JSON.", - "isOptional": true, - "environmentValue": "SHOPIFY_FLAG_JSON" - }, { "filePath": "docs-shopify.dev/commands/interfaces/theme-preview.interface.ts", "syntaxKind": "PropertySignature", @@ -8380,6 +8371,15 @@ "isOptional": true, "environmentValue": "SHOPIFY_FLAG_ENVIRONMENT" }, + { + "filePath": "docs-shopify.dev/commands/interfaces/theme-preview.interface.ts", + "syntaxKind": "PropertySignature", + "name": "-j, --json", + "value": "''", + "description": "Output the preview URL and identifier as JSON.", + "isOptional": true, + "environmentValue": "SHOPIFY_FLAG_JSON" + }, { "filePath": "docs-shopify.dev/commands/interfaces/theme-preview.interface.ts", "syntaxKind": "PropertySignature", @@ -8398,7 +8398,7 @@ "environmentValue": "SHOPIFY_FLAG_THEME_ID" } ], - "value": "export interface themepreview {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The environment to apply to the current command.\n * @environment SHOPIFY_FLAG_ENVIRONMENT\n */\n '-e, --environment '?: string\n\n /**\n * Output the preview URL and identifier as JSON.\n * @environment SHOPIFY_FLAG_JSON\n */\n '--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 * Automatically launch the theme preview in your default web browser.\n * @environment SHOPIFY_FLAG_OPEN\n */\n '--open'?: ''\n\n /**\n * Path to a JSON overrides file.\n * @environment SHOPIFY_FLAG_OVERRIDES\n */\n '--overrides ': string\n\n /**\n * Password generated from the Theme Access app or an Admin API token.\n * @environment SHOPIFY_CLI_THEME_TOKEN\n */\n '--password '?: string\n\n /**\n * The path where you want to run the command. Defaults to the current working directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * An existing preview identifier to update instead of creating a new preview.\n * @environment SHOPIFY_FLAG_PREVIEW_ID\n */\n '--preview-id '?: string\n\n /**\n * Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com).\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Theme ID or name of the remote theme.\n * @environment SHOPIFY_FLAG_THEME_ID\n */\n '-t, --theme ': string\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 themepreview {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The environment to apply to the current command.\n * @environment SHOPIFY_FLAG_ENVIRONMENT\n */\n '-e, --environment '?: string\n\n /**\n * Output the preview URL and identifier as JSON.\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 * Automatically launch the theme preview in your default web browser.\n * @environment SHOPIFY_FLAG_OPEN\n */\n '--open'?: ''\n\n /**\n * Path to a JSON overrides file.\n * @environment SHOPIFY_FLAG_OVERRIDES\n */\n '--overrides ': string\n\n /**\n * Password generated from the Theme Access app or an Admin API token.\n * @environment SHOPIFY_CLI_THEME_TOKEN\n */\n '--password '?: string\n\n /**\n * The path where you want to run the command. Defaults to the current working directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * An existing preview identifier to update instead of creating a new preview.\n * @environment SHOPIFY_FLAG_PREVIEW_ID\n */\n '--preview-id '?: string\n\n /**\n * Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com).\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Theme ID or name of the remote theme.\n * @environment SHOPIFY_FLAG_THEME_ID\n */\n '-t, --theme ': string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, "themeprofile": { diff --git a/packages/cli/README.md b/packages/cli/README.md index b187342c879..80748ac75ce 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -8811,7 +8811,7 @@ Applies JSON overrides to a theme and returns a preview URL. ``` USAGE - $ shopify theme preview --overrides -t [--auth-alias ] [-e ...] [--json] + $ shopify theme preview --overrides -t [--auth-alias ] [-e ...] [-j] [--json-schema] [--no-color] [--open] [--password ] [--path ] [--preview-id ] [-s ] [--verbose] @@ -8820,6 +8820,10 @@ FLAGS The environment to apply to the current command. [env: SHOPIFY_FLAG_ENVIRONMENT] + -j, --json + Output the preview URL and identifier as JSON. + [env: SHOPIFY_FLAG_JSON] + -s, --store= Store URL. It can be the store prefix (example) or the full myshopify.com URL (example.myshopify.com, https://example.myshopify.com). @@ -8833,10 +8837,6 @@ FLAGS Alias of the Shopify account to use for authentication. [env: SHOPIFY_FLAG_AUTH_ALIAS] - --json - Output the preview URL and identifier as JSON. - [env: SHOPIFY_FLAG_JSON] - --json-schema Print the command's JSON schemas. [env: SHOPIFY_FLAG_JSON_SCHEMA] @@ -8876,6 +8876,31 @@ DESCRIPTION The command returns a preview URL and a preview identifier. You can reuse the preview identifier with `--preview-id` to update an existing preview instead of creating a new one. + + Use `--json-schema` to print the result, error, and event schemas. + + Output from `--json` conforms to the `ThemePreviewResult` schema. + + ```json + { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "preview_identifier": { + "type": "string" + } + }, + "required": [ + "url", + "preview_identifier" + ], + "additionalProperties": false, + "title": "ThemePreviewResult", + "$schema": "http://json-schema.org/draft-07/schema#" + } + ``` ``` ## `shopify theme profile` diff --git a/packages/cli/oclif.manifest.json b/packages/cli/oclif.manifest.json index c7f9686e409..743dc1502ac 100644 --- a/packages/cli/oclif.manifest.json +++ b/packages/cli/oclif.manifest.json @@ -10805,7 +10805,7 @@ "args": { }, "customPluginName": "@shopify/theme", - "description": "Applies a JSON overrides file to a theme and creates or updates a preview. This lets you quickly preview changes.\n\n The command returns a preview URL and a preview identifier. You can reuse the preview identifier with `--preview-id` to update an existing preview instead of creating a new one.", + "description": "Applies a JSON overrides file to a theme and creates or updates a preview. This lets you quickly preview changes.\n\n The command returns a preview URL and a preview identifier. You can reuse the preview identifier with `--preview-id` to update an existing preview instead of creating a new one.\n\nUse `--json-schema` to print the result, error, and event schemas.\n\nOutput from `--json` conforms to the `ThemePreviewResult` schema.\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"url\": {\n \"type\": \"string\"\n },\n \"preview_identifier\": {\n \"type\": \"string\"\n }\n },\n \"required\": [\n \"url\",\n \"preview_identifier\"\n ],\n \"additionalProperties\": false,\n \"title\": \"ThemePreviewResult\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n}\n```", "descriptionWithMarkdown": "Applies a JSON overrides file to a theme and creates or updates a preview. This lets you quickly preview changes.\n\n The command returns a preview URL and a preview identifier. You can reuse the preview identifier with `--preview-id` to update an existing preview instead of creating a new one.", "enableJsonFlag": false, "flags": { @@ -10828,8 +10828,10 @@ }, "json": { "allowNo": false, + "char": "j", "description": "Output the preview URL and identifier as JSON.", "env": "SHOPIFY_FLAG_JSON", + "hidden": false, "name": "json", "type": "boolean" }, diff --git a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js index fb7a06d6430..7c092b1483d 100644 --- a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js +++ b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js @@ -47,7 +47,6 @@ const commandExceptions = [ 'packages/theme/src/cli/commands/theme/init.ts', 'packages/theme/src/cli/commands/theme/metafields/pull.ts', 'packages/theme/src/cli/commands/theme/package.ts', - 'packages/theme/src/cli/commands/theme/preview.ts', 'packages/theme/src/cli/commands/theme/profile.ts', // Streaming commands without a single finite result. diff --git a/packages/theme/src/cli/commands/theme/preview.test.ts b/packages/theme/src/cli/commands/theme/preview.test.ts index c0076dcef95..64438afc51c 100644 --- a/packages/theme/src/cli/commands/theme/preview.test.ts +++ b/packages/theme/src/cli/commands/theme/preview.test.ts @@ -1,13 +1,23 @@ import Preview from './preview.js' +import {themePreviewJsonOutputSchema} from '../../services/dev-override/types.js' import {devWithOverrideFile} from '../../services/dev-override.js' import {findOrSelectTheme} from '../../utilities/theme-selector.js' import {ensureThemeStore} from '../../utilities/theme-store.js' +import {openURL} from '@shopify/cli-kit/node/system' +import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events' +import {renderSuccess} from '@shopify/cli-kit/node/ui' import {buildTheme} from '@shopify/cli-kit/node/themes/factories' import {recordEvent} from '@shopify/cli-kit/node/analytics' import {ensureAuthenticatedThemes} from '@shopify/cli-kit/node/session' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' import {Config} from '@oclif/core' import {describe, vi, expect, test, beforeEach} from 'vitest' +vi.mock('@shopify/cli-kit/node/ui') +vi.mock('@shopify/cli-kit/node/system', async (importOriginal) => ({ + ...(await importOriginal()), + openURL: vi.fn(), +})) vi.mock('@shopify/cli-kit/node/session') vi.mock('@shopify/cli-kit/node/analytics', () => ({ recordEvent: vi.fn(), @@ -24,6 +34,8 @@ vi.mock('../../utilities/theme-store.js') const CommandConfig = new Config({root: __dirname}) +const result = {url: 'https://abc123.shopifypreview.com', preview_identifier: 'abc123'} + const adminSession = {token: 'test-token', storeFqdn: 'test-store.myshopify.com'} const namedTheme = buildTheme({id: 2, name: 'My Theme', role: 'unpublished'})! @@ -38,7 +50,7 @@ describe('Preview', () => { vi.mocked(ensureThemeStore).mockReturnValue('test-store.myshopify.com') vi.mocked(ensureAuthenticatedThemes).mockResolvedValue(adminSession) vi.mocked(findOrSelectTheme).mockResolvedValue(namedTheme) - vi.mocked(devWithOverrideFile).mockResolvedValue(undefined) + vi.mocked(devWithOverrideFile).mockResolvedValue(result) }) test('calls devWithOverrideFile with minimum options passed into the command', async () => { @@ -52,7 +64,6 @@ describe('Preview', () => { adminSession, overrideJson: '/path/to/overrides.json', themeId: expectedTheme.id.toString(), - open: false, }), ) }) @@ -71,16 +82,18 @@ describe('Preview', () => { ) }) - test('passes --open to devWithOverrideFile when provided', async () => { + test('opens the resulting preview when requested', async () => { + vi.mocked(openURL).mockResolvedValue(true) const expectedTheme = buildTheme({id: 5, name: 'Expected Theme', role: 'unpublished'})! vi.mocked(findOrSelectTheme).mockResolvedValue(expectedTheme) await run(['--overrides=/path/to/overrides.json', `--theme=${expectedTheme.id}`, '--open']) + expect(openURL).toHaveBeenCalledWith(result.url) + expect(devWithOverrideFile).toHaveBeenCalledWith( expect.objectContaining({ themeId: expectedTheme.id.toString(), - open: true, }), ) }) @@ -108,17 +121,65 @@ describe('Preview', () => { ) }) - test('passes --json to devWithOverrideFile when provided', async () => { - const expectedTheme = buildTheme({id: 5, name: 'Expected Theme', role: 'unpublished'})! - vi.mocked(findOrSelectTheme).mockResolvedValue(expectedTheme) + test('writes the JSON result to stdout through the real presenter and writer', async () => { + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(['--json'], () => + run(['--overrides=/path/to/overrides.json', '--theme=2', '--json']), + ) + + expect(JSON.parse(stdout())).toEqual(result) + expect(stderr()).toBe('') + }) + expect(renderSuccess).not.toHaveBeenCalled() + expect(openURL).not.toHaveBeenCalled() + expect(devWithOverrideFile).toHaveBeenCalledWith({ + adminSession, + overrideJson: '/path/to/overrides.json', + themeId: '2', + previewIdentifier: undefined, + password: undefined, + }) + }) - await run(['--overrides=/path/to/overrides.json', `--theme=${expectedTheme.id}`, '--json']) + test('exposes its result schema in help', () => { + expect(Preview.jsonOutputSchema).toBe(themePreviewJsonOutputSchema) + expect(Preview.description).toContain('ThemePreviewResult') + expect(Preview.description).toContain('preview_identifier') + expect(Preview.flags.json.env).toBe('SHOPIFY_FLAG_JSON') + }) - expect(devWithOverrideFile).toHaveBeenCalledWith( - expect.objectContaining({ - themeId: expectedTheme.id.toString(), - json: true, - }), - ) + test('propagates failures without printing a success result or opening a browser', async () => { + const error = new Error('Failed to parse override file') + vi.mocked(devWithOverrideFile).mockRejectedValue(error) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await expect(run(['--overrides=/path/to/overrides.json', '--theme=2', '--json', '--open'])).rejects.toBe(error) + + expect(stdout()).toBe('') + expect(stderr()).toBe('') + }) + + expect(renderSuccess).not.toHaveBeenCalled() + expect(openURL).not.toHaveBeenCalled() + }) + + test('keeps browser failures nonfatal and sends a typed warning to stderr', async () => { + const error = new Error('Browser unavailable') + vi.mocked(openURL).mockRejectedValue(error) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(['--json'], () => + run(['--overrides=/path/to/overrides.json', '--theme=2', '--json', '--open']), + ) + + const events = stderr() + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + expect(events).toMatchObject([ + {type: 'diagnostic', level: 'warning', message: `Failed to open theme preview.\n${error.stack}`}, + ]) + expect(JSON.parse(stdout())).toEqual(result) + }) }) }) diff --git a/packages/theme/src/cli/commands/theme/preview.ts b/packages/theme/src/cli/commands/theme/preview.ts index 66b2fea0061..9b9c1865f31 100644 --- a/packages/theme/src/cli/commands/theme/preview.ts +++ b/packages/theme/src/cli/commands/theme/preview.ts @@ -1,15 +1,22 @@ import {themeFlags} from '../../flags.js' import ThemeCommand, {RequiredFlags} from '../../utilities/theme-command.js' import {devWithOverrideFile} from '../../services/dev-override.js' +import {renderThemePreviewResult, renderThemePreviewOpenError} from '../../services/dev-override/result.js' +import {themePreviewJsonOutputSchema} from '../../services/dev-override/types.js' import {findOrSelectTheme} from '../../utilities/theme-selector.js' import {Flags} from '@oclif/core' -import {globalFlags} from '@shopify/cli-kit/node/cli' +import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' +import {openURL} from '@shopify/cli-kit/node/system' import {AdminSession} from '@shopify/cli-kit/node/session' import {InferredFlags} from '@oclif/core/interfaces' type PreviewFlags = InferredFlags export default class Preview extends ThemeCommand { + static get jsonOutputSchema() { + return themePreviewJsonOutputSchema + } + static summary = 'Applies JSON overrides to a theme and returns a preview URL.' static descriptionWithMarkdown = `Applies a JSON overrides file to a theme and creates or updates a preview. This lets you quickly preview changes. @@ -20,6 +27,7 @@ export default class Preview extends ThemeCommand { static flags = { ...globalFlags, + ...jsonFlag, ...themeFlags, theme: Flags.string({ char: 't', @@ -42,6 +50,7 @@ export default class Preview extends ThemeCommand { default: false, }), json: Flags.boolean({ + ...jsonFlag.json, description: 'Output the preview URL and identifier as JSON.', env: 'SHOPIFY_FLAG_JSON', default: false, @@ -52,14 +61,17 @@ export default class Preview extends ThemeCommand { async command(flags: PreviewFlags, adminSession: AdminSession) { const theme = await findOrSelectTheme(adminSession, {filter: {theme: flags.theme}}) - await devWithOverrideFile({ + const result = await devWithOverrideFile({ adminSession, overrideJson: flags.overrides, themeId: theme.id.toString(), previewIdentifier: flags['preview-id'], - open: flags.open, password: flags.password, - json: flags.json, }) + const format = flags.json ? 'json' : 'text' + renderThemePreviewResult(result, format, Boolean(flags['preview-id'])) + if (flags.open) { + openURL(result.url).catch((error: Error) => renderThemePreviewOpenError(error, format)) + } } } diff --git a/packages/theme/src/cli/services/dev-override.test.ts b/packages/theme/src/cli/services/dev-override.test.ts index 093c91335cc..334f7af112a 100644 --- a/packages/theme/src/cli/services/dev-override.test.ts +++ b/packages/theme/src/cli/services/dev-override.test.ts @@ -1,16 +1,13 @@ import {devWithOverrideFile} from './dev-override.js' -import {openURLSafely} from './dev.js' import {fetchDevServerSession} from '../utilities/theme-environment/dev-server-session.js' import {createThemePreview, updateThemePreview} from '../utilities/theme-previews/preview.js' import {describe, expect, test, vi} from 'vitest' import {renderSuccess} from '@shopify/cli-kit/node/ui' -import {collectedLogs, clearCollectedLogs} from '@shopify/cli-kit/node/output' import {inTemporaryDirectory, writeFile} from '@shopify/cli-kit/node/fs' import {joinPath} from '@shopify/cli-kit/node/path' vi.mock('../utilities/theme-environment/dev-server-session.js') vi.mock('../utilities/theme-previews/preview.js') -vi.mock('./dev.js', () => ({openURLSafely: vi.fn()})) vi.mock('@shopify/cli-kit/node/ui') const adminSession = {token: 'token', storeFqdn: 'store.myshopify.com'} @@ -30,7 +27,7 @@ describe('devWithOverrideFile', () => { const overrideJson = joinPath(tmpDir, 'missing.json') // When/Then - await expect(devWithOverrideFile({adminSession, overrideJson, themeId: '123', open: false})).rejects.toThrow( + await expect(devWithOverrideFile({adminSession, overrideJson, themeId: '123'})).rejects.toThrow( `Override file not found: ${overrideJson}`, ) }) @@ -46,7 +43,7 @@ describe('devWithOverrideFile', () => { const expectedThemeId = '789' // When - await devWithOverrideFile({adminSession, overrideJson, themeId: expectedThemeId, open: false}) + const result = await devWithOverrideFile({adminSession, overrideJson, themeId: expectedThemeId}) // Then expect(fetchDevServerSession).toHaveBeenCalledWith(expectedThemeId, adminSession, undefined) @@ -56,21 +53,12 @@ describe('devWithOverrideFile', () => { expect.objectContaining({ session: mockSession, themeId: expectedThemeId, + overridesContent: JSON.stringify({templates: {}}), }), ) expect(updateThemePreview).not.toHaveBeenCalled() - expect(renderSuccess).toHaveBeenCalledWith( - expect.objectContaining({ - body: [ - { - list: { - title: 'Preview is ready', - items: [{link: {url: expectedPreviewUrl}}, `Preview ID: ${expectedPreviewId}`], - }, - }, - ], - }), - ) + expect(result).toEqual({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) + expect(renderSuccess).not.toHaveBeenCalled() }) }) @@ -84,13 +72,11 @@ describe('devWithOverrideFile', () => { const expectedThemeId = '789' // When - await devWithOverrideFile({ + const result = await devWithOverrideFile({ adminSession, overrideJson, themeId: expectedThemeId, previewIdentifier: expectedPreviewId, - open: false, - json: false, }) // Then @@ -98,22 +84,13 @@ describe('devWithOverrideFile', () => { expect.objectContaining({ session: mockSession, themeId: expectedThemeId, + overridesContent: JSON.stringify({templates: {}}), previewIdentifier: expectedPreviewId, }), ) expect(createThemePreview).not.toHaveBeenCalled() - expect(renderSuccess).toHaveBeenCalledWith( - expect.objectContaining({ - body: [ - { - list: { - title: 'Preview updated', - items: [{link: {url: expectedPreviewUrl}}, `Preview ID: ${expectedPreviewId}`], - }, - }, - ], - }), - ) + expect(result).toEqual({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) + expect(renderSuccess).not.toHaveBeenCalled() }) }) @@ -128,46 +105,12 @@ describe('devWithOverrideFile', () => { adminSession, overrideJson, themeId: '123', - open: false, - json: false, }).catch((err) => err) expect(error.message).toBe(`Failed to parse override file: ${overrideJson}`) expect(error.tryMessage).toMatch(/not valid json/i) }) }) - test('opens the preview URL when open is true', async () => { - await inTemporaryDirectory(async (tmpDir) => { - // Given - const overrideJson = joinPath(tmpDir, 'overrides.json') - await writeFile(overrideJson, JSON.stringify({templates: {}})) - vi.mocked(fetchDevServerSession).mockResolvedValue(mockSession) - vi.mocked(createThemePreview).mockResolvedValue({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) - - // When - await devWithOverrideFile({adminSession, overrideJson, themeId: '789', open: true}) - - // Then - expect(openURLSafely).toHaveBeenCalledWith(expectedPreviewUrl, 'theme preview') - }) - }) - - test('does not open the preview URL when open is false', async () => { - await inTemporaryDirectory(async (tmpDir) => { - // Given - const overrideJson = joinPath(tmpDir, 'overrides.json') - await writeFile(overrideJson, JSON.stringify({templates: {}})) - vi.mocked(fetchDevServerSession).mockResolvedValue(mockSession) - vi.mocked(createThemePreview).mockResolvedValue({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) - - // When - await devWithOverrideFile({adminSession, overrideJson, themeId: '789', open: false}) - - // Then - expect(openURLSafely).not.toHaveBeenCalled() - }) - }) - test('passes password to fetchDevServerSession when provided', async () => { await inTemporaryDirectory(async (tmpDir) => { // Given @@ -181,8 +124,6 @@ describe('devWithOverrideFile', () => { adminSession, overrideJson, themeId: '789', - open: false, - json: false, password: 'shptka_abc123', }) @@ -191,39 +132,19 @@ describe('devWithOverrideFile', () => { }) }) - test('outputs JSON when json flag is true', async () => { + test.each([undefined, 'existing-preview'])('propagates API failures for preview %s', async (previewIdentifier) => { await inTemporaryDirectory(async (tmpDir) => { - // Given const overrideJson = joinPath(tmpDir, 'overrides.json') - await writeFile(overrideJson, JSON.stringify({templates: {}})) + await writeFile(overrideJson, '{}') vi.mocked(fetchDevServerSession).mockResolvedValue(mockSession) - vi.mocked(createThemePreview).mockResolvedValue({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) - clearCollectedLogs() + const error = new Error('Theme preview request failed') + vi.mocked(createThemePreview).mockRejectedValue(error) + vi.mocked(updateThemePreview).mockRejectedValue(error) - // When - await devWithOverrideFile({adminSession, overrideJson, themeId: '789', open: false, json: true}) - - // Then - const expectedJson = JSON.stringify({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) - expect(collectedLogs.info).toContainEqual(expectedJson) + await expect(devWithOverrideFile({adminSession, overrideJson, themeId: '123', previewIdentifier})).rejects.toBe( + error, + ) expect(renderSuccess).not.toHaveBeenCalled() }) }) - - test('renders success body by default when json flag is omitted', async () => { - await inTemporaryDirectory(async (tmpDir) => { - // Given - const overrideJson = joinPath(tmpDir, 'overrides.json') - await writeFile(overrideJson, JSON.stringify({templates: {}})) - vi.mocked(fetchDevServerSession).mockResolvedValue(mockSession) - vi.mocked(createThemePreview).mockResolvedValue({url: expectedPreviewUrl, preview_identifier: expectedPreviewId}) - clearCollectedLogs() - - // When - await devWithOverrideFile({adminSession, overrideJson, themeId: '789', open: false}) - - // Then - expect(renderSuccess).toHaveBeenCalled() - }) - }) }) diff --git a/packages/theme/src/cli/services/dev-override.ts b/packages/theme/src/cli/services/dev-override.ts index be29c90c226..d199ad7e98d 100644 --- a/packages/theme/src/cli/services/dev-override.ts +++ b/packages/theme/src/cli/services/dev-override.ts @@ -1,8 +1,6 @@ -import {openURLSafely} from './dev.js' +import {type ThemePreviewResult} from './dev-override/types.js' import {fetchDevServerSession} from '../utilities/theme-environment/dev-server-session.js' import {createThemePreview, updateThemePreview} from '../utilities/theme-previews/preview.js' -import {renderSuccess} from '@shopify/cli-kit/node/ui' -import {outputInfo} from '@shopify/cli-kit/node/output' import {AdminSession} from '@shopify/cli-kit/node/session' import {AbortError} from '@shopify/cli-kit/node/error' import {readFile, fileExistsSync} from '@shopify/cli-kit/node/fs' @@ -16,16 +14,14 @@ interface DevWithOverrideFileOptions { overrideJson: string themeId: string previewIdentifier?: string - open: boolean password?: string - json?: boolean } /** * Reads a JSON overrides file and creates or updates a Storefront preview. - * The resulting preview URL is displayed to the user. + * Returns the preview URL and identifier. */ -export async function devWithOverrideFile(options: DevWithOverrideFileOptions) { +export async function devWithOverrideFile(options: DevWithOverrideFileOptions): Promise { if (!fileExistsSync(options.overrideJson)) { throw new AbortError(`Override file not found: ${options.overrideJson}`) } @@ -42,35 +38,16 @@ export async function devWithOverrideFile(options: DevWithOverrideFileOptions) { const session = await fetchDevServerSession(options.themeId, options.adminSession, options.password) const overridesContent = JSON.stringify(overrides) - const preview = options.previewIdentifier - ? await updateThemePreview({ + return options.previewIdentifier + ? updateThemePreview({ session, overridesContent, themeId: options.themeId, previewIdentifier: options.previewIdentifier, }) - : await createThemePreview({ + : createThemePreview({ session, overridesContent, themeId: options.themeId, }) - - if (options.json) { - outputInfo(JSON.stringify({url: preview.url, preview_identifier: preview.preview_identifier})) - } else { - renderSuccess({ - body: [ - { - list: { - title: options.previewIdentifier ? 'Preview updated' : 'Preview is ready', - items: [{link: {url: preview.url}}, `Preview ID: ${preview.preview_identifier}`], - }, - }, - ], - }) - } - - if (options.open) { - openURLSafely(preview.url, 'theme preview') - } } diff --git a/packages/theme/src/cli/services/dev-override/codec.test.ts b/packages/theme/src/cli/services/dev-override/codec.test.ts new file mode 100644 index 00000000000..3a28d3ba2ef --- /dev/null +++ b/packages/theme/src/cli/services/dev-override/codec.test.ts @@ -0,0 +1,25 @@ +import {encodeThemePreviewResult} from './codec.js' +import {themePreviewJsonOutputSchema} from './types.js' +import {expect, test} from 'vitest' + +const result = {url: 'https://abc123.shopifypreview.com', preview_identifier: 'abc123'} + +test('preserves the compact JSON wire format and key order', () => { + expect(encodeThemePreviewResult(result)).toBe( + '{"url":"https://abc123.shopifypreview.com","preview_identifier":"abc123"}', + ) +}) + +test('omits internal API fields', () => { + const response = {...result, internal: 'private'} + expect(JSON.parse(encodeThemePreviewResult(response))).toEqual(result) +}) + +test.each([ + {url: null, preview_identifier: 'abc123'}, + {url: 'https://abc123.shopifypreview.com', preview_identifier: 123}, + {url: 'https://abc123.shopifypreview.com'}, + {preview_identifier: 'abc123'}, +])('rejects invalid preview results %j', (invalid) => { + expect(() => themePreviewJsonOutputSchema.validate(invalid)).toThrow() +}) diff --git a/packages/theme/src/cli/services/dev-override/codec.ts b/packages/theme/src/cli/services/dev-override/codec.ts new file mode 100644 index 00000000000..cbe4b597fec --- /dev/null +++ b/packages/theme/src/cli/services/dev-override/codec.ts @@ -0,0 +1,6 @@ +import {themePreviewJsonOutputSchema, type ThemePreviewResult} from './types.js' + +export function encodeThemePreviewResult(result: ThemePreviewResult): string { + // Keep the compact wire format and key order used by the original preview command. + return JSON.stringify(themePreviewJsonOutputSchema.validate(result)) +} diff --git a/packages/theme/src/cli/services/dev-override/result.test.ts b/packages/theme/src/cli/services/dev-override/result.test.ts new file mode 100644 index 00000000000..bedd48f1cba --- /dev/null +++ b/packages/theme/src/cli/services/dev-override/result.test.ts @@ -0,0 +1,66 @@ +import {renderThemePreviewResult, renderThemePreviewOpenError} from './result.js' +import {expect, test, vi} from 'vitest' +import {renderSuccess, renderWarning} from '@shopify/cli-kit/node/ui' +import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' + +vi.mock('@shopify/cli-kit/node/ui') + +const result = {url: 'https://abc123.shopifypreview.com', preview_identifier: 'abc123'} + +test.each([false, true])('preserves the success banner with updated=%s', (updated) => { + renderThemePreviewResult(result, 'text', updated) + + expect(renderSuccess).toHaveBeenCalledWith({ + body: [ + { + list: { + title: updated ? 'Preview updated' : 'Preview is ready', + items: [{link: {url: result.url}}, `Preview ID: ${result.preview_identifier}`], + }, + }, + ], + }) +}) + +test('preserves the browser warning in text mode', () => { + const error = new Error('Browser unavailable') + renderThemePreviewOpenError(error, 'text') + + expect(renderWarning).toHaveBeenCalledWith({headline: 'Failed to open theme preview.', body: error.stack}) +}) + +test('sends browser failures as diagnostic events to stderr', async () => { + const error = new Error('Browser unavailable') + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(['--json'], () => renderThemePreviewOpenError(error, 'json')) + + expect(stdout()).toBe('') + expect(JSON.parse(stderr())).toMatchObject({ + type: 'diagnostic', + level: 'warning', + message: `Failed to open theme preview.\n${error.stack}`, + }) + }) + expect(renderWarning).not.toHaveBeenCalled() +}) + +test('writes compact JSON to stdout outside the command event context', async () => { + await withCapturedStandardStreams(({stdout, stderr}) => { + renderThemePreviewResult(result, 'json', false) + + expect(stdout()).toBe('{"url":"https://abc123.shopifypreview.com","preview_identifier":"abc123"}\n') + expect(stderr()).toBe('') + }) + expect(renderSuccess).not.toHaveBeenCalled() +}) + +test('writes the JSON result to stdout without a diagnostic wrapper during the command lifecycle', async () => { + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(['--json'], () => renderThemePreviewResult(result, 'json', false)) + + expect(stdout()).toBe('{"url":"https://abc123.shopifypreview.com","preview_identifier":"abc123"}\n') + expect(stderr()).toBe('') + }) + expect(renderSuccess).not.toHaveBeenCalled() +}) diff --git a/packages/theme/src/cli/services/dev-override/result.ts b/packages/theme/src/cli/services/dev-override/result.ts new file mode 100644 index 00000000000..985691e26d4 --- /dev/null +++ b/packages/theme/src/cli/services/dev-override/result.ts @@ -0,0 +1,33 @@ +import {type ThemePreviewResult} from './types.js' +import {encodeThemePreviewResult} from './codec.js' +import {outputResult} from '@shopify/cli-kit/node/output' +import {renderSuccess, renderWarning} from '@shopify/cli-kit/node/ui' +import {emitCommandEvent} from '@shopify/cli-kit/node/command-events' + +export function renderThemePreviewResult(result: ThemePreviewResult, format: 'text' | 'json', updated: boolean): void { + if (format === 'json') { + outputResult(encodeThemePreviewResult(result)) + return + } + + renderSuccess({ + body: [ + { + list: { + title: updated ? 'Preview updated' : 'Preview is ready', + items: [{link: {url: result.url}}, `Preview ID: ${result.preview_identifier}`], + }, + }, + ], + }) +} + +export function renderThemePreviewOpenError(error: Error, format: 'text' | 'json'): void { + const headline = 'Failed to open theme preview.' + const body = error.stack ?? error.message + if (format === 'json') { + emitCommandEvent({type: 'diagnostic', level: 'warning', message: `${headline}\n${body}`}) + } else { + renderWarning({headline, body}) + } +} diff --git a/packages/theme/src/cli/services/dev-override/types.ts b/packages/theme/src/cli/services/dev-override/types.ts new file mode 100644 index 00000000000..a3e51a1e626 --- /dev/null +++ b/packages/theme/src/cli/services/dev-override/types.ts @@ -0,0 +1,12 @@ +import {defineJsonOutputSchema, type InferJsonOutputSchema} from '@shopify/cli-kit/node/json-output-schema' +import {zod} from '@shopify/cli-kit/node/schema' + +export const themePreviewJsonOutputSchema = defineJsonOutputSchema({ + name: 'ThemePreviewResult', + schema: zod.object({ + url: zod.string(), + preview_identifier: zod.string(), + }), +}) + +export type ThemePreviewResult = InferJsonOutputSchema