@capawesome/cli 4.6.0-dev.80c962a.1774597304 → 4.6.0-dev.8ae803e.1775035527

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ import { DEFAULT_CONSOLE_BASE_URL } from '../../../config/consts.js';
2
+ import appBuildSourcesService from '../../../services/app-build-sources.js';
3
+ import appBuildsService from '../../../services/app-builds.js';
4
+ import appCertificatesService from '../../../services/app-certificates.js';
5
+ import appDeploymentsService from '../../../services/app-deployments.js';
6
+ import appEnvironmentsService from '../../../services/app-environments.js';
7
+ import { parseKeyValuePairs } from '../../../utils/app-environments.js';
8
+ import { withAuth } from '../../../utils/auth.js';
9
+ import { parseCustomProperties } from '../../../utils/custom-properties.js';
10
+ import { isInteractive } from '../../../utils/environment.js';
11
+ import { waitForJobCompletion } from '../../../utils/job.js';
12
+ import { prompt, promptAppSelection, promptOrganizationSelection } from '../../../utils/prompt.js';
13
+ import zip from '../../../utils/zip.js';
14
+ import { defineCommand, defineOptions } from '@robingenz/zli';
15
+ import consola from 'consola';
16
+ import fs from 'fs/promises';
17
+ import path from 'path';
18
+ import { z } from 'zod';
19
+ export default defineCommand({
20
+ description: 'Create a new live update by building and deploying web assets using Capawesome Cloud Runners.',
21
+ options: defineOptions(z.object({
22
+ androidEq: z.string().optional().describe('The exact Android versionCode for the live update.'),
23
+ androidMax: z.string().optional().describe('The maximum Android versionCode for the live update.'),
24
+ androidMin: z.string().optional().describe('The minimum Android versionCode for the live update.'),
25
+ appId: z
26
+ .uuid({
27
+ message: 'App ID must be a UUID.',
28
+ })
29
+ .optional()
30
+ .describe('App ID to create the live update for.'),
31
+ certificate: z.string().optional().describe('The name of the certificate to use for the build.'),
32
+ channel: z.string().optional().describe('The name of the channel to deploy to.'),
33
+ customProperty: z
34
+ .array(z.string().min(1).max(100))
35
+ .max(10)
36
+ .optional()
37
+ .describe('A custom property to assign to the build. Must be in the format `key=value`. Can be specified multiple times.'),
38
+ environment: z.string().optional().describe('The name of the environment to use for the build.'),
39
+ gitRef: z.string().optional().describe('The Git reference (branch, tag, or commit SHA) to build.'),
40
+ iosEq: z.string().optional().describe('The exact iOS CFBundleVersion for the live update.'),
41
+ iosMax: z.string().optional().describe('The maximum iOS CFBundleVersion for the live update.'),
42
+ iosMin: z.string().optional().describe('The minimum iOS CFBundleVersion for the live update.'),
43
+ json: z.boolean().optional().describe('Output in JSON format.'),
44
+ path: z.string().optional().describe('Path to local source files to upload.'),
45
+ rolloutPercentage: z.coerce
46
+ .number()
47
+ .int()
48
+ .min(0)
49
+ .max(100)
50
+ .optional()
51
+ .describe('The rollout percentage for the deployment (0-100). Default: 100.'),
52
+ stack: z
53
+ .enum(['macos-sequoia', 'macos-tahoe'], {
54
+ message: 'Build stack must be either `macos-sequoia` or `macos-tahoe`.',
55
+ })
56
+ .optional()
57
+ .describe('The build stack to use for the build process.'),
58
+ url: z.string().optional().describe('URL to a zip file to use as build source.'),
59
+ variable: z
60
+ .array(z.string())
61
+ .optional()
62
+ .describe('Ad hoc environment variable in key=value format. Can be specified multiple times.'),
63
+ variableFile: z
64
+ .string()
65
+ .optional()
66
+ .describe('Path to a file containing ad hoc environment variables in .env format.'),
67
+ yes: z.boolean().optional().describe('Skip confirmation prompts.'),
68
+ }), { y: 'yes' }),
69
+ action: withAuth(async (options) => {
70
+ let { appId, certificate, channel, gitRef, environment, json, stack, path: sourcePath, url } = options;
71
+ // Validate that path, url, and gitRef cannot be used together
72
+ if (sourcePath && gitRef) {
73
+ consola.error('The --path and --git-ref flags cannot be used together.');
74
+ process.exit(1);
75
+ }
76
+ if (url && gitRef) {
77
+ consola.error('The --url and --git-ref flags cannot be used together.');
78
+ process.exit(1);
79
+ }
80
+ if (url && sourcePath) {
81
+ consola.error('The --url and --path flags cannot be used together.');
82
+ process.exit(1);
83
+ }
84
+ // Validate url if provided
85
+ if (url) {
86
+ consola.warn('The --url option is experimental and may change in the future.');
87
+ }
88
+ // Validate path if provided
89
+ if (sourcePath) {
90
+ consola.warn('The --path option is experimental and may change in the future.');
91
+ const resolvedPath = path.resolve(sourcePath);
92
+ const stat = await fs.stat(resolvedPath).catch(() => null);
93
+ if (!stat || !stat.isDirectory()) {
94
+ consola.error('The --path must point to an existing directory.');
95
+ process.exit(1);
96
+ }
97
+ const packageJsonPath = path.join(resolvedPath, 'package.json');
98
+ const packageJsonStat = await fs.stat(packageJsonPath).catch(() => null);
99
+ if (!packageJsonStat || !packageJsonStat.isFile()) {
100
+ consola.error('The directory specified by --path must contain a package.json file.');
101
+ process.exit(1);
102
+ }
103
+ }
104
+ // Prompt for app ID if not provided
105
+ if (!appId) {
106
+ if (!isInteractive()) {
107
+ consola.error('You must provide an app ID when running in non-interactive environment.');
108
+ process.exit(1);
109
+ }
110
+ const organizationId = await promptOrganizationSelection({ allowCreate: true });
111
+ appId = await promptAppSelection(organizationId, { allowCreate: true });
112
+ }
113
+ // Prompt for git ref if not provided and no path or url specified
114
+ if (!sourcePath && !url && !gitRef) {
115
+ if (!isInteractive()) {
116
+ consola.error('You must provide a git ref, path, or url when running in non-interactive environment.');
117
+ process.exit(1);
118
+ }
119
+ gitRef = await prompt('Enter the Git reference (branch, tag, or commit SHA):', {
120
+ type: 'text',
121
+ });
122
+ if (!gitRef) {
123
+ consola.error('You must provide a git ref.');
124
+ process.exit(1);
125
+ }
126
+ }
127
+ // Prompt for channel if not provided
128
+ if (!channel) {
129
+ if (!isInteractive()) {
130
+ consola.error('You must provide a channel when running in non-interactive environment.');
131
+ process.exit(1);
132
+ }
133
+ channel = await prompt('Enter the channel name to deploy to:', {
134
+ type: 'text',
135
+ });
136
+ if (!channel) {
137
+ consola.error('You must provide a channel.');
138
+ process.exit(1);
139
+ }
140
+ }
141
+ // Prompt for environment if not provided
142
+ if (!environment && !options.yes && isInteractive()) {
143
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
144
+ const selectEnvironment = await prompt('Do you want to select an environment?', {
145
+ type: 'confirm',
146
+ initial: false,
147
+ });
148
+ if (selectEnvironment) {
149
+ const environments = await appEnvironmentsService.findAll({ appId });
150
+ if (environments.length === 0) {
151
+ consola.warn('No environments found for this app.');
152
+ }
153
+ else {
154
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
155
+ environment = await prompt('Select the environment for the build:', {
156
+ type: 'select',
157
+ options: environments.map((env) => ({ label: env.name, value: env.name })),
158
+ });
159
+ }
160
+ }
161
+ }
162
+ // Prompt for certificate if not provided
163
+ if (!certificate && !options.yes && isInteractive()) {
164
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
165
+ const selectCertificate = await prompt('Do you want to select a certificate?', {
166
+ type: 'confirm',
167
+ initial: false,
168
+ });
169
+ if (selectCertificate) {
170
+ const certificates = await appCertificatesService.findAll({ appId, platform: 'web' });
171
+ if (certificates.length === 0) {
172
+ consola.warn('No certificates found for this app.');
173
+ }
174
+ else {
175
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
176
+ certificate = await prompt('Select the certificate for the build:', {
177
+ type: 'select',
178
+ options: certificates.map((cert) => ({ label: cert.name, value: cert.name })),
179
+ });
180
+ }
181
+ }
182
+ }
183
+ // Parse ad hoc environment variables from inline and file
184
+ const variablesMap = new Map();
185
+ if (options.variableFile) {
186
+ const fileContent = await fs.readFile(options.variableFile, 'utf-8');
187
+ const fileVariables = parseKeyValuePairs(fileContent);
188
+ fileVariables.forEach((v) => variablesMap.set(v.key, v.value));
189
+ }
190
+ if (options.variable) {
191
+ const inlineVariables = parseKeyValuePairs(options.variable.join('\n'));
192
+ inlineVariables.forEach((v) => variablesMap.set(v.key, v.value));
193
+ }
194
+ const adHocEnvironmentVariables = variablesMap.size > 0 ? Object.fromEntries(variablesMap) : undefined;
195
+ // Create build source from URL if provided
196
+ let appBuildSourceId;
197
+ if (url) {
198
+ consola.start('Creating build source from URL...');
199
+ const appBuildSource = await appBuildSourcesService.createFromUrl({ appId, fileUrl: url });
200
+ appBuildSourceId = appBuildSource.id;
201
+ consola.success('Build source created successfully.');
202
+ }
203
+ // Upload source files if path is provided
204
+ if (sourcePath) {
205
+ const resolvedPath = path.resolve(sourcePath);
206
+ consola.start('Zipping source files...');
207
+ const buffer = await zip.zipFolderWithGitignore(resolvedPath);
208
+ consola.start('Uploading source files...');
209
+ const appBuildSource = await appBuildSourcesService.createFromFile({
210
+ appId,
211
+ fileSizeInBytes: buffer.byteLength,
212
+ buffer,
213
+ name: 'source.zip',
214
+ }, (currentPart, totalParts) => {
215
+ consola.start(`Uploading source files (${currentPart}/${totalParts})...`);
216
+ });
217
+ appBuildSourceId = appBuildSource.id;
218
+ consola.success('Source files uploaded successfully.');
219
+ }
220
+ // Create the web build
221
+ consola.start('Creating build...');
222
+ const response = await appBuildsService.create({
223
+ adHocEnvironmentVariables,
224
+ appBuildSourceId,
225
+ appCertificateName: certificate,
226
+ appEnvironmentName: environment,
227
+ appId,
228
+ stack,
229
+ gitRef,
230
+ platform: 'web',
231
+ });
232
+ consola.info(`Build ID: ${response.id}`);
233
+ consola.info(`Build Number: ${response.numberAsString}`);
234
+ consola.info(`Build URL: ${DEFAULT_CONSOLE_BASE_URL}/apps/${appId}/builds/${response.id}`);
235
+ consola.success('Build created successfully.');
236
+ // Wait for build to complete
237
+ await waitForJobCompletion({ jobId: response.jobId });
238
+ consola.success('Build completed successfully.');
239
+ console.log();
240
+ // Update build with custom properties and version constraints if any are provided
241
+ const customProperties = parseCustomProperties(options.customProperty);
242
+ const hasUpdateFields = customProperties ||
243
+ options.androidMin ||
244
+ options.androidMax ||
245
+ options.androidEq ||
246
+ options.iosMin ||
247
+ options.iosMax ||
248
+ options.iosEq;
249
+ if (hasUpdateFields) {
250
+ consola.start('Updating build...');
251
+ await appBuildsService.update({
252
+ appId,
253
+ appBuildId: response.id,
254
+ customProperties,
255
+ minAndroidAppVersionCode: options.androidMin,
256
+ maxAndroidAppVersionCode: options.androidMax,
257
+ eqAndroidAppVersionCode: options.androidEq,
258
+ minIosAppVersionCode: options.iosMin,
259
+ maxIosAppVersionCode: options.iosMax,
260
+ eqIosAppVersionCode: options.iosEq,
261
+ });
262
+ consola.success('Build updated successfully.');
263
+ }
264
+ // Deploy to channel
265
+ consola.start('Creating deployment...');
266
+ const rolloutPercentage = (options.rolloutPercentage ?? 100) / 100;
267
+ const deployment = await appDeploymentsService.create({
268
+ appId,
269
+ appBuildId: response.id,
270
+ appChannelName: channel,
271
+ rolloutPercentage,
272
+ });
273
+ consola.info(`Deployment ID: ${deployment.id}`);
274
+ consola.info(`Deployment URL: ${DEFAULT_CONSOLE_BASE_URL}/apps/${appId}/deployments/${deployment.id}`);
275
+ consola.success('Deployment created successfully.');
276
+ // Output JSON if json flag is set
277
+ if (json) {
278
+ console.log(JSON.stringify({
279
+ buildId: response.id,
280
+ buildNumberAsString: response.numberAsString,
281
+ deploymentId: deployment.id,
282
+ }, null, 2));
283
+ }
284
+ }),
285
+ });
@@ -0,0 +1,262 @@
1
+ import { DEFAULT_API_BASE_URL, DEFAULT_CONSOLE_BASE_URL } from '../../../config/consts.js';
2
+ import authorizationService from '../../../services/authorization-service.js';
3
+ import userConfig from '../../../utils/user-config.js';
4
+ import consola from 'consola';
5
+ import nock from 'nock';
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import createCommand from './create.js';
8
+ // Mock dependencies
9
+ vi.mock('@/utils/user-config.js');
10
+ vi.mock('@/utils/prompt.js');
11
+ vi.mock('@/services/authorization-service.js');
12
+ vi.mock('@/utils/job.js');
13
+ vi.mock('consola');
14
+ vi.mock('@/utils/environment.js', () => ({
15
+ isInteractive: () => false,
16
+ }));
17
+ describe('apps-liveupdates-create', () => {
18
+ const mockUserConfig = vi.mocked(userConfig);
19
+ const mockAuthorizationService = vi.mocked(authorizationService);
20
+ const mockConsola = vi.mocked(consola);
21
+ const testToken = 'test-token';
22
+ const appId = '00000000-0000-0000-0000-000000000001';
23
+ const buildId = '00000000-0000-0000-0000-000000000002';
24
+ const deploymentId = '00000000-0000-0000-0000-000000000003';
25
+ beforeEach(async () => {
26
+ vi.clearAllMocks();
27
+ mockUserConfig.read.mockReturnValue({ token: testToken });
28
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(true);
29
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue(testToken);
30
+ // Mock waitForJobCompletion to resolve immediately
31
+ const jobUtils = await import('../../../utils/job.js');
32
+ vi.mocked(jobUtils.waitForJobCompletion).mockResolvedValue({
33
+ id: 'job-1',
34
+ status: 'succeeded',
35
+ createdAt: '2024-01-01T00:00:00Z',
36
+ });
37
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
38
+ throw new Error(`Process exited with code ${code}`);
39
+ });
40
+ vi.spyOn(console, 'log').mockImplementation(() => { });
41
+ });
42
+ afterEach(() => {
43
+ nock.cleanAll();
44
+ vi.restoreAllMocks();
45
+ });
46
+ it('should require authentication', async () => {
47
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(false);
48
+ const options = { appId, gitRef: 'main', channel: 'production' };
49
+ await expect(createCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
50
+ expect(mockConsola.error).toHaveBeenCalledWith('You must be logged in to run this command. Set the `CAPAWESOME_TOKEN` environment variable or use the `--token` option.');
51
+ });
52
+ it('should create a live update with build and deployment', async () => {
53
+ const options = {
54
+ appId,
55
+ gitRef: 'main',
56
+ channel: 'production',
57
+ yes: true,
58
+ };
59
+ const buildScope = nock(DEFAULT_API_BASE_URL)
60
+ .post(`/v1/apps/${appId}/builds`, {
61
+ gitRef: 'main',
62
+ platform: 'web',
63
+ })
64
+ .matchHeader('Authorization', `Bearer ${testToken}`)
65
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
66
+ const deploymentScope = nock(DEFAULT_API_BASE_URL)
67
+ .post(`/v1/apps/${appId}/deployments`, {
68
+ appId,
69
+ appBuildId: buildId,
70
+ appChannelName: 'production',
71
+ rolloutPercentage: 1,
72
+ })
73
+ .matchHeader('Authorization', `Bearer ${testToken}`)
74
+ .reply(201, { id: deploymentId });
75
+ await createCommand.action(options, undefined);
76
+ expect(buildScope.isDone()).toBe(true);
77
+ expect(deploymentScope.isDone()).toBe(true);
78
+ expect(mockConsola.success).toHaveBeenCalledWith('Build created successfully.');
79
+ expect(mockConsola.success).toHaveBeenCalledWith('Build completed successfully.');
80
+ expect(mockConsola.success).toHaveBeenCalledWith('Deployment created successfully.');
81
+ expect(mockConsola.info).toHaveBeenCalledWith(`Build ID: ${buildId}`);
82
+ expect(mockConsola.info).toHaveBeenCalledWith(`Deployment ID: ${deploymentId}`);
83
+ });
84
+ it('should pass environment and certificate to build', async () => {
85
+ const options = {
86
+ appId,
87
+ gitRef: 'v1.0.0',
88
+ channel: 'production',
89
+ environment: 'staging',
90
+ certificate: 'my-cert',
91
+ yes: true,
92
+ };
93
+ const buildScope = nock(DEFAULT_API_BASE_URL)
94
+ .post(`/v1/apps/${appId}/builds`, {
95
+ gitRef: 'v1.0.0',
96
+ platform: 'web',
97
+ appEnvironmentName: 'staging',
98
+ appCertificateName: 'my-cert',
99
+ })
100
+ .matchHeader('Authorization', `Bearer ${testToken}`)
101
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
102
+ const deploymentScope = nock(DEFAULT_API_BASE_URL)
103
+ .post(`/v1/apps/${appId}/deployments`)
104
+ .matchHeader('Authorization', `Bearer ${testToken}`)
105
+ .reply(201, { id: deploymentId });
106
+ await createCommand.action(options, undefined);
107
+ expect(buildScope.isDone()).toBe(true);
108
+ expect(deploymentScope.isDone()).toBe(true);
109
+ });
110
+ it('should pass stack to build', async () => {
111
+ const options = {
112
+ appId,
113
+ gitRef: 'main',
114
+ channel: 'production',
115
+ stack: 'macos-tahoe',
116
+ yes: true,
117
+ };
118
+ const buildScope = nock(DEFAULT_API_BASE_URL)
119
+ .post(`/v1/apps/${appId}/builds`, {
120
+ gitRef: 'main',
121
+ platform: 'web',
122
+ stack: 'macos-tahoe',
123
+ })
124
+ .matchHeader('Authorization', `Bearer ${testToken}`)
125
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
126
+ const deploymentScope = nock(DEFAULT_API_BASE_URL)
127
+ .post(`/v1/apps/${appId}/deployments`)
128
+ .matchHeader('Authorization', `Bearer ${testToken}`)
129
+ .reply(201, { id: deploymentId });
130
+ await createCommand.action(options, undefined);
131
+ expect(buildScope.isDone()).toBe(true);
132
+ expect(deploymentScope.isDone()).toBe(true);
133
+ });
134
+ it('should update version constraints when provided', async () => {
135
+ const options = {
136
+ appId,
137
+ gitRef: 'main',
138
+ channel: 'production',
139
+ androidMin: '10',
140
+ androidMax: '50',
141
+ iosEq: '42',
142
+ yes: true,
143
+ };
144
+ const buildScope = nock(DEFAULT_API_BASE_URL)
145
+ .post(`/v1/apps/${appId}/builds`)
146
+ .matchHeader('Authorization', `Bearer ${testToken}`)
147
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
148
+ const updateScope = nock(DEFAULT_API_BASE_URL)
149
+ .patch(`/v1/apps/${appId}/builds/${buildId}`, {
150
+ minAndroidAppVersionCode: '10',
151
+ maxAndroidAppVersionCode: '50',
152
+ eqIosAppVersionCode: '42',
153
+ })
154
+ .matchHeader('Authorization', `Bearer ${testToken}`)
155
+ .reply(200, { id: buildId });
156
+ const deploymentScope = nock(DEFAULT_API_BASE_URL)
157
+ .post(`/v1/apps/${appId}/deployments`)
158
+ .matchHeader('Authorization', `Bearer ${testToken}`)
159
+ .reply(201, { id: deploymentId });
160
+ await createCommand.action(options, undefined);
161
+ expect(buildScope.isDone()).toBe(true);
162
+ expect(updateScope.isDone()).toBe(true);
163
+ expect(deploymentScope.isDone()).toBe(true);
164
+ expect(mockConsola.success).toHaveBeenCalledWith('Build updated successfully.');
165
+ });
166
+ it('should convert rollout percentage to decimal', async () => {
167
+ const options = {
168
+ appId,
169
+ gitRef: 'main',
170
+ channel: 'production',
171
+ rolloutPercentage: 50,
172
+ yes: true,
173
+ };
174
+ const buildScope = nock(DEFAULT_API_BASE_URL)
175
+ .post(`/v1/apps/${appId}/builds`)
176
+ .matchHeader('Authorization', `Bearer ${testToken}`)
177
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
178
+ const deploymentScope = nock(DEFAULT_API_BASE_URL)
179
+ .post(`/v1/apps/${appId}/deployments`, {
180
+ appId,
181
+ appBuildId: buildId,
182
+ appChannelName: 'production',
183
+ rolloutPercentage: 0.5,
184
+ })
185
+ .matchHeader('Authorization', `Bearer ${testToken}`)
186
+ .reply(201, { id: deploymentId });
187
+ await createCommand.action(options, undefined);
188
+ expect(buildScope.isDone()).toBe(true);
189
+ expect(deploymentScope.isDone()).toBe(true);
190
+ });
191
+ it('should output JSON when json flag is set', async () => {
192
+ const options = {
193
+ appId,
194
+ gitRef: 'main',
195
+ channel: 'production',
196
+ json: true,
197
+ yes: true,
198
+ };
199
+ nock(DEFAULT_API_BASE_URL)
200
+ .post(`/v1/apps/${appId}/builds`)
201
+ .matchHeader('Authorization', `Bearer ${testToken}`)
202
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '42' });
203
+ nock(DEFAULT_API_BASE_URL)
204
+ .post(`/v1/apps/${appId}/deployments`)
205
+ .matchHeader('Authorization', `Bearer ${testToken}`)
206
+ .reply(201, { id: deploymentId });
207
+ await createCommand.action(options, undefined);
208
+ expect(console.log).toHaveBeenCalledWith(JSON.stringify({
209
+ buildId,
210
+ buildNumberAsString: '42',
211
+ deploymentId,
212
+ }, null, 2));
213
+ });
214
+ it('should require app ID in non-interactive mode', async () => {
215
+ const options = { gitRef: 'main', channel: 'production' };
216
+ await expect(createCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
217
+ expect(mockConsola.error).toHaveBeenCalledWith('You must provide an app ID when running in non-interactive environment.');
218
+ });
219
+ it('should require git ref in non-interactive mode', async () => {
220
+ const options = { appId, channel: 'production' };
221
+ await expect(createCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
222
+ expect(mockConsola.error).toHaveBeenCalledWith('You must provide a git ref, path, or url when running in non-interactive environment.');
223
+ });
224
+ it('should require channel in non-interactive mode', async () => {
225
+ const options = { appId, gitRef: 'main' };
226
+ await expect(createCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
227
+ expect(mockConsola.error).toHaveBeenCalledWith('You must provide a channel when running in non-interactive environment.');
228
+ });
229
+ it('should handle build creation API error', async () => {
230
+ const options = {
231
+ appId,
232
+ gitRef: 'main',
233
+ channel: 'production',
234
+ yes: true,
235
+ };
236
+ const buildScope = nock(DEFAULT_API_BASE_URL)
237
+ .post(`/v1/apps/${appId}/builds`)
238
+ .matchHeader('Authorization', `Bearer ${testToken}`)
239
+ .reply(400, { message: 'Invalid build data' });
240
+ await expect(createCommand.action(options, undefined)).rejects.toThrow();
241
+ expect(buildScope.isDone()).toBe(true);
242
+ });
243
+ it('should include build URL in output', async () => {
244
+ const options = {
245
+ appId,
246
+ gitRef: 'main',
247
+ channel: 'production',
248
+ yes: true,
249
+ };
250
+ nock(DEFAULT_API_BASE_URL)
251
+ .post(`/v1/apps/${appId}/builds`)
252
+ .matchHeader('Authorization', `Bearer ${testToken}`)
253
+ .reply(201, { id: buildId, jobId: 'job-1', numberAsString: '1' });
254
+ nock(DEFAULT_API_BASE_URL)
255
+ .post(`/v1/apps/${appId}/deployments`)
256
+ .matchHeader('Authorization', `Bearer ${testToken}`)
257
+ .reply(201, { id: deploymentId });
258
+ await createCommand.action(options, undefined);
259
+ expect(mockConsola.info).toHaveBeenCalledWith(`Build URL: ${DEFAULT_CONSOLE_BASE_URL}/apps/${appId}/builds/${buildId}`);
260
+ expect(mockConsola.info).toHaveBeenCalledWith(`Deployment URL: ${DEFAULT_CONSOLE_BASE_URL}/apps/${appId}/deployments/${deploymentId}`);
261
+ });
262
+ });
@@ -1,5 +1,5 @@
1
1
  import { isInteractive } from '../../../utils/environment.js';
2
- import { directoryContainsSourceMaps, fileExistsAtPath } from '../../../utils/file.js';
2
+ import { directoryContainsSourceMaps, directoryContainsSymlinks, fileExistsAtPath, isDirectory } from '../../../utils/file.js';
3
3
  import { generateManifestJson } from '../../../utils/manifest.js';
4
4
  import { prompt } from '../../../utils/prompt.js';
5
5
  import { defineCommand, defineOptions } from '@robingenz/zli';
@@ -32,11 +32,22 @@ export default defineCommand({
32
32
  consola.error(`The path does not exist.`);
33
33
  process.exit(1);
34
34
  }
35
+ // Check if the path is a directory
36
+ const pathIsDirectory = await isDirectory(path);
37
+ if (!pathIsDirectory) {
38
+ consola.error(`The path is not a directory.`);
39
+ process.exit(1);
40
+ }
35
41
  // Check for source maps
36
42
  const containsSourceMaps = await directoryContainsSourceMaps(path);
37
43
  if (containsSourceMaps) {
38
44
  consola.warn('Source map files were detected in the specified path. Source maps should not be distributed to end users as they expose your original source code and increase the download size. Consider excluding source map files from your build output.');
39
45
  }
46
+ // Check for symlinks
47
+ const containsSymlinks = await directoryContainsSymlinks(path);
48
+ if (containsSymlinks) {
49
+ consola.warn('Symbolic links were detected in the specified path. Symbolic links are skipped during manifest generation.');
50
+ }
40
51
  // Generate the manifest file
41
52
  await generateManifestJson(path);
42
53
  consola.success('Manifest file generated.');
@@ -1,4 +1,4 @@
1
- import { fileExistsAtPath } from '../../../utils/file.js';
1
+ import { directoryContainsSymlinks, fileExistsAtPath, isDirectory } from '../../../utils/file.js';
2
2
  import { generateManifestJson } from '../../../utils/manifest.js';
3
3
  import { prompt } from '../../../utils/prompt.js';
4
4
  import consola from 'consola';
@@ -14,6 +14,8 @@ vi.mock('@/utils/environment.js', () => ({
14
14
  }));
15
15
  describe('apps-liveupdates-generatemanifest', () => {
16
16
  const mockFileExistsAtPath = vi.mocked(fileExistsAtPath);
17
+ const mockIsDirectory = vi.mocked(isDirectory);
18
+ const mockDirectoryContainsSymlinks = vi.mocked(directoryContainsSymlinks);
17
19
  const mockGenerateManifestJson = vi.mocked(generateManifestJson);
18
20
  const mockPrompt = vi.mocked(prompt);
19
21
  const mockConsola = vi.mocked(consola);
@@ -29,6 +31,7 @@ describe('apps-liveupdates-generatemanifest', () => {
29
31
  it('should generate manifest with provided path', async () => {
30
32
  const options = { path: './dist' };
31
33
  mockFileExistsAtPath.mockResolvedValue(true);
34
+ mockIsDirectory.mockResolvedValue(true);
32
35
  mockGenerateManifestJson.mockResolvedValue(undefined);
33
36
  await generateManifestCommand.action(options, undefined);
34
37
  expect(mockFileExistsAtPath).toHaveBeenCalledWith('./dist');
@@ -39,6 +42,7 @@ describe('apps-liveupdates-generatemanifest', () => {
39
42
  const options = {};
40
43
  mockPrompt.mockResolvedValueOnce('./www');
41
44
  mockFileExistsAtPath.mockResolvedValue(true);
45
+ mockIsDirectory.mockResolvedValue(true);
42
46
  mockGenerateManifestJson.mockResolvedValue(undefined);
43
47
  await generateManifestCommand.action(options, undefined);
44
48
  expect(mockPrompt).toHaveBeenCalledWith('Enter the path to the web assets folder (e.g., `dist` or `www`):', {
@@ -60,4 +64,20 @@ describe('apps-liveupdates-generatemanifest', () => {
60
64
  await expect(generateManifestCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
61
65
  expect(mockConsola.error).toHaveBeenCalledWith('The path does not exist.');
62
66
  });
67
+ it('should handle non-directory path', async () => {
68
+ const options = { path: './file.txt' };
69
+ mockFileExistsAtPath.mockResolvedValue(true);
70
+ mockIsDirectory.mockResolvedValue(false);
71
+ await expect(generateManifestCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
72
+ expect(mockConsola.error).toHaveBeenCalledWith('The path is not a directory.');
73
+ });
74
+ it('should warn when symlinks are detected', async () => {
75
+ const options = { path: './dist' };
76
+ mockFileExistsAtPath.mockResolvedValue(true);
77
+ mockIsDirectory.mockResolvedValue(true);
78
+ mockDirectoryContainsSymlinks.mockResolvedValue(true);
79
+ mockGenerateManifestJson.mockResolvedValue(undefined);
80
+ await generateManifestCommand.action(options, undefined);
81
+ expect(mockConsola.warn).toHaveBeenCalledWith('Symbolic links were detected in the specified path. Symbolic links are skipped during manifest generation.');
82
+ });
63
83
  });