import { createTestHttpHandler } from "@webiny/event-handler-core/features/testing"; import type { Container } from "@webiny/di"; import { ApiCoreFeature, registerApiCoreStorageOperations } from "@webiny/api-core"; import { GraphQLSchemaCacheFeature } from "@webiny/api-graphql"; import { GraphQLSchemaKeyVerificationFeature } from "@webiny/api-graphql"; import { EncryptionKeyCacheFeature } from "@webiny/api-core/features/encryption/index.js"; import { JwksStoreFeature } from "@webiny/api-core/idp/index.js"; import { GraphQLEngineFeature } from "@webiny/api-graphql"; import { WcpLicenseLoader } from "@webiny/api-core/features/wcp/WcpLicenseLoader.js"; import { getStorageOps } from "@webiny/api-core/testing/environment.js"; import { createTestWcpLicense } from "@webiny/wcp/testing/createTestWcpLicense.js"; import { getIntrospectionQuery } from "graphql"; import type { ApiCoreStorageOperations } from "@webiny/api-core/types/core.js"; import type { IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js"; import type { SecurityPermission } from "@webiny/api-core/types/security.js"; import type { DecryptedWcpProjectLicense } from "@webiny/wcp/types.js"; import { HeadlessCmsFeature } from "@webiny/api-headless-cms/HeadlessCmsFeature.js"; import { TestIdentity, TestAuthenticator } from "@webiny/api-core-testing"; import { TestPermissions, TestAuthorizer } from "@webiny/api-core-testing"; import { AuthTriggerHandler } from "@webiny/api-core-testing"; import { RootTenantInitializer } from "@webiny/api-core-testing"; import { processLegacyPlugins } from "./processLegacyPlugins.js"; import { Logger } from "@webiny/api-core/features/logger/index.js"; import { NullLogger } from "@webiny/api-core/features/logger/index.js"; const DEFAULT_IDENTITY: IdentityData = { id: "id-12345678", type: "admin", displayName: "John Doe" }; export interface CmsTestHandlerParams { /** Identity for the request. `undefined` → a default admin; `null` → anonymous. */ identity?: IdentityData | null; permissions?: SecurityPermission[]; /** * Permissions of other identities, by identity id, for code that evaluates another user * through `IdentityContext.withIdentity`. The request identity gets `permissions`; other * identities not listed here get none. */ permissionsByIdentity?: Record; testProjectLicense?: DecryptedWcpProjectLicense; /** CMS endpoint type to build. Defaults to "manage". */ cmsType?: "manage" | "read" | "preview"; /** Plugins forwarded to `HeadlessCmsFeature.register` as `extraPlugins` (e.g. CMS model plugins). */ extraCmsPlugins?: any[]; /** * Legacy escape hatch (being retired — prefer `setup`). A mixed array, dispatched like the old * `useContextHandler`: * - RegisterExtensionPlugins are applied at register() time (DI registration); * - static plugins (CmsModelPlugin, GraphQLSchemaPlugin, …) are forwarded to HeadlessCmsFeature * as extraPlugins so their models reach the container before any initializer caches them; * - plain `container => {}` functions run LAST (after `setup`), so they can override defaults. */ legacyPlugins?: any; /** * Register the consuming package's own features here (e.g. AcoFeature, FileModel, plus its own * getStorageOps presets via processLegacyPlugins). Runs in the request phase AFTER ApiCore + CMS * storage + HeadlessCmsFeature, and BEFORE the GraphQL engine — i.e. before any initializer or * resolver, the same window the real app handler uses. */ setup?: (container: Container) => void | Promise; } export interface InvokeParams { httpMethod?: "POST"; type?: string; body: { query: string; variables?: Record }; headers?: Record; } /** * Shared integration test handler that wires the real CMS base (ApiCore + HeadlessCms + GraphQL * engine + the CMS manage route) the same way the AWS app handler does — auth via Test * authenticator/authorizer, root tenant seeded, storage via getStorageOps. Consuming packages add * their own features through `params.setup` and build their SDKs on top of `invoke`/`invokeCms`, * or grab the fully-initialized request context via `getContext()`. */ export const createCmsTestHandler = (params: CmsTestHandlerParams = {}) => { const apiCoreStorage = getStorageOps("apiCore"); const cmsStorage = getStorageOps("cms"); const identity = params.identity === undefined ? DEFAULT_IDENTITY : params.identity; const permissions = params.permissions === undefined ? [{ name: "*" }] : params.permissions; const cmsType = params.cmsType ?? "manage"; const setupRoot = (container: Container) => { container.registerInstance(TestIdentity, identity); container.registerInstance(TestPermissions, { list: permissions, byIdentity: params.permissionsByIdentity }); container.register(TestAuthenticator); container.register(TestAuthorizer); container.registerDecorator(AuthTriggerHandler); container.registerDecorator(RootTenantInitializer); // Same as the real handlers, so every request after the first reuses the built schema. GraphQLSchemaCacheFeature.register(container); // Fails a test when a schema factory's output changes under the same schema key. GraphQLSchemaKeyVerificationFeature.register(container); // Same as the real handlers, so the encryption key is derived once, not per request. EncryptionKeyCacheFeature.register(container); // Root, so identity providers' signing keys are fetched once per process, not per request. JwksStoreFeature.register(container); }; // Everything up to (but not including) the GraphQL engine — shared by the HTTP handler and the // context-capture handler. const setupRequest = async (container: Container) => { const wcpLicense = await WcpLicenseLoader.load( params.testProjectLicense ?? createTestWcpLicense() ); registerApiCoreStorageOperations(container, apiCoreStorage.storageOperations); const logger = new NullLogger(); container.registerInstance(Logger, logger); ApiCoreFeature.register(container, { wcpLicense }); // CMS storage preset. All storage presets are RegisterExtensionPlugins (registerDynamoDBCore, // registerCmsOpenSearchStorageOperations, dbPlugins, ...); processLegacyPlugins runs them at // register() time — before HeadlessCmsFeature builds storage, mirroring the real app's // registerExtensions. processLegacyPlugins(container, cmsStorage.plugins); // `legacyPlugins` is a mixed bag: plain `container => {}` functions (called last, after // `setup`) plus legacy plugin objects — RegisterExtensionPlugins (register-time) or static // Plugins (extraPlugins). const legacyItems = [params.legacyPlugins].flat(Infinity as 1).filter(Boolean); const isFn = (p: any) => typeof p === "function" && !p.prototype; const legacyObjects = legacyItems.filter(p => !isFn(p)); processLegacyPlugins(container, legacyObjects); const staticPlugins = legacyObjects.filter( p => typeof (p as any).apply !== "function" && typeof p !== "function" ); HeadlessCmsFeature.register(container, { type: cmsType, extraPlugins: [...(params.extraCmsPlugins ?? []), ...staticPlugins] }); await params.setup?.(container); // Function plugins in `legacyPlugins` run LAST — after the consuming package's own `setup` — // so they can override defaults it registered (last-wins). for (const plugin of legacyItems.filter(isFn)) { (plugin as (container: any) => void)(container); } }; const handler = createTestHttpHandler({ root: setupRoot, child: async container => { await setupRequest(container); GraphQLEngineFeature.register(container); } }); const invoke = async ({ httpMethod = "POST", body, headers = {} }: InvokeParams) => { const response = await handler({ method: httpMethod, path: "/graphql", headers: { "x-tenant": "root", "content-type": "application/json", ...headers }, body }); return [response.body, response] as const; }; const invokeCms = async ({ httpMethod = "POST", type = "manage", body, headers = {} }: InvokeParams) => { const response = await handler({ method: httpMethod, path: `/cms/${type}`, headers: { "x-tenant": "root", "content-type": "application/json", ...headers }, body }); return [response.body, response] as const; }; /** * Build the request once and return the fully-initialized context (after auth, tenant, CMS and * all consumer features): the request container, captured when the handler creates it, after * one request has run through it. For tests that resolve services directly from the container * rather than issuing GraphQL queries. */ const getContext = async < C extends Record = Record >(): Promise => { let requestContainer: Container | undefined; const ctxHandler = createTestHttpHandler({ root: setupRoot, child: async container => { await setupRequest(container); GraphQLEngineFeature.register(container); requestContainer = container; } }); await ctxHandler({ method: "POST", path: "/graphql", headers: { "x-tenant": "root", "content-type": "application/json" }, body: { query: "{ __typename }" } }); return { container: requestContainer } as unknown as C; }; // Convenience wrappers mirroring the retired `useGraphQLHandler` — thin builders over `invoke` // (the main `/graphql` endpoint) so consumers can issue typed queries/mutations directly. const createQuery = = Record>(query: string) => { return (variables?: Record, headers: Record = {}) => invoke({ body: { query, variables: variables || undefined }, headers }) as Promise< readonly [T, any] >; }; const createMutation = = Record>( mutation: string ) => { return (variables?: Record, headers: Record = {}) => invoke({ body: { query: mutation, variables: variables || undefined }, headers }) as Promise; }; const introspect = () => invoke({ body: { query: getIntrospectionQuery() } }); return { handler, invoke, invokeCms, getContext, createQuery, createMutation, introspect, identity, tenant: { id: "root", name: "Root", parent: null } }; };