summaryrefslogtreecommitdiff
path: root/packages/cli/src/services/CommandService.test.ts
blob: e2d5b9f585d6132a2a19a0b7478fb799a4a01112 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import { CommandService } from './CommandService.js';
import { type ICommandLoader } from './types.js';
import { CommandKind, type SlashCommand } from '../ui/commands/types.js';

const createMockCommand = (name: string, kind: CommandKind): SlashCommand => ({
  name,
  description: `Description for ${name}`,
  kind,
  action: vi.fn(),
});

const mockCommandA = createMockCommand('command-a', CommandKind.BUILT_IN);
const mockCommandB = createMockCommand('command-b', CommandKind.BUILT_IN);
const mockCommandC = createMockCommand('command-c', CommandKind.FILE);
const mockCommandB_Override = createMockCommand('command-b', CommandKind.FILE);

class MockCommandLoader implements ICommandLoader {
  private commandsToLoad: SlashCommand[];

  constructor(commandsToLoad: SlashCommand[]) {
    this.commandsToLoad = commandsToLoad;
  }

  loadCommands = vi.fn(
    async (): Promise<SlashCommand[]> => Promise.resolve(this.commandsToLoad),
  );
}

describe('CommandService', () => {
  beforeEach(() => {
    vi.spyOn(console, 'debug').mockImplementation(() => {});
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('should load commands from a single loader', async () => {
    const mockLoader = new MockCommandLoader([mockCommandA, mockCommandB]);
    const service = await CommandService.create(
      [mockLoader],
      new AbortController().signal,
    );

    const commands = service.getCommands();

    expect(mockLoader.loadCommands).toHaveBeenCalledTimes(1);
    expect(commands).toHaveLength(2);
    expect(commands).toEqual(
      expect.arrayContaining([mockCommandA, mockCommandB]),
    );
  });

  it('should aggregate commands from multiple loaders', async () => {
    const loader1 = new MockCommandLoader([mockCommandA]);
    const loader2 = new MockCommandLoader([mockCommandC]);
    const service = await CommandService.create(
      [loader1, loader2],
      new AbortController().signal,
    );

    const commands = service.getCommands();

    expect(loader1.loadCommands).toHaveBeenCalledTimes(1);
    expect(loader2.loadCommands).toHaveBeenCalledTimes(1);
    expect(commands).toHaveLength(2);
    expect(commands).toEqual(
      expect.arrayContaining([mockCommandA, mockCommandC]),
    );
  });

  it('should override commands from earlier loaders with those from later loaders', async () => {
    const loader1 = new MockCommandLoader([mockCommandA, mockCommandB]);
    const loader2 = new MockCommandLoader([
      mockCommandB_Override,
      mockCommandC,
    ]);
    const service = await CommandService.create(
      [loader1, loader2],
      new AbortController().signal,
    );

    const commands = service.getCommands();

    expect(commands).toHaveLength(3); // Should be A, C, and the overridden B.

    // The final list should contain the override from the *last* loader.
    const commandB = commands.find((cmd) => cmd.name === 'command-b');
    expect(commandB).toBeDefined();
    expect(commandB?.kind).toBe(CommandKind.FILE); // Verify it's the overridden version.
    expect(commandB).toEqual(mockCommandB_Override);

    // Ensure the other commands are still present.
    expect(commands).toEqual(
      expect.arrayContaining([
        mockCommandA,
        mockCommandC,
        mockCommandB_Override,
      ]),
    );
  });

  it('should handle loaders that return an empty array of commands gracefully', async () => {
    const loader1 = new MockCommandLoader([mockCommandA]);
    const emptyLoader = new MockCommandLoader([]);
    const loader3 = new MockCommandLoader([mockCommandB]);
    const service = await CommandService.create(
      [loader1, emptyLoader, loader3],
      new AbortController().signal,
    );

    const commands = service.getCommands();

    expect(emptyLoader.loadCommands).toHaveBeenCalledTimes(1);
    expect(commands).toHaveLength(2);
    expect(commands).toEqual(
      expect.arrayContaining([mockCommandA, mockCommandB]),
    );
  });

  it('should load commands from successful loaders even if one fails', async () => {
    const successfulLoader = new MockCommandLoader([mockCommandA]);
    const failingLoader = new MockCommandLoader([]);
    const error = new Error('Loader failed');
    vi.spyOn(failingLoader, 'loadCommands').mockRejectedValue(error);

    const service = await CommandService.create(
      [successfulLoader, failingLoader],
      new AbortController().signal,
    );

    const commands = service.getCommands();
    expect(commands).toHaveLength(1);
    expect(commands).toEqual([mockCommandA]);
    expect(console.debug).toHaveBeenCalledWith(
      'A command loader failed:',
      error,
    );
  });

  it('getCommands should return a readonly array that cannot be mutated', async () => {
    const service = await CommandService.create(
      [new MockCommandLoader([mockCommandA])],
      new AbortController().signal,
    );

    const commands = service.getCommands();

    // Expect it to throw a TypeError at runtime because the array is frozen.
    expect(() => {
      // @ts-expect-error - Testing immutability is intentional here.
      commands.push(mockCommandB);
    }).toThrow();

    // Verify the original array was not mutated.
    expect(service.getCommands()).toHaveLength(1);
  });

  it('should pass the abort signal to all loaders', async () => {
    const controller = new AbortController();
    const signal = controller.signal;

    const loader1 = new MockCommandLoader([mockCommandA]);
    const loader2 = new MockCommandLoader([mockCommandB]);

    await CommandService.create([loader1, loader2], signal);

    expect(loader1.loadCommands).toHaveBeenCalledTimes(1);
    expect(loader1.loadCommands).toHaveBeenCalledWith(signal);
    expect(loader2.loadCommands).toHaveBeenCalledTimes(1);
    expect(loader2.loadCommands).toHaveBeenCalledWith(signal);
  });

  it('should rename extension commands when they conflict', async () => {
    const builtinCommand = createMockCommand('deploy', CommandKind.BUILT_IN);
    const userCommand = createMockCommand('sync', CommandKind.FILE);
    const extensionCommand1 = {
      ...createMockCommand('deploy', CommandKind.FILE),
      extensionName: 'firebase',
      description: '[firebase] Deploy to Firebase',
    };
    const extensionCommand2 = {
      ...createMockCommand('sync', CommandKind.FILE),
      extensionName: 'git-helper',
      description: '[git-helper] Sync with remote',
    };

    const mockLoader1 = new MockCommandLoader([builtinCommand]);
    const mockLoader2 = new MockCommandLoader([
      userCommand,
      extensionCommand1,
      extensionCommand2,
    ]);

    const service = await CommandService.create(
      [mockLoader1, mockLoader2],
      new AbortController().signal,
    );

    const commands = service.getCommands();
    expect(commands).toHaveLength(4);

    // Built-in command keeps original name
    const deployBuiltin = commands.find(
      (cmd) => cmd.name === 'deploy' && !cmd.extensionName,
    );
    expect(deployBuiltin).toBeDefined();
    expect(deployBuiltin?.kind).toBe(CommandKind.BUILT_IN);

    // Extension command conflicting with built-in gets renamed
    const deployExtension = commands.find(
      (cmd) => cmd.name === 'firebase.deploy',
    );
    expect(deployExtension).toBeDefined();
    expect(deployExtension?.extensionName).toBe('firebase');

    // User command keeps original name
    const syncUser = commands.find(
      (cmd) => cmd.name === 'sync' && !cmd.extensionName,
    );
    expect(syncUser).toBeDefined();
    expect(syncUser?.kind).toBe(CommandKind.FILE);

    // Extension command conflicting with user command gets renamed
    const syncExtension = commands.find(
      (cmd) => cmd.name === 'git-helper.sync',
    );
    expect(syncExtension).toBeDefined();
    expect(syncExtension?.extensionName).toBe('git-helper');
  });

  it('should handle user/project command override correctly', async () => {
    const builtinCommand = createMockCommand('help', CommandKind.BUILT_IN);
    const userCommand = createMockCommand('help', CommandKind.FILE);
    const projectCommand = createMockCommand('deploy', CommandKind.FILE);
    const userDeployCommand = createMockCommand('deploy', CommandKind.FILE);

    const mockLoader1 = new MockCommandLoader([builtinCommand]);
    const mockLoader2 = new MockCommandLoader([
      userCommand,
      userDeployCommand,
      projectCommand,
    ]);

    const service = await CommandService.create(
      [mockLoader1, mockLoader2],
      new AbortController().signal,
    );

    const commands = service.getCommands();
    expect(commands).toHaveLength(2);

    // User command overrides built-in
    const helpCommand = commands.find((cmd) => cmd.name === 'help');
    expect(helpCommand).toBeDefined();
    expect(helpCommand?.kind).toBe(CommandKind.FILE);

    // Project command overrides user command (last wins)
    const deployCommand = commands.find((cmd) => cmd.name === 'deploy');
    expect(deployCommand).toBeDefined();
    expect(deployCommand?.kind).toBe(CommandKind.FILE);
  });

  it('should handle secondary conflicts when renaming extension commands', async () => {
    // User has both /deploy and /gcp.deploy commands
    const userCommand1 = createMockCommand('deploy', CommandKind.FILE);
    const userCommand2 = createMockCommand('gcp.deploy', CommandKind.FILE);

    // Extension also has a deploy command that will conflict with user's /deploy
    const extensionCommand = {
      ...createMockCommand('deploy', CommandKind.FILE),
      extensionName: 'gcp',
      description: '[gcp] Deploy to Google Cloud',
    };

    const mockLoader = new MockCommandLoader([
      userCommand1,
      userCommand2,
      extensionCommand,
    ]);

    const service = await CommandService.create(
      [mockLoader],
      new AbortController().signal,
    );

    const commands = service.getCommands();
    expect(commands).toHaveLength(3);

    // Original user command keeps its name
    const deployUser = commands.find(
      (cmd) => cmd.name === 'deploy' && !cmd.extensionName,
    );
    expect(deployUser).toBeDefined();

    // User's dot notation command keeps its name
    const gcpDeployUser = commands.find(
      (cmd) => cmd.name === 'gcp.deploy' && !cmd.extensionName,
    );
    expect(gcpDeployUser).toBeDefined();

    // Extension command gets renamed with suffix due to secondary conflict
    const deployExtension = commands.find(
      (cmd) => cmd.name === 'gcp.deploy1' && cmd.extensionName === 'gcp',
    );
    expect(deployExtension).toBeDefined();
    expect(deployExtension?.description).toBe('[gcp] Deploy to Google Cloud');
  });

  it('should handle multiple secondary conflicts with incrementing suffixes', async () => {
    // User has /deploy, /gcp.deploy, and /gcp.deploy1
    const userCommand1 = createMockCommand('deploy', CommandKind.FILE);
    const userCommand2 = createMockCommand('gcp.deploy', CommandKind.FILE);
    const userCommand3 = createMockCommand('gcp.deploy1', CommandKind.FILE);

    // Extension has a deploy command
    const extensionCommand = {
      ...createMockCommand('deploy', CommandKind.FILE),
      extensionName: 'gcp',
      description: '[gcp] Deploy to Google Cloud',
    };

    const mockLoader = new MockCommandLoader([
      userCommand1,
      userCommand2,
      userCommand3,
      extensionCommand,
    ]);

    const service = await CommandService.create(
      [mockLoader],
      new AbortController().signal,
    );

    const commands = service.getCommands();
    expect(commands).toHaveLength(4);

    // Extension command gets renamed with suffix 2 due to multiple conflicts
    const deployExtension = commands.find(
      (cmd) => cmd.name === 'gcp.deploy2' && cmd.extensionName === 'gcp',
    );
    expect(deployExtension).toBeDefined();
    expect(deployExtension?.description).toBe('[gcp] Deploy to Google Cloud');
  });
});