import type { Container } from "@webiny/di"; import { Result } from "@webiny/feature/api"; import { createCmsTestHandler } from "@webiny/api-headless-cms-testing"; import type { SecurityPermission } from "@webiny/api-core/types/security.js"; import type { IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js"; import { AiModelRegistry } from "@webiny/api-core/features/ai/index.js"; import { Encryption } from "@webiny/api-core/features/encryption/index.js"; import { TaskService } from "@webiny/api-core/features/task/TaskService/index.js"; import { createTestWcpLicense } from "@webiny/wcp/testing/createTestWcpLicense.js"; import { PROJECT_PACKAGE_FEATURE_NAME } from "@webiny/wcp/types.js"; import type { DecryptedWcpProjectLicense } from "@webiny/wcp/types.js"; import { GetFileUseCase } from "@webiny/api-file-manager/features/file/GetFile/index.js"; import { FileNotAuthorizedError } from "@webiny/api-file-manager/domain/file/errors.js"; import type { File } from "@webiny/api-file-manager/domain/file/types.js"; import { Extension } from "~/api/Extension.js"; export const TEST_SDK_NAME = "test"; class TestAiModelRegistry implements AiModelRegistry.Interface { async listModels() { return [ { providerId: "test", providerName: "Test", modelId: "model", modelName: "Model", deprecated: undefined, endOfLife: undefined, supports: undefined } ]; } } /** * Records triggered tasks instead of running them. */ class TestTaskService { public readonly triggered: unknown[] = []; async trigger(params: unknown) { this.triggered.push(params); return Result.ok({ id: `task-${this.triggered.length}` }); } } /** * Stands in for File Manager's `GetFileUseCase`: only `accessibleFileIds` can be read, every * other file is refused as the real use case does for files the caller can't access. */ class TestGetFileUseCase implements GetFileUseCase.Interface { public readonly requested: string[] = []; constructor(private accessibleFileIds: string[]) {} async execute(id: string) { this.requested.push(id); if (!this.accessibleFileIds.includes(id)) { return Result.fail(new FileNotAuthorizedError()); } return Result.ok({ id, name: `${id}.txt`, type: "text/plain" } as unknown as File); } } /** Reversible, so a test can tell a stored key from the decrypted one and still read it back. */ const testEncryption = { encrypt: async (plain: string) => `encrypted:${plain}`, decrypt: async (encrypted: string) => encrypted.replace(/^encrypted:/, "") } as unknown as Encryption.Interface; /** * The test license plus AI Power-Ups with CMS entry generation. Workflows are off: with them on, * `Extension` also registers the workflow AI schema, which extends types only the workflows * engine adds, and these tests don't register it. */ const createAiTestLicense = (): DecryptedWcpProjectLicense => { const base = createTestWcpLicense(); return { ...base, package: { ...base.package, features: { ...base.package.features, [PROJECT_PACKAGE_FEATURE_NAME.AI_POWERUPS]: { enabled: true, options: { cms: { entryGeneration: true } } }, [PROJECT_PACKAGE_FEATURE_NAME.APW]: { enabled: false } } } } as DecryptedWcpProjectLicense; }; export interface UseGraphQLHandlerParams { permissions?: SecurityPermission[]; /** * `undefined` uses the default identity, `null` makes the caller anonymous. */ identity?: IdentityData | null; /** * Registers test-specific implementations (models, decorators) in the request container. */ register?: (container: Container) => void; /** * Files the caller can read through File Manager's `GetFileUseCase`. */ accessibleFileIds?: string[]; } const createHandler = ( params: UseGraphQLHandlerParams, taskService: TestTaskService, getFile: TestGetFileUseCase ) => { return createCmsTestHandler({ permissions: params.permissions, identity: params.identity, testProjectLicense: createAiTestLicense(), setup: container => { Extension.register(container); container.registerInstance(Encryption, testEncryption); container.registerInstance(AiModelRegistry, new TestAiModelRegistry()); container.registerInstance( TaskService, taskService as unknown as TaskService.Interface ); container.registerInstance(GetFileUseCase, getFile); params.register?.(container); } }); }; /** * Returns the request context, to call internal use cases that GraphQL doesn't expose. */ export const useContext = async (params: UseGraphQLHandlerParams = {}) => { const handler = createHandler( params, new TestTaskService(), new TestGetFileUseCase(params.accessibleFileIds ?? []) ); return handler.getContext<{ container: Container }>(); }; export const useGraphQLHandler = (params: UseGraphQLHandlerParams = {}) => { const taskService = new TestTaskService(); const getFile = new TestGetFileUseCase(params.accessibleFileIds ?? []); const handler = createHandler(params, taskService, getFile); const invoke = async (query: string, variables: Record = {}) => { const [body] = await handler.invoke({ body: { query, variables } }); return body as any; }; return { taskService, getFile, getSettings() { return invoke(/* GraphQL */ ` query { aiPowerUps { getSettings } } `); }, updateSettings(input: Record) { return invoke( /* GraphQL */ ` mutation UpdateSettings($input: JSON!) { aiPowerUps { updateSettings(input: $input) { data error { code message } } } } `, { input } ); }, listModels() { return invoke(/* GraphQL */ ` query { aiPowerUps { listModels { providerId modelId } } } `); }, listCapabilities() { return invoke(/* GraphQL */ ` query { aiPowerUps { listCapabilities { id } } } `); }, generatePageContent(additionalFileIds?: string[]) { return invoke( /* GraphQL */ ` mutation GeneratePageContent($additionalFileIds: [String!]) { aiPowerUps { generatePageContent( prompt: "Hello" components: [] tools: [] additionalFileIds: $additionalFileIds ) } } `, { additionalFileIds } ); }, compareEntryRevisions(modelId: string) { return invoke( /* GraphQL */ ` query CompareEntryRevisions($modelId: String!) { cms { compareEntryRevisions( modelId: $modelId revisionId1: "a#0001" revisionId2: "a#0002" ) { data { summary } error { message code } } } } `, { modelId } ); }, generateEntryContent(modelId = "article", additionalFileIds?: string[]) { return invoke( /* GraphQL */ ` mutation GenerateEntryContent( $modelId: String! $additionalFileIds: [String!] ) { aiPowerUps { generateEntryContent( prompt: "Hello" modelId: $modelId additionalFileIds: $additionalFileIds ) } } `, { modelId, additionalFileIds } ); } }; };