@capawesome/cli 1.14.0 → 2.0.1

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.
Files changed (76) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +7 -3
  3. package/dist/commands/apps/bundles/create.js +206 -239
  4. package/dist/commands/apps/bundles/create.test.js +276 -0
  5. package/dist/commands/apps/bundles/delete.js +35 -60
  6. package/dist/commands/apps/bundles/delete.test.js +139 -0
  7. package/dist/commands/apps/bundles/update.js +61 -89
  8. package/dist/commands/apps/bundles/update.test.js +141 -0
  9. package/dist/commands/apps/channels/create.js +45 -75
  10. package/dist/commands/apps/channels/create.test.js +119 -0
  11. package/dist/commands/apps/channels/delete.js +46 -69
  12. package/dist/commands/apps/channels/delete.test.js +141 -0
  13. package/dist/commands/apps/channels/get.js +52 -94
  14. package/dist/commands/apps/channels/get.test.js +135 -0
  15. package/dist/commands/apps/channels/list.js +37 -82
  16. package/dist/commands/apps/channels/list.test.js +121 -0
  17. package/dist/commands/apps/channels/update.js +39 -83
  18. package/dist/commands/apps/channels/update.test.js +138 -0
  19. package/dist/commands/apps/create.js +28 -53
  20. package/dist/commands/apps/create.test.js +117 -0
  21. package/dist/commands/apps/delete.js +29 -50
  22. package/dist/commands/apps/delete.test.js +120 -0
  23. package/dist/commands/apps/devices/delete.js +35 -60
  24. package/dist/commands/apps/devices/delete.test.js +139 -0
  25. package/dist/commands/doctor.js +12 -29
  26. package/dist/commands/doctor.test.js +52 -0
  27. package/dist/commands/login.js +50 -71
  28. package/dist/commands/login.test.js +116 -0
  29. package/dist/commands/logout.js +13 -31
  30. package/dist/commands/logout.test.js +47 -0
  31. package/dist/commands/manifests/generate.js +20 -38
  32. package/dist/commands/manifests/generate.test.js +60 -0
  33. package/dist/commands/organizations/create.js +25 -0
  34. package/dist/commands/organizations/create.test.js +80 -0
  35. package/dist/commands/whoami.js +20 -31
  36. package/dist/commands/whoami.test.js +30 -0
  37. package/dist/config/consts.js +4 -5
  38. package/dist/config/index.js +1 -17
  39. package/dist/index.js +59 -80
  40. package/dist/services/app-bundle-files.js +117 -136
  41. package/dist/services/app-bundles.js +22 -41
  42. package/dist/services/app-channels.js +54 -77
  43. package/dist/services/app-devices.js +10 -25
  44. package/dist/services/apps.js +25 -43
  45. package/dist/services/authorization-service.js +4 -8
  46. package/dist/services/config.js +15 -28
  47. package/dist/services/organizations.js +19 -26
  48. package/dist/services/session-code.js +7 -22
  49. package/dist/services/sessions.js +13 -30
  50. package/dist/services/update.js +17 -55
  51. package/dist/services/users.js +11 -26
  52. package/dist/types/app-bundle-file.js +1 -2
  53. package/dist/types/app-bundle.js +1 -2
  54. package/dist/types/app-channel.js +1 -2
  55. package/dist/types/app-device.js +1 -2
  56. package/dist/types/app.js +1 -2
  57. package/dist/types/index.js +8 -24
  58. package/dist/types/npm-package.js +1 -2
  59. package/dist/types/organization.js +1 -2
  60. package/dist/types/session-code.js +1 -2
  61. package/dist/types/session.js +1 -2
  62. package/dist/types/user.js +1 -2
  63. package/dist/utils/buffer.js +12 -43
  64. package/dist/utils/error.js +24 -14
  65. package/dist/utils/file.js +22 -41
  66. package/dist/utils/hash.js +3 -39
  67. package/dist/utils/http-client.js +27 -53
  68. package/dist/utils/manifest.js +11 -24
  69. package/dist/utils/private-key.js +23 -0
  70. package/dist/utils/prompt.js +9 -26
  71. package/dist/utils/signature.js +3 -39
  72. package/dist/utils/user-config.js +12 -0
  73. package/dist/utils/zip.js +11 -27
  74. package/package.json +22 -9
  75. package/dist/utils/ci.js +0 -7
  76. package/dist/utils/userConfig.js +0 -16
@@ -1,100 +1,77 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const citty_1 = require("citty");
16
- const consola_1 = __importDefault(require("consola"));
17
- const app_channels_1 = __importDefault(require("../../../services/app-channels"));
18
- const apps_1 = __importDefault(require("../../../services/apps"));
19
- const organizations_1 = __importDefault(require("../../../services/organizations"));
20
- const ci_1 = require("../../../utils/ci");
21
- const error_1 = require("../../../utils/error");
22
- const prompt_1 = require("../../../utils/prompt");
23
- exports.default = (0, citty_1.defineCommand)({
24
- meta: {
25
- description: 'Delete an app channel.',
26
- },
27
- args: {
28
- appId: {
29
- type: 'string',
30
- description: 'ID of the app.',
31
- },
32
- channelId: {
33
- type: 'string',
34
- description: 'ID of the channel. Either the ID or name of the channel must be provided.',
35
- },
36
- name: {
37
- type: 'string',
38
- description: 'Name of the channel. Either the ID or name of the channel must be provided.',
39
- },
40
- },
41
- run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
42
- let appId = ctx.args.appId;
43
- let channelId = ctx.args.channelId;
44
- let channelName = ctx.args.name;
1
+ import appChannelsService from '../../../services/app-channels.js';
2
+ import appsService from '../../../services/apps.js';
3
+ import authorizationService from '../../../services/authorization-service.js';
4
+ import organizationsService from '../../../services/organizations.js';
5
+ import { prompt } from '../../../utils/prompt.js';
6
+ import { defineCommand, defineOptions } from '@robingenz/zli';
7
+ import consola from 'consola';
8
+ import { isCI } from 'std-env';
9
+ import { z } from 'zod';
10
+ export default defineCommand({
11
+ description: 'Delete an app channel.',
12
+ options: defineOptions(z.object({
13
+ appId: z.string().optional().describe('ID of the app.'),
14
+ channelId: z
15
+ .string()
16
+ .optional()
17
+ .describe('ID of the channel. Either the ID or name of the channel must be provided.'),
18
+ name: z
19
+ .string()
20
+ .optional()
21
+ .describe('Name of the channel. Either the ID or name of the channel must be provided.'),
22
+ })),
23
+ action: async (options, args) => {
24
+ let { appId, channelId, name } = options;
25
+ if (!authorizationService.hasAuthorizationToken()) {
26
+ consola.error('You must be logged in to run this command.');
27
+ process.exit(1);
28
+ }
45
29
  if (!appId) {
46
- const organizations = yield organizations_1.default.findAll();
30
+ const organizations = await organizationsService.findAll();
47
31
  if (organizations.length === 0) {
48
- consola_1.default.error('You must create an organization before deleting a channel.');
32
+ consola.error('You must create an organization before deleting a channel.');
49
33
  process.exit(1);
50
34
  }
51
35
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
52
- const organizationId = yield (0, prompt_1.prompt)('Select the organization of the app from which you want to delete a channel.', {
36
+ const organizationId = await prompt('Select the organization of the app from which you want to delete a channel.', {
53
37
  type: 'select',
54
38
  options: organizations.map((organization) => ({ label: organization.name, value: organization.id })),
55
39
  });
56
40
  if (!organizationId) {
57
- consola_1.default.error('You must select the organization of an app from which you want to delete a channel.');
41
+ consola.error('You must select the organization of an app from which you want to delete a channel.');
58
42
  process.exit(1);
59
43
  }
60
- const apps = yield apps_1.default.findAll({
44
+ const apps = await appsService.findAll({
61
45
  organizationId,
62
46
  });
63
47
  if (!apps.length) {
64
- consola_1.default.error('You must create an app before deleting a channel.');
48
+ consola.error('You must create an app before deleting a channel.');
65
49
  process.exit(1);
66
50
  }
67
51
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
68
- appId = yield (0, prompt_1.prompt)('Which app do you want to delete the channel from?', {
52
+ appId = await prompt('Which app do you want to delete the channel from?', {
69
53
  type: 'select',
70
54
  options: apps.map((app) => ({ label: app.name, value: app.id })),
71
55
  });
72
56
  }
73
- if (!channelId && !channelName) {
74
- channelName = yield (0, prompt_1.prompt)('Enter the channel name:', {
57
+ if (!channelId && !name) {
58
+ name = await prompt('Enter the channel name:', {
75
59
  type: 'text',
76
60
  });
77
61
  }
78
- if (!(0, ci_1.isRunningInCi)()) {
79
- const confirmed = yield (0, prompt_1.prompt)('Are you sure you want to delete this channel?', {
62
+ if (!isCI) {
63
+ const confirmed = await prompt('Are you sure you want to delete this channel?', {
80
64
  type: 'confirm',
81
65
  });
82
66
  if (!confirmed) {
83
67
  return;
84
68
  }
85
69
  }
86
- try {
87
- yield app_channels_1.default.delete({
88
- appId,
89
- id: channelId,
90
- name: channelName,
91
- });
92
- consola_1.default.success('Channel deleted successfully.');
93
- }
94
- catch (error) {
95
- const message = (0, error_1.getMessageFromUnknownError)(error);
96
- consola_1.default.error(message);
97
- process.exit(1);
98
- }
99
- }),
70
+ await appChannelsService.delete({
71
+ appId,
72
+ id: channelId,
73
+ name,
74
+ });
75
+ consola.success('Channel deleted successfully.');
76
+ },
100
77
  });
@@ -0,0 +1,141 @@
1
+ import { DEFAULT_API_BASE_URL } from '../../../config/consts.js';
2
+ import authorizationService from '../../../services/authorization-service.js';
3
+ import { prompt } from '../../../utils/prompt.js';
4
+ import userConfig from '../../../utils/user-config.js';
5
+ import consola from 'consola';
6
+ import nock from 'nock';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import deleteChannelCommand from './delete.js';
9
+ // Mock dependencies
10
+ vi.mock('@/utils/user-config.js');
11
+ vi.mock('@/utils/prompt.js');
12
+ vi.mock('@/services/authorization-service.js');
13
+ vi.mock('consola');
14
+ vi.mock('std-env', () => ({
15
+ isCI: false,
16
+ }));
17
+ describe('apps-channels-delete', () => {
18
+ const mockUserConfig = vi.mocked(userConfig);
19
+ const mockPrompt = vi.mocked(prompt);
20
+ const mockConsola = vi.mocked(consola);
21
+ const mockAuthorizationService = vi.mocked(authorizationService);
22
+ beforeEach(() => {
23
+ vi.clearAllMocks();
24
+ mockUserConfig.read.mockReturnValue({ token: 'test-token' });
25
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue('test-token');
26
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(true);
27
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
28
+ throw new Error(`Process exited with code ${code}`);
29
+ });
30
+ });
31
+ afterEach(() => {
32
+ nock.cleanAll();
33
+ vi.restoreAllMocks();
34
+ });
35
+ it('should delete channel with provided appId and channelId after confirmation', async () => {
36
+ const appId = 'app-123';
37
+ const channelId = 'channel-456';
38
+ const testToken = 'test-token';
39
+ const options = { appId, channelId };
40
+ mockPrompt.mockResolvedValueOnce(true); // confirmation
41
+ const scope = nock(DEFAULT_API_BASE_URL)
42
+ .delete(`/v1/apps/${appId}/channels/${channelId}`)
43
+ .matchHeader('Authorization', `Bearer ${testToken}`)
44
+ .reply(200);
45
+ await deleteChannelCommand.action(options, undefined);
46
+ expect(scope.isDone()).toBe(true);
47
+ expect(mockPrompt).toHaveBeenCalledWith('Are you sure you want to delete this channel?', {
48
+ type: 'confirm',
49
+ });
50
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel deleted successfully.');
51
+ });
52
+ it('should delete channel with provided appId and name after confirmation', async () => {
53
+ const appId = 'app-123';
54
+ const channelName = 'production';
55
+ const testToken = 'test-token';
56
+ const options = { appId, name: channelName };
57
+ mockPrompt.mockResolvedValueOnce(true); // confirmation
58
+ const scope = nock(DEFAULT_API_BASE_URL)
59
+ .delete(`/v1/apps/${appId}/channels`)
60
+ .query({ name: channelName })
61
+ .matchHeader('Authorization', `Bearer ${testToken}`)
62
+ .reply(200);
63
+ await deleteChannelCommand.action(options, undefined);
64
+ expect(scope.isDone()).toBe(true);
65
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel deleted successfully.');
66
+ });
67
+ it('should not delete channel when confirmation is declined', async () => {
68
+ const appId = 'app-123';
69
+ const channelId = 'channel-456';
70
+ const options = { appId, channelId };
71
+ mockPrompt.mockResolvedValueOnce(false); // declined confirmation
72
+ await deleteChannelCommand.action(options, undefined);
73
+ expect(mockPrompt).toHaveBeenCalledWith('Are you sure you want to delete this channel?', {
74
+ type: 'confirm',
75
+ });
76
+ expect(mockConsola.success).not.toHaveBeenCalled();
77
+ });
78
+ it('should prompt for app selection when appId not provided', async () => {
79
+ const orgId = 'org-1';
80
+ const appId = 'app-1';
81
+ const channelName = 'staging';
82
+ const testToken = 'test-token';
83
+ const organization = { id: orgId, name: 'Org 1' };
84
+ const app = { id: appId, name: 'App 1' };
85
+ const options = { name: channelName };
86
+ const orgsScope = nock(DEFAULT_API_BASE_URL)
87
+ .get('/v1/organizations')
88
+ .matchHeader('Authorization', `Bearer ${testToken}`)
89
+ .reply(200, [organization]);
90
+ const appsScope = nock(DEFAULT_API_BASE_URL)
91
+ .get('/v1/apps')
92
+ .query({ organizationId: orgId })
93
+ .matchHeader('Authorization', `Bearer ${testToken}`)
94
+ .reply(200, [app]);
95
+ const deleteScope = nock(DEFAULT_API_BASE_URL)
96
+ .delete(`/v1/apps/${appId}/channels`)
97
+ .query({ name: channelName })
98
+ .matchHeader('Authorization', `Bearer ${testToken}`)
99
+ .reply(200);
100
+ mockPrompt
101
+ .mockResolvedValueOnce(orgId) // organization selection
102
+ .mockResolvedValueOnce(appId) // app selection
103
+ .mockResolvedValueOnce(true); // confirmation
104
+ await deleteChannelCommand.action(options, undefined);
105
+ expect(orgsScope.isDone()).toBe(true);
106
+ expect(appsScope.isDone()).toBe(true);
107
+ expect(deleteScope.isDone()).toBe(true);
108
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel deleted successfully.');
109
+ });
110
+ it('should prompt for channel name when neither channelId nor name provided', async () => {
111
+ const appId = 'app-123';
112
+ const channelName = 'development';
113
+ const testToken = 'test-token';
114
+ const options = { appId };
115
+ const scope = nock(DEFAULT_API_BASE_URL)
116
+ .delete(`/v1/apps/${appId}/channels`)
117
+ .query({ name: channelName })
118
+ .matchHeader('Authorization', `Bearer ${testToken}`)
119
+ .reply(200);
120
+ mockPrompt
121
+ .mockResolvedValueOnce(channelName) // channel name input
122
+ .mockResolvedValueOnce(true); // confirmation
123
+ await deleteChannelCommand.action(options, undefined);
124
+ expect(scope.isDone()).toBe(true);
125
+ expect(mockPrompt).toHaveBeenCalledWith('Enter the channel name:', { type: 'text' });
126
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel deleted successfully.');
127
+ });
128
+ it('should handle API error during deletion', async () => {
129
+ const appId = 'app-123';
130
+ const channelId = 'channel-456';
131
+ const testToken = 'test-token';
132
+ const options = { appId, channelId };
133
+ mockPrompt.mockResolvedValueOnce(true);
134
+ const scope = nock(DEFAULT_API_BASE_URL)
135
+ .delete(`/v1/apps/${appId}/channels/${channelId}`)
136
+ .matchHeader('Authorization', `Bearer ${testToken}`)
137
+ .reply(404, { message: 'Channel not found' });
138
+ await expect(deleteChannelCommand.action(options, undefined)).rejects.toThrow();
139
+ expect(scope.isDone()).toBe(true);
140
+ });
141
+ });
@@ -1,106 +1,64 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const citty_1 = require("citty");
16
- const consola_1 = __importDefault(require("consola"));
17
- const app_channels_1 = __importDefault(require("../../../services/app-channels"));
18
- const authorization_service_1 = __importDefault(require("../../../services/authorization-service"));
19
- const error_1 = require("../../../utils/error");
20
- exports.default = (0, citty_1.defineCommand)({
21
- meta: {
22
- description: 'Get an existing app channel.',
23
- },
24
- args: {
25
- appId: {
26
- type: 'string',
27
- description: 'ID of the app.',
28
- },
29
- channelId: {
30
- type: 'string',
31
- description: 'ID of the channel.',
32
- },
33
- json: {
34
- type: 'boolean',
35
- description: 'Output in JSON format.',
36
- },
37
- name: {
38
- type: 'string',
39
- description: 'Name of the channel.',
40
- },
41
- },
42
- run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
43
- if (!authorization_service_1.default.hasAuthorizationToken()) {
44
- consola_1.default.error('You must be logged in to run this command.');
1
+ import appChannelsService from '../../../services/app-channels.js';
2
+ import authorizationService from '../../../services/authorization-service.js';
3
+ import { defineCommand, defineOptions } from '@robingenz/zli';
4
+ import consola from 'consola';
5
+ import { z } from 'zod';
6
+ export default defineCommand({
7
+ description: 'Get an existing app channel.',
8
+ options: defineOptions(z.object({
9
+ appId: z.string().optional().describe('ID of the app.'),
10
+ channelId: z.string().optional().describe('ID of the channel.'),
11
+ json: z.boolean().optional().describe('Output in JSON format.'),
12
+ name: z.string().optional().describe('Name of the channel.'),
13
+ })),
14
+ action: async (options, args) => {
15
+ let { appId, channelId, json, name } = options;
16
+ if (!authorizationService.hasAuthorizationToken()) {
17
+ consola.error('You must be logged in to run this command.');
45
18
  process.exit(1);
46
19
  }
47
- let appId = ctx.args.appId;
48
- let channelId = ctx.args.channelId;
49
- let json = ctx.args.json;
50
- // Convert json to boolean
51
- if (typeof json === 'string') {
52
- json = json.toLowerCase() === 'true';
53
- }
54
- let name = ctx.args.name;
55
20
  if (!appId) {
56
- consola_1.default.error('You must provide an app ID.');
21
+ consola.error('You must provide an app ID.');
57
22
  process.exit(1);
58
23
  }
59
24
  if (!channelId && !name) {
60
- consola_1.default.error('You must provide a channel ID or name.');
25
+ consola.error('You must provide a channel ID or name.');
61
26
  process.exit(1);
62
27
  }
63
- try {
64
- let channel;
65
- if (channelId) {
66
- channel = yield app_channels_1.default.findOneById({
67
- appId,
68
- id: channelId,
69
- });
70
- }
71
- else if (name) {
72
- const foundChannels = yield app_channels_1.default.findAll({
73
- appId,
74
- name,
75
- });
76
- channel = foundChannels[0];
77
- }
78
- if (!channel) {
79
- consola_1.default.error('Channel not found.');
80
- process.exit(1);
81
- }
82
- if (json) {
83
- console.log(JSON.stringify({
84
- id: channel.id,
85
- name: channel.name,
86
- totalAppBundleLimit: channel.totalAppBundleLimit,
87
- appId: channel.appId,
88
- }, null, 2));
89
- }
90
- else {
91
- console.table({
92
- id: channel.id,
93
- name: channel.name,
94
- totalAppBundleLimit: channel.totalAppBundleLimit,
95
- appId: channel.appId,
96
- });
97
- consola_1.default.success('Channel retrieved successfully.');
98
- }
28
+ let channel;
29
+ if (channelId) {
30
+ channel = await appChannelsService.findOneById({
31
+ appId,
32
+ id: channelId,
33
+ });
34
+ }
35
+ else if (name) {
36
+ const foundChannels = await appChannelsService.findAll({
37
+ appId,
38
+ name,
39
+ });
40
+ channel = foundChannels[0];
99
41
  }
100
- catch (error) {
101
- const message = (0, error_1.getMessageFromUnknownError)(error);
102
- consola_1.default.error(message);
42
+ if (!channel) {
43
+ consola.error('Channel not found.');
103
44
  process.exit(1);
104
45
  }
105
- }),
46
+ if (json) {
47
+ console.log(JSON.stringify({
48
+ id: channel.id,
49
+ name: channel.name,
50
+ totalAppBundleLimit: channel.totalAppBundleLimit,
51
+ appId: channel.appId,
52
+ }, null, 2));
53
+ }
54
+ else {
55
+ console.table({
56
+ id: channel.id,
57
+ name: channel.name,
58
+ totalAppBundleLimit: channel.totalAppBundleLimit,
59
+ appId: channel.appId,
60
+ });
61
+ consola.success('Channel retrieved successfully.');
62
+ }
63
+ },
106
64
  });
@@ -0,0 +1,135 @@
1
+ import { DEFAULT_API_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 getChannelCommand from './get.js';
8
+ // Mock dependencies
9
+ vi.mock('@/utils/user-config.js');
10
+ vi.mock('@/services/authorization-service.js');
11
+ vi.mock('consola');
12
+ describe('apps-channels-get', () => {
13
+ const mockUserConfig = vi.mocked(userConfig);
14
+ const mockConsola = vi.mocked(consola);
15
+ const mockAuthorizationService = vi.mocked(authorizationService);
16
+ beforeEach(() => {
17
+ vi.clearAllMocks();
18
+ mockUserConfig.read.mockReturnValue({ token: 'test-token' });
19
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(true);
20
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue('test-token');
21
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
22
+ throw new Error(`Process exited with code ${code}`);
23
+ });
24
+ vi.spyOn(console, 'log').mockImplementation(() => { });
25
+ vi.spyOn(console, 'table').mockImplementation(() => { });
26
+ });
27
+ afterEach(() => {
28
+ nock.cleanAll();
29
+ vi.restoreAllMocks();
30
+ });
31
+ it('should require authentication', async () => {
32
+ const appId = 'app-123';
33
+ const channelId = 'channel-456';
34
+ const options = { appId, channelId };
35
+ // Mock no authentication token
36
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue(null);
37
+ const scope = nock(DEFAULT_API_BASE_URL)
38
+ .get(`/v1/apps/${appId}/channels/${channelId}`)
39
+ .matchHeader('Authorization', 'Bearer null')
40
+ .reply(401, { message: 'Unauthorized' });
41
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow();
42
+ expect(scope.isDone()).toBe(true);
43
+ });
44
+ it('should require appId', async () => {
45
+ const channelId = 'channel-456';
46
+ const options = { channelId, appId: undefined };
47
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
48
+ expect(mockConsola.error).toHaveBeenCalledWith('You must provide an app ID.');
49
+ });
50
+ it('should require channelId or name', async () => {
51
+ const appId = 'app-123';
52
+ const options = { appId, channelId: undefined, name: undefined };
53
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
54
+ expect(mockConsola.error).toHaveBeenCalledWith('You must provide a channel ID or name.');
55
+ });
56
+ it('should get channel by channelId and display table format', async () => {
57
+ const appId = 'app-123';
58
+ const channelId = 'channel-456';
59
+ const testToken = 'test-token';
60
+ const channel = {
61
+ id: channelId,
62
+ name: 'production',
63
+ totalAppBundleLimit: 10,
64
+ appId,
65
+ };
66
+ const options = { appId, channelId };
67
+ const scope = nock(DEFAULT_API_BASE_URL)
68
+ .get(`/v1/apps/${appId}/channels/${channelId}`)
69
+ .matchHeader('Authorization', `Bearer ${testToken}`)
70
+ .reply(200, channel);
71
+ await getChannelCommand.action(options, undefined);
72
+ expect(scope.isDone()).toBe(true);
73
+ expect(console.table).toHaveBeenCalledWith(channel);
74
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel retrieved successfully.');
75
+ });
76
+ it('should get channel by name and display JSON format', async () => {
77
+ const appId = 'app-123';
78
+ const channelName = 'staging';
79
+ const testToken = 'test-token';
80
+ const channel = {
81
+ id: 'channel-789',
82
+ name: channelName,
83
+ totalAppBundleLimit: 5,
84
+ appId,
85
+ };
86
+ const options = { appId, name: channelName, json: true };
87
+ const scope = nock(DEFAULT_API_BASE_URL)
88
+ .get(`/v1/apps/${appId}/channels`)
89
+ .query({ name: channelName })
90
+ .matchHeader('Authorization', `Bearer ${testToken}`)
91
+ .reply(200, [channel]);
92
+ await getChannelCommand.action(options, undefined);
93
+ expect(scope.isDone()).toBe(true);
94
+ expect(console.log).toHaveBeenCalledWith(JSON.stringify(channel, null, 2));
95
+ expect(mockConsola.success).not.toHaveBeenCalled();
96
+ });
97
+ it('should handle channel not found by channelId', async () => {
98
+ const appId = 'app-123';
99
+ const channelId = 'channel-456';
100
+ const testToken = 'test-token';
101
+ const options = { appId, channelId };
102
+ const scope = nock(DEFAULT_API_BASE_URL)
103
+ .get(`/v1/apps/${appId}/channels/${channelId}`)
104
+ .matchHeader('Authorization', `Bearer ${testToken}`)
105
+ .reply(404, { message: 'Channel not found' });
106
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow();
107
+ expect(scope.isDone()).toBe(true);
108
+ });
109
+ it('should handle channel not found by name', async () => {
110
+ const appId = 'app-123';
111
+ const channelName = 'nonexistent';
112
+ const testToken = 'test-token';
113
+ const options = { appId, name: channelName };
114
+ const scope = nock(DEFAULT_API_BASE_URL)
115
+ .get(`/v1/apps/${appId}/channels`)
116
+ .query({ name: channelName })
117
+ .matchHeader('Authorization', `Bearer ${testToken}`)
118
+ .reply(200, []);
119
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
120
+ expect(scope.isDone()).toBe(true);
121
+ expect(mockConsola.error).toHaveBeenCalledWith('Channel not found.');
122
+ });
123
+ it('should handle API error', async () => {
124
+ const appId = 'app-123';
125
+ const channelId = 'channel-456';
126
+ const testToken = 'test-token';
127
+ const options = { appId, channelId };
128
+ const scope = nock(DEFAULT_API_BASE_URL)
129
+ .get(`/v1/apps/${appId}/channels/${channelId}`)
130
+ .matchHeader('Authorization', `Bearer ${testToken}`)
131
+ .reply(500, { message: 'Internal server error' });
132
+ await expect(getChannelCommand.action(options, undefined)).rejects.toThrow();
133
+ expect(scope.isDone()).toBe(true);
134
+ });
135
+ });