All files / src/entities/wiki registry.ts

100% Statements 37/37
91.66% Branches 11/12
100% Functions 6/6
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 14921x 21x 21x 21x 21x   21x               21x                             13x   9x   9x   9x     6x 6x   6x         3x                                                     28x   22x   22x   22x     4x   4x               15x     15x 4x     15x               3x     2x                             21x 40x           21x 7x           21x 6x 4x 4x 8x     2x    
import * as z from 'zod';
import { BrowseWikiSchema } from './schema-readonly';
import { ManageWikiSchema } from './schema';
import { gitlab, toQuery } from '../../utils/gitlab-api';
import { resolveNamespaceForAPI } from '../../utils/namespace';
import { ToolRegistry, EnhancedToolDefinition } from '../../types';
import { assertActionAllowed } from '../utils';
 
/**
 * Wiki tools registry - 2 CQRS tools replacing 5 individual tools
 *
 * browse_wiki (Query): list, get
 * manage_wiki (Command): create, update, delete
 */
export const wikiToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_wiki - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    'browse_wiki',
    {
      name: 'browse_wiki',
      description:
        'Read wiki pages in projects or groups. Actions: list (all pages with metadata), get (page content by slug). Related: manage_wiki to create/update/delete.',
      inputSchema: z.toJSONSchema(BrowseWikiSchema),
      requirements: { default: { tier: 'free' } },
      gate: { envVar: 'USE_GITLAB_WIKI', defaultValue: true },
      handler: async (args: unknown) => {
        const input = BrowseWikiSchema.parse(args);
 
        assertActionAllowed('browse_wiki', input.action);
 
        const { entityType, encodedPath } = await resolveNamespaceForAPI(input.namespace);
 
        switch (input.action) {
          case 'list': {
            // TypeScript knows: input has with_content, per_page, page (optional)
            const { action: _action, namespace: _namespace, ...rest } = input;
            const query = toQuery(rest, []);
 
            return gitlab.get(`${entityType}/${encodedPath}/wikis`, { query });
          }
 
          case 'get': {
            // TypeScript knows: input has slug (required)
            return gitlab.get(
              `${entityType}/${encodedPath}/wikis/${encodeURIComponent(input.slug)}`,
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_wiki - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    'manage_wiki',
    {
      name: 'manage_wiki',
      description:
        'Create, update, or delete wiki pages. Actions: create (new page with title/content/format), update (modify content or title), delete (remove permanently). Related: browse_wiki to read pages.',
      inputSchema: z.toJSONSchema(ManageWikiSchema),
      requirements: { default: { tier: 'free' } },
      gate: { envVar: 'USE_GITLAB_WIKI', defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageWikiSchema.parse(args);
 
        assertActionAllowed('manage_wiki', input.action);
 
        const { entityType, encodedPath } = await resolveNamespaceForAPI(input.namespace);
 
        switch (input.action) {
          case 'create': {
            // TypeScript knows: input has title, content (required), format (optional)
            const { action: _action, namespace: _namespace, ...body } = input;
 
            return gitlab.post(`${entityType}/${encodedPath}/wikis`, {
              body,
              contentType: 'json',
            });
          }
 
          case 'update': {
            // TypeScript knows: input has slug (required), title, content, format (optional)
            const { action: _action, namespace: _namespace, slug, ...body } = input;
 
            // Without title, GitLab can reuse only the leaf name and flatten the path.
            if (body.title === undefined && slug.includes('/')) {
              body.title = slug;
            }
 
            return gitlab.put(`${entityType}/${encodedPath}/wikis/${encodeURIComponent(slug)}`, {
              body,
              contentType: 'json',
            });
          }
 
          case 'delete': {
            // TypeScript knows: input has slug (required)
            await gitlab.delete(
              `${entityType}/${encodedPath}/wikis/${encodeURIComponent(input.slug)}`,
            );
            return { deleted: true };
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getWikiReadOnlyToolNames(): string[] {
  return ['browse_wiki'];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getWikiToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(wikiToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredWikiTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getWikiReadOnlyToolNames();
    return Array.from(wikiToolRegistry.values()).filter((tool) =>
      readOnlyNames.includes(tool.name),
    );
  }
  return getWikiToolDefinitions();
}