diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index e91cd1011ee..36eaa443c98 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -9789,9 +9789,18 @@ "description": "Increase the verbosity of the output. May include sensitive data.", "isOptional": true, "environmentValue": "SHOPIFY_FLAG_VERBOSE" + }, + { + "filePath": "docs-shopify.dev/commands/interfaces/theme-package.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 themepackage {\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 * 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 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 * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" + "value": "export interface themepackage {\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 * 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 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 * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, "themepreview": { diff --git a/packages/cli-kit/src/public/node/archiver.ts b/packages/cli-kit/src/public/node/archiver.ts index 35d781a2f75..952979ec35f 100644 --- a/packages/cli-kit/src/public/node/archiver.ts +++ b/packages/cli-kit/src/public/node/archiver.ts @@ -46,11 +46,17 @@ export async function zip(options: ZipOptions): Promise { const archive = archiver('zip') const output = createWriteStream(outputZipPath) + let outputError: Error | undefined + output.on('error', (error) => { + outputError = error + archive.abort() + }) output.on('close', () => { - resolve() + if (outputError) reject(outputError) + else resolve() }) archive.on('error', (error) => { - reject(error) + output.destroy(error) }) archive.pipe(output) @@ -75,12 +81,10 @@ export async function zip(options: ZipOptions): Promise { // Wait for all files to be read and added before finalizing Promise.all(addFilesPromises) .then(() => { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - archive.finalize() + if (!output.destroyed) return archive.finalize() }) .catch((error) => { - // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors - reject(error) + output.destroy(error instanceof Error ? error : new Error(String(error))) }) }) } diff --git a/packages/cli/README.md b/packages/cli/README.md index 13e58c87648..49035cf0ada 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -15090,10 +15090,14 @@ Package your theme into a .zip file, ready to upload to the Online Store. ``` USAGE - $ shopify theme package [--auth-alias ] [--json-schema] [--no-color] [--no-input] [--path ] + $ shopify theme package [--auth-alias ] [-j] [--json-schema] [--no-color] [--no-input] [--path ] [--verbose] FLAGS + -j, --json + Output the result as JSON. Automatically disables color output. + [env: SHOPIFY_FLAG_JSON] + --auth-alias= Alias of the Shopify account to use for authentication. [env: SHOPIFY_FLAG_AUTH_ALIAS] @@ -15132,6 +15136,28 @@ DESCRIPTION The ZIP file uses the name `theme_name-theme_version.zip`, based on parameters in your "settings_schema.json" (https://shopify.dev/docs/storefronts/themes/architecture/config/settings-schema-json) file. + + Use `--json-schema` to print the result, error, and event schemas. + + Output from `--json` conforms to the `ThemePackageResult` schema. + + ```json + { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "The absolute native path of the ZIP archive." + } + }, + "required": [ + "path" + ], + "additionalProperties": false, + "title": "ThemePackageResult", + "$schema": "http://json-schema.org/draft-07/schema#" + } + ``` ``` ## `shopify theme preview` diff --git a/packages/cli/oclif.manifest.json b/packages/cli/oclif.manifest.json index 3e414b30b4c..a0885c6f9d5 100644 --- a/packages/cli/oclif.manifest.json +++ b/packages/cli/oclif.manifest.json @@ -12061,7 +12061,7 @@ "args": { }, "customPluginName": "@shopify/theme", - "description": "Packages your local theme files into a ZIP file that can be uploaded to Shopify.\n\n Only folders that match the \"default Shopify theme folder structure\" (https://shopify.dev/docs/storefronts/themes/tools/cli#directory-structure) are included in the package.\n\n The package includes the `listings` directory if present (required for multi-preset themes per \"Theme Store requirements\" (https://shopify.dev/docs/storefronts/themes/store/requirements#adding-presets-to-your-theme-zip-submission)).\n\n The ZIP file uses the name `theme_name-theme_version.zip`, based on parameters in your \"settings_schema.json\" (https://shopify.dev/docs/storefronts/themes/architecture/config/settings-schema-json) file.", + "description": "Packages your local theme files into a ZIP file that can be uploaded to Shopify.\n\n Only folders that match the \"default Shopify theme folder structure\" (https://shopify.dev/docs/storefronts/themes/tools/cli#directory-structure) are included in the package.\n\n The package includes the `listings` directory if present (required for multi-preset themes per \"Theme Store requirements\" (https://shopify.dev/docs/storefronts/themes/store/requirements#adding-presets-to-your-theme-zip-submission)).\n\n The ZIP file uses the name `theme_name-theme_version.zip`, based on parameters in your \"settings_schema.json\" (https://shopify.dev/docs/storefronts/themes/architecture/config/settings-schema-json) file.\n\nUse `--json-schema` to print the result, error, and event schemas.\n\nOutput from `--json` conforms to the `ThemePackageResult` schema.\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"The absolute native path of the ZIP archive.\"\n }\n },\n \"required\": [\n \"path\"\n ],\n \"additionalProperties\": false,\n \"title\": \"ThemePackageResult\",\n \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n}\n```", "descriptionWithMarkdown": "Packages your local theme files into a ZIP file that can be uploaded to Shopify.\n\n Only folders that match the [default Shopify theme folder structure](https://shopify.dev/docs/storefronts/themes/tools/cli#directory-structure) are included in the package.\n\n The package includes the `listings` directory if present (required for multi-preset themes per [Theme Store requirements](https://shopify.dev/docs/storefronts/themes/store/requirements#adding-presets-to-your-theme-zip-submission)).\n\n The ZIP file uses the name `theme_name-theme_version.zip`, based on parameters in your [settings_schema.json](https://shopify.dev/docs/storefronts/themes/architecture/config/settings-schema-json) file.", "enableJsonFlag": false, "flags": { @@ -12073,6 +12073,15 @@ "name": "auth-alias", "type": "option" }, + "json": { + "allowNo": false, + "char": "j", + "description": "Output the result as JSON. Automatically disables color output.", + "env": "SHOPIFY_FLAG_JSON", + "hidden": false, + "name": "json", + "type": "boolean" + }, "json-schema": { "allowNo": false, "description": "Print the command's JSON schemas.", 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 18e26068614..630871ee575 100644 --- a/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js +++ b/packages/eslint-plugin-cli/rules/json-output-command-exceptions.js @@ -7,7 +7,6 @@ const commandExceptions = [ 'packages/plugin-did-you-mean/src/commands/config/autocorrect/status.ts', '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', // App Security commands, launched before adopting typed JSON output. Remove entries as they adopt it. 'packages/app/src/cli/commands/app/security/check.ts', diff --git a/packages/theme/src/cli/commands/theme/package.test.ts b/packages/theme/src/cli/commands/theme/package.test.ts new file mode 100644 index 00000000000..9ab449b87ef --- /dev/null +++ b/packages/theme/src/cli/commands/theme/package.test.ts @@ -0,0 +1,102 @@ +import Package from './package.js' +import {themePackageJsonOutputSchema} from '../../services/package/types.js' +import {renderThemePackageResult} from '../../services/package/result.js' +import {Config} from '@oclif/core' +import {runWithCommandEventsForCommand} from '@shopify/cli-kit/node/command-events' +import {inTemporaryDirectory, mkdir, writeFile, fileExists} from '@shopify/cli-kit/node/fs' +import {joinPath, relativizePath, cwd} from '@shopify/cli-kit/node/path' +import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' +import {renderSuccess} from '@shopify/cli-kit/node/ui' +import {expect, test, vi} from 'vitest' +// Native JSON paths must preserve Windows separators instead of pathe normalization. +// eslint-disable-next-line no-restricted-imports +import {resolve as nativePath} from 'node:path' + +vi.mock('@shopify/cli-kit/node/ui') +vi.mock('@shopify/cli-kit/node/analytics') +vi.mock('@shopify/cli-kit/node/metadata') +vi.mock('@shopify/cli-kit/node/environments') + +async function run(argv: string[]) { + const config = new Config({root: __dirname}) + await config.load() + await new Package(argv, config).run() +} + +test.each([true, false])('writes the package receipt to stdout with version=%s', async (includeVersion) => { + await inTemporaryDirectory(async (directory) => { + await mkdir(joinPath(directory, 'config')) + await writeFile( + joinPath(directory, 'config/settings_schema.json'), + JSON.stringify([{name: 'theme_info', theme_name: 'Dawn', ...(includeVersion ? {theme_version: '1.0'} : {})}]), + ) + const path = joinPath(directory, includeVersion ? 'Dawn-1.0.zip' : 'Dawn.zip') + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(['--json'], () => run(['--path', directory, '--json'])) + expect(stdout()).toBe(`${themePackageJsonOutputSchema.encode({path: nativePath(path)})}\n`) + expect(stderr()).toBe('') + }) + await expect(fileExists(path)).resolves.toBe(true) + expect(renderSuccess).not.toHaveBeenCalled() + }) +}) + +test('preserves the text success banner', () => { + const path = joinPath(cwd(), 'Dawn.zip') + renderThemePackageResult({path}, 'text') + expect(renderSuccess).toHaveBeenCalledWith({ + body: ['Your local theme was packaged in', {filePath: relativizePath(path)}], + }) +}) + +test('emits a fatal JSON error when the archive destination is a directory', async () => { + await inTemporaryDirectory(async (directory) => { + await mkdir(joinPath(directory, 'config')) + await writeFile( + joinPath(directory, 'config/settings_schema.json'), + JSON.stringify([{name: 'theme_info', theme_name: 'Dawn'}]), + ) + const destination = joinPath(directory, 'Dawn.zip') + await mkdir(destination) + await writeFile(joinPath(destination, 'keep.txt'), 'Existing content') + const config = new Config({root: __dirname}) + await config.load() + class LifecyclePackage extends Package { + execute(): Promise { + return this._run() + } + } + vi.spyOn(Package.prototype as unknown as {init(): Promise}, 'init').mockResolvedValue(undefined) + vi.spyOn(process, 'exit').mockImplementation(() => undefined as never) + const argv = ['--path', directory, '--json'] + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await runWithCommandEventsForCommand(argv, () => new LifecyclePackage(argv, config).execute()) + expect(JSON.parse(stdout())).toEqual({error: expect.objectContaining({message: expect.any(String)})}) + expect(stderr()).toBe('') + }) + expect(process.exit).toHaveBeenCalledWith(1) + await expect(fileExists(joinPath(destination, 'keep.txt'))).resolves.toBe(true) + expect(renderSuccess).not.toHaveBeenCalled() + }) +}) + +test('does not emit a result when packaging fails', async () => { + await inTemporaryDirectory(async (directory) => { + await withCapturedStandardStreams(async ({stdout}) => { + await expect(run(['--path', directory, '--json'])).rejects.toThrow( + 'Provide a config/settings_schema.json to package your theme.', + ) + expect(stdout()).toBe('') + }) + }) +}) + +test('exposes the schema and rejects invalid package paths', () => { + expect(Package.jsonOutputSchema).toBe(themePackageJsonOutputSchema) + expect(Package.flags.json).toBeDefined() + expect(Package.description).toContain('--json-schema') + expect(() => themePackageJsonOutputSchema.validate({path: 42})).toThrow() + expect(() => themePackageJsonOutputSchema.validate({path: 'Dawn.zip'})).toThrow() + expect(() => themePackageJsonOutputSchema.validate({path: joinPath(cwd(), 'Dawn.zip'), extra: true})).toThrow() +}) diff --git a/packages/theme/src/cli/commands/theme/package.ts b/packages/theme/src/cli/commands/theme/package.ts index 925d13602f4..a69ce14d0b6 100644 --- a/packages/theme/src/cli/commands/theme/package.ts +++ b/packages/theme/src/cli/commands/theme/package.ts @@ -1,11 +1,17 @@ import {themeFlags} from '../../flags.js' import ThemeCommand, {RequiredFlags} from '../../utilities/theme-command.js' import {packageTheme} from '../../services/package.js' -import {globalFlags} from '@shopify/cli-kit/node/cli' +import {themePackageJsonOutputSchema} from '../../services/package/types.js' +import {renderThemePackageResult} from '../../services/package/result.js' +import {globalFlags, jsonFlag} from '@shopify/cli-kit/node/cli' import {InferredFlags} from '@oclif/core/interfaces' type PackageFlags = InferredFlags export default class Package extends ThemeCommand { + static get jsonOutputSchema() { + return themePackageJsonOutputSchema + } + static summary = 'Package your theme into a .zip file, ready to upload to the Online Store.' static descriptionWithMarkdown = `Packages your local theme files into a ZIP file that can be uploaded to Shopify. @@ -20,12 +26,14 @@ export default class Package extends ThemeCommand { static flags = { ...globalFlags, + ...jsonFlag, path: themeFlags.path, } static multiEnvironmentsFlags: RequiredFlags = null async command(flags: PackageFlags) { - await packageTheme(flags.path) + const result = await packageTheme(flags.path) + renderThemePackageResult(result, flags.json ? 'json' : 'text') } } diff --git a/packages/theme/src/cli/services/package.test.ts b/packages/theme/src/cli/services/package.test.ts index edbf5bae0d3..0cddce7caf0 100644 --- a/packages/theme/src/cli/services/package.test.ts +++ b/packages/theme/src/cli/services/package.test.ts @@ -9,6 +9,33 @@ const StreamZip = require('node-stream-zip') vi.mock('@shopify/cli-kit/node/ui') describe('packageTheme', () => { + test.each([ + {name: '../outside', version: ''}, + {name: 'absolute', version: ''}, + {name: 'C:\\outside', version: ''}, + {name: 'C:outside', version: ''}, + {name: 'Dawn', version: '../outside'}, + {name: 'Dawn', version: '..\\outside'}, + ])('rejects paths in the package filename: %j', async ({name, version}) => { + await inTemporaryDirectory(async (tmpDir) => { + const inputDirectory = joinPath(tmpDir, 'theme') + await mkdir(joinPath(inputDirectory, 'config')) + await createSettingsSchema( + JSON.stringify([ + { + name: 'theme_info', + theme_name: name === 'absolute' ? joinPath(tmpDir, 'outside') : name, + theme_version: version, + }, + ]), + inputDirectory, + ) + + await expect(packageTheme(inputDirectory)).rejects.toThrow('Theme name and version must not contain paths.') + await expect(fileExists(joinPath(tmpDir, 'outside.zip'))).resolves.toBe(false) + }) + }) + test('creates zip file from theme', async () => { await inTemporaryDirectory(async (tmpDir) => { // Given @@ -33,7 +60,7 @@ describe('packageTheme', () => { ) // When - await packageTheme(inputDirectory) + const result = await packageTheme(inputDirectory) // Then const expectedOutputZipPath = joinPath(inputDirectory, 'Dawn-7.0.2.zip') @@ -42,9 +69,8 @@ describe('packageTheme', () => { const archiveEntries = await readArchiveFiles(expectedOutputZipPath) expect(themeRelativePaths.sort()).toEqual(archiveEntries.sort()) - expect(renderSuccess).toBeCalledWith({ - body: ['Your local theme was packaged in', {filePath: expectedOutputZipPath}], - }) + expect(result).toEqual({path: expectedOutputZipPath}) + expect(renderSuccess).not.toHaveBeenCalled() }) }) @@ -73,7 +99,7 @@ describe('packageTheme', () => { ) // When - await packageTheme(inputDirectory) + const result = await packageTheme(inputDirectory) // Then const expectedOutputZipPath = joinPath(inputDirectory, 'Dawn-7.0.2.zip') @@ -82,9 +108,8 @@ describe('packageTheme', () => { const archiveEntries = await readArchiveFiles(expectedOutputZipPath) expect(expectedThemeRelativePaths.sort()).toEqual(archiveEntries.sort()) - expect(renderSuccess).toBeCalledWith({ - body: ['Your local theme was packaged in', {filePath: expectedOutputZipPath}], - }) + expect(result).toEqual({path: expectedOutputZipPath}) + expect(renderSuccess).not.toHaveBeenCalled() }) }) @@ -105,7 +130,7 @@ describe('packageTheme', () => { await createSettingsSchema('[{"name": "theme_info", "theme_name": "Dawn"}]', inputDirectory) // When - await packageTheme(inputDirectory) + const result = await packageTheme(inputDirectory) // Then const expectedOutputZipPath = joinPath(inputDirectory, 'Dawn.zip') @@ -114,9 +139,8 @@ describe('packageTheme', () => { const archiveEntries = await readArchiveFiles(expectedOutputZipPath) expect(themeRelativePaths.sort()).toEqual(archiveEntries.sort()) - expect(renderSuccess).toBeCalledWith({ - body: ['Your local theme was packaged in', {filePath: expectedOutputZipPath}], - }) + expect(result).toEqual({path: expectedOutputZipPath}) + expect(renderSuccess).not.toHaveBeenCalled() }) }) diff --git a/packages/theme/src/cli/services/package.ts b/packages/theme/src/cli/services/package.ts index bfe10e0b60a..dca85d5efd4 100644 --- a/packages/theme/src/cli/services/package.ts +++ b/packages/theme/src/cli/services/package.ts @@ -1,8 +1,8 @@ +import {type ThemePackageResult} from './package/types.js' import {zip} from '@shopify/cli-kit/node/archiver' import {fileExists, readFile} from '@shopify/cli-kit/node/fs' import {AbortError} from '@shopify/cli-kit/node/error' -import {renderSuccess} from '@shopify/cli-kit/node/ui' -import {resolvePath, relativizePath} from '@shopify/cli-kit/node/path' +import {resolvePath} from '@shopify/cli-kit/node/path' import {parseJSON} from '@shopify/theme-check-node' const themeFilesPattern = [ @@ -23,10 +23,10 @@ const themeFilesPattern = [ ].join('|') // package is a reserved word so the function needs to be named packageTheme -export async function packageTheme(inputDirectory: string) { +export async function packageTheme(inputDirectory: string): Promise { const packageName = await getThemePackageName(inputDirectory) - const outputZipPath = `${inputDirectory}/${packageName}` + const outputZipPath = resolvePath(inputDirectory, packageName) const matchFilePattern = `${inputDirectory}/(${themeFilesPattern})` await zip({ @@ -35,9 +35,7 @@ export async function packageTheme(inputDirectory: string) { matchFilePattern, }) - renderSuccess({ - body: ['Your local theme was packaged in', {filePath: relativizePath(outputZipPath)}], - }) + return {path: outputZipPath} } async function getThemePackageName(inputDirectory: string) { @@ -55,6 +53,10 @@ async function getThemePackageName(inputDirectory: string) { const themeNameVersion = [themeInfo.theme_name, themeInfo.theme_version].filter(Boolean).join('-') + if (/[/\\]/.test(themeNameVersion) || /^[a-z]:/i.test(themeNameVersion)) { + throw new AbortError('Theme name and version must not contain paths.') + } + return `${themeNameVersion}.zip` } diff --git a/packages/theme/src/cli/services/package/result.ts b/packages/theme/src/cli/services/package/result.ts new file mode 100644 index 00000000000..de42b9b4a40 --- /dev/null +++ b/packages/theme/src/cli/services/package/result.ts @@ -0,0 +1,16 @@ +import {themePackageJsonOutputSchema, type ThemePackageResult} from './types.js' +import {outputResult} from '@shopify/cli-kit/node/output' +import {relativizePath} from '@shopify/cli-kit/node/path' +import {renderSuccess} from '@shopify/cli-kit/node/ui' +// Native JSON paths must preserve Windows separators instead of pathe normalization. +// eslint-disable-next-line no-restricted-imports +import {resolve as resolvePath} from 'node:path' + +export function renderThemePackageResult(result: ThemePackageResult, format: 'text' | 'json'): void { + if (format === 'json') { + outputResult(themePackageJsonOutputSchema.encode({...result, path: resolvePath(result.path)})) + return + } + + renderSuccess({body: ['Your local theme was packaged in', {filePath: relativizePath(result.path)}]}) +} diff --git a/packages/theme/src/cli/services/package/types.ts b/packages/theme/src/cli/services/package/types.ts new file mode 100644 index 00000000000..32c572614f3 --- /dev/null +++ b/packages/theme/src/cli/services/package/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' +import {isAbsolutePath} from '@shopify/cli-kit/node/path' + +export const themePackageJsonOutputSchema = defineJsonOutputSchema({ + name: 'ThemePackageResult', + schema: zod + .object({path: zod.string().refine(isAbsolutePath).describe('The absolute native path of the ZIP archive.')}) + .strict(), +}) + +export type ThemePackageResult = InferJsonOutputSchema